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  */
tpm_calc_ordinal_duration(struct tpm_chip * chip,u32 ordinal)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 
tpm_chip_cancel(struct tpm_chip * chip)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 
tpm_chip_status(struct tpm_chip * chip)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 
tpm_chip_req_canceled(struct tpm_chip * chip,u8 status)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 
tpm_try_transmit(struct tpm_chip * chip,void * buf,size_t bufsiz)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, 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 	/* A sanity check. send() should just return zero on success e.g.
118 	 * not the command length.
119 	 */
120 	if (rc > 0) {
121 		dev_warn(&chip->dev,
122 			 "%s: send(): invalid value %d\n", __func__, rc);
123 		rc = 0;
124 	}
125 
126 	if (chip->flags & TPM_CHIP_FLAG_IRQ)
127 		goto out_recv;
128 
129 	stop = jiffies + tpm_calc_ordinal_duration(chip, ordinal);
130 	do {
131 		u8 status = tpm_chip_status(chip);
132 		if ((status & chip->ops->req_complete_mask) ==
133 		    chip->ops->req_complete_val)
134 			goto out_recv;
135 
136 		if (tpm_chip_req_canceled(chip, status)) {
137 			dev_err(&chip->dev, "Operation Canceled\n");
138 			return -ECANCELED;
139 		}
140 
141 		tpm_msleep(TPM_TIMEOUT_POLL);
142 		rmb();
143 	} while (time_before(jiffies, stop));
144 
145 	tpm_chip_cancel(chip);
146 	dev_err(&chip->dev, "Operation Timed out\n");
147 	return -ETIME;
148 
149 out_recv:
150 	len = chip->ops->recv(chip, buf, bufsiz);
151 	if (len < 0) {
152 		rc = len;
153 		dev_err(&chip->dev, "tpm_transmit: tpm_recv: error %d\n", rc);
154 	} else if (len < TPM_HEADER_SIZE || len != be32_to_cpu(header->length))
155 		rc = -EFAULT;
156 
157 	return rc ? rc : len;
158 }
159 
160 /**
161  * tpm_transmit - Internal kernel interface to transmit TPM commands.
162  * @chip:	a TPM chip to use
163  * @buf:	a TPM command buffer
164  * @bufsiz:	length of the TPM command buffer
165  *
166  * A wrapper around tpm_try_transmit() that handles TPM2_RC_RETRY returns from
167  * the TPM and retransmits the command after a delay up to a maximum wait of
168  * TPM2_DURATION_LONG.
169  *
170  * Note that TPM 1.x never returns TPM2_RC_RETRY so the retry logic is TPM 2.0
171  * only.
172  *
173  * Return:
174  * * The response length	- OK
175  * * -errno			- A system error
176  */
tpm_transmit(struct tpm_chip * chip,u8 * buf,size_t bufsiz)177 ssize_t tpm_transmit(struct tpm_chip *chip, u8 *buf, size_t bufsiz)
178 {
179 	struct tpm_header *header = (struct tpm_header *)buf;
180 	/* space for header and handles */
181 	u8 save[TPM_HEADER_SIZE + 3*sizeof(u32)];
182 	unsigned int delay_msec = TPM2_DURATION_SHORT;
183 	u32 rc = 0;
184 	ssize_t ret;
185 	const size_t save_size = min(sizeof(save), bufsiz);
186 	/* the command code is where the return code will be */
187 	u32 cc = be32_to_cpu(header->return_code);
188 
189 	/*
190 	 * Subtlety here: if we have a space, the handles will be
191 	 * transformed, so when we restore the header we also have to
192 	 * restore the handles.
193 	 */
194 	memcpy(save, buf, save_size);
195 
196 	for (;;) {
197 		ret = tpm_try_transmit(chip, buf, bufsiz);
198 		if (ret < 0)
199 			break;
200 		rc = be32_to_cpu(header->return_code);
201 		if (rc != TPM2_RC_RETRY && rc != TPM2_RC_TESTING)
202 			break;
203 		/*
204 		 * return immediately if self test returns test
205 		 * still running to shorten boot time.
206 		 */
207 		if (rc == TPM2_RC_TESTING && cc == TPM2_CC_SELF_TEST)
208 			break;
209 
210 		if (delay_msec > TPM2_DURATION_LONG) {
211 			if (rc == TPM2_RC_RETRY)
212 				dev_err(&chip->dev, "in retry loop\n");
213 			else
214 				dev_err(&chip->dev,
215 					"self test is still running\n");
216 			break;
217 		}
218 		tpm_msleep(delay_msec);
219 		delay_msec *= 2;
220 		memcpy(buf, save, save_size);
221 	}
222 	return ret;
223 }
224 
225 /**
226  * tpm_transmit_cmd - send a tpm command to the device
227  * @chip:			a TPM chip to use
228  * @buf:			a TPM command buffer
229  * @min_rsp_body_length:	minimum expected length of response body
230  * @desc:			command description used in the error message
231  *
232  * Return:
233  * * 0		- OK
234  * * -errno	- A system error
235  * * TPM_RC	- A TPM error
236  */
tpm_transmit_cmd(struct tpm_chip * chip,struct tpm_buf * buf,size_t min_rsp_body_length,const char * desc)237 ssize_t tpm_transmit_cmd(struct tpm_chip *chip, struct tpm_buf *buf,
238 			 size_t min_rsp_body_length, const char *desc)
239 {
240 	const struct tpm_header *header = (struct tpm_header *)buf->data;
241 	int err;
242 	ssize_t len;
243 
244 	len = tpm_transmit(chip, buf->data, PAGE_SIZE);
245 	if (len <  0)
246 		return len;
247 
248 	err = be32_to_cpu(header->return_code);
249 	if (err != 0 && err != TPM_ERR_DISABLED && err != TPM_ERR_DEACTIVATED
250 	    && err != TPM2_RC_TESTING && desc)
251 		dev_err(&chip->dev, "A TPM error (%d) occurred %s\n", err,
252 			desc);
253 	if (err)
254 		return err;
255 
256 	if (len < min_rsp_body_length + TPM_HEADER_SIZE)
257 		return -EFAULT;
258 
259 	buf->length = len;
260 	return 0;
261 }
262 EXPORT_SYMBOL_GPL(tpm_transmit_cmd);
263 
tpm_get_timeouts(struct tpm_chip * chip)264 int tpm_get_timeouts(struct tpm_chip *chip)
265 {
266 	if (chip->flags & TPM_CHIP_FLAG_HAVE_TIMEOUTS)
267 		return 0;
268 
269 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
270 		return tpm2_get_timeouts(chip);
271 	else
272 		return tpm1_get_timeouts(chip);
273 }
274 EXPORT_SYMBOL_GPL(tpm_get_timeouts);
275 
276 /**
277  * tpm_is_tpm2 - do we a have a TPM2 chip?
278  * @chip:	a &struct tpm_chip instance, %NULL for the default chip
279  *
280  * Return:
281  * 1 if we have a TPM2 chip.
282  * 0 if we don't have a TPM2 chip.
283  * A negative number for system errors (errno).
284  */
tpm_is_tpm2(struct tpm_chip * chip)285 int tpm_is_tpm2(struct tpm_chip *chip)
286 {
287 	int rc;
288 
289 	chip = tpm_find_get_ops(chip);
290 	if (!chip)
291 		return -ENODEV;
292 
293 	rc = (chip->flags & TPM_CHIP_FLAG_TPM2) != 0;
294 
295 	tpm_put_ops(chip);
296 
297 	return rc;
298 }
299 EXPORT_SYMBOL_GPL(tpm_is_tpm2);
300 
301 /**
302  * tpm_pcr_read - read a PCR value from SHA1 bank
303  * @chip:	a &struct tpm_chip instance, %NULL for the default chip
304  * @pcr_idx:	the PCR to be retrieved
305  * @digest:	the PCR bank and buffer current PCR value is written to
306  *
307  * Return: same as with tpm_transmit_cmd()
308  */
tpm_pcr_read(struct tpm_chip * chip,u32 pcr_idx,struct tpm_digest * digest)309 int tpm_pcr_read(struct tpm_chip *chip, u32 pcr_idx,
310 		 struct tpm_digest *digest)
311 {
312 	int rc;
313 
314 	chip = tpm_find_get_ops(chip);
315 	if (!chip)
316 		return -ENODEV;
317 
318 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
319 		rc = tpm2_pcr_read(chip, pcr_idx, digest, NULL);
320 	else
321 		rc = tpm1_pcr_read(chip, pcr_idx, digest->digest);
322 
323 	tpm_put_ops(chip);
324 	return rc;
325 }
326 EXPORT_SYMBOL_GPL(tpm_pcr_read);
327 
328 /**
329  * tpm_pcr_extend - extend a PCR value in SHA1 bank.
330  * @chip:	a &struct tpm_chip instance, %NULL for the default chip
331  * @pcr_idx:	the PCR to be retrieved
332  * @digests:	array of tpm_digest structures used to extend PCRs
333  *
334  * Note: callers must pass a digest for every allocated PCR bank, in the same
335  * order of the banks in chip->allocated_banks.
336  *
337  * Return: same as with tpm_transmit_cmd()
338  */
tpm_pcr_extend(struct tpm_chip * chip,u32 pcr_idx,struct tpm_digest * digests)339 int tpm_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
340 		   struct tpm_digest *digests)
341 {
342 	int rc;
343 	int i;
344 
345 	chip = tpm_find_get_ops(chip);
346 	if (!chip)
347 		return -ENODEV;
348 
349 	for (i = 0; i < chip->nr_allocated_banks; i++) {
350 		if (digests[i].alg_id != chip->allocated_banks[i].alg_id) {
351 			rc = -EINVAL;
352 			goto out;
353 		}
354 	}
355 
356 	if (chip->flags & TPM_CHIP_FLAG_TPM2) {
357 		rc = tpm2_pcr_extend(chip, pcr_idx, digests);
358 		goto out;
359 	}
360 
361 	rc = tpm1_pcr_extend(chip, pcr_idx, digests[0].digest,
362 			     "attempting extend a PCR value");
363 
364 out:
365 	tpm_put_ops(chip);
366 	return rc;
367 }
368 EXPORT_SYMBOL_GPL(tpm_pcr_extend);
369 
tpm_auto_startup(struct tpm_chip * chip)370 int tpm_auto_startup(struct tpm_chip *chip)
371 {
372 	int rc;
373 
374 	if (!(chip->ops->flags & TPM_OPS_AUTO_STARTUP))
375 		return 0;
376 
377 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
378 		rc = tpm2_auto_startup(chip);
379 	else
380 		rc = tpm1_auto_startup(chip);
381 
382 	return rc;
383 }
384 
385 /*
386  * We are about to suspend. Save the TPM state
387  * so that it can be restored.
388  */
tpm_pm_suspend(struct device * dev)389 int tpm_pm_suspend(struct device *dev)
390 {
391 	struct tpm_chip *chip = dev_get_drvdata(dev);
392 	int rc = 0;
393 
394 	if (!chip)
395 		return -ENODEV;
396 
397 	rc = tpm_try_get_ops(chip);
398 	if (rc) {
399 		/* Can be safely set out of locks, as no action cannot race: */
400 		chip->flags |= TPM_CHIP_FLAG_SUSPENDED;
401 		goto out;
402 	}
403 
404 	if (chip->flags & TPM_CHIP_FLAG_ALWAYS_POWERED)
405 		goto suspended;
406 
407 	if ((chip->flags & TPM_CHIP_FLAG_FIRMWARE_POWER_MANAGED) &&
408 	    !pm_suspend_via_firmware())
409 		goto suspended;
410 
411 	if (chip->flags & TPM_CHIP_FLAG_TPM2) {
412 		tpm2_end_auth_session(chip);
413 		tpm2_shutdown(chip, TPM2_SU_STATE);
414 		goto suspended;
415 	}
416 
417 	rc = tpm1_pm_suspend(chip, tpm_suspend_pcr);
418 
419 suspended:
420 	chip->flags |= TPM_CHIP_FLAG_SUSPENDED;
421 	tpm_put_ops(chip);
422 
423 out:
424 	if (rc)
425 		dev_err(dev, "Ignoring error %d while suspending\n", rc);
426 	return 0;
427 }
428 EXPORT_SYMBOL_GPL(tpm_pm_suspend);
429 
430 /*
431  * Resume from a power safe. The BIOS already restored
432  * the TPM state.
433  */
tpm_pm_resume(struct device * dev)434 int tpm_pm_resume(struct device *dev)
435 {
436 	struct tpm_chip *chip = dev_get_drvdata(dev);
437 
438 	if (chip == NULL)
439 		return -ENODEV;
440 
441 	chip->flags &= ~TPM_CHIP_FLAG_SUSPENDED;
442 
443 	/*
444 	 * Guarantee that SUSPENDED is written last, so that hwrng does not
445 	 * activate before the chip has been fully resumed.
446 	 */
447 	wmb();
448 
449 	return 0;
450 }
451 EXPORT_SYMBOL_GPL(tpm_pm_resume);
452 
453 /**
454  * tpm_get_random() - get random bytes from the TPM's RNG
455  * @chip:	a &struct tpm_chip instance, %NULL for the default chip
456  * @out:	destination buffer for the random bytes
457  * @max:	the max number of bytes to write to @out
458  *
459  * Return: number of random bytes read or a negative error value.
460  */
tpm_get_random(struct tpm_chip * chip,u8 * out,size_t max)461 int tpm_get_random(struct tpm_chip *chip, u8 *out, size_t max)
462 {
463 	int rc;
464 
465 	if (!out || max > TPM_MAX_RNG_DATA)
466 		return -EINVAL;
467 
468 	chip = tpm_find_get_ops(chip);
469 	if (!chip)
470 		return -ENODEV;
471 
472 	if (chip->flags & TPM_CHIP_FLAG_TPM2)
473 		rc = tpm2_get_random(chip, out, max);
474 	else
475 		rc = tpm1_get_random(chip, out, max);
476 
477 	tpm_put_ops(chip);
478 	return rc;
479 }
480 EXPORT_SYMBOL_GPL(tpm_get_random);
481 
tpm_init(void)482 static int __init tpm_init(void)
483 {
484 	int rc;
485 
486 	rc = class_register(&tpm_class);
487 	if (rc) {
488 		pr_err("couldn't create tpm class\n");
489 		return rc;
490 	}
491 
492 	rc = class_register(&tpmrm_class);
493 	if (rc) {
494 		pr_err("couldn't create tpmrm class\n");
495 		goto out_destroy_tpm_class;
496 	}
497 
498 	rc = alloc_chrdev_region(&tpm_devt, 0, 2*TPM_NUM_DEVICES, "tpm");
499 	if (rc < 0) {
500 		pr_err("tpm: failed to allocate char dev region\n");
501 		goto out_destroy_tpmrm_class;
502 	}
503 
504 	rc = tpm_dev_common_init();
505 	if (rc) {
506 		pr_err("tpm: failed to allocate char dev region\n");
507 		goto out_unreg_chrdev;
508 	}
509 
510 	return 0;
511 
512 out_unreg_chrdev:
513 	unregister_chrdev_region(tpm_devt, 2 * TPM_NUM_DEVICES);
514 out_destroy_tpmrm_class:
515 	class_unregister(&tpmrm_class);
516 out_destroy_tpm_class:
517 	class_unregister(&tpm_class);
518 
519 	return rc;
520 }
521 
tpm_exit(void)522 static void __exit tpm_exit(void)
523 {
524 	idr_destroy(&dev_nums_idr);
525 	class_unregister(&tpm_class);
526 	class_unregister(&tpmrm_class);
527 	unregister_chrdev_region(tpm_devt, 2*TPM_NUM_DEVICES);
528 	tpm_dev_common_exit();
529 }
530 
531 subsys_initcall(tpm_init);
532 module_exit(tpm_exit);
533 
534 MODULE_AUTHOR("Leendert van Doorn <leendert@watson.ibm.com>");
535 MODULE_DESCRIPTION("TPM Driver");
536 MODULE_VERSION("2.0");
537 MODULE_LICENSE("GPL");
538