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