xref: /openbmc/u-boot/drivers/misc/cros_ec.c (revision d024236e5a31a2b4b82cbcc98b31b8170fc88d28)
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 <linux/errno.h>
26 #include <asm/io.h>
27 #include <asm-generic/gpio.h>
28 #include <dm/device-internal.h>
29 #include <dm/of_extra.h>
30 #include <dm/uclass-internal.h>
31 
32 #ifdef DEBUG_TRACE
33 #define debug_trace(fmt, b...)	debug(fmt, #b)
34 #else
35 #define debug_trace(fmt, b...)
36 #endif
37 
38 enum {
39 	/* Timeout waiting for a flash erase command to complete */
40 	CROS_EC_CMD_TIMEOUT_MS	= 5000,
41 	/* Timeout waiting for a synchronous hash to be recomputed */
42 	CROS_EC_CMD_HASH_TIMEOUT_MS = 2000,
43 };
44 
45 void cros_ec_dump_data(const char *name, int cmd, const uint8_t *data, int len)
46 {
47 #ifdef DEBUG
48 	int i;
49 
50 	printf("%s: ", name);
51 	if (cmd != -1)
52 		printf("cmd=%#x: ", cmd);
53 	for (i = 0; i < len; i++)
54 		printf("%02x ", data[i]);
55 	printf("\n");
56 #endif
57 }
58 
59 /*
60  * Calculate a simple 8-bit checksum of a data block
61  *
62  * @param data	Data block to checksum
63  * @param size	Size of data block in bytes
64  * @return checksum value (0 to 255)
65  */
66 int cros_ec_calc_checksum(const uint8_t *data, int size)
67 {
68 	int csum, i;
69 
70 	for (i = csum = 0; i < size; i++)
71 		csum += data[i];
72 	return csum & 0xff;
73 }
74 
75 /**
76  * Create a request packet for protocol version 3.
77  *
78  * The packet is stored in the device's internal output buffer.
79  *
80  * @param dev		CROS-EC device
81  * @param cmd		Command to send (EC_CMD_...)
82  * @param cmd_version	Version of command to send (EC_VER_...)
83  * @param dout          Output data (may be NULL If dout_len=0)
84  * @param dout_len      Size of output data in bytes
85  * @return packet size in bytes, or <0 if error.
86  */
87 static int create_proto3_request(struct cros_ec_dev *dev,
88 				 int cmd, int cmd_version,
89 				 const void *dout, int dout_len)
90 {
91 	struct ec_host_request *rq = (struct ec_host_request *)dev->dout;
92 	int out_bytes = dout_len + sizeof(*rq);
93 
94 	/* Fail if output size is too big */
95 	if (out_bytes > (int)sizeof(dev->dout)) {
96 		debug("%s: Cannot send %d bytes\n", __func__, dout_len);
97 		return -EC_RES_REQUEST_TRUNCATED;
98 	}
99 
100 	/* Fill in request packet */
101 	rq->struct_version = EC_HOST_REQUEST_VERSION;
102 	rq->checksum = 0;
103 	rq->command = cmd;
104 	rq->command_version = cmd_version;
105 	rq->reserved = 0;
106 	rq->data_len = dout_len;
107 
108 	/* Copy data after header */
109 	memcpy(rq + 1, dout, dout_len);
110 
111 	/* Write checksum field so the entire packet sums to 0 */
112 	rq->checksum = (uint8_t)(-cros_ec_calc_checksum(dev->dout, out_bytes));
113 
114 	cros_ec_dump_data("out", cmd, dev->dout, out_bytes);
115 
116 	/* Return size of request packet */
117 	return out_bytes;
118 }
119 
120 /**
121  * Prepare the device to receive a protocol version 3 response.
122  *
123  * @param dev		CROS-EC device
124  * @param din_len       Maximum size of response in bytes
125  * @return maximum expected number of bytes in response, or <0 if error.
126  */
127 static int prepare_proto3_response_buffer(struct cros_ec_dev *dev, int din_len)
128 {
129 	int in_bytes = din_len + sizeof(struct ec_host_response);
130 
131 	/* Fail if input size is too big */
132 	if (in_bytes > (int)sizeof(dev->din)) {
133 		debug("%s: Cannot receive %d bytes\n", __func__, din_len);
134 		return -EC_RES_RESPONSE_TOO_BIG;
135 	}
136 
137 	/* Return expected size of response packet */
138 	return in_bytes;
139 }
140 
141 /**
142  * Handle a protocol version 3 response packet.
143  *
144  * The packet must already be stored in the device's internal input buffer.
145  *
146  * @param dev		CROS-EC device
147  * @param dinp          Returns pointer to response data
148  * @param din_len       Maximum size of response in bytes
149  * @return number of bytes of response data, or <0 if error. Note that error
150  * codes can be from errno.h or -ve EC_RES_INVALID_CHECKSUM values (and they
151  * overlap!)
152  */
153 static int handle_proto3_response(struct cros_ec_dev *dev,
154 				  uint8_t **dinp, int din_len)
155 {
156 	struct ec_host_response *rs = (struct ec_host_response *)dev->din;
157 	int in_bytes;
158 	int csum;
159 
160 	cros_ec_dump_data("in-header", -1, dev->din, sizeof(*rs));
161 
162 	/* Check input data */
163 	if (rs->struct_version != EC_HOST_RESPONSE_VERSION) {
164 		debug("%s: EC response version mismatch\n", __func__);
165 		return -EC_RES_INVALID_RESPONSE;
166 	}
167 
168 	if (rs->reserved) {
169 		debug("%s: EC response reserved != 0\n", __func__);
170 		return -EC_RES_INVALID_RESPONSE;
171 	}
172 
173 	if (rs->data_len > din_len) {
174 		debug("%s: EC returned too much data\n", __func__);
175 		return -EC_RES_RESPONSE_TOO_BIG;
176 	}
177 
178 	cros_ec_dump_data("in-data", -1, dev->din + sizeof(*rs), rs->data_len);
179 
180 	/* Update in_bytes to actual data size */
181 	in_bytes = sizeof(*rs) + rs->data_len;
182 
183 	/* Verify checksum */
184 	csum = cros_ec_calc_checksum(dev->din, in_bytes);
185 	if (csum) {
186 		debug("%s: EC response checksum invalid: 0x%02x\n", __func__,
187 		      csum);
188 		return -EC_RES_INVALID_CHECKSUM;
189 	}
190 
191 	/* Return error result, if any */
192 	if (rs->result)
193 		return -(int)rs->result;
194 
195 	/* If we're still here, set response data pointer and return length */
196 	*dinp = (uint8_t *)(rs + 1);
197 
198 	return rs->data_len;
199 }
200 
201 static int send_command_proto3(struct cros_ec_dev *dev,
202 			       int cmd, int cmd_version,
203 			       const void *dout, int dout_len,
204 			       uint8_t **dinp, int din_len)
205 {
206 	struct dm_cros_ec_ops *ops;
207 	int out_bytes, in_bytes;
208 	int rv;
209 
210 	/* Create request packet */
211 	out_bytes = create_proto3_request(dev, cmd, cmd_version,
212 					  dout, dout_len);
213 	if (out_bytes < 0)
214 		return out_bytes;
215 
216 	/* Prepare response buffer */
217 	in_bytes = prepare_proto3_response_buffer(dev, din_len);
218 	if (in_bytes < 0)
219 		return in_bytes;
220 
221 	ops = dm_cros_ec_get_ops(dev->dev);
222 	rv = ops->packet ? ops->packet(dev->dev, out_bytes, in_bytes) : -ENOSYS;
223 	if (rv < 0)
224 		return rv;
225 
226 	/* Process the response */
227 	return handle_proto3_response(dev, dinp, din_len);
228 }
229 
230 static int send_command(struct cros_ec_dev *dev, uint8_t cmd, int cmd_version,
231 			const void *dout, int dout_len,
232 			uint8_t **dinp, int din_len)
233 {
234 	struct dm_cros_ec_ops *ops;
235 	int ret = -1;
236 
237 	/* Handle protocol version 3 support */
238 	if (dev->protocol_version == 3) {
239 		return send_command_proto3(dev, cmd, cmd_version,
240 					   dout, dout_len, dinp, din_len);
241 	}
242 
243 	ops = dm_cros_ec_get_ops(dev->dev);
244 	ret = ops->command(dev->dev, cmd, cmd_version,
245 			   (const uint8_t *)dout, dout_len, dinp, din_len);
246 
247 	return ret;
248 }
249 
250 /**
251  * Send a command to the CROS-EC device and return the reply.
252  *
253  * The device's internal input/output buffers are used.
254  *
255  * @param dev		CROS-EC device
256  * @param cmd		Command to send (EC_CMD_...)
257  * @param cmd_version	Version of command to send (EC_VER_...)
258  * @param dout          Output data (may be NULL If dout_len=0)
259  * @param dout_len      Size of output data in bytes
260  * @param dinp          Response data (may be NULL If din_len=0).
261  *			If not NULL, it will be updated to point to the data
262  *			and will always be double word aligned (64-bits)
263  * @param din_len       Maximum size of response in bytes
264  * @return number of bytes in response, or -ve on error
265  */
266 static int ec_command_inptr(struct cros_ec_dev *dev, uint8_t cmd,
267 		int cmd_version, const void *dout, int dout_len, uint8_t **dinp,
268 		int din_len)
269 {
270 	uint8_t *din = NULL;
271 	int len;
272 
273 	len = send_command(dev, cmd, cmd_version, dout, dout_len,
274 				&din, din_len);
275 
276 	/* If the command doesn't complete, wait a while */
277 	if (len == -EC_RES_IN_PROGRESS) {
278 		struct ec_response_get_comms_status *resp = NULL;
279 		ulong start;
280 
281 		/* Wait for command to complete */
282 		start = get_timer(0);
283 		do {
284 			int ret;
285 
286 			mdelay(50);	/* Insert some reasonable delay */
287 			ret = send_command(dev, EC_CMD_GET_COMMS_STATUS, 0,
288 					NULL, 0,
289 					(uint8_t **)&resp, sizeof(*resp));
290 			if (ret < 0)
291 				return ret;
292 
293 			if (get_timer(start) > CROS_EC_CMD_TIMEOUT_MS) {
294 				debug("%s: Command %#02x timeout\n",
295 				      __func__, cmd);
296 				return -EC_RES_TIMEOUT;
297 			}
298 		} while (resp->flags & EC_COMMS_STATUS_PROCESSING);
299 
300 		/* OK it completed, so read the status response */
301 		/* not sure why it was 0 for the last argument */
302 		len = send_command(dev, EC_CMD_RESEND_RESPONSE, 0,
303 				NULL, 0, &din, din_len);
304 	}
305 
306 	debug("%s: len=%d, din=%p\n", __func__, len, din);
307 	if (dinp) {
308 		/* If we have any data to return, it must be 64bit-aligned */
309 		assert(len <= 0 || !((uintptr_t)din & 7));
310 		*dinp = din;
311 	}
312 
313 	return len;
314 }
315 
316 /**
317  * Send a command to the CROS-EC device and return the reply.
318  *
319  * The device's internal input/output buffers are used.
320  *
321  * @param dev		CROS-EC device
322  * @param cmd		Command to send (EC_CMD_...)
323  * @param cmd_version	Version of command to send (EC_VER_...)
324  * @param dout          Output data (may be NULL If dout_len=0)
325  * @param dout_len      Size of output data in bytes
326  * @param din           Response data (may be NULL If din_len=0).
327  *			It not NULL, it is a place for ec_command() to copy the
328  *      data to.
329  * @param din_len       Maximum size of response in bytes
330  * @return number of bytes in response, or -ve on error
331  */
332 static int ec_command(struct cros_ec_dev *dev, uint8_t cmd, int cmd_version,
333 		      const void *dout, int dout_len,
334 		      void *din, int din_len)
335 {
336 	uint8_t *in_buffer;
337 	int len;
338 
339 	assert((din_len == 0) || din);
340 	len = ec_command_inptr(dev, cmd, cmd_version, dout, dout_len,
341 			&in_buffer, din_len);
342 	if (len > 0) {
343 		/*
344 		 * If we were asked to put it somewhere, do so, otherwise just
345 		 * disregard the result.
346 		 */
347 		if (din && in_buffer) {
348 			assert(len <= din_len);
349 			memmove(din, in_buffer, len);
350 		}
351 	}
352 	return len;
353 }
354 
355 int cros_ec_scan_keyboard(struct udevice *dev, struct mbkp_keyscan *scan)
356 {
357 	struct cros_ec_dev *cdev = dev_get_uclass_priv(dev);
358 
359 	if (ec_command(cdev, EC_CMD_MKBP_STATE, 0, NULL, 0, scan,
360 		       sizeof(scan->data)) != sizeof(scan->data))
361 		return -1;
362 
363 	return 0;
364 }
365 
366 int cros_ec_read_id(struct cros_ec_dev *dev, char *id, int maxlen)
367 {
368 	struct ec_response_get_version *r;
369 
370 	if (ec_command_inptr(dev, EC_CMD_GET_VERSION, 0, NULL, 0,
371 			(uint8_t **)&r, sizeof(*r)) != sizeof(*r))
372 		return -1;
373 
374 	if (maxlen > (int)sizeof(r->version_string_ro))
375 		maxlen = sizeof(r->version_string_ro);
376 
377 	switch (r->current_image) {
378 	case EC_IMAGE_RO:
379 		memcpy(id, r->version_string_ro, maxlen);
380 		break;
381 	case EC_IMAGE_RW:
382 		memcpy(id, r->version_string_rw, maxlen);
383 		break;
384 	default:
385 		return -1;
386 	}
387 
388 	id[maxlen - 1] = '\0';
389 	return 0;
390 }
391 
392 int cros_ec_read_version(struct cros_ec_dev *dev,
393 		       struct ec_response_get_version **versionp)
394 {
395 	if (ec_command_inptr(dev, EC_CMD_GET_VERSION, 0, NULL, 0,
396 			(uint8_t **)versionp, sizeof(**versionp))
397 			!= sizeof(**versionp))
398 		return -1;
399 
400 	return 0;
401 }
402 
403 int cros_ec_read_build_info(struct cros_ec_dev *dev, char **strp)
404 {
405 	if (ec_command_inptr(dev, EC_CMD_GET_BUILD_INFO, 0, NULL, 0,
406 			(uint8_t **)strp, EC_PROTO2_MAX_PARAM_SIZE) < 0)
407 		return -1;
408 
409 	return 0;
410 }
411 
412 int cros_ec_read_current_image(struct cros_ec_dev *dev,
413 		enum ec_current_image *image)
414 {
415 	struct ec_response_get_version *r;
416 
417 	if (ec_command_inptr(dev, EC_CMD_GET_VERSION, 0, NULL, 0,
418 			(uint8_t **)&r, sizeof(*r)) != sizeof(*r))
419 		return -1;
420 
421 	*image = r->current_image;
422 	return 0;
423 }
424 
425 static int cros_ec_wait_on_hash_done(struct cros_ec_dev *dev,
426 				  struct ec_response_vboot_hash *hash)
427 {
428 	struct ec_params_vboot_hash p;
429 	ulong start;
430 
431 	start = get_timer(0);
432 	while (hash->status == EC_VBOOT_HASH_STATUS_BUSY) {
433 		mdelay(50);	/* Insert some reasonable delay */
434 
435 		p.cmd = EC_VBOOT_HASH_GET;
436 		if (ec_command(dev, EC_CMD_VBOOT_HASH, 0, &p, sizeof(p),
437 		       hash, sizeof(*hash)) < 0)
438 			return -1;
439 
440 		if (get_timer(start) > CROS_EC_CMD_HASH_TIMEOUT_MS) {
441 			debug("%s: EC_VBOOT_HASH_GET timeout\n", __func__);
442 			return -EC_RES_TIMEOUT;
443 		}
444 	}
445 	return 0;
446 }
447 
448 
449 int cros_ec_read_hash(struct cros_ec_dev *dev,
450 		struct ec_response_vboot_hash *hash)
451 {
452 	struct ec_params_vboot_hash p;
453 	int rv;
454 
455 	p.cmd = EC_VBOOT_HASH_GET;
456 	if (ec_command(dev, EC_CMD_VBOOT_HASH, 0, &p, sizeof(p),
457 		       hash, sizeof(*hash)) < 0)
458 		return -1;
459 
460 	/* If the EC is busy calculating the hash, fidget until it's done. */
461 	rv = cros_ec_wait_on_hash_done(dev, hash);
462 	if (rv)
463 		return rv;
464 
465 	/* If the hash is valid, we're done. Otherwise, we have to kick it off
466 	 * again and wait for it to complete. Note that we explicitly assume
467 	 * that hashing zero bytes is always wrong, even though that would
468 	 * produce a valid hash value. */
469 	if (hash->status == EC_VBOOT_HASH_STATUS_DONE && hash->size)
470 		return 0;
471 
472 	debug("%s: No valid hash (status=%d size=%d). Compute one...\n",
473 	      __func__, hash->status, hash->size);
474 
475 	p.cmd = EC_VBOOT_HASH_START;
476 	p.hash_type = EC_VBOOT_HASH_TYPE_SHA256;
477 	p.nonce_size = 0;
478 	p.offset = EC_VBOOT_HASH_OFFSET_RW;
479 
480 	if (ec_command(dev, EC_CMD_VBOOT_HASH, 0, &p, sizeof(p),
481 		       hash, sizeof(*hash)) < 0)
482 		return -1;
483 
484 	rv = cros_ec_wait_on_hash_done(dev, hash);
485 	if (rv)
486 		return rv;
487 
488 	debug("%s: hash done\n", __func__);
489 
490 	return 0;
491 }
492 
493 static int cros_ec_invalidate_hash(struct cros_ec_dev *dev)
494 {
495 	struct ec_params_vboot_hash p;
496 	struct ec_response_vboot_hash *hash;
497 
498 	/* We don't have an explict command for the EC to discard its current
499 	 * hash value, so we'll just tell it to calculate one that we know is
500 	 * wrong (we claim that hashing zero bytes is always invalid).
501 	 */
502 	p.cmd = EC_VBOOT_HASH_RECALC;
503 	p.hash_type = EC_VBOOT_HASH_TYPE_SHA256;
504 	p.nonce_size = 0;
505 	p.offset = 0;
506 	p.size = 0;
507 
508 	debug("%s:\n", __func__);
509 
510 	if (ec_command_inptr(dev, EC_CMD_VBOOT_HASH, 0, &p, sizeof(p),
511 		       (uint8_t **)&hash, sizeof(*hash)) < 0)
512 		return -1;
513 
514 	/* No need to wait for it to finish */
515 	return 0;
516 }
517 
518 int cros_ec_reboot(struct cros_ec_dev *dev, enum ec_reboot_cmd cmd,
519 		uint8_t flags)
520 {
521 	struct ec_params_reboot_ec p;
522 
523 	p.cmd = cmd;
524 	p.flags = flags;
525 
526 	if (ec_command_inptr(dev, EC_CMD_REBOOT_EC, 0, &p, sizeof(p), NULL, 0)
527 			< 0)
528 		return -1;
529 
530 	if (!(flags & EC_REBOOT_FLAG_ON_AP_SHUTDOWN)) {
531 		/*
532 		 * EC reboot will take place immediately so delay to allow it
533 		 * to complete.  Note that some reboot types (EC_REBOOT_COLD)
534 		 * will reboot the AP as well, in which case we won't actually
535 		 * get to this point.
536 		 */
537 		/*
538 		 * TODO(rspangler@chromium.org): Would be nice if we had a
539 		 * better way to determine when the reboot is complete.  Could
540 		 * we poll a memory-mapped LPC value?
541 		 */
542 		udelay(50000);
543 	}
544 
545 	return 0;
546 }
547 
548 int cros_ec_interrupt_pending(struct udevice *dev)
549 {
550 	struct cros_ec_dev *cdev = dev_get_uclass_priv(dev);
551 
552 	/* no interrupt support : always poll */
553 	if (!dm_gpio_is_valid(&cdev->ec_int))
554 		return -ENOENT;
555 
556 	return dm_gpio_get_value(&cdev->ec_int);
557 }
558 
559 int cros_ec_info(struct cros_ec_dev *dev, struct ec_response_mkbp_info *info)
560 {
561 	if (ec_command(dev, EC_CMD_MKBP_INFO, 0, NULL, 0, info,
562 		       sizeof(*info)) != sizeof(*info))
563 		return -1;
564 
565 	return 0;
566 }
567 
568 int cros_ec_get_host_events(struct cros_ec_dev *dev, uint32_t *events_ptr)
569 {
570 	struct ec_response_host_event_mask *resp;
571 
572 	/*
573 	 * Use the B copy of the event flags, because the main copy is already
574 	 * used by ACPI/SMI.
575 	 */
576 	if (ec_command_inptr(dev, EC_CMD_HOST_EVENT_GET_B, 0, NULL, 0,
577 		       (uint8_t **)&resp, sizeof(*resp)) < (int)sizeof(*resp))
578 		return -1;
579 
580 	if (resp->mask & EC_HOST_EVENT_MASK(EC_HOST_EVENT_INVALID))
581 		return -1;
582 
583 	*events_ptr = resp->mask;
584 	return 0;
585 }
586 
587 int cros_ec_clear_host_events(struct cros_ec_dev *dev, uint32_t events)
588 {
589 	struct ec_params_host_event_mask params;
590 
591 	params.mask = events;
592 
593 	/*
594 	 * Use the B copy of the event flags, so it affects the data returned
595 	 * by cros_ec_get_host_events().
596 	 */
597 	if (ec_command_inptr(dev, EC_CMD_HOST_EVENT_CLEAR_B, 0,
598 		       &params, sizeof(params), NULL, 0) < 0)
599 		return -1;
600 
601 	return 0;
602 }
603 
604 int cros_ec_flash_protect(struct cros_ec_dev *dev,
605 		       uint32_t set_mask, uint32_t set_flags,
606 		       struct ec_response_flash_protect *resp)
607 {
608 	struct ec_params_flash_protect params;
609 
610 	params.mask = set_mask;
611 	params.flags = set_flags;
612 
613 	if (ec_command(dev, EC_CMD_FLASH_PROTECT, EC_VER_FLASH_PROTECT,
614 		       &params, sizeof(params),
615 		       resp, sizeof(*resp)) != sizeof(*resp))
616 		return -1;
617 
618 	return 0;
619 }
620 
621 static int cros_ec_check_version(struct cros_ec_dev *dev)
622 {
623 	struct ec_params_hello req;
624 	struct ec_response_hello *resp;
625 
626 	struct dm_cros_ec_ops *ops;
627 	int ret;
628 
629 	ops = dm_cros_ec_get_ops(dev->dev);
630 	if (ops->check_version) {
631 		ret = ops->check_version(dev->dev);
632 		if (ret)
633 			return ret;
634 	}
635 
636 	/*
637 	 * TODO(sjg@chromium.org).
638 	 * There is a strange oddity here with the EC. We could just ignore
639 	 * the response, i.e. pass the last two parameters as NULL and 0.
640 	 * In this case we won't read back very many bytes from the EC.
641 	 * On the I2C bus the EC gets upset about this and will try to send
642 	 * the bytes anyway. This means that we will have to wait for that
643 	 * to complete before continuing with a new EC command.
644 	 *
645 	 * This problem is probably unique to the I2C bus.
646 	 *
647 	 * So for now, just read all the data anyway.
648 	 */
649 
650 	/* Try sending a version 3 packet */
651 	dev->protocol_version = 3;
652 	req.in_data = 0;
653 	if (ec_command_inptr(dev, EC_CMD_HELLO, 0, &req, sizeof(req),
654 			     (uint8_t **)&resp, sizeof(*resp)) > 0) {
655 		return 0;
656 	}
657 
658 	/* Try sending a version 2 packet */
659 	dev->protocol_version = 2;
660 	if (ec_command_inptr(dev, EC_CMD_HELLO, 0, &req, sizeof(req),
661 		       (uint8_t **)&resp, sizeof(*resp)) > 0) {
662 		return 0;
663 	}
664 
665 	/*
666 	 * Fail if we're still here, since the EC doesn't understand any
667 	 * protcol version we speak.  Version 1 interface without command
668 	 * version is no longer supported, and we don't know about any new
669 	 * protocol versions.
670 	 */
671 	dev->protocol_version = 0;
672 	printf("%s: ERROR: old EC interface not supported\n", __func__);
673 	return -1;
674 }
675 
676 int cros_ec_test(struct cros_ec_dev *dev)
677 {
678 	struct ec_params_hello req;
679 	struct ec_response_hello *resp;
680 
681 	req.in_data = 0x12345678;
682 	if (ec_command_inptr(dev, EC_CMD_HELLO, 0, &req, sizeof(req),
683 		       (uint8_t **)&resp, sizeof(*resp)) < sizeof(*resp)) {
684 		printf("ec_command_inptr() returned error\n");
685 		return -1;
686 	}
687 	if (resp->out_data != req.in_data + 0x01020304) {
688 		printf("Received invalid handshake %x\n", resp->out_data);
689 		return -1;
690 	}
691 
692 	return 0;
693 }
694 
695 int cros_ec_flash_offset(struct cros_ec_dev *dev, enum ec_flash_region region,
696 		      uint32_t *offset, uint32_t *size)
697 {
698 	struct ec_params_flash_region_info p;
699 	struct ec_response_flash_region_info *r;
700 	int ret;
701 
702 	p.region = region;
703 	ret = ec_command_inptr(dev, EC_CMD_FLASH_REGION_INFO,
704 			 EC_VER_FLASH_REGION_INFO,
705 			 &p, sizeof(p), (uint8_t **)&r, sizeof(*r));
706 	if (ret != sizeof(*r))
707 		return -1;
708 
709 	if (offset)
710 		*offset = r->offset;
711 	if (size)
712 		*size = r->size;
713 
714 	return 0;
715 }
716 
717 int cros_ec_flash_erase(struct cros_ec_dev *dev, uint32_t offset, uint32_t size)
718 {
719 	struct ec_params_flash_erase p;
720 
721 	p.offset = offset;
722 	p.size = size;
723 	return ec_command_inptr(dev, EC_CMD_FLASH_ERASE, 0, &p, sizeof(p),
724 			NULL, 0);
725 }
726 
727 /**
728  * Write a single block to the flash
729  *
730  * Write a block of data to the EC flash. The size must not exceed the flash
731  * write block size which you can obtain from cros_ec_flash_write_burst_size().
732  *
733  * The offset starts at 0. You can obtain the region information from
734  * cros_ec_flash_offset() to find out where to write for a particular region.
735  *
736  * Attempting to write to the region where the EC is currently running from
737  * will result in an error.
738  *
739  * @param dev		CROS-EC device
740  * @param data		Pointer to data buffer to write
741  * @param offset	Offset within flash to write to.
742  * @param size		Number of bytes to write
743  * @return 0 if ok, -1 on error
744  */
745 static int cros_ec_flash_write_block(struct cros_ec_dev *dev,
746 		const uint8_t *data, uint32_t offset, uint32_t size)
747 {
748 	struct ec_params_flash_write *p;
749 	int ret;
750 
751 	p = malloc(sizeof(*p) + size);
752 	if (!p)
753 		return -ENOMEM;
754 
755 	p->offset = offset;
756 	p->size = size;
757 	assert(data && p->size <= EC_FLASH_WRITE_VER0_SIZE);
758 	memcpy(p + 1, data, p->size);
759 
760 	ret = ec_command_inptr(dev, EC_CMD_FLASH_WRITE, 0,
761 			  p, sizeof(*p) + size, NULL, 0) >= 0 ? 0 : -1;
762 
763 	free(p);
764 
765 	return ret;
766 }
767 
768 /**
769  * Return optimal flash write burst size
770  */
771 static int cros_ec_flash_write_burst_size(struct cros_ec_dev *dev)
772 {
773 	return EC_FLASH_WRITE_VER0_SIZE;
774 }
775 
776 /**
777  * Check if a block of data is erased (all 0xff)
778  *
779  * This function is useful when dealing with flash, for checking whether a
780  * data block is erased and thus does not need to be programmed.
781  *
782  * @param data		Pointer to data to check (must be word-aligned)
783  * @param size		Number of bytes to check (must be word-aligned)
784  * @return 0 if erased, non-zero if any word is not erased
785  */
786 static int cros_ec_data_is_erased(const uint32_t *data, int size)
787 {
788 	assert(!(size & 3));
789 	size /= sizeof(uint32_t);
790 	for (; size > 0; size -= 4, data++)
791 		if (*data != -1U)
792 			return 0;
793 
794 	return 1;
795 }
796 
797 /**
798  * Read back flash parameters
799  *
800  * This function reads back parameters of the flash as reported by the EC
801  *
802  * @param dev  Pointer to device
803  * @param info Pointer to output flash info struct
804  */
805 int cros_ec_read_flashinfo(struct cros_ec_dev *dev,
806 			  struct ec_response_flash_info *info)
807 {
808 	int ret;
809 
810 	ret = ec_command(dev, EC_CMD_FLASH_INFO, 0,
811 			 NULL, 0, info, sizeof(*info));
812 	if (ret < 0)
813 		return ret;
814 
815 	return ret < sizeof(*info) ? -1 : 0;
816 }
817 
818 int cros_ec_flash_write(struct cros_ec_dev *dev, const uint8_t *data,
819 		     uint32_t offset, uint32_t size)
820 {
821 	uint32_t burst = cros_ec_flash_write_burst_size(dev);
822 	uint32_t end, off;
823 	int ret;
824 
825 	/*
826 	 * TODO: round up to the nearest multiple of write size.  Can get away
827 	 * without that on link right now because its write size is 4 bytes.
828 	 */
829 	end = offset + size;
830 	for (off = offset; off < end; off += burst, data += burst) {
831 		uint32_t todo;
832 
833 		/* If the data is empty, there is no point in programming it */
834 		todo = min(end - off, burst);
835 		if (dev->optimise_flash_write &&
836 				cros_ec_data_is_erased((uint32_t *)data, todo))
837 			continue;
838 
839 		ret = cros_ec_flash_write_block(dev, data, off, todo);
840 		if (ret)
841 			return ret;
842 	}
843 
844 	return 0;
845 }
846 
847 /**
848  * Read a single block from the flash
849  *
850  * Read a block of data from the EC flash. The size must not exceed the flash
851  * write block size which you can obtain from cros_ec_flash_write_burst_size().
852  *
853  * The offset starts at 0. You can obtain the region information from
854  * cros_ec_flash_offset() to find out where to read for a particular region.
855  *
856  * @param dev		CROS-EC device
857  * @param data		Pointer to data buffer to read into
858  * @param offset	Offset within flash to read from
859  * @param size		Number of bytes to read
860  * @return 0 if ok, -1 on error
861  */
862 static int cros_ec_flash_read_block(struct cros_ec_dev *dev, uint8_t *data,
863 				 uint32_t offset, uint32_t size)
864 {
865 	struct ec_params_flash_read p;
866 
867 	p.offset = offset;
868 	p.size = size;
869 
870 	return ec_command(dev, EC_CMD_FLASH_READ, 0,
871 			  &p, sizeof(p), data, size) >= 0 ? 0 : -1;
872 }
873 
874 int cros_ec_flash_read(struct cros_ec_dev *dev, uint8_t *data, uint32_t offset,
875 		    uint32_t size)
876 {
877 	uint32_t burst = cros_ec_flash_write_burst_size(dev);
878 	uint32_t end, off;
879 	int ret;
880 
881 	end = offset + size;
882 	for (off = offset; off < end; off += burst, data += burst) {
883 		ret = cros_ec_flash_read_block(dev, data, off,
884 					    min(end - off, burst));
885 		if (ret)
886 			return ret;
887 	}
888 
889 	return 0;
890 }
891 
892 int cros_ec_flash_update_rw(struct cros_ec_dev *dev,
893 			 const uint8_t *image, int image_size)
894 {
895 	uint32_t rw_offset, rw_size;
896 	int ret;
897 
898 	if (cros_ec_flash_offset(dev, EC_FLASH_REGION_RW, &rw_offset, &rw_size))
899 		return -1;
900 	if (image_size > (int)rw_size)
901 		return -1;
902 
903 	/* Invalidate the existing hash, just in case the AP reboots
904 	 * unexpectedly during the update. If that happened, the EC RW firmware
905 	 * would be invalid, but the EC would still have the original hash.
906 	 */
907 	ret = cros_ec_invalidate_hash(dev);
908 	if (ret)
909 		return ret;
910 
911 	/*
912 	 * Erase the entire RW section, so that the EC doesn't see any garbage
913 	 * past the new image if it's smaller than the current image.
914 	 *
915 	 * TODO: could optimize this to erase just the current image, since
916 	 * presumably everything past that is 0xff's.  But would still need to
917 	 * round up to the nearest multiple of erase size.
918 	 */
919 	ret = cros_ec_flash_erase(dev, rw_offset, rw_size);
920 	if (ret)
921 		return ret;
922 
923 	/* Write the image */
924 	ret = cros_ec_flash_write(dev, image, rw_offset, image_size);
925 	if (ret)
926 		return ret;
927 
928 	return 0;
929 }
930 
931 int cros_ec_read_vbnvcontext(struct cros_ec_dev *dev, uint8_t *block)
932 {
933 	struct ec_params_vbnvcontext p;
934 	int len;
935 
936 	p.op = EC_VBNV_CONTEXT_OP_READ;
937 
938 	len = ec_command(dev, EC_CMD_VBNV_CONTEXT, EC_VER_VBNV_CONTEXT,
939 			&p, sizeof(p), block, EC_VBNV_BLOCK_SIZE);
940 	if (len < EC_VBNV_BLOCK_SIZE)
941 		return -1;
942 
943 	return 0;
944 }
945 
946 int cros_ec_write_vbnvcontext(struct cros_ec_dev *dev, const uint8_t *block)
947 {
948 	struct ec_params_vbnvcontext p;
949 	int len;
950 
951 	p.op = EC_VBNV_CONTEXT_OP_WRITE;
952 	memcpy(p.block, block, sizeof(p.block));
953 
954 	len = ec_command_inptr(dev, EC_CMD_VBNV_CONTEXT, EC_VER_VBNV_CONTEXT,
955 			&p, sizeof(p), NULL, 0);
956 	if (len < 0)
957 		return -1;
958 
959 	return 0;
960 }
961 
962 int cros_ec_set_ldo(struct udevice *dev, uint8_t index, uint8_t state)
963 {
964 	struct cros_ec_dev *cdev = dev_get_uclass_priv(dev);
965 	struct ec_params_ldo_set params;
966 
967 	params.index = index;
968 	params.state = state;
969 
970 	if (ec_command_inptr(cdev, EC_CMD_LDO_SET, 0, &params, sizeof(params),
971 			     NULL, 0))
972 		return -1;
973 
974 	return 0;
975 }
976 
977 int cros_ec_get_ldo(struct udevice *dev, uint8_t index, uint8_t *state)
978 {
979 	struct cros_ec_dev *cdev = dev_get_uclass_priv(dev);
980 	struct ec_params_ldo_get params;
981 	struct ec_response_ldo_get *resp;
982 
983 	params.index = index;
984 
985 	if (ec_command_inptr(cdev, EC_CMD_LDO_GET, 0, &params, sizeof(params),
986 			     (uint8_t **)&resp, sizeof(*resp)) !=
987 			     sizeof(*resp))
988 		return -1;
989 
990 	*state = resp->state;
991 
992 	return 0;
993 }
994 
995 int cros_ec_register(struct udevice *dev)
996 {
997 	struct cros_ec_dev *cdev = dev_get_uclass_priv(dev);
998 	char id[MSG_BYTES];
999 
1000 	cdev->dev = dev;
1001 	gpio_request_by_name(dev, "ec-interrupt", 0, &cdev->ec_int,
1002 			     GPIOD_IS_IN);
1003 	cdev->optimise_flash_write = dev_read_bool(dev, "optimise-flash-write");
1004 
1005 	if (cros_ec_check_version(cdev)) {
1006 		debug("%s: Could not detect CROS-EC version\n", __func__);
1007 		return -CROS_EC_ERR_CHECK_VERSION;
1008 	}
1009 
1010 	if (cros_ec_read_id(cdev, id, sizeof(id))) {
1011 		debug("%s: Could not read KBC ID\n", __func__);
1012 		return -CROS_EC_ERR_READ_ID;
1013 	}
1014 
1015 	/* Remember this device for use by the cros_ec command */
1016 	debug("Google Chrome EC v%d CROS-EC driver ready, id '%s'\n",
1017 	      cdev->protocol_version, id);
1018 
1019 	return 0;
1020 }
1021 
1022 int cros_ec_decode_ec_flash(struct udevice *dev, struct fdt_cros_ec *config)
1023 {
1024 	ofnode flash_node, node;
1025 
1026 	flash_node = dev_read_subnode(dev, "flash");
1027 	if (!ofnode_valid(flash_node)) {
1028 		debug("Failed to find flash node\n");
1029 		return -1;
1030 	}
1031 
1032 	if (of_read_fmap_entry(flash_node, "flash", &config->flash)) {
1033 		debug("Failed to decode flash node in chrome-ec\n");
1034 		return -1;
1035 	}
1036 
1037 	config->flash_erase_value = ofnode_read_s32_default(flash_node,
1038 							    "erase-value", -1);
1039 	ofnode_for_each_subnode(node, flash_node) {
1040 		const char *name = ofnode_get_name(node);
1041 		enum ec_flash_region region;
1042 
1043 		if (0 == strcmp(name, "ro")) {
1044 			region = EC_FLASH_REGION_RO;
1045 		} else if (0 == strcmp(name, "rw")) {
1046 			region = EC_FLASH_REGION_RW;
1047 		} else if (0 == strcmp(name, "wp-ro")) {
1048 			region = EC_FLASH_REGION_WP_RO;
1049 		} else {
1050 			debug("Unknown EC flash region name '%s'\n", name);
1051 			return -1;
1052 		}
1053 
1054 		if (of_read_fmap_entry(node, "reg", &config->region[region])) {
1055 			debug("Failed to decode flash region in chrome-ec'\n");
1056 			return -1;
1057 		}
1058 	}
1059 
1060 	return 0;
1061 }
1062 
1063 int cros_ec_i2c_tunnel(struct udevice *dev, int port, struct i2c_msg *in,
1064 		       int nmsgs)
1065 {
1066 	struct cros_ec_dev *cdev = dev_get_uclass_priv(dev);
1067 	union {
1068 		struct ec_params_i2c_passthru p;
1069 		uint8_t outbuf[EC_PROTO2_MAX_PARAM_SIZE];
1070 	} params;
1071 	union {
1072 		struct ec_response_i2c_passthru r;
1073 		uint8_t inbuf[EC_PROTO2_MAX_PARAM_SIZE];
1074 	} response;
1075 	struct ec_params_i2c_passthru *p = &params.p;
1076 	struct ec_response_i2c_passthru *r = &response.r;
1077 	struct ec_params_i2c_passthru_msg *msg;
1078 	uint8_t *pdata, *read_ptr = NULL;
1079 	int read_len;
1080 	int size;
1081 	int rv;
1082 	int i;
1083 
1084 	p->port = port;
1085 
1086 	p->num_msgs = nmsgs;
1087 	size = sizeof(*p) + p->num_msgs * sizeof(*msg);
1088 
1089 	/* Create a message to write the register address and optional data */
1090 	pdata = (uint8_t *)p + size;
1091 
1092 	read_len = 0;
1093 	for (i = 0, msg = p->msg; i < nmsgs; i++, msg++, in++) {
1094 		bool is_read = in->flags & I2C_M_RD;
1095 
1096 		msg->addr_flags = in->addr;
1097 		msg->len = in->len;
1098 		if (is_read) {
1099 			msg->addr_flags |= EC_I2C_FLAG_READ;
1100 			read_len += in->len;
1101 			read_ptr = in->buf;
1102 			if (sizeof(*r) + read_len > sizeof(response)) {
1103 				puts("Read length too big for buffer\n");
1104 				return -1;
1105 			}
1106 		} else {
1107 			if (pdata - (uint8_t *)p + in->len > sizeof(params)) {
1108 				puts("Params too large for buffer\n");
1109 				return -1;
1110 			}
1111 			memcpy(pdata, in->buf, in->len);
1112 			pdata += in->len;
1113 		}
1114 	}
1115 
1116 	rv = ec_command(cdev, EC_CMD_I2C_PASSTHRU, 0, p, pdata - (uint8_t *)p,
1117 			r, sizeof(*r) + read_len);
1118 	if (rv < 0)
1119 		return rv;
1120 
1121 	/* Parse response */
1122 	if (r->i2c_status & EC_I2C_STATUS_ERROR) {
1123 		printf("Transfer failed with status=0x%x\n", r->i2c_status);
1124 		return -1;
1125 	}
1126 
1127 	if (rv < sizeof(*r) + read_len) {
1128 		puts("Truncated read response\n");
1129 		return -1;
1130 	}
1131 
1132 	/* We only support a single read message for each transfer */
1133 	if (read_len)
1134 		memcpy(read_ptr, r->data, read_len);
1135 
1136 	return 0;
1137 }
1138 
1139 UCLASS_DRIVER(cros_ec) = {
1140 	.id		= UCLASS_CROS_EC,
1141 	.name		= "cros_ec",
1142 	.per_device_auto_alloc_size = sizeof(struct cros_ec_dev),
1143 	.post_bind	= dm_scan_fdt_dev,
1144 };
1145