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