]> git.kernelconcepts.de Git - karo-tx-uboot.git/blob - drivers/misc/cros_ec.c
cros_ec: Sync up with latest Chrome OS EC version
[karo-tx-uboot.git] / drivers / misc / cros_ec.c
1 /*
2  * Chromium OS cros_ec driver
3  *
4  * Copyright (c) 2012 The Chromium OS Authors.
5  *
6  * SPDX-License-Identifier:     GPL-2.0+
7  */
8
9 /*
10  * This is the interface to the Chrome OS EC. It provides keyboard functions,
11  * power control and battery management. Quite a few other functions are
12  * provided to enable the EC software to be updated, talk to the EC's I2C bus
13  * and store a small amount of data in a memory which persists while the EC
14  * is not reset.
15  */
16
17 #include <common.h>
18 #include <command.h>
19 #include <i2c.h>
20 #include <cros_ec.h>
21 #include <fdtdec.h>
22 #include <malloc.h>
23 #include <spi.h>
24 #include <asm/io.h>
25 #include <asm-generic/gpio.h>
26
27 #ifdef DEBUG_TRACE
28 #define debug_trace(fmt, b...)  debug(fmt, #b)
29 #else
30 #define debug_trace(fmt, b...)
31 #endif
32
33 enum {
34         /* Timeout waiting for a flash erase command to complete */
35         CROS_EC_CMD_TIMEOUT_MS  = 5000,
36         /* Timeout waiting for a synchronous hash to be recomputed */
37         CROS_EC_CMD_HASH_TIMEOUT_MS = 2000,
38 };
39
40 static struct cros_ec_dev static_dev, *last_dev;
41
42 DECLARE_GLOBAL_DATA_PTR;
43
44 /* Note: depends on enum ec_current_image */
45 static const char * const ec_current_image_name[] = {"unknown", "RO", "RW"};
46
47 void cros_ec_dump_data(const char *name, int cmd, const uint8_t *data, int len)
48 {
49 #ifdef DEBUG
50         int i;
51
52         printf("%s: ", name);
53         if (cmd != -1)
54                 printf("cmd=%#x: ", cmd);
55         for (i = 0; i < len; i++)
56                 printf("%02x ", data[i]);
57         printf("\n");
58 #endif
59 }
60
61 /*
62  * Calculate a simple 8-bit checksum of a data block
63  *
64  * @param data  Data block to checksum
65  * @param size  Size of data block in bytes
66  * @return checksum value (0 to 255)
67  */
68 int cros_ec_calc_checksum(const uint8_t *data, int size)
69 {
70         int csum, i;
71
72         for (i = csum = 0; i < size; i++)
73                 csum += data[i];
74         return csum & 0xff;
75 }
76
77 static int send_command(struct cros_ec_dev *dev, uint8_t cmd, int cmd_version,
78                         const void *dout, int dout_len,
79                         uint8_t **dinp, int din_len)
80 {
81         int ret;
82
83         switch (dev->interface) {
84 #ifdef CONFIG_CROS_EC_SPI
85         case CROS_EC_IF_SPI:
86                 ret = cros_ec_spi_command(dev, cmd, cmd_version,
87                                         (const uint8_t *)dout, dout_len,
88                                         dinp, din_len);
89                 break;
90 #endif
91 #ifdef CONFIG_CROS_EC_I2C
92         case CROS_EC_IF_I2C:
93                 ret = cros_ec_i2c_command(dev, cmd, cmd_version,
94                                         (const uint8_t *)dout, dout_len,
95                                         dinp, din_len);
96                 break;
97 #endif
98 #ifdef CONFIG_CROS_EC_LPC
99         case CROS_EC_IF_LPC:
100                 ret = cros_ec_lpc_command(dev, cmd, cmd_version,
101                                         (const uint8_t *)dout, dout_len,
102                                         dinp, din_len);
103                 break;
104 #endif
105         case CROS_EC_IF_NONE:
106         default:
107                 ret = -1;
108         }
109
110         return ret;
111 }
112
113 /**
114  * Send a command to the CROS-EC device and return the reply.
115  *
116  * The device's internal input/output buffers are used.
117  *
118  * @param dev           CROS-EC device
119  * @param cmd           Command to send (EC_CMD_...)
120  * @param cmd_version   Version of command to send (EC_VER_...)
121  * @param dout          Output data (may be NULL If dout_len=0)
122  * @param dout_len      Size of output data in bytes
123  * @param dinp          Response data (may be NULL If din_len=0).
124  *                      If not NULL, it will be updated to point to the data
125  *                      and will always be double word aligned (64-bits)
126  * @param din_len       Maximum size of response in bytes
127  * @return number of bytes in response, or -1 on error
128  */
129 static int ec_command_inptr(struct cros_ec_dev *dev, uint8_t cmd,
130                 int cmd_version, const void *dout, int dout_len, uint8_t **dinp,
131                 int din_len)
132 {
133         uint8_t *din;
134         int len;
135
136         len = send_command(dev, cmd, cmd_version, dout, dout_len,
137                                 &din, din_len);
138
139         /* If the command doesn't complete, wait a while */
140         if (len == -EC_RES_IN_PROGRESS) {
141                 struct ec_response_get_comms_status *resp;
142                 ulong start;
143
144                 /* Wait for command to complete */
145                 start = get_timer(0);
146                 do {
147                         int ret;
148
149                         mdelay(50);     /* Insert some reasonable delay */
150                         ret = send_command(dev, EC_CMD_GET_COMMS_STATUS, 0,
151                                         NULL, 0,
152                                         (uint8_t **)&resp, sizeof(*resp));
153                         if (ret < 0)
154                                 return ret;
155
156                         if (get_timer(start) > CROS_EC_CMD_TIMEOUT_MS) {
157                                 debug("%s: Command %#02x timeout\n",
158                                       __func__, cmd);
159                                 return -EC_RES_TIMEOUT;
160                         }
161                 } while (resp->flags & EC_COMMS_STATUS_PROCESSING);
162
163                 /* OK it completed, so read the status response */
164                 /* not sure why it was 0 for the last argument */
165                 len = send_command(dev, EC_CMD_RESEND_RESPONSE, 0,
166                                 NULL, 0, &din, din_len);
167         }
168
169         debug("%s: len=%d, dinp=%p, *dinp=%p\n", __func__, len, dinp, *dinp);
170         if (dinp) {
171                 /* If we have any data to return, it must be 64bit-aligned */
172                 assert(len <= 0 || !((uintptr_t)din & 7));
173                 *dinp = din;
174         }
175
176         return len;
177 }
178
179 /**
180  * Send a command to the CROS-EC device and return the reply.
181  *
182  * The device's internal input/output buffers are used.
183  *
184  * @param dev           CROS-EC device
185  * @param cmd           Command to send (EC_CMD_...)
186  * @param cmd_version   Version of command to send (EC_VER_...)
187  * @param dout          Output data (may be NULL If dout_len=0)
188  * @param dout_len      Size of output data in bytes
189  * @param din           Response data (may be NULL If din_len=0).
190  *                      It not NULL, it is a place for ec_command() to copy the
191  *      data to.
192  * @param din_len       Maximum size of response in bytes
193  * @return number of bytes in response, or -1 on error
194  */
195 static int ec_command(struct cros_ec_dev *dev, uint8_t cmd, int cmd_version,
196                       const void *dout, int dout_len,
197                       void *din, int din_len)
198 {
199         uint8_t *in_buffer;
200         int len;
201
202         assert((din_len == 0) || din);
203         len = ec_command_inptr(dev, cmd, cmd_version, dout, dout_len,
204                         &in_buffer, din_len);
205         if (len > 0) {
206                 /*
207                  * If we were asked to put it somewhere, do so, otherwise just
208                  * disregard the result.
209                  */
210                 if (din && in_buffer) {
211                         assert(len <= din_len);
212                         memmove(din, in_buffer, len);
213                 }
214         }
215         return len;
216 }
217
218 int cros_ec_scan_keyboard(struct cros_ec_dev *dev, struct mbkp_keyscan *scan)
219 {
220         if (ec_command(dev, EC_CMD_MKBP_STATE, 0, NULL, 0, scan,
221                        sizeof(scan->data)) < sizeof(scan->data))
222                 return -1;
223
224         return 0;
225 }
226
227 int cros_ec_read_id(struct cros_ec_dev *dev, char *id, int maxlen)
228 {
229         struct ec_response_get_version *r;
230
231         if (ec_command_inptr(dev, EC_CMD_GET_VERSION, 0, NULL, 0,
232                         (uint8_t **)&r, sizeof(*r)) < sizeof(*r))
233                 return -1;
234
235         if (maxlen > sizeof(r->version_string_ro))
236                 maxlen = sizeof(r->version_string_ro);
237
238         switch (r->current_image) {
239         case EC_IMAGE_RO:
240                 memcpy(id, r->version_string_ro, maxlen);
241                 break;
242         case EC_IMAGE_RW:
243                 memcpy(id, r->version_string_rw, maxlen);
244                 break;
245         default:
246                 return -1;
247         }
248
249         id[maxlen - 1] = '\0';
250         return 0;
251 }
252
253 int cros_ec_read_version(struct cros_ec_dev *dev,
254                        struct ec_response_get_version **versionp)
255 {
256         if (ec_command_inptr(dev, EC_CMD_GET_VERSION, 0, NULL, 0,
257                         (uint8_t **)versionp, sizeof(**versionp))
258                         < sizeof(**versionp))
259                 return -1;
260
261         return 0;
262 }
263
264 int cros_ec_read_build_info(struct cros_ec_dev *dev, char **strp)
265 {
266         if (ec_command_inptr(dev, EC_CMD_GET_BUILD_INFO, 0, NULL, 0,
267                         (uint8_t **)strp, EC_PROTO2_MAX_PARAM_SIZE) < 0)
268                 return -1;
269
270         return 0;
271 }
272
273 int cros_ec_read_current_image(struct cros_ec_dev *dev,
274                 enum ec_current_image *image)
275 {
276         struct ec_response_get_version *r;
277
278         if (ec_command_inptr(dev, EC_CMD_GET_VERSION, 0, NULL, 0,
279                         (uint8_t **)&r, sizeof(*r)) < sizeof(*r))
280                 return -1;
281
282         *image = r->current_image;
283         return 0;
284 }
285
286 static int cros_ec_wait_on_hash_done(struct cros_ec_dev *dev,
287                                   struct ec_response_vboot_hash *hash)
288 {
289         struct ec_params_vboot_hash p;
290         ulong start;
291
292         start = get_timer(0);
293         while (hash->status == EC_VBOOT_HASH_STATUS_BUSY) {
294                 mdelay(50);     /* Insert some reasonable delay */
295
296                 p.cmd = EC_VBOOT_HASH_GET;
297                 if (ec_command(dev, EC_CMD_VBOOT_HASH, 0, &p, sizeof(p),
298                        hash, sizeof(*hash)) < 0)
299                         return -1;
300
301                 if (get_timer(start) > CROS_EC_CMD_HASH_TIMEOUT_MS) {
302                         debug("%s: EC_VBOOT_HASH_GET timeout\n", __func__);
303                         return -EC_RES_TIMEOUT;
304                 }
305         }
306         return 0;
307 }
308
309
310 int cros_ec_read_hash(struct cros_ec_dev *dev,
311                 struct ec_response_vboot_hash *hash)
312 {
313         struct ec_params_vboot_hash p;
314         int rv;
315
316         p.cmd = EC_VBOOT_HASH_GET;
317         if (ec_command(dev, EC_CMD_VBOOT_HASH, 0, &p, sizeof(p),
318                        hash, sizeof(*hash)) < 0)
319                 return -1;
320
321         /* If the EC is busy calculating the hash, fidget until it's done. */
322         rv = cros_ec_wait_on_hash_done(dev, hash);
323         if (rv)
324                 return rv;
325
326         /* If the hash is valid, we're done. Otherwise, we have to kick it off
327          * again and wait for it to complete. Note that we explicitly assume
328          * that hashing zero bytes is always wrong, even though that would
329          * produce a valid hash value. */
330         if (hash->status == EC_VBOOT_HASH_STATUS_DONE && hash->size)
331                 return 0;
332
333         debug("%s: No valid hash (status=%d size=%d). Compute one...\n",
334               __func__, hash->status, hash->size);
335
336         p.cmd = EC_VBOOT_HASH_START;
337         p.hash_type = EC_VBOOT_HASH_TYPE_SHA256;
338         p.nonce_size = 0;
339         p.offset = EC_VBOOT_HASH_OFFSET_RW;
340
341         if (ec_command(dev, EC_CMD_VBOOT_HASH, 0, &p, sizeof(p),
342                        hash, sizeof(*hash)) < 0)
343                 return -1;
344
345         rv = cros_ec_wait_on_hash_done(dev, hash);
346         if (rv)
347                 return rv;
348
349         debug("%s: hash done\n", __func__);
350
351         return 0;
352 }
353
354 static int cros_ec_invalidate_hash(struct cros_ec_dev *dev)
355 {
356         struct ec_params_vboot_hash p;
357         struct ec_response_vboot_hash *hash;
358
359         /* We don't have an explict command for the EC to discard its current
360          * hash value, so we'll just tell it to calculate one that we know is
361          * wrong (we claim that hashing zero bytes is always invalid).
362          */
363         p.cmd = EC_VBOOT_HASH_RECALC;
364         p.hash_type = EC_VBOOT_HASH_TYPE_SHA256;
365         p.nonce_size = 0;
366         p.offset = 0;
367         p.size = 0;
368
369         debug("%s:\n", __func__);
370
371         if (ec_command_inptr(dev, EC_CMD_VBOOT_HASH, 0, &p, sizeof(p),
372                        (uint8_t **)&hash, sizeof(*hash)) < 0)
373                 return -1;
374
375         /* No need to wait for it to finish */
376         return 0;
377 }
378
379 int cros_ec_reboot(struct cros_ec_dev *dev, enum ec_reboot_cmd cmd,
380                 uint8_t flags)
381 {
382         struct ec_params_reboot_ec p;
383
384         p.cmd = cmd;
385         p.flags = flags;
386
387         if (ec_command_inptr(dev, EC_CMD_REBOOT_EC, 0, &p, sizeof(p), NULL, 0)
388                         < 0)
389                 return -1;
390
391         if (!(flags & EC_REBOOT_FLAG_ON_AP_SHUTDOWN)) {
392                 /*
393                  * EC reboot will take place immediately so delay to allow it
394                  * to complete.  Note that some reboot types (EC_REBOOT_COLD)
395                  * will reboot the AP as well, in which case we won't actually
396                  * get to this point.
397                  */
398                 /*
399                  * TODO(rspangler@chromium.org): Would be nice if we had a
400                  * better way to determine when the reboot is complete.  Could
401                  * we poll a memory-mapped LPC value?
402                  */
403                 udelay(50000);
404         }
405
406         return 0;
407 }
408
409 int cros_ec_interrupt_pending(struct cros_ec_dev *dev)
410 {
411         /* no interrupt support : always poll */
412         if (!fdt_gpio_isvalid(&dev->ec_int))
413                 return 1;
414
415         return !gpio_get_value(dev->ec_int.gpio);
416 }
417
418 int cros_ec_info(struct cros_ec_dev *dev, struct ec_response_mkbp_info *info)
419 {
420         if (ec_command(dev, EC_CMD_MKBP_INFO, 0, NULL, 0, info,
421                        sizeof(*info)) < sizeof(*info))
422                 return -1;
423
424         return 0;
425 }
426
427 int cros_ec_get_host_events(struct cros_ec_dev *dev, uint32_t *events_ptr)
428 {
429         struct ec_response_host_event_mask *resp;
430
431         /*
432          * Use the B copy of the event flags, because the main copy is already
433          * used by ACPI/SMI.
434          */
435         if (ec_command_inptr(dev, EC_CMD_HOST_EVENT_GET_B, 0, NULL, 0,
436                        (uint8_t **)&resp, sizeof(*resp)) < sizeof(*resp))
437                 return -1;
438
439         if (resp->mask & EC_HOST_EVENT_MASK(EC_HOST_EVENT_INVALID))
440                 return -1;
441
442         *events_ptr = resp->mask;
443         return 0;
444 }
445
446 int cros_ec_clear_host_events(struct cros_ec_dev *dev, uint32_t events)
447 {
448         struct ec_params_host_event_mask params;
449
450         params.mask = events;
451
452         /*
453          * Use the B copy of the event flags, so it affects the data returned
454          * by cros_ec_get_host_events().
455          */
456         if (ec_command_inptr(dev, EC_CMD_HOST_EVENT_CLEAR_B, 0,
457                        &params, sizeof(params), NULL, 0) < 0)
458                 return -1;
459
460         return 0;
461 }
462
463 int cros_ec_flash_protect(struct cros_ec_dev *dev,
464                        uint32_t set_mask, uint32_t set_flags,
465                        struct ec_response_flash_protect *resp)
466 {
467         struct ec_params_flash_protect params;
468
469         params.mask = set_mask;
470         params.flags = set_flags;
471
472         if (ec_command(dev, EC_CMD_FLASH_PROTECT, EC_VER_FLASH_PROTECT,
473                        &params, sizeof(params),
474                        resp, sizeof(*resp)) < sizeof(*resp))
475                 return -1;
476
477         return 0;
478 }
479
480 static int cros_ec_check_version(struct cros_ec_dev *dev)
481 {
482         struct ec_params_hello req;
483         struct ec_response_hello *resp;
484
485 #ifdef CONFIG_CROS_EC_LPC
486         /* LPC has its own way of doing this */
487         if (dev->interface == CROS_EC_IF_LPC)
488                 return cros_ec_lpc_check_version(dev);
489 #endif
490
491         /*
492          * TODO(sjg@chromium.org).
493          * There is a strange oddity here with the EC. We could just ignore
494          * the response, i.e. pass the last two parameters as NULL and 0.
495          * In this case we won't read back very many bytes from the EC.
496          * On the I2C bus the EC gets upset about this and will try to send
497          * the bytes anyway. This means that we will have to wait for that
498          * to complete before continuing with a new EC command.
499          *
500          * This problem is probably unique to the I2C bus.
501          *
502          * So for now, just read all the data anyway.
503          */
504         dev->cmd_version_is_supported = 1;
505         if (ec_command_inptr(dev, EC_CMD_HELLO, 0, &req, sizeof(req),
506                        (uint8_t **)&resp, sizeof(*resp)) > 0) {
507                 /* It appears to understand new version commands */
508                 dev->cmd_version_is_supported = 1;
509         } else {
510                 printf("%s: ERROR: old EC interface not supported\n",
511                        __func__);
512                 return -1;
513         }
514
515         return 0;
516 }
517
518 int cros_ec_test(struct cros_ec_dev *dev)
519 {
520         struct ec_params_hello req;
521         struct ec_response_hello *resp;
522
523         req.in_data = 0x12345678;
524         if (ec_command_inptr(dev, EC_CMD_HELLO, 0, &req, sizeof(req),
525                        (uint8_t **)&resp, sizeof(*resp)) < sizeof(*resp)) {
526                 printf("ec_command_inptr() returned error\n");
527                 return -1;
528         }
529         if (resp->out_data != req.in_data + 0x01020304) {
530                 printf("Received invalid handshake %x\n", resp->out_data);
531                 return -1;
532         }
533
534         return 0;
535 }
536
537 int cros_ec_flash_offset(struct cros_ec_dev *dev, enum ec_flash_region region,
538                       uint32_t *offset, uint32_t *size)
539 {
540         struct ec_params_flash_region_info p;
541         struct ec_response_flash_region_info *r;
542         int ret;
543
544         p.region = region;
545         ret = ec_command_inptr(dev, EC_CMD_FLASH_REGION_INFO,
546                          EC_VER_FLASH_REGION_INFO,
547                          &p, sizeof(p), (uint8_t **)&r, sizeof(*r));
548         if (ret != sizeof(*r))
549                 return -1;
550
551         if (offset)
552                 *offset = r->offset;
553         if (size)
554                 *size = r->size;
555
556         return 0;
557 }
558
559 int cros_ec_flash_erase(struct cros_ec_dev *dev, uint32_t offset, uint32_t size)
560 {
561         struct ec_params_flash_erase p;
562
563         p.offset = offset;
564         p.size = size;
565         return ec_command_inptr(dev, EC_CMD_FLASH_ERASE, 0, &p, sizeof(p),
566                         NULL, 0);
567 }
568
569 /**
570  * Write a single block to the flash
571  *
572  * Write a block of data to the EC flash. The size must not exceed the flash
573  * write block size which you can obtain from cros_ec_flash_write_burst_size().
574  *
575  * The offset starts at 0. You can obtain the region information from
576  * cros_ec_flash_offset() to find out where to write for a particular region.
577  *
578  * Attempting to write to the region where the EC is currently running from
579  * will result in an error.
580  *
581  * @param dev           CROS-EC device
582  * @param data          Pointer to data buffer to write
583  * @param offset        Offset within flash to write to.
584  * @param size          Number of bytes to write
585  * @return 0 if ok, -1 on error
586  */
587 static int cros_ec_flash_write_block(struct cros_ec_dev *dev,
588                 const uint8_t *data, uint32_t offset, uint32_t size)
589 {
590         struct ec_params_flash_write p;
591
592         p.offset = offset;
593         p.size = size;
594         assert(data && p.size <= EC_FLASH_WRITE_VER0_SIZE);
595         memcpy(&p + 1, data, p.size);
596
597         return ec_command_inptr(dev, EC_CMD_FLASH_WRITE, 0,
598                           &p, sizeof(p), NULL, 0) >= 0 ? 0 : -1;
599 }
600
601 /**
602  * Return optimal flash write burst size
603  */
604 static int cros_ec_flash_write_burst_size(struct cros_ec_dev *dev)
605 {
606         return EC_FLASH_WRITE_VER0_SIZE;
607 }
608
609 /**
610  * Check if a block of data is erased (all 0xff)
611  *
612  * This function is useful when dealing with flash, for checking whether a
613  * data block is erased and thus does not need to be programmed.
614  *
615  * @param data          Pointer to data to check (must be word-aligned)
616  * @param size          Number of bytes to check (must be word-aligned)
617  * @return 0 if erased, non-zero if any word is not erased
618  */
619 static int cros_ec_data_is_erased(const uint32_t *data, int size)
620 {
621         assert(!(size & 3));
622         size /= sizeof(uint32_t);
623         for (; size > 0; size -= 4, data++)
624                 if (*data != -1U)
625                         return 0;
626
627         return 1;
628 }
629
630 int cros_ec_flash_write(struct cros_ec_dev *dev, const uint8_t *data,
631                      uint32_t offset, uint32_t size)
632 {
633         uint32_t burst = cros_ec_flash_write_burst_size(dev);
634         uint32_t end, off;
635         int ret;
636
637         /*
638          * TODO: round up to the nearest multiple of write size.  Can get away
639          * without that on link right now because its write size is 4 bytes.
640          */
641         end = offset + size;
642         for (off = offset; off < end; off += burst, data += burst) {
643                 uint32_t todo;
644
645                 /* If the data is empty, there is no point in programming it */
646                 todo = min(end - off, burst);
647                 if (dev->optimise_flash_write &&
648                                 cros_ec_data_is_erased((uint32_t *)data, todo))
649                         continue;
650
651                 ret = cros_ec_flash_write_block(dev, data, off, todo);
652                 if (ret)
653                         return ret;
654         }
655
656         return 0;
657 }
658
659 /**
660  * Read a single block from the flash
661  *
662  * Read a block of data from the EC flash. The size must not exceed the flash
663  * write block size which you can obtain from cros_ec_flash_write_burst_size().
664  *
665  * The offset starts at 0. You can obtain the region information from
666  * cros_ec_flash_offset() to find out where to read for a particular region.
667  *
668  * @param dev           CROS-EC device
669  * @param data          Pointer to data buffer to read into
670  * @param offset        Offset within flash to read from
671  * @param size          Number of bytes to read
672  * @return 0 if ok, -1 on error
673  */
674 static int cros_ec_flash_read_block(struct cros_ec_dev *dev, uint8_t *data,
675                                  uint32_t offset, uint32_t size)
676 {
677         struct ec_params_flash_read p;
678
679         p.offset = offset;
680         p.size = size;
681
682         return ec_command(dev, EC_CMD_FLASH_READ, 0,
683                           &p, sizeof(p), data, size) >= 0 ? 0 : -1;
684 }
685
686 int cros_ec_flash_read(struct cros_ec_dev *dev, uint8_t *data, uint32_t offset,
687                     uint32_t size)
688 {
689         uint32_t burst = cros_ec_flash_write_burst_size(dev);
690         uint32_t end, off;
691         int ret;
692
693         end = offset + size;
694         for (off = offset; off < end; off += burst, data += burst) {
695                 ret = cros_ec_flash_read_block(dev, data, off,
696                                             min(end - off, burst));
697                 if (ret)
698                         return ret;
699         }
700
701         return 0;
702 }
703
704 int cros_ec_flash_update_rw(struct cros_ec_dev *dev,
705                          const uint8_t *image, int image_size)
706 {
707         uint32_t rw_offset, rw_size;
708         int ret;
709
710         if (cros_ec_flash_offset(dev, EC_FLASH_REGION_RW, &rw_offset, &rw_size))
711                 return -1;
712         if (image_size > rw_size)
713                 return -1;
714
715         /* Invalidate the existing hash, just in case the AP reboots
716          * unexpectedly during the update. If that happened, the EC RW firmware
717          * would be invalid, but the EC would still have the original hash.
718          */
719         ret = cros_ec_invalidate_hash(dev);
720         if (ret)
721                 return ret;
722
723         /*
724          * Erase the entire RW section, so that the EC doesn't see any garbage
725          * past the new image if it's smaller than the current image.
726          *
727          * TODO: could optimize this to erase just the current image, since
728          * presumably everything past that is 0xff's.  But would still need to
729          * round up to the nearest multiple of erase size.
730          */
731         ret = cros_ec_flash_erase(dev, rw_offset, rw_size);
732         if (ret)
733                 return ret;
734
735         /* Write the image */
736         ret = cros_ec_flash_write(dev, image, rw_offset, image_size);
737         if (ret)
738                 return ret;
739
740         return 0;
741 }
742
743 int cros_ec_read_vbnvcontext(struct cros_ec_dev *dev, uint8_t *block)
744 {
745         struct ec_params_vbnvcontext p;
746         int len;
747
748         p.op = EC_VBNV_CONTEXT_OP_READ;
749
750         len = ec_command(dev, EC_CMD_VBNV_CONTEXT, EC_VER_VBNV_CONTEXT,
751                         &p, sizeof(p), block, EC_VBNV_BLOCK_SIZE);
752         if (len < EC_VBNV_BLOCK_SIZE)
753                 return -1;
754
755         return 0;
756 }
757
758 int cros_ec_write_vbnvcontext(struct cros_ec_dev *dev, const uint8_t *block)
759 {
760         struct ec_params_vbnvcontext p;
761         int len;
762
763         p.op = EC_VBNV_CONTEXT_OP_WRITE;
764         memcpy(p.block, block, sizeof(p.block));
765
766         len = ec_command_inptr(dev, EC_CMD_VBNV_CONTEXT, EC_VER_VBNV_CONTEXT,
767                         &p, sizeof(p), NULL, 0);
768         if (len < 0)
769                 return -1;
770
771         return 0;
772 }
773
774 int cros_ec_set_ldo(struct cros_ec_dev *dev, uint8_t index, uint8_t state)
775 {
776         struct ec_params_ldo_set params;
777
778         params.index = index;
779         params.state = state;
780
781         if (ec_command_inptr(dev, EC_CMD_LDO_SET, 0,
782                        &params, sizeof(params),
783                        NULL, 0))
784                 return -1;
785
786         return 0;
787 }
788
789 int cros_ec_get_ldo(struct cros_ec_dev *dev, uint8_t index, uint8_t *state)
790 {
791         struct ec_params_ldo_get params;
792         struct ec_response_ldo_get *resp;
793
794         params.index = index;
795
796         if (ec_command_inptr(dev, EC_CMD_LDO_GET, 0,
797                        &params, sizeof(params),
798                        (uint8_t **)&resp, sizeof(*resp)) < sizeof(*resp))
799                 return -1;
800
801         *state = resp->state;
802
803         return 0;
804 }
805
806 /**
807  * Decode EC interface details from the device tree and allocate a suitable
808  * device.
809  *
810  * @param blob          Device tree blob
811  * @param node          Node to decode from
812  * @param devp          Returns a pointer to the new allocated device
813  * @return 0 if ok, -1 on error
814  */
815 static int cros_ec_decode_fdt(const void *blob, int node,
816                 struct cros_ec_dev **devp)
817 {
818         enum fdt_compat_id compat;
819         struct cros_ec_dev *dev;
820         int parent;
821
822         /* See what type of parent we are inside (this is expensive) */
823         parent = fdt_parent_offset(blob, node);
824         if (parent < 0) {
825                 debug("%s: Cannot find node parent\n", __func__);
826                 return -1;
827         }
828
829         dev = &static_dev;
830         dev->node = node;
831         dev->parent_node = parent;
832
833         compat = fdtdec_lookup(blob, parent);
834         switch (compat) {
835 #ifdef CONFIG_CROS_EC_SPI
836         case COMPAT_SAMSUNG_EXYNOS_SPI:
837                 dev->interface = CROS_EC_IF_SPI;
838                 if (cros_ec_spi_decode_fdt(dev, blob))
839                         return -1;
840                 break;
841 #endif
842 #ifdef CONFIG_CROS_EC_I2C
843         case COMPAT_SAMSUNG_S3C2440_I2C:
844                 dev->interface = CROS_EC_IF_I2C;
845                 if (cros_ec_i2c_decode_fdt(dev, blob))
846                         return -1;
847                 break;
848 #endif
849 #ifdef CONFIG_CROS_EC_LPC
850         case COMPAT_INTEL_LPC:
851                 dev->interface = CROS_EC_IF_LPC;
852                 break;
853 #endif
854         default:
855                 debug("%s: Unknown compat id %d\n", __func__, compat);
856                 return -1;
857         }
858
859         fdtdec_decode_gpio(blob, node, "ec-interrupt", &dev->ec_int);
860         dev->optimise_flash_write = fdtdec_get_bool(blob, node,
861                                                     "optimise-flash-write");
862         *devp = dev;
863
864         return 0;
865 }
866
867 int cros_ec_init(const void *blob, struct cros_ec_dev **cros_ecp)
868 {
869         char id[MSG_BYTES];
870         struct cros_ec_dev *dev;
871         int node = 0;
872
873         *cros_ecp = NULL;
874         do {
875                 node = fdtdec_next_compatible(blob, node,
876                                               COMPAT_GOOGLE_CROS_EC);
877                 if (node < 0) {
878                         debug("%s: Node not found\n", __func__);
879                         return 0;
880                 }
881         } while (!fdtdec_get_is_enabled(blob, node));
882
883         if (cros_ec_decode_fdt(blob, node, &dev)) {
884                 debug("%s: Failed to decode device.\n", __func__);
885                 return -CROS_EC_ERR_FDT_DECODE;
886         }
887
888         switch (dev->interface) {
889 #ifdef CONFIG_CROS_EC_SPI
890         case CROS_EC_IF_SPI:
891                 if (cros_ec_spi_init(dev, blob)) {
892                         debug("%s: Could not setup SPI interface\n", __func__);
893                         return -CROS_EC_ERR_DEV_INIT;
894                 }
895                 break;
896 #endif
897 #ifdef CONFIG_CROS_EC_I2C
898         case CROS_EC_IF_I2C:
899                 if (cros_ec_i2c_init(dev, blob))
900                         return -CROS_EC_ERR_DEV_INIT;
901                 break;
902 #endif
903 #ifdef CONFIG_CROS_EC_LPC
904         case CROS_EC_IF_LPC:
905                 if (cros_ec_lpc_init(dev, blob))
906                         return -CROS_EC_ERR_DEV_INIT;
907                 break;
908 #endif
909         case CROS_EC_IF_NONE:
910         default:
911                 return 0;
912         }
913
914         /* we will poll the EC interrupt line */
915         fdtdec_setup_gpio(&dev->ec_int);
916         if (fdt_gpio_isvalid(&dev->ec_int))
917                 gpio_direction_input(dev->ec_int.gpio);
918
919         if (cros_ec_check_version(dev)) {
920                 debug("%s: Could not detect CROS-EC version\n", __func__);
921                 return -CROS_EC_ERR_CHECK_VERSION;
922         }
923
924         if (cros_ec_read_id(dev, id, sizeof(id))) {
925                 debug("%s: Could not read KBC ID\n", __func__);
926                 return -CROS_EC_ERR_READ_ID;
927         }
928
929         /* Remember this device for use by the cros_ec command */
930         last_dev = *cros_ecp = dev;
931         debug("Google Chrome EC CROS-EC driver ready, id '%s'\n", id);
932
933         return 0;
934 }
935
936 int cros_ec_decode_region(int argc, char * const argv[])
937 {
938         if (argc > 0) {
939                 if (0 == strcmp(*argv, "rw"))
940                         return EC_FLASH_REGION_RW;
941                 else if (0 == strcmp(*argv, "ro"))
942                         return EC_FLASH_REGION_RO;
943
944                 debug("%s: Invalid region '%s'\n", __func__, *argv);
945         } else {
946                 debug("%s: Missing region parameter\n", __func__);
947         }
948
949         return -1;
950 }
951
952 int cros_ec_decode_ec_flash(const void *blob, struct fdt_cros_ec *config)
953 {
954         int flash_node, node;
955
956         node = fdtdec_next_compatible(blob, 0, COMPAT_GOOGLE_CROS_EC);
957         if (node < 0) {
958                 debug("Failed to find chrome-ec node'\n");
959                 return -1;
960         }
961
962         flash_node = fdt_subnode_offset(blob, node, "flash");
963         if (flash_node < 0) {
964                 debug("Failed to find flash node\n");
965                 return -1;
966         }
967
968         if (fdtdec_read_fmap_entry(blob, flash_node, "flash",
969                                    &config->flash)) {
970                 debug("Failed to decode flash node in chrome-ec'\n");
971                 return -1;
972         }
973
974         config->flash_erase_value = fdtdec_get_int(blob, flash_node,
975                                                     "erase-value", -1);
976         for (node = fdt_first_subnode(blob, flash_node); node >= 0;
977              node = fdt_next_subnode(blob, node)) {
978                 const char *name = fdt_get_name(blob, node, NULL);
979                 enum ec_flash_region region;
980
981                 if (0 == strcmp(name, "ro")) {
982                         region = EC_FLASH_REGION_RO;
983                 } else if (0 == strcmp(name, "rw")) {
984                         region = EC_FLASH_REGION_RW;
985                 } else if (0 == strcmp(name, "wp-ro")) {
986                         region = EC_FLASH_REGION_WP_RO;
987                 } else {
988                         debug("Unknown EC flash region name '%s'\n", name);
989                         return -1;
990                 }
991
992                 if (fdtdec_read_fmap_entry(blob, node, "reg",
993                                            &config->region[region])) {
994                         debug("Failed to decode flash region in chrome-ec'\n");
995                         return -1;
996                 }
997         }
998
999         return 0;
1000 }
1001
1002 #ifdef CONFIG_CMD_CROS_EC
1003
1004 /**
1005  * Perform a flash read or write command
1006  *
1007  * @param dev           CROS-EC device to read/write
1008  * @param is_write      1 do to a write, 0 to do a read
1009  * @param argc          Number of arguments
1010  * @param argv          Arguments (2 is region, 3 is address)
1011  * @return 0 for ok, 1 for a usage error or -ve for ec command error
1012  *      (negative EC_RES_...)
1013  */
1014 static int do_read_write(struct cros_ec_dev *dev, int is_write, int argc,
1015                          char * const argv[])
1016 {
1017         uint32_t offset, size = -1U, region_size;
1018         unsigned long addr;
1019         char *endp;
1020         int region;
1021         int ret;
1022
1023         region = cros_ec_decode_region(argc - 2, argv + 2);
1024         if (region == -1)
1025                 return 1;
1026         if (argc < 4)
1027                 return 1;
1028         addr = simple_strtoul(argv[3], &endp, 16);
1029         if (*argv[3] == 0 || *endp != 0)
1030                 return 1;
1031         if (argc > 4) {
1032                 size = simple_strtoul(argv[4], &endp, 16);
1033                 if (*argv[4] == 0 || *endp != 0)
1034                         return 1;
1035         }
1036
1037         ret = cros_ec_flash_offset(dev, region, &offset, &region_size);
1038         if (ret) {
1039                 debug("%s: Could not read region info\n", __func__);
1040                 return ret;
1041         }
1042         if (size == -1U)
1043                 size = region_size;
1044
1045         ret = is_write ?
1046                 cros_ec_flash_write(dev, (uint8_t *)addr, offset, size) :
1047                 cros_ec_flash_read(dev, (uint8_t *)addr, offset, size);
1048         if (ret) {
1049                 debug("%s: Could not %s region\n", __func__,
1050                       is_write ? "write" : "read");
1051                 return ret;
1052         }
1053
1054         return 0;
1055 }
1056
1057 static int do_cros_ec(cmd_tbl_t *cmdtp, int flag, int argc, char * const argv[])
1058 {
1059         struct cros_ec_dev *dev = last_dev;
1060         const char *cmd;
1061         int ret = 0;
1062
1063         if (argc < 2)
1064                 return CMD_RET_USAGE;
1065
1066         cmd = argv[1];
1067         if (0 == strcmp("init", cmd)) {
1068                 ret = cros_ec_init(gd->fdt_blob, &dev);
1069                 if (ret) {
1070                         printf("Could not init cros_ec device (err %d)\n", ret);
1071                         return 1;
1072                 }
1073                 return 0;
1074         }
1075
1076         /* Just use the last allocated device; there should be only one */
1077         if (!last_dev) {
1078                 printf("No CROS-EC device available\n");
1079                 return 1;
1080         }
1081         if (0 == strcmp("id", cmd)) {
1082                 char id[MSG_BYTES];
1083
1084                 if (cros_ec_read_id(dev, id, sizeof(id))) {
1085                         debug("%s: Could not read KBC ID\n", __func__);
1086                         return 1;
1087                 }
1088                 printf("%s\n", id);
1089         } else if (0 == strcmp("info", cmd)) {
1090                 struct ec_response_mkbp_info info;
1091
1092                 if (cros_ec_info(dev, &info)) {
1093                         debug("%s: Could not read KBC info\n", __func__);
1094                         return 1;
1095                 }
1096                 printf("rows     = %u\n", info.rows);
1097                 printf("cols     = %u\n", info.cols);
1098                 printf("switches = %#x\n", info.switches);
1099         } else if (0 == strcmp("curimage", cmd)) {
1100                 enum ec_current_image image;
1101
1102                 if (cros_ec_read_current_image(dev, &image)) {
1103                         debug("%s: Could not read KBC image\n", __func__);
1104                         return 1;
1105                 }
1106                 printf("%d\n", image);
1107         } else if (0 == strcmp("hash", cmd)) {
1108                 struct ec_response_vboot_hash hash;
1109                 int i;
1110
1111                 if (cros_ec_read_hash(dev, &hash)) {
1112                         debug("%s: Could not read KBC hash\n", __func__);
1113                         return 1;
1114                 }
1115
1116                 if (hash.hash_type == EC_VBOOT_HASH_TYPE_SHA256)
1117                         printf("type:    SHA-256\n");
1118                 else
1119                         printf("type:    %d\n", hash.hash_type);
1120
1121                 printf("offset:  0x%08x\n", hash.offset);
1122                 printf("size:    0x%08x\n", hash.size);
1123
1124                 printf("digest:  ");
1125                 for (i = 0; i < hash.digest_size; i++)
1126                         printf("%02x", hash.hash_digest[i]);
1127                 printf("\n");
1128         } else if (0 == strcmp("reboot", cmd)) {
1129                 int region;
1130                 enum ec_reboot_cmd cmd;
1131
1132                 if (argc >= 3 && !strcmp(argv[2], "cold"))
1133                         cmd = EC_REBOOT_COLD;
1134                 else {
1135                         region = cros_ec_decode_region(argc - 2, argv + 2);
1136                         if (region == EC_FLASH_REGION_RO)
1137                                 cmd = EC_REBOOT_JUMP_RO;
1138                         else if (region == EC_FLASH_REGION_RW)
1139                                 cmd = EC_REBOOT_JUMP_RW;
1140                         else
1141                                 return CMD_RET_USAGE;
1142                 }
1143
1144                 if (cros_ec_reboot(dev, cmd, 0)) {
1145                         debug("%s: Could not reboot KBC\n", __func__);
1146                         return 1;
1147                 }
1148         } else if (0 == strcmp("events", cmd)) {
1149                 uint32_t events;
1150
1151                 if (cros_ec_get_host_events(dev, &events)) {
1152                         debug("%s: Could not read host events\n", __func__);
1153                         return 1;
1154                 }
1155                 printf("0x%08x\n", events);
1156         } else if (0 == strcmp("clrevents", cmd)) {
1157                 uint32_t events = 0x7fffffff;
1158
1159                 if (argc >= 3)
1160                         events = simple_strtol(argv[2], NULL, 0);
1161
1162                 if (cros_ec_clear_host_events(dev, events)) {
1163                         debug("%s: Could not clear host events\n", __func__);
1164                         return 1;
1165                 }
1166         } else if (0 == strcmp("read", cmd)) {
1167                 ret = do_read_write(dev, 0, argc, argv);
1168                 if (ret > 0)
1169                         return CMD_RET_USAGE;
1170         } else if (0 == strcmp("write", cmd)) {
1171                 ret = do_read_write(dev, 1, argc, argv);
1172                 if (ret > 0)
1173                         return CMD_RET_USAGE;
1174         } else if (0 == strcmp("erase", cmd)) {
1175                 int region = cros_ec_decode_region(argc - 2, argv + 2);
1176                 uint32_t offset, size;
1177
1178                 if (region == -1)
1179                         return CMD_RET_USAGE;
1180                 if (cros_ec_flash_offset(dev, region, &offset, &size)) {
1181                         debug("%s: Could not read region info\n", __func__);
1182                         ret = -1;
1183                 } else {
1184                         ret = cros_ec_flash_erase(dev, offset, size);
1185                         if (ret) {
1186                                 debug("%s: Could not erase region\n",
1187                                       __func__);
1188                         }
1189                 }
1190         } else if (0 == strcmp("regioninfo", cmd)) {
1191                 int region = cros_ec_decode_region(argc - 2, argv + 2);
1192                 uint32_t offset, size;
1193
1194                 if (region == -1)
1195                         return CMD_RET_USAGE;
1196                 ret = cros_ec_flash_offset(dev, region, &offset, &size);
1197                 if (ret) {
1198                         debug("%s: Could not read region info\n", __func__);
1199                 } else {
1200                         printf("Region: %s\n", region == EC_FLASH_REGION_RO ?
1201                                         "RO" : "RW");
1202                         printf("Offset: %x\n", offset);
1203                         printf("Size:   %x\n", size);
1204                 }
1205         } else if (0 == strcmp("vbnvcontext", cmd)) {
1206                 uint8_t block[EC_VBNV_BLOCK_SIZE];
1207                 char buf[3];
1208                 int i, len;
1209                 unsigned long result;
1210
1211                 if (argc <= 2) {
1212                         ret = cros_ec_read_vbnvcontext(dev, block);
1213                         if (!ret) {
1214                                 printf("vbnv_block: ");
1215                                 for (i = 0; i < EC_VBNV_BLOCK_SIZE; i++)
1216                                         printf("%02x", block[i]);
1217                                 putc('\n');
1218                         }
1219                 } else {
1220                         /*
1221                          * TODO(clchiou): Move this to a utility function as
1222                          * cmd_spi might want to call it.
1223                          */
1224                         memset(block, 0, EC_VBNV_BLOCK_SIZE);
1225                         len = strlen(argv[2]);
1226                         buf[2] = '\0';
1227                         for (i = 0; i < EC_VBNV_BLOCK_SIZE; i++) {
1228                                 if (i * 2 >= len)
1229                                         break;
1230                                 buf[0] = argv[2][i * 2];
1231                                 if (i * 2 + 1 >= len)
1232                                         buf[1] = '0';
1233                                 else
1234                                         buf[1] = argv[2][i * 2 + 1];
1235                                 strict_strtoul(buf, 16, &result);
1236                                 block[i] = result;
1237                         }
1238                         ret = cros_ec_write_vbnvcontext(dev, block);
1239                 }
1240                 if (ret) {
1241                         debug("%s: Could not %s VbNvContext\n", __func__,
1242                                         argc <= 2 ?  "read" : "write");
1243                 }
1244         } else if (0 == strcmp("test", cmd)) {
1245                 int result = cros_ec_test(dev);
1246
1247                 if (result)
1248                         printf("Test failed with error %d\n", result);
1249                 else
1250                         puts("Test passed\n");
1251         } else if (0 == strcmp("version", cmd)) {
1252                 struct ec_response_get_version *p;
1253                 char *build_string;
1254
1255                 ret = cros_ec_read_version(dev, &p);
1256                 if (!ret) {
1257                         /* Print versions */
1258                         printf("RO version:    %1.*s\n",
1259                                sizeof(p->version_string_ro),
1260                                p->version_string_ro);
1261                         printf("RW version:    %1.*s\n",
1262                                sizeof(p->version_string_rw),
1263                                p->version_string_rw);
1264                         printf("Firmware copy: %s\n",
1265                                 (p->current_image <
1266                                         ARRAY_SIZE(ec_current_image_name) ?
1267                                 ec_current_image_name[p->current_image] :
1268                                 "?"));
1269                         ret = cros_ec_read_build_info(dev, &build_string);
1270                         if (!ret)
1271                                 printf("Build info:    %s\n", build_string);
1272                 }
1273         } else if (0 == strcmp("ldo", cmd)) {
1274                 uint8_t index, state;
1275                 char *endp;
1276
1277                 if (argc < 3)
1278                         return CMD_RET_USAGE;
1279                 index = simple_strtoul(argv[2], &endp, 10);
1280                 if (*argv[2] == 0 || *endp != 0)
1281                         return CMD_RET_USAGE;
1282                 if (argc > 3) {
1283                         state = simple_strtoul(argv[3], &endp, 10);
1284                         if (*argv[3] == 0 || *endp != 0)
1285                                 return CMD_RET_USAGE;
1286                         ret = cros_ec_set_ldo(dev, index, state);
1287                 } else {
1288                         ret = cros_ec_get_ldo(dev, index, &state);
1289                         if (!ret) {
1290                                 printf("LDO%d: %s\n", index,
1291                                         state == EC_LDO_STATE_ON ?
1292                                         "on" : "off");
1293                         }
1294                 }
1295
1296                 if (ret) {
1297                         debug("%s: Could not access LDO%d\n", __func__, index);
1298                         return ret;
1299                 }
1300         } else {
1301                 return CMD_RET_USAGE;
1302         }
1303
1304         if (ret < 0) {
1305                 printf("Error: CROS-EC command failed (error %d)\n", ret);
1306                 ret = 1;
1307         }
1308
1309         return ret;
1310 }
1311
1312 U_BOOT_CMD(
1313         crosec, 5,      1,      do_cros_ec,
1314         "CROS-EC utility command",
1315         "init                Re-init CROS-EC (done on startup automatically)\n"
1316         "crosec id                  Read CROS-EC ID\n"
1317         "crosec info                Read CROS-EC info\n"
1318         "crosec curimage            Read CROS-EC current image\n"
1319         "crosec hash                Read CROS-EC hash\n"
1320         "crosec reboot [rw | ro | cold]  Reboot CROS-EC\n"
1321         "crosec events              Read CROS-EC host events\n"
1322         "crosec clrevents [mask]    Clear CROS-EC host events\n"
1323         "crosec regioninfo <ro|rw>  Read image info\n"
1324         "crosec erase <ro|rw>       Erase EC image\n"
1325         "crosec read <ro|rw> <addr> [<size>]   Read EC image\n"
1326         "crosec write <ro|rw> <addr> [<size>]  Write EC image\n"
1327         "crosec vbnvcontext [hexstring]        Read [write] VbNvContext from EC\n"
1328         "crosec ldo <idx> [<state>] Switch/Read LDO state\n"
1329         "crosec test                run tests on cros_ec\n"
1330         "crosec version             Read CROS-EC version"
1331 );
1332 #endif