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