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