platform/chrome: cros_ec_proto: drop unneeded BUG_ON() in prepare_packet()
[linux-2.6-microblaze.git] / drivers / platform / chrome / cros_ec_proto.c
1 // SPDX-License-Identifier: GPL-2.0
2 // ChromeOS EC communication protocol helper functions
3 //
4 // Copyright (C) 2015 Google, Inc
5
6 #include <linux/delay.h>
7 #include <linux/device.h>
8 #include <linux/module.h>
9 #include <linux/platform_data/cros_ec_commands.h>
10 #include <linux/platform_data/cros_ec_proto.h>
11 #include <linux/slab.h>
12 #include <asm/unaligned.h>
13
14 #include "cros_ec_trace.h"
15
16 #define EC_COMMAND_RETRIES      50
17
18 static const int cros_ec_error_map[] = {
19         [EC_RES_INVALID_COMMAND] = -EOPNOTSUPP,
20         [EC_RES_ERROR] = -EIO,
21         [EC_RES_INVALID_PARAM] = -EINVAL,
22         [EC_RES_ACCESS_DENIED] = -EACCES,
23         [EC_RES_INVALID_RESPONSE] = -EPROTO,
24         [EC_RES_INVALID_VERSION] = -ENOPROTOOPT,
25         [EC_RES_INVALID_CHECKSUM] = -EBADMSG,
26         [EC_RES_IN_PROGRESS] = -EINPROGRESS,
27         [EC_RES_UNAVAILABLE] = -ENODATA,
28         [EC_RES_TIMEOUT] = -ETIMEDOUT,
29         [EC_RES_OVERFLOW] = -EOVERFLOW,
30         [EC_RES_INVALID_HEADER] = -EBADR,
31         [EC_RES_REQUEST_TRUNCATED] = -EBADR,
32         [EC_RES_RESPONSE_TOO_BIG] = -EFBIG,
33         [EC_RES_BUS_ERROR] = -EFAULT,
34         [EC_RES_BUSY] = -EBUSY,
35         [EC_RES_INVALID_HEADER_VERSION] = -EBADMSG,
36         [EC_RES_INVALID_HEADER_CRC] = -EBADMSG,
37         [EC_RES_INVALID_DATA_CRC] = -EBADMSG,
38         [EC_RES_DUP_UNAVAILABLE] = -ENODATA,
39 };
40
41 static int cros_ec_map_error(uint32_t result)
42 {
43         int ret = 0;
44
45         if (result != EC_RES_SUCCESS) {
46                 if (result < ARRAY_SIZE(cros_ec_error_map) && cros_ec_error_map[result])
47                         ret = cros_ec_error_map[result];
48                 else
49                         ret = -EPROTO;
50         }
51
52         return ret;
53 }
54
55 static int prepare_packet(struct cros_ec_device *ec_dev,
56                           struct cros_ec_command *msg)
57 {
58         struct ec_host_request *request;
59         u8 *out;
60         int i;
61         u8 csum = 0;
62
63         BUG_ON(msg->outsize + sizeof(*request) > ec_dev->dout_size);
64
65         out = ec_dev->dout;
66         request = (struct ec_host_request *)out;
67         request->struct_version = EC_HOST_REQUEST_VERSION;
68         request->checksum = 0;
69         request->command = msg->command;
70         request->command_version = msg->version;
71         request->reserved = 0;
72         request->data_len = msg->outsize;
73
74         for (i = 0; i < sizeof(*request); i++)
75                 csum += out[i];
76
77         /* Copy data and update checksum */
78         memcpy(out + sizeof(*request), msg->data, msg->outsize);
79         for (i = 0; i < msg->outsize; i++)
80                 csum += msg->data[i];
81
82         request->checksum = -csum;
83
84         return sizeof(*request) + msg->outsize;
85 }
86
87 static int send_command(struct cros_ec_device *ec_dev,
88                         struct cros_ec_command *msg)
89 {
90         int ret;
91         int (*xfer_fxn)(struct cros_ec_device *ec, struct cros_ec_command *msg);
92
93         if (ec_dev->proto_version > 2)
94                 xfer_fxn = ec_dev->pkt_xfer;
95         else
96                 xfer_fxn = ec_dev->cmd_xfer;
97
98         if (!xfer_fxn) {
99                 /*
100                  * This error can happen if a communication error happened and
101                  * the EC is trying to use protocol v2, on an underlying
102                  * communication mechanism that does not support v2.
103                  */
104                 dev_err_once(ec_dev->dev,
105                              "missing EC transfer API, cannot send command\n");
106                 return -EIO;
107         }
108
109         trace_cros_ec_request_start(msg);
110         ret = (*xfer_fxn)(ec_dev, msg);
111         trace_cros_ec_request_done(msg, ret);
112         if (msg->result == EC_RES_IN_PROGRESS) {
113                 int i;
114                 struct cros_ec_command *status_msg;
115                 struct ec_response_get_comms_status *status;
116
117                 status_msg = kmalloc(sizeof(*status_msg) + sizeof(*status),
118                                      GFP_KERNEL);
119                 if (!status_msg)
120                         return -ENOMEM;
121
122                 status_msg->version = 0;
123                 status_msg->command = EC_CMD_GET_COMMS_STATUS;
124                 status_msg->insize = sizeof(*status);
125                 status_msg->outsize = 0;
126
127                 /*
128                  * Query the EC's status until it's no longer busy or
129                  * we encounter an error.
130                  */
131                 for (i = 0; i < EC_COMMAND_RETRIES; i++) {
132                         usleep_range(10000, 11000);
133
134                         trace_cros_ec_request_start(status_msg);
135                         ret = (*xfer_fxn)(ec_dev, status_msg);
136                         trace_cros_ec_request_done(status_msg, ret);
137                         if (ret == -EAGAIN)
138                                 continue;
139                         if (ret < 0)
140                                 break;
141
142                         msg->result = status_msg->result;
143                         if (status_msg->result != EC_RES_SUCCESS)
144                                 break;
145
146                         status = (struct ec_response_get_comms_status *)
147                                  status_msg->data;
148                         if (!(status->flags & EC_COMMS_STATUS_PROCESSING))
149                                 break;
150                 }
151
152                 kfree(status_msg);
153         }
154
155         return ret;
156 }
157
158 /**
159  * cros_ec_prepare_tx() - Prepare an outgoing message in the output buffer.
160  * @ec_dev: Device to register.
161  * @msg: Message to write.
162  *
163  * This is intended to be used by all ChromeOS EC drivers, but at present
164  * only SPI uses it. Once LPC uses the same protocol it can start using it.
165  * I2C could use it now, with a refactor of the existing code.
166  *
167  * Return: 0 on success or negative error code.
168  */
169 int cros_ec_prepare_tx(struct cros_ec_device *ec_dev,
170                        struct cros_ec_command *msg)
171 {
172         u8 *out;
173         u8 csum;
174         int i;
175
176         if (ec_dev->proto_version > 2)
177                 return prepare_packet(ec_dev, msg);
178
179         BUG_ON(msg->outsize > EC_PROTO2_MAX_PARAM_SIZE);
180         out = ec_dev->dout;
181         out[0] = EC_CMD_VERSION0 + msg->version;
182         out[1] = msg->command;
183         out[2] = msg->outsize;
184         csum = out[0] + out[1] + out[2];
185         for (i = 0; i < msg->outsize; i++)
186                 csum += out[EC_MSG_TX_HEADER_BYTES + i] = msg->data[i];
187         out[EC_MSG_TX_HEADER_BYTES + msg->outsize] = csum;
188
189         return EC_MSG_TX_PROTO_BYTES + msg->outsize;
190 }
191 EXPORT_SYMBOL(cros_ec_prepare_tx);
192
193 /**
194  * cros_ec_check_result() - Check ec_msg->result.
195  * @ec_dev: EC device.
196  * @msg: Message to check.
197  *
198  * This is used by ChromeOS EC drivers to check the ec_msg->result for
199  * errors and to warn about them.
200  *
201  * Return: 0 on success or negative error code.
202  */
203 int cros_ec_check_result(struct cros_ec_device *ec_dev,
204                          struct cros_ec_command *msg)
205 {
206         switch (msg->result) {
207         case EC_RES_SUCCESS:
208                 return 0;
209         case EC_RES_IN_PROGRESS:
210                 dev_dbg(ec_dev->dev, "command 0x%02x in progress\n",
211                         msg->command);
212                 return -EAGAIN;
213         default:
214                 dev_dbg(ec_dev->dev, "command 0x%02x returned %d\n",
215                         msg->command, msg->result);
216                 return 0;
217         }
218 }
219 EXPORT_SYMBOL(cros_ec_check_result);
220
221 /*
222  * cros_ec_get_host_event_wake_mask
223  *
224  * Get the mask of host events that cause wake from suspend.
225  *
226  * @ec_dev: EC device to call
227  * @msg: message structure to use
228  * @mask: result when function returns >=0.
229  *
230  * LOCKING:
231  * the caller has ec_dev->lock mutex, or the caller knows there is
232  * no other command in progress.
233  */
234 static int cros_ec_get_host_event_wake_mask(struct cros_ec_device *ec_dev,
235                                             struct cros_ec_command *msg,
236                                             uint32_t *mask)
237 {
238         struct ec_response_host_event_mask *r;
239         int ret;
240
241         msg->command = EC_CMD_HOST_EVENT_GET_WAKE_MASK;
242         msg->version = 0;
243         msg->outsize = 0;
244         msg->insize = sizeof(*r);
245
246         ret = send_command(ec_dev, msg);
247         if (ret >= 0) {
248                 if (msg->result == EC_RES_INVALID_COMMAND)
249                         return -EOPNOTSUPP;
250                 if (msg->result != EC_RES_SUCCESS)
251                         return -EPROTO;
252         }
253         if (ret > 0) {
254                 r = (struct ec_response_host_event_mask *)msg->data;
255                 *mask = r->mask;
256         }
257
258         return ret;
259 }
260
261 static int cros_ec_host_command_proto_query(struct cros_ec_device *ec_dev,
262                                             int devidx,
263                                             struct cros_ec_command *msg)
264 {
265         /*
266          * Try using v3+ to query for supported protocols. If this
267          * command fails, fall back to v2. Returns the highest protocol
268          * supported by the EC.
269          * Also sets the max request/response/passthru size.
270          */
271         int ret;
272
273         if (!ec_dev->pkt_xfer)
274                 return -EPROTONOSUPPORT;
275
276         memset(msg, 0, sizeof(*msg));
277         msg->command = EC_CMD_PASSTHRU_OFFSET(devidx) | EC_CMD_GET_PROTOCOL_INFO;
278         msg->insize = sizeof(struct ec_response_get_protocol_info);
279
280         ret = send_command(ec_dev, msg);
281         /*
282          * Send command once again when timeout occurred.
283          * Fingerprint MCU (FPMCU) is restarted during system boot which
284          * introduces small window in which FPMCU won't respond for any
285          * messages sent by kernel. There is no need to wait before next
286          * attempt because we waited at least EC_MSG_DEADLINE_MS.
287          */
288         if (ret == -ETIMEDOUT)
289                 ret = send_command(ec_dev, msg);
290
291         if (ret < 0) {
292                 dev_dbg(ec_dev->dev,
293                         "failed to check for EC[%d] protocol version: %d\n",
294                         devidx, ret);
295                 return ret;
296         }
297
298         if (devidx > 0 && msg->result == EC_RES_INVALID_COMMAND)
299                 return -ENODEV;
300         else if (msg->result != EC_RES_SUCCESS)
301                 return msg->result;
302
303         return 0;
304 }
305
306 static int cros_ec_host_command_proto_query_v2(struct cros_ec_device *ec_dev)
307 {
308         struct cros_ec_command *msg;
309         struct ec_params_hello *hello_params;
310         struct ec_response_hello *hello_response;
311         int ret;
312         int len = max(sizeof(*hello_params), sizeof(*hello_response));
313
314         msg = kmalloc(sizeof(*msg) + len, GFP_KERNEL);
315         if (!msg)
316                 return -ENOMEM;
317
318         msg->version = 0;
319         msg->command = EC_CMD_HELLO;
320         hello_params = (struct ec_params_hello *)msg->data;
321         msg->outsize = sizeof(*hello_params);
322         hello_response = (struct ec_response_hello *)msg->data;
323         msg->insize = sizeof(*hello_response);
324
325         hello_params->in_data = 0xa0b0c0d0;
326
327         ret = send_command(ec_dev, msg);
328
329         if (ret < 0) {
330                 dev_dbg(ec_dev->dev,
331                         "EC failed to respond to v2 hello: %d\n",
332                         ret);
333                 goto exit;
334         } else if (msg->result != EC_RES_SUCCESS) {
335                 dev_err(ec_dev->dev,
336                         "EC responded to v2 hello with error: %d\n",
337                         msg->result);
338                 ret = msg->result;
339                 goto exit;
340         } else if (hello_response->out_data != 0xa1b2c3d4) {
341                 dev_err(ec_dev->dev,
342                         "EC responded to v2 hello with bad result: %u\n",
343                         hello_response->out_data);
344                 ret = -EBADMSG;
345                 goto exit;
346         }
347
348         ret = 0;
349
350  exit:
351         kfree(msg);
352         return ret;
353 }
354
355 /*
356  * cros_ec_get_host_command_version_mask
357  *
358  * Get the version mask of a given command.
359  *
360  * @ec_dev: EC device to call
361  * @msg: message structure to use
362  * @cmd: command to get the version of.
363  * @mask: result when function returns 0.
364  *
365  * @return 0 on success, error code otherwise
366  *
367  * LOCKING:
368  * the caller has ec_dev->lock mutex or the caller knows there is
369  * no other command in progress.
370  */
371 static int cros_ec_get_host_command_version_mask(struct cros_ec_device *ec_dev,
372         u16 cmd, u32 *mask)
373 {
374         struct ec_params_get_cmd_versions *pver;
375         struct ec_response_get_cmd_versions *rver;
376         struct cros_ec_command *msg;
377         int ret;
378
379         msg = kmalloc(sizeof(*msg) + max(sizeof(*rver), sizeof(*pver)),
380                       GFP_KERNEL);
381         if (!msg)
382                 return -ENOMEM;
383
384         msg->version = 0;
385         msg->command = EC_CMD_GET_CMD_VERSIONS;
386         msg->insize = sizeof(*rver);
387         msg->outsize = sizeof(*pver);
388
389         pver = (struct ec_params_get_cmd_versions *)msg->data;
390         pver->cmd = cmd;
391
392         ret = send_command(ec_dev, msg);
393         if (ret > 0) {
394                 rver = (struct ec_response_get_cmd_versions *)msg->data;
395                 *mask = rver->version_mask;
396         }
397
398         kfree(msg);
399
400         return ret;
401 }
402
403 /**
404  * cros_ec_query_all() -  Query the protocol version supported by the
405  *         ChromeOS EC.
406  * @ec_dev: Device to register.
407  *
408  * Return: 0 on success or negative error code.
409  */
410 int cros_ec_query_all(struct cros_ec_device *ec_dev)
411 {
412         struct device *dev = ec_dev->dev;
413         struct cros_ec_command *proto_msg;
414         struct ec_response_get_protocol_info *proto_info;
415         u32 ver_mask = 0;
416         int ret;
417
418         proto_msg = kzalloc(sizeof(*proto_msg) + sizeof(*proto_info),
419                             GFP_KERNEL);
420         if (!proto_msg)
421                 return -ENOMEM;
422
423         /* First try sending with proto v3. */
424         ec_dev->proto_version = 3;
425         ret = cros_ec_host_command_proto_query(ec_dev, 0, proto_msg);
426
427         if (ret == 0) {
428                 proto_info = (struct ec_response_get_protocol_info *)
429                         proto_msg->data;
430                 ec_dev->max_request = proto_info->max_request_packet_size -
431                         sizeof(struct ec_host_request);
432                 ec_dev->max_response = proto_info->max_response_packet_size -
433                         sizeof(struct ec_host_response);
434                 ec_dev->proto_version =
435                         min(EC_HOST_REQUEST_VERSION,
436                                         fls(proto_info->protocol_versions) - 1);
437                 dev_dbg(ec_dev->dev,
438                         "using proto v%u\n",
439                         ec_dev->proto_version);
440
441                 ec_dev->din_size = ec_dev->max_response +
442                         sizeof(struct ec_host_response) +
443                         EC_MAX_RESPONSE_OVERHEAD;
444                 ec_dev->dout_size = ec_dev->max_request +
445                         sizeof(struct ec_host_request) +
446                         EC_MAX_REQUEST_OVERHEAD;
447
448                 /*
449                  * Check for PD
450                  */
451                 ret = cros_ec_host_command_proto_query(ec_dev, 1, proto_msg);
452
453                 if (ret) {
454                         dev_dbg(ec_dev->dev, "no PD chip found: %d\n", ret);
455                         ec_dev->max_passthru = 0;
456                 } else {
457                         dev_dbg(ec_dev->dev, "found PD chip\n");
458                         ec_dev->max_passthru =
459                                 proto_info->max_request_packet_size -
460                                 sizeof(struct ec_host_request);
461                 }
462         } else {
463                 /* Try querying with a v2 hello message. */
464                 ec_dev->proto_version = 2;
465                 ret = cros_ec_host_command_proto_query_v2(ec_dev);
466
467                 if (ret == 0) {
468                         /* V2 hello succeeded. */
469                         dev_dbg(ec_dev->dev, "falling back to proto v2\n");
470
471                         ec_dev->max_request = EC_PROTO2_MAX_PARAM_SIZE;
472                         ec_dev->max_response = EC_PROTO2_MAX_PARAM_SIZE;
473                         ec_dev->max_passthru = 0;
474                         ec_dev->pkt_xfer = NULL;
475                         ec_dev->din_size = EC_PROTO2_MSG_BYTES;
476                         ec_dev->dout_size = EC_PROTO2_MSG_BYTES;
477                 } else {
478                         /*
479                          * It's possible for a test to occur too early when
480                          * the EC isn't listening. If this happens, we'll
481                          * test later when the first command is run.
482                          */
483                         ec_dev->proto_version = EC_PROTO_VERSION_UNKNOWN;
484                         dev_dbg(ec_dev->dev, "EC query failed: %d\n", ret);
485                         goto exit;
486                 }
487         }
488
489         devm_kfree(dev, ec_dev->din);
490         devm_kfree(dev, ec_dev->dout);
491
492         ec_dev->din = devm_kzalloc(dev, ec_dev->din_size, GFP_KERNEL);
493         if (!ec_dev->din) {
494                 ret = -ENOMEM;
495                 goto exit;
496         }
497
498         ec_dev->dout = devm_kzalloc(dev, ec_dev->dout_size, GFP_KERNEL);
499         if (!ec_dev->dout) {
500                 devm_kfree(dev, ec_dev->din);
501                 ret = -ENOMEM;
502                 goto exit;
503         }
504
505         /* Probe if MKBP event is supported */
506         ret = cros_ec_get_host_command_version_mask(ec_dev,
507                                                     EC_CMD_GET_NEXT_EVENT,
508                                                     &ver_mask);
509         if (ret < 0 || ver_mask == 0)
510                 ec_dev->mkbp_event_supported = 0;
511         else
512                 ec_dev->mkbp_event_supported = fls(ver_mask);
513
514         dev_dbg(ec_dev->dev, "MKBP support version %u\n",
515                 ec_dev->mkbp_event_supported - 1);
516
517         /* Probe if host sleep v1 is supported for S0ix failure detection. */
518         ret = cros_ec_get_host_command_version_mask(ec_dev,
519                                                     EC_CMD_HOST_SLEEP_EVENT,
520                                                     &ver_mask);
521         ec_dev->host_sleep_v1 = (ret >= 0 && (ver_mask & EC_VER_MASK(1)));
522
523         /* Get host event wake mask. */
524         ret = cros_ec_get_host_event_wake_mask(ec_dev, proto_msg,
525                                                &ec_dev->host_event_wake_mask);
526         if (ret < 0) {
527                 /*
528                  * If the EC doesn't support EC_CMD_HOST_EVENT_GET_WAKE_MASK,
529                  * use a reasonable default. Note that we ignore various
530                  * battery, AC status, and power-state events, because (a)
531                  * those can be quite common (e.g., when sitting at full
532                  * charge, on AC) and (b) these are not actionable wake events;
533                  * if anything, we'd like to continue suspending (to save
534                  * power), not wake up.
535                  */
536                 ec_dev->host_event_wake_mask = U32_MAX &
537                         ~(EC_HOST_EVENT_MASK(EC_HOST_EVENT_LID_CLOSED) |
538                           EC_HOST_EVENT_MASK(EC_HOST_EVENT_AC_DISCONNECTED) |
539                           EC_HOST_EVENT_MASK(EC_HOST_EVENT_BATTERY_LOW) |
540                           EC_HOST_EVENT_MASK(EC_HOST_EVENT_BATTERY_CRITICAL) |
541                           EC_HOST_EVENT_MASK(EC_HOST_EVENT_BATTERY) |
542                           EC_HOST_EVENT_MASK(EC_HOST_EVENT_PD_MCU) |
543                           EC_HOST_EVENT_MASK(EC_HOST_EVENT_BATTERY_STATUS));
544                 /*
545                  * Old ECs may not support this command. Complain about all
546                  * other errors.
547                  */
548                 if (ret != -EOPNOTSUPP)
549                         dev_err(ec_dev->dev,
550                                 "failed to retrieve wake mask: %d\n", ret);
551         }
552
553         ret = 0;
554
555 exit:
556         kfree(proto_msg);
557         return ret;
558 }
559 EXPORT_SYMBOL(cros_ec_query_all);
560
561 /**
562  * cros_ec_cmd_xfer() - Send a command to the ChromeOS EC.
563  * @ec_dev: EC device.
564  * @msg: Message to write.
565  *
566  * Call this to send a command to the ChromeOS EC. This should be used instead
567  * of calling the EC's cmd_xfer() callback directly. This function does not
568  * convert EC command execution error codes to Linux error codes. Most
569  * in-kernel users will want to use cros_ec_cmd_xfer_status() instead since
570  * that function implements the conversion.
571  *
572  * Return:
573  * >0 - EC command was executed successfully. The return value is the number
574  *      of bytes returned by the EC (excluding the header).
575  * =0 - EC communication was successful. EC command execution results are
576  *      reported in msg->result. The result will be EC_RES_SUCCESS if the
577  *      command was executed successfully or report an EC command execution
578  *      error.
579  * <0 - EC communication error. Return value is the Linux error code.
580  */
581 int cros_ec_cmd_xfer(struct cros_ec_device *ec_dev, struct cros_ec_command *msg)
582 {
583         int ret;
584
585         mutex_lock(&ec_dev->lock);
586         if (ec_dev->proto_version == EC_PROTO_VERSION_UNKNOWN) {
587                 ret = cros_ec_query_all(ec_dev);
588                 if (ret) {
589                         dev_err(ec_dev->dev,
590                                 "EC version unknown and query failed; aborting command\n");
591                         mutex_unlock(&ec_dev->lock);
592                         return ret;
593                 }
594         }
595
596         if (msg->insize > ec_dev->max_response) {
597                 dev_dbg(ec_dev->dev, "clamping message receive buffer\n");
598                 msg->insize = ec_dev->max_response;
599         }
600
601         if (msg->command < EC_CMD_PASSTHRU_OFFSET(1)) {
602                 if (msg->outsize > ec_dev->max_request) {
603                         dev_err(ec_dev->dev,
604                                 "request of size %u is too big (max: %u)\n",
605                                 msg->outsize,
606                                 ec_dev->max_request);
607                         mutex_unlock(&ec_dev->lock);
608                         return -EMSGSIZE;
609                 }
610         } else {
611                 if (msg->outsize > ec_dev->max_passthru) {
612                         dev_err(ec_dev->dev,
613                                 "passthru rq of size %u is too big (max: %u)\n",
614                                 msg->outsize,
615                                 ec_dev->max_passthru);
616                         mutex_unlock(&ec_dev->lock);
617                         return -EMSGSIZE;
618                 }
619         }
620
621         ret = send_command(ec_dev, msg);
622         mutex_unlock(&ec_dev->lock);
623
624         return ret;
625 }
626 EXPORT_SYMBOL(cros_ec_cmd_xfer);
627
628 /**
629  * cros_ec_cmd_xfer_status() - Send a command to the ChromeOS EC.
630  * @ec_dev: EC device.
631  * @msg: Message to write.
632  *
633  * Call this to send a command to the ChromeOS EC. This should be used instead of calling the EC's
634  * cmd_xfer() callback directly. It returns success status only if both the command was transmitted
635  * successfully and the EC replied with success status.
636  *
637  * Return:
638  * >=0 - The number of bytes transferred.
639  * <0 - Linux error code
640  */
641 int cros_ec_cmd_xfer_status(struct cros_ec_device *ec_dev,
642                             struct cros_ec_command *msg)
643 {
644         int ret, mapped;
645
646         ret = cros_ec_cmd_xfer(ec_dev, msg);
647         if (ret < 0)
648                 return ret;
649
650         mapped = cros_ec_map_error(msg->result);
651         if (mapped) {
652                 dev_dbg(ec_dev->dev, "Command result (err: %d [%d])\n",
653                         msg->result, mapped);
654                 ret = mapped;
655         }
656
657         return ret;
658 }
659 EXPORT_SYMBOL(cros_ec_cmd_xfer_status);
660
661 static int get_next_event_xfer(struct cros_ec_device *ec_dev,
662                                struct cros_ec_command *msg,
663                                struct ec_response_get_next_event_v1 *event,
664                                int version, uint32_t size)
665 {
666         int ret;
667
668         msg->version = version;
669         msg->command = EC_CMD_GET_NEXT_EVENT;
670         msg->insize = size;
671         msg->outsize = 0;
672
673         ret = cros_ec_cmd_xfer_status(ec_dev, msg);
674         if (ret > 0) {
675                 ec_dev->event_size = ret - 1;
676                 ec_dev->event_data = *event;
677         }
678
679         return ret;
680 }
681
682 static int get_next_event(struct cros_ec_device *ec_dev)
683 {
684         struct {
685                 struct cros_ec_command msg;
686                 struct ec_response_get_next_event_v1 event;
687         } __packed buf;
688         struct cros_ec_command *msg = &buf.msg;
689         struct ec_response_get_next_event_v1 *event = &buf.event;
690         const int cmd_version = ec_dev->mkbp_event_supported - 1;
691
692         memset(msg, 0, sizeof(*msg));
693         if (ec_dev->suspended) {
694                 dev_dbg(ec_dev->dev, "Device suspended.\n");
695                 return -EHOSTDOWN;
696         }
697
698         if (cmd_version == 0)
699                 return get_next_event_xfer(ec_dev, msg, event, 0,
700                                   sizeof(struct ec_response_get_next_event));
701
702         return get_next_event_xfer(ec_dev, msg, event, cmd_version,
703                                 sizeof(struct ec_response_get_next_event_v1));
704 }
705
706 static int get_keyboard_state_event(struct cros_ec_device *ec_dev)
707 {
708         u8 buffer[sizeof(struct cros_ec_command) +
709                   sizeof(ec_dev->event_data.data)];
710         struct cros_ec_command *msg = (struct cros_ec_command *)&buffer;
711
712         msg->version = 0;
713         msg->command = EC_CMD_MKBP_STATE;
714         msg->insize = sizeof(ec_dev->event_data.data);
715         msg->outsize = 0;
716
717         ec_dev->event_size = cros_ec_cmd_xfer_status(ec_dev, msg);
718         ec_dev->event_data.event_type = EC_MKBP_EVENT_KEY_MATRIX;
719         memcpy(&ec_dev->event_data.data, msg->data,
720                sizeof(ec_dev->event_data.data));
721
722         return ec_dev->event_size;
723 }
724
725 /**
726  * cros_ec_get_next_event() - Fetch next event from the ChromeOS EC.
727  * @ec_dev: Device to fetch event from.
728  * @wake_event: Pointer to a bool set to true upon return if the event might be
729  *              treated as a wake event. Ignored if null.
730  * @has_more_events: Pointer to bool set to true if more than one event is
731  *              pending.
732  *              Some EC will set this flag to indicate cros_ec_get_next_event()
733  *              can be called multiple times in a row.
734  *              It is an optimization to prevent issuing a EC command for
735  *              nothing or wait for another interrupt from the EC to process
736  *              the next message.
737  *              Ignored if null.
738  *
739  * Return: negative error code on errors; 0 for no data; or else number of
740  * bytes received (i.e., an event was retrieved successfully). Event types are
741  * written out to @ec_dev->event_data.event_type on success.
742  */
743 int cros_ec_get_next_event(struct cros_ec_device *ec_dev,
744                            bool *wake_event,
745                            bool *has_more_events)
746 {
747         u8 event_type;
748         u32 host_event;
749         int ret;
750
751         /*
752          * Default value for wake_event.
753          * Wake up on keyboard event, wake up for spurious interrupt or link
754          * error to the EC.
755          */
756         if (wake_event)
757                 *wake_event = true;
758
759         /*
760          * Default value for has_more_events.
761          * EC will raise another interrupt if AP does not process all events
762          * anyway.
763          */
764         if (has_more_events)
765                 *has_more_events = false;
766
767         if (!ec_dev->mkbp_event_supported)
768                 return get_keyboard_state_event(ec_dev);
769
770         ret = get_next_event(ec_dev);
771         if (ret <= 0)
772                 return ret;
773
774         if (has_more_events)
775                 *has_more_events = ec_dev->event_data.event_type &
776                         EC_MKBP_HAS_MORE_EVENTS;
777         ec_dev->event_data.event_type &= EC_MKBP_EVENT_TYPE_MASK;
778
779         if (wake_event) {
780                 event_type = ec_dev->event_data.event_type;
781                 host_event = cros_ec_get_host_event(ec_dev);
782
783                 /*
784                  * Sensor events need to be parsed by the sensor sub-device.
785                  * Defer them, and don't report the wakeup here.
786                  */
787                 if (event_type == EC_MKBP_EVENT_SENSOR_FIFO) {
788                         *wake_event = false;
789                 } else if (host_event) {
790                         /* rtc_update_irq() already handles wakeup events. */
791                         if (host_event & EC_HOST_EVENT_MASK(EC_HOST_EVENT_RTC))
792                                 *wake_event = false;
793                         /* Masked host-events should not count as wake events. */
794                         if (!(host_event & ec_dev->host_event_wake_mask))
795                                 *wake_event = false;
796                 }
797         }
798
799         return ret;
800 }
801 EXPORT_SYMBOL(cros_ec_get_next_event);
802
803 /**
804  * cros_ec_get_host_event() - Return a mask of event set by the ChromeOS EC.
805  * @ec_dev: Device to fetch event from.
806  *
807  * When MKBP is supported, when the EC raises an interrupt, we collect the
808  * events raised and call the functions in the ec notifier. This function
809  * is a helper to know which events are raised.
810  *
811  * Return: 0 on error or non-zero bitmask of one or more EC_HOST_EVENT_*.
812  */
813 u32 cros_ec_get_host_event(struct cros_ec_device *ec_dev)
814 {
815         u32 host_event;
816
817         BUG_ON(!ec_dev->mkbp_event_supported);
818
819         if (ec_dev->event_data.event_type != EC_MKBP_EVENT_HOST_EVENT)
820                 return 0;
821
822         if (ec_dev->event_size != sizeof(host_event)) {
823                 dev_warn(ec_dev->dev, "Invalid host event size\n");
824                 return 0;
825         }
826
827         host_event = get_unaligned_le32(&ec_dev->event_data.data.host_event);
828
829         return host_event;
830 }
831 EXPORT_SYMBOL(cros_ec_get_host_event);
832
833 /**
834  * cros_ec_check_features() - Test for the presence of EC features
835  *
836  * @ec: EC device, does not have to be connected directly to the AP,
837  *      can be daisy chained through another device.
838  * @feature: One of ec_feature_code bit.
839  *
840  * Call this function to test whether the ChromeOS EC supports a feature.
841  *
842  * Return: true if supported, false if not (or if an error was encountered).
843  */
844 bool cros_ec_check_features(struct cros_ec_dev *ec, int feature)
845 {
846         struct ec_response_get_features *features = &ec->features;
847         int ret;
848
849         if (features->flags[0] == -1U && features->flags[1] == -1U) {
850                 /* features bitmap not read yet */
851                 ret = cros_ec_command(ec->ec_dev, 0, EC_CMD_GET_FEATURES + ec->cmd_offset,
852                                       NULL, 0, features, sizeof(*features));
853                 if (ret < 0) {
854                         dev_warn(ec->dev, "cannot get EC features: %d\n", ret);
855                         memset(features, 0, sizeof(*features));
856                 }
857
858                 dev_dbg(ec->dev, "EC features %08x %08x\n",
859                         features->flags[0], features->flags[1]);
860         }
861
862         return !!(features->flags[feature / 32] & EC_FEATURE_MASK_0(feature));
863 }
864 EXPORT_SYMBOL_GPL(cros_ec_check_features);
865
866 /**
867  * cros_ec_get_sensor_count() - Return the number of MEMS sensors supported.
868  *
869  * @ec: EC device, does not have to be connected directly to the AP,
870  *      can be daisy chained through another device.
871  * Return: < 0 in case of error.
872  */
873 int cros_ec_get_sensor_count(struct cros_ec_dev *ec)
874 {
875         /*
876          * Issue a command to get the number of sensor reported.
877          * If not supported, check for legacy mode.
878          */
879         int ret, sensor_count;
880         struct ec_params_motion_sense *params;
881         struct ec_response_motion_sense *resp;
882         struct cros_ec_command *msg;
883         struct cros_ec_device *ec_dev = ec->ec_dev;
884         u8 status;
885
886         msg = kzalloc(sizeof(*msg) + max(sizeof(*params), sizeof(*resp)),
887                       GFP_KERNEL);
888         if (!msg)
889                 return -ENOMEM;
890
891         msg->version = 1;
892         msg->command = EC_CMD_MOTION_SENSE_CMD + ec->cmd_offset;
893         msg->outsize = sizeof(*params);
894         msg->insize = sizeof(*resp);
895
896         params = (struct ec_params_motion_sense *)msg->data;
897         params->cmd = MOTIONSENSE_CMD_DUMP;
898
899         ret = cros_ec_cmd_xfer_status(ec->ec_dev, msg);
900         if (ret < 0) {
901                 sensor_count = ret;
902         } else {
903                 resp = (struct ec_response_motion_sense *)msg->data;
904                 sensor_count = resp->dump.sensor_count;
905         }
906         kfree(msg);
907
908         /*
909          * Check legacy mode: Let's find out if sensors are accessible
910          * via LPC interface.
911          */
912         if (sensor_count < 0 && ec->cmd_offset == 0 && ec_dev->cmd_readmem) {
913                 ret = ec_dev->cmd_readmem(ec_dev, EC_MEMMAP_ACC_STATUS,
914                                 1, &status);
915                 if (ret >= 0 &&
916                     (status & EC_MEMMAP_ACC_STATUS_PRESENCE_BIT)) {
917                         /*
918                          * We have 2 sensors, one in the lid, one in the base.
919                          */
920                         sensor_count = 2;
921                 } else {
922                         /*
923                          * EC uses LPC interface and no sensors are presented.
924                          */
925                         sensor_count = 0;
926                 }
927         }
928         return sensor_count;
929 }
930 EXPORT_SYMBOL_GPL(cros_ec_get_sensor_count);
931
932 /**
933  * cros_ec_command - Send a command to the EC.
934  *
935  * @ec_dev: EC device
936  * @version: EC command version
937  * @command: EC command
938  * @outdata: EC command output data
939  * @outsize: Size of outdata
940  * @indata: EC command input data
941  * @insize: Size of indata
942  *
943  * Return: >= 0 on success, negative error number on failure.
944  */
945 int cros_ec_command(struct cros_ec_device *ec_dev,
946                     unsigned int version,
947                     int command,
948                     void *outdata,
949                     int outsize,
950                     void *indata,
951                     int insize)
952 {
953         struct cros_ec_command *msg;
954         int ret;
955
956         msg = kzalloc(sizeof(*msg) + max(insize, outsize), GFP_KERNEL);
957         if (!msg)
958                 return -ENOMEM;
959
960         msg->version = version;
961         msg->command = command;
962         msg->outsize = outsize;
963         msg->insize = insize;
964
965         if (outsize)
966                 memcpy(msg->data, outdata, outsize);
967
968         ret = cros_ec_cmd_xfer_status(ec_dev, msg);
969         if (ret < 0)
970                 goto error;
971
972         if (insize)
973                 memcpy(indata, msg->data, insize);
974 error:
975         kfree(msg);
976         return ret;
977 }
978 EXPORT_SYMBOL_GPL(cros_ec_command);