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/trigger_consumer.h>
15 #include <linux/kernel.h>
16 #include <linux/mfd/cros_ec.h>
17 #include <linux/mfd/cros_ec_commands.h>
18 #include <linux/module.h>
19 #include <linux/slab.h>
20 #include <linux/platform_device.h>
21 
22 static char *cros_ec_loc[] = {
23 	[MOTIONSENSE_LOC_BASE] = "base",
24 	[MOTIONSENSE_LOC_LID] = "lid",
25 	[MOTIONSENSE_LOC_MAX] = "unknown",
26 };
27 
28 int cros_ec_sensors_core_init(struct platform_device *pdev,
29 			      struct iio_dev *indio_dev,
30 			      bool physical_device)
31 {
32 	struct device *dev = &pdev->dev;
33 	struct cros_ec_sensors_core_state *state = iio_priv(indio_dev);
34 	struct cros_ec_dev *ec = dev_get_drvdata(pdev->dev.parent);
35 	struct cros_ec_sensor_platform *sensor_platform = dev_get_platdata(dev);
36 
37 	platform_set_drvdata(pdev, indio_dev);
38 
39 	state->ec = ec->ec_dev;
40 	state->msg = devm_kzalloc(&pdev->dev,
41 				max((u16)sizeof(struct ec_params_motion_sense),
42 				state->ec->max_response), GFP_KERNEL);
43 	if (!state->msg)
44 		return -ENOMEM;
45 
46 	state->resp = (struct ec_response_motion_sense *)state->msg->data;
47 
48 	mutex_init(&state->cmd_lock);
49 
50 	/* Set up the host command structure. */
51 	state->msg->version = 2;
52 	state->msg->command = EC_CMD_MOTION_SENSE_CMD + ec->cmd_offset;
53 	state->msg->outsize = sizeof(struct ec_params_motion_sense);
54 
55 	indio_dev->dev.parent = &pdev->dev;
56 	indio_dev->name = pdev->name;
57 
58 	if (physical_device) {
59 		indio_dev->modes = INDIO_DIRECT_MODE;
60 
61 		state->param.cmd = MOTIONSENSE_CMD_INFO;
62 		state->param.info.sensor_num = sensor_platform->sensor_num;
63 		if (cros_ec_motion_send_host_cmd(state, 0)) {
64 			dev_warn(dev, "Can not access sensor info\n");
65 			return -EIO;
66 		}
67 		state->type = state->resp->info.type;
68 		state->loc = state->resp->info.location;
69 	}
70 
71 	return 0;
72 }
73 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_init);
74 
75 int cros_ec_motion_send_host_cmd(struct cros_ec_sensors_core_state *state,
76 				 u16 opt_length)
77 {
78 	int ret;
79 
80 	if (opt_length)
81 		state->msg->insize = min(opt_length, state->ec->max_response);
82 	else
83 		state->msg->insize = state->ec->max_response;
84 
85 	memcpy(state->msg->data, &state->param, sizeof(state->param));
86 
87 	ret = cros_ec_cmd_xfer_status(state->ec, state->msg);
88 	if (ret < 0)
89 		return -EIO;
90 
91 	if (ret &&
92 	    state->resp != (struct ec_response_motion_sense *)state->msg->data)
93 		memcpy(state->resp, state->msg->data, ret);
94 
95 	return 0;
96 }
97 EXPORT_SYMBOL_GPL(cros_ec_motion_send_host_cmd);
98 
99 static ssize_t cros_ec_sensors_calibrate(struct iio_dev *indio_dev,
100 		uintptr_t private, const struct iio_chan_spec *chan,
101 		const char *buf, size_t len)
102 {
103 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
104 	int ret, i;
105 	bool calibrate;
106 
107 	ret = strtobool(buf, &calibrate);
108 	if (ret < 0)
109 		return ret;
110 	if (!calibrate)
111 		return -EINVAL;
112 
113 	mutex_lock(&st->cmd_lock);
114 	st->param.cmd = MOTIONSENSE_CMD_PERFORM_CALIB;
115 	ret = cros_ec_motion_send_host_cmd(st, 0);
116 	if (ret != 0) {
117 		dev_warn(&indio_dev->dev, "Unable to calibrate sensor\n");
118 	} else {
119 		/* Save values */
120 		for (i = CROS_EC_SENSOR_X; i < CROS_EC_SENSOR_MAX_AXIS; i++)
121 			st->calib[i] = st->resp->perform_calib.offset[i];
122 	}
123 	mutex_unlock(&st->cmd_lock);
124 
125 	return ret ? ret : len;
126 }
127 
128 static ssize_t cros_ec_sensors_loc(struct iio_dev *indio_dev,
129 		uintptr_t private, const struct iio_chan_spec *chan,
130 		char *buf)
131 {
132 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
133 
134 	return snprintf(buf, PAGE_SIZE, "%s\n", cros_ec_loc[st->loc]);
135 }
136 
137 const struct iio_chan_spec_ext_info cros_ec_sensors_ext_info[] = {
138 	{
139 		.name = "calibrate",
140 		.shared = IIO_SHARED_BY_ALL,
141 		.write = cros_ec_sensors_calibrate
142 	},
143 	{
144 		.name = "location",
145 		.shared = IIO_SHARED_BY_ALL,
146 		.read = cros_ec_sensors_loc
147 	},
148 	{ },
149 };
150 EXPORT_SYMBOL_GPL(cros_ec_sensors_ext_info);
151 
152 /**
153  * cros_ec_sensors_idx_to_reg - convert index into offset in shared memory
154  * @st:		pointer to state information for device
155  * @idx:	sensor index (should be element of enum sensor_index)
156  *
157  * Return:	address to read at
158  */
159 static unsigned int cros_ec_sensors_idx_to_reg(
160 					struct cros_ec_sensors_core_state *st,
161 					unsigned int idx)
162 {
163 	/*
164 	 * When using LPC interface, only space for 2 Accel and one Gyro.
165 	 * First halfword of MOTIONSENSE_TYPE_ACCEL is used by angle.
166 	 */
167 	if (st->type == MOTIONSENSE_TYPE_ACCEL)
168 		return EC_MEMMAP_ACC_DATA + sizeof(u16) *
169 			(1 + idx + st->param.info.sensor_num *
170 			 CROS_EC_SENSOR_MAX_AXIS);
171 
172 	return EC_MEMMAP_GYRO_DATA + sizeof(u16) * idx;
173 }
174 
175 static int cros_ec_sensors_cmd_read_u8(struct cros_ec_device *ec,
176 				       unsigned int offset, u8 *dest)
177 {
178 	return ec->cmd_readmem(ec, offset, 1, dest);
179 }
180 
181 static int cros_ec_sensors_cmd_read_u16(struct cros_ec_device *ec,
182 					 unsigned int offset, u16 *dest)
183 {
184 	__le16 tmp;
185 	int ret = ec->cmd_readmem(ec, offset, 2, &tmp);
186 
187 	if (ret >= 0)
188 		*dest = le16_to_cpu(tmp);
189 
190 	return ret;
191 }
192 
193 /**
194  * cros_ec_sensors_read_until_not_busy() - read until is not busy
195  *
196  * @st:	pointer to state information for device
197  *
198  * Read from EC status byte until it reads not busy.
199  * Return: 8-bit status if ok, -errno on failure.
200  */
201 static int cros_ec_sensors_read_until_not_busy(
202 					struct cros_ec_sensors_core_state *st)
203 {
204 	struct cros_ec_device *ec = st->ec;
205 	u8 status;
206 	int ret, attempts = 0;
207 
208 	ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS, &status);
209 	if (ret < 0)
210 		return ret;
211 
212 	while (status & EC_MEMMAP_ACC_STATUS_BUSY_BIT) {
213 		/* Give up after enough attempts, return error. */
214 		if (attempts++ >= 50)
215 			return -EIO;
216 
217 		/* Small delay every so often. */
218 		if (attempts % 5 == 0)
219 			msleep(25);
220 
221 		ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS,
222 						  &status);
223 		if (ret < 0)
224 			return ret;
225 	}
226 
227 	return status;
228 }
229 
230 /**
231  * read_ec_sensors_data_unsafe() - read acceleration data from EC shared memory
232  * @indio_dev:	pointer to IIO device
233  * @scan_mask:	bitmap of the sensor indices to scan
234  * @data:	location to store data
235  *
236  * This is the unsafe function for reading the EC data. It does not guarantee
237  * that the EC will not modify the data as it is being read in.
238  *
239  * Return: 0 on success, -errno on failure.
240  */
241 static int cros_ec_sensors_read_data_unsafe(struct iio_dev *indio_dev,
242 			 unsigned long scan_mask, s16 *data)
243 {
244 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
245 	struct cros_ec_device *ec = st->ec;
246 	unsigned int i;
247 	int ret;
248 
249 	/* Read all sensors enabled in scan_mask. Each value is 2 bytes. */
250 	for_each_set_bit(i, &scan_mask, indio_dev->masklength) {
251 		ret = cros_ec_sensors_cmd_read_u16(ec,
252 					     cros_ec_sensors_idx_to_reg(st, i),
253 					     data);
254 		if (ret < 0)
255 			return ret;
256 
257 		data++;
258 	}
259 
260 	return 0;
261 }
262 
263 /**
264  * cros_ec_sensors_read_lpc() - read acceleration data from EC shared memory.
265  * @indio_dev: pointer to IIO device.
266  * @scan_mask: bitmap of the sensor indices to scan.
267  * @data: location to store data.
268  *
269  * Note: this is the safe function for reading the EC data. It guarantees
270  * that the data sampled was not modified by the EC while being read.
271  *
272  * Return: 0 on success, -errno on failure.
273  */
274 int cros_ec_sensors_read_lpc(struct iio_dev *indio_dev,
275 			     unsigned long scan_mask, s16 *data)
276 {
277 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
278 	struct cros_ec_device *ec = st->ec;
279 	u8 samp_id = 0xff, status = 0;
280 	int ret, attempts = 0;
281 
282 	/*
283 	 * Continually read all data from EC until the status byte after
284 	 * all reads reflects that the EC is not busy and the sample id
285 	 * matches the sample id from before all reads. This guarantees
286 	 * that data read in was not modified by the EC while reading.
287 	 */
288 	while ((status & (EC_MEMMAP_ACC_STATUS_BUSY_BIT |
289 			  EC_MEMMAP_ACC_STATUS_SAMPLE_ID_MASK)) != samp_id) {
290 		/* If we have tried to read too many times, return error. */
291 		if (attempts++ >= 5)
292 			return -EIO;
293 
294 		/* Read status byte until EC is not busy. */
295 		ret = cros_ec_sensors_read_until_not_busy(st);
296 		if (ret < 0)
297 			return ret;
298 
299 		/*
300 		 * Store the current sample id so that we can compare to the
301 		 * sample id after reading the data.
302 		 */
303 		samp_id = ret & EC_MEMMAP_ACC_STATUS_SAMPLE_ID_MASK;
304 
305 		/* Read all EC data, format it, and store it into data. */
306 		ret = cros_ec_sensors_read_data_unsafe(indio_dev, scan_mask,
307 						       data);
308 		if (ret < 0)
309 			return ret;
310 
311 		/* Read status byte. */
312 		ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS,
313 						  &status);
314 		if (ret < 0)
315 			return ret;
316 	}
317 
318 	return 0;
319 }
320 EXPORT_SYMBOL_GPL(cros_ec_sensors_read_lpc);
321 
322 int cros_ec_sensors_read_cmd(struct iio_dev *indio_dev,
323 			     unsigned long scan_mask, s16 *data)
324 {
325 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
326 	int ret;
327 	unsigned int i;
328 
329 	/* Read all sensor data through a command. */
330 	st->param.cmd = MOTIONSENSE_CMD_DATA;
331 	ret = cros_ec_motion_send_host_cmd(st, sizeof(st->resp->data));
332 	if (ret != 0) {
333 		dev_warn(&indio_dev->dev, "Unable to read sensor data\n");
334 		return ret;
335 	}
336 
337 	for_each_set_bit(i, &scan_mask, indio_dev->masklength) {
338 		*data = st->resp->data.data[i];
339 		data++;
340 	}
341 
342 	return 0;
343 }
344 EXPORT_SYMBOL_GPL(cros_ec_sensors_read_cmd);
345 
346 irqreturn_t cros_ec_sensors_capture(int irq, void *p)
347 {
348 	struct iio_poll_func *pf = p;
349 	struct iio_dev *indio_dev = pf->indio_dev;
350 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
351 	int ret;
352 
353 	mutex_lock(&st->cmd_lock);
354 
355 	/* Clear capture data. */
356 	memset(st->samples, 0, indio_dev->scan_bytes);
357 
358 	/* Read data based on which channels are enabled in scan mask. */
359 	ret = st->read_ec_sensors_data(indio_dev,
360 				       *(indio_dev->active_scan_mask),
361 				       (s16 *)st->samples);
362 	if (ret < 0)
363 		goto done;
364 
365 	iio_push_to_buffers_with_timestamp(indio_dev, st->samples,
366 					   iio_get_time_ns(indio_dev));
367 
368 done:
369 	/*
370 	 * Tell the core we are done with this trigger and ready for the
371 	 * next one.
372 	 */
373 	iio_trigger_notify_done(indio_dev->trig);
374 
375 	mutex_unlock(&st->cmd_lock);
376 
377 	return IRQ_HANDLED;
378 }
379 EXPORT_SYMBOL_GPL(cros_ec_sensors_capture);
380 
381 int cros_ec_sensors_core_read(struct cros_ec_sensors_core_state *st,
382 			  struct iio_chan_spec const *chan,
383 			  int *val, int *val2, long mask)
384 {
385 	int ret = IIO_VAL_INT;
386 
387 	switch (mask) {
388 	case IIO_CHAN_INFO_SAMP_FREQ:
389 		st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
390 		st->param.ec_rate.data =
391 			EC_MOTION_SENSE_NO_VALUE;
392 
393 		if (cros_ec_motion_send_host_cmd(st, 0))
394 			ret = -EIO;
395 		else
396 			*val = st->resp->ec_rate.ret;
397 		break;
398 	case IIO_CHAN_INFO_FREQUENCY:
399 		st->param.cmd = MOTIONSENSE_CMD_SENSOR_ODR;
400 		st->param.sensor_odr.data =
401 			EC_MOTION_SENSE_NO_VALUE;
402 
403 		if (cros_ec_motion_send_host_cmd(st, 0))
404 			ret = -EIO;
405 		else
406 			*val = st->resp->sensor_odr.ret;
407 		break;
408 	default:
409 		break;
410 	}
411 
412 	return ret;
413 }
414 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_read);
415 
416 int cros_ec_sensors_core_write(struct cros_ec_sensors_core_state *st,
417 			       struct iio_chan_spec const *chan,
418 			       int val, int val2, long mask)
419 {
420 	int ret = 0;
421 
422 	switch (mask) {
423 	case IIO_CHAN_INFO_FREQUENCY:
424 		st->param.cmd = MOTIONSENSE_CMD_SENSOR_ODR;
425 		st->param.sensor_odr.data = val;
426 
427 		/* Always roundup, so caller gets at least what it asks for. */
428 		st->param.sensor_odr.roundup = 1;
429 
430 		if (cros_ec_motion_send_host_cmd(st, 0))
431 			ret = -EIO;
432 		break;
433 	case IIO_CHAN_INFO_SAMP_FREQ:
434 		st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
435 		st->param.ec_rate.data = val;
436 
437 		if (cros_ec_motion_send_host_cmd(st, 0))
438 			ret = -EIO;
439 		else
440 			st->curr_sampl_freq = val;
441 		break;
442 	default:
443 		ret = -EINVAL;
444 		break;
445 	}
446 	return ret;
447 }
448 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_write);
449 
450 static int __maybe_unused cros_ec_sensors_prepare(struct device *dev)
451 {
452 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
453 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
454 
455 	if (st->curr_sampl_freq == 0)
456 		return 0;
457 
458 	/*
459 	 * If the sensors are sampled at high frequency, we will not be able to
460 	 * sleep. Set sampling to a long period if necessary.
461 	 */
462 	if (st->curr_sampl_freq < CROS_EC_MIN_SUSPEND_SAMPLING_FREQUENCY) {
463 		mutex_lock(&st->cmd_lock);
464 		st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
465 		st->param.ec_rate.data = CROS_EC_MIN_SUSPEND_SAMPLING_FREQUENCY;
466 		cros_ec_motion_send_host_cmd(st, 0);
467 		mutex_unlock(&st->cmd_lock);
468 	}
469 	return 0;
470 }
471 
472 static void __maybe_unused cros_ec_sensors_complete(struct device *dev)
473 {
474 	struct iio_dev *indio_dev = dev_get_drvdata(dev);
475 	struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
476 
477 	if (st->curr_sampl_freq == 0)
478 		return;
479 
480 	if (st->curr_sampl_freq < CROS_EC_MIN_SUSPEND_SAMPLING_FREQUENCY) {
481 		mutex_lock(&st->cmd_lock);
482 		st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
483 		st->param.ec_rate.data = st->curr_sampl_freq;
484 		cros_ec_motion_send_host_cmd(st, 0);
485 		mutex_unlock(&st->cmd_lock);
486 	}
487 }
488 
489 const struct dev_pm_ops cros_ec_sensors_pm_ops = {
490 #ifdef CONFIG_PM_SLEEP
491 	.prepare = cros_ec_sensors_prepare,
492 	.complete = cros_ec_sensors_complete
493 #endif
494 };
495 EXPORT_SYMBOL_GPL(cros_ec_sensors_pm_ops);
496 
497 MODULE_DESCRIPTION("ChromeOS EC sensor hub core functions");
498 MODULE_LICENSE("GPL v2");
499