ARM: dts: at91: sama5d2_icp: fix i2c eeprom compatible
[platform/kernel/u-boot.git] / drivers / misc / cros_ec.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Chromium OS cros_ec driver
4  *
5  * Copyright (c) 2012 The Chromium OS Authors.
6  */
7
8 /*
9  * This is the interface to the Chrome OS EC. It provides keyboard functions,
10  * power control and battery management. Quite a few other functions are
11  * provided to enable the EC software to be updated, talk to the EC's I2C bus
12  * and store a small amount of data in a memory which persists while the EC
13  * is not reset.
14  */
15
16 #define LOG_CATEGORY UCLASS_CROS_EC
17
18 #include <common.h>
19 #include <command.h>
20 #include <dm.h>
21 #include <flash.h>
22 #include <i2c.h>
23 #include <cros_ec.h>
24 #include <fdtdec.h>
25 #include <log.h>
26 #include <malloc.h>
27 #include <spi.h>
28 #include <linux/delay.h>
29 #include <linux/errno.h>
30 #include <asm/io.h>
31 #include <asm-generic/gpio.h>
32 #include <dm/device-internal.h>
33 #include <dm/of_extra.h>
34 #include <dm/uclass-internal.h>
35
36 #ifdef DEBUG_TRACE
37 #define debug_trace(fmt, b...)  debug(fmt, #b)
38 #else
39 #define debug_trace(fmt, b...)
40 #endif
41
42 enum {
43         /* Timeout waiting for a flash erase command to complete */
44         CROS_EC_CMD_TIMEOUT_MS  = 5000,
45         /* Timeout waiting for a synchronous hash to be recomputed */
46         CROS_EC_CMD_HASH_TIMEOUT_MS = 2000,
47 };
48
49 #define INVALID_HCMD 0xFF
50
51 /*
52  * Map UHEPI masks to non UHEPI commands in order to support old EC FW
53  * which does not support UHEPI command.
54  */
55 static const struct {
56         u8 set_cmd;
57         u8 clear_cmd;
58         u8 get_cmd;
59 } event_map[] = {
60         [EC_HOST_EVENT_MAIN] = {
61                 INVALID_HCMD, EC_CMD_HOST_EVENT_CLEAR,
62                 INVALID_HCMD,
63         },
64         [EC_HOST_EVENT_B] = {
65                 INVALID_HCMD, EC_CMD_HOST_EVENT_CLEAR_B,
66                 EC_CMD_HOST_EVENT_GET_B,
67         },
68         [EC_HOST_EVENT_SCI_MASK] = {
69                 EC_CMD_HOST_EVENT_SET_SCI_MASK, INVALID_HCMD,
70                 EC_CMD_HOST_EVENT_GET_SCI_MASK,
71         },
72         [EC_HOST_EVENT_SMI_MASK] = {
73                 EC_CMD_HOST_EVENT_SET_SMI_MASK, INVALID_HCMD,
74                 EC_CMD_HOST_EVENT_GET_SMI_MASK,
75         },
76         [EC_HOST_EVENT_ALWAYS_REPORT_MASK] = {
77                 INVALID_HCMD, INVALID_HCMD, INVALID_HCMD,
78         },
79         [EC_HOST_EVENT_ACTIVE_WAKE_MASK] = {
80                 EC_CMD_HOST_EVENT_SET_WAKE_MASK, INVALID_HCMD,
81                 EC_CMD_HOST_EVENT_GET_WAKE_MASK,
82         },
83         [EC_HOST_EVENT_LAZY_WAKE_MASK_S0IX] = {
84                 EC_CMD_HOST_EVENT_SET_WAKE_MASK, INVALID_HCMD,
85                 EC_CMD_HOST_EVENT_GET_WAKE_MASK,
86         },
87         [EC_HOST_EVENT_LAZY_WAKE_MASK_S3] = {
88                 EC_CMD_HOST_EVENT_SET_WAKE_MASK, INVALID_HCMD,
89                 EC_CMD_HOST_EVENT_GET_WAKE_MASK,
90         },
91         [EC_HOST_EVENT_LAZY_WAKE_MASK_S5] = {
92                 EC_CMD_HOST_EVENT_SET_WAKE_MASK, INVALID_HCMD,
93                 EC_CMD_HOST_EVENT_GET_WAKE_MASK,
94         },
95 };
96
97 void cros_ec_dump_data(const char *name, int cmd, const uint8_t *data, int len)
98 {
99 #ifdef DEBUG
100         int i;
101
102         printf("%s: ", name);
103         if (cmd != -1)
104                 printf("cmd=%#x: ", cmd);
105         for (i = 0; i < len; i++)
106                 printf("%02x ", data[i]);
107         printf("\n");
108 #endif
109 }
110
111 /*
112  * Calculate a simple 8-bit checksum of a data block
113  *
114  * @param data  Data block to checksum
115  * @param size  Size of data block in bytes
116  * @return checksum value (0 to 255)
117  */
118 int cros_ec_calc_checksum(const uint8_t *data, int size)
119 {
120         int csum, i;
121
122         for (i = csum = 0; i < size; i++)
123                 csum += data[i];
124         return csum & 0xff;
125 }
126
127 /**
128  * Create a request packet for protocol version 3.
129  *
130  * The packet is stored in the device's internal output buffer.
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  * @return packet size in bytes, or <0 if error.
138  */
139 static int create_proto3_request(struct cros_ec_dev *cdev,
140                                  int cmd, int cmd_version,
141                                  const void *dout, int dout_len)
142 {
143         struct ec_host_request *rq = (struct ec_host_request *)cdev->dout;
144         int out_bytes = dout_len + sizeof(*rq);
145
146         /* Fail if output size is too big */
147         if (out_bytes > (int)sizeof(cdev->dout)) {
148                 debug("%s: Cannot send %d bytes\n", __func__, dout_len);
149                 return -EC_RES_REQUEST_TRUNCATED;
150         }
151
152         /* Fill in request packet */
153         rq->struct_version = EC_HOST_REQUEST_VERSION;
154         rq->checksum = 0;
155         rq->command = cmd;
156         rq->command_version = cmd_version;
157         rq->reserved = 0;
158         rq->data_len = dout_len;
159
160         /* Copy data after header */
161         memcpy(rq + 1, dout, dout_len);
162
163         /* Write checksum field so the entire packet sums to 0 */
164         rq->checksum = (uint8_t)(-cros_ec_calc_checksum(cdev->dout, out_bytes));
165
166         cros_ec_dump_data("out", cmd, cdev->dout, out_bytes);
167
168         /* Return size of request packet */
169         return out_bytes;
170 }
171
172 /**
173  * Prepare the device to receive a protocol version 3 response.
174  *
175  * @param dev           CROS-EC device
176  * @param din_len       Maximum size of response in bytes
177  * @return maximum expected number of bytes in response, or <0 if error.
178  */
179 static int prepare_proto3_response_buffer(struct cros_ec_dev *cdev, int din_len)
180 {
181         int in_bytes = din_len + sizeof(struct ec_host_response);
182
183         /* Fail if input size is too big */
184         if (in_bytes > (int)sizeof(cdev->din)) {
185                 debug("%s: Cannot receive %d bytes\n", __func__, din_len);
186                 return -EC_RES_RESPONSE_TOO_BIG;
187         }
188
189         /* Return expected size of response packet */
190         return in_bytes;
191 }
192
193 /**
194  * Handle a protocol version 3 response packet.
195  *
196  * The packet must already be stored in the device's internal input buffer.
197  *
198  * @param dev           CROS-EC device
199  * @param dinp          Returns pointer to response data
200  * @param din_len       Maximum size of response in bytes
201  * @return number of bytes of response data, or <0 if error. Note that error
202  * codes can be from errno.h or -ve EC_RES_INVALID_CHECKSUM values (and they
203  * overlap!)
204  */
205 static int handle_proto3_response(struct cros_ec_dev *dev,
206                                   uint8_t **dinp, int din_len)
207 {
208         struct ec_host_response *rs = (struct ec_host_response *)dev->din;
209         int in_bytes;
210         int csum;
211
212         cros_ec_dump_data("in-header", -1, dev->din, sizeof(*rs));
213
214         /* Check input data */
215         if (rs->struct_version != EC_HOST_RESPONSE_VERSION) {
216                 debug("%s: EC response version mismatch\n", __func__);
217                 return -EC_RES_INVALID_RESPONSE;
218         }
219
220         if (rs->reserved) {
221                 debug("%s: EC response reserved != 0\n", __func__);
222                 return -EC_RES_INVALID_RESPONSE;
223         }
224
225         if (rs->data_len > din_len) {
226                 debug("%s: EC returned too much data\n", __func__);
227                 return -EC_RES_RESPONSE_TOO_BIG;
228         }
229
230         cros_ec_dump_data("in-data", -1, dev->din + sizeof(*rs), rs->data_len);
231
232         /* Update in_bytes to actual data size */
233         in_bytes = sizeof(*rs) + rs->data_len;
234
235         /* Verify checksum */
236         csum = cros_ec_calc_checksum(dev->din, in_bytes);
237         if (csum) {
238                 debug("%s: EC response checksum invalid: 0x%02x\n", __func__,
239                       csum);
240                 return -EC_RES_INVALID_CHECKSUM;
241         }
242
243         /* Return error result, if any */
244         if (rs->result)
245                 return -(int)rs->result;
246
247         /* If we're still here, set response data pointer and return length */
248         *dinp = (uint8_t *)(rs + 1);
249
250         return rs->data_len;
251 }
252
253 static int send_command_proto3(struct cros_ec_dev *cdev,
254                                int cmd, int cmd_version,
255                                const void *dout, int dout_len,
256                                uint8_t **dinp, int din_len)
257 {
258         struct dm_cros_ec_ops *ops;
259         int out_bytes, in_bytes;
260         int rv;
261
262         /* Create request packet */
263         out_bytes = create_proto3_request(cdev, cmd, cmd_version,
264                                           dout, dout_len);
265         if (out_bytes < 0)
266                 return out_bytes;
267
268         /* Prepare response buffer */
269         in_bytes = prepare_proto3_response_buffer(cdev, din_len);
270         if (in_bytes < 0)
271                 return in_bytes;
272
273         ops = dm_cros_ec_get_ops(cdev->dev);
274         rv = ops->packet ? ops->packet(cdev->dev, out_bytes, in_bytes) :
275                         -ENOSYS;
276         if (rv < 0)
277                 return rv;
278
279         /* Process the response */
280         return handle_proto3_response(cdev, dinp, din_len);
281 }
282
283 static int send_command(struct cros_ec_dev *dev, uint cmd, int cmd_version,
284                         const void *dout, int dout_len,
285                         uint8_t **dinp, int din_len)
286 {
287         struct dm_cros_ec_ops *ops;
288         int ret = -1;
289
290         /* Handle protocol version 3 support */
291         if (dev->protocol_version == 3) {
292                 return send_command_proto3(dev, cmd, cmd_version,
293                                            dout, dout_len, dinp, din_len);
294         }
295
296         ops = dm_cros_ec_get_ops(dev->dev);
297         ret = ops->command(dev->dev, cmd, cmd_version,
298                            (const uint8_t *)dout, dout_len, dinp, din_len);
299
300         return ret;
301 }
302
303 /**
304  * Send a command to the CROS-EC device and return the reply.
305  *
306  * The device's internal input/output buffers are used.
307  *
308  * @param dev           CROS-EC device
309  * @param cmd           Command to send (EC_CMD_...)
310  * @param cmd_version   Version of command to send (EC_VER_...)
311  * @param dout          Output data (may be NULL If dout_len=0)
312  * @param dout_len      Size of output data in bytes
313  * @param dinp          Response data (may be NULL If din_len=0).
314  *                      If not NULL, it will be updated to point to the data
315  *                      and will always be double word aligned (64-bits)
316  * @param din_len       Maximum size of response in bytes
317  * @return number of bytes in response, or -ve on error
318  */
319 static int ec_command_inptr(struct udevice *dev, uint cmd,
320                             int cmd_version, const void *dout, int dout_len,
321                             uint8_t **dinp, int din_len)
322 {
323         struct cros_ec_dev *cdev = dev_get_uclass_priv(dev);
324         uint8_t *din = NULL;
325         int len;
326
327         len = send_command(cdev, cmd, cmd_version, dout, dout_len, &din,
328                            din_len);
329
330         /* If the command doesn't complete, wait a while */
331         if (len == -EC_RES_IN_PROGRESS) {
332                 struct ec_response_get_comms_status *resp = NULL;
333                 ulong start;
334
335                 /* Wait for command to complete */
336                 start = get_timer(0);
337                 do {
338                         int ret;
339
340                         mdelay(50);     /* Insert some reasonable delay */
341                         ret = send_command(cdev, EC_CMD_GET_COMMS_STATUS, 0,
342                                            NULL, 0,
343                                            (uint8_t **)&resp, sizeof(*resp));
344                         if (ret < 0)
345                                 return ret;
346
347                         if (get_timer(start) > CROS_EC_CMD_TIMEOUT_MS) {
348                                 debug("%s: Command %#02x timeout\n",
349                                       __func__, cmd);
350                                 return -EC_RES_TIMEOUT;
351                         }
352                 } while (resp->flags & EC_COMMS_STATUS_PROCESSING);
353
354                 /* OK it completed, so read the status response */
355                 /* not sure why it was 0 for the last argument */
356                 len = send_command(cdev, EC_CMD_RESEND_RESPONSE, 0, NULL, 0,
357                                    &din, din_len);
358         }
359
360         debug("%s: len=%d, din=%p\n", __func__, len, din);
361         if (dinp) {
362                 /* If we have any data to return, it must be 64bit-aligned */
363                 assert(len <= 0 || !((uintptr_t)din & 7));
364                 *dinp = din;
365         }
366
367         return len;
368 }
369
370 /**
371  * Send a command to the CROS-EC device and return the reply.
372  *
373  * The device's internal input/output buffers are used.
374  *
375  * @param dev           CROS-EC device
376  * @param cmd           Command to send (EC_CMD_...)
377  * @param cmd_version   Version of command to send (EC_VER_...)
378  * @param dout          Output data (may be NULL If dout_len=0)
379  * @param dout_len      Size of output data in bytes
380  * @param din           Response data (may be NULL If din_len=0).
381  *                      It not NULL, it is a place for ec_command() to copy the
382  *      data to.
383  * @param din_len       Maximum size of response in bytes
384  * @return number of bytes in response, or -ve on error
385  */
386 static int ec_command(struct udevice *dev, uint cmd, int cmd_version,
387                       const void *dout, int dout_len,
388                       void *din, int din_len)
389 {
390         uint8_t *in_buffer;
391         int len;
392
393         assert((din_len == 0) || din);
394         len = ec_command_inptr(dev, cmd, cmd_version, dout, dout_len,
395                                &in_buffer, din_len);
396         if (len > 0) {
397                 /*
398                  * If we were asked to put it somewhere, do so, otherwise just
399                  * disregard the result.
400                  */
401                 if (din && in_buffer) {
402                         assert(len <= din_len);
403                         memmove(din, in_buffer, len);
404                 }
405         }
406         return len;
407 }
408
409 int cros_ec_scan_keyboard(struct udevice *dev, struct mbkp_keyscan *scan)
410 {
411         if (ec_command(dev, EC_CMD_MKBP_STATE, 0, NULL, 0, scan,
412                        sizeof(scan->data)) != sizeof(scan->data))
413                 return -1;
414
415         return 0;
416 }
417
418 int cros_ec_get_next_event(struct udevice *dev,
419                            struct ec_response_get_next_event *event)
420 {
421         int ret;
422
423         ret = ec_command(dev, EC_CMD_GET_NEXT_EVENT, 0, NULL, 0,
424                          event, sizeof(*event));
425         if (ret < 0)
426                 return ret;
427         else if (ret != sizeof(*event))
428                 return -EC_RES_INVALID_RESPONSE;
429
430         return 0;
431 }
432
433 int cros_ec_read_id(struct udevice *dev, char *id, int maxlen)
434 {
435         struct ec_response_get_version *r;
436         int ret;
437
438         ret = ec_command_inptr(dev, EC_CMD_GET_VERSION, 0, NULL, 0,
439                                (uint8_t **)&r, sizeof(*r));
440         if (ret != sizeof(*r)) {
441                 log_err("Got rc %d, expected %u\n", ret, (uint)sizeof(*r));
442                 return -1;
443         }
444
445         if (maxlen > (int)sizeof(r->version_string_ro))
446                 maxlen = sizeof(r->version_string_ro);
447
448         switch (r->current_image) {
449         case EC_IMAGE_RO:
450                 memcpy(id, r->version_string_ro, maxlen);
451                 break;
452         case EC_IMAGE_RW:
453                 memcpy(id, r->version_string_rw, maxlen);
454                 break;
455         default:
456                 log_err("Invalid EC image %d\n", r->current_image);
457                 return -1;
458         }
459
460         id[maxlen - 1] = '\0';
461         return 0;
462 }
463
464 int cros_ec_read_version(struct udevice *dev,
465                          struct ec_response_get_version **versionp)
466 {
467         if (ec_command_inptr(dev, EC_CMD_GET_VERSION, 0, NULL, 0,
468                         (uint8_t **)versionp, sizeof(**versionp))
469                         != sizeof(**versionp))
470                 return -1;
471
472         return 0;
473 }
474
475 int cros_ec_read_build_info(struct udevice *dev, char **strp)
476 {
477         if (ec_command_inptr(dev, EC_CMD_GET_BUILD_INFO, 0, NULL, 0,
478                         (uint8_t **)strp, EC_PROTO2_MAX_PARAM_SIZE) < 0)
479                 return -1;
480
481         return 0;
482 }
483
484 int cros_ec_read_current_image(struct udevice *dev,
485                                enum ec_current_image *image)
486 {
487         struct ec_response_get_version *r;
488
489         if (ec_command_inptr(dev, EC_CMD_GET_VERSION, 0, NULL, 0,
490                         (uint8_t **)&r, sizeof(*r)) != sizeof(*r))
491                 return -1;
492
493         *image = r->current_image;
494         return 0;
495 }
496
497 static int cros_ec_wait_on_hash_done(struct udevice *dev,
498                                      struct ec_response_vboot_hash *hash)
499 {
500         struct ec_params_vboot_hash p;
501         ulong start;
502
503         start = get_timer(0);
504         while (hash->status == EC_VBOOT_HASH_STATUS_BUSY) {
505                 mdelay(50);     /* Insert some reasonable delay */
506
507                 p.cmd = EC_VBOOT_HASH_GET;
508                 if (ec_command(dev, EC_CMD_VBOOT_HASH, 0, &p, sizeof(p),
509                        hash, sizeof(*hash)) < 0)
510                         return -1;
511
512                 if (get_timer(start) > CROS_EC_CMD_HASH_TIMEOUT_MS) {
513                         debug("%s: EC_VBOOT_HASH_GET timeout\n", __func__);
514                         return -EC_RES_TIMEOUT;
515                 }
516         }
517         return 0;
518 }
519
520 int cros_ec_read_hash(struct udevice *dev, uint hash_offset,
521                       struct ec_response_vboot_hash *hash)
522 {
523         struct ec_params_vboot_hash p;
524         int rv;
525
526         p.cmd = EC_VBOOT_HASH_GET;
527         p.offset = hash_offset;
528         if (ec_command(dev, EC_CMD_VBOOT_HASH, 0, &p, sizeof(p),
529                        hash, sizeof(*hash)) < 0)
530                 return -1;
531
532         /* If the EC is busy calculating the hash, fidget until it's done. */
533         rv = cros_ec_wait_on_hash_done(dev, hash);
534         if (rv)
535                 return rv;
536
537         /* If the hash is valid, we're done. Otherwise, we have to kick it off
538          * again and wait for it to complete. Note that we explicitly assume
539          * that hashing zero bytes is always wrong, even though that would
540          * produce a valid hash value. */
541         if (hash->status == EC_VBOOT_HASH_STATUS_DONE && hash->size)
542                 return 0;
543
544         debug("%s: No valid hash (status=%d size=%d). Compute one...\n",
545               __func__, hash->status, hash->size);
546
547         p.cmd = EC_VBOOT_HASH_START;
548         p.hash_type = EC_VBOOT_HASH_TYPE_SHA256;
549         p.nonce_size = 0;
550         p.offset = hash_offset;
551
552         if (ec_command(dev, EC_CMD_VBOOT_HASH, 0, &p, sizeof(p),
553                        hash, sizeof(*hash)) < 0)
554                 return -1;
555
556         rv = cros_ec_wait_on_hash_done(dev, hash);
557         if (rv)
558                 return rv;
559
560         debug("%s: hash done\n", __func__);
561
562         return 0;
563 }
564
565 static int cros_ec_invalidate_hash(struct udevice *dev)
566 {
567         struct ec_params_vboot_hash p;
568         struct ec_response_vboot_hash *hash;
569
570         /* We don't have an explict command for the EC to discard its current
571          * hash value, so we'll just tell it to calculate one that we know is
572          * wrong (we claim that hashing zero bytes is always invalid).
573          */
574         p.cmd = EC_VBOOT_HASH_RECALC;
575         p.hash_type = EC_VBOOT_HASH_TYPE_SHA256;
576         p.nonce_size = 0;
577         p.offset = 0;
578         p.size = 0;
579
580         debug("%s:\n", __func__);
581
582         if (ec_command_inptr(dev, EC_CMD_VBOOT_HASH, 0, &p, sizeof(p),
583                        (uint8_t **)&hash, sizeof(*hash)) < 0)
584                 return -1;
585
586         /* No need to wait for it to finish */
587         return 0;
588 }
589
590 int cros_ec_reboot(struct udevice *dev, enum ec_reboot_cmd cmd, uint8_t flags)
591 {
592         struct ec_params_reboot_ec p;
593
594         p.cmd = cmd;
595         p.flags = flags;
596
597         if (ec_command_inptr(dev, EC_CMD_REBOOT_EC, 0, &p, sizeof(p), NULL, 0)
598                         < 0)
599                 return -1;
600
601         if (!(flags & EC_REBOOT_FLAG_ON_AP_SHUTDOWN)) {
602                 /*
603                  * EC reboot will take place immediately so delay to allow it
604                  * to complete.  Note that some reboot types (EC_REBOOT_COLD)
605                  * will reboot the AP as well, in which case we won't actually
606                  * get to this point.
607                  */
608                 /*
609                  * TODO(rspangler@chromium.org): Would be nice if we had a
610                  * better way to determine when the reboot is complete.  Could
611                  * we poll a memory-mapped LPC value?
612                  */
613                 udelay(50000);
614         }
615
616         return 0;
617 }
618
619 int cros_ec_interrupt_pending(struct udevice *dev)
620 {
621         struct cros_ec_dev *cdev = dev_get_uclass_priv(dev);
622
623         /* no interrupt support : always poll */
624         if (!dm_gpio_is_valid(&cdev->ec_int))
625                 return -ENOENT;
626
627         return dm_gpio_get_value(&cdev->ec_int);
628 }
629
630 int cros_ec_info(struct udevice *dev, struct ec_response_mkbp_info *info)
631 {
632         if (ec_command(dev, EC_CMD_MKBP_INFO, 0, NULL, 0, info,
633                        sizeof(*info)) != sizeof(*info))
634                 return -1;
635
636         return 0;
637 }
638
639 int cros_ec_get_event_mask(struct udevice *dev, uint type, uint32_t *mask)
640 {
641         struct ec_response_host_event_mask rsp;
642         int ret;
643
644         ret = ec_command(dev, type, 0, NULL, 0, &rsp, sizeof(rsp));
645         if (ret < 0)
646                 return ret;
647         else if (ret != sizeof(rsp))
648                 return -EINVAL;
649
650         *mask = rsp.mask;
651
652         return 0;
653 }
654
655 int cros_ec_set_event_mask(struct udevice *dev, uint type, uint32_t mask)
656 {
657         struct ec_params_host_event_mask req;
658         int ret;
659
660         req.mask = mask;
661
662         ret = ec_command(dev, type, 0, &req, sizeof(req), NULL, 0);
663         if (ret < 0)
664                 return ret;
665
666         return 0;
667 }
668
669 int cros_ec_get_host_events(struct udevice *dev, uint32_t *events_ptr)
670 {
671         struct ec_response_host_event_mask *resp;
672
673         /*
674          * Use the B copy of the event flags, because the main copy is already
675          * used by ACPI/SMI.
676          */
677         if (ec_command_inptr(dev, EC_CMD_HOST_EVENT_GET_B, 0, NULL, 0,
678                        (uint8_t **)&resp, sizeof(*resp)) < (int)sizeof(*resp))
679                 return -1;
680
681         if (resp->mask & EC_HOST_EVENT_MASK(EC_HOST_EVENT_INVALID))
682                 return -1;
683
684         *events_ptr = resp->mask;
685         return 0;
686 }
687
688 int cros_ec_clear_host_events(struct udevice *dev, uint32_t events)
689 {
690         struct ec_params_host_event_mask params;
691
692         params.mask = events;
693
694         /*
695          * Use the B copy of the event flags, so it affects the data returned
696          * by cros_ec_get_host_events().
697          */
698         if (ec_command_inptr(dev, EC_CMD_HOST_EVENT_CLEAR_B, 0,
699                        &params, sizeof(params), NULL, 0) < 0)
700                 return -1;
701
702         return 0;
703 }
704
705 int cros_ec_flash_protect(struct udevice *dev, uint32_t set_mask,
706                           uint32_t set_flags,
707                           struct ec_response_flash_protect *resp)
708 {
709         struct ec_params_flash_protect params;
710
711         params.mask = set_mask;
712         params.flags = set_flags;
713
714         if (ec_command(dev, EC_CMD_FLASH_PROTECT, EC_VER_FLASH_PROTECT,
715                        &params, sizeof(params),
716                        resp, sizeof(*resp)) != sizeof(*resp))
717                 return -1;
718
719         return 0;
720 }
721
722 int cros_ec_entering_mode(struct udevice *dev, int mode)
723 {
724         int rc;
725
726         rc = ec_command(dev, EC_CMD_ENTERING_MODE, 0, &mode, sizeof(mode),
727                         NULL, 0);
728         if (rc)
729                 return -1;
730         return 0;
731 }
732
733 static int cros_ec_check_version(struct udevice *dev)
734 {
735         struct cros_ec_dev *cdev = dev_get_uclass_priv(dev);
736         struct ec_params_hello req;
737         struct ec_response_hello *resp;
738
739         struct dm_cros_ec_ops *ops;
740         int ret;
741
742         ops = dm_cros_ec_get_ops(dev);
743         if (ops->check_version) {
744                 ret = ops->check_version(dev);
745                 if (ret)
746                         return ret;
747         }
748
749         /*
750          * TODO(sjg@chromium.org).
751          * There is a strange oddity here with the EC. We could just ignore
752          * the response, i.e. pass the last two parameters as NULL and 0.
753          * In this case we won't read back very many bytes from the EC.
754          * On the I2C bus the EC gets upset about this and will try to send
755          * the bytes anyway. This means that we will have to wait for that
756          * to complete before continuing with a new EC command.
757          *
758          * This problem is probably unique to the I2C bus.
759          *
760          * So for now, just read all the data anyway.
761          */
762
763         /* Try sending a version 3 packet */
764         cdev->protocol_version = 3;
765         req.in_data = 0;
766         if (ec_command_inptr(dev, EC_CMD_HELLO, 0, &req, sizeof(req),
767                              (uint8_t **)&resp, sizeof(*resp)) > 0)
768                 return 0;
769
770         /* Try sending a version 2 packet */
771         cdev->protocol_version = 2;
772         if (ec_command_inptr(dev, EC_CMD_HELLO, 0, &req, sizeof(req),
773                              (uint8_t **)&resp, sizeof(*resp)) > 0)
774                 return 0;
775
776         /*
777          * Fail if we're still here, since the EC doesn't understand any
778          * protcol version we speak.  Version 1 interface without command
779          * version is no longer supported, and we don't know about any new
780          * protocol versions.
781          */
782         cdev->protocol_version = 0;
783         printf("%s: ERROR: old EC interface not supported\n", __func__);
784         return -1;
785 }
786
787 int cros_ec_test(struct udevice *dev)
788 {
789         struct ec_params_hello req;
790         struct ec_response_hello *resp;
791
792         req.in_data = 0x12345678;
793         if (ec_command_inptr(dev, EC_CMD_HELLO, 0, &req, sizeof(req),
794                        (uint8_t **)&resp, sizeof(*resp)) < sizeof(*resp)) {
795                 printf("ec_command_inptr() returned error\n");
796                 return -1;
797         }
798         if (resp->out_data != req.in_data + 0x01020304) {
799                 printf("Received invalid handshake %x\n", resp->out_data);
800                 return -1;
801         }
802
803         return 0;
804 }
805
806 int cros_ec_flash_offset(struct udevice *dev, enum ec_flash_region region,
807                       uint32_t *offset, uint32_t *size)
808 {
809         struct ec_params_flash_region_info p;
810         struct ec_response_flash_region_info *r;
811         int ret;
812
813         p.region = region;
814         ret = ec_command_inptr(dev, EC_CMD_FLASH_REGION_INFO,
815                          EC_VER_FLASH_REGION_INFO,
816                          &p, sizeof(p), (uint8_t **)&r, sizeof(*r));
817         if (ret != sizeof(*r))
818                 return -1;
819
820         if (offset)
821                 *offset = r->offset;
822         if (size)
823                 *size = r->size;
824
825         return 0;
826 }
827
828 int cros_ec_flash_erase(struct udevice *dev, uint32_t offset, uint32_t size)
829 {
830         struct ec_params_flash_erase p;
831
832         p.offset = offset;
833         p.size = size;
834         return ec_command_inptr(dev, EC_CMD_FLASH_ERASE, 0, &p, sizeof(p),
835                         NULL, 0);
836 }
837
838 /**
839  * Write a single block to the flash
840  *
841  * Write a block of data to the EC flash. The size must not exceed the flash
842  * write block size which you can obtain from cros_ec_flash_write_burst_size().
843  *
844  * The offset starts at 0. You can obtain the region information from
845  * cros_ec_flash_offset() to find out where to write for a particular region.
846  *
847  * Attempting to write to the region where the EC is currently running from
848  * will result in an error.
849  *
850  * @param dev           CROS-EC device
851  * @param data          Pointer to data buffer to write
852  * @param offset        Offset within flash to write to.
853  * @param size          Number of bytes to write
854  * @return 0 if ok, -1 on error
855  */
856 static int cros_ec_flash_write_block(struct udevice *dev, const uint8_t *data,
857                                      uint32_t offset, uint32_t size)
858 {
859         struct ec_params_flash_write *p;
860         int ret;
861
862         p = malloc(sizeof(*p) + size);
863         if (!p)
864                 return -ENOMEM;
865
866         p->offset = offset;
867         p->size = size;
868         assert(data && p->size <= EC_FLASH_WRITE_VER0_SIZE);
869         memcpy(p + 1, data, p->size);
870
871         ret = ec_command_inptr(dev, EC_CMD_FLASH_WRITE, 0,
872                           p, sizeof(*p) + size, NULL, 0) >= 0 ? 0 : -1;
873
874         free(p);
875
876         return ret;
877 }
878
879 /**
880  * Return optimal flash write burst size
881  */
882 static int cros_ec_flash_write_burst_size(struct udevice *dev)
883 {
884         return EC_FLASH_WRITE_VER0_SIZE;
885 }
886
887 /**
888  * Check if a block of data is erased (all 0xff)
889  *
890  * This function is useful when dealing with flash, for checking whether a
891  * data block is erased and thus does not need to be programmed.
892  *
893  * @param data          Pointer to data to check (must be word-aligned)
894  * @param size          Number of bytes to check (must be word-aligned)
895  * @return 0 if erased, non-zero if any word is not erased
896  */
897 static int cros_ec_data_is_erased(const uint32_t *data, int size)
898 {
899         assert(!(size & 3));
900         size /= sizeof(uint32_t);
901         for (; size > 0; size -= 4, data++)
902                 if (*data != -1U)
903                         return 0;
904
905         return 1;
906 }
907
908 /**
909  * Read back flash parameters
910  *
911  * This function reads back parameters of the flash as reported by the EC
912  *
913  * @param dev  Pointer to device
914  * @param info Pointer to output flash info struct
915  */
916 int cros_ec_read_flashinfo(struct udevice *dev,
917                            struct ec_response_flash_info *info)
918 {
919         int ret;
920
921         ret = ec_command(dev, EC_CMD_FLASH_INFO, 0,
922                          NULL, 0, info, sizeof(*info));
923         if (ret < 0)
924                 return ret;
925
926         return ret < sizeof(*info) ? -1 : 0;
927 }
928
929 int cros_ec_flash_write(struct udevice *dev, const uint8_t *data,
930                         uint32_t offset, uint32_t size)
931 {
932         struct cros_ec_dev *cdev = dev_get_uclass_priv(dev);
933         uint32_t burst = cros_ec_flash_write_burst_size(dev);
934         uint32_t end, off;
935         int ret;
936
937         if (!burst)
938                 return -EINVAL;
939
940         /*
941          * TODO: round up to the nearest multiple of write size.  Can get away
942          * without that on link right now because its write size is 4 bytes.
943          */
944         end = offset + size;
945         for (off = offset; off < end; off += burst, data += burst) {
946                 uint32_t todo;
947
948                 /* If the data is empty, there is no point in programming it */
949                 todo = min(end - off, burst);
950                 if (cdev->optimise_flash_write &&
951                     cros_ec_data_is_erased((uint32_t *)data, todo))
952                         continue;
953
954                 ret = cros_ec_flash_write_block(dev, data, off, todo);
955                 if (ret)
956                         return ret;
957         }
958
959         return 0;
960 }
961
962 /**
963  * Run verification on a slot
964  *
965  * @param me     CrosEc instance
966  * @param region Region to run verification on
967  * @return 0 if success or not applicable. Non-zero if verification failed.
968  */
969 int cros_ec_efs_verify(struct udevice *dev, enum ec_flash_region region)
970 {
971         struct ec_params_efs_verify p;
972         int rv;
973
974         log_info("EFS: EC is verifying updated image...\n");
975         p.region = region;
976
977         rv = ec_command(dev, EC_CMD_EFS_VERIFY, 0, &p, sizeof(p), NULL, 0);
978         if (rv >= 0) {
979                 log_info("EFS: Verification success\n");
980                 return 0;
981         }
982         if (rv == -EC_RES_INVALID_COMMAND) {
983                 log_info("EFS: EC doesn't support EFS_VERIFY command\n");
984                 return 0;
985         }
986         log_info("EFS: Verification failed\n");
987
988         return rv;
989 }
990
991 /**
992  * Read a single block from the flash
993  *
994  * Read a block of data from the EC flash. The size must not exceed the flash
995  * write block size which you can obtain from cros_ec_flash_write_burst_size().
996  *
997  * The offset starts at 0. You can obtain the region information from
998  * cros_ec_flash_offset() to find out where to read for a particular region.
999  *
1000  * @param dev           CROS-EC device
1001  * @param data          Pointer to data buffer to read into
1002  * @param offset        Offset within flash to read from
1003  * @param size          Number of bytes to read
1004  * @return 0 if ok, -1 on error
1005  */
1006 static int cros_ec_flash_read_block(struct udevice *dev, uint8_t *data,
1007                                     uint32_t offset, uint32_t size)
1008 {
1009         struct ec_params_flash_read p;
1010
1011         p.offset = offset;
1012         p.size = size;
1013
1014         return ec_command(dev, EC_CMD_FLASH_READ, 0,
1015                           &p, sizeof(p), data, size) >= 0 ? 0 : -1;
1016 }
1017
1018 int cros_ec_flash_read(struct udevice *dev, uint8_t *data, uint32_t offset,
1019                        uint32_t size)
1020 {
1021         uint32_t burst = cros_ec_flash_write_burst_size(dev);
1022         uint32_t end, off;
1023         int ret;
1024
1025         end = offset + size;
1026         for (off = offset; off < end; off += burst, data += burst) {
1027                 ret = cros_ec_flash_read_block(dev, data, off,
1028                                             min(end - off, burst));
1029                 if (ret)
1030                         return ret;
1031         }
1032
1033         return 0;
1034 }
1035
1036 int cros_ec_flash_update_rw(struct udevice *dev, const uint8_t *image,
1037                             int image_size)
1038 {
1039         uint32_t rw_offset, rw_size;
1040         int ret;
1041
1042         if (cros_ec_flash_offset(dev, EC_FLASH_REGION_ACTIVE, &rw_offset,
1043                 &rw_size))
1044                 return -1;
1045         if (image_size > (int)rw_size)
1046                 return -1;
1047
1048         /* Invalidate the existing hash, just in case the AP reboots
1049          * unexpectedly during the update. If that happened, the EC RW firmware
1050          * would be invalid, but the EC would still have the original hash.
1051          */
1052         ret = cros_ec_invalidate_hash(dev);
1053         if (ret)
1054                 return ret;
1055
1056         /*
1057          * Erase the entire RW section, so that the EC doesn't see any garbage
1058          * past the new image if it's smaller than the current image.
1059          *
1060          * TODO: could optimize this to erase just the current image, since
1061          * presumably everything past that is 0xff's.  But would still need to
1062          * round up to the nearest multiple of erase size.
1063          */
1064         ret = cros_ec_flash_erase(dev, rw_offset, rw_size);
1065         if (ret)
1066                 return ret;
1067
1068         /* Write the image */
1069         ret = cros_ec_flash_write(dev, image, rw_offset, image_size);
1070         if (ret)
1071                 return ret;
1072
1073         return 0;
1074 }
1075
1076 int cros_ec_read_nvdata(struct udevice *dev, uint8_t *block, int size)
1077 {
1078         struct ec_params_vbnvcontext p;
1079         int len;
1080
1081         if (size != EC_VBNV_BLOCK_SIZE && size != EC_VBNV_BLOCK_SIZE_V2)
1082                 return -EINVAL;
1083
1084         p.op = EC_VBNV_CONTEXT_OP_READ;
1085
1086         len = ec_command(dev, EC_CMD_VBNV_CONTEXT, EC_VER_VBNV_CONTEXT,
1087                          &p, sizeof(uint32_t) + size, block, size);
1088         if (len != size) {
1089                 log_err("Expected %d bytes, got %d\n", size, len);
1090                 return -EIO;
1091         }
1092
1093         return 0;
1094 }
1095
1096 int cros_ec_write_nvdata(struct udevice *dev, const uint8_t *block, int size)
1097 {
1098         struct ec_params_vbnvcontext p;
1099         int len;
1100
1101         if (size != EC_VBNV_BLOCK_SIZE && size != EC_VBNV_BLOCK_SIZE_V2)
1102                 return -EINVAL;
1103         p.op = EC_VBNV_CONTEXT_OP_WRITE;
1104         memcpy(p.block, block, size);
1105
1106         len = ec_command_inptr(dev, EC_CMD_VBNV_CONTEXT, EC_VER_VBNV_CONTEXT,
1107                         &p, sizeof(uint32_t) + size, NULL, 0);
1108         if (len < 0)
1109                 return -1;
1110
1111         return 0;
1112 }
1113
1114 int cros_ec_battery_cutoff(struct udevice *dev, uint8_t flags)
1115 {
1116         struct ec_params_battery_cutoff p;
1117         int len;
1118
1119         p.flags = flags;
1120         len = ec_command(dev, EC_CMD_BATTERY_CUT_OFF, 1, &p, sizeof(p),
1121                          NULL, 0);
1122
1123         if (len < 0)
1124                 return -1;
1125         return 0;
1126 }
1127
1128 int cros_ec_set_ldo(struct udevice *dev, uint8_t index, uint8_t state)
1129 {
1130         struct ec_params_ldo_set params;
1131
1132         params.index = index;
1133         params.state = state;
1134
1135         if (ec_command_inptr(dev, EC_CMD_LDO_SET, 0, &params, sizeof(params),
1136                              NULL, 0))
1137                 return -1;
1138
1139         return 0;
1140 }
1141
1142 int cros_ec_get_ldo(struct udevice *dev, uint8_t index, uint8_t *state)
1143 {
1144         struct ec_params_ldo_get params;
1145         struct ec_response_ldo_get *resp;
1146
1147         params.index = index;
1148
1149         if (ec_command_inptr(dev, EC_CMD_LDO_GET, 0, &params, sizeof(params),
1150                              (uint8_t **)&resp, sizeof(*resp)) !=
1151                              sizeof(*resp))
1152                 return -1;
1153
1154         *state = resp->state;
1155
1156         return 0;
1157 }
1158
1159 int cros_ec_register(struct udevice *dev)
1160 {
1161         struct cros_ec_dev *cdev = dev_get_uclass_priv(dev);
1162         char id[MSG_BYTES];
1163
1164         cdev->dev = dev;
1165         gpio_request_by_name(dev, "ec-interrupt", 0, &cdev->ec_int,
1166                              GPIOD_IS_IN);
1167         cdev->optimise_flash_write = dev_read_bool(dev, "optimise-flash-write");
1168
1169         if (cros_ec_check_version(dev)) {
1170                 debug("%s: Could not detect CROS-EC version\n", __func__);
1171                 return -CROS_EC_ERR_CHECK_VERSION;
1172         }
1173
1174         if (cros_ec_read_id(dev, id, sizeof(id))) {
1175                 debug("%s: Could not read KBC ID\n", __func__);
1176                 return -CROS_EC_ERR_READ_ID;
1177         }
1178
1179         /* Remember this device for use by the cros_ec command */
1180         debug("Google Chrome EC v%d CROS-EC driver ready, id '%s'\n",
1181               cdev->protocol_version, id);
1182
1183         return 0;
1184 }
1185
1186 int cros_ec_decode_ec_flash(struct udevice *dev, struct fdt_cros_ec *config)
1187 {
1188         ofnode flash_node, node;
1189
1190         flash_node = dev_read_subnode(dev, "flash");
1191         if (!ofnode_valid(flash_node)) {
1192                 debug("Failed to find flash node\n");
1193                 return -1;
1194         }
1195
1196         if (ofnode_read_fmap_entry(flash_node,  &config->flash)) {
1197                 debug("Failed to decode flash node in chrome-ec\n");
1198                 return -1;
1199         }
1200
1201         config->flash_erase_value = ofnode_read_s32_default(flash_node,
1202                                                             "erase-value", -1);
1203         ofnode_for_each_subnode(node, flash_node) {
1204                 const char *name = ofnode_get_name(node);
1205                 enum ec_flash_region region;
1206
1207                 if (0 == strcmp(name, "ro")) {
1208                         region = EC_FLASH_REGION_RO;
1209                 } else if (0 == strcmp(name, "rw")) {
1210                         region = EC_FLASH_REGION_ACTIVE;
1211                 } else if (0 == strcmp(name, "wp-ro")) {
1212                         region = EC_FLASH_REGION_WP_RO;
1213                 } else {
1214                         debug("Unknown EC flash region name '%s'\n", name);
1215                         return -1;
1216                 }
1217
1218                 if (ofnode_read_fmap_entry(node, &config->region[region])) {
1219                         debug("Failed to decode flash region in chrome-ec'\n");
1220                         return -1;
1221                 }
1222         }
1223
1224         return 0;
1225 }
1226
1227 int cros_ec_i2c_tunnel(struct udevice *dev, int port, struct i2c_msg *in,
1228                        int nmsgs)
1229 {
1230         union {
1231                 struct ec_params_i2c_passthru p;
1232                 uint8_t outbuf[EC_PROTO2_MAX_PARAM_SIZE];
1233         } params;
1234         union {
1235                 struct ec_response_i2c_passthru r;
1236                 uint8_t inbuf[EC_PROTO2_MAX_PARAM_SIZE];
1237         } response;
1238         struct ec_params_i2c_passthru *p = &params.p;
1239         struct ec_response_i2c_passthru *r = &response.r;
1240         struct ec_params_i2c_passthru_msg *msg;
1241         uint8_t *pdata, *read_ptr = NULL;
1242         int read_len;
1243         int size;
1244         int rv;
1245         int i;
1246
1247         p->port = port;
1248
1249         p->num_msgs = nmsgs;
1250         size = sizeof(*p) + p->num_msgs * sizeof(*msg);
1251
1252         /* Create a message to write the register address and optional data */
1253         pdata = (uint8_t *)p + size;
1254
1255         read_len = 0;
1256         for (i = 0, msg = p->msg; i < nmsgs; i++, msg++, in++) {
1257                 bool is_read = in->flags & I2C_M_RD;
1258
1259                 msg->addr_flags = in->addr;
1260                 msg->len = in->len;
1261                 if (is_read) {
1262                         msg->addr_flags |= EC_I2C_FLAG_READ;
1263                         read_len += in->len;
1264                         read_ptr = in->buf;
1265                         if (sizeof(*r) + read_len > sizeof(response)) {
1266                                 puts("Read length too big for buffer\n");
1267                                 return -1;
1268                         }
1269                 } else {
1270                         if (pdata - (uint8_t *)p + in->len > sizeof(params)) {
1271                                 puts("Params too large for buffer\n");
1272                                 return -1;
1273                         }
1274                         memcpy(pdata, in->buf, in->len);
1275                         pdata += in->len;
1276                 }
1277         }
1278
1279         rv = ec_command(dev, EC_CMD_I2C_PASSTHRU, 0, p, pdata - (uint8_t *)p,
1280                         r, sizeof(*r) + read_len);
1281         if (rv < 0)
1282                 return rv;
1283
1284         /* Parse response */
1285         if (r->i2c_status & EC_I2C_STATUS_ERROR) {
1286                 printf("Transfer failed with status=0x%x\n", r->i2c_status);
1287                 return -1;
1288         }
1289
1290         if (rv < sizeof(*r) + read_len) {
1291                 puts("Truncated read response\n");
1292                 return -1;
1293         }
1294
1295         /* We only support a single read message for each transfer */
1296         if (read_len)
1297                 memcpy(read_ptr, r->data, read_len);
1298
1299         return 0;
1300 }
1301
1302 int cros_ec_check_feature(struct udevice *dev, int feature)
1303 {
1304         struct ec_response_get_features r;
1305         int rv;
1306
1307         rv = ec_command(dev, EC_CMD_GET_FEATURES, 0, &r, sizeof(r), NULL, 0);
1308         if (rv)
1309                 return rv;
1310
1311         if (feature >= 8 * sizeof(r.flags))
1312                 return -1;
1313
1314         return r.flags[feature / 32] & EC_FEATURE_MASK_0(feature);
1315 }
1316
1317 /*
1318  * Query the EC for specified mask indicating enabled events.
1319  * The EC maintains separate event masks for SMI, SCI and WAKE.
1320  */
1321 static int cros_ec_uhepi_cmd(struct udevice *dev, uint mask, uint action,
1322                              uint64_t *value)
1323 {
1324         int ret;
1325         struct ec_params_host_event req;
1326         struct ec_response_host_event rsp;
1327
1328         req.action = action;
1329         req.mask_type = mask;
1330         if (action != EC_HOST_EVENT_GET)
1331                 req.value = *value;
1332         else
1333                 *value = 0;
1334         ret = ec_command(dev, EC_CMD_HOST_EVENT, 0, &req, sizeof(req), &rsp,
1335                          sizeof(rsp));
1336
1337         if (action != EC_HOST_EVENT_GET)
1338                 return ret;
1339         if (ret == 0)
1340                 *value = rsp.value;
1341
1342         return ret;
1343 }
1344
1345 static int cros_ec_handle_non_uhepi_cmd(struct udevice *dev, uint hcmd,
1346                                         uint action, uint64_t *value)
1347 {
1348         int ret = -1;
1349         struct ec_params_host_event_mask req;
1350         struct ec_response_host_event_mask rsp;
1351
1352         if (hcmd == INVALID_HCMD)
1353                 return ret;
1354
1355         if (action != EC_HOST_EVENT_GET)
1356                 req.mask = (uint32_t)*value;
1357         else
1358                 *value = 0;
1359
1360         ret = ec_command(dev, hcmd, 0, &req, sizeof(req), &rsp, sizeof(rsp));
1361         if (action != EC_HOST_EVENT_GET)
1362                 return ret;
1363         if (ret == 0)
1364                 *value = rsp.mask;
1365
1366         return ret;
1367 }
1368
1369 bool cros_ec_is_uhepi_supported(struct udevice *dev)
1370 {
1371 #define UHEPI_SUPPORTED 1
1372 #define UHEPI_NOT_SUPPORTED 2
1373         static int uhepi_support;
1374
1375         if (!uhepi_support) {
1376                 uhepi_support = cros_ec_check_feature(dev,
1377                         EC_FEATURE_UNIFIED_WAKE_MASKS) > 0 ? UHEPI_SUPPORTED :
1378                         UHEPI_NOT_SUPPORTED;
1379                 log_debug("Chrome EC: UHEPI %s\n",
1380                           uhepi_support == UHEPI_SUPPORTED ? "supported" :
1381                           "not supported");
1382         }
1383         return uhepi_support == UHEPI_SUPPORTED;
1384 }
1385
1386 static int cros_ec_get_mask(struct udevice *dev, uint type)
1387 {
1388         u64 value = 0;
1389
1390         if (cros_ec_is_uhepi_supported(dev)) {
1391                 cros_ec_uhepi_cmd(dev, type, EC_HOST_EVENT_GET, &value);
1392         } else {
1393                 assert(type < ARRAY_SIZE(event_map));
1394                 cros_ec_handle_non_uhepi_cmd(dev, event_map[type].get_cmd,
1395                                              EC_HOST_EVENT_GET, &value);
1396         }
1397         return value;
1398 }
1399
1400 static int cros_ec_clear_mask(struct udevice *dev, uint type, u64 mask)
1401 {
1402         if (cros_ec_is_uhepi_supported(dev))
1403                 return cros_ec_uhepi_cmd(dev, type, EC_HOST_EVENT_CLEAR, &mask);
1404
1405         assert(type < ARRAY_SIZE(event_map));
1406
1407         return cros_ec_handle_non_uhepi_cmd(dev, event_map[type].clear_cmd,
1408                                             EC_HOST_EVENT_CLEAR, &mask);
1409 }
1410
1411 uint64_t cros_ec_get_events_b(struct udevice *dev)
1412 {
1413         return cros_ec_get_mask(dev, EC_HOST_EVENT_B);
1414 }
1415
1416 int cros_ec_clear_events_b(struct udevice *dev, uint64_t mask)
1417 {
1418         log_debug("Chrome EC: clear events_b mask to 0x%016llx\n", mask);
1419
1420         return cros_ec_clear_mask(dev, EC_HOST_EVENT_B, mask);
1421 }
1422
1423 int cros_ec_read_limit_power(struct udevice *dev, int *limit_powerp)
1424 {
1425         struct ec_params_charge_state p;
1426         struct ec_response_charge_state r;
1427         int ret;
1428
1429         p.cmd = CHARGE_STATE_CMD_GET_PARAM;
1430         p.get_param.param = CS_PARAM_LIMIT_POWER;
1431         ret = ec_command(dev, EC_CMD_CHARGE_STATE, 0, &p, sizeof(p),
1432                          &r, sizeof(r));
1433
1434         /*
1435          * If our EC doesn't support the LIMIT_POWER parameter, assume that
1436          * LIMIT_POWER is not requested.
1437          */
1438         if (ret == -EC_RES_INVALID_PARAM || ret == -EC_RES_INVALID_COMMAND) {
1439                 log_warning("PARAM_LIMIT_POWER not supported by EC\n");
1440                 return -ENOSYS;
1441         }
1442
1443         if (ret != sizeof(r.get_param))
1444                 return -EINVAL;
1445
1446         *limit_powerp = r.get_param.value;
1447         return 0;
1448 }
1449
1450 int cros_ec_config_powerbtn(struct udevice *dev, uint32_t flags)
1451 {
1452         struct ec_params_config_power_button params;
1453         int ret;
1454
1455         params.flags = flags;
1456         ret = ec_command(dev, EC_CMD_CONFIG_POWER_BUTTON, 0,
1457                          &params, sizeof(params), NULL, 0);
1458         if (ret < 0)
1459                 return ret;
1460
1461         return 0;
1462 }
1463
1464 int cros_ec_get_lid_shutdown_mask(struct udevice *dev)
1465 {
1466         u32 mask;
1467         int ret;
1468
1469         ret = cros_ec_get_event_mask(dev, EC_CMD_HOST_EVENT_GET_SMI_MASK,
1470                                      &mask);
1471         if (ret < 0)
1472                 return ret;
1473
1474         return !!(mask & EC_HOST_EVENT_MASK(EC_HOST_EVENT_LID_CLOSED));
1475 }
1476
1477 int cros_ec_set_lid_shutdown_mask(struct udevice *dev, int enable)
1478 {
1479         u32 mask;
1480         int ret;
1481
1482         ret = cros_ec_get_event_mask(dev, EC_CMD_HOST_EVENT_GET_SMI_MASK,
1483                                      &mask);
1484         if (ret < 0)
1485                 return ret;
1486
1487         /* Set lid close event state in the EC SMI event mask */
1488         if (enable)
1489                 mask |= EC_HOST_EVENT_MASK(EC_HOST_EVENT_LID_CLOSED);
1490         else
1491                 mask &= ~EC_HOST_EVENT_MASK(EC_HOST_EVENT_LID_CLOSED);
1492
1493         ret = cros_ec_set_event_mask(dev, EC_CMD_HOST_EVENT_SET_SMI_MASK, mask);
1494         if (ret < 0)
1495                 return ret;
1496
1497         printf("EC: %sabled lid close event\n", enable ? "en" : "dis");
1498         return 0;
1499 }
1500
1501 UCLASS_DRIVER(cros_ec) = {
1502         .id             = UCLASS_CROS_EC,
1503         .name           = "cros-ec",
1504         .per_device_auto_alloc_size = sizeof(struct cros_ec_dev),
1505         .post_bind      = dm_scan_fdt_dev,
1506         .flags          = DM_UC_FLAG_ALLOC_PRIV_DMA,
1507 };