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