1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * cros_ec_sensors_core - Common function for Chrome OS EC sensor driver.
4  *
5  * Copyright (C) 2016 Google, Inc
6  */
7 
8 #include <linux/delay.h>
9 #include <linux/device.h>
10 #include <linux/iio/buffer.h>
11 #include <linux/iio/common/cros_ec_sensors_core.h>
12 #include <linux/iio/iio.h>
13 #include <linux/iio/kfifo_buf.h>
14 #include <linux/iio/trigger_consumer.h>
15 #include <linux/kernel.h>
16 #include <linux/mfd/cros_ec.h>
17 #include <linux/module.h>
18 #include <linux/slab.h>
19 #include <linux/platform_data/cros_ec_commands.h>
20 #include <linux/platform_data/cros_ec_proto.h>
21 #include <linux/platform_data/cros_ec_sensorhub.h>
22 #include <linux/platform_device.h>
23 
24 static char *cros_ec_loc[] = {
25 	[MOTIONSENSE_LOC_BASE] = "base",
26 	[MOTIONSENSE_LOC_LID] = "lid",
27 	[MOTIONSENSE_LOC_MAX] = "unknown",
28 };
29 
30 static int cros_ec_get_host_cmd_version_mask(struct cros_ec_device *ec_dev,
31 					     u16 cmd_offset, u16 cmd, u32 *mask)
32 {
33 	int ret;
34 	struct {
35 		struct cros_ec_command msg;
36 		union {
37 			struct ec_params_get_cmd_versions params;
38 			struct ec_response_get_cmd_versions resp;
39 		};
40 	} __packed buf = {
41 		.msg = {
42 			.command = EC_CMD_GET_CMD_VERSIONS + cmd_offset,
43 			.insize = sizeof(struct ec_response_get_cmd_versions),
44 			.outsize = sizeof(struct ec_params_get_cmd_versions)
45 			},
46 		.params = {.cmd = cmd}
47 	};
48 
49 	ret = cros_ec_cmd_xfer_status(ec_dev, &buf.msg);
50 	if (ret >= 0)
51 		*mask = buf.resp.version_mask;
52 	return ret;
53 }
54 
55 static void get_default_min_max_freq(enum motionsensor_type type,
56 				     u32 *min_freq,
57 				     u32 *max_freq)
58 {
59 	switch (type) {
60 	case MOTIONSENSE_TYPE_ACCEL:
61 	case MOTIONSENSE_TYPE_GYRO:
62 		*min_freq = 12500;
63 		*max_freq = 100000;
64 		break;
65 	case MOTIONSENSE_TYPE_MAG:
66 		*min_freq = 5000;
67 		*max_freq = 25000;
68 		break;
69 	case MOTIONSENSE_TYPE_PROX:
70 	case MOTIONSENSE_TYPE_LIGHT:
71 		*min_freq = 100;
72 		*max_freq = 50000;
73 		break;
74 	case MOTIONSENSE_TYPE_BARO:
75 		*min_freq = 250;
76 		*max_freq = 20000;
77 		break;
78 	case MOTIONSENSE_TYPE_ACTIVITY:
79 	default:
80 		*min_freq = 0;
81 		*max_freq = 0;
82 		break;
83 	}
84 }
85 
86 int cros_ec_sensors_core_init(struct platform_device *pdev,
87 			      struct iio_dev *indio_dev,
88 			      bool physical_device)
89 {
90 	struct device *dev = &pdev->dev;
91 	struct cros_ec_sensors_core_state *state = iio_priv(indio_dev);
92 	struct cros_ec_sensorhub *sensor_hub = dev_get_drvdata(dev->parent);
93 	struct cros_ec_dev *ec = sensor_hub->ec;
94 	struct cros_ec_sensor_platform *sensor_platform = dev_get_platdata(dev);
95 	u32 ver_mask;
96 	int ret, i;
97 
98 	platform_set_drvdata(pdev, indio_dev);
99 
100 	state->ec = ec->ec_dev;
101 	state->msg = devm_kzalloc(&pdev->dev,
102 				max((u16)sizeof(struct ec_params_motion_sense),
103 				state->ec->max_response), GFP_KERNEL);
104 	if (!state->msg)
105 		return -ENOMEM;
106 
107 	state->resp = (struct ec_response_motion_sense *)state->msg->data;
108 
109 	mutex_init(&state->cmd_lock);
110 
111 	ret = cros_ec_get_host_cmd_version_mask(state->ec,
112 						ec->cmd_offset,
113 						EC_CMD_MOTION_SENSE_CMD,
114 						&ver_mask);
115 	if (ret < 0)
116 		return ret;
117 
118 	/* Set up the host command structure. */
119 	state->msg->version = fls(ver_mask) - 1;
120 	state->msg->command = EC_CMD_MOTION_SENSE_CMD + ec->cmd_offset;
121 	state->msg->outsize = sizeof(struct ec_params_motion_sense);
122 
123 	indio_dev->dev.parent = &pdev->dev;
124 	indio_dev->name = pdev->name;
125 
126 	if (physical_device) {
127 		indio_dev->modes = INDIO_DIRECT_MODE;
128 
129 		state->param.cmd = MOTIONSENSE_CMD_INFO;
130 		state->param.info.sensor_num = sensor_platform->sensor_num;
131 		ret = cros_ec_motion_send_host_cmd(state, 0);
132 		if (ret) {
133 			dev_warn(dev, "Can not access sensor info\n");
134 			return ret;
135 		}
136 		state->type = state->resp->info.type;
137 		state->loc = state->resp->info.location;
138 
139 		/* Set sign vector, only used for backward compatibility. */
140 		memset(state->sign, 1, CROS_EC_SENSOR_MAX_AXIS);
141 
142 		for (i = CROS_EC_SENSOR_X; i < CROS_EC_SENSOR_MAX_AXIS; i++)
143 			state->calib[i].scale = MOTION_SENSE_DEFAULT_SCALE;
144 
145 		/* 0 is a correct value used to stop the device */
146 		state->frequencies[0] = 0;
147 		if (state->msg->version < 3) {
148 			get_default_min_max_freq(state->resp->info.type,
149 						 &state->frequencies[1],
150 						 &state->frequencies[2]);
151 		} else {
152 			state->frequencies[1] =
153 			    state->resp->info_3.min_frequency;
154 			state->frequencies[2] =
155 			    state->resp->info_3.max_frequency;
156 		}
157 	}
158 
159 	return 0;
160 }
161 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_init);
162 
163 int cros_ec_motion_send_host_cmd(struct cros_ec_sensors_core_state *state,
164 				 u16 opt_length)
165 {
166 	int ret;
167 
168 	if (opt_length)
169 		state->msg->insize = min(opt_length, state->ec->max_response);
170 	else
171 		state->msg->insize = state->ec->max_response;
172 
173 	memcpy(state->msg->data, &state->param, sizeof(state->param));
174 
175 	ret = cros_ec_cmd_xfer_status(state->ec, state->msg);
176 	if (ret < 0)
177 		return ret;
178 
179 	if (ret &&
180 	    state->resp != (struct ec_response_motion_sense *)state->msg->data)
181 		memcpy(state->resp, state->msg->data, ret);
182 
183 	return 0;
184 }
185 EXPORT_SYMBOL_GPL(cros_ec_motion_send_host_cmd);
186 
187 static ssize_t cros_ec_sensors_calibrate(struct iio_dev *indio_dev,
188 		uintptr_t private, const struct iio_chan_spec *chan,
189 		const char *buf, size_t len)
190 {
191 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
192 	int ret, i;
193 	bool calibrate;
194 
195 	ret = strtobool(buf, &calibrate);
196 	if (ret < 0)
197 		return ret;
198 	if (!calibrate)
199 		return -EINVAL;
200 
201 	mutex_lock(&st->cmd_lock);
202 	st->param.cmd = MOTIONSENSE_CMD_PERFORM_CALIB;
203 	ret = cros_ec_motion_send_host_cmd(st, 0);
204 	if (ret != 0) {
205 		dev_warn(&indio_dev->dev, "Unable to calibrate sensor\n");
206 	} else {
207 		/* Save values */
208 		for (i = CROS_EC_SENSOR_X; i < CROS_EC_SENSOR_MAX_AXIS; i++)
209 			st->calib[i].offset = st->resp->perform_calib.offset[i];
210 	}
211 	mutex_unlock(&st->cmd_lock);
212 
213 	return ret ? ret : len;
214 }
215 
216 static ssize_t cros_ec_sensors_id(struct iio_dev *indio_dev,
217 				  uintptr_t private,
218 				  const struct iio_chan_spec *chan, char *buf)
219 {
220 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
221 
222 	return snprintf(buf, PAGE_SIZE, "%d\n", st->param.info.sensor_num);
223 }
224 
225 static ssize_t cros_ec_sensors_loc(struct iio_dev *indio_dev,
226 		uintptr_t private, const struct iio_chan_spec *chan,
227 		char *buf)
228 {
229 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
230 
231 	return snprintf(buf, PAGE_SIZE, "%s\n", cros_ec_loc[st->loc]);
232 }
233 
234 const struct iio_chan_spec_ext_info cros_ec_sensors_ext_info[] = {
235 	{
236 		.name = "calibrate",
237 		.shared = IIO_SHARED_BY_ALL,
238 		.write = cros_ec_sensors_calibrate
239 	},
240 	{
241 		.name = "id",
242 		.shared = IIO_SHARED_BY_ALL,
243 		.read = cros_ec_sensors_id
244 	},
245 	{
246 		.name = "location",
247 		.shared = IIO_SHARED_BY_ALL,
248 		.read = cros_ec_sensors_loc
249 	},
250 	{ },
251 };
252 EXPORT_SYMBOL_GPL(cros_ec_sensors_ext_info);
253 
254 /**
255  * cros_ec_sensors_idx_to_reg - convert index into offset in shared memory
256  * @st:		pointer to state information for device
257  * @idx:	sensor index (should be element of enum sensor_index)
258  *
259  * Return:	address to read at
260  */
261 static unsigned int cros_ec_sensors_idx_to_reg(
262 					struct cros_ec_sensors_core_state *st,
263 					unsigned int idx)
264 {
265 	/*
266 	 * When using LPC interface, only space for 2 Accel and one Gyro.
267 	 * First halfword of MOTIONSENSE_TYPE_ACCEL is used by angle.
268 	 */
269 	if (st->type == MOTIONSENSE_TYPE_ACCEL)
270 		return EC_MEMMAP_ACC_DATA + sizeof(u16) *
271 			(1 + idx + st->param.info.sensor_num *
272 			 CROS_EC_SENSOR_MAX_AXIS);
273 
274 	return EC_MEMMAP_GYRO_DATA + sizeof(u16) * idx;
275 }
276 
277 static int cros_ec_sensors_cmd_read_u8(struct cros_ec_device *ec,
278 				       unsigned int offset, u8 *dest)
279 {
280 	return ec->cmd_readmem(ec, offset, 1, dest);
281 }
282 
283 static int cros_ec_sensors_cmd_read_u16(struct cros_ec_device *ec,
284 					 unsigned int offset, u16 *dest)
285 {
286 	__le16 tmp;
287 	int ret = ec->cmd_readmem(ec, offset, 2, &tmp);
288 
289 	if (ret >= 0)
290 		*dest = le16_to_cpu(tmp);
291 
292 	return ret;
293 }
294 
295 /**
296  * cros_ec_sensors_read_until_not_busy() - read until is not busy
297  *
298  * @st:	pointer to state information for device
299  *
300  * Read from EC status byte until it reads not busy.
301  * Return: 8-bit status if ok, -errno on failure.
302  */
303 static int cros_ec_sensors_read_until_not_busy(
304 					struct cros_ec_sensors_core_state *st)
305 {
306 	struct cros_ec_device *ec = st->ec;
307 	u8 status;
308 	int ret, attempts = 0;
309 
310 	ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS, &status);
311 	if (ret < 0)
312 		return ret;
313 
314 	while (status & EC_MEMMAP_ACC_STATUS_BUSY_BIT) {
315 		/* Give up after enough attempts, return error. */
316 		if (attempts++ >= 50)
317 			return -EIO;
318 
319 		/* Small delay every so often. */
320 		if (attempts % 5 == 0)
321 			msleep(25);
322 
323 		ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS,
324 						  &status);
325 		if (ret < 0)
326 			return ret;
327 	}
328 
329 	return status;
330 }
331 
332 /**
333  * read_ec_sensors_data_unsafe() - read acceleration data from EC shared memory
334  * @indio_dev:	pointer to IIO device
335  * @scan_mask:	bitmap of the sensor indices to scan
336  * @data:	location to store data
337  *
338  * This is the unsafe function for reading the EC data. It does not guarantee
339  * that the EC will not modify the data as it is being read in.
340  *
341  * Return: 0 on success, -errno on failure.
342  */
343 static int cros_ec_sensors_read_data_unsafe(struct iio_dev *indio_dev,
344 			 unsigned long scan_mask, s16 *data)
345 {
346 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
347 	struct cros_ec_device *ec = st->ec;
348 	unsigned int i;
349 	int ret;
350 
351 	/* Read all sensors enabled in scan_mask. Each value is 2 bytes. */
352 	for_each_set_bit(i, &scan_mask, indio_dev->masklength) {
353 		ret = cros_ec_sensors_cmd_read_u16(ec,
354 					     cros_ec_sensors_idx_to_reg(st, i),
355 					     data);
356 		if (ret < 0)
357 			return ret;
358 
359 		*data *= st->sign[i];
360 		data++;
361 	}
362 
363 	return 0;
364 }
365 
366 /**
367  * cros_ec_sensors_read_lpc() - read acceleration data from EC shared memory.
368  * @indio_dev: pointer to IIO device.
369  * @scan_mask: bitmap of the sensor indices to scan.
370  * @data: location to store data.
371  *
372  * Note: this is the safe function for reading the EC data. It guarantees
373  * that the data sampled was not modified by the EC while being read.
374  *
375  * Return: 0 on success, -errno on failure.
376  */
377 int cros_ec_sensors_read_lpc(struct iio_dev *indio_dev,
378 			     unsigned long scan_mask, s16 *data)
379 {
380 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
381 	struct cros_ec_device *ec = st->ec;
382 	u8 samp_id = 0xff, status = 0;
383 	int ret, attempts = 0;
384 
385 	/*
386 	 * Continually read all data from EC until the status byte after
387 	 * all reads reflects that the EC is not busy and the sample id
388 	 * matches the sample id from before all reads. This guarantees
389 	 * that data read in was not modified by the EC while reading.
390 	 */
391 	while ((status & (EC_MEMMAP_ACC_STATUS_BUSY_BIT |
392 			  EC_MEMMAP_ACC_STATUS_SAMPLE_ID_MASK)) != samp_id) {
393 		/* If we have tried to read too many times, return error. */
394 		if (attempts++ >= 5)
395 			return -EIO;
396 
397 		/* Read status byte until EC is not busy. */
398 		ret = cros_ec_sensors_read_until_not_busy(st);
399 		if (ret < 0)
400 			return ret;
401 
402 		/*
403 		 * Store the current sample id so that we can compare to the
404 		 * sample id after reading the data.
405 		 */
406 		samp_id = ret & EC_MEMMAP_ACC_STATUS_SAMPLE_ID_MASK;
407 
408 		/* Read all EC data, format it, and store it into data. */
409 		ret = cros_ec_sensors_read_data_unsafe(indio_dev, scan_mask,
410 						       data);
411 		if (ret < 0)
412 			return ret;
413 
414 		/* Read status byte. */
415 		ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS,
416 						  &status);
417 		if (ret < 0)
418 			return ret;
419 	}
420 
421 	return 0;
422 }
423 EXPORT_SYMBOL_GPL(cros_ec_sensors_read_lpc);
424 
425 int cros_ec_sensors_read_cmd(struct iio_dev *indio_dev,
426 			     unsigned long scan_mask, s16 *data)
427 {
428 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
429 	int ret;
430 	unsigned int i;
431 
432 	/* Read all sensor data through a command. */
433 	st->param.cmd = MOTIONSENSE_CMD_DATA;
434 	ret = cros_ec_motion_send_host_cmd(st, sizeof(st->resp->data));
435 	if (ret != 0) {
436 		dev_warn(&indio_dev->dev, "Unable to read sensor data\n");
437 		return ret;
438 	}
439 
440 	for_each_set_bit(i, &scan_mask, indio_dev->masklength) {
441 		*data = st->resp->data.data[i];
442 		data++;
443 	}
444 
445 	return 0;
446 }
447 EXPORT_SYMBOL_GPL(cros_ec_sensors_read_cmd);
448 
449 irqreturn_t cros_ec_sensors_capture(int irq, void *p)
450 {
451 	struct iio_poll_func *pf = p;
452 	struct iio_dev *indio_dev = pf->indio_dev;
453 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
454 	int ret;
455 
456 	mutex_lock(&st->cmd_lock);
457 
458 	/* Clear capture data. */
459 	memset(st->samples, 0, indio_dev->scan_bytes);
460 
461 	/* Read data based on which channels are enabled in scan mask. */
462 	ret = st->read_ec_sensors_data(indio_dev,
463 				       *(indio_dev->active_scan_mask),
464 				       (s16 *)st->samples);
465 	if (ret < 0)
466 		goto done;
467 
468 	iio_push_to_buffers_with_timestamp(indio_dev, st->samples,
469 					   iio_get_time_ns(indio_dev));
470 
471 done:
472 	/*
473 	 * Tell the core we are done with this trigger and ready for the
474 	 * next one.
475 	 */
476 	iio_trigger_notify_done(indio_dev->trig);
477 
478 	mutex_unlock(&st->cmd_lock);
479 
480 	return IRQ_HANDLED;
481 }
482 EXPORT_SYMBOL_GPL(cros_ec_sensors_capture);
483 
484 int cros_ec_sensors_core_read(struct cros_ec_sensors_core_state *st,
485 			  struct iio_chan_spec const *chan,
486 			  int *val, int *val2, long mask)
487 {
488 	int ret;
489 
490 	switch (mask) {
491 	case IIO_CHAN_INFO_SAMP_FREQ:
492 		st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
493 		st->param.ec_rate.data =
494 			EC_MOTION_SENSE_NO_VALUE;
495 
496 		ret = cros_ec_motion_send_host_cmd(st, 0);
497 		if (ret)
498 			break;
499 
500 		*val = st->resp->ec_rate.ret;
501 		ret = IIO_VAL_INT;
502 		break;
503 	case IIO_CHAN_INFO_FREQUENCY:
504 		st->param.cmd = MOTIONSENSE_CMD_SENSOR_ODR;
505 		st->param.sensor_odr.data =
506 			EC_MOTION_SENSE_NO_VALUE;
507 
508 		ret = cros_ec_motion_send_host_cmd(st, 0);
509 		if (ret)
510 			break;
511 
512 		*val = st->resp->sensor_odr.ret;
513 		ret = IIO_VAL_INT;
514 		break;
515 	default:
516 		ret = -EINVAL;
517 		break;
518 	}
519 
520 	return ret;
521 }
522 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_read);
523 
524 int cros_ec_sensors_core_read_avail(struct iio_dev *indio_dev,
525 				    struct iio_chan_spec const *chan,
526 				    const int **vals,
527 				    int *type,
528 				    int *length,
529 				    long mask)
530 {
531 	struct cros_ec_sensors_core_state *state = iio_priv(indio_dev);
532 
533 	switch (mask) {
534 	case IIO_CHAN_INFO_SAMP_FREQ:
535 		*length = ARRAY_SIZE(state->frequencies);
536 		*vals = (const int *)&state->frequencies;
537 		*type = IIO_VAL_INT;
538 		return IIO_AVAIL_LIST;
539 	}
540 
541 	return -EINVAL;
542 }
543 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_read_avail);
544 
545 int cros_ec_sensors_core_write(struct cros_ec_sensors_core_state *st,
546 			       struct iio_chan_spec const *chan,
547 			       int val, int val2, long mask)
548 {
549 	int ret;
550 
551 	switch (mask) {
552 	case IIO_CHAN_INFO_FREQUENCY:
553 		st->param.cmd = MOTIONSENSE_CMD_SENSOR_ODR;
554 		st->param.sensor_odr.data = val;
555 
556 		/* Always roundup, so caller gets at least what it asks for. */
557 		st->param.sensor_odr.roundup = 1;
558 
559 		ret = cros_ec_motion_send_host_cmd(st, 0);
560 		break;
561 	case IIO_CHAN_INFO_SAMP_FREQ:
562 		st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
563 		st->param.ec_rate.data = val;
564 
565 		ret = cros_ec_motion_send_host_cmd(st, 0);
566 		if (ret)
567 			break;
568 		st->curr_sampl_freq = val;
569 		break;
570 	default:
571 		ret = -EINVAL;
572 		break;
573 	}
574 	return ret;
575 }
576 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_write);
577 
578 static int __maybe_unused cros_ec_sensors_prepare(struct device *dev)
579 {
580 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
581 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
582 
583 	if (st->curr_sampl_freq == 0)
584 		return 0;
585 
586 	/*
587 	 * If the sensors are sampled at high frequency, we will not be able to
588 	 * sleep. Set sampling to a long period if necessary.
589 	 */
590 	if (st->curr_sampl_freq < CROS_EC_MIN_SUSPEND_SAMPLING_FREQUENCY) {
591 		mutex_lock(&st->cmd_lock);
592 		st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
593 		st->param.ec_rate.data = CROS_EC_MIN_SUSPEND_SAMPLING_FREQUENCY;
594 		cros_ec_motion_send_host_cmd(st, 0);
595 		mutex_unlock(&st->cmd_lock);
596 	}
597 	return 0;
598 }
599 
600 static void __maybe_unused cros_ec_sensors_complete(struct device *dev)
601 {
602 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
603 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
604 
605 	if (st->curr_sampl_freq == 0)
606 		return;
607 
608 	if (st->curr_sampl_freq < CROS_EC_MIN_SUSPEND_SAMPLING_FREQUENCY) {
609 		mutex_lock(&st->cmd_lock);
610 		st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
611 		st->param.ec_rate.data = st->curr_sampl_freq;
612 		cros_ec_motion_send_host_cmd(st, 0);
613 		mutex_unlock(&st->cmd_lock);
614 	}
615 }
616 
617 const struct dev_pm_ops cros_ec_sensors_pm_ops = {
618 #ifdef CONFIG_PM_SLEEP
619 	.prepare = cros_ec_sensors_prepare,
620 	.complete = cros_ec_sensors_complete
621 #endif
622 };
623 EXPORT_SYMBOL_GPL(cros_ec_sensors_pm_ops);
624 
625 MODULE_DESCRIPTION("ChromeOS EC sensor hub core functions");
626 MODULE_LICENSE("GPL v2");
627