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