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