xref: /linux/drivers/char/tpm/tpm2-cmd.c (revision 3a2c4d55e32ad65efebdb6de44eef3bfa08bb49d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2014, 2015 Intel Corporation
4  *
5  * Authors:
6  * Jarkko Sakkinen <jarkko.sakkinen@linux.intel.com>
7  *
8  * Maintained by: <tpmdd-devel@lists.sourceforge.net>
9  *
10  * This file contains TPM2 protocol implementations of the commands
11  * used by the kernel internally.
12  */
13 
14 #include "linux/dev_printk.h"
15 #include "linux/tpm.h"
16 #include "tpm.h"
17 #include <crypto/hash_info.h>
18 #include <linux/unaligned.h>
19 
20 static bool disable_pcr_integrity;
21 module_param(disable_pcr_integrity, bool, 0444);
22 MODULE_PARM_DESC(disable_pcr_integrity, "Disable integrity protection of TPM2_PCR_Extend");
23 
24 static const struct tpm2_hash tpm2_hash_map[] = {
25 	{HASH_ALGO_SHA1, TPM_ALG_SHA1},
26 	{HASH_ALGO_SHA256, TPM_ALG_SHA256},
27 	{HASH_ALGO_SHA384, TPM_ALG_SHA384},
28 	{HASH_ALGO_SHA512, TPM_ALG_SHA512},
29 	{HASH_ALGO_SM3_256, TPM_ALG_SM3_256},
30 };
31 
32 int tpm2_find_hash_alg(unsigned int crypto_id)
33 {
34 	int i;
35 
36 	for (i = 0; i < ARRAY_SIZE(tpm2_hash_map); i++)
37 		if (crypto_id == tpm2_hash_map[i].crypto_id)
38 			return tpm2_hash_map[i].tpm_id;
39 
40 	return -EINVAL;
41 }
42 EXPORT_SYMBOL_GPL(tpm2_find_hash_alg);
43 
44 int tpm2_get_timeouts(struct tpm_chip *chip)
45 {
46 	chip->timeout_a = msecs_to_jiffies(TPM2_TIMEOUT_A);
47 	chip->timeout_b = msecs_to_jiffies(TPM2_TIMEOUT_B);
48 	chip->timeout_c = msecs_to_jiffies(TPM2_TIMEOUT_C);
49 	chip->timeout_d = msecs_to_jiffies(TPM2_TIMEOUT_D);
50 	chip->flags |= TPM_CHIP_FLAG_HAVE_TIMEOUTS;
51 	return 0;
52 }
53 
54 /*
55  * Contains the maximum durations in milliseconds for TPM2 commands.
56  */
57 static const struct {
58 	unsigned long ordinal;
59 	unsigned long duration;
60 } tpm2_ordinal_duration_map[] = {
61 	{TPM2_CC_STARTUP, 750},
62 	{TPM2_CC_SELF_TEST, 3000},
63 	{TPM2_CC_GET_RANDOM, 2000},
64 	{TPM2_CC_SEQUENCE_UPDATE, 750},
65 	{TPM2_CC_SEQUENCE_COMPLETE, 750},
66 	{TPM2_CC_EVENT_SEQUENCE_COMPLETE, 750},
67 	{TPM2_CC_HASH_SEQUENCE_START, 750},
68 	{TPM2_CC_VERIFY_SIGNATURE, 30000},
69 	{TPM2_CC_PCR_EXTEND, 750},
70 	{TPM2_CC_HIERARCHY_CONTROL, 2000},
71 	{TPM2_CC_HIERARCHY_CHANGE_AUTH, 2000},
72 	{TPM2_CC_GET_CAPABILITY, 750},
73 	{TPM2_CC_NV_READ, 2000},
74 	{TPM2_CC_CREATE_PRIMARY, 300000},
75 	{TPM2_CC_CREATE, 300000},
76 	{TPM2_CC_CREATE_LOADED, 300000},
77 };
78 
79 /**
80  * tpm2_calc_ordinal_duration() - Calculate the maximum command duration
81  * @ordinal: TPM command ordinal.
82  *
83  * Returns the maximum amount of time the chip is expected by kernel to
84  * take in jiffies.
85  */
86 unsigned long tpm2_calc_ordinal_duration(u32 ordinal)
87 {
88 	int i;
89 
90 	for (i = 0; i < ARRAY_SIZE(tpm2_ordinal_duration_map); i++)
91 		if (ordinal == tpm2_ordinal_duration_map[i].ordinal)
92 			return msecs_to_jiffies(tpm2_ordinal_duration_map[i].duration);
93 
94 	return msecs_to_jiffies(TPM2_DURATION_DEFAULT);
95 }
96 
97 /**
98  * tpm2_pcr_read() - read a PCR value
99  * @chip:	TPM chip to use.
100  * @pcr_idx:	index of the PCR to read.
101  * @digest:	PCR bank and buffer current PCR value is written to.
102  * @digest_size_ptr:	pointer to variable that stores the digest size.
103  *
104  * Return: Same as with tpm_transmit_cmd.
105  */
106 int tpm2_pcr_read(struct tpm_chip *chip, u32 pcr_idx,
107 		  struct tpm_digest *digest, u16 *digest_size_ptr)
108 {
109 	int i;
110 	int rc;
111 	struct tpm2_pcr_read_out *out;
112 	u8 pcr_select[TPM2_PCR_SELECT_MIN] = {0};
113 	u16 digest_size;
114 	u16 expected_digest_size = 0;
115 
116 	struct tpm_buf *buf __free(kfree) = NULL;
117 
118 	if (pcr_idx >= TPM2_PLATFORM_PCR)
119 		return -EINVAL;
120 
121 	if (!digest_size_ptr) {
122 		for (i = 0; i < chip->nr_allocated_banks &&
123 		     chip->allocated_banks[i].alg_id != digest->alg_id; i++)
124 			;
125 
126 		if (i == chip->nr_allocated_banks)
127 			return -EINVAL;
128 
129 		expected_digest_size = chip->allocated_banks[i].digest_size;
130 	}
131 
132 	buf = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
133 	if (!buf)
134 		return -ENOMEM;
135 
136 	tpm_buf_init(buf, TPM_BUFSIZE);
137 	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_PCR_READ);
138 
139 	pcr_select[pcr_idx >> 3] = 1 << (pcr_idx & 0x7);
140 
141 	tpm_buf_append_u32(buf, 1);
142 	tpm_buf_append_u16(buf, digest->alg_id);
143 	tpm_buf_append_u8(buf, TPM2_PCR_SELECT_MIN);
144 	tpm_buf_append(buf, (const unsigned char *)pcr_select,
145 		       sizeof(pcr_select));
146 
147 	rc = tpm_transmit_cmd(chip, buf, 0, "attempting to read a pcr value");
148 	if (rc)
149 		return rc;
150 
151 	out = (struct tpm2_pcr_read_out *)&buf->data[TPM_HEADER_SIZE];
152 	digest_size = be16_to_cpu(out->digest_size);
153 	if (digest_size > sizeof(digest->digest) ||
154 	    (!digest_size_ptr && digest_size != expected_digest_size))
155 		return -EINVAL;
156 
157 	if (digest_size_ptr)
158 		*digest_size_ptr = digest_size;
159 
160 	memcpy(digest->digest, out->digest, digest_size);
161 	return rc;
162 }
163 
164 /**
165  * tpm2_pcr_extend() - extend a PCR value
166  *
167  * @chip:	TPM chip to use.
168  * @pcr_idx:	index of the PCR.
169  * @digests:	list of pcr banks and corresponding digest values to extend.
170  *
171  * Return: Same as with tpm_transmit_cmd.
172  */
173 int tpm2_pcr_extend(struct tpm_chip *chip, u32 pcr_idx,
174 		    struct tpm_digest *digests)
175 {
176 	struct tpm_buf *buf __free(kfree) = NULL;
177 	int rc;
178 	int i;
179 
180 	if (!disable_pcr_integrity) {
181 		rc = tpm2_start_auth_session(chip);
182 		if (rc)
183 			return rc;
184 	}
185 
186 	buf = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
187 	if (!buf) {
188 		if (!disable_pcr_integrity)
189 			tpm2_end_auth_session(chip);
190 		return -ENOMEM;
191 	}
192 
193 	tpm_buf_init(buf, TPM_BUFSIZE);
194 	tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_PCR_EXTEND);
195 
196 	if (!disable_pcr_integrity) {
197 		rc = tpm_buf_append_name(chip, buf, pcr_idx, NULL);
198 		if (rc) {
199 			tpm2_end_auth_session(chip);
200 			return rc;
201 		}
202 		tpm_buf_append_hmac_session(chip, buf, 0, NULL, 0);
203 	} else {
204 		tpm_buf_append_handle(buf, pcr_idx);
205 		tpm_buf_append_auth(chip, buf, NULL, 0);
206 	}
207 
208 	tpm_buf_append_u32(buf, chip->nr_allocated_banks);
209 
210 	for (i = 0; i < chip->nr_allocated_banks; i++) {
211 		tpm_buf_append_u16(buf, digests[i].alg_id);
212 		tpm_buf_append(buf, (const unsigned char *)&digests[i].digest,
213 			       chip->allocated_banks[i].digest_size);
214 	}
215 
216 	if (!disable_pcr_integrity) {
217 		rc = tpm_buf_fill_hmac_session(chip, buf);
218 		if (rc)
219 			return rc;
220 	}
221 
222 	rc = tpm_transmit_cmd(chip, buf, 0, "attempting extend a PCR value");
223 	if (!disable_pcr_integrity)
224 		rc = tpm_buf_check_hmac_response(chip, buf, rc);
225 
226 	return rc;
227 }
228 
229 /**
230  * tpm2_get_random() - get random bytes from the TPM RNG
231  *
232  * @chip:	a &tpm_chip instance
233  * @dest:	destination buffer
234  * @max:	the max number of random bytes to pull
235  *
236  * Return:
237  *   size of the buffer on success,
238  *   -errno otherwise (positive TPM return codes are masked to -EIO)
239  */
240 int tpm2_get_random(struct tpm_chip *chip, u8 *dest, size_t max)
241 {
242 	struct tpm2_get_random_out *out;
243 	struct tpm_header *head;
244 	u32 recd;
245 	u32 num_bytes = max;
246 	int err;
247 	int total = 0;
248 	int retries = 5;
249 	u8 *dest_ptr = dest;
250 	off_t offset;
251 
252 	struct tpm_buf *buf __free(kfree) = NULL;
253 
254 	if (!num_bytes || max > TPM_MAX_RNG_DATA)
255 		return -EINVAL;
256 
257 	err = tpm2_start_auth_session(chip);
258 	if (err)
259 		return err;
260 
261 	buf = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
262 	if (!buf) {
263 		tpm2_end_auth_session(chip);
264 		return -ENOMEM;
265 	}
266 
267 	tpm_buf_init(buf, TPM_BUFSIZE);
268 
269 	do {
270 		tpm_buf_reset(buf, TPM2_ST_SESSIONS, TPM2_CC_GET_RANDOM);
271 		if (tpm2_chip_auth(chip)) {
272 			tpm_buf_append_hmac_session(chip, buf,
273 						    TPM2_SA_ENCRYPT |
274 						    TPM2_SA_CONTINUE_SESSION,
275 						    NULL, 0);
276 		} else  {
277 			offset = buf->handles * 4 + TPM_HEADER_SIZE;
278 			head = (struct tpm_header *)buf->data;
279 			if (tpm_buf_length(buf) == offset)
280 				head->tag = cpu_to_be16(TPM2_ST_NO_SESSIONS);
281 		}
282 		tpm_buf_append_u16(buf, num_bytes);
283 		err = tpm_buf_fill_hmac_session(chip, buf);
284 		if (err)
285 			return err;
286 
287 		err = tpm_transmit_cmd(chip, buf,
288 				       offsetof(struct tpm2_get_random_out,
289 						buffer),
290 				       "attempting get random");
291 		err = tpm_buf_check_hmac_response(chip, buf, err);
292 		if (err) {
293 			if (err > 0)
294 				err = -EIO;
295 			tpm2_end_auth_session(chip);
296 			return err;
297 		}
298 
299 		head = (struct tpm_header *)buf->data;
300 		offset = TPM_HEADER_SIZE;
301 		/* Skip the parameter size field: */
302 		if (be16_to_cpu(head->tag) == TPM2_ST_SESSIONS)
303 			offset += 4;
304 
305 		out = (struct tpm2_get_random_out *)&buf->data[offset];
306 		recd = min_t(u32, be16_to_cpu(out->size), num_bytes);
307 		if (tpm_buf_length(buf) <
308 		    TPM_HEADER_SIZE +
309 		    offsetof(struct tpm2_get_random_out, buffer) +
310 		    recd) {
311 			tpm2_end_auth_session(chip);
312 			return -EFAULT;
313 		}
314 		memcpy(dest_ptr, out->buffer, recd);
315 
316 		dest_ptr += recd;
317 		total += recd;
318 		num_bytes -= recd;
319 	} while (retries-- && total < max);
320 
321 	return total ? total : -EIO;
322 }
323 
324 /**
325  * tpm2_flush_context() - execute a TPM2_FlushContext command
326  * @chip:	TPM chip to use
327  * @handle:	context handle
328  */
329 void tpm2_flush_context(struct tpm_chip *chip, u32 handle)
330 {
331 	struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
332 	if (!buf) {
333 		dev_warn(&chip->dev, "0x%08x was not flushed, out of memory\n",
334 			 handle);
335 		return;
336 	}
337 
338 	tpm_buf_init(buf, TPM_BUFSIZE);
339 	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_FLUSH_CONTEXT);
340 	tpm_buf_append_u32(buf, handle);
341 
342 	tpm_transmit_cmd(chip, buf, 0, "flushing context");
343 }
344 EXPORT_SYMBOL_GPL(tpm2_flush_context);
345 
346 /**
347  * tpm2_get_tpm_pt() - get value of a TPM_CAP_TPM_PROPERTIES type property
348  * @chip:		a &tpm_chip instance
349  * @property_id:	property ID.
350  * @value:		output variable.
351  * @desc:		passed to tpm_transmit_cmd()
352  *
353  * Return:
354  *   0 on success,
355  *   -errno or a TPM return code otherwise
356  */
357 ssize_t tpm2_get_tpm_pt(struct tpm_chip *chip, u32 property_id,  u32 *value,
358 			const char *desc)
359 {
360 	struct tpm2_get_cap_out *out;
361 	int rc;
362 
363 	struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
364 	if (!buf)
365 		return -ENOMEM;
366 
367 	tpm_buf_init(buf, TPM_BUFSIZE);
368 	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
369 	tpm_buf_append_u32(buf, TPM2_CAP_TPM_PROPERTIES);
370 	tpm_buf_append_u32(buf, property_id);
371 	tpm_buf_append_u32(buf, 1);
372 	rc = tpm_transmit_cmd(chip, buf, 0, NULL);
373 	if (!rc) {
374 		out = (struct tpm2_get_cap_out *)
375 			&buf->data[TPM_HEADER_SIZE];
376 		/*
377 		 * To prevent failing boot up of some systems, Infineon TPM2.0
378 		 * returns SUCCESS on TPM2_Startup in field upgrade mode. Also
379 		 * the TPM2_Getcapability command returns a zero length list
380 		 * in field upgrade mode.
381 		 */
382 		if (be32_to_cpu(out->property_cnt) > 0)
383 			*value = be32_to_cpu(out->value);
384 		else
385 			rc = -ENODATA;
386 	}
387 	return rc;
388 }
389 EXPORT_SYMBOL_GPL(tpm2_get_tpm_pt);
390 
391 /**
392  * tpm2_shutdown() - send a TPM shutdown command
393  *
394  * Sends a TPM shutdown command. The shutdown command is used in call
395  * sites where the system is going down. If it fails, there is not much
396  * that can be done except print an error message.
397  *
398  * @chip:		a &tpm_chip instance
399  * @shutdown_type:	TPM_SU_CLEAR or TPM_SU_STATE.
400  */
401 void tpm2_shutdown(struct tpm_chip *chip, u16 shutdown_type)
402 {
403 	struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
404 	if (!buf)
405 		return;
406 
407 	tpm_buf_init(buf, TPM_BUFSIZE);
408 	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_SHUTDOWN);
409 	tpm_buf_append_u16(buf, shutdown_type);
410 	tpm_transmit_cmd(chip, buf, 0, "stopping the TPM");
411 }
412 
413 /**
414  * tpm2_do_selftest() - ensure that all self tests have passed
415  *
416  * @chip: TPM chip to use
417  *
418  * Return: Same as with tpm_transmit_cmd.
419  *
420  * The TPM can either run all self tests synchronously and then return
421  * RC_SUCCESS once all tests were successful. Or it can choose to run the tests
422  * asynchronously and return RC_TESTING immediately while the self tests still
423  * execute in the background. This function handles both cases and waits until
424  * all tests have completed.
425  */
426 static int tpm2_do_selftest(struct tpm_chip *chip)
427 {
428 	int full;
429 	int rc;
430 
431 	for (full = 0; full < 2; full++) {
432 		struct tpm_buf *buf __free(kfree) = NULL;
433 
434 		buf = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
435 		if (!buf)
436 			return -ENOMEM;
437 
438 		tpm_buf_init(buf, TPM_BUFSIZE);
439 		tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_SELF_TEST);
440 		tpm_buf_append_u8(buf, full);
441 		rc = tpm_transmit_cmd(chip, buf, 0,
442 				      "attempting the self test");
443 		if (rc == TPM2_RC_TESTING)
444 			rc = TPM2_RC_SUCCESS;
445 		if (rc == TPM2_RC_INITIALIZE || rc == TPM2_RC_SUCCESS)
446 			return rc;
447 	}
448 
449 	return rc;
450 }
451 
452 /**
453  * tpm2_probe() - probe for the TPM 2.0 protocol
454  * @chip:	a &tpm_chip instance
455  *
456  * Send an idempotent TPM 2.0 command and see whether there is TPM2 chip in the
457  * other end based on the response tag. The flag TPM_CHIP_FLAG_TPM2 is set by
458  * this function if this is the case.
459  *
460  * Return:
461  *   0 on success,
462  *   -errno otherwise
463  */
464 int tpm2_probe(struct tpm_chip *chip)
465 {
466 	struct tpm_header *out;
467 	int rc;
468 
469 	struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
470 	if (!buf)
471 		return -ENOMEM;
472 
473 	tpm_buf_init(buf, TPM_BUFSIZE);
474 	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
475 	tpm_buf_append_u32(buf, TPM2_CAP_TPM_PROPERTIES);
476 	tpm_buf_append_u32(buf, TPM_PT_TOTAL_COMMANDS);
477 	tpm_buf_append_u32(buf, 1);
478 	rc = tpm_transmit_cmd(chip, buf, 0, NULL);
479 	/* We ignore TPM return codes on purpose. */
480 	if (rc >=  0) {
481 		out = (struct tpm_header *)buf->data;
482 		if (be16_to_cpu(out->tag) == TPM2_ST_NO_SESSIONS)
483 			chip->flags |= TPM_CHIP_FLAG_TPM2;
484 	}
485 	return 0;
486 }
487 EXPORT_SYMBOL_GPL(tpm2_probe);
488 
489 static int tpm2_init_bank_info(struct tpm_chip *chip, u32 bank_index)
490 {
491 	struct tpm_bank_info *bank = chip->allocated_banks + bank_index;
492 	struct tpm_digest digest = { .alg_id = bank->alg_id };
493 	int i;
494 
495 	/*
496 	 * Avoid unnecessary PCR read operations to reduce overhead
497 	 * and obtain identifiers of the crypto subsystem.
498 	 */
499 	for (i = 0; i < ARRAY_SIZE(tpm2_hash_map); i++) {
500 		enum hash_algo crypto_algo = tpm2_hash_map[i].crypto_id;
501 
502 		if (bank->alg_id != tpm2_hash_map[i].tpm_id)
503 			continue;
504 
505 		bank->digest_size = hash_digest_size[crypto_algo];
506 		bank->crypto_id = crypto_algo;
507 		return 0;
508 	}
509 
510 	bank->crypto_id = HASH_ALGO__LAST;
511 
512 	return tpm2_pcr_read(chip, 0, &digest, &bank->digest_size);
513 }
514 
515 ssize_t tpm2_get_pcr_allocation(struct tpm_chip *chip)
516 {
517 	struct tpm2_pcr_selection pcr_selection;
518 	void *marker;
519 	void *end;
520 	void *pcr_select_offset;
521 	u32 sizeof_pcr_selection;
522 	u32 nr_possible_banks;
523 	u32 nr_alloc_banks = 0;
524 	u16 hash_alg;
525 	u32 rsp_len;
526 	int rc;
527 	int i = 0;
528 
529 	struct tpm_buf *buf __free(kfree) = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
530 	if (!buf)
531 		return -ENOMEM;
532 
533 	tpm_buf_init(buf, TPM_BUFSIZE);
534 	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
535 	tpm_buf_append_u32(buf, TPM2_CAP_PCRS);
536 	tpm_buf_append_u32(buf, 0);
537 	tpm_buf_append_u32(buf, 1);
538 
539 	rc = tpm_transmit_cmd(chip, buf, 9, "get tpm pcr allocation");
540 	if (rc)
541 		return rc;
542 
543 	nr_possible_banks = be32_to_cpup(
544 		(__be32 *)&buf->data[TPM_HEADER_SIZE + 5]);
545 	if (nr_possible_banks > TPM2_MAX_PCR_BANKS) {
546 		pr_err("tpm: out of bank capacity: %u > %u\n",
547 		       nr_possible_banks, TPM2_MAX_PCR_BANKS);
548 		return -ENOMEM;
549 	}
550 
551 	marker = &buf->data[TPM_HEADER_SIZE + 9];
552 
553 	rsp_len = be32_to_cpup((__be32 *)&buf->data[2]);
554 	end = &buf->data[rsp_len];
555 
556 	for (i = 0; i < nr_possible_banks; i++) {
557 		pcr_select_offset = marker +
558 			offsetof(struct tpm2_pcr_selection, size_of_select);
559 		if (pcr_select_offset >= end) {
560 			rc = -EFAULT;
561 			break;
562 		}
563 
564 		memcpy(&pcr_selection, marker, sizeof(pcr_selection));
565 		hash_alg = be16_to_cpu(pcr_selection.hash_alg);
566 
567 		pcr_select_offset = memchr_inv(pcr_selection.pcr_select, 0,
568 					       pcr_selection.size_of_select);
569 		if (pcr_select_offset) {
570 			chip->allocated_banks[nr_alloc_banks].alg_id = hash_alg;
571 
572 			rc = tpm2_init_bank_info(chip, nr_alloc_banks);
573 			if (rc < 0)
574 				break;
575 
576 			nr_alloc_banks++;
577 		}
578 
579 		sizeof_pcr_selection = sizeof(pcr_selection.hash_alg) +
580 			sizeof(pcr_selection.size_of_select) +
581 			pcr_selection.size_of_select;
582 		marker = marker + sizeof_pcr_selection;
583 	}
584 
585 	chip->nr_allocated_banks = nr_alloc_banks;
586 
587 	return rc;
588 }
589 
590 int tpm2_get_cc_attrs_tbl(struct tpm_chip *chip)
591 {
592 	u32 nr_commands;
593 	__be32 *attrs;
594 	u32 cc;
595 	int i;
596 	int rc;
597 
598 	struct tpm_buf *buf __free(kfree) = NULL;
599 
600 	rc = tpm2_get_tpm_pt(chip, TPM_PT_TOTAL_COMMANDS, &nr_commands, NULL);
601 	if (rc)
602 		goto out;
603 
604 	if (nr_commands > 0xFFFFF) {
605 		rc = -EFAULT;
606 		goto out;
607 	}
608 
609 	chip->cc_attrs_tbl = devm_kcalloc(&chip->dev, 4, nr_commands,
610 					  GFP_KERNEL);
611 	if (!chip->cc_attrs_tbl) {
612 		rc = -ENOMEM;
613 		goto out;
614 	}
615 
616 	buf = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
617 	if (!buf) {
618 		rc = -ENOMEM;
619 		goto out;
620 	}
621 
622 	tpm_buf_init(buf, TPM_BUFSIZE);
623 	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_GET_CAPABILITY);
624 	tpm_buf_append_u32(buf, TPM2_CAP_COMMANDS);
625 	tpm_buf_append_u32(buf, TPM2_CC_FIRST);
626 	tpm_buf_append_u32(buf, nr_commands);
627 
628 	rc = tpm_transmit_cmd(chip, buf, 9 + 4 * nr_commands, NULL);
629 	if (rc)
630 		goto out;
631 
632 	if (nr_commands !=
633 	    be32_to_cpup((__be32 *)&buf->data[TPM_HEADER_SIZE + 5])) {
634 		rc = -EFAULT;
635 		goto out;
636 	}
637 
638 	chip->nr_commands = nr_commands;
639 
640 	attrs = (__be32 *)&buf->data[TPM_HEADER_SIZE + 9];
641 	for (i = 0; i < nr_commands; i++, attrs++) {
642 		chip->cc_attrs_tbl[i] = be32_to_cpup(attrs);
643 		cc = chip->cc_attrs_tbl[i] & 0xFFFF;
644 
645 		if (cc == TPM2_CC_CONTEXT_SAVE || cc == TPM2_CC_FLUSH_CONTEXT) {
646 			chip->cc_attrs_tbl[i] &=
647 				~(GENMASK(2, 0) << TPM2_CC_ATTR_CHANDLES);
648 			chip->cc_attrs_tbl[i] |= 1 << TPM2_CC_ATTR_CHANDLES;
649 		}
650 	}
651 
652 out:
653 	if (rc > 0)
654 		rc = -ENODEV;
655 	return rc;
656 }
657 EXPORT_SYMBOL_GPL(tpm2_get_cc_attrs_tbl);
658 
659 /**
660  * tpm2_startup - turn on the TPM
661  * @chip: TPM chip to use
662  *
663  * Normally the firmware should start the TPM. This function is provided as a
664  * workaround if this does not happen. A legal case for this could be for
665  * example when a TPM emulator is used.
666  *
667  * Return: same as tpm_transmit_cmd()
668  */
669 
670 static int tpm2_startup(struct tpm_chip *chip)
671 {
672 	struct tpm_buf *buf __free(kfree) = NULL;
673 
674 	dev_info(&chip->dev, "starting up the TPM manually\n");
675 
676 	buf = kzalloc(TPM_BUFSIZE, GFP_KERNEL);
677 	if (!buf)
678 		return -ENOMEM;
679 
680 	tpm_buf_init(buf, TPM_BUFSIZE);
681 	tpm_buf_reset(buf, TPM2_ST_NO_SESSIONS, TPM2_CC_STARTUP);
682 	tpm_buf_append_u16(buf, TPM2_SU_CLEAR);
683 	return tpm_transmit_cmd(chip, buf, 0, "attempting to start the TPM");
684 }
685 
686 /**
687  * tpm2_auto_startup - Perform the standard automatic TPM initialization
688  *                     sequence
689  * @chip: TPM chip to use
690  *
691  * Returns 0 on success, < 0 in case of fatal error.
692  */
693 int tpm2_auto_startup(struct tpm_chip *chip)
694 {
695 	int rc;
696 
697 	rc = tpm2_get_timeouts(chip);
698 	if (rc)
699 		goto out;
700 
701 	rc = tpm2_do_selftest(chip);
702 	if (rc && rc != TPM2_RC_INITIALIZE)
703 		goto out;
704 
705 	if (rc == TPM2_RC_INITIALIZE) {
706 		rc = tpm2_startup(chip);
707 		if (rc)
708 			goto out;
709 
710 		rc = tpm2_do_selftest(chip);
711 		if (rc)
712 			goto out;
713 	}
714 
715 	rc = tpm2_get_cc_attrs_tbl(chip);
716 	if (rc == TPM2_RC_FAILURE || (rc < 0 && rc != -ENOMEM)) {
717 		dev_info(&chip->dev,
718 			 "TPM in field failure mode, requires firmware upgrade\n");
719 		chip->flags |= TPM_CHIP_FLAG_FIRMWARE_UPGRADE;
720 		rc = 0;
721 	}
722 
723 	if (rc)
724 		goto out;
725 
726 	rc = tpm2_sessions_init(chip);
727 
728 out:
729 	/*
730 	 * Infineon TPM in field upgrade mode will return no data for the number
731 	 * of supported commands.
732 	 */
733 	if (rc == TPM2_RC_UPGRADE || rc == -ENODATA) {
734 		dev_info(&chip->dev, "TPM in field upgrade mode, requires firmware upgrade\n");
735 		chip->flags |= TPM_CHIP_FLAG_FIRMWARE_UPGRADE;
736 		rc = 0;
737 	}
738 
739 	if (rc > 0)
740 		rc = -ENODEV;
741 	return rc;
742 }
743 
744 int tpm2_find_cc(struct tpm_chip *chip, u32 cc)
745 {
746 	u32 cc_mask;
747 	int i;
748 
749 	cc_mask = 1 << TPM2_CC_ATTR_VENDOR | GENMASK(15, 0);
750 	for (i = 0; i < chip->nr_commands; i++)
751 		if (cc == (chip->cc_attrs_tbl[i] & cc_mask))
752 			return i;
753 
754 	return -1;
755 }
756