Linux-libre 5.3.12-gnu
[librecmc/linux-libre.git] / drivers / iio / common / cros_ec_sensors / cros_ec_sensors_core.c
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_id(struct iio_dev *indio_dev,
129                                   uintptr_t private,
130                                   const struct iio_chan_spec *chan, char *buf)
131 {
132         struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
133
134         return snprintf(buf, PAGE_SIZE, "%d\n", st->param.info.sensor_num);
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 = "id",
154                 .shared = IIO_SHARED_BY_ALL,
155                 .read = cros_ec_sensors_id
156         },
157         {
158                 .name = "location",
159                 .shared = IIO_SHARED_BY_ALL,
160                 .read = cros_ec_sensors_loc
161         },
162         { },
163 };
164 EXPORT_SYMBOL_GPL(cros_ec_sensors_ext_info);
165
166 /**
167  * cros_ec_sensors_idx_to_reg - convert index into offset in shared memory
168  * @st:         pointer to state information for device
169  * @idx:        sensor index (should be element of enum sensor_index)
170  *
171  * Return:      address to read at
172  */
173 static unsigned int cros_ec_sensors_idx_to_reg(
174                                         struct cros_ec_sensors_core_state *st,
175                                         unsigned int idx)
176 {
177         /*
178          * When using LPC interface, only space for 2 Accel and one Gyro.
179          * First halfword of MOTIONSENSE_TYPE_ACCEL is used by angle.
180          */
181         if (st->type == MOTIONSENSE_TYPE_ACCEL)
182                 return EC_MEMMAP_ACC_DATA + sizeof(u16) *
183                         (1 + idx + st->param.info.sensor_num *
184                          CROS_EC_SENSOR_MAX_AXIS);
185
186         return EC_MEMMAP_GYRO_DATA + sizeof(u16) * idx;
187 }
188
189 static int cros_ec_sensors_cmd_read_u8(struct cros_ec_device *ec,
190                                        unsigned int offset, u8 *dest)
191 {
192         return ec->cmd_readmem(ec, offset, 1, dest);
193 }
194
195 static int cros_ec_sensors_cmd_read_u16(struct cros_ec_device *ec,
196                                          unsigned int offset, u16 *dest)
197 {
198         __le16 tmp;
199         int ret = ec->cmd_readmem(ec, offset, 2, &tmp);
200
201         if (ret >= 0)
202                 *dest = le16_to_cpu(tmp);
203
204         return ret;
205 }
206
207 /**
208  * cros_ec_sensors_read_until_not_busy() - read until is not busy
209  *
210  * @st: pointer to state information for device
211  *
212  * Read from EC status byte until it reads not busy.
213  * Return: 8-bit status if ok, -errno on failure.
214  */
215 static int cros_ec_sensors_read_until_not_busy(
216                                         struct cros_ec_sensors_core_state *st)
217 {
218         struct cros_ec_device *ec = st->ec;
219         u8 status;
220         int ret, attempts = 0;
221
222         ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS, &status);
223         if (ret < 0)
224                 return ret;
225
226         while (status & EC_MEMMAP_ACC_STATUS_BUSY_BIT) {
227                 /* Give up after enough attempts, return error. */
228                 if (attempts++ >= 50)
229                         return -EIO;
230
231                 /* Small delay every so often. */
232                 if (attempts % 5 == 0)
233                         msleep(25);
234
235                 ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS,
236                                                   &status);
237                 if (ret < 0)
238                         return ret;
239         }
240
241         return status;
242 }
243
244 /**
245  * read_ec_sensors_data_unsafe() - read acceleration data from EC shared memory
246  * @indio_dev:  pointer to IIO device
247  * @scan_mask:  bitmap of the sensor indices to scan
248  * @data:       location to store data
249  *
250  * This is the unsafe function for reading the EC data. It does not guarantee
251  * that the EC will not modify the data as it is being read in.
252  *
253  * Return: 0 on success, -errno on failure.
254  */
255 static int cros_ec_sensors_read_data_unsafe(struct iio_dev *indio_dev,
256                          unsigned long scan_mask, s16 *data)
257 {
258         struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
259         struct cros_ec_device *ec = st->ec;
260         unsigned int i;
261         int ret;
262
263         /* Read all sensors enabled in scan_mask. Each value is 2 bytes. */
264         for_each_set_bit(i, &scan_mask, indio_dev->masklength) {
265                 ret = cros_ec_sensors_cmd_read_u16(ec,
266                                              cros_ec_sensors_idx_to_reg(st, i),
267                                              data);
268                 if (ret < 0)
269                         return ret;
270
271                 data++;
272         }
273
274         return 0;
275 }
276
277 /**
278  * cros_ec_sensors_read_lpc() - read acceleration data from EC shared memory.
279  * @indio_dev: pointer to IIO device.
280  * @scan_mask: bitmap of the sensor indices to scan.
281  * @data: location to store data.
282  *
283  * Note: this is the safe function for reading the EC data. It guarantees
284  * that the data sampled was not modified by the EC while being read.
285  *
286  * Return: 0 on success, -errno on failure.
287  */
288 int cros_ec_sensors_read_lpc(struct iio_dev *indio_dev,
289                              unsigned long scan_mask, s16 *data)
290 {
291         struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
292         struct cros_ec_device *ec = st->ec;
293         u8 samp_id = 0xff, status = 0;
294         int ret, attempts = 0;
295
296         /*
297          * Continually read all data from EC until the status byte after
298          * all reads reflects that the EC is not busy and the sample id
299          * matches the sample id from before all reads. This guarantees
300          * that data read in was not modified by the EC while reading.
301          */
302         while ((status & (EC_MEMMAP_ACC_STATUS_BUSY_BIT |
303                           EC_MEMMAP_ACC_STATUS_SAMPLE_ID_MASK)) != samp_id) {
304                 /* If we have tried to read too many times, return error. */
305                 if (attempts++ >= 5)
306                         return -EIO;
307
308                 /* Read status byte until EC is not busy. */
309                 ret = cros_ec_sensors_read_until_not_busy(st);
310                 if (ret < 0)
311                         return ret;
312
313                 /*
314                  * Store the current sample id so that we can compare to the
315                  * sample id after reading the data.
316                  */
317                 samp_id = ret & EC_MEMMAP_ACC_STATUS_SAMPLE_ID_MASK;
318
319                 /* Read all EC data, format it, and store it into data. */
320                 ret = cros_ec_sensors_read_data_unsafe(indio_dev, scan_mask,
321                                                        data);
322                 if (ret < 0)
323                         return ret;
324
325                 /* Read status byte. */
326                 ret = cros_ec_sensors_cmd_read_u8(ec, EC_MEMMAP_ACC_STATUS,
327                                                   &status);
328                 if (ret < 0)
329                         return ret;
330         }
331
332         return 0;
333 }
334 EXPORT_SYMBOL_GPL(cros_ec_sensors_read_lpc);
335
336 int cros_ec_sensors_read_cmd(struct iio_dev *indio_dev,
337                              unsigned long scan_mask, s16 *data)
338 {
339         struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
340         int ret;
341         unsigned int i;
342
343         /* Read all sensor data through a command. */
344         st->param.cmd = MOTIONSENSE_CMD_DATA;
345         ret = cros_ec_motion_send_host_cmd(st, sizeof(st->resp->data));
346         if (ret != 0) {
347                 dev_warn(&indio_dev->dev, "Unable to read sensor data\n");
348                 return ret;
349         }
350
351         for_each_set_bit(i, &scan_mask, indio_dev->masklength) {
352                 *data = st->resp->data.data[i];
353                 data++;
354         }
355
356         return 0;
357 }
358 EXPORT_SYMBOL_GPL(cros_ec_sensors_read_cmd);
359
360 irqreturn_t cros_ec_sensors_capture(int irq, void *p)
361 {
362         struct iio_poll_func *pf = p;
363         struct iio_dev *indio_dev = pf->indio_dev;
364         struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
365         int ret;
366
367         mutex_lock(&st->cmd_lock);
368
369         /* Clear capture data. */
370         memset(st->samples, 0, indio_dev->scan_bytes);
371
372         /* Read data based on which channels are enabled in scan mask. */
373         ret = st->read_ec_sensors_data(indio_dev,
374                                        *(indio_dev->active_scan_mask),
375                                        (s16 *)st->samples);
376         if (ret < 0)
377                 goto done;
378
379         iio_push_to_buffers_with_timestamp(indio_dev, st->samples,
380                                            iio_get_time_ns(indio_dev));
381
382 done:
383         /*
384          * Tell the core we are done with this trigger and ready for the
385          * next one.
386          */
387         iio_trigger_notify_done(indio_dev->trig);
388
389         mutex_unlock(&st->cmd_lock);
390
391         return IRQ_HANDLED;
392 }
393 EXPORT_SYMBOL_GPL(cros_ec_sensors_capture);
394
395 int cros_ec_sensors_core_read(struct cros_ec_sensors_core_state *st,
396                           struct iio_chan_spec const *chan,
397                           int *val, int *val2, long mask)
398 {
399         int ret = IIO_VAL_INT;
400
401         switch (mask) {
402         case IIO_CHAN_INFO_SAMP_FREQ:
403                 st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
404                 st->param.ec_rate.data =
405                         EC_MOTION_SENSE_NO_VALUE;
406
407                 if (cros_ec_motion_send_host_cmd(st, 0))
408                         ret = -EIO;
409                 else
410                         *val = st->resp->ec_rate.ret;
411                 break;
412         case IIO_CHAN_INFO_FREQUENCY:
413                 st->param.cmd = MOTIONSENSE_CMD_SENSOR_ODR;
414                 st->param.sensor_odr.data =
415                         EC_MOTION_SENSE_NO_VALUE;
416
417                 if (cros_ec_motion_send_host_cmd(st, 0))
418                         ret = -EIO;
419                 else
420                         *val = st->resp->sensor_odr.ret;
421                 break;
422         default:
423                 break;
424         }
425
426         return ret;
427 }
428 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_read);
429
430 int cros_ec_sensors_core_write(struct cros_ec_sensors_core_state *st,
431                                struct iio_chan_spec const *chan,
432                                int val, int val2, long mask)
433 {
434         int ret = 0;
435
436         switch (mask) {
437         case IIO_CHAN_INFO_FREQUENCY:
438                 st->param.cmd = MOTIONSENSE_CMD_SENSOR_ODR;
439                 st->param.sensor_odr.data = val;
440
441                 /* Always roundup, so caller gets at least what it asks for. */
442                 st->param.sensor_odr.roundup = 1;
443
444                 if (cros_ec_motion_send_host_cmd(st, 0))
445                         ret = -EIO;
446                 break;
447         case IIO_CHAN_INFO_SAMP_FREQ:
448                 st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
449                 st->param.ec_rate.data = val;
450
451                 if (cros_ec_motion_send_host_cmd(st, 0))
452                         ret = -EIO;
453                 else
454                         st->curr_sampl_freq = val;
455                 break;
456         default:
457                 ret = -EINVAL;
458                 break;
459         }
460         return ret;
461 }
462 EXPORT_SYMBOL_GPL(cros_ec_sensors_core_write);
463
464 static int __maybe_unused cros_ec_sensors_prepare(struct device *dev)
465 {
466         struct iio_dev *indio_dev = dev_get_drvdata(dev);
467         struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
468
469         if (st->curr_sampl_freq == 0)
470                 return 0;
471
472         /*
473          * If the sensors are sampled at high frequency, we will not be able to
474          * sleep. Set sampling to a long period if necessary.
475          */
476         if (st->curr_sampl_freq < CROS_EC_MIN_SUSPEND_SAMPLING_FREQUENCY) {
477                 mutex_lock(&st->cmd_lock);
478                 st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
479                 st->param.ec_rate.data = CROS_EC_MIN_SUSPEND_SAMPLING_FREQUENCY;
480                 cros_ec_motion_send_host_cmd(st, 0);
481                 mutex_unlock(&st->cmd_lock);
482         }
483         return 0;
484 }
485
486 static void __maybe_unused cros_ec_sensors_complete(struct device *dev)
487 {
488         struct iio_dev *indio_dev = dev_get_drvdata(dev);
489         struct cros_ec_sensors_core_state *st = iio_priv(indio_dev);
490
491         if (st->curr_sampl_freq == 0)
492                 return;
493
494         if (st->curr_sampl_freq < CROS_EC_MIN_SUSPEND_SAMPLING_FREQUENCY) {
495                 mutex_lock(&st->cmd_lock);
496                 st->param.cmd = MOTIONSENSE_CMD_EC_RATE;
497                 st->param.ec_rate.data = st->curr_sampl_freq;
498                 cros_ec_motion_send_host_cmd(st, 0);
499                 mutex_unlock(&st->cmd_lock);
500         }
501 }
502
503 const struct dev_pm_ops cros_ec_sensors_pm_ops = {
504 #ifdef CONFIG_PM_SLEEP
505         .prepare = cros_ec_sensors_prepare,
506         .complete = cros_ec_sensors_complete
507 #endif
508 };
509 EXPORT_SYMBOL_GPL(cros_ec_sensors_pm_ops);
510
511 MODULE_DESCRIPTION("ChromeOS EC sensor hub core functions");
512 MODULE_LICENSE("GPL v2");