xref: /linux/drivers/iio/common/cros_ec_sensors/cros_ec_sensors_core.c (revision 0d5ec7919f3747193f051036b2301734a4b5e1d6)
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 const struct iio_chan_spec_ext_info cros_ec_sensors_limited_info[] = {
490 	{
491 		.name = "id",
492 		.shared = IIO_SHARED_BY_ALL,
493 		.read = cros_ec_sensors_id
494 	},
495 	{ }
496 };
497 EXPORT_SYMBOL_GPL(cros_ec_sensors_limited_info);
498 
499 /**
500  * cros_ec_sensors_idx_to_reg - convert index into offset in shared memory
501  * @st:		pointer to state information for device
502  * @idx:	sensor index (should be element of enum sensor_index)
503  *
504  * Return:	address to read at
505  */
cros_ec_sensors_idx_to_reg(struct cros_ec_sensors_core_state * st,unsigned int idx)506 static unsigned int cros_ec_sensors_idx_to_reg(
507 					struct cros_ec_sensors_core_state *st,
508 					unsigned int idx)
509 {
510 	/*
511 	 * When using LPC interface, only space for 2 Accel and one Gyro.
512 	 * First halfword of MOTIONSENSE_TYPE_ACCEL is used by angle.
513 	 */
514 	if (st->type == MOTIONSENSE_TYPE_ACCEL)
515 		return EC_MEMMAP_ACC_DATA + sizeof(u16) *
516 			(1 + idx + st->param.info.sensor_num *
517 			 CROS_EC_SENSOR_MAX_AXIS);
518 
519 	return EC_MEMMAP_GYRO_DATA + sizeof(u16) * idx;
520 }
521 
cros_ec_sensors_cmd_read_u8(struct cros_ec_device * ec,unsigned int offset,u8 * dest)522 static int cros_ec_sensors_cmd_read_u8(struct cros_ec_device *ec,
523 				       unsigned int offset, u8 *dest)
524 {
525 	return ec->cmd_readmem(ec, offset, 1, dest);
526 }
527 
cros_ec_sensors_cmd_read_u16(struct cros_ec_device * ec,unsigned int offset,u16 * dest)528 static int cros_ec_sensors_cmd_read_u16(struct cros_ec_device *ec,
529 					 unsigned int offset, u16 *dest)
530 {
531 	__le16 tmp;
532 	int ret = ec->cmd_readmem(ec, offset, 2, &tmp);
533 
534 	if (ret >= 0)
535 		*dest = le16_to_cpu(tmp);
536 
537 	return ret;
538 }
539 
540 /**
541  * cros_ec_sensors_read_until_not_busy() - read until is not busy
542  *
543  * @st:	pointer to state information for device
544  *
545  * Read from EC status byte until it reads not busy.
546  * Return: 8-bit status if ok, -errno on failure.
547  */
cros_ec_sensors_read_until_not_busy(struct cros_ec_sensors_core_state * st)548 static int cros_ec_sensors_read_until_not_busy(
549 					struct cros_ec_sensors_core_state *st)
550 {
551 	struct cros_ec_device *ec = st->ec;
552 	u8 status;
553 	int ret, attempts = 0;
554 
555 	ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS, &status);
556 	if (ret < 0)
557 		return ret;
558 
559 	while (status & EC_MEMMAP_ACC_STATUS_BUSY_BIT) {
560 		/* Give up after enough attempts, return error. */
561 		if (attempts++ >= 50)
562 			return -EIO;
563 
564 		/* Small delay every so often. */
565 		if (attempts % 5 == 0)
566 			msleep(25);
567 
568 		ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS,
569 						  &status);
570 		if (ret < 0)
571 			return ret;
572 	}
573 
574 	return status;
575 }
576 
577 /**
578  * cros_ec_sensors_read_data_unsafe() - read acceleration data from EC shared memory
579  * @indio_dev:	pointer to IIO device
580  * @scan_mask:	bitmap of the sensor indices to scan
581  * @data:	location to store data
582  *
583  * This is the unsafe function for reading the EC data. It does not guarantee
584  * that the EC will not modify the data as it is being read in.
585  *
586  * Return: 0 on success, -errno on failure.
587  */
cros_ec_sensors_read_data_unsafe(struct iio_dev * indio_dev,unsigned long scan_mask,s16 * data)588 static int cros_ec_sensors_read_data_unsafe(struct iio_dev *indio_dev,
589 			 unsigned long scan_mask, s16 *data)
590 {
591 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
592 	struct cros_ec_device *ec = st->ec;
593 	unsigned int i;
594 	int ret;
595 
596 	/* Read all sensors enabled in scan_mask. Each value is 2 bytes. */
597 	for_each_set_bit(i, &scan_mask, iio_get_masklength(indio_dev)) {
598 		ret = cros_ec_sensors_cmd_read_u16(ec,
599 					     cros_ec_sensors_idx_to_reg(st, i),
600 					     data);
601 		if (ret < 0)
602 			return ret;
603 
604 		*data *= st->sign[i];
605 		data++;
606 	}
607 
608 	return 0;
609 }
610 
611 /**
612  * cros_ec_sensors_read_lpc() - read acceleration data from EC shared memory.
613  * @indio_dev: pointer to IIO device.
614  * @scan_mask: bitmap of the sensor indices to scan.
615  * @data: location to store data.
616  *
617  * Note: this is the safe function for reading the EC data. It guarantees
618  * that the data sampled was not modified by the EC while being read.
619  *
620  * Return: 0 on success, -errno on failure.
621  */
cros_ec_sensors_read_lpc(struct iio_dev * indio_dev,unsigned long scan_mask,s16 * data)622 int cros_ec_sensors_read_lpc(struct iio_dev *indio_dev,
623 			     unsigned long scan_mask, s16 *data)
624 {
625 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
626 	struct cros_ec_device *ec = st->ec;
627 	u8 samp_id = 0xff, status = 0;
628 	int ret, attempts = 0;
629 
630 	/*
631 	 * Continually read all data from EC until the status byte after
632 	 * all reads reflects that the EC is not busy and the sample id
633 	 * matches the sample id from before all reads. This guarantees
634 	 * that data read in was not modified by the EC while reading.
635 	 */
636 	while ((status & (EC_MEMMAP_ACC_STATUS_BUSY_BIT |
637 			  EC_MEMMAP_ACC_STATUS_SAMPLE_ID_MASK)) != samp_id) {
638 		/* If we have tried to read too many times, return error. */
639 		if (attempts++ >= 5)
640 			return -EIO;
641 
642 		/* Read status byte until EC is not busy. */
643 		ret = cros_ec_sensors_read_until_not_busy(st);
644 		if (ret < 0)
645 			return ret;
646 
647 		/*
648 		 * Store the current sample id so that we can compare to the
649 		 * sample id after reading the data.
650 		 */
651 		samp_id = ret & EC_MEMMAP_ACC_STATUS_SAMPLE_ID_MASK;
652 
653 		/* Read all EC data, format it, and store it into data. */
654 		ret = cros_ec_sensors_read_data_unsafe(indio_dev, scan_mask,
655 						       data);
656 		if (ret < 0)
657 			return ret;
658 
659 		/* Read status byte. */
660 		ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS,
661 						  &status);
662 		if (ret < 0)
663 			return ret;
664 	}
665 
666 	return 0;
667 }
668 EXPORT_SYMBOL_GPL(cros_ec_sensors_read_lpc);
669 
670 /**
671  * cros_ec_sensors_read_cmd() - retrieve data using the EC command protocol
672  * @indio_dev:	pointer to IIO device
673  * @scan_mask:	bitmap of the sensor indices to scan
674  * @data:	location to store data
675  *
676  * Return: 0 on success, -errno on failure.
677  */
cros_ec_sensors_read_cmd(struct iio_dev * indio_dev,unsigned long scan_mask,s16 * data)678 int cros_ec_sensors_read_cmd(struct iio_dev *indio_dev,
679 			     unsigned long scan_mask, s16 *data)
680 {
681 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
682 	int ret;
683 	unsigned int i;
684 
685 	/* Read all sensor data through a command. */
686 	st->param.cmd = MOTIONSENSE_CMD_DATA;
687 	ret = cros_ec_motion_send_host_cmd(st, sizeof(st->resp->data));
688 	if (ret != 0) {
689 		dev_warn(&indio_dev->dev, "Unable to read sensor data\n");
690 		return ret;
691 	}
692 
693 	for_each_set_bit(i, &scan_mask, iio_get_masklength(indio_dev)) {
694 		*data = st->resp->data.data[i];
695 		data++;
696 	}
697 
698 	return 0;
699 }
700 EXPORT_SYMBOL_GPL(cros_ec_sensors_read_cmd);
701 
702 /**
703  * cros_ec_sensors_capture() - the trigger handler function
704  * @irq:	the interrupt number.
705  * @p:		a pointer to the poll function.
706  *
707  * On a trigger event occurring, if the pollfunc is attached then this
708  * handler is called as a threaded interrupt (and hence may sleep). It
709  * is responsible for grabbing data from the device and pushing it into
710  * the associated buffer.
711  *
712  * Return: IRQ_HANDLED
713  */
cros_ec_sensors_capture(int irq,void * p)714 irqreturn_t cros_ec_sensors_capture(int irq, void *p)
715 {
716 	struct iio_poll_func *pf = p;
717 	struct iio_dev *indio_dev = pf->indio_dev;
718 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
719 	int ret;
720 
721 	mutex_lock(&st->cmd_lock);
722 
723 	/* Clear capture data. */
724 	memset(st->samples, 0, indio_dev->scan_bytes);
725 
726 	/* Read data based on which channels are enabled in scan mask. */
727 	ret = st->read_ec_sensors_data(indio_dev,
728 				       *(indio_dev->active_scan_mask),
729 				       (s16 *)st->samples);
730 	if (ret < 0)
731 		goto done;
732 
733 	iio_push_to_buffers_with_timestamp(indio_dev, st->samples,
734 					   iio_get_time_ns(indio_dev));
735 
736 done:
737 	/*
738 	 * Tell the core we are done with this trigger and ready for the
739 	 * next one.
740 	 */
741 	iio_trigger_notify_done(indio_dev->trig);
742 
743 	mutex_unlock(&st->cmd_lock);
744 
745 	return IRQ_HANDLED;
746 }
747 EXPORT_SYMBOL_GPL(cros_ec_sensors_capture);
748 
749 /**
750  * cros_ec_sensors_core_read() - function to request a value from the sensor
751  * @st:		pointer to state information for device
752  * @chan:	channel specification structure table
753  * @val:	will contain one element making up the returned value
754  * @val2:	will contain another element making up the returned value
755  * @mask:	specifies which values to be requested
756  *
757  * Return:	the type of value returned by the device
758  */
cros_ec_sensors_core_read(struct cros_ec_sensors_core_state * st,struct iio_chan_spec const * chan,int * val,int * val2,long mask)759 int cros_ec_sensors_core_read(struct cros_ec_sensors_core_state *st,
760 			  struct iio_chan_spec const *chan,
761 			  int *val, int *val2, long mask)
762 {
763 	int ret, frequency;
764 
765 	switch (mask) {
766 	case IIO_CHAN_INFO_SAMP_FREQ:
767 		st->param.cmd = MOTIONSENSE_CMD_SENSOR_ODR;
768 		st->param.sensor_odr.data =
769 			EC_MOTION_SENSE_NO_VALUE;
770 
771 		ret = cros_ec_motion_send_host_cmd(st, 0);
772 		if (ret)
773 			break;
774 
775 		frequency = st->resp->sensor_odr.ret;
776 		*val = frequency / 1000;
777 		*val2 = (frequency % 1000) * 1000;
778 		ret = IIO_VAL_INT_PLUS_MICRO;
779 		break;
780 	default:
781 		ret = -EINVAL;
782 		break;
783 	}
784 
785 	return ret;
786 }
787 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_read);
788 
789 /**
790  * cros_ec_sensors_core_read_avail() - get available values
791  * @indio_dev:		pointer to state information for device
792  * @chan:	channel specification structure table
793  * @vals:	list of available values
794  * @type:	type of data returned
795  * @length:	number of data returned in the array
796  * @mask:	specifies which values to be requested
797  *
798  * Return:	an error code, IIO_AVAIL_RANGE or IIO_AVAIL_LIST
799  */
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)800 int cros_ec_sensors_core_read_avail(struct iio_dev *indio_dev,
801 				    struct iio_chan_spec const *chan,
802 				    const int **vals,
803 				    int *type,
804 				    int *length,
805 				    long mask)
806 {
807 	struct cros_ec_sensors_core_state *state = iio_priv(indio_dev);
808 
809 	switch (mask) {
810 	case IIO_CHAN_INFO_SAMP_FREQ:
811 		*length = ARRAY_SIZE(state->frequencies);
812 		*vals = (const int *)&state->frequencies;
813 		*type = IIO_VAL_INT_PLUS_MICRO;
814 		return IIO_AVAIL_LIST;
815 	}
816 
817 	return -EINVAL;
818 }
819 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_read_avail);
820 
821 /**
822  * cros_ec_sensors_core_write() - function to write a value to the sensor
823  * @st:		pointer to state information for device
824  * @chan:	channel specification structure table
825  * @val:	first part of value to write
826  * @val2:	second part of value to write
827  * @mask:	specifies which values to write
828  *
829  * Return:	the type of value returned by the device
830  */
cros_ec_sensors_core_write(struct cros_ec_sensors_core_state * st,struct iio_chan_spec const * chan,int val,int val2,long mask)831 int cros_ec_sensors_core_write(struct cros_ec_sensors_core_state *st,
832 			       struct iio_chan_spec const *chan,
833 			       int val, int val2, long mask)
834 {
835 	int ret, frequency;
836 
837 	switch (mask) {
838 	case IIO_CHAN_INFO_SAMP_FREQ:
839 		frequency = val * 1000 + val2 / 1000;
840 		st->param.cmd = MOTIONSENSE_CMD_SENSOR_ODR;
841 		st->param.sensor_odr.data = frequency;
842 
843 		/* Always roundup, so caller gets at least what it asks for. */
844 		st->param.sensor_odr.roundup = 1;
845 
846 		ret = cros_ec_motion_send_host_cmd(st, 0);
847 		if (ret)
848 			break;
849 
850 		/* Flush the FIFO when a sensor is stopped.
851 		 * If the FIFO has just been emptied, pending samples will be
852 		 * stuck until new samples are available. It will not happen
853 		 * when all the sensors are stopped.
854 		 */
855 		if (frequency == 0) {
856 			st->param.cmd = MOTIONSENSE_CMD_FIFO_FLUSH;
857 			ret = cros_ec_motion_send_host_cmd(st, 0);
858 		}
859 		break;
860 	default:
861 		ret = -EINVAL;
862 		break;
863 	}
864 	return ret;
865 }
866 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_write);
867 
cros_ec_sensors_resume(struct device * dev)868 static int __maybe_unused cros_ec_sensors_resume(struct device *dev)
869 {
870 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
871 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
872 	int ret = 0;
873 
874 	if (st->range_updated) {
875 		mutex_lock(&st->cmd_lock);
876 		st->param.cmd = MOTIONSENSE_CMD_SENSOR_RANGE;
877 		st->param.sensor_range.data = st->curr_range;
878 		st->param.sensor_range.roundup = 1;
879 		ret = cros_ec_motion_send_host_cmd(st, 0);
880 		mutex_unlock(&st->cmd_lock);
881 	}
882 	return ret;
883 }
884 
885 SIMPLE_DEV_PM_OPS(cros_ec_sensors_pm_ops, NULL, cros_ec_sensors_resume);
886 EXPORT_SYMBOL_GPL(cros_ec_sensors_pm_ops);
887 
888 MODULE_DESCRIPTION("ChromeOS EC sensor hub core functions");
889 MODULE_LICENSE("GPL v2");
890