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