blob: 4de62d95c49744aa18b05a4195003de6ab24df3f [file] [log] [blame]
Vadim Bendeburye31d2432016-04-09 18:33:49 -07001/*
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.
5 *
6 * This is a driver for a SPI interfaced TPM2 device.
7 *
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.
13 *
14 * References to documentation are based on the TCG issued "TPM Profile (PTP)
15 * Specification Revision 00.43".
16 */
17
18#include <commonlib/endian.h>
19#include <console/console.h>
20#include <delay.h>
21#include <endian.h>
22#include <string.h>
23#include <timer.h>
24
25#include "tpm.h"
26
Vadim Bendebury05155c02016-06-23 12:03:18 -070027#define TPM_LOCALITY_0_SPI_BASE 0x00d40000
28
Vadim Bendeburye31d2432016-04-09 18:33:49 -070029/* Assorted TPM2 registers for interface type FIFO. */
Vadim Bendebury05155c02016-06-23 12:03:18 -070030#define TPM_ACCESS_REG (TPM_LOCALITY_0_SPI_BASE + 0)
31#define TPM_STS_REG (TPM_LOCALITY_0_SPI_BASE + 0x18)
32#define TPM_DATA_FIFO_REG (TPM_LOCALITY_0_SPI_BASE + 0x24)
33#define TPM_DID_VID_REG (TPM_LOCALITY_0_SPI_BASE + 0xf00)
34#define TPM_RID_REG (TPM_LOCALITY_0_SPI_BASE + 0xf04)
Vadim Bendebury58826fc2016-06-23 18:17:33 -070035#define TPM_FW_VER (TPM_LOCALITY_0_SPI_BASE + 0xf90)
Vadim Bendeburye31d2432016-04-09 18:33:49 -070036
37/* SPI Interface descriptor used by the driver. */
38struct tpm_spi_if {
39 struct spi_slave *slave;
40 int (*cs_assert)(struct spi_slave *slave);
41 void (*cs_deassert)(struct spi_slave *slave);
42 int (*xfer)(struct spi_slave *slave, const void *dout,
43 unsigned bytesout, void *din,
44 unsigned bytesin);
45};
46
47/* Use the common SPI driver wrapper as the interface callbacks. */
48static struct tpm_spi_if tpm_if = {
49 .cs_assert = spi_claim_bus,
50 .cs_deassert = spi_release_bus,
51 .xfer = spi_xfer
52};
53
54/* Cached TPM device identification. */
55struct tpm2_info tpm_info;
56
57/*
58 * TODO(vbendeb): make CONFIG_DEBUG_TPM an int to allow different level of
59 * debug traces. Right now it is either 0 or 1.
60 */
61static const int debug_level_ = CONFIG_DEBUG_TPM;
62
63/* Locality management bits (in TPM_ACCESS_REG) */
64enum tpm_access_bits {
65 tpm_reg_valid_sts = (1 << 7),
66 active_locality = (1 << 5),
67 request_use = (1 << 1),
68 tpm_establishment = (1 << 0),
69};
70
71/*
72 * Variuous fields of the TPM status register, arguably the most important
73 * register when interfacing to a TPM.
74 */
75enum tpm_sts_bits {
76 tpm_family_shift = 26,
77 tpm_family_mask = ((1 << 2) - 1), /* 2 bits wide. */
78 tpm_family_tpm2 = 1,
79 reset_establishment_bit = (1 << 25),
80 command_cancel = (1 << 24),
81 burst_count_shift = 8,
82 burst_count_mask = ((1 << 16) - 1), /* 16 bits wide. */
83 sts_valid = (1 << 7),
84 command_ready = (1 << 6),
85 tpm_go = (1 << 5),
86 data_avail = (1 << 4),
87 expect = (1 << 3),
88 self_test_done = (1 << 2),
89 response_retry = (1 << 1),
90};
91
92/*
93 * SPI frame header for TPM transactions is 4 bytes in size, it is described
94 * in section "6.4.6 Spi Bit Protocol".
95 */
96typedef struct {
97 unsigned char body[4];
98} spi_frame_header;
99
100void tpm2_get_info(struct tpm2_info *info)
101{
102 *info = tpm_info;
103}
104
105/*
106 * Each TPM2 SPI transaction starts the same: CS is asserted, the 4 byte
107 * header is sent to the TPM, the master waits til TPM is ready to continue.
108 */
109static void start_transaction(int read_write, size_t bytes, unsigned addr)
110{
111 spi_frame_header header;
112 uint8_t byte;
113 int i;
114
115 /*
116 * Give it 10 ms. TODO(vbendeb): remove this once cr50 SPS TPM driver
117 * performance is fixed.
118 */
119 mdelay(10);
120
121 /*
122 * The first byte of the frame header encodes the transaction type
123 * (read or write) and transfer size (set to lentgh - 1), limited to
124 * 64 bytes.
125 */
126 header.body[0] = (read_write ? 0x80 : 0) | 0x40 | (bytes - 1);
127
128 /* The rest of the frame header is the TPM register address. */
129 for (i = 0; i < 3; i++)
130 header.body[i + 1] = (addr >> (8 * (2 - i))) & 0xff;
131
132 /* CS assert wakes up the slave. */
133 tpm_if.cs_assert(tpm_if.slave);
134
135 /*
136 * The TCG TPM over SPI specification introduces the notion of SPI
137 * flow control (Section "6.4.5 Flow Control").
138 *
139 * Again, the slave (TPM device) expects each transaction to start
140 * with a 4 byte header trasmitted by master. The header indicates if
141 * the master needs to read or write a register, and the register
142 * address.
143 *
144 * If the slave needs to stall the transaction (for instance it is not
145 * ready to send the register value to the master), it sets the MOSI
146 * line to 0 during the last clock of the 4 byte header. In this case
147 * the master is supposed to start polling the SPI bus, one byte at
148 * time, until the last bit in the received byte (transferred during
149 * the last clock of the byte) is set to 1.
150 *
151 * Due to some SPI controllers' shortcomings (Rockchip comes to
152 * mind...) we trasmit the 4 byte header without checking the byte
153 * transmitted by the TPM during the transaction's last byte.
154 *
155 * We know that cr50 is guaranteed to set the flow control bit to 0
156 * during the header transfer, but real TPM2 might be fast enough not
157 * to require to stall the master, this would present an issue.
158 * crosbug.com/p/52132 has been opened to track this.
159 */
160 tpm_if.xfer(tpm_if.slave, header.body, sizeof(header.body), NULL, 0);
161
162 /* Now poll the bus until TPM removes the stall bit. */
163 do {
164 tpm_if.xfer(tpm_if.slave, NULL, 0, &byte, 1);
165 } while (!(byte & 1));
166}
167
168/*
169 * Print out the contents of a buffer, if debug is enabled. Skip registers
170 * other than FIFO, unless debug_level_ is 2.
171 */
172static void trace_dump(const char *prefix, uint32_t reg,
173 size_t bytes, const uint8_t *buffer,
174 int force)
175{
176 static char prev_prefix;
177 static unsigned prev_reg;
178 static int current_char;
179 const int BYTES_PER_LINE = 32;
180
181 if (!force) {
182 if (!debug_level_)
183 return;
184
185 if ((debug_level_ < 2) && (reg != TPM_DATA_FIFO_REG))
186 return;
187 }
188
189 /*
190 * Do not print register address again if the last dump print was for
191 * that register.
192 */
193 if ((prev_prefix != *prefix) || (prev_reg != reg)) {
194 prev_prefix = *prefix;
195 prev_reg = reg;
196 printk(BIOS_DEBUG, "\n%s %2.2x:", prefix, reg);
197 current_char = 0;
198 }
199
200 if ((reg != TPM_DATA_FIFO_REG) && (bytes == 4)) {
201 /*
202 * This must be a regular register address, print the 32 bit
203 * value.
204 */
205 printk(BIOS_DEBUG, " %8.8x", *(const uint32_t *)buffer);
206 } else {
207 int i;
208
209 /*
210 * Data read from or written to FIFO or not in 4 byte
211 * quantiites is printed byte at a time.
212 */
213 for (i = 0; i < bytes; i++) {
214 if (current_char && !(current_char % BYTES_PER_LINE)) {
215 printk(BIOS_DEBUG, "\n ");
216 current_char = 0;
217 }
218 current_char++;
219 printk(BIOS_DEBUG, " %2.2x", buffer[i]);
220 }
221 }
222}
223
224/*
225 * Once transaction is initiated and the TPM indicated that it is ready to go,
226 * write the actual bytes to the register.
227 */
228static void write_bytes(const void *buffer, size_t bytes)
229{
230 tpm_if.xfer(tpm_if.slave, buffer, bytes, NULL, 0);
231}
232
233/*
234 * Once transaction is initiated and the TPM indicated that it is ready to go,
235 * read the actual bytes from the register.
236 */
237static void read_bytes(void *buffer, size_t bytes)
238{
239 tpm_if.xfer(tpm_if.slave, NULL, 0, buffer, bytes);
240}
241
242/*
243 * To write a register, start transaction, transfer data to the TPM, deassert
244 * CS when done.
245 *
246 * Returns one to indicate success, zero (not yet implemented) to indicate
247 * failure.
248 */
249static int tpm2_write_reg(unsigned reg_number, const void *buffer, size_t bytes)
250{
251 trace_dump("W", reg_number, bytes, buffer, 0);
252 start_transaction(false, bytes, reg_number);
253 write_bytes(buffer, bytes);
254 tpm_if.cs_deassert(tpm_if.slave);
255 return 1;
256}
257
258/*
259 * To read a register, start transaction, transfer data from the TPM, deassert
260 * CS when done.
261 *
262 * Returns one to indicate success, zero (not yet implemented) to indicate
263 * failure.
264 */
265static int tpm2_read_reg(unsigned reg_number, void *buffer, size_t bytes)
266{
267 start_transaction(true, bytes, reg_number);
268 read_bytes(buffer, bytes);
269 tpm_if.cs_deassert(tpm_if.slave);
270 trace_dump("R", reg_number, bytes, buffer, 0);
271 return 1;
272}
273
274/*
275 * Status register is accessed often, wrap reading and writing it into
276 * dedicated functions.
277 */
278static int read_tpm_sts(uint32_t *status)
279{
280 return tpm2_read_reg(TPM_STS_REG, status, sizeof(*status));
281}
282
283static int write_tpm_sts(uint32_t status)
284{
285 return tpm2_write_reg(TPM_STS_REG, &status, sizeof(status));
286}
287
288/*
289 * The TPM may limit the transaction bytes count (burst count) below the 64
290 * bytes max. The current value is available as a field of the status
291 * register.
292 */
293static uint32_t get_burst_count(void)
294{
295 uint32_t status;
296
297 read_tpm_sts(&status);
298 return (status >> burst_count_shift) & burst_count_mask;
299}
300
301int tpm2_init(struct spi_slave *spi_if)
302{
303 uint32_t did_vid, status;
304 uint8_t cmd;
305
306 tpm_if.slave = spi_if;
307
308 tpm2_read_reg(TPM_DID_VID_REG, &did_vid, sizeof(did_vid));
309
310 /* Try claiming locality zero. */
311 tpm2_read_reg(TPM_ACCESS_REG, &cmd, sizeof(cmd));
312 if ((cmd & (active_locality & tpm_reg_valid_sts)) ==
313 (active_locality & tpm_reg_valid_sts)) {
314 /*
315 * Locality active - maybe reset line is not connected?
316 * Release the locality and try again
317 */
318 cmd = active_locality;
319 tpm2_write_reg(TPM_ACCESS_REG, &cmd, sizeof(cmd));
320 tpm2_read_reg(TPM_ACCESS_REG, &cmd, sizeof(cmd));
321 }
322
323 /* The tpm_establishment bit can be either set or not, ignore it. */
324 if ((cmd & ~tpm_establishment) != tpm_reg_valid_sts) {
325 printk(BIOS_ERR, "invalid reset status: %#x\n", cmd);
326 return -1;
327 }
328
329 cmd = request_use;
330 tpm2_write_reg(TPM_ACCESS_REG, &cmd, sizeof(cmd));
331 tpm2_read_reg(TPM_ACCESS_REG, &cmd, sizeof(cmd));
332 if ((cmd & ~tpm_establishment) !=
333 (tpm_reg_valid_sts | active_locality)) {
334 printk(BIOS_ERR, "failed to claim locality 0, status: %#x\n",
335 cmd);
336 return -1;
337 }
338
339 read_tpm_sts(&status);
340 if (((status >> tpm_family_shift) & tpm_family_mask) !=
341 tpm_family_tpm2) {
342 printk(BIOS_ERR, "unexpected TPM family value, status: %#x\n",
343 status);
344 return -1;
345 }
346
347 /*
348 * Locality claimed, read the revision value and set up the tpm_info
349 * structure.
350 */
351 tpm2_read_reg(TPM_RID_REG, &cmd, sizeof(cmd));
352 tpm_info.vendor_id = did_vid & 0xffff;
353 tpm_info.device_id = did_vid >> 16;
354 tpm_info.revision = cmd;
355
356 printk(BIOS_INFO, "Connected to device vid:did:rid of %4.4x:%4.4x:%2.2x\n",
357 tpm_info.vendor_id, tpm_info.device_id, tpm_info.revision);
358
Vadim Bendebury58826fc2016-06-23 18:17:33 -0700359 /* Let's report device FW version if available. */
360 if (tpm_info.vendor_id == 0x1ae0) {
361 int chunk_count = 0;
362 uint32_t chunk = 0;
363 char vstr[sizeof(chunk) + 1]; /* room for 4 chars + zero */
364
365 printk(BIOS_INFO, "Firmware version: ");
366
367 /*
368 * Does not really matter what's written, this just makes sure
369 * the version is reported from the beginning.
370 */
371 tpm2_write_reg(TPM_FW_VER, &chunk, sizeof(chunk));
372
373 /* Print it out in 4 byte chunks. */
374 vstr[sizeof(vstr) - 1] = 0;
375 do {
376 tpm2_read_reg(TPM_FW_VER, vstr, sizeof(chunk));
377 printk(BIOS_INFO, "%s", vstr);
378
379 /*
380 * While string is not over, and no more than 200
381 * characters.
382 * This is likely result in one extra printk()
383 * invocation with an empty string, not a big deal.
384 */
385 } while (vstr[0] && (chunk_count++ < (200 / sizeof(chunk))));
386
387 printk(BIOS_INFO, "\n");
388 }
Vadim Bendeburye31d2432016-04-09 18:33:49 -0700389 return 0;
390}
391
392/*
393 * This is in seconds, certain TPM commands, like key generation, can take
394 * long time to complete.
395 *
396 * Returns one to indicate success, zero (not yet implemented) to indicate
397 * failure.
398 */
399#define MAX_STATUS_TIMEOUT 120
400static int wait_for_status(uint32_t status_mask, uint32_t status_expected)
401{
402 uint32_t status;
403 struct stopwatch sw;
404
405 stopwatch_init_usecs_expire(&sw, MAX_STATUS_TIMEOUT * 1000 * 1000);
406 do {
407 udelay(1000);
408 if (stopwatch_expired(&sw)) {
409 printk(BIOS_ERR, "failed to get expected status %x\n",
410 status_expected);
411 return false;
412 }
413 read_tpm_sts(&status);
414 } while ((status & status_mask) != status_expected);
415
416 return 1;
417}
418
419enum fifo_transfer_direction {
420 fifo_transmit = 0,
421 fifo_receive = 1
422};
423
424/* Union allows to avoid casting away 'const' on transmit buffers. */
425union fifo_transfer_buffer {
426 uint8_t *rx_buffer;
427 const uint8_t *tx_buffer;
428};
429
430/*
431 * Transfer requested number of bytes to or from TPM FIFO, accounting for the
432 * current burst count value.
433 */
434static void fifo_transfer(size_t transfer_size,
435 union fifo_transfer_buffer buffer,
436 enum fifo_transfer_direction direction)
437{
438 size_t transaction_size;
439 size_t burst_count;
440 size_t handled_so_far = 0;
441
442 do {
443 do {
444 /* Could be zero when TPM is busy. */
445 burst_count = get_burst_count();
446 } while (!burst_count);
447
448 transaction_size = transfer_size - handled_so_far;
449 transaction_size = MIN(transaction_size, burst_count);
450
451 /*
452 * The SPI frame header does not allow to pass more than 64
453 * bytes.
454 */
455 transaction_size = MIN(transaction_size, 64);
456
457 if (direction == fifo_receive)
458 tpm2_read_reg(TPM_DATA_FIFO_REG,
459 buffer.rx_buffer + handled_so_far,
460 transaction_size);
461 else
462 tpm2_write_reg(TPM_DATA_FIFO_REG,
463 buffer.tx_buffer + handled_so_far,
464 transaction_size);
465
466 handled_so_far += transaction_size;
467
468 } while (handled_so_far != transfer_size);
469}
470
471size_t tpm2_process_command(const void *tpm2_command, size_t command_size,
472 void *tpm2_response, size_t max_response)
473{
474 uint32_t status;
475 uint32_t expected_status_bits;
476 size_t payload_size;
477 size_t bytes_to_go;
478 const uint8_t *cmd_body = tpm2_command;
479 uint8_t *rsp_body = tpm2_response;
480 union fifo_transfer_buffer fifo_buffer;
481 const int HEADER_SIZE = 6;
482
483 /* Skip the two byte tag, read the size field. */
484 payload_size = read_be32(cmd_body + 2);
485
486 /* Sanity check. */
487 if (payload_size != command_size) {
488 printk(BIOS_ERR,
489 "Command size mismatch: encoded %zd != requested %zd\n",
490 payload_size, command_size);
491 trace_dump("W", TPM_DATA_FIFO_REG, command_size, cmd_body, 1);
492 printk(BIOS_DEBUG, "\n");
493 return 0;
494 }
495
496 /* Let the TPM know that the command is coming. */
497 write_tpm_sts(command_ready);
498
499 /*
500 * Tpm commands and responses written to and read from the FIFO
501 * register (0x24) are datagrams of variable size, prepended by a 6
502 * byte header.
503 *
504 * The specification description of the state machine is a bit vague,
505 * but from experience it looks like there is no need to wait for the
506 * sts.expect bit to be set, at least with the 9670 and cr50 devices.
507 * Just write the command into FIFO, making sure not to exceed the
508 * burst count or the maximum PDU size, whatever is smaller.
509 */
510 fifo_buffer.tx_buffer = cmd_body;
511 fifo_transfer(command_size, fifo_buffer, fifo_transmit);
512
513 /* Now tell the TPM it can start processing the command. */
514 write_tpm_sts(tpm_go);
515
516 /* Now wait for it to report that the response is ready. */
517 expected_status_bits = sts_valid | data_avail;
518 if (!wait_for_status(expected_status_bits, expected_status_bits)) {
519 /*
520 * If timed out, which should never happen, let's at least
521 * print out the offending command.
522 */
523 trace_dump("W", TPM_DATA_FIFO_REG, command_size, cmd_body, 1);
524 printk(BIOS_DEBUG, "\n");
525 return 0;
526 }
527
528 /*
529 * The response is ready, let's read it. First we read the FIFO
530 * payload header, to see how much data to expect. The response header
531 * size is fixed to six bytes, the total payload size is stored in
532 * network order in the last four bytes.
533 */
534 tpm2_read_reg(TPM_DATA_FIFO_REG, rsp_body, HEADER_SIZE);
535
536 /* Find out the total payload size, skipping the two byte tag. */
537 payload_size = read_be32(rsp_body + 2);
538
539 if (payload_size > max_response) {
540 /*
541 * TODO(vbendeb): at least drain the FIFO here or somehow let
542 * the TPM know that the response can be dropped.
543 */
544 printk(BIOS_ERR, " tpm response too long (%zd bytes)",
545 payload_size);
546 return 0;
547 }
548
549 /*
550 * Now let's read all but the last byte in the FIFO to make sure the
551 * status register is showing correct flow control bits: 'more data'
552 * until the last byte and then 'no more data' once the last byte is
553 * read.
554 */
555 bytes_to_go = payload_size - 1 - HEADER_SIZE;
556 fifo_buffer.rx_buffer = rsp_body + HEADER_SIZE;
557 fifo_transfer(bytes_to_go, fifo_buffer, fifo_receive);
558
559 /* Verify that there is still data to read. */
560 read_tpm_sts(&status);
561 if ((status & expected_status_bits) != expected_status_bits) {
562 printk(BIOS_ERR, "unexpected intermediate status %#x\n",
563 status);
564 return 0;
565 }
566
567 /* Read the last byte of the PDU. */
568 tpm2_read_reg(TPM_DATA_FIFO_REG, rsp_body + payload_size - 1, 1);
569
570 /* Terminate the dump, if enabled. */
571 if (debug_level_)
572 printk(BIOS_DEBUG, "\n");
573
574 /* Verify that 'data available' is not asseretd any more. */
575 read_tpm_sts(&status);
576 if ((status & expected_status_bits) != sts_valid) {
577 printk(BIOS_ERR, "unexpected final status %#x\n", status);
578 return 0;
579 }
580
581 /* Move the TPM back to idle state. */
582 write_tpm_sts(command_ready);
583
584 return payload_size;
585}