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