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