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