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