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