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/sysfs.h>
15 #include <linux/iio/trigger.h>
16 #include <linux/iio/trigger_consumer.h>
17 #include <linux/iio/triggered_buffer.h>
18 #include <linux/kernel.h>
19 #include <linux/module.h>
20 #include <linux/slab.h>
21 #include <linux/platform_data/cros_ec_commands.h>
22 #include <linux/platform_data/cros_ec_proto.h>
23 #include <linux/platform_data/cros_ec_sensorhub.h>
24 #include <linux/platform_device.h>
25 
26 /*
27  * Hard coded to the first device to support sensor fifo.  The EC has a 2048
28  * byte fifo and will trigger an interrupt when fifo is 2/3 full.
29  */
30 #define CROS_EC_FIFO_SIZE (2048 * 2 / 3)
31 
32 static int cros_ec_get_host_cmd_version_mask(struct cros_ec_device *ec_dev,
33 					     u16 cmd_offset, u16 cmd, u32 *mask)
34 {
35 	int ret;
36 	struct {
37 		struct cros_ec_command msg;
38 		union {
39 			struct ec_params_get_cmd_versions params;
40 			struct ec_response_get_cmd_versions resp;
41 		};
42 	} __packed buf = {
43 		.msg = {
44 			.command = EC_CMD_GET_CMD_VERSIONS + cmd_offset,
45 			.insize = sizeof(struct ec_response_get_cmd_versions),
46 			.outsize = sizeof(struct ec_params_get_cmd_versions)
47 			},
48 		.params = {.cmd = cmd}
49 	};
50 
51 	ret = cros_ec_cmd_xfer_status(ec_dev, &buf.msg);
52 	if (ret >= 0)
53 		*mask = buf.resp.version_mask;
54 	return ret;
55 }
56 
57 static void get_default_min_max_freq(enum motionsensor_type type,
58 				     u32 *min_freq,
59 				     u32 *max_freq,
60 				     u32 *max_fifo_events)
61 {
62 	/*
63 	 * We don't know fifo size, set to size previously used by older
64 	 * hardware.
65 	 */
66 	*max_fifo_events = CROS_EC_FIFO_SIZE;
67 
68 	switch (type) {
69 	case MOTIONSENSE_TYPE_ACCEL:
70 		*min_freq = 12500;
71 		*max_freq = 100000;
72 		break;
73 	case MOTIONSENSE_TYPE_GYRO:
74 		*min_freq = 25000;
75 		*max_freq = 100000;
76 		break;
77 	case MOTIONSENSE_TYPE_MAG:
78 		*min_freq = 5000;
79 		*max_freq = 25000;
80 		break;
81 	case MOTIONSENSE_TYPE_PROX:
82 	case MOTIONSENSE_TYPE_LIGHT:
83 		*min_freq = 100;
84 		*max_freq = 50000;
85 		break;
86 	case MOTIONSENSE_TYPE_BARO:
87 		*min_freq = 250;
88 		*max_freq = 20000;
89 		break;
90 	case MOTIONSENSE_TYPE_ACTIVITY:
91 	default:
92 		*min_freq = 0;
93 		*max_freq = 0;
94 		break;
95 	}
96 }
97 
98 static int cros_ec_sensor_set_ec_rate(struct cros_ec_sensors_core_state *st,
99 				      int rate)
100 {
101 	int ret;
102 
103 	if (rate > U16_MAX)
104 		rate = U16_MAX;
105 
106 	mutex_lock(&st->cmd_lock);
107 	st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
108 	st->param.ec_rate.data = rate;
109 	ret = cros_ec_motion_send_host_cmd(st, 0);
110 	mutex_unlock(&st->cmd_lock);
111 	return ret;
112 }
113 
114 static ssize_t cros_ec_sensor_set_report_latency(struct device *dev,
115 						 struct device_attribute *attr,
116 						 const char *buf, size_t len)
117 {
118 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
119 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
120 	int integer, fract, ret;
121 	int latency;
122 
123 	ret = iio_str_to_fixpoint(buf, 100000, &integer, &fract);
124 	if (ret)
125 		return ret;
126 
127 	/* EC rate is in ms. */
128 	latency = integer * 1000 + fract / 1000;
129 	ret = cros_ec_sensor_set_ec_rate(st, latency);
130 	if (ret < 0)
131 		return ret;
132 
133 	return len;
134 }
135 
136 static ssize_t cros_ec_sensor_get_report_latency(struct device *dev,
137 						 struct device_attribute *attr,
138 						 char *buf)
139 {
140 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
141 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
142 	int latency, ret;
143 
144 	mutex_lock(&st->cmd_lock);
145 	st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
146 	st->param.ec_rate.data = EC_MOTION_SENSE_NO_VALUE;
147 
148 	ret = cros_ec_motion_send_host_cmd(st, 0);
149 	latency = st->resp->ec_rate.ret;
150 	mutex_unlock(&st->cmd_lock);
151 	if (ret < 0)
152 		return ret;
153 
154 	return sprintf(buf, "%d.%06u\n",
155 		       latency / 1000,
156 		       (latency % 1000) * 1000);
157 }
158 
159 static IIO_DEVICE_ATTR(hwfifo_timeout, 0644,
160 		       cros_ec_sensor_get_report_latency,
161 		       cros_ec_sensor_set_report_latency, 0);
162 
163 static ssize_t hwfifo_watermark_max_show(struct device *dev,
164 					 struct device_attribute *attr,
165 					 char *buf)
166 {
167 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
168 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
169 
170 	return sprintf(buf, "%d\n", st->fifo_max_event_count);
171 }
172 
173 static IIO_DEVICE_ATTR_RO(hwfifo_watermark_max, 0);
174 
175 static const struct attribute *cros_ec_sensor_fifo_attributes[] = {
176 	&iio_dev_attr_hwfifo_timeout.dev_attr.attr,
177 	&iio_dev_attr_hwfifo_watermark_max.dev_attr.attr,
178 	NULL,
179 };
180 
181 int cros_ec_sensors_push_data(struct iio_dev *indio_dev,
182 			      s16 *data,
183 			      s64 timestamp)
184 {
185 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
186 	s16 *out;
187 	s64 delta;
188 	unsigned int i;
189 
190 	/*
191 	 * Ignore samples if the buffer is not set: it is needed if the ODR is
192 	 * set but the buffer is not enabled yet.
193 	 */
194 	if (!iio_buffer_enabled(indio_dev))
195 		return 0;
196 
197 	out = (s16 *)st->samples;
198 	for_each_set_bit(i,
199 			 indio_dev->active_scan_mask,
200 			 indio_dev->masklength) {
201 		*out = data[i];
202 		out++;
203 	}
204 
205 	if (iio_device_get_clock(indio_dev) != CLOCK_BOOTTIME)
206 		delta = iio_get_time_ns(indio_dev) - cros_ec_get_time_ns();
207 	else
208 		delta = 0;
209 
210 	iio_push_to_buffers_with_timestamp(indio_dev, st->samples,
211 					   timestamp + delta);
212 
213 	return 0;
214 }
215 EXPORT_SYMBOL_GPL(cros_ec_sensors_push_data);
216 
217 static void cros_ec_sensors_core_clean(void *arg)
218 {
219 	struct platform_device *pdev = (struct platform_device *)arg;
220 	struct cros_ec_sensorhub *sensor_hub =
221 		dev_get_drvdata(pdev->dev.parent);
222 	struct iio_dev *indio_dev = platform_get_drvdata(pdev);
223 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
224 	u8 sensor_num = st->param.info.sensor_num;
225 
226 	cros_ec_sensorhub_unregister_push_data(sensor_hub, sensor_num);
227 }
228 
229 /**
230  * cros_ec_sensors_core_init() - basic initialization of the core structure
231  * @pdev:		platform device created for the sensors
232  * @indio_dev:		iio device structure of the device
233  * @physical_device:	true if the device refers to a physical device
234  * @trigger_capture:    function pointer to call buffer is triggered,
235  *    for backward compatibility.
236  * @push_data:          function to call when cros_ec_sensorhub receives
237  *    a sample for that sensor.
238  *
239  * Return: 0 on success, -errno on failure.
240  */
241 int cros_ec_sensors_core_init(struct platform_device *pdev,
242 			      struct iio_dev *indio_dev,
243 			      bool physical_device,
244 			      cros_ec_sensors_capture_t trigger_capture,
245 			      cros_ec_sensorhub_push_data_cb_t push_data)
246 {
247 	struct device *dev = &pdev->dev;
248 	struct cros_ec_sensors_core_state *state = iio_priv(indio_dev);
249 	struct cros_ec_sensorhub *sensor_hub = dev_get_drvdata(dev->parent);
250 	struct cros_ec_dev *ec = sensor_hub->ec;
251 	struct cros_ec_sensor_platform *sensor_platform = dev_get_platdata(dev);
252 	u32 ver_mask, temp;
253 	int frequencies[ARRAY_SIZE(state->frequencies) / 2] = { 0 };
254 	int ret, i;
255 
256 	platform_set_drvdata(pdev, indio_dev);
257 
258 	state->ec = ec->ec_dev;
259 	state->msg = devm_kzalloc(&pdev->dev,
260 				max((u16)sizeof(struct ec_params_motion_sense),
261 				state->ec->max_response), GFP_KERNEL);
262 	if (!state->msg)
263 		return -ENOMEM;
264 
265 	state->resp = (struct ec_response_motion_sense *)state->msg->data;
266 
267 	mutex_init(&state->cmd_lock);
268 
269 	ret = cros_ec_get_host_cmd_version_mask(state->ec,
270 						ec->cmd_offset,
271 						EC_CMD_MOTION_SENSE_CMD,
272 						&ver_mask);
273 	if (ret < 0)
274 		return ret;
275 
276 	/* Set up the host command structure. */
277 	state->msg->version = fls(ver_mask) - 1;
278 	state->msg->command = EC_CMD_MOTION_SENSE_CMD + ec->cmd_offset;
279 	state->msg->outsize = sizeof(struct ec_params_motion_sense);
280 
281 	indio_dev->name = pdev->name;
282 
283 	if (physical_device) {
284 		enum motionsensor_location loc;
285 
286 		state->param.cmd = MOTIONSENSE_CMD_INFO;
287 		state->param.info.sensor_num = sensor_platform->sensor_num;
288 		ret = cros_ec_motion_send_host_cmd(state, 0);
289 		if (ret) {
290 			dev_warn(dev, "Can not access sensor info\n");
291 			return ret;
292 		}
293 		state->type = state->resp->info.type;
294 		loc = state->resp->info.location;
295 		if (loc == MOTIONSENSE_LOC_BASE)
296 			indio_dev->label = "accel-base";
297 		else if (loc == MOTIONSENSE_LOC_LID)
298 			indio_dev->label = "accel-display";
299 		else if (loc == MOTIONSENSE_LOC_CAMERA)
300 			indio_dev->label = "accel-camera";
301 
302 		/* Set sign vector, only used for backward compatibility. */
303 		memset(state->sign, 1, CROS_EC_SENSOR_MAX_AXIS);
304 
305 		for (i = CROS_EC_SENSOR_X; i < CROS_EC_SENSOR_MAX_AXIS; i++)
306 			state->calib[i].scale = MOTION_SENSE_DEFAULT_SCALE;
307 
308 		/* 0 is a correct value used to stop the device */
309 		if (state->msg->version < 3) {
310 			get_default_min_max_freq(state->resp->info.type,
311 						 &frequencies[1],
312 						 &frequencies[2],
313 						 &state->fifo_max_event_count);
314 		} else {
315 			if (state->resp->info_3.max_frequency == 0) {
316 				get_default_min_max_freq(state->resp->info.type,
317 							 &frequencies[1],
318 							 &frequencies[2],
319 							 &temp);
320 			} else {
321 				frequencies[1] = state->resp->info_3.min_frequency;
322 				frequencies[2] = state->resp->info_3.max_frequency;
323 			}
324 			state->fifo_max_event_count = state->resp->info_3.fifo_max_event_count;
325 		}
326 		for (i = 0; i < ARRAY_SIZE(frequencies); i++) {
327 			state->frequencies[2 * i] = frequencies[i] / 1000;
328 			state->frequencies[2 * i + 1] =
329 				(frequencies[i] % 1000) * 1000;
330 		}
331 
332 		if (cros_ec_check_features(ec, EC_FEATURE_MOTION_SENSE_FIFO)) {
333 			/*
334 			 * Create a software buffer, feed by the EC FIFO.
335 			 * We can not use trigger here, as events are generated
336 			 * as soon as sample_frequency is set.
337 			 */
338 			ret = devm_iio_kfifo_buffer_setup_ext(dev, indio_dev, NULL,
339 							      cros_ec_sensor_fifo_attributes);
340 			if (ret)
341 				return ret;
342 
343 			ret = cros_ec_sensorhub_register_push_data(
344 					sensor_hub, sensor_platform->sensor_num,
345 					indio_dev, push_data);
346 			if (ret)
347 				return ret;
348 
349 			ret = devm_add_action_or_reset(
350 					dev, cros_ec_sensors_core_clean, pdev);
351 			if (ret)
352 				return ret;
353 
354 			/* Timestamp coming from FIFO are in ns since boot. */
355 			ret = iio_device_set_clock(indio_dev, CLOCK_BOOTTIME);
356 			if (ret)
357 				return ret;
358 
359 		} else {
360 			/*
361 			 * The only way to get samples in buffer is to set a
362 			 * software trigger (systrig, hrtimer).
363 			 */
364 			ret = devm_iio_triggered_buffer_setup(dev, indio_dev,
365 					NULL, trigger_capture, NULL);
366 			if (ret)
367 				return ret;
368 		}
369 	}
370 
371 	return 0;
372 }
373 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_init);
374 
375 /**
376  * cros_ec_motion_send_host_cmd() - send motion sense host command
377  * @state:		pointer to state information for device
378  * @opt_length:	optional length to reduce the response size, useful on the data
379  *		path. Otherwise, the maximal allowed response size is used
380  *
381  * When called, the sub-command is assumed to be set in param->cmd.
382  *
383  * Return: 0 on success, -errno on failure.
384  */
385 int cros_ec_motion_send_host_cmd(struct cros_ec_sensors_core_state *state,
386 				 u16 opt_length)
387 {
388 	int ret;
389 
390 	if (opt_length)
391 		state->msg->insize = min(opt_length, state->ec->max_response);
392 	else
393 		state->msg->insize = state->ec->max_response;
394 
395 	memcpy(state->msg->data, &state->param, sizeof(state->param));
396 
397 	ret = cros_ec_cmd_xfer_status(state->ec, state->msg);
398 	if (ret < 0)
399 		return ret;
400 
401 	if (ret &&
402 	    state->resp != (struct ec_response_motion_sense *)state->msg->data)
403 		memcpy(state->resp, state->msg->data, ret);
404 
405 	return 0;
406 }
407 EXPORT_SYMBOL_GPL(cros_ec_motion_send_host_cmd);
408 
409 static ssize_t cros_ec_sensors_calibrate(struct iio_dev *indio_dev,
410 		uintptr_t private, const struct iio_chan_spec *chan,
411 		const char *buf, size_t len)
412 {
413 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
414 	int ret, i;
415 	bool calibrate;
416 
417 	ret = kstrtobool(buf, &calibrate);
418 	if (ret < 0)
419 		return ret;
420 	if (!calibrate)
421 		return -EINVAL;
422 
423 	mutex_lock(&st->cmd_lock);
424 	st->param.cmd = MOTIONSENSE_CMD_PERFORM_CALIB;
425 	ret = cros_ec_motion_send_host_cmd(st, 0);
426 	if (ret != 0) {
427 		dev_warn(&indio_dev->dev, "Unable to calibrate sensor\n");
428 	} else {
429 		/* Save values */
430 		for (i = CROS_EC_SENSOR_X; i < CROS_EC_SENSOR_MAX_AXIS; i++)
431 			st->calib[i].offset = st->resp->perform_calib.offset[i];
432 	}
433 	mutex_unlock(&st->cmd_lock);
434 
435 	return ret ? ret : len;
436 }
437 
438 static ssize_t cros_ec_sensors_id(struct iio_dev *indio_dev,
439 				  uintptr_t private,
440 				  const struct iio_chan_spec *chan, char *buf)
441 {
442 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
443 
444 	return snprintf(buf, PAGE_SIZE, "%d\n", st->param.info.sensor_num);
445 }
446 
447 const struct iio_chan_spec_ext_info cros_ec_sensors_ext_info[] = {
448 	{
449 		.name = "calibrate",
450 		.shared = IIO_SHARED_BY_ALL,
451 		.write = cros_ec_sensors_calibrate
452 	},
453 	{
454 		.name = "id",
455 		.shared = IIO_SHARED_BY_ALL,
456 		.read = cros_ec_sensors_id
457 	},
458 	{ },
459 };
460 EXPORT_SYMBOL_GPL(cros_ec_sensors_ext_info);
461 
462 /**
463  * cros_ec_sensors_idx_to_reg - convert index into offset in shared memory
464  * @st:		pointer to state information for device
465  * @idx:	sensor index (should be element of enum sensor_index)
466  *
467  * Return:	address to read at
468  */
469 static unsigned int cros_ec_sensors_idx_to_reg(
470 					struct cros_ec_sensors_core_state *st,
471 					unsigned int idx)
472 {
473 	/*
474 	 * When using LPC interface, only space for 2 Accel and one Gyro.
475 	 * First halfword of MOTIONSENSE_TYPE_ACCEL is used by angle.
476 	 */
477 	if (st->type == MOTIONSENSE_TYPE_ACCEL)
478 		return EC_MEMMAP_ACC_DATA + sizeof(u16) *
479 			(1 + idx + st->param.info.sensor_num *
480 			 CROS_EC_SENSOR_MAX_AXIS);
481 
482 	return EC_MEMMAP_GYRO_DATA + sizeof(u16) * idx;
483 }
484 
485 static int cros_ec_sensors_cmd_read_u8(struct cros_ec_device *ec,
486 				       unsigned int offset, u8 *dest)
487 {
488 	return ec->cmd_readmem(ec, offset, 1, dest);
489 }
490 
491 static int cros_ec_sensors_cmd_read_u16(struct cros_ec_device *ec,
492 					 unsigned int offset, u16 *dest)
493 {
494 	__le16 tmp;
495 	int ret = ec->cmd_readmem(ec, offset, 2, &tmp);
496 
497 	if (ret >= 0)
498 		*dest = le16_to_cpu(tmp);
499 
500 	return ret;
501 }
502 
503 /**
504  * cros_ec_sensors_read_until_not_busy() - read until is not busy
505  *
506  * @st:	pointer to state information for device
507  *
508  * Read from EC status byte until it reads not busy.
509  * Return: 8-bit status if ok, -errno on failure.
510  */
511 static int cros_ec_sensors_read_until_not_busy(
512 					struct cros_ec_sensors_core_state *st)
513 {
514 	struct cros_ec_device *ec = st->ec;
515 	u8 status;
516 	int ret, attempts = 0;
517 
518 	ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS, &status);
519 	if (ret < 0)
520 		return ret;
521 
522 	while (status & EC_MEMMAP_ACC_STATUS_BUSY_BIT) {
523 		/* Give up after enough attempts, return error. */
524 		if (attempts++ >= 50)
525 			return -EIO;
526 
527 		/* Small delay every so often. */
528 		if (attempts % 5 == 0)
529 			msleep(25);
530 
531 		ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS,
532 						  &status);
533 		if (ret < 0)
534 			return ret;
535 	}
536 
537 	return status;
538 }
539 
540 /**
541  * cros_ec_sensors_read_data_unsafe() - read acceleration data from EC shared memory
542  * @indio_dev:	pointer to IIO device
543  * @scan_mask:	bitmap of the sensor indices to scan
544  * @data:	location to store data
545  *
546  * This is the unsafe function for reading the EC data. It does not guarantee
547  * that the EC will not modify the data as it is being read in.
548  *
549  * Return: 0 on success, -errno on failure.
550  */
551 static int cros_ec_sensors_read_data_unsafe(struct iio_dev *indio_dev,
552 			 unsigned long scan_mask, s16 *data)
553 {
554 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
555 	struct cros_ec_device *ec = st->ec;
556 	unsigned int i;
557 	int ret;
558 
559 	/* Read all sensors enabled in scan_mask. Each value is 2 bytes. */
560 	for_each_set_bit(i, &scan_mask, indio_dev->masklength) {
561 		ret = cros_ec_sensors_cmd_read_u16(ec,
562 					     cros_ec_sensors_idx_to_reg(st, i),
563 					     data);
564 		if (ret < 0)
565 			return ret;
566 
567 		*data *= st->sign[i];
568 		data++;
569 	}
570 
571 	return 0;
572 }
573 
574 /**
575  * cros_ec_sensors_read_lpc() - read acceleration data from EC shared memory.
576  * @indio_dev: pointer to IIO device.
577  * @scan_mask: bitmap of the sensor indices to scan.
578  * @data: location to store data.
579  *
580  * Note: this is the safe function for reading the EC data. It guarantees
581  * that the data sampled was not modified by the EC while being read.
582  *
583  * Return: 0 on success, -errno on failure.
584  */
585 int cros_ec_sensors_read_lpc(struct iio_dev *indio_dev,
586 			     unsigned long scan_mask, s16 *data)
587 {
588 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
589 	struct cros_ec_device *ec = st->ec;
590 	u8 samp_id = 0xff, status = 0;
591 	int ret, attempts = 0;
592 
593 	/*
594 	 * Continually read all data from EC until the status byte after
595 	 * all reads reflects that the EC is not busy and the sample id
596 	 * matches the sample id from before all reads. This guarantees
597 	 * that data read in was not modified by the EC while reading.
598 	 */
599 	while ((status & (EC_MEMMAP_ACC_STATUS_BUSY_BIT |
600 			  EC_MEMMAP_ACC_STATUS_SAMPLE_ID_MASK)) != samp_id) {
601 		/* If we have tried to read too many times, return error. */
602 		if (attempts++ >= 5)
603 			return -EIO;
604 
605 		/* Read status byte until EC is not busy. */
606 		ret = cros_ec_sensors_read_until_not_busy(st);
607 		if (ret < 0)
608 			return ret;
609 
610 		/*
611 		 * Store the current sample id so that we can compare to the
612 		 * sample id after reading the data.
613 		 */
614 		samp_id = ret & EC_MEMMAP_ACC_STATUS_SAMPLE_ID_MASK;
615 
616 		/* Read all EC data, format it, and store it into data. */
617 		ret = cros_ec_sensors_read_data_unsafe(indio_dev, scan_mask,
618 						       data);
619 		if (ret < 0)
620 			return ret;
621 
622 		/* Read status byte. */
623 		ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS,
624 						  &status);
625 		if (ret < 0)
626 			return ret;
627 	}
628 
629 	return 0;
630 }
631 EXPORT_SYMBOL_GPL(cros_ec_sensors_read_lpc);
632 
633 /**
634  * cros_ec_sensors_read_cmd() - retrieve data using the EC command protocol
635  * @indio_dev:	pointer to IIO device
636  * @scan_mask:	bitmap of the sensor indices to scan
637  * @data:	location to store data
638  *
639  * Return: 0 on success, -errno on failure.
640  */
641 int cros_ec_sensors_read_cmd(struct iio_dev *indio_dev,
642 			     unsigned long scan_mask, s16 *data)
643 {
644 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
645 	int ret;
646 	unsigned int i;
647 
648 	/* Read all sensor data through a command. */
649 	st->param.cmd = MOTIONSENSE_CMD_DATA;
650 	ret = cros_ec_motion_send_host_cmd(st, sizeof(st->resp->data));
651 	if (ret != 0) {
652 		dev_warn(&indio_dev->dev, "Unable to read sensor data\n");
653 		return ret;
654 	}
655 
656 	for_each_set_bit(i, &scan_mask, indio_dev->masklength) {
657 		*data = st->resp->data.data[i];
658 		data++;
659 	}
660 
661 	return 0;
662 }
663 EXPORT_SYMBOL_GPL(cros_ec_sensors_read_cmd);
664 
665 /**
666  * cros_ec_sensors_capture() - the trigger handler function
667  * @irq:	the interrupt number.
668  * @p:		a pointer to the poll function.
669  *
670  * On a trigger event occurring, if the pollfunc is attached then this
671  * handler is called as a threaded interrupt (and hence may sleep). It
672  * is responsible for grabbing data from the device and pushing it into
673  * the associated buffer.
674  *
675  * Return: IRQ_HANDLED
676  */
677 irqreturn_t cros_ec_sensors_capture(int irq, void *p)
678 {
679 	struct iio_poll_func *pf = p;
680 	struct iio_dev *indio_dev = pf->indio_dev;
681 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
682 	int ret;
683 
684 	mutex_lock(&st->cmd_lock);
685 
686 	/* Clear capture data. */
687 	memset(st->samples, 0, indio_dev->scan_bytes);
688 
689 	/* Read data based on which channels are enabled in scan mask. */
690 	ret = st->read_ec_sensors_data(indio_dev,
691 				       *(indio_dev->active_scan_mask),
692 				       (s16 *)st->samples);
693 	if (ret < 0)
694 		goto done;
695 
696 	iio_push_to_buffers_with_timestamp(indio_dev, st->samples,
697 					   iio_get_time_ns(indio_dev));
698 
699 done:
700 	/*
701 	 * Tell the core we are done with this trigger and ready for the
702 	 * next one.
703 	 */
704 	iio_trigger_notify_done(indio_dev->trig);
705 
706 	mutex_unlock(&st->cmd_lock);
707 
708 	return IRQ_HANDLED;
709 }
710 EXPORT_SYMBOL_GPL(cros_ec_sensors_capture);
711 
712 /**
713  * cros_ec_sensors_core_read() - function to request a value from the sensor
714  * @st:		pointer to state information for device
715  * @chan:	channel specification structure table
716  * @val:	will contain one element making up the returned value
717  * @val2:	will contain another element making up the returned value
718  * @mask:	specifies which values to be requested
719  *
720  * Return:	the type of value returned by the device
721  */
722 int cros_ec_sensors_core_read(struct cros_ec_sensors_core_state *st,
723 			  struct iio_chan_spec const *chan,
724 			  int *val, int *val2, long mask)
725 {
726 	int ret, frequency;
727 
728 	switch (mask) {
729 	case IIO_CHAN_INFO_SAMP_FREQ:
730 		st->param.cmd = MOTIONSENSE_CMD_SENSOR_ODR;
731 		st->param.sensor_odr.data =
732 			EC_MOTION_SENSE_NO_VALUE;
733 
734 		ret = cros_ec_motion_send_host_cmd(st, 0);
735 		if (ret)
736 			break;
737 
738 		frequency = st->resp->sensor_odr.ret;
739 		*val = frequency / 1000;
740 		*val2 = (frequency % 1000) * 1000;
741 		ret = IIO_VAL_INT_PLUS_MICRO;
742 		break;
743 	default:
744 		ret = -EINVAL;
745 		break;
746 	}
747 
748 	return ret;
749 }
750 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_read);
751 
752 /**
753  * cros_ec_sensors_core_read_avail() - get available values
754  * @indio_dev:		pointer to state information for device
755  * @chan:	channel specification structure table
756  * @vals:	list of available values
757  * @type:	type of data returned
758  * @length:	number of data returned in the array
759  * @mask:	specifies which values to be requested
760  *
761  * Return:	an error code, IIO_AVAIL_RANGE or IIO_AVAIL_LIST
762  */
763 int cros_ec_sensors_core_read_avail(struct iio_dev *indio_dev,
764 				    struct iio_chan_spec const *chan,
765 				    const int **vals,
766 				    int *type,
767 				    int *length,
768 				    long mask)
769 {
770 	struct cros_ec_sensors_core_state *state = iio_priv(indio_dev);
771 
772 	switch (mask) {
773 	case IIO_CHAN_INFO_SAMP_FREQ:
774 		*length = ARRAY_SIZE(state->frequencies);
775 		*vals = (const int *)&state->frequencies;
776 		*type = IIO_VAL_INT_PLUS_MICRO;
777 		return IIO_AVAIL_LIST;
778 	}
779 
780 	return -EINVAL;
781 }
782 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_read_avail);
783 
784 /**
785  * cros_ec_sensors_core_write() - function to write a value to the sensor
786  * @st:		pointer to state information for device
787  * @chan:	channel specification structure table
788  * @val:	first part of value to write
789  * @val2:	second part of value to write
790  * @mask:	specifies which values to write
791  *
792  * Return:	the type of value returned by the device
793  */
794 int cros_ec_sensors_core_write(struct cros_ec_sensors_core_state *st,
795 			       struct iio_chan_spec const *chan,
796 			       int val, int val2, long mask)
797 {
798 	int ret, frequency;
799 
800 	switch (mask) {
801 	case IIO_CHAN_INFO_SAMP_FREQ:
802 		frequency = val * 1000 + val2 / 1000;
803 		st->param.cmd = MOTIONSENSE_CMD_SENSOR_ODR;
804 		st->param.sensor_odr.data = frequency;
805 
806 		/* Always roundup, so caller gets at least what it asks for. */
807 		st->param.sensor_odr.roundup = 1;
808 
809 		ret = cros_ec_motion_send_host_cmd(st, 0);
810 		break;
811 	default:
812 		ret = -EINVAL;
813 		break;
814 	}
815 	return ret;
816 }
817 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_write);
818 
819 static int __maybe_unused cros_ec_sensors_resume(struct device *dev)
820 {
821 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
822 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
823 	int ret = 0;
824 
825 	if (st->range_updated) {
826 		mutex_lock(&st->cmd_lock);
827 		st->param.cmd = MOTIONSENSE_CMD_SENSOR_RANGE;
828 		st->param.sensor_range.data = st->curr_range;
829 		st->param.sensor_range.roundup = 1;
830 		ret = cros_ec_motion_send_host_cmd(st, 0);
831 		mutex_unlock(&st->cmd_lock);
832 	}
833 	return ret;
834 }
835 
836 SIMPLE_DEV_PM_OPS(cros_ec_sensors_pm_ops, NULL, cros_ec_sensors_resume);
837 EXPORT_SYMBOL_GPL(cros_ec_sensors_pm_ops);
838 
839 MODULE_DESCRIPTION("ChromeOS EC sensor hub core functions");
840 MODULE_LICENSE("GPL v2");
841