xref: /linux/drivers/char/tpm/tpm-interface.c (revision 0e0546eabcd6c19765a8dbf5b5db3723e7b0ea75)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2004 IBM Corporation
4  * Copyright (C) 2014 Intel Corporation
5  *
6  * Authors:
7  * Leendert van Doorn <leendert@watson.ibm.com>
8  * Dave Safford <safford@watson.ibm.com>
9  * Reiner Sailer <sailer@watson.ibm.com>
10  * Kylene Hall <kjhall@us.ibm.com>
11  *
12  * Maintained by: <tpmdd-devel@lists.sourceforge.net>
13  *
14  * Device driver for TCG/TCPA TPM (trusted platform module).
15  * Specifications at www.trustedcomputinggroup.org
16  *
17  * Note, the TPM chip is not interrupt driven (only polling)
18  * and can have very long timeouts (minutes!). Hence the unusual
19  * calls to msleep.
20  */
21 
22 #include <linux/poll.h>
23 #include <linux/slab.h>
24 #include <linux/mutex.h>
25 #include <linux/spinlock.h>
26 #include <linux/suspend.h>
27 #include <linux/freezer.h>
28 #include <linux/tpm_eventlog.h>
29 
30 #include "tpm.h"
31 
32 /*
33  * Bug workaround - some TPM's don't flush the most
34  * recently changed pcr on suspend, so force the flush
35  * with an extend to the selected _unused_ non-volatile pcr.
36  */
37 static u32 tpm_suspend_pcr;
38 module_param_named(suspend_pcr, tpm_suspend_pcr, uint, 0644);
39 MODULE_PARM_DESC(suspend_pcr,
40 		 "PCR to use for dummy writes to facilitate flush on suspend.");
41 
42 /**
43  * tpm_calc_ordinal_duration() - calculate the maximum command duration
44  * @chip:    TPM chip to use.
45  * @ordinal: TPM command ordinal.
46  *
47  * The function returns the maximum amount of time the chip could take
48  * to return the result for a particular ordinal in jiffies.
49  *
50  * Return: A maximal duration time for an ordinal in jiffies.
51  */
52 unsigned long tpm_calc_ordinal_duration(struct tpm_chip *chip, u32 ordinal)
53 {
54 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
55 		return tpm2_calc_ordinal_duration(chip, ordinal);
56 	else
57 		return tpm1_calc_ordinal_duration(chip, ordinal);
58 }
59 EXPORT_SYMBOL_GPL(tpm_calc_ordinal_duration);
60 
61 static void tpm_chip_cancel(struct tpm_chip *chip)
62 {
63 	if (!chip->ops->cancel)
64 		return;
65 
66 	chip->ops->cancel(chip);
67 }
68 
69 static u8 tpm_chip_status(struct tpm_chip *chip)
70 {
71 	if (!chip->ops->status)
72 		return 0;
73 
74 	return chip->ops->status(chip);
75 }
76 
77 static bool tpm_chip_req_canceled(struct tpm_chip *chip, u8 status)
78 {
79 	if (!chip->ops->req_canceled)
80 		return false;
81 
82 	return chip->ops->req_canceled(chip, status);
83 }
84 
85 static ssize_t tpm_try_transmit(struct tpm_chip *chip, void *buf, size_t bufsiz)
86 {
87 	struct tpm_header *header = buf;
88 	int rc;
89 	ssize_t len = 0;
90 	u32 count, ordinal;
91 	unsigned long stop;
92 
93 	if (bufsiz < TPM_HEADER_SIZE)
94 		return -EINVAL;
95 
96 	if (bufsiz > TPM_BUFSIZE)
97 		bufsiz = TPM_BUFSIZE;
98 
99 	count = be32_to_cpu(header->length);
100 	ordinal = be32_to_cpu(header->ordinal);
101 	if (count == 0)
102 		return -ENODATA;
103 	if (count > bufsiz) {
104 		dev_err(&chip->dev,
105 			"invalid count value %x %zx\n", count, bufsiz);
106 		return -E2BIG;
107 	}
108 
109 	rc = chip->ops->send(chip, buf, bufsiz, count);
110 	if (rc < 0) {
111 		if (rc != -EPIPE)
112 			dev_err(&chip->dev,
113 				"%s: send(): error %d\n", __func__, rc);
114 		return rc;
115 	}
116 
117 	/*
118 	 * Synchronous devices return the response directly during the send()
119 	 * call in the same buffer.
120 	 */
121 	if (chip->flags & TPM_CHIP_FLAG_SYNC) {
122 		len = rc;
123 		rc = 0;
124 		goto out_sync;
125 	}
126 
127 	/*
128 	 * A sanity check. send() of asynchronous devices should just return
129 	 * zero on success e.g. not the command length.
130 	 */
131 	if (rc > 0) {
132 		dev_warn(&chip->dev,
133 			 "%s: send(): invalid value %d\n", __func__, rc);
134 		rc = 0;
135 	}
136 
137 	if (chip->flags & TPM_CHIP_FLAG_IRQ)
138 		goto out_recv;
139 
140 	stop = jiffies + tpm_calc_ordinal_duration(chip, ordinal);
141 	do {
142 		u8 status = tpm_chip_status(chip);
143 		if ((status & chip->ops->req_complete_mask) ==
144 		    chip->ops->req_complete_val)
145 			goto out_recv;
146 
147 		if (tpm_chip_req_canceled(chip, status)) {
148 			dev_err(&chip->dev, "Operation Canceled\n");
149 			return -ECANCELED;
150 		}
151 
152 		tpm_msleep(TPM_TIMEOUT_POLL);
153 		rmb();
154 	} while (time_before(jiffies, stop));
155 
156 	tpm_chip_cancel(chip);
157 	dev_err(&chip->dev, "Operation Timed out\n");
158 	return -ETIME;
159 
160 out_recv:
161 	len = chip->ops->recv(chip, buf, bufsiz);
162 	if (len < 0) {
163 		rc = len;
164 		dev_err(&chip->dev, "tpm_transmit: tpm_recv: error %d\n", rc);
165 		return rc;
166 	}
167 out_sync:
168 	if (len < TPM_HEADER_SIZE || len != be32_to_cpu(header->length))
169 		rc = -EFAULT;
170 
171 	return rc ? rc : len;
172 }
173 
174 /**
175  * tpm_transmit - Internal kernel interface to transmit TPM commands.
176  * @chip:	a TPM chip to use
177  * @buf:	a TPM command buffer
178  * @bufsiz:	length of the TPM command buffer
179  *
180  * A wrapper around tpm_try_transmit() that handles TPM2_RC_RETRY returns from
181  * the TPM and retransmits the command after a delay up to a maximum wait of
182  * TPM2_DURATION_LONG.
183  *
184  * Note that TPM 1.x never returns TPM2_RC_RETRY so the retry logic is TPM 2.0
185  * only.
186  *
187  * Return:
188  * * The response length	- OK
189  * * -errno			- A system error
190  */
191 ssize_t tpm_transmit(struct tpm_chip *chip, u8 *buf, size_t bufsiz)
192 {
193 	struct tpm_header *header = (struct tpm_header *)buf;
194 	/* space for header and handles */
195 	u8 save[TPM_HEADER_SIZE + 3*sizeof(u32)];
196 	unsigned int delay_msec = TPM2_DURATION_SHORT;
197 	u32 rc = 0;
198 	ssize_t ret;
199 	const size_t save_size = min(sizeof(save), bufsiz);
200 	/* the command code is where the return code will be */
201 	u32 cc = be32_to_cpu(header->return_code);
202 
203 	/*
204 	 * Subtlety here: if we have a space, the handles will be
205 	 * transformed, so when we restore the header we also have to
206 	 * restore the handles.
207 	 */
208 	memcpy(save, buf, save_size);
209 
210 	for (;;) {
211 		ret = tpm_try_transmit(chip, buf, bufsiz);
212 		if (ret < 0)
213 			break;
214 		rc = be32_to_cpu(header->return_code);
215 		if (rc != TPM2_RC_RETRY && rc != TPM2_RC_TESTING)
216 			break;
217 		/*
218 		 * return immediately if self test returns test
219 		 * still running to shorten boot time.
220 		 */
221 		if (rc == TPM2_RC_TESTING && cc == TPM2_CC_SELF_TEST)
222 			break;
223 
224 		if (delay_msec > TPM2_DURATION_LONG) {
225 			if (rc == TPM2_RC_RETRY)
226 				dev_err(&chip->dev, "in retry loop\n");
227 			else
228 				dev_err(&chip->dev,
229 					"self test is still running\n");
230 			break;
231 		}
232 		tpm_msleep(delay_msec);
233 		delay_msec *= 2;
234 		memcpy(buf, save, save_size);
235 	}
236 	return ret;
237 }
238 
239 /**
240  * tpm_transmit_cmd - send a tpm command to the device
241  * @chip:			a TPM chip to use
242  * @buf:			a TPM command buffer
243  * @min_rsp_body_length:	minimum expected length of response body
244  * @desc:			command description used in the error message
245  *
246  * Return:
247  * * 0		- OK
248  * * -errno	- A system error
249  * * TPM_RC	- A TPM error
250  */
251 ssize_t tpm_transmit_cmd(struct tpm_chip *chip, struct tpm_buf *buf,
252 			 size_t min_rsp_body_length, const char *desc)
253 {
254 	const struct tpm_header *header = (struct tpm_header *)buf->data;
255 	int err;
256 	ssize_t len;
257 
258 	len = tpm_transmit(chip, buf->data, PAGE_SIZE);
259 	if (len <  0)
260 		return len;
261 
262 	err = be32_to_cpu(header->return_code);
263 	if (err != 0 && err != TPM_ERR_DISABLED && err != TPM_ERR_DEACTIVATED
264 	    && err != TPM2_RC_TESTING && desc)
265 		dev_err(&chip->dev, "A TPM error (%d) occurred %s\n", err,
266 			desc);
267 	if (err)
268 		return err;
269 
270 	if (len < min_rsp_body_length + TPM_HEADER_SIZE)
271 		return -EFAULT;
272 
273 	buf->length = len;
274 	return 0;
275 }
276 EXPORT_SYMBOL_GPL(tpm_transmit_cmd);
277 
278 int tpm_get_timeouts(struct tpm_chip *chip)
279 {
280 	if (chip->flags & TPM_CHIP_FLAG_HAVE_TIMEOUTS)
281 		return 0;
282 
283 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
284 		return tpm2_get_timeouts(chip);
285 	else
286 		return tpm1_get_timeouts(chip);
287 }
288 EXPORT_SYMBOL_GPL(tpm_get_timeouts);
289 
290 /**
291  * tpm_is_tpm2 - do we a have a TPM2 chip?
292  * @chip:	a &struct tpm_chip instance, %NULL for the default chip
293  *
294  * Return:
295  * 1 if we have a TPM2 chip.
296  * 0 if we don't have a TPM2 chip.
297  * A negative number for system errors (errno).
298  */
299 int tpm_is_tpm2(struct tpm_chip *chip)
300 {
301 	int rc;
302 
303 	chip = tpm_find_get_ops(chip);
304 	if (!chip)
305 		return -ENODEV;
306 
307 	rc = (chip->flags & TPM_CHIP_FLAG_TPM2) != 0;
308 
309 	tpm_put_ops(chip);
310 
311 	return rc;
312 }
313 EXPORT_SYMBOL_GPL(tpm_is_tpm2);
314 
315 /**
316  * tpm_pcr_read - read a PCR value from SHA1 bank
317  * @chip:	a &struct tpm_chip instance, %NULL for the default chip
318  * @pcr_idx:	the PCR to be retrieved
319  * @digest:	the PCR bank and buffer current PCR value is written to
320  *
321  * Return: same as with tpm_transmit_cmd()
322  */
323 int tpm_pcr_read(struct tpm_chip *chip, u32 pcr_idx,
324 		 struct tpm_digest *digest)
325 {
326 	int rc;
327 
328 	chip = tpm_find_get_ops(chip);
329 	if (!chip)
330 		return -ENODEV;
331 
332 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
333 		rc = tpm2_pcr_read(chip, pcr_idx, digest, NULL);
334 	else
335 		rc = tpm1_pcr_read(chip, pcr_idx, digest->digest);
336 
337 	tpm_put_ops(chip);
338 	return rc;
339 }
340 EXPORT_SYMBOL_GPL(tpm_pcr_read);
341 
342 /**
343  * tpm_pcr_extend - extend a PCR value in SHA1 bank.
344  * @chip:	a &struct tpm_chip instance, %NULL for the default chip
345  * @pcr_idx:	the PCR to be retrieved
346  * @digests:	array of tpm_digest structures used to extend PCRs
347  *
348  * Note: callers must pass a digest for every allocated PCR bank, in the same
349  * order of the banks in chip->allocated_banks.
350  *
351  * Return: same as with tpm_transmit_cmd()
352  */
353 int tpm_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
354 		   struct tpm_digest *digests)
355 {
356 	int rc;
357 	int i;
358 
359 	chip = tpm_find_get_ops(chip);
360 	if (!chip)
361 		return -ENODEV;
362 
363 	for (i = 0; i < chip->nr_allocated_banks; i++) {
364 		if (digests[i].alg_id != chip->allocated_banks[i].alg_id) {
365 			rc = -EINVAL;
366 			goto out;
367 		}
368 	}
369 
370 	if (chip->flags & TPM_CHIP_FLAG_TPM2) {
371 		rc = tpm2_pcr_extend(chip, pcr_idx, digests);
372 		goto out;
373 	}
374 
375 	rc = tpm1_pcr_extend(chip, pcr_idx, digests[0].digest,
376 			     "attempting extend a PCR value");
377 
378 out:
379 	tpm_put_ops(chip);
380 	return rc;
381 }
382 EXPORT_SYMBOL_GPL(tpm_pcr_extend);
383 
384 int tpm_auto_startup(struct tpm_chip *chip)
385 {
386 	int rc;
387 
388 	if (!(chip->ops->flags & TPM_OPS_AUTO_STARTUP))
389 		return 0;
390 
391 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
392 		rc = tpm2_auto_startup(chip);
393 	else
394 		rc = tpm1_auto_startup(chip);
395 
396 	return rc;
397 }
398 
399 /*
400  * We are about to suspend. Save the TPM state
401  * so that it can be restored.
402  */
403 int tpm_pm_suspend(struct device *dev)
404 {
405 	struct tpm_chip *chip = dev_get_drvdata(dev);
406 	int rc = 0;
407 
408 	if (!chip)
409 		return -ENODEV;
410 
411 	rc = tpm_try_get_ops(chip);
412 	if (rc) {
413 		/* Can be safely set out of locks, as no action cannot race: */
414 		chip->flags |= TPM_CHIP_FLAG_SUSPENDED;
415 		goto out;
416 	}
417 
418 	if (chip->flags & TPM_CHIP_FLAG_ALWAYS_POWERED)
419 		goto suspended;
420 
421 	if ((chip->flags & TPM_CHIP_FLAG_FIRMWARE_POWER_MANAGED) &&
422 	    !pm_suspend_via_firmware())
423 		goto suspended;
424 
425 	if (chip->flags & TPM_CHIP_FLAG_TPM2) {
426 		tpm2_end_auth_session(chip);
427 		tpm2_shutdown(chip, TPM2_SU_STATE);
428 		goto suspended;
429 	}
430 
431 	rc = tpm1_pm_suspend(chip, tpm_suspend_pcr);
432 
433 suspended:
434 	chip->flags |= TPM_CHIP_FLAG_SUSPENDED;
435 	tpm_put_ops(chip);
436 
437 out:
438 	if (rc)
439 		dev_err(dev, "Ignoring error %d while suspending\n", rc);
440 	return 0;
441 }
442 EXPORT_SYMBOL_GPL(tpm_pm_suspend);
443 
444 /*
445  * Resume from a power safe. The BIOS already restored
446  * the TPM state.
447  */
448 int tpm_pm_resume(struct device *dev)
449 {
450 	struct tpm_chip *chip = dev_get_drvdata(dev);
451 
452 	if (chip == NULL)
453 		return -ENODEV;
454 
455 	chip->flags &= ~TPM_CHIP_FLAG_SUSPENDED;
456 
457 	/*
458 	 * Guarantee that SUSPENDED is written last, so that hwrng does not
459 	 * activate before the chip has been fully resumed.
460 	 */
461 	wmb();
462 
463 	return 0;
464 }
465 EXPORT_SYMBOL_GPL(tpm_pm_resume);
466 
467 /**
468  * tpm_get_random() - get random bytes from the TPM's RNG
469  * @chip:	a &struct tpm_chip instance, %NULL for the default chip
470  * @out:	destination buffer for the random bytes
471  * @max:	the max number of bytes to write to @out
472  *
473  * Return: number of random bytes read or a negative error value.
474  */
475 int tpm_get_random(struct tpm_chip *chip, u8 *out, size_t max)
476 {
477 	int rc;
478 
479 	if (!out || max > TPM_MAX_RNG_DATA)
480 		return -EINVAL;
481 
482 	chip = tpm_find_get_ops(chip);
483 	if (!chip)
484 		return -ENODEV;
485 
486 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
487 		rc = tpm2_get_random(chip, out, max);
488 	else
489 		rc = tpm1_get_random(chip, out, max);
490 
491 	tpm_put_ops(chip);
492 	return rc;
493 }
494 EXPORT_SYMBOL_GPL(tpm_get_random);
495 
496 static int __init tpm_init(void)
497 {
498 	int rc;
499 
500 	rc = class_register(&tpm_class);
501 	if (rc) {
502 		pr_err("couldn't create tpm class\n");
503 		return rc;
504 	}
505 
506 	rc = class_register(&tpmrm_class);
507 	if (rc) {
508 		pr_err("couldn't create tpmrm class\n");
509 		goto out_destroy_tpm_class;
510 	}
511 
512 	rc = alloc_chrdev_region(&tpm_devt, 0, 2*TPM_NUM_DEVICES, "tpm");
513 	if (rc < 0) {
514 		pr_err("tpm: failed to allocate char dev region\n");
515 		goto out_destroy_tpmrm_class;
516 	}
517 
518 	rc = tpm_dev_common_init();
519 	if (rc) {
520 		pr_err("tpm: failed to allocate char dev region\n");
521 		goto out_unreg_chrdev;
522 	}
523 
524 	return 0;
525 
526 out_unreg_chrdev:
527 	unregister_chrdev_region(tpm_devt, 2 * TPM_NUM_DEVICES);
528 out_destroy_tpmrm_class:
529 	class_unregister(&tpmrm_class);
530 out_destroy_tpm_class:
531 	class_unregister(&tpm_class);
532 
533 	return rc;
534 }
535 
536 static void __exit tpm_exit(void)
537 {
538 	idr_destroy(&dev_nums_idr);
539 	class_unregister(&tpm_class);
540 	class_unregister(&tpmrm_class);
541 	unregister_chrdev_region(tpm_devt, 2*TPM_NUM_DEVICES);
542 	tpm_dev_common_exit();
543 }
544 
545 subsys_initcall(tpm_init);
546 module_exit(tpm_exit);
547 
548 MODULE_AUTHOR("Leendert van Doorn <leendert@watson.ibm.com>");
549 MODULE_DESCRIPTION("TPM Driver");
550 MODULE_VERSION("2.0");
551 MODULE_LICENSE("GPL");
552