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