2 * Copyright 2016 The Chromium OS Authors. All rights reserved.
3 * Use of this source code is governed by a BSD-style license that can be
4 * found in the LICENSE file.
6 * This is a driver for a SPI interfaced TPM2 device.
8 * It assumes that the required SPI interface has been initialized before the
9 * driver is started. A 'sruct spi_slave' pointer passed at initialization is
10 * used to direct traffic to the correct SPI interface. This dirver does not
11 * provide a way to instantiate multiple TPM devices. Also, to keep things
12 * simple, the driver unconditionally uses of TPM locality zero.
14 * References to documentation are based on the TCG issued "TPM Profile (PTP)
15 * Specification Revision 00.43".
18 #include <libpayload.h>
22 /************************************************************/
23 /* Plumbing to make porting of the coreboot driver easier. */
40 static void stopwatch_init_usecs_expire(struct stopwatch *sw, long us)
42 sw->start = timer_us(0);
46 static int stopwatch_expired(struct stopwatch *sw)
48 return timer_us(sw->start > sw->expires);
52 * Use static driver structure, we're not going to have multiple TPM devices
55 static SpiTpm spi_tpm;
57 static int spi_claim_bus(struct spi_slave *unused)
59 return spi_tpm.bus->start(spi_tpm.bus);
62 static void spi_release_bus(struct spi_slave *unused)
64 spi_tpm.bus->stop(spi_tpm.bus);
67 static int spi_xfer(struct spi_slave *unused, const void *dout,
68 unsigned bytesout, void *din, unsigned bytesin)
73 if (bytesin < bytesout)
78 return spi_tpm.bus->transfer(spi_tpm.bus, din, dout, count);
81 static uint32_t read_be32(const void *ptr)
85 memcpy(&result, ptr, sizeof(result));
86 return be32toh(result);
89 /*********************************************************/
90 /* Coreboot driver with as little changes as possible. */
93 #define TPM_LOCALITY_0_SPI_BASE 0x00d40000
95 /* Assorted TPM2 registers for interface type FIFO. */
96 #define TPM_ACCESS_REG (TPM_LOCALITY_0_SPI_BASE + 0)
97 #define TPM_STS_REG (TPM_LOCALITY_0_SPI_BASE + 0x18)
98 #define TPM_DATA_FIFO_REG (TPM_LOCALITY_0_SPI_BASE + 0x24)
99 #define TPM_DID_VID_REG (TPM_LOCALITY_0_SPI_BASE + 0xf00)
100 #define TPM_RID_REG (TPM_LOCALITY_0_SPI_BASE + 0xf04)
102 /* SPI Interface descriptor used by the driver. */
104 struct spi_slave *slave;
105 int (*cs_assert)(struct spi_slave *slave);
106 void (*cs_deassert)(struct spi_slave *slave);
107 int (*xfer)(struct spi_slave *slave, const void *dout,
108 unsigned bytesout, void *din,
112 /* Use the common SPI driver wrapper as the interface callbacks. */
113 static struct tpm_spi_if tpm_if = {
114 .cs_assert = spi_claim_bus,
115 .cs_deassert = spi_release_bus,
119 /* Cached TPM device identification. */
120 struct tpm2_info tpm_info;
123 * TODO(vbendeb): make CONFIG_DEBUG_TPM an int to allow different level of
124 * debug traces. Right now it is either 0 or 1.
126 static const int debug_level_ = 1;
128 /* Locality management bits (in TPM_ACCESS_REG) */
129 enum tpm_access_bits {
130 tpm_reg_valid_sts = (1 << 7),
131 active_locality = (1 << 5),
132 request_use = (1 << 1),
133 tpm_establishment = (1 << 0),
137 * Variuous fields of the TPM status register, arguably the most important
138 * register when interfacing to a TPM.
141 tpm_family_shift = 26,
142 tpm_family_mask = ((1 << 2) - 1), /* 2 bits wide. */
144 reset_establishment_bit = (1 << 25),
145 command_cancel = (1 << 24),
146 burst_count_shift = 8,
147 burst_count_mask = ((1 << 16) - 1), /* 16 bits wide. */
148 sts_valid = (1 << 7),
149 command_ready = (1 << 6),
151 data_avail = (1 << 4),
153 self_test_done = (1 << 2),
154 response_retry = (1 << 1),
158 * SPI frame header for TPM transactions is 4 bytes in size, it is described
159 * in section "6.4.6 Spi Bit Protocol".
162 unsigned char body[4];
166 * Each TPM2 SPI transaction starts the same: CS is asserted, the 4 byte
167 * header is sent to the TPM, the master waits til TPM is ready to continue.
169 static void start_transaction(int read_write, size_t bytes, unsigned addr)
171 spi_frame_header header;
176 * Give it 10 ms. TODO(vbendeb): remove this once cr50 SPS TPM driver
177 * performance is fixed.
182 * The first byte of the frame header encodes the transaction type
183 * (read or write) and transfer size (set to lentgh - 1), limited to
186 header.body[0] = (read_write ? 0x80 : 0) | 0x40 | (bytes - 1);
188 /* The rest of the frame header is the TPM register address. */
189 for (i = 0; i < 3; i++)
190 header.body[i + 1] = (addr >> (8 * (2 - i))) & 0xff;
192 /* CS assert wakes up the slave. */
193 tpm_if.cs_assert(tpm_if.slave);
196 * The TCG TPM over SPI specification introduces the notion of SPI
197 * flow control (Section "6.4.5 Flow Control").
199 * Again, the slave (TPM device) expects each transaction to start
200 * with a 4 byte header trasmitted by master. The header indicates if
201 * the master needs to read or write a register, and the register
204 * If the slave needs to stall the transaction (for instance it is not
205 * ready to send the register value to the master), it sets the MOSI
206 * line to 0 during the last clock of the 4 byte header. In this case
207 * the master is supposed to start polling the SPI bus, one byte at
208 * time, until the last bit in the received byte (transferred during
209 * the last clock of the byte) is set to 1.
211 * Due to some SPI controllers' shortcomings (Rockchip comes to
212 * mind...) we trasmit the 4 byte header without checking the byte
213 * transmitted by the TPM during the transaction's last byte.
215 * We know that cr50 is guaranteed to set the flow control bit to 0
216 * during the header transfer, but real TPM2 might be fast enough not
217 * to require to stall the master, this would present an issue.
218 * crosbug.com/p/52132 has been opened to track this.
220 tpm_if.xfer(tpm_if.slave, header.body, sizeof(header.body), NULL, 0);
222 /* Now poll the bus until TPM removes the stall bit. */
224 tpm_if.xfer(tpm_if.slave, NULL, 0, &byte, 1);
225 } while (!(byte & 1));
229 * Print out the contents of a buffer, if debug is enabled. Skip registers
230 * other than FIFO, unless debug_level_ is 2.
232 static void trace_dump(const char *prefix, uint32_t reg,
233 size_t bytes, const uint8_t *buffer,
236 static char prev_prefix;
237 static unsigned prev_reg;
238 static int current_char;
239 const int BYTES_PER_LINE = 32;
245 if ((debug_level_ < 2) && (reg != TPM_DATA_FIFO_REG))
250 * Do not print register address again if the last dump print was for
253 if ((prev_prefix != *prefix) || (prev_reg != reg)) {
254 prev_prefix = *prefix;
256 printf("\n%s %2.2x:", prefix, reg);
260 if ((reg != TPM_DATA_FIFO_REG) && (bytes == 4)) {
262 * This must be a regular register address, print the 32 bit
265 printf(" %8.8x", *(const uint32_t *)buffer);
270 * Data read from or written to FIFO or not in 4 byte
271 * quantiites is printed byte at a time.
273 for (i = 0; i < bytes; i++) {
274 if (current_char && !(current_char % BYTES_PER_LINE)) {
279 printf(" %2.2x", buffer[i]);
285 * Once transaction is initiated and the TPM indicated that it is ready to go,
286 * write the actual bytes to the register.
288 static void write_bytes(const void *buffer, size_t bytes)
290 tpm_if.xfer(tpm_if.slave, buffer, bytes, NULL, 0);
294 * Once transaction is initiated and the TPM indicated that it is ready to go,
295 * read the actual bytes from the register.
297 static void read_bytes(void *buffer, size_t bytes)
299 tpm_if.xfer(tpm_if.slave, NULL, 0, buffer, bytes);
303 * To write a register, start transaction, transfer data to the TPM, deassert
306 * Returns one to indicate success, zero (not yet implemented) to indicate
309 static int tpm2_write_reg(unsigned reg_number, const void *buffer, size_t bytes)
311 trace_dump("W", reg_number, bytes, buffer, 0);
312 start_transaction(false, bytes, reg_number);
313 write_bytes(buffer, bytes);
314 tpm_if.cs_deassert(tpm_if.slave);
319 * To read a register, start transaction, transfer data from the TPM, deassert
322 * Returns one to indicate success, zero (not yet implemented) to indicate
325 static int tpm2_read_reg(unsigned reg_number, void *buffer, size_t bytes)
327 start_transaction(true, bytes, reg_number);
328 read_bytes(buffer, bytes);
329 tpm_if.cs_deassert(tpm_if.slave);
330 trace_dump("R", reg_number, bytes, buffer, 0);
335 * Status register is accessed often, wrap reading and writing it into
336 * dedicated functions.
338 static int read_tpm_sts(uint32_t *status)
340 return tpm2_read_reg(TPM_STS_REG, status, sizeof(*status));
343 static int write_tpm_sts(uint32_t status)
345 return tpm2_write_reg(TPM_STS_REG, &status, sizeof(status));
349 * The TPM may limit the transaction bytes count (burst count) below the 64
350 * bytes max. The current value is available as a field of the status
353 static uint32_t get_burst_count(void)
357 read_tpm_sts(&status);
358 return (status >> burst_count_shift) & burst_count_mask;
361 static int tpm2_init(SpiOps *spi_ops)
363 uint32_t did_vid, status;
366 tpm2_read_reg(TPM_DID_VID_REG, &did_vid, sizeof(did_vid));
368 /* Try claiming locality zero. */
369 tpm2_read_reg(TPM_ACCESS_REG, &cmd, sizeof(cmd));
370 if ((cmd & (active_locality & tpm_reg_valid_sts)) ==
371 (active_locality & tpm_reg_valid_sts)) {
373 * Locality active - maybe reset line is not connected?
374 * Release the locality and try again
376 cmd = active_locality;
377 tpm2_write_reg(TPM_ACCESS_REG, &cmd, sizeof(cmd));
378 tpm2_read_reg(TPM_ACCESS_REG, &cmd, sizeof(cmd));
381 /* The tpm_establishment bit can be either set or not, ignore it. */
382 if ((cmd & ~tpm_establishment) != tpm_reg_valid_sts) {
383 printf("invalid reset status: %#x\n", cmd);
388 tpm2_write_reg(TPM_ACCESS_REG, &cmd, sizeof(cmd));
389 tpm2_read_reg(TPM_ACCESS_REG, &cmd, sizeof(cmd));
390 if ((cmd & ~tpm_establishment) !=
391 (tpm_reg_valid_sts | active_locality)) {
392 printf("failed to claim locality 0, status: %#x\n",
397 read_tpm_sts(&status);
398 if (((status >> tpm_family_shift) & tpm_family_mask) !=
400 printf("unexpected TPM family value, status: %#x\n",
406 * Locality claimed, read the revision value and set up the tpm_info
409 tpm2_read_reg(TPM_RID_REG, &cmd, sizeof(cmd));
410 tpm_info.vendor_id = did_vid & 0xffff;
411 tpm_info.device_id = did_vid >> 16;
412 tpm_info.revision = cmd;
414 printf("Connected to device vid:did:rid of %4.4x:%4.4x:%2.2x\n",
415 tpm_info.vendor_id, tpm_info.device_id, tpm_info.revision);
421 * This is in seconds, certain TPM commands, like key generation, can take
422 * long time to complete.
424 * Returns one to indicate success, zero (not yet implemented) to indicate
427 #define MAX_STATUS_TIMEOUT 120
428 static int wait_for_status(uint32_t status_mask, uint32_t status_expected)
433 stopwatch_init_usecs_expire(&sw, MAX_STATUS_TIMEOUT * 1000 * 1000);
436 if (stopwatch_expired(&sw)) {
437 printf("failed to get expected status %x\n",
441 read_tpm_sts(&status);
442 } while ((status & status_mask) != status_expected);
447 enum fifo_transfer_direction {
452 /* Union allows to avoid casting away 'const' on transmit buffers. */
453 union fifo_transfer_buffer {
455 const uint8_t *tx_buffer;
459 * Transfer requested number of bytes to or from TPM FIFO, accounting for the
460 * current burst count value.
462 static void fifo_transfer(size_t transfer_size,
463 union fifo_transfer_buffer buffer,
464 enum fifo_transfer_direction direction)
466 size_t transaction_size;
468 size_t handled_so_far = 0;
472 /* Could be zero when TPM is busy. */
473 burst_count = get_burst_count();
474 } while (!burst_count);
476 transaction_size = transfer_size - handled_so_far;
477 transaction_size = MIN(transaction_size, burst_count);
480 * The SPI frame header does not allow to pass more than 64
483 transaction_size = MIN(transaction_size, 64);
485 if (direction == fifo_receive)
486 tpm2_read_reg(TPM_DATA_FIFO_REG,
487 buffer.rx_buffer + handled_so_far,
490 tpm2_write_reg(TPM_DATA_FIFO_REG,
491 buffer.tx_buffer + handled_so_far,
494 handled_so_far += transaction_size;
496 } while (handled_so_far != transfer_size);
499 static size_t tpm2_process_command(const void *tpm2_command,
505 uint32_t expected_status_bits;
508 const uint8_t *cmd_body = tpm2_command;
509 uint8_t *rsp_body = tpm2_response;
510 union fifo_transfer_buffer fifo_buffer;
511 const int HEADER_SIZE = 6;
513 /* Skip the two byte tag, read the size field. */
514 payload_size = read_be32(cmd_body + 2);
517 if (payload_size != command_size) {
518 printf("Command size mismatch: encoded %zd != requested %zd\n",
519 payload_size, command_size);
520 trace_dump("W", TPM_DATA_FIFO_REG, command_size, cmd_body, 1);
525 /* Let the TPM know that the command is coming. */
526 write_tpm_sts(command_ready);
529 * Tpm commands and responses written to and read from the FIFO
530 * register (0x24) are datagrams of variable size, prepended by a 6
533 * The specification description of the state machine is a bit vague,
534 * but from experience it looks like there is no need to wait for the
535 * sts.expect bit to be set, at least with the 9670 and cr50 devices.
536 * Just write the command into FIFO, making sure not to exceed the
537 * burst count or the maximum PDU size, whatever is smaller.
539 fifo_buffer.tx_buffer = cmd_body;
540 fifo_transfer(command_size, fifo_buffer, fifo_transmit);
542 /* Now tell the TPM it can start processing the command. */
543 write_tpm_sts(tpm_go);
545 /* Now wait for it to report that the response is ready. */
546 expected_status_bits = sts_valid | data_avail;
547 if (!wait_for_status(expected_status_bits, expected_status_bits)) {
549 * If timed out, which should never happen, let's at least
550 * print out the offending command.
552 trace_dump("W", TPM_DATA_FIFO_REG, command_size, cmd_body, 1);
558 * The response is ready, let's read it. First we read the FIFO
559 * payload header, to see how much data to expect. The response header
560 * size is fixed to six bytes, the total payload size is stored in
561 * network order in the last four bytes.
563 tpm2_read_reg(TPM_DATA_FIFO_REG, rsp_body, HEADER_SIZE);
565 /* Find out the total payload size, skipping the two byte tag. */
566 payload_size = read_be32(rsp_body + 2);
568 if (payload_size > max_response) {
570 * TODO(vbendeb): at least drain the FIFO here or somehow let
571 * the TPM know that the response can be dropped.
573 printf(" tpm response too long (%zd bytes)",
579 * Now let's read all but the last byte in the FIFO to make sure the
580 * status register is showing correct flow control bits: 'more data'
581 * until the last byte and then 'no more data' once the last byte is
584 bytes_to_go = payload_size - 1 - HEADER_SIZE;
585 fifo_buffer.rx_buffer = rsp_body + HEADER_SIZE;
586 fifo_transfer(bytes_to_go, fifo_buffer, fifo_receive);
588 /* Verify that there is still data to read. */
589 read_tpm_sts(&status);
590 if ((status & expected_status_bits) != expected_status_bits) {
591 printf("unexpected intermediate status %#x\n",
596 /* Read the last byte of the PDU. */
597 tpm2_read_reg(TPM_DATA_FIFO_REG, rsp_body + payload_size - 1, 1);
599 /* Terminate the dump, if enabled. */
603 /* Verify that 'data available' is not asseretd any more. */
604 read_tpm_sts(&status);
605 if ((status & expected_status_bits) != sts_valid) {
606 printf("unexpected final status %#x\n", status);
610 /* Move the TPM back to idle state. */
611 write_tpm_sts(command_ready);
616 /*********************************************************/
617 /* Depthcharge interface to the coreboot SPI TPM driver. */
619 static int tpm_initialized;
620 static int tpm_cleanup(CleanupFunc *cleanup, CleanupType type)
622 printf("%s: add release locality here.\n", __func__);
626 static int xmit_wrapper(struct TpmOps *me,
627 const uint8_t *sendbuf,
632 size_t response_size;
633 SpiTpm *tpm = container_of(me, SpiTpm, ops);
635 if (!tpm_initialized) {
636 if (tpm2_init(tpm->bus))
639 list_insert_after(&spi_tpm.cleanup.list_node, &cleanup_funcs);
643 response_size = tpm2_process_command(sendbuf,
644 send_size, recvbuf, *recv_len);
646 *recv_len = response_size;
653 SpiTpm *new_tpm_spi(SpiOps *bus)
655 spi_tpm.ops.xmit = xmit_wrapper;
657 spi_tpm.cleanup.cleanup = tpm_cleanup;
658 spi_tpm.cleanup.types = CleanupOnReboot | CleanupOnPowerOff |
659 CleanupOnHandoff | CleanupOnLegacy;