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