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