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