BACKPORT: TPM: Retry SaveState command in suspend path
[cascardo/linux.git] / drivers / char / tpm / tpm.c
1 /*
2  * Copyright (C) 2004 IBM Corporation
3  *
4  * Authors:
5  * Leendert van Doorn <leendert@watson.ibm.com>
6  * Dave Safford <safford@watson.ibm.com>
7  * Reiner Sailer <sailer@watson.ibm.com>
8  * Kylene Hall <kjhall@us.ibm.com>
9  *
10  * Maintained by: <tpmdd-devel@lists.sourceforge.net>
11  *
12  * Device driver for TCG/TCPA TPM (trusted platform module).
13  * Specifications at www.trustedcomputinggroup.org       
14  *
15  * This program is free software; you can redistribute it and/or
16  * modify it under the terms of the GNU General Public License as
17  * published by the Free Software Foundation, version 2 of the
18  * License.
19  * 
20  * Note, the TPM chip is not interrupt driven (only polling)
21  * and can have very long timeouts (minutes!). Hence the unusual
22  * calls to msleep.
23  *
24  */
25
26 #include <linux/poll.h>
27 #include <linux/slab.h>
28 #include <linux/jiffies.h>
29 #include <linux/mutex.h>
30 #include <linux/spinlock.h>
31 #include <linux/freezer.h>
32
33 #include "tpm.h"
34
35 enum tpm_const {
36         TPM_MINOR = 224,        /* officially assigned */
37         TPM_BUFSIZE = 4096,
38         TPM_NUM_DEVICES = 256,
39 };
40
41 enum tpm_duration {
42         TPM_SHORT = 0,
43         TPM_MEDIUM = 1,
44         TPM_LONG = 2,
45         TPM_UNDEFINED,
46 };
47
48 #define TPM_MAX_ORDINAL 243
49 #define TPM_MAX_PROTECTED_ORDINAL 12
50 #define TPM_PROTECTED_ORDINAL_MASK 0xFF
51
52 /*
53  * Bug workaround - some TPM's don't flush the most
54  * recently changed pcr on suspend, so force the flush
55  * with an extend to the selected _unused_ non-volatile pcr.
56  */
57 static int tpm_suspend_pcr;
58 module_param_named(suspend_pcr, tpm_suspend_pcr, uint, 0644);
59 MODULE_PARM_DESC(suspend_pcr,
60                  "PCR to use for dummy writes to faciltate flush on suspend.");
61
62 static LIST_HEAD(tpm_chip_list);
63 static DEFINE_SPINLOCK(driver_lock);
64 static DECLARE_BITMAP(dev_mask, TPM_NUM_DEVICES);
65
66 /*
67  * Array with one entry per ordinal defining the maximum amount
68  * of time the chip could take to return the result.  The ordinal
69  * designation of short, medium or long is defined in a table in
70  * TCG Specification TPM Main Part 2 TPM Structures Section 17. The
71  * values of the SHORT, MEDIUM, and LONG durations are retrieved
72  * from the chip during initialization with a call to tpm_get_timeouts.
73  */
74 static const u8 tpm_protected_ordinal_duration[TPM_MAX_PROTECTED_ORDINAL] = {
75         TPM_UNDEFINED,          /* 0 */
76         TPM_UNDEFINED,
77         TPM_UNDEFINED,
78         TPM_UNDEFINED,
79         TPM_UNDEFINED,
80         TPM_UNDEFINED,          /* 5 */
81         TPM_UNDEFINED,
82         TPM_UNDEFINED,
83         TPM_UNDEFINED,
84         TPM_UNDEFINED,
85         TPM_SHORT,              /* 10 */
86         TPM_SHORT,
87 };
88
89 static const u8 tpm_ordinal_duration[TPM_MAX_ORDINAL] = {
90         TPM_UNDEFINED,          /* 0 */
91         TPM_UNDEFINED,
92         TPM_UNDEFINED,
93         TPM_UNDEFINED,
94         TPM_UNDEFINED,
95         TPM_UNDEFINED,          /* 5 */
96         TPM_UNDEFINED,
97         TPM_UNDEFINED,
98         TPM_UNDEFINED,
99         TPM_UNDEFINED,
100         TPM_SHORT,              /* 10 */
101         TPM_SHORT,
102         TPM_MEDIUM,
103         TPM_LONG,
104         TPM_LONG,
105         TPM_MEDIUM,             /* 15 */
106         TPM_SHORT,
107         TPM_SHORT,
108         TPM_MEDIUM,
109         TPM_LONG,
110         TPM_SHORT,              /* 20 */
111         TPM_SHORT,
112         TPM_MEDIUM,
113         TPM_MEDIUM,
114         TPM_MEDIUM,
115         TPM_SHORT,              /* 25 */
116         TPM_SHORT,
117         TPM_MEDIUM,
118         TPM_SHORT,
119         TPM_SHORT,
120         TPM_MEDIUM,             /* 30 */
121         TPM_LONG,
122         TPM_MEDIUM,
123         TPM_SHORT,
124         TPM_SHORT,
125         TPM_SHORT,              /* 35 */
126         TPM_MEDIUM,
127         TPM_MEDIUM,
128         TPM_UNDEFINED,
129         TPM_UNDEFINED,
130         TPM_MEDIUM,             /* 40 */
131         TPM_LONG,
132         TPM_MEDIUM,
133         TPM_SHORT,
134         TPM_SHORT,
135         TPM_SHORT,              /* 45 */
136         TPM_SHORT,
137         TPM_SHORT,
138         TPM_SHORT,
139         TPM_LONG,
140         TPM_MEDIUM,             /* 50 */
141         TPM_MEDIUM,
142         TPM_UNDEFINED,
143         TPM_UNDEFINED,
144         TPM_UNDEFINED,
145         TPM_UNDEFINED,          /* 55 */
146         TPM_UNDEFINED,
147         TPM_UNDEFINED,
148         TPM_UNDEFINED,
149         TPM_UNDEFINED,
150         TPM_MEDIUM,             /* 60 */
151         TPM_MEDIUM,
152         TPM_MEDIUM,
153         TPM_SHORT,
154         TPM_SHORT,
155         TPM_MEDIUM,             /* 65 */
156         TPM_UNDEFINED,
157         TPM_UNDEFINED,
158         TPM_UNDEFINED,
159         TPM_UNDEFINED,
160         TPM_SHORT,              /* 70 */
161         TPM_SHORT,
162         TPM_UNDEFINED,
163         TPM_UNDEFINED,
164         TPM_UNDEFINED,
165         TPM_UNDEFINED,          /* 75 */
166         TPM_UNDEFINED,
167         TPM_UNDEFINED,
168         TPM_UNDEFINED,
169         TPM_UNDEFINED,
170         TPM_LONG,               /* 80 */
171         TPM_UNDEFINED,
172         TPM_MEDIUM,
173         TPM_LONG,
174         TPM_SHORT,
175         TPM_UNDEFINED,          /* 85 */
176         TPM_UNDEFINED,
177         TPM_UNDEFINED,
178         TPM_UNDEFINED,
179         TPM_UNDEFINED,
180         TPM_SHORT,              /* 90 */
181         TPM_SHORT,
182         TPM_SHORT,
183         TPM_SHORT,
184         TPM_SHORT,
185         TPM_UNDEFINED,          /* 95 */
186         TPM_UNDEFINED,
187         TPM_UNDEFINED,
188         TPM_UNDEFINED,
189         TPM_UNDEFINED,
190         TPM_MEDIUM,             /* 100 */
191         TPM_SHORT,
192         TPM_SHORT,
193         TPM_UNDEFINED,
194         TPM_UNDEFINED,
195         TPM_UNDEFINED,          /* 105 */
196         TPM_UNDEFINED,
197         TPM_UNDEFINED,
198         TPM_UNDEFINED,
199         TPM_UNDEFINED,
200         TPM_SHORT,              /* 110 */
201         TPM_SHORT,
202         TPM_SHORT,
203         TPM_SHORT,
204         TPM_SHORT,
205         TPM_SHORT,              /* 115 */
206         TPM_SHORT,
207         TPM_SHORT,
208         TPM_UNDEFINED,
209         TPM_UNDEFINED,
210         TPM_LONG,               /* 120 */
211         TPM_LONG,
212         TPM_MEDIUM,
213         TPM_UNDEFINED,
214         TPM_SHORT,
215         TPM_SHORT,              /* 125 */
216         TPM_SHORT,
217         TPM_LONG,
218         TPM_SHORT,
219         TPM_SHORT,
220         TPM_SHORT,              /* 130 */
221         TPM_MEDIUM,
222         TPM_UNDEFINED,
223         TPM_SHORT,
224         TPM_MEDIUM,
225         TPM_UNDEFINED,          /* 135 */
226         TPM_UNDEFINED,
227         TPM_UNDEFINED,
228         TPM_UNDEFINED,
229         TPM_UNDEFINED,
230         TPM_SHORT,              /* 140 */
231         TPM_SHORT,
232         TPM_UNDEFINED,
233         TPM_UNDEFINED,
234         TPM_UNDEFINED,
235         TPM_UNDEFINED,          /* 145 */
236         TPM_UNDEFINED,
237         TPM_UNDEFINED,
238         TPM_UNDEFINED,
239         TPM_UNDEFINED,
240         TPM_SHORT,              /* 150 */
241         TPM_MEDIUM,
242         TPM_MEDIUM,
243         TPM_SHORT,
244         TPM_SHORT,
245         TPM_UNDEFINED,          /* 155 */
246         TPM_UNDEFINED,
247         TPM_UNDEFINED,
248         TPM_UNDEFINED,
249         TPM_UNDEFINED,
250         TPM_SHORT,              /* 160 */
251         TPM_SHORT,
252         TPM_SHORT,
253         TPM_SHORT,
254         TPM_UNDEFINED,
255         TPM_UNDEFINED,          /* 165 */
256         TPM_UNDEFINED,
257         TPM_UNDEFINED,
258         TPM_UNDEFINED,
259         TPM_UNDEFINED,
260         TPM_LONG,               /* 170 */
261         TPM_UNDEFINED,
262         TPM_UNDEFINED,
263         TPM_UNDEFINED,
264         TPM_UNDEFINED,
265         TPM_UNDEFINED,          /* 175 */
266         TPM_UNDEFINED,
267         TPM_UNDEFINED,
268         TPM_UNDEFINED,
269         TPM_UNDEFINED,
270         TPM_MEDIUM,             /* 180 */
271         TPM_SHORT,
272         TPM_MEDIUM,
273         TPM_MEDIUM,
274         TPM_MEDIUM,
275         TPM_MEDIUM,             /* 185 */
276         TPM_SHORT,
277         TPM_UNDEFINED,
278         TPM_UNDEFINED,
279         TPM_UNDEFINED,
280         TPM_UNDEFINED,          /* 190 */
281         TPM_UNDEFINED,
282         TPM_UNDEFINED,
283         TPM_UNDEFINED,
284         TPM_UNDEFINED,
285         TPM_UNDEFINED,          /* 195 */
286         TPM_UNDEFINED,
287         TPM_UNDEFINED,
288         TPM_UNDEFINED,
289         TPM_UNDEFINED,
290         TPM_SHORT,              /* 200 */
291         TPM_UNDEFINED,
292         TPM_UNDEFINED,
293         TPM_UNDEFINED,
294         TPM_SHORT,
295         TPM_SHORT,              /* 205 */
296         TPM_SHORT,
297         TPM_SHORT,
298         TPM_SHORT,
299         TPM_SHORT,
300         TPM_MEDIUM,             /* 210 */
301         TPM_UNDEFINED,
302         TPM_MEDIUM,
303         TPM_MEDIUM,
304         TPM_MEDIUM,
305         TPM_UNDEFINED,          /* 215 */
306         TPM_MEDIUM,
307         TPM_UNDEFINED,
308         TPM_UNDEFINED,
309         TPM_SHORT,
310         TPM_SHORT,              /* 220 */
311         TPM_SHORT,
312         TPM_SHORT,
313         TPM_SHORT,
314         TPM_SHORT,
315         TPM_UNDEFINED,          /* 225 */
316         TPM_UNDEFINED,
317         TPM_UNDEFINED,
318         TPM_UNDEFINED,
319         TPM_UNDEFINED,
320         TPM_SHORT,              /* 230 */
321         TPM_LONG,
322         TPM_MEDIUM,
323         TPM_UNDEFINED,
324         TPM_UNDEFINED,
325         TPM_UNDEFINED,          /* 235 */
326         TPM_UNDEFINED,
327         TPM_UNDEFINED,
328         TPM_UNDEFINED,
329         TPM_UNDEFINED,
330         TPM_SHORT,              /* 240 */
331         TPM_UNDEFINED,
332         TPM_MEDIUM,
333 };
334
335 static void user_reader_timeout(unsigned long ptr)
336 {
337         struct tpm_chip *chip = (struct tpm_chip *) ptr;
338
339         schedule_work(&chip->work);
340 }
341
342 static void timeout_work(struct work_struct *work)
343 {
344         struct tpm_chip *chip = container_of(work, struct tpm_chip, work);
345
346         mutex_lock(&chip->buffer_mutex);
347         atomic_set(&chip->data_pending, 0);
348         memset(chip->data_buffer, 0, TPM_BUFSIZE);
349         mutex_unlock(&chip->buffer_mutex);
350 }
351
352 static void set_needs_resume(struct tpm_chip *chip)
353 {
354         mutex_lock(&chip->resume_mutex);
355         chip->needs_resume = 1;
356         mutex_unlock(&chip->resume_mutex);
357 }
358
359 #define TPM_ORD_CONTINUE_SELFTEST 83
360 #define CONTINUE_SELFTEST_RESULT_SIZE 10
361
362 #define TPM_INTERNAL_RESULT_SIZE 200
363 #define TPM_TAG_RQU_COMMAND cpu_to_be16(193)
364 #define TPM_ORD_GET_CAP cpu_to_be32(101)
365
366 static const struct tpm_input_header tpm_getcap_header = {
367         .tag = TPM_TAG_RQU_COMMAND,
368         .length = cpu_to_be32(22),
369         .ordinal = TPM_ORD_GET_CAP
370 };
371
372 static struct tpm_input_header continue_selftest_header = {
373         .tag = TPM_TAG_RQU_COMMAND,
374         .length = cpu_to_be32(10),
375         .ordinal = cpu_to_be32(TPM_ORD_CONTINUE_SELFTEST),
376 };
377
378 /*
379  * Internal kernel interface to transmit TPM commands
380  */
381 static ssize_t tpm_transmit(struct tpm_chip *chip, const char *buf,
382                             size_t bufsiz)
383 {
384         ssize_t rc;
385         u32 count, ordinal;
386         unsigned long stop;
387
388         if (bufsiz > TPM_BUFSIZE)
389                 bufsiz = TPM_BUFSIZE;
390
391         count = be32_to_cpu(*((__be32 *) (buf + 2)));
392         ordinal = be32_to_cpu(*((__be32 *) (buf + 6)));
393         if (count == 0)
394                 return -ENODATA;
395         if (count > bufsiz) {
396                 dev_err(chip->dev,
397                         "invalid count value %x %zx \n", count, bufsiz);
398                 return -E2BIG;
399         }
400
401         mutex_lock(&chip->tpm_mutex);
402
403         if ((rc = chip->vendor.send(chip, (u8 *) buf, count)) < 0) {
404                 dev_err(chip->dev,
405                         "tpm_transmit: tpm_send: error %zd\n", rc);
406                 goto out;
407         }
408
409         if (chip->vendor.irq)
410                 goto out_recv;
411
412         stop = jiffies + tpm_calc_ordinal_duration(chip, ordinal);
413         do {
414                 u8 status = chip->vendor.status(chip);
415                 if ((status & chip->vendor.req_complete_mask) ==
416                     chip->vendor.req_complete_val)
417                         goto out_recv;
418
419                 if ((status == chip->vendor.req_canceled)) {
420                         dev_err(chip->dev, "Operation Canceled\n");
421                         rc = -ECANCELED;
422                         goto out;
423                 }
424
425                 msleep(TPM_TIMEOUT);    /* CHECK */
426                 rmb();
427         } while (time_before(jiffies, stop));
428
429         chip->vendor.cancel(chip);
430         dev_err(chip->dev, "Operation Timed out\n");
431         rc = -ETIME;
432         goto out;
433
434 out_recv:
435         rc = chip->vendor.recv(chip, (u8 *) buf, bufsiz);
436         if (rc < 0)
437                 dev_err(chip->dev,
438                         "tpm_transmit: tpm_recv: error %zd\n", rc);
439 out:
440         mutex_unlock(&chip->tpm_mutex);
441         return rc;
442 }
443
444 void tpm_continue_selftest_nocheck(struct tpm_chip *chip)
445 {
446         struct tpm_cmd_t cmd;
447         cmd.header.in = continue_selftest_header;
448         tpm_transmit(chip, (u8 *) &cmd, CONTINUE_SELFTEST_RESULT_SIZE);
449 }
450 EXPORT_SYMBOL_GPL(tpm_continue_selftest_nocheck);
451
452 /* The maximum time in milliseconds that the TPM self test will take to
453  * complete.  TODO(semenzato): 1s should be plenty for all TPMs, but how can we
454  * ensure it?
455  */
456 #define TPM_SELF_TEST_DURATION_MSEC 1000
457
458 /* We don't want to wait for the self test to complete at resume, because it
459  * impacts the resume speed.  TPM commands are infrequent so the wait is
460  * usually not needed and is wasteful.  Instead, before we send any command, we
461  * check that enough time has elapsed from the resume so that we are
462  * comfortable that the self test has completed.  If not, we wait.  Unlike at
463  * boot, here we don't check the return code of continue_self_test, so we can
464  * use a code path which avoids recursion.  Furthermore, this only works when
465  * ContinueSelfTest is blocking, that is it returns only after the self test
466  * has completed, which is the case for the Infineon TPM.
467  */
468 static void resume_if_needed(struct tpm_chip *chip)
469 {
470         mutex_lock(&chip->resume_mutex);
471         if (chip->needs_resume) {
472                 dev_info(chip->dev, "waiting for TPM self test\n");
473                 tpm_continue_selftest_nocheck(chip);
474                 chip->needs_resume = 0;
475                 dev_info(chip->dev, "TPM delayed resume completed\n");
476         }
477         mutex_unlock(&chip->resume_mutex);
478 }
479
480 ssize_t tpm_transmit_cmd(struct tpm_chip *chip, struct tpm_cmd_t *cmd,
481                          int len, const char *desc)
482 {
483         int err;
484
485         resume_if_needed(chip);
486
487         len = tpm_transmit(chip,(u8 *) cmd, len);
488         if (len <  0)
489                 return len;
490         else if (len < TPM_HEADER_SIZE)
491                 return -EFAULT;
492
493         err = be32_to_cpu(cmd->header.out.return_code);
494         if (err != 0)
495                 dev_err(chip->dev, "A TPM error (%d) occurred %s\n", err, desc);
496
497         return err;
498 }
499 EXPORT_SYMBOL_GPL(tpm_transmit_cmd);
500
501 /**
502  * tpm_continue_selftest -- run TPM's selftest
503  * @chip: TPM chip to use
504  *
505  * Returns 0 on success, < 0 in case of fatal error or a value > 0 representing
506  * a TPM error code.
507  */
508 int tpm_continue_selftest(struct tpm_chip *chip)
509 {
510         int rc;
511         struct tpm_cmd_t cmd;
512
513         cmd.header.in = continue_selftest_header;
514         rc = tpm_transmit_cmd(chip, &cmd,
515                               CONTINUE_SELFTEST_RESULT_SIZE, "continue selftest");
516         return rc;
517 }
518 EXPORT_SYMBOL_GPL(tpm_continue_selftest);
519
520 /*
521  * Returns max number of jiffies to wait
522  */
523 unsigned long tpm_calc_ordinal_duration(struct tpm_chip *chip,
524                                            u32 ordinal)
525 {
526         int duration_idx = TPM_UNDEFINED;
527         int duration = 0;
528
529         if (ordinal < TPM_MAX_ORDINAL)
530                 duration_idx = tpm_ordinal_duration[ordinal];
531         else if ((ordinal & TPM_PROTECTED_ORDINAL_MASK) <
532                  TPM_MAX_PROTECTED_ORDINAL)
533                 duration_idx =
534                     tpm_protected_ordinal_duration[ordinal &
535                                                    TPM_PROTECTED_ORDINAL_MASK];
536
537         if (duration_idx != TPM_UNDEFINED)
538                 duration = chip->vendor.duration[duration_idx];
539         if (duration <= 0)
540                 return 2 * 60 * HZ;
541         else
542                 return duration;
543 }
544 EXPORT_SYMBOL_GPL(tpm_calc_ordinal_duration);
545
546 #define TPM_DIGEST_SIZE 20
547 #define TPM_RET_CODE_IDX 6
548
549 enum tpm_capabilities {
550         TPM_CAP_FLAG = cpu_to_be32(4),
551         TPM_CAP_PROP = cpu_to_be32(5),
552         CAP_VERSION_1_1 = cpu_to_be32(0x06),
553         CAP_VERSION_1_2 = cpu_to_be32(0x1A)
554 };
555
556 enum tpm_sub_capabilities {
557         TPM_CAP_PROP_PCR = cpu_to_be32(0x101),
558         TPM_CAP_PROP_MANUFACTURER = cpu_to_be32(0x103),
559         TPM_CAP_FLAG_PERM = cpu_to_be32(0x108),
560         TPM_CAP_FLAG_VOL = cpu_to_be32(0x109),
561         TPM_CAP_PROP_OWNER = cpu_to_be32(0x111),
562         TPM_CAP_PROP_TIS_TIMEOUT = cpu_to_be32(0x115),
563         TPM_CAP_PROP_TIS_DURATION = cpu_to_be32(0x120),
564
565 };
566
567 ssize_t tpm_getcap(struct device *dev, __be32 subcap_id, cap_t *cap,
568                    const char *desc)
569 {
570         struct tpm_cmd_t tpm_cmd;
571         int rc;
572         struct tpm_chip *chip = dev_get_drvdata(dev);
573
574         tpm_cmd.header.in = tpm_getcap_header;
575         if (subcap_id == CAP_VERSION_1_1 || subcap_id == CAP_VERSION_1_2) {
576                 tpm_cmd.params.getcap_in.cap = subcap_id;
577                 /*subcap field not necessary */
578                 tpm_cmd.params.getcap_in.subcap_size = cpu_to_be32(0);
579                 tpm_cmd.header.in.length -= cpu_to_be32(sizeof(__be32));
580         } else {
581                 if (subcap_id == TPM_CAP_FLAG_PERM ||
582                     subcap_id == TPM_CAP_FLAG_VOL)
583                         tpm_cmd.params.getcap_in.cap = TPM_CAP_FLAG;
584                 else
585                         tpm_cmd.params.getcap_in.cap = TPM_CAP_PROP;
586                 tpm_cmd.params.getcap_in.subcap_size = cpu_to_be32(4);
587                 tpm_cmd.params.getcap_in.subcap = subcap_id;
588         }
589         rc = tpm_transmit_cmd(chip, &tpm_cmd, TPM_INTERNAL_RESULT_SIZE, desc);
590         if (!rc)
591                 *cap = tpm_cmd.params.getcap_out.cap;
592         return rc;
593 }
594
595 void tpm_gen_interrupt(struct tpm_chip *chip)
596 {
597         struct  tpm_cmd_t tpm_cmd;
598         ssize_t rc;
599
600         tpm_cmd.header.in = tpm_getcap_header;
601         tpm_cmd.params.getcap_in.cap = TPM_CAP_PROP;
602         tpm_cmd.params.getcap_in.subcap_size = cpu_to_be32(4);
603         tpm_cmd.params.getcap_in.subcap = TPM_CAP_PROP_TIS_TIMEOUT;
604
605         rc = tpm_transmit_cmd(chip, &tpm_cmd, TPM_INTERNAL_RESULT_SIZE,
606                               "attempting to determine the timeouts");
607 }
608 EXPORT_SYMBOL_GPL(tpm_gen_interrupt);
609
610 int tpm_get_timeouts(struct tpm_chip *chip)
611 {
612         struct tpm_cmd_t tpm_cmd;
613         struct timeout_t *timeout_cap;
614         struct duration_t *duration_cap;
615         ssize_t rc;
616         u32 timeout;
617         unsigned int scale = 1;
618
619         tpm_cmd.header.in = tpm_getcap_header;
620         tpm_cmd.params.getcap_in.cap = TPM_CAP_PROP;
621         tpm_cmd.params.getcap_in.subcap_size = cpu_to_be32(4);
622         tpm_cmd.params.getcap_in.subcap = TPM_CAP_PROP_TIS_TIMEOUT;
623
624         rc = tpm_transmit_cmd(chip, &tpm_cmd, TPM_INTERNAL_RESULT_SIZE,
625                               "attempting to determine the timeouts");
626         if (rc)
627                 goto duration;
628
629         if (be32_to_cpu(tpm_cmd.header.out.return_code) != 0 ||
630             be32_to_cpu(tpm_cmd.header.out.length)
631             != sizeof(tpm_cmd.header.out) + sizeof(u32) + 4 * sizeof(u32))
632                 return -EINVAL;
633
634         timeout_cap = &tpm_cmd.params.getcap_out.cap.timeout;
635         /* Don't overwrite default if value is 0 */
636         timeout = be32_to_cpu(timeout_cap->a);
637         if (timeout && timeout < 1000) {
638                 /* timeouts in msec rather usec */
639                 scale = 1000;
640                 chip->vendor.timeout_adjusted = true;
641         }
642         if (timeout)
643                 chip->vendor.timeout_a = usecs_to_jiffies(timeout * scale);
644         timeout = be32_to_cpu(timeout_cap->b);
645         if (timeout)
646                 chip->vendor.timeout_b = usecs_to_jiffies(timeout * scale);
647         timeout = be32_to_cpu(timeout_cap->c);
648         if (timeout)
649                 chip->vendor.timeout_c = usecs_to_jiffies(timeout * scale);
650         timeout = be32_to_cpu(timeout_cap->d);
651         if (timeout)
652                 chip->vendor.timeout_d = usecs_to_jiffies(timeout * scale);
653
654 duration:
655         tpm_cmd.header.in = tpm_getcap_header;
656         tpm_cmd.params.getcap_in.cap = TPM_CAP_PROP;
657         tpm_cmd.params.getcap_in.subcap_size = cpu_to_be32(4);
658         tpm_cmd.params.getcap_in.subcap = TPM_CAP_PROP_TIS_DURATION;
659
660         rc = tpm_transmit_cmd(chip, &tpm_cmd, TPM_INTERNAL_RESULT_SIZE,
661                               "attempting to determine the durations");
662         if (rc)
663                 return rc;
664
665         if (be32_to_cpu(tpm_cmd.header.out.return_code) != 0 ||
666             be32_to_cpu(tpm_cmd.header.out.length)
667             != sizeof(tpm_cmd.header.out) + sizeof(u32) + 3 * sizeof(u32))
668                 return -EINVAL;
669
670         duration_cap = &tpm_cmd.params.getcap_out.cap.duration;
671         chip->vendor.duration[TPM_SHORT] =
672             usecs_to_jiffies(be32_to_cpu(duration_cap->tpm_short));
673         chip->vendor.duration[TPM_MEDIUM] =
674             usecs_to_jiffies(be32_to_cpu(duration_cap->tpm_medium));
675         chip->vendor.duration[TPM_LONG] =
676             usecs_to_jiffies(be32_to_cpu(duration_cap->tpm_long));
677
678         /* The Broadcom BCM0102 chipset in a Dell Latitude D820 gets the above
679          * value wrong and apparently reports msecs rather than usecs. So we
680          * fix up the resulting too-small TPM_SHORT value to make things work.
681          * We also scale the TPM_MEDIUM and -_LONG values by 1000.
682          */
683         if (chip->vendor.duration[TPM_SHORT] < (HZ / 100)) {
684                 chip->vendor.duration[TPM_SHORT] = HZ;
685                 chip->vendor.duration[TPM_MEDIUM] *= 1000;
686                 chip->vendor.duration[TPM_LONG] *= 1000;
687                 chip->vendor.duration_adjusted = true;
688                 dev_info(chip->dev, "Adjusting TPM timeout parameters.\n");
689         }
690         return 0;
691 }
692 EXPORT_SYMBOL_GPL(tpm_get_timeouts);
693
694 ssize_t tpm_show_enabled(struct device * dev, struct device_attribute * attr,
695                         char *buf)
696 {
697         cap_t cap;
698         ssize_t rc;
699
700         rc = tpm_getcap(dev, TPM_CAP_FLAG_PERM, &cap,
701                          "attempting to determine the permanent enabled state");
702         if (rc)
703                 return 0;
704
705         rc = sprintf(buf, "%d\n", !cap.perm_flags.disable);
706         return rc;
707 }
708 EXPORT_SYMBOL_GPL(tpm_show_enabled);
709
710 ssize_t tpm_show_active(struct device * dev, struct device_attribute * attr,
711                         char *buf)
712 {
713         cap_t cap;
714         ssize_t rc;
715
716         rc = tpm_getcap(dev, TPM_CAP_FLAG_PERM, &cap,
717                          "attempting to determine the permanent active state");
718         if (rc)
719                 return 0;
720
721         rc = sprintf(buf, "%d\n", !cap.perm_flags.deactivated);
722         return rc;
723 }
724 EXPORT_SYMBOL_GPL(tpm_show_active);
725
726 ssize_t tpm_show_owned(struct device * dev, struct device_attribute * attr,
727                         char *buf)
728 {
729         cap_t cap;
730         ssize_t rc;
731
732         rc = tpm_getcap(dev, TPM_CAP_PROP_OWNER, &cap,
733                          "attempting to determine the owner state");
734         if (rc)
735                 return 0;
736
737         rc = sprintf(buf, "%d\n", cap.owned);
738         return rc;
739 }
740 EXPORT_SYMBOL_GPL(tpm_show_owned);
741
742 ssize_t tpm_show_temp_deactivated(struct device * dev,
743                                 struct device_attribute * attr, char *buf)
744 {
745         cap_t cap;
746         ssize_t rc;
747
748         rc = tpm_getcap(dev, TPM_CAP_FLAG_VOL, &cap,
749                          "attempting to determine the temporary state");
750         if (rc)
751                 return 0;
752
753         rc = sprintf(buf, "%d\n", cap.stclear_flags.deactivated);
754         return rc;
755 }
756 EXPORT_SYMBOL_GPL(tpm_show_temp_deactivated);
757
758 /*
759  * tpm_chip_find_get - return tpm_chip for given chip number
760  */
761 static struct tpm_chip *tpm_chip_find_get(int chip_num)
762 {
763         struct tpm_chip *pos, *chip = NULL;
764
765         rcu_read_lock();
766         list_for_each_entry_rcu(pos, &tpm_chip_list, list) {
767                 if (chip_num != TPM_ANY_NUM && chip_num != pos->dev_num)
768                         continue;
769
770                 if (try_module_get(pos->dev->driver->owner)) {
771                         chip = pos;
772                         break;
773                 }
774         }
775         rcu_read_unlock();
776         return chip;
777 }
778
779 #define TPM_ORDINAL_PCRREAD cpu_to_be32(21)
780 #define READ_PCR_RESULT_SIZE 30
781 static struct tpm_input_header pcrread_header = {
782         .tag = TPM_TAG_RQU_COMMAND,
783         .length = cpu_to_be32(14),
784         .ordinal = TPM_ORDINAL_PCRREAD
785 };
786
787 static int __tpm_pcr_read(struct tpm_chip *chip, int pcr_idx, u8 *res_buf)
788 {
789         int rc;
790         struct tpm_cmd_t cmd;
791
792         cmd.header.in = pcrread_header;
793         cmd.params.pcrread_in.pcr_idx = cpu_to_be32(pcr_idx);
794         rc = tpm_transmit_cmd(chip, &cmd, READ_PCR_RESULT_SIZE,
795                               "attempting to read a pcr value");
796
797         if (rc == 0)
798                 memcpy(res_buf, cmd.params.pcrread_out.pcr_result,
799                        TPM_DIGEST_SIZE);
800         return rc;
801 }
802
803 /**
804  * tpm_pcr_read - read a pcr value
805  * @chip_num:   tpm idx # or ANY
806  * @pcr_idx:    pcr idx to retrieve
807  * @res_buf:    TPM_PCR value
808  *              size of res_buf is 20 bytes (or NULL if you don't care)
809  *
810  * The TPM driver should be built-in, but for whatever reason it
811  * isn't, protect against the chip disappearing, by incrementing
812  * the module usage count.
813  */
814 int tpm_pcr_read(u32 chip_num, int pcr_idx, u8 *res_buf)
815 {
816         struct tpm_chip *chip;
817         int rc;
818
819         chip = tpm_chip_find_get(chip_num);
820         if (chip == NULL)
821                 return -ENODEV;
822         rc = __tpm_pcr_read(chip, pcr_idx, res_buf);
823         tpm_chip_put(chip);
824         return rc;
825 }
826 EXPORT_SYMBOL_GPL(tpm_pcr_read);
827
828 /**
829  * tpm_pcr_extend - extend pcr value with hash
830  * @chip_num:   tpm idx # or AN&
831  * @pcr_idx:    pcr idx to extend
832  * @hash:       hash value used to extend pcr value
833  *
834  * The TPM driver should be built-in, but for whatever reason it
835  * isn't, protect against the chip disappearing, by incrementing
836  * the module usage count.
837  */
838 #define TPM_ORD_PCR_EXTEND cpu_to_be32(20)
839 #define EXTEND_PCR_RESULT_SIZE 34
840 static struct tpm_input_header pcrextend_header = {
841         .tag = TPM_TAG_RQU_COMMAND,
842         .length = cpu_to_be32(34),
843         .ordinal = TPM_ORD_PCR_EXTEND
844 };
845
846 int tpm_pcr_extend(u32 chip_num, int pcr_idx, const u8 *hash)
847 {
848         struct tpm_cmd_t cmd;
849         int rc;
850         struct tpm_chip *chip;
851
852         chip = tpm_chip_find_get(chip_num);
853         if (chip == NULL)
854                 return -ENODEV;
855
856         cmd.header.in = pcrextend_header;
857         cmd.params.pcrextend_in.pcr_idx = cpu_to_be32(pcr_idx);
858         memcpy(cmd.params.pcrextend_in.hash, hash, TPM_DIGEST_SIZE);
859         rc = tpm_transmit_cmd(chip, &cmd, EXTEND_PCR_RESULT_SIZE,
860                               "attempting extend a PCR value");
861
862         tpm_chip_put(chip);
863         return rc;
864 }
865 EXPORT_SYMBOL_GPL(tpm_pcr_extend);
866
867 /**
868  * tpm_do_selftest - have the TPM continue its selftest and wait until it
869  *                   can receive further commands
870  * @chip: TPM chip to use
871  *
872  * Returns 0 on success, < 0 in case of fatal error or a value > 0 representing
873  * a TPM error code.
874  */
875 int tpm_do_selftest(struct tpm_chip *chip)
876 {
877         int rc;
878         u8 digest[TPM_DIGEST_SIZE];
879         unsigned int loops;
880         unsigned int delay_msec = 1000;
881         unsigned long duration;
882
883         duration = tpm_calc_ordinal_duration(chip,
884                                              TPM_ORD_CONTINUE_SELFTEST);
885
886         loops = jiffies_to_msecs(duration) / delay_msec;
887
888         rc = tpm_continue_selftest(chip);
889         /* This may fail if there was no TPM driver during a suspend/resume
890          * cycle; some may return 10 (BAD_ORDINAL), others 28 (FAILEDSELFTEST)
891          */
892         if (rc)
893                 return rc;
894
895         do {
896                 rc = __tpm_pcr_read(chip, 0, digest);
897                 if (rc == TPM_ERR_DISABLED || rc == TPM_ERR_DEACTIVATED) {
898                         dev_info(chip->dev,
899                                  "TPM is disabled/deactivated (0x%X)\n", rc);
900                         /* TPM is disabled and/or deactivated; driver can
901                          * proceed and TPM does handle commands for
902                          * suspend/resume correctly
903                          */
904                         return 0;
905                 }
906                 if (rc != TPM_WARN_DOING_SELFTEST)
907                         return rc;
908                 msleep(delay_msec);
909         } while (--loops > 0);
910
911         return rc;
912 }
913 EXPORT_SYMBOL_GPL(tpm_do_selftest);
914
915 int tpm_send(u32 chip_num, void *cmd, size_t buflen)
916 {
917         struct tpm_chip *chip;
918         int rc;
919
920         chip = tpm_chip_find_get(chip_num);
921         if (chip == NULL)
922                 return -ENODEV;
923
924         rc = tpm_transmit_cmd(chip, cmd, buflen, "attempting tpm_cmd");
925
926         tpm_chip_put(chip);
927         return rc;
928 }
929 EXPORT_SYMBOL_GPL(tpm_send);
930
931 ssize_t tpm_show_pcrs(struct device *dev, struct device_attribute *attr,
932                       char *buf)
933 {
934         cap_t cap;
935         u8 digest[TPM_DIGEST_SIZE];
936         ssize_t rc;
937         int i, j, num_pcrs;
938         char *str = buf;
939         struct tpm_chip *chip = dev_get_drvdata(dev);
940
941         rc = tpm_getcap(dev, TPM_CAP_PROP_PCR, &cap,
942                         "attempting to determine the number of PCRS");
943         if (rc)
944                 return 0;
945
946         num_pcrs = be32_to_cpu(cap.num_pcrs);
947         for (i = 0; i < num_pcrs; i++) {
948                 rc = __tpm_pcr_read(chip, i, digest);
949                 if (rc)
950                         break;
951                 str += sprintf(str, "PCR-%02d: ", i);
952                 for (j = 0; j < TPM_DIGEST_SIZE; j++)
953                         str += sprintf(str, "%02X ", digest[j]);
954                 str += sprintf(str, "\n");
955         }
956         return str - buf;
957 }
958 EXPORT_SYMBOL_GPL(tpm_show_pcrs);
959
960 #define  READ_PUBEK_RESULT_SIZE 314
961 #define TPM_ORD_READPUBEK cpu_to_be32(124)
962 struct tpm_input_header tpm_readpubek_header = {
963         .tag = TPM_TAG_RQU_COMMAND,
964         .length = cpu_to_be32(30),
965         .ordinal = TPM_ORD_READPUBEK
966 };
967
968 ssize_t tpm_show_pubek(struct device *dev, struct device_attribute *attr,
969                        char *buf)
970 {
971         u8 *data;
972         struct tpm_cmd_t tpm_cmd;
973         ssize_t err;
974         int i, rc;
975         char *str = buf;
976
977         struct tpm_chip *chip = dev_get_drvdata(dev);
978
979         tpm_cmd.header.in = tpm_readpubek_header;
980         err = tpm_transmit_cmd(chip, &tpm_cmd, READ_PUBEK_RESULT_SIZE,
981                                "attempting to read the PUBEK");
982         if (err)
983                 goto out;
984
985         /* 
986            ignore header 10 bytes
987            algorithm 32 bits (1 == RSA )
988            encscheme 16 bits
989            sigscheme 16 bits
990            parameters (RSA 12->bytes: keybit, #primes, expbit)  
991            keylenbytes 32 bits
992            256 byte modulus
993            ignore checksum 20 bytes
994          */
995         data = tpm_cmd.params.readpubek_out_buffer;
996         str +=
997             sprintf(str,
998                     "Algorithm: %02X %02X %02X %02X\n"
999                     "Encscheme: %02X %02X\n"
1000                     "Sigscheme: %02X %02X\n"
1001                     "Parameters: %02X %02X %02X %02X "
1002                     "%02X %02X %02X %02X "
1003                     "%02X %02X %02X %02X\n"
1004                     "Modulus length: %d\n"
1005                     "Modulus:\n",
1006                     data[0], data[1], data[2], data[3],
1007                     data[4], data[5],
1008                     data[6], data[7],
1009                     data[12], data[13], data[14], data[15],
1010                     data[16], data[17], data[18], data[19],
1011                     data[20], data[21], data[22], data[23],
1012                     be32_to_cpu(*((__be32 *) (data + 24))));
1013
1014         for (i = 0; i < 256; i++) {
1015                 str += sprintf(str, "%02X ", data[i + 28]);
1016                 if ((i + 1) % 16 == 0)
1017                         str += sprintf(str, "\n");
1018         }
1019 out:
1020         rc = str - buf;
1021         return rc;
1022 }
1023 EXPORT_SYMBOL_GPL(tpm_show_pubek);
1024
1025
1026 ssize_t tpm_show_caps(struct device *dev, struct device_attribute *attr,
1027                       char *buf)
1028 {
1029         cap_t cap;
1030         ssize_t rc;
1031         char *str = buf;
1032
1033         rc = tpm_getcap(dev, TPM_CAP_PROP_MANUFACTURER, &cap,
1034                         "attempting to determine the manufacturer");
1035         if (rc)
1036                 return 0;
1037         str += sprintf(str, "Manufacturer: 0x%x\n",
1038                        be32_to_cpu(cap.manufacturer_id));
1039
1040         rc = tpm_getcap(dev, CAP_VERSION_1_1, &cap,
1041                         "attempting to determine the 1.1 version");
1042         if (rc)
1043                 return 0;
1044         str += sprintf(str,
1045                        "TCG version: %d.%d\nFirmware version: %d.%d\n",
1046                        cap.tpm_version.Major, cap.tpm_version.Minor,
1047                        cap.tpm_version.revMajor, cap.tpm_version.revMinor);
1048         return str - buf;
1049 }
1050 EXPORT_SYMBOL_GPL(tpm_show_caps);
1051
1052 ssize_t tpm_show_caps_1_2(struct device * dev,
1053                           struct device_attribute * attr, char *buf)
1054 {
1055         cap_t cap;
1056         ssize_t rc;
1057         char *str = buf;
1058
1059         rc = tpm_getcap(dev, TPM_CAP_PROP_MANUFACTURER, &cap,
1060                         "attempting to determine the manufacturer");
1061         if (rc)
1062                 return 0;
1063         str += sprintf(str, "Manufacturer: 0x%x\n",
1064                        be32_to_cpu(cap.manufacturer_id));
1065         rc = tpm_getcap(dev, CAP_VERSION_1_2, &cap,
1066                          "attempting to determine the 1.2 version");
1067         if (rc)
1068                 return 0;
1069         str += sprintf(str,
1070                        "TCG version: %d.%d\nFirmware version: %d.%d\n",
1071                        cap.tpm_version_1_2.Major, cap.tpm_version_1_2.Minor,
1072                        cap.tpm_version_1_2.revMajor,
1073                        cap.tpm_version_1_2.revMinor);
1074         return str - buf;
1075 }
1076 EXPORT_SYMBOL_GPL(tpm_show_caps_1_2);
1077
1078 ssize_t tpm_show_durations(struct device *dev, struct device_attribute *attr,
1079                           char *buf)
1080 {
1081         struct tpm_chip *chip = dev_get_drvdata(dev);
1082
1083         if (chip->vendor.duration[TPM_LONG] == 0)
1084                 return 0;
1085
1086         return sprintf(buf, "%d %d %d [%s]\n",
1087                        jiffies_to_usecs(chip->vendor.duration[TPM_SHORT]),
1088                        jiffies_to_usecs(chip->vendor.duration[TPM_MEDIUM]),
1089                        jiffies_to_usecs(chip->vendor.duration[TPM_LONG]),
1090                        chip->vendor.duration_adjusted
1091                        ? "adjusted" : "original");
1092 }
1093 EXPORT_SYMBOL_GPL(tpm_show_durations);
1094
1095 ssize_t tpm_show_timeouts(struct device *dev, struct device_attribute *attr,
1096                           char *buf)
1097 {
1098         struct tpm_chip *chip = dev_get_drvdata(dev);
1099
1100         return sprintf(buf, "%d %d %d %d [%s]\n",
1101                        jiffies_to_usecs(chip->vendor.timeout_a),
1102                        jiffies_to_usecs(chip->vendor.timeout_b),
1103                        jiffies_to_usecs(chip->vendor.timeout_c),
1104                        jiffies_to_usecs(chip->vendor.timeout_d),
1105                        chip->vendor.timeout_adjusted
1106                        ? "adjusted" : "original");
1107 }
1108 EXPORT_SYMBOL_GPL(tpm_show_timeouts);
1109
1110 ssize_t tpm_store_cancel(struct device *dev, struct device_attribute *attr,
1111                         const char *buf, size_t count)
1112 {
1113         struct tpm_chip *chip = dev_get_drvdata(dev);
1114         if (chip == NULL)
1115                 return 0;
1116
1117         chip->vendor.cancel(chip);
1118         return count;
1119 }
1120 EXPORT_SYMBOL_GPL(tpm_store_cancel);
1121
1122 int wait_for_tpm_stat(struct tpm_chip *chip, u8 mask, unsigned long timeout,
1123                          wait_queue_head_t *queue)
1124 {
1125         unsigned long stop;
1126         long rc;
1127         u8 status;
1128
1129         /* check current status */
1130         status = chip->vendor.status(chip);
1131         if ((status & mask) == mask)
1132                 return 0;
1133
1134         stop = jiffies + timeout;
1135
1136         if (chip->vendor.irq) {
1137 again:
1138                 timeout = stop - jiffies;
1139                 if ((long)timeout <= 0)
1140                         return -ETIME;
1141                 rc = wait_event_interruptible_timeout(*queue,
1142                                                       ((chip->vendor.status(chip)
1143                                                       & mask) == mask),
1144                                                       timeout);
1145                 if (rc > 0)
1146                         return 0;
1147                 if (rc == -ERESTARTSYS && freezing(current)) {
1148                         clear_thread_flag(TIF_SIGPENDING);
1149                         goto again;
1150                 }
1151         } else {
1152                 do {
1153                         msleep(TPM_TIMEOUT);
1154                         status = chip->vendor.status(chip);
1155                         if ((status & mask) == mask)
1156                                 return 0;
1157                 } while (time_before(jiffies, stop));
1158         }
1159         return -ETIME;
1160 }
1161 EXPORT_SYMBOL_GPL(wait_for_tpm_stat);
1162 /*
1163  * Device file system interface to the TPM
1164  *
1165  * It's assured that the chip will be opened just once,
1166  * by the check of is_open variable, which is protected
1167  * by driver_lock.
1168  */
1169 int tpm_open(struct inode *inode, struct file *file)
1170 {
1171         int minor = iminor(inode);
1172         struct tpm_chip *chip = NULL, *pos;
1173
1174         rcu_read_lock();
1175         list_for_each_entry_rcu(pos, &tpm_chip_list, list) {
1176                 if (pos->vendor.miscdev.minor == minor) {
1177                         chip = pos;
1178                         get_device(chip->dev);
1179                         break;
1180                 }
1181         }
1182         rcu_read_unlock();
1183
1184         if (!chip)
1185                 return -ENODEV;
1186
1187         if (test_and_set_bit(0, &chip->is_open)) {
1188                 dev_dbg(chip->dev, "Another process owns this TPM\n");
1189                 put_device(chip->dev);
1190                 return -EBUSY;
1191         }
1192
1193         chip->data_buffer = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
1194         if (chip->data_buffer == NULL) {
1195                 clear_bit(0, &chip->is_open);
1196                 put_device(chip->dev);
1197                 return -ENOMEM;
1198         }
1199
1200         atomic_set(&chip->data_pending, 0);
1201
1202         file->private_data = chip;
1203         return 0;
1204 }
1205 EXPORT_SYMBOL_GPL(tpm_open);
1206
1207 /*
1208  * Called on file close
1209  */
1210 int tpm_release(struct inode *inode, struct file *file)
1211 {
1212         struct tpm_chip *chip = file->private_data;
1213
1214         del_singleshot_timer_sync(&chip->user_read_timer);
1215         flush_work_sync(&chip->work);
1216         file->private_data = NULL;
1217         atomic_set(&chip->data_pending, 0);
1218         kfree(chip->data_buffer);
1219         clear_bit(0, &chip->is_open);
1220         put_device(chip->dev);
1221         return 0;
1222 }
1223 EXPORT_SYMBOL_GPL(tpm_release);
1224
1225 ssize_t tpm_write(struct file *file, const char __user *buf,
1226                   size_t size, loff_t *off)
1227 {
1228         struct tpm_chip *chip = file->private_data;
1229         size_t in_size = size, out_size;
1230
1231         /* cannot perform a write until the read has cleared
1232            either via tpm_read or a user_read_timer timeout */
1233         while (atomic_read(&chip->data_pending) != 0)
1234                 msleep(TPM_TIMEOUT);
1235
1236         resume_if_needed(chip);
1237
1238         mutex_lock(&chip->buffer_mutex);
1239
1240         if (in_size > TPM_BUFSIZE)
1241                 in_size = TPM_BUFSIZE;
1242
1243         if (copy_from_user
1244             (chip->data_buffer, (void __user *) buf, in_size)) {
1245                 mutex_unlock(&chip->buffer_mutex);
1246                 return -EFAULT;
1247         }
1248
1249         /* atomic tpm command send and result receive */
1250         out_size = tpm_transmit(chip, chip->data_buffer, TPM_BUFSIZE);
1251
1252         atomic_set(&chip->data_pending, out_size);
1253         mutex_unlock(&chip->buffer_mutex);
1254
1255         /* Set a timeout by which the reader must come claim the result */
1256         mod_timer(&chip->user_read_timer, jiffies + (60 * HZ));
1257
1258         return in_size;
1259 }
1260 EXPORT_SYMBOL_GPL(tpm_write);
1261
1262 ssize_t tpm_read(struct file *file, char __user *buf,
1263                  size_t size, loff_t *off)
1264 {
1265         struct tpm_chip *chip = file->private_data;
1266         ssize_t ret_size;
1267         int rc;
1268
1269         del_singleshot_timer_sync(&chip->user_read_timer);
1270         flush_work_sync(&chip->work);
1271         ret_size = atomic_read(&chip->data_pending);
1272         /* TODO(wad): atomic_set should come AFTER the buffer is copied. */
1273         atomic_set(&chip->data_pending, 0);
1274         if (ret_size > 0) {     /* relay data */
1275                 ssize_t orig_ret_size = ret_size;
1276                 if (size < ret_size)
1277                         ret_size = size;
1278
1279                 mutex_lock(&chip->buffer_mutex);
1280                 rc = copy_to_user(buf, chip->data_buffer, ret_size);
1281                 memset(chip->data_buffer, 0, orig_ret_size);
1282                 if (rc)
1283                         ret_size = -EFAULT;
1284
1285                 mutex_unlock(&chip->buffer_mutex);
1286         }
1287
1288         return ret_size;
1289 }
1290 EXPORT_SYMBOL_GPL(tpm_read);
1291
1292 void tpm_remove_hardware(struct device *dev)
1293 {
1294         struct tpm_chip *chip = dev_get_drvdata(dev);
1295
1296         if (chip == NULL) {
1297                 dev_err(dev, "No device data found\n");
1298                 return;
1299         }
1300
1301         spin_lock(&driver_lock);
1302         list_del_rcu(&chip->list);
1303         spin_unlock(&driver_lock);
1304         synchronize_rcu();
1305
1306         misc_deregister(&chip->vendor.miscdev);
1307         sysfs_remove_group(&dev->kobj, chip->vendor.attr_group);
1308         tpm_bios_log_teardown(chip->bios_dir);
1309
1310         /* write it this way to be explicit (chip->dev == dev) */
1311         put_device(chip->dev);
1312 }
1313 EXPORT_SYMBOL_GPL(tpm_remove_hardware);
1314
1315 #define TPM_ORD_SAVESTATE cpu_to_be32(152)
1316 #define SAVESTATE_RESULT_SIZE 10
1317
1318 static struct tpm_input_header savestate_header = {
1319         .tag = TPM_TAG_RQU_COMMAND,
1320         .length = cpu_to_be32(10),
1321         .ordinal = TPM_ORD_SAVESTATE
1322 };
1323
1324 /*
1325  * We are about to suspend. Save the TPM state
1326  * so that it can be restored.
1327  */
1328 int tpm_pm_suspend(struct device *dev, pm_message_t pm_state)
1329 {
1330         struct tpm_chip *chip = dev_get_drvdata(dev);
1331         struct tpm_cmd_t cmd;
1332         int rc, try;
1333
1334         u8 dummy_hash[TPM_DIGEST_SIZE] = { 0 };
1335
1336         if (chip == NULL)
1337                 return -ENODEV;
1338
1339         /* for buggy tpm, flush pcrs with extend to selected dummy */
1340         if (tpm_suspend_pcr) {
1341                 cmd.header.in = pcrextend_header;
1342                 cmd.params.pcrextend_in.pcr_idx = cpu_to_be32(tpm_suspend_pcr);
1343                 memcpy(cmd.params.pcrextend_in.hash, dummy_hash,
1344                        TPM_DIGEST_SIZE);
1345                 rc = tpm_transmit_cmd(chip, &cmd, EXTEND_PCR_RESULT_SIZE,
1346                                       "extending dummy pcr before suspend");
1347         }
1348
1349         /* now do the actual savestate */
1350         for (try = 0; try < TPM_RETRY; try++) {
1351                 cmd.header.in = savestate_header;
1352                 rc = tpm_transmit_cmd(chip, &cmd, SAVESTATE_RESULT_SIZE, NULL);
1353
1354                 /*
1355                  * If the TPM indicates that it is too busy to respond to
1356                  * this command then retry before giving up.  It can take
1357                  * several seconds for this TPM to be ready.
1358                  *
1359                  * This can happen if the TPM has already been sent the
1360                  * SaveState command before the driver has loaded.  TCG 1.2
1361                  * specification states that any communication after SaveState
1362                  * may cause the TPM to invalidate previously saved state.
1363                  */
1364                 if (rc != TPM_WARN_RETRY)
1365                         break;
1366                 msleep(TPM_TIMEOUT_RETRY);
1367         }
1368
1369         if (rc)
1370                 dev_err(chip->dev,
1371                         "Error (%d) sending savestate before suspend\n", rc);
1372         else if (try > 0)
1373                 dev_warn(chip->dev, "TPM savestate took %dms\n",
1374                          try * TPM_TIMEOUT_RETRY);
1375
1376         return rc;
1377 }
1378 EXPORT_SYMBOL_GPL(tpm_pm_suspend);
1379
1380 /*
1381  * Resume from a power safe. The BIOS already restored
1382  * the TPM state.
1383  */
1384 int tpm_pm_resume(struct device *dev)
1385 {
1386         struct tpm_chip *chip = dev_get_drvdata(dev);
1387
1388         if (chip == NULL)
1389                 return -ENODEV;
1390
1391         set_needs_resume(chip);
1392         return 0;
1393 }
1394 EXPORT_SYMBOL_GPL(tpm_pm_resume);
1395
1396 /* In case vendor provided release function, call it too.*/
1397
1398 void tpm_dev_vendor_release(struct tpm_chip *chip)
1399 {
1400         if (chip->vendor.release)
1401                 chip->vendor.release(chip->dev);
1402
1403         clear_bit(chip->dev_num, dev_mask);
1404         kfree(chip->vendor.miscdev.name);
1405 }
1406 EXPORT_SYMBOL_GPL(tpm_dev_vendor_release);
1407
1408
1409 /*
1410  * Once all references to platform device are down to 0,
1411  * release all allocated structures.
1412  */
1413 void tpm_dev_release(struct device *dev)
1414 {
1415         struct tpm_chip *chip = dev_get_drvdata(dev);
1416
1417         tpm_dev_vendor_release(chip);
1418
1419         chip->release(dev);
1420         kfree(chip);
1421 }
1422 EXPORT_SYMBOL_GPL(tpm_dev_release);
1423
1424 /*
1425  * Called from tpm_<specific>.c probe function only for devices 
1426  * the driver has determined it should claim.  Prior to calling
1427  * this function the specific probe function has called pci_enable_device
1428  * upon errant exit from this function specific probe function should call
1429  * pci_disable_device
1430  */
1431 struct tpm_chip *tpm_register_hardware(struct device *dev,
1432                                         const struct tpm_vendor_specific *entry)
1433 {
1434 #define DEVNAME_SIZE 7
1435
1436         char *devname;
1437         struct tpm_chip *chip;
1438
1439         /* Driver specific per-device data */
1440         chip = kzalloc(sizeof(*chip), GFP_KERNEL);
1441         devname = kmalloc(DEVNAME_SIZE, GFP_KERNEL);
1442
1443         if (chip == NULL || devname == NULL)
1444                 goto out_free;
1445
1446         mutex_init(&chip->buffer_mutex);
1447         mutex_init(&chip->tpm_mutex);
1448         mutex_init(&chip->resume_mutex);
1449         INIT_LIST_HEAD(&chip->list);
1450
1451         INIT_WORK(&chip->work, timeout_work);
1452
1453         setup_timer(&chip->user_read_timer, user_reader_timeout,
1454                         (unsigned long)chip);
1455
1456         memcpy(&chip->vendor, entry, sizeof(struct tpm_vendor_specific));
1457
1458         chip->dev_num = find_first_zero_bit(dev_mask, TPM_NUM_DEVICES);
1459
1460         if (chip->dev_num >= TPM_NUM_DEVICES) {
1461                 dev_err(dev, "No available tpm device numbers\n");
1462                 goto out_free;
1463         } else if (chip->dev_num == 0)
1464                 chip->vendor.miscdev.minor = TPM_MINOR;
1465         else
1466                 chip->vendor.miscdev.minor = MISC_DYNAMIC_MINOR;
1467
1468         set_bit(chip->dev_num, dev_mask);
1469
1470         scnprintf(devname, DEVNAME_SIZE, "%s%d", "tpm", chip->dev_num);
1471         chip->vendor.miscdev.name = devname;
1472
1473         chip->vendor.miscdev.parent = dev;
1474         chip->dev = get_device(dev);
1475         chip->release = dev->release;
1476         dev->release = tpm_dev_release;
1477         dev_set_drvdata(dev, chip);
1478
1479         if (misc_register(&chip->vendor.miscdev)) {
1480                 dev_err(chip->dev,
1481                         "unable to misc_register %s, minor %d\n",
1482                         chip->vendor.miscdev.name,
1483                         chip->vendor.miscdev.minor);
1484                 put_device(chip->dev);
1485                 return NULL;
1486         }
1487
1488         if (sysfs_create_group(&dev->kobj, chip->vendor.attr_group)) {
1489                 misc_deregister(&chip->vendor.miscdev);
1490                 put_device(chip->dev);
1491
1492                 return NULL;
1493         }
1494
1495         chip->bios_dir = tpm_bios_log_setup(devname);
1496
1497         /* Make chip available */
1498         spin_lock(&driver_lock);
1499         list_add_rcu(&chip->list, &tpm_chip_list);
1500         spin_unlock(&driver_lock);
1501
1502         return chip;
1503
1504 out_free:
1505         kfree(chip);
1506         kfree(devname);
1507         return NULL;
1508 }
1509 EXPORT_SYMBOL_GPL(tpm_register_hardware);
1510
1511 MODULE_AUTHOR("Leendert van Doorn (leendert@watson.ibm.com)");
1512 MODULE_DESCRIPTION("TPM Driver");
1513 MODULE_VERSION("2.0");
1514 MODULE_LICENSE("GPL");