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