test: stabilize test_efi_secboot
[platform/kernel/u-boot.git] / drivers / tpm / cr50_i2c.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Cr50 / H1 TPM support
4  *
5  * Copyright 2018 Google LLC
6  */
7
8 #define LOG_CATEGORY UCLASS_TPM
9
10 #include <common.h>
11 #include <dm.h>
12 #include <i2c.h>
13 #include <irq.h>
14 #include <spl.h>
15 #include <tpm-v2.h>
16 #include <asm/gpio.h>
17 #include <asm/io.h>
18 #include <asm/arch/iomap.h>
19 #include <asm/arch/pm.h>
20
21 enum {
22         TIMEOUT_INIT_MS         = 30000, /* Very long timeout for TPM init */
23         TIMEOUT_LONG_US         = 2 * 1000 * 1000,
24         TIMEOUT_SHORT_US        = 2 * 1000,
25         TIMEOUT_NO_IRQ_US       = 20 * 1000,
26         TIMEOUT_IRQ_US          = 100 * 1000,
27 };
28
29 enum {
30         CR50_DID_VID = 0x00281ae0L
31 };
32
33 enum {
34         CR50_MAX_BUF_SIZE = 63,
35 };
36
37 /**
38  * struct cr50_priv - Private driver data
39  *
40  * @ready_gpio: GPIO to use to check if the TPM is ready
41  * @irq: IRQ to use check if the TPM is ready (has priority over @ready_gpio)
42  * @locality: Currenttly claimed locality (-1 if none)
43  * @vendor: vendor: Vendor ID for TPM
44  * @use_irq: true to use @irq, false to use @ready if available
45  */
46 struct cr50_priv {
47         struct gpio_desc ready_gpio;
48         struct irq irq;
49         int locality;
50         uint vendor;
51         bool use_irq;
52 };
53
54 /* Wait for interrupt to indicate TPM is ready */
55 static int cr50_i2c_wait_tpm_ready(struct udevice *dev)
56 {
57         struct cr50_priv *priv = dev_get_priv(dev);
58         ulong timeout, base;
59         int i;
60
61         if (!priv->use_irq && !dm_gpio_is_valid(&priv->ready_gpio)) {
62                 /* Fixed delay if interrupt not supported */
63                 udelay(TIMEOUT_NO_IRQ_US);
64                 return 0;
65         }
66
67         base = timer_get_us();
68         timeout = base + TIMEOUT_IRQ_US;
69
70         i = 0;
71         while (priv->use_irq ? !irq_read_and_clear(&priv->irq) :
72                !dm_gpio_get_value(&priv->ready_gpio)) {
73                 i++;
74                 if ((int)(timer_get_us() - timeout) >= 0) {
75                         log_warning("Timeout\n");
76                         /* Use this instead of the -ETIMEDOUT used by i2c */
77                         return -ETIME;
78                 }
79         }
80         log_debug("i=%d\n", i);
81
82         return 0;
83 }
84
85 /* Clear pending interrupts */
86 static void cr50_i2c_clear_tpm_irq(struct udevice *dev)
87 {
88         struct cr50_priv *priv = dev_get_priv(dev);
89
90         if (priv->use_irq)
91                 irq_read_and_clear(&priv->irq);
92 }
93
94 /*
95  * cr50_i2c_read() - read from TPM register
96  *
97  * @dev: TPM chip information
98  * @addr: register address to read from
99  * @buffer: provided by caller
100  * @len: number of bytes to read
101  *
102  * 1) send register address byte 'addr' to the TPM
103  * 2) wait for TPM to indicate it is ready
104  * 3) read 'len' bytes of TPM response into the provided 'buffer'
105  *
106  * Return 0 on success. -ve on error
107  */
108 static int cr50_i2c_read(struct udevice *dev, u8 addr, u8 *buffer,
109                          size_t len)
110 {
111         int ret;
112
113         /* Clear interrupt before starting transaction */
114         cr50_i2c_clear_tpm_irq(dev);
115
116         /* Send the register address byte to the TPM */
117         ret = dm_i2c_write(dev, 0, &addr, 1);
118         if (ret) {
119                 log_err("Address write failed (err=%d)\n", ret);
120                 return ret;
121         }
122
123         /* Wait for TPM to be ready with response data */
124         ret = cr50_i2c_wait_tpm_ready(dev);
125         if (ret)
126                 return ret;
127
128         /* Read response data frrom the TPM */
129         ret = dm_i2c_read(dev, 0, buffer, len);
130         if (ret) {
131                 log_err("Read response failed (err=%d)\n", ret);
132                 return ret;
133         }
134
135         return 0;
136 }
137
138 /*
139  * cr50_i2c_write() - write to TPM register
140  *
141  * @dev: TPM chip information
142  * @addr: register address to write to
143  * @buffer: data to write
144  * @len: number of bytes to write
145  *
146  * 1) prepend the provided address to the provided data
147  * 2) send the address+data to the TPM
148  * 3) wait for TPM to indicate it is done writing
149  *
150  * Returns -1 on error, 0 on success.
151  */
152 static int cr50_i2c_write(struct udevice *dev, u8 addr, const u8 *buffer,
153                           size_t len)
154 {
155         u8 buf[len + 1];
156         int ret;
157
158         if (len > CR50_MAX_BUF_SIZE) {
159                 log_err("Length %zd is too large\n", len);
160                 return -E2BIG;
161         }
162
163         /* Prepend the 'register address' to the buffer */
164         buf[0] = addr;
165         memcpy(buf + 1, buffer, len);
166
167         /* Clear interrupt before starting transaction */
168         cr50_i2c_clear_tpm_irq(dev);
169
170         /* Send write request buffer with address */
171         ret = dm_i2c_write(dev, 0, buf, len + 1);
172         if (ret) {
173                 log_err("Error writing to TPM (err=%d)\n", ret);
174                 return ret;
175         }
176
177         /* Wait for TPM to be ready */
178         return cr50_i2c_wait_tpm_ready(dev);
179 }
180
181 static inline u8 tpm_access(u8 locality)
182 {
183         return 0x0 | (locality << 4);
184 }
185
186 static inline u8 tpm_sts(u8 locality)
187 {
188         return 0x1 | (locality << 4);
189 }
190
191 static inline u8 tpm_data_fifo(u8 locality)
192 {
193         return 0x5 | (locality << 4);
194 }
195
196 static inline u8 tpm_did_vid(u8 locality)
197 {
198         return 0x6 | (locality << 4);
199 }
200
201 static int release_locality(struct udevice *dev, int force)
202 {
203         struct cr50_priv *priv = dev_get_priv(dev);
204         u8 mask = TPM_ACCESS_VALID | TPM_ACCESS_REQUEST_PENDING;
205         u8 addr = tpm_access(priv->locality);
206         int ret;
207         u8 buf;
208
209         ret = cr50_i2c_read(dev, addr, &buf, 1);
210         if (ret)
211                 return ret;
212
213         if (force || (buf & mask) == mask) {
214                 buf = TPM_ACCESS_ACTIVE_LOCALITY;
215                 cr50_i2c_write(dev, addr, &buf, 1);
216         }
217
218         priv->locality = -1;
219
220         return 0;
221 }
222
223 /* cr50 requires all 4 bytes of status register to be read */
224 static int cr50_i2c_status(struct udevice *dev)
225 {
226         struct cr50_priv *priv = dev_get_priv(dev);
227         u8 buf[4];
228         int ret;
229
230         ret = cr50_i2c_read(dev, tpm_sts(priv->locality), buf, sizeof(buf));
231         if (ret) {
232                 log_warning("%s: Failed to read status\n", __func__);
233                 return ret;
234         }
235
236         return buf[0];
237 }
238
239 /* cr50 requires all 4 bytes of status register to be written */
240 static int cr50_i2c_ready(struct udevice *dev)
241 {
242         struct cr50_priv *priv = dev_get_priv(dev);
243         u8 buf[4] = { TPM_STS_COMMAND_READY };
244         int ret;
245
246         ret = cr50_i2c_write(dev, tpm_sts(priv->locality), buf, sizeof(buf));
247         if (ret)
248                 return ret;
249
250         udelay(TIMEOUT_SHORT_US);
251
252         return 0;
253 }
254
255 static int cr50_i2c_wait_burststs(struct udevice *dev, u8 mask,
256                                   size_t *burst, int *status)
257 {
258         struct cr50_priv *priv = dev_get_priv(dev);
259         ulong timeout;
260         u32 buf;
261
262         /*
263          * cr50 uses bytes 3:2 of status register for burst count and all 4
264          * bytes must be read
265          */
266         timeout = timer_get_us() + TIMEOUT_LONG_US;
267         while (timer_get_us() < timeout) {
268                 if (cr50_i2c_read(dev, tpm_sts(priv->locality),
269                                   (u8 *)&buf, sizeof(buf)) < 0) {
270                         udelay(TIMEOUT_SHORT_US);
271                         continue;
272                 }
273
274                 *status = buf & 0xff;
275                 *burst = le16_to_cpu((buf >> 8) & 0xffff);
276
277                 if ((*status & mask) == mask &&
278                     *burst > 0 && *burst <= CR50_MAX_BUF_SIZE)
279                         return 0;
280
281                 udelay(TIMEOUT_SHORT_US);
282         }
283
284         log_warning("Timeout reading burst and status\n");
285
286         return -ETIMEDOUT;
287 }
288
289 static int cr50_i2c_recv(struct udevice *dev, u8 *buf, size_t buf_len)
290 {
291         struct cr50_priv *priv = dev_get_priv(dev);
292         size_t burstcnt, expected, current, len;
293         u8 addr = tpm_data_fifo(priv->locality);
294         u8 mask = TPM_STS_VALID | TPM_STS_DATA_AVAIL;
295         u32 expected_buf;
296         int status;
297         int ret;
298
299         log_debug("%s: len=%x\n", __func__, buf_len);
300         if (buf_len < TPM_HEADER_SIZE)
301                 return -E2BIG;
302
303         ret = cr50_i2c_wait_burststs(dev, mask, &burstcnt, &status);
304         if (ret < 0) {
305                 log_warning("First chunk not available\n");
306                 goto out_err;
307         }
308
309         /* Read first chunk of burstcnt bytes */
310         if (cr50_i2c_read(dev, addr, buf, burstcnt) < 0) {
311                 log_warning("Read failed\n");
312                 goto out_err;
313         }
314
315         /* Determine expected data in the return buffer */
316         memcpy(&expected_buf, buf + TPM_CMD_COUNT_OFFSET, sizeof(expected_buf));
317         expected = be32_to_cpu(expected_buf);
318         if (expected > buf_len) {
319                 log_warning("Too much data: %zu > %zu\n", expected, buf_len);
320                 goto out_err;
321         }
322
323         /* Now read the rest of the data */
324         current = burstcnt;
325         while (current < expected) {
326                 /* Read updated burst count and check status */
327                 if (cr50_i2c_wait_burststs(dev, mask, &burstcnt, &status) < 0) {
328                         log_warning("- burst failure1\n");
329                         goto out_err;
330                         }
331
332                 len = min(burstcnt, expected - current);
333                 if (cr50_i2c_read(dev, addr, buf + current, len) != 0) {
334                         log_warning("Read failed\n");
335                         goto out_err;
336                 }
337
338                 current += len;
339         }
340
341         if (cr50_i2c_wait_burststs(dev, TPM_STS_VALID, &burstcnt,
342                                    &status) < 0) {
343                 log_warning("- burst failure2\n");
344                 goto out_err;
345         }
346         if (status & TPM_STS_DATA_AVAIL) {
347                 log_warning("Data still available\n");
348                 goto out_err;
349         }
350
351         return current;
352
353 out_err:
354         /* Abort current transaction if still pending */
355         ret = cr50_i2c_status(dev);
356         if (ret < 0)
357                 return ret;
358         if (ret & TPM_STS_COMMAND_READY) {
359                 ret = cr50_i2c_ready(dev);
360                 if (ret)
361                         return ret;
362         }
363
364         return -EIO;
365 }
366
367 static int cr50_i2c_send(struct udevice *dev, const u8 *buf, size_t len)
368 {
369         struct cr50_priv *priv = dev_get_priv(dev);
370
371         int status;
372         size_t burstcnt, limit, sent = 0;
373         u8 tpm_go[4] = { TPM_STS_GO };
374         ulong timeout;
375         int ret;
376
377         log_debug("%s: len=%x\n", __func__, len);
378         timeout = timer_get_us() + TIMEOUT_LONG_US;
379         do {
380                 ret = cr50_i2c_status(dev);
381                 if (ret < 0)
382                         goto out_err;
383                 if (ret & TPM_STS_COMMAND_READY)
384                         break;
385
386                 if (timer_get_us() > timeout)
387                         goto out_err;
388
389                 ret = cr50_i2c_ready(dev);
390                 if (ret)
391                         goto out_err;
392         } while (1);
393
394         while (len > 0) {
395                 u8 mask = TPM_STS_VALID;
396
397                 /* Wait for data if this is not the first chunk */
398                 if (sent > 0)
399                         mask |= TPM_STS_DATA_EXPECT;
400
401                 if (cr50_i2c_wait_burststs(dev, mask, &burstcnt, &status) < 0)
402                         goto out_err;
403
404                 /*
405                  * Use burstcnt - 1 to account for the address byte
406                  * that is inserted by cr50_i2c_write()
407                  */
408                 limit = min(burstcnt - 1, len);
409                 if (cr50_i2c_write(dev, tpm_data_fifo(priv->locality),
410                                    &buf[sent], limit) != 0) {
411                         log_warning("Write failed\n");
412                         goto out_err;
413                 }
414
415                 sent += limit;
416                 len -= limit;
417         }
418
419         /* Ensure TPM is not expecting more data */
420         if (cr50_i2c_wait_burststs(dev, TPM_STS_VALID, &burstcnt, &status) < 0)
421                 goto out_err;
422         if (status & TPM_STS_DATA_EXPECT) {
423                 log_warning("Data still expected\n");
424                 goto out_err;
425         }
426
427         /* Start the TPM command */
428         ret = cr50_i2c_write(dev, tpm_sts(priv->locality), tpm_go,
429                              sizeof(tpm_go));
430         if (ret) {
431                 log_warning("Start command failed\n");
432                 goto out_err;
433         }
434
435         return sent;
436
437 out_err:
438         /* Abort current transaction if still pending */
439         ret = cr50_i2c_status(dev);
440
441         if (ret < 0 || (ret & TPM_STS_COMMAND_READY)) {
442                 ret = cr50_i2c_ready(dev);
443                 if (ret)
444                         return ret;
445         }
446
447         return -EIO;
448 }
449
450 /**
451  * process_reset() - Wait for the Cr50 to reset
452  *
453  * Cr50 processes reset requests asynchronously and conceivably could be busy
454  * executing a long command and not reacting to the reset pulse for a while.
455  *
456  * This function will make sure that the AP does not proceed with boot until
457  * TPM finished reset processing.
458  *
459  * @dev: Cr50 device
460  * @return 0 if OK, -EPERM if locality could not be taken
461  */
462 static int process_reset(struct udevice *dev)
463 {
464         const int loc = 0;
465         u8 access;
466         ulong start;
467
468         /*
469          * Locality is released by TPM reset.
470          *
471          * If locality is taken at this point, this could be due to the fact
472          * that the TPM is performing a long operation and has not processed
473          * reset request yet. We'll wait up to CR50_TIMEOUT_INIT_MS and see if
474          * it releases locality when reset is processed.
475          */
476         start = get_timer(0);
477         do {
478                 const u8 mask = TPM_ACCESS_VALID | TPM_ACCESS_ACTIVE_LOCALITY;
479                 int ret;
480
481                 ret = cr50_i2c_read(dev, tpm_access(loc),
482                                     &access, sizeof(access));
483                 if (ret || ((access & mask) == mask)) {
484                         /*
485                          * Don't bombard the chip with traffic; let it keep
486                          * processing the command.
487                          */
488                         mdelay(2);
489                         continue;
490                 }
491
492                 log_warning("TPM ready after %ld ms\n", get_timer(start));
493
494                 return 0;
495         } while (get_timer(start) < TIMEOUT_INIT_MS);
496
497         log_warning("TPM failed to reset after %ld ms, status: %#x\n",
498                     get_timer(start), access);
499
500         return -EPERM;
501 }
502
503 /*
504  * Locality could be already claimed (if this is a later U-Boot phase and the
505  * read-only U-Boot did not release it), or not yet claimed, if this is TPL or
506  * the older read-only U-Boot did release it.
507  */
508 static int claim_locality(struct udevice *dev, int loc)
509 {
510         const u8 mask = TPM_ACCESS_VALID | TPM_ACCESS_ACTIVE_LOCALITY;
511         struct cr50_priv *priv = dev_get_priv(dev);
512         u8 access;
513         int ret;
514
515         ret = cr50_i2c_read(dev, tpm_access(loc), &access, sizeof(access));
516         if (ret)
517                 return log_msg_ret("read1", ret);
518
519         if ((access & mask) == mask) {
520                 log_warning("Locality already claimed\n");
521                 return 0;
522         }
523
524         access = TPM_ACCESS_REQUEST_USE;
525         ret = cr50_i2c_write(dev, tpm_access(loc), &access, sizeof(access));
526         if (ret)
527                 return log_msg_ret("write", ret);
528
529         ret = cr50_i2c_read(dev, tpm_access(loc), &access, sizeof(access));
530         if (ret)
531                 return log_msg_ret("read2", ret);
532
533         if ((access & mask) != mask) {
534                 log_err("Failed to claim locality\n");
535                 return -EPERM;
536         }
537         log_info("Claimed locality %d\n", loc);
538         priv->locality = loc;
539
540         return 0;
541 }
542
543 static int cr50_i2c_get_desc(struct udevice *dev, char *buf, int size)
544 {
545         struct dm_i2c_chip *chip = dev_get_parent_platdata(dev);
546         struct cr50_priv *priv = dev_get_priv(dev);
547
548         return snprintf(buf, size, "cr50 TPM 2.0 (i2c %02x id %x) irq=%d",
549                         chip->chip_addr, priv->vendor >> 16, priv->use_irq);
550 }
551
552 static int cr50_i2c_open(struct udevice *dev)
553 {
554         char buf[80];
555         int ret;
556
557         ret = process_reset(dev);
558         if (ret)
559                 return log_msg_ret("reset", ret);
560
561         ret = claim_locality(dev, 0);
562         if (ret)
563                 return log_msg_ret("claim", ret);
564
565         cr50_i2c_get_desc(dev, buf, sizeof(buf));
566         log_debug("%s\n", buf);
567
568         return 0;
569 }
570
571 static int cr50_i2c_cleanup(struct udevice *dev)
572 {
573         struct cr50_priv *priv = dev_get_priv(dev);
574
575         printf("%s: cleanup %d\n", __func__, priv->locality);
576         if (priv->locality != -1)
577                 release_locality(dev, 1);
578
579         return 0;
580 }
581
582 enum {
583         TPM_TIMEOUT_MS          = 5,
584         SHORT_TIMEOUT_MS        = 750,
585         LONG_TIMEOUT_MS         = 2000,
586 };
587
588 static int cr50_i2c_ofdata_to_platdata(struct udevice *dev)
589 {
590         struct tpm_chip_priv *upriv = dev_get_uclass_priv(dev);
591         struct cr50_priv *priv = dev_get_priv(dev);
592         struct irq irq;
593         int ret;
594
595         upriv->version = TPM_V2;
596         upriv->duration_ms[TPM_SHORT] = SHORT_TIMEOUT_MS;
597         upriv->duration_ms[TPM_MEDIUM] = LONG_TIMEOUT_MS;
598         upriv->duration_ms[TPM_LONG] = LONG_TIMEOUT_MS;
599         upriv->retry_time_ms = TPM_TIMEOUT_MS;
600
601         upriv->pcr_count = 32;
602         upriv->pcr_select_min = 2;
603
604         /* Optional GPIO to track when cr50 is ready */
605         ret = irq_get_by_index(dev, 0, &irq);
606         if (!ret) {
607                 priv->irq = irq;
608                 priv->use_irq = true;
609         } else {
610                 ret = gpio_request_by_name(dev, "ready-gpios", 0,
611                                            &priv->ready_gpio, GPIOD_IS_IN);
612                 if (ret) {
613                         log_warning("Cr50 does not have an ready GPIO/interrupt (err=%d)\n",
614                                     ret);
615                 }
616         }
617
618         return 0;
619 }
620
621 static int cr50_i2c_probe(struct udevice *dev)
622 {
623         struct cr50_priv *priv = dev_get_priv(dev);
624         u32 vendor = 0;
625         ulong start;
626
627         /*
628          * 150ms should be enough to synchronise with the TPM even under the
629          * worst nested-reset-request conditions. In the vast majority of cases
630          * there will be no wait at all.
631          */
632         start = get_timer(0);
633         while (get_timer(start) < 150) {
634                 int ret;
635
636                 /* Exit once DID and VID verified */
637                 ret = cr50_i2c_read(dev, tpm_did_vid(0), (u8 *)&vendor, 4);
638                 if (!ret && vendor == CR50_DID_VID)
639                         break;
640
641                 /* TPM might be resetting; let's retry in a bit */
642                 mdelay(10);
643         }
644         if (vendor != CR50_DID_VID) {
645                 log_debug("DID_VID %08x not recognised\n", vendor);
646                 return log_msg_ret("vendor-id", -EXDEV);
647         }
648         priv->vendor = vendor;
649         priv->locality = -1;
650
651         return 0;
652 }
653
654 static const struct tpm_ops cr50_i2c_ops = {
655         .open           = cr50_i2c_open,
656         .get_desc       = cr50_i2c_get_desc,
657         .send           = cr50_i2c_send,
658         .recv           = cr50_i2c_recv,
659         .cleanup        = cr50_i2c_cleanup,
660 };
661
662 static const struct udevice_id cr50_i2c_ids[] = {
663         { .compatible = "google,cr50" },
664         { }
665 };
666
667 U_BOOT_DRIVER(cr50_i2c) = {
668         .name   = "cr50_i2c",
669         .id     = UCLASS_TPM,
670         .of_match = cr50_i2c_ids,
671         .ops    = &cr50_i2c_ops,
672         .ofdata_to_platdata     = cr50_i2c_ofdata_to_platdata,
673         .probe  = cr50_i2c_probe,
674         .remove = cr50_i2c_cleanup,
675         .priv_auto_alloc_size = sizeof(struct cr50_priv),
676         .flags          = DM_FLAG_OS_PREPARE,
677 };