- Update Xen patches to 3.3-rc5 and c/s 1157.
[linux-flexiantxendom0-3.2.10.git] / drivers / char / tpm / tpm_xen.c
1 /*
2  * Copyright (c) 2005, IBM Corporation
3  *
4  * Author: Stefan Berger, stefanb@us.ibm.com
5  * Grant table support: Mahadevan Gomathisankaran
6  *
7  * This code has been derived from drivers/xen/netfront/netfront.c
8  *
9  * Copyright (c) 2002-2004, K A Fraser
10  *
11  * This program is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU General Public License version 2
13  * as published by the Free Software Foundation; or, when distributed
14  * separately from the Linux kernel or incorporated into other
15  * software packages, subject to the following license:
16  *
17  * Permission is hereby granted, free of charge, to any person obtaining a copy
18  * of this source file (the "Software"), to deal in the Software without
19  * restriction, including without limitation the rights to use, copy, modify,
20  * merge, publish, distribute, sublicense, and/or sell copies of the Software,
21  * and to permit persons to whom the Software is furnished to do so, subject to
22  * the following conditions:
23  *
24  * The above copyright notice and this permission notice shall be included in
25  * all copies or substantial portions of the Software.
26  *
27  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
28  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
29  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
30  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
31  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
32  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
33  * IN THE SOFTWARE.
34  */
35
36 #include <linux/errno.h>
37 #include <linux/err.h>
38 #include <linux/interrupt.h>
39 #include <linux/mutex.h>
40 #include <linux/slab.h>
41 #include <asm/uaccess.h>
42 #include <xen/evtchn.h>
43 #include <xen/interface/grant_table.h>
44 #include <xen/interface/io/tpmif.h>
45 #include <xen/gnttab.h>
46 #include <xen/xenbus.h>
47 #include "tpm.h"
48 #include "tpm_vtpm.h"
49
50 #undef DEBUG
51
52 /* local structures */
53 struct tpm_private {
54         struct tpm_chip *chip;
55
56         tpmif_tx_interface_t *tx;
57         atomic_t refcnt;
58         unsigned int irq;
59         u8 is_connected;
60         u8 is_suspended;
61
62         spinlock_t tx_lock;
63
64         struct tx_buffer *tx_buffers[TPMIF_TX_RING_SIZE];
65
66         atomic_t tx_busy;
67         void *tx_remember;
68
69         domid_t backend_id;
70         wait_queue_head_t wait_q;
71
72         struct xenbus_device *dev;
73         int ring_ref;
74 };
75
76 struct tx_buffer {
77         unsigned int size;      // available space in data
78         unsigned int len;       // used space in data
79         unsigned char *data;    // pointer to a page
80 };
81
82
83 /* locally visible variables */
84 static grant_ref_t gref_head;
85 static struct tpm_private *my_priv;
86
87 /* local function prototypes */
88 static irqreturn_t tpmif_int(int irq,
89                              void *tpm_priv);
90 static void tpmif_rx_action(unsigned long unused);
91 static int tpmif_connect(struct xenbus_device *dev,
92                          struct tpm_private *tp,
93                          domid_t domid);
94 static DECLARE_TASKLET(tpmif_rx_tasklet, tpmif_rx_action, 0);
95 static int tpmif_allocate_tx_buffers(struct tpm_private *tp);
96 static void tpmif_free_tx_buffers(struct tpm_private *tp);
97 static void tpmif_set_connected_state(struct tpm_private *tp,
98                                       u8 newstate);
99 static int tpm_xmit(struct tpm_private *tp,
100                     const u8 * buf, size_t count, int userbuffer,
101                     void *remember);
102 static void destroy_tpmring(struct tpm_private *tp);
103 void __exit tpmif_exit(void);
104
105 #define DPRINTK(fmt, args...) \
106     pr_debug("xen_tpm_fr (%s:%d) " fmt, __FUNCTION__, __LINE__, ##args)
107 #define IPRINTK(fmt, args...) \
108     pr_info("xen_tpm_fr: " fmt, ##args)
109 #define WPRINTK(fmt, args...) \
110     pr_warning("xen_tpm_fr: " fmt, ##args)
111
112 #define GRANT_INVALID_REF       0
113
114
115 static inline int
116 tx_buffer_copy(struct tx_buffer *txb, const u8 *src, int len,
117                int isuserbuffer)
118 {
119         int copied = len;
120
121         if (len > txb->size)
122                 copied = txb->size;
123         if (isuserbuffer) {
124                 if (copy_from_user(txb->data, src, copied))
125                         return -EFAULT;
126         } else {
127                 memcpy(txb->data, src, copied);
128         }
129         txb->len = len;
130         return copied;
131 }
132
133 static inline struct tx_buffer *tx_buffer_alloc(void)
134 {
135         struct tx_buffer *txb;
136
137         txb = kzalloc(sizeof(struct tx_buffer), GFP_KERNEL);
138         if (!txb)
139                 return NULL;
140
141         txb->len = 0;
142         txb->size = PAGE_SIZE;
143         txb->data = (unsigned char *)__get_free_page(GFP_KERNEL);
144         if (txb->data == NULL) {
145                 kfree(txb);
146                 txb = NULL;
147         }
148
149         return txb;
150 }
151
152
153 static inline void tx_buffer_free(struct tx_buffer *txb)
154 {
155         if (txb) {
156                 free_page((long)txb->data);
157                 kfree(txb);
158         }
159 }
160
161 /**************************************************************
162  Utility function for the tpm_private structure
163 **************************************************************/
164 static void tpm_private_init(struct tpm_private *tp)
165 {
166         spin_lock_init(&tp->tx_lock);
167         init_waitqueue_head(&tp->wait_q);
168         atomic_set(&tp->refcnt, 1);
169 }
170
171 static void tpm_private_put(void)
172 {
173         if (!atomic_dec_and_test(&my_priv->refcnt))
174                 return;
175
176         tpmif_free_tx_buffers(my_priv);
177         kfree(my_priv);
178         my_priv = NULL;
179 }
180
181 static struct tpm_private *tpm_private_get(void)
182 {
183         int err;
184
185         if (my_priv) {
186                 atomic_inc(&my_priv->refcnt);
187                 return my_priv;
188         }
189
190         my_priv = kzalloc(sizeof(struct tpm_private), GFP_KERNEL);
191         if (!my_priv)
192                 return NULL;
193
194         tpm_private_init(my_priv);
195         err = tpmif_allocate_tx_buffers(my_priv);
196         if (err < 0)
197                 tpm_private_put();
198
199         return my_priv;
200 }
201
202 /**************************************************************
203
204  The interface to let the tpm plugin register its callback
205  function and send data to another partition using this module
206
207 **************************************************************/
208
209 static DEFINE_MUTEX(suspend_lock);
210 /*
211  * Send data via this module by calling this function
212  */
213 int vtpm_vd_send(struct tpm_private *tp,
214                  const u8 * buf, size_t count, void *ptr)
215 {
216         int sent;
217
218         mutex_lock(&suspend_lock);
219         sent = tpm_xmit(tp, buf, count, 0, ptr);
220         mutex_unlock(&suspend_lock);
221
222         return sent;
223 }
224
225 /**************************************************************
226  XENBUS support code
227 **************************************************************/
228
229 static int setup_tpmring(struct xenbus_device *dev,
230                          struct tpm_private *tp)
231 {
232         tpmif_tx_interface_t *sring;
233         int err;
234
235         tp->ring_ref = GRANT_INVALID_REF;
236
237         sring = (void *)__get_free_page(GFP_KERNEL);
238         if (!sring) {
239                 xenbus_dev_fatal(dev, -ENOMEM, "allocating shared ring");
240                 return -ENOMEM;
241         }
242         tp->tx = sring;
243
244         err = xenbus_grant_ring(dev, virt_to_mfn(tp->tx));
245         if (err < 0) {
246                 free_page((unsigned long)sring);
247                 tp->tx = NULL;
248                 xenbus_dev_fatal(dev, err, "allocating grant reference");
249                 goto fail;
250         }
251         tp->ring_ref = err;
252
253         err = tpmif_connect(dev, tp, dev->otherend_id);
254         if (err)
255                 goto fail;
256
257         return 0;
258 fail:
259         destroy_tpmring(tp);
260         return err;
261 }
262
263
264 static void destroy_tpmring(struct tpm_private *tp)
265 {
266         tpmif_set_connected_state(tp, 0);
267
268         if (tp->ring_ref != GRANT_INVALID_REF) {
269                 gnttab_end_foreign_access(tp->ring_ref, (unsigned long)tp->tx);
270                 tp->ring_ref = GRANT_INVALID_REF;
271                 tp->tx = NULL;
272         }
273
274         if (tp->irq)
275                 unbind_from_irqhandler(tp->irq, tp);
276
277         tp->irq = 0;
278 }
279
280
281 static int talk_to_backend(struct xenbus_device *dev,
282                            struct tpm_private *tp)
283 {
284         const char *message = NULL;
285         int err;
286         struct xenbus_transaction xbt;
287
288         err = setup_tpmring(dev, tp);
289         if (err) {
290                 xenbus_dev_fatal(dev, err, "setting up ring");
291                 goto out;
292         }
293
294 again:
295         err = xenbus_transaction_start(&xbt);
296         if (err) {
297                 xenbus_dev_fatal(dev, err, "starting transaction");
298                 goto destroy_tpmring;
299         }
300
301         err = xenbus_printf(xbt, dev->nodename,
302                             "ring-ref","%u", tp->ring_ref);
303         if (err) {
304                 message = "writing ring-ref";
305                 goto abort_transaction;
306         }
307
308         err = xenbus_printf(xbt, dev->nodename, "event-channel", "%u",
309                             irq_to_evtchn_port(tp->irq));
310         if (err) {
311                 message = "writing event-channel";
312                 goto abort_transaction;
313         }
314
315         err = xenbus_transaction_end(xbt, 0);
316         if (err == -EAGAIN)
317                 goto again;
318         if (err) {
319                 xenbus_dev_fatal(dev, err, "completing transaction");
320                 goto destroy_tpmring;
321         }
322
323         xenbus_switch_state(dev, XenbusStateConnected);
324
325         return 0;
326
327 abort_transaction:
328         xenbus_transaction_end(xbt, 1);
329         if (message)
330                 xenbus_dev_error(dev, err, "%s", message);
331 destroy_tpmring:
332         destroy_tpmring(tp);
333 out:
334         return err;
335 }
336
337 /**
338  * Callback received when the backend's state changes.
339  */
340 static void backend_changed(struct xenbus_device *dev,
341                             enum xenbus_state backend_state)
342 {
343         struct tpm_private *tp = tpm_private_from_dev(&dev->dev);
344         DPRINTK("\n");
345
346         switch (backend_state) {
347         case XenbusStateInitialising:
348         case XenbusStateInitWait:
349         case XenbusStateInitialised:
350         case XenbusStateReconfiguring:
351         case XenbusStateReconfigured:
352         case XenbusStateUnknown:
353                 break;
354
355         case XenbusStateConnected:
356                 tpmif_set_connected_state(tp, 1);
357                 break;
358
359         case XenbusStateClosing:
360                 tpmif_set_connected_state(tp, 0);
361                 xenbus_frontend_closed(dev);
362                 break;
363
364         case XenbusStateClosed:
365                 tpmif_set_connected_state(tp, 0);
366                 if (tp->is_suspended == 0)
367                         device_unregister(&dev->dev);
368                 xenbus_frontend_closed(dev);
369                 break;
370         }
371 }
372
373 static int tpmfront_probe(struct xenbus_device *dev,
374                           const struct xenbus_device_id *id)
375 {
376         int err;
377         int handle;
378         struct tpm_private *tp = tpm_private_get();
379
380         if (!tp)
381                 return -ENOMEM;
382
383         tp->chip = init_vtpm(&dev->dev, tp);
384         if (IS_ERR(tp->chip))
385                 return PTR_ERR(tp->chip);
386
387         err = xenbus_scanf(XBT_NIL, dev->nodename,
388                            "handle", "%i", &handle);
389         if (XENBUS_EXIST_ERR(err))
390                 return err;
391
392         if (err < 0) {
393                 xenbus_dev_fatal(dev,err,"reading virtual-device");
394                 return err;
395         }
396
397         tp->dev = dev;
398
399         err = talk_to_backend(dev, tp);
400         if (err) {
401                 tpm_private_put();
402                 return err;
403         }
404
405         return 0;
406 }
407
408
409 static int tpmfront_remove(struct xenbus_device *dev)
410 {
411         struct tpm_private *tp = tpm_private_from_dev(&dev->dev);
412         destroy_tpmring(tp);
413         cleanup_vtpm(&dev->dev);
414         return 0;
415 }
416
417 static int tpmfront_suspend(struct xenbus_device *dev)
418 {
419         struct tpm_private *tp = tpm_private_from_dev(&dev->dev);
420         u32 ctr;
421
422         /* Take the lock, preventing any application from sending. */
423         mutex_lock(&suspend_lock);
424         tp->is_suspended = 1;
425
426         for (ctr = 0; atomic_read(&tp->tx_busy); ctr++) {
427                 if ((ctr % 10) == 0)
428                         printk("TPM-FE [INFO]: Waiting for outstanding "
429                                "request.\n");
430                 /* Wait for a request to be responded to. */
431                 interruptible_sleep_on_timeout(&tp->wait_q, 100);
432         }
433
434         return 0;
435 }
436
437 static int tpmfront_suspend_finish(struct tpm_private *tp)
438 {
439         tp->is_suspended = 0;
440         /* Allow applications to send again. */
441         mutex_unlock(&suspend_lock);
442         return 0;
443 }
444
445 static int tpmfront_suspend_cancel(struct xenbus_device *dev)
446 {
447         struct tpm_private *tp = tpm_private_from_dev(&dev->dev);
448         return tpmfront_suspend_finish(tp);
449 }
450
451 static int tpmfront_resume(struct xenbus_device *dev)
452 {
453         struct tpm_private *tp = tpm_private_from_dev(&dev->dev);
454         destroy_tpmring(tp);
455         return talk_to_backend(dev, tp);
456 }
457
458 static int tpmif_connect(struct xenbus_device *dev,
459                          struct tpm_private *tp,
460                          domid_t domid)
461 {
462         int err;
463
464         tp->backend_id = domid;
465
466         err = bind_listening_port_to_irqhandler(
467                 domid, tpmif_int, IRQF_SAMPLE_RANDOM, "tpmif", tp);
468         if (err <= 0) {
469                 WPRINTK("bind_listening_port_to_irqhandler failed "
470                         "(err=%d)\n", err);
471                 return err;
472         }
473         tp->irq = err;
474
475         return 0;
476 }
477
478 static const struct xenbus_device_id tpmfront_ids[] = {
479         { "vtpm" },
480         { "" }
481 };
482 MODULE_ALIAS("xen:vtpm");
483
484 static DEFINE_XENBUS_DRIVER(tpmfront, ,
485         .probe = tpmfront_probe,
486         .remove =  tpmfront_remove,
487         .resume = tpmfront_resume,
488         .otherend_changed = backend_changed,
489         .suspend = tpmfront_suspend,
490         .suspend_cancel = tpmfront_suspend_cancel,
491 );
492
493 static int __init init_tpm_xenbus(void)
494 {
495         return xenbus_register_frontend(&tpmfront_driver);
496 }
497
498 static int tpmif_allocate_tx_buffers(struct tpm_private *tp)
499 {
500         unsigned int i;
501
502         for (i = 0; i < TPMIF_TX_RING_SIZE; i++) {
503                 tp->tx_buffers[i] = tx_buffer_alloc();
504                 if (!tp->tx_buffers[i]) {
505                         tpmif_free_tx_buffers(tp);
506                         return -ENOMEM;
507                 }
508         }
509         return 0;
510 }
511
512 static void tpmif_free_tx_buffers(struct tpm_private *tp)
513 {
514         unsigned int i;
515
516         for (i = 0; i < TPMIF_TX_RING_SIZE; i++)
517                 tx_buffer_free(tp->tx_buffers[i]);
518 }
519
520 static void tpmif_rx_action(unsigned long priv)
521 {
522         struct tpm_private *tp = (struct tpm_private *)priv;
523         int i = 0;
524         unsigned int received;
525         unsigned int offset = 0;
526         u8 *buffer;
527         tpmif_tx_request_t *tx = &tp->tx->ring[i].req;
528
529         atomic_set(&tp->tx_busy, 0);
530         wake_up_interruptible(&tp->wait_q);
531
532         received = tx->size;
533
534         buffer = kmalloc(received, GFP_ATOMIC);
535         if (!buffer)
536                 return;
537
538         for (i = 0; i < TPMIF_TX_RING_SIZE && offset < received; i++) {
539                 struct tx_buffer *txb = tp->tx_buffers[i];
540                 tpmif_tx_request_t *tx;
541                 unsigned int tocopy;
542
543                 tx = &tp->tx->ring[i].req;
544                 tocopy = tx->size;
545                 if (tocopy > PAGE_SIZE)
546                         tocopy = PAGE_SIZE;
547
548                 memcpy(&buffer[offset], txb->data, tocopy);
549
550                 gnttab_release_grant_reference(&gref_head, tx->ref);
551
552                 offset += tocopy;
553         }
554
555         vtpm_vd_recv(tp->chip, buffer, received, tp->tx_remember);
556         kfree(buffer);
557 }
558
559
560 static irqreturn_t tpmif_int(int irq, void *tpm_priv)
561 {
562         struct tpm_private *tp = tpm_priv;
563         unsigned long flags;
564
565         spin_lock_irqsave(&tp->tx_lock, flags);
566         tpmif_rx_tasklet.data = (unsigned long)tp;
567         tasklet_schedule(&tpmif_rx_tasklet);
568         spin_unlock_irqrestore(&tp->tx_lock, flags);
569
570         return IRQ_HANDLED;
571 }
572
573
574 static int tpm_xmit(struct tpm_private *tp,
575                     const u8 * buf, size_t count, int isuserbuffer,
576                     void *remember)
577 {
578         tpmif_tx_request_t *tx;
579         TPMIF_RING_IDX i;
580         unsigned int offset = 0;
581
582         spin_lock_irq(&tp->tx_lock);
583
584         if (unlikely(atomic_read(&tp->tx_busy))) {
585                 printk("tpm_xmit: There's an outstanding request/response "
586                        "on the way!\n");
587                 spin_unlock_irq(&tp->tx_lock);
588                 return -EBUSY;
589         }
590
591         if (tp->is_connected != 1) {
592                 spin_unlock_irq(&tp->tx_lock);
593                 return -EIO;
594         }
595
596         for (i = 0; count > 0 && i < TPMIF_TX_RING_SIZE; i++) {
597                 struct tx_buffer *txb = tp->tx_buffers[i];
598                 int copied;
599
600                 if (!txb) {
601                         DPRINTK("txb (i=%d) is NULL. buffers initilized?\n"
602                                 "Not transmitting anything!\n", i);
603                         spin_unlock_irq(&tp->tx_lock);
604                         return -EFAULT;
605                 }
606
607                 copied = tx_buffer_copy(txb, &buf[offset], count,
608                                         isuserbuffer);
609                 if (copied < 0) {
610                         /* An error occurred */
611                         spin_unlock_irq(&tp->tx_lock);
612                         return copied;
613                 }
614                 count -= copied;
615                 offset += copied;
616
617                 tx = &tp->tx->ring[i].req;
618                 tx->addr = virt_to_machine(txb->data);
619                 tx->size = txb->len;
620                 tx->unused = 0;
621
622                 DPRINTK("First 4 characters sent by TPM-FE are "
623                         "0x%02x 0x%02x 0x%02x 0x%02x\n",
624                         txb->data[0],txb->data[1],txb->data[2],txb->data[3]);
625
626                 /* Get the granttable reference for this page. */
627                 tx->ref = gnttab_claim_grant_reference(&gref_head);
628                 if (tx->ref == -ENOSPC) {
629                         spin_unlock_irq(&tp->tx_lock);
630                         DPRINTK("Grant table claim reference failed in "
631                                 "func:%s line:%d file:%s\n",
632                                 __FUNCTION__, __LINE__, __FILE__);
633                         return -ENOSPC;
634                 }
635                 gnttab_grant_foreign_access_ref(tx->ref,
636                                                 tp->backend_id,
637                                                 virt_to_mfn(txb->data),
638                                                 0 /*RW*/);
639                 wmb();
640         }
641
642         atomic_set(&tp->tx_busy, 1);
643         tp->tx_remember = remember;
644
645         mb();
646
647         notify_remote_via_irq(tp->irq);
648
649         spin_unlock_irq(&tp->tx_lock);
650         return offset;
651 }
652
653
654 static void tpmif_notify_upperlayer(struct tpm_private *tp)
655 {
656         /* Notify upper layer about the state of the connection to the BE. */
657         vtpm_vd_status(tp->chip, (tp->is_connected
658                                   ? TPM_VD_STATUS_CONNECTED
659                                   : TPM_VD_STATUS_DISCONNECTED));
660 }
661
662
663 static void tpmif_set_connected_state(struct tpm_private *tp, u8 is_connected)
664 {
665         /*
666          * Don't notify upper layer if we are in suspend mode and
667          * should disconnect - assumption is that we will resume
668          * The mutex keeps apps from sending.
669          */
670         if (is_connected == 0 && tp->is_suspended == 1)
671                 return;
672
673         /*
674          * Unlock the mutex if we are connected again
675          * after being suspended - now resuming.
676          * This also removes the suspend state.
677          */
678         if (is_connected == 1 && tp->is_suspended == 1)
679                 tpmfront_suspend_finish(tp);
680
681         if (is_connected != tp->is_connected) {
682                 tp->is_connected = is_connected;
683                 tpmif_notify_upperlayer(tp);
684         }
685 }
686
687
688
689 /* =================================================================
690  * Initialization function.
691  * =================================================================
692  */
693
694
695 static int __init tpmif_init(void)
696 {
697         struct tpm_private *tp;
698
699         if (is_initial_xendomain())
700                 return -EPERM;
701
702         tp = tpm_private_get();
703         if (!tp)
704                 return -ENOMEM;
705
706         IPRINTK("Initialising the vTPM driver.\n");
707         if (gnttab_alloc_grant_references(TPMIF_TX_RING_SIZE,
708                                           &gref_head) < 0) {
709                 tpm_private_put();
710                 return -EFAULT;
711         }
712
713         init_tpm_xenbus();
714         return 0;
715 }
716
717
718 module_init(tpmif_init);
719
720 MODULE_LICENSE("Dual BSD/GPL");