GNU Linux-libre 4.14.266-gnu1
[releases.git] / drivers / iio / pressure / zpa2326.c
1 /*
2  * Murata ZPA2326 pressure and temperature sensor IIO driver
3  *
4  * Copyright (c) 2016 Parrot S.A.
5  *
6  * Author: Gregor Boirie <gregor.boirie@parrot.com>
7  *
8  * This program is free software; you can redistribute it and/or modify it
9  * under the terms of the GNU General Public License version 2 as published by
10  * the Free Software Foundation.
11  *
12  * This program is distributed in the hope that it will be useful, but WITHOUT
13  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
15  * more details.
16  */
17
18 /**
19  * DOC: ZPA2326 theory of operations
20  *
21  * This driver supports %INDIO_DIRECT_MODE and %INDIO_BUFFER_TRIGGERED IIO
22  * modes.
23  * A internal hardware trigger is also implemented to dispatch registered IIO
24  * trigger consumers upon "sample ready" interrupts.
25  *
26  * ZPA2326 hardware supports 2 sampling mode: one shot and continuous.
27  *
28  * A complete one shot sampling cycle gets device out of low power mode,
29  * performs pressure and temperature measurements, then automatically switches
30  * back to low power mode. It is meant for on demand sampling with optimal power
31  * saving at the cost of lower sampling rate and higher software overhead.
32  * This is a natural candidate for IIO read_raw hook implementation
33  * (%INDIO_DIRECT_MODE). It is also used for triggered buffering support to
34  * ensure explicit synchronization with external trigger events
35  * (%INDIO_BUFFER_TRIGGERED).
36  *
37  * The continuous mode works according to a periodic hardware measurement
38  * process continuously pushing samples into an internal hardware FIFO (for
39  * pressure samples only). Measurement cycle completion may be signaled by a
40  * "sample ready" interrupt.
41  * Typical software sequence of operations :
42  * - get device out of low power mode,
43  * - setup hardware sampling period,
44  * - at end of period, upon data ready interrupt: pop pressure samples out of
45  *   hardware FIFO and fetch temperature sample
46  * - when no longer needed, stop sampling process by putting device into
47  *   low power mode.
48  * This mode is used to implement %INDIO_BUFFER_TRIGGERED mode if device tree
49  * declares a valid interrupt line. In this case, the internal hardware trigger
50  * drives acquisition.
51  *
52  * Note that hardware sampling frequency is taken into account only when
53  * internal hardware trigger is attached as the highest sampling rate seems to
54  * be the most energy efficient.
55  *
56  * TODO:
57  *   preset pressure threshold crossing / IIO events ;
58  *   differential pressure sampling ;
59  *   hardware samples averaging.
60  */
61
62 #include <linux/module.h>
63 #include <linux/kernel.h>
64 #include <linux/delay.h>
65 #include <linux/interrupt.h>
66 #include <linux/regulator/consumer.h>
67 #include <linux/pm_runtime.h>
68 #include <linux/regmap.h>
69 #include <linux/iio/iio.h>
70 #include <linux/iio/sysfs.h>
71 #include <linux/iio/buffer.h>
72 #include <linux/iio/trigger.h>
73 #include <linux/iio/trigger_consumer.h>
74 #include <linux/iio/triggered_buffer.h>
75 #include "zpa2326.h"
76
77 /* 200 ms should be enough for the longest conversion time in one-shot mode. */
78 #define ZPA2326_CONVERSION_JIFFIES (HZ / 5)
79
80 /* There should be a 1 ms delay (Tpup) after getting out of reset. */
81 #define ZPA2326_TPUP_USEC_MIN      (1000)
82 #define ZPA2326_TPUP_USEC_MAX      (2000)
83
84 /**
85  * struct zpa2326_frequency - Hardware sampling frequency descriptor
86  * @hz : Frequency in Hertz.
87  * @odr: Output Data Rate word as expected by %ZPA2326_CTRL_REG3_REG.
88  */
89 struct zpa2326_frequency {
90         int hz;
91         u16 odr;
92 };
93
94 /*
95  * Keep these in strict ascending order: last array entry is expected to
96  * correspond to the highest sampling frequency.
97  */
98 static const struct zpa2326_frequency zpa2326_sampling_frequencies[] = {
99         { .hz = 1,  .odr = 1 << ZPA2326_CTRL_REG3_ODR_SHIFT },
100         { .hz = 5,  .odr = 5 << ZPA2326_CTRL_REG3_ODR_SHIFT },
101         { .hz = 11, .odr = 6 << ZPA2326_CTRL_REG3_ODR_SHIFT },
102         { .hz = 23, .odr = 7 << ZPA2326_CTRL_REG3_ODR_SHIFT },
103 };
104
105 /* Return the highest hardware sampling frequency available. */
106 static const struct zpa2326_frequency *zpa2326_highest_frequency(void)
107 {
108         return &zpa2326_sampling_frequencies[
109                 ARRAY_SIZE(zpa2326_sampling_frequencies) - 1];
110 }
111
112 /**
113  * struct zpa_private - Per-device internal private state
114  * @timestamp:  Buffered samples ready datum.
115  * @regmap:     Underlying I2C / SPI bus adapter used to abstract slave register
116  *              accesses.
117  * @result:     Allows sampling logic to get completion status of operations
118  *              that interrupt handlers perform asynchronously.
119  * @data_ready: Interrupt handler uses this to wake user context up at sampling
120  *              operation completion.
121  * @trigger:    Optional hardware / interrupt driven trigger used to notify
122  *              external devices a new sample is ready.
123  * @waken:      Flag indicating whether or not device has just been powered on.
124  * @irq:        Optional interrupt line: negative or zero if not declared into
125  *              DT, in which case sampling logic keeps polling status register
126  *              to detect completion.
127  * @frequency:  Current hardware sampling frequency.
128  * @vref:       Power / voltage reference.
129  * @vdd:        Power supply.
130  */
131 struct zpa2326_private {
132         s64                             timestamp;
133         struct regmap                  *regmap;
134         int                             result;
135         struct completion               data_ready;
136         struct iio_trigger             *trigger;
137         bool                            waken;
138         int                             irq;
139         const struct zpa2326_frequency *frequency;
140         struct regulator               *vref;
141         struct regulator               *vdd;
142 };
143
144 #define zpa2326_err(idev, fmt, ...)                                     \
145         dev_err(idev->dev.parent, fmt "\n", ##__VA_ARGS__)
146
147 #define zpa2326_warn(idev, fmt, ...)                                    \
148         dev_warn(idev->dev.parent, fmt "\n", ##__VA_ARGS__)
149
150 #define zpa2326_dbg(idev, fmt, ...)                                     \
151         dev_dbg(idev->dev.parent, fmt "\n", ##__VA_ARGS__)
152
153 bool zpa2326_isreg_writeable(struct device *dev, unsigned int reg)
154 {
155         switch (reg) {
156         case ZPA2326_REF_P_XL_REG:
157         case ZPA2326_REF_P_L_REG:
158         case ZPA2326_REF_P_H_REG:
159         case ZPA2326_RES_CONF_REG:
160         case ZPA2326_CTRL_REG0_REG:
161         case ZPA2326_CTRL_REG1_REG:
162         case ZPA2326_CTRL_REG2_REG:
163         case ZPA2326_CTRL_REG3_REG:
164         case ZPA2326_THS_P_LOW_REG:
165         case ZPA2326_THS_P_HIGH_REG:
166                 return true;
167
168         default:
169                 return false;
170         }
171 }
172 EXPORT_SYMBOL_GPL(zpa2326_isreg_writeable);
173
174 bool zpa2326_isreg_readable(struct device *dev, unsigned int reg)
175 {
176         switch (reg) {
177         case ZPA2326_REF_P_XL_REG:
178         case ZPA2326_REF_P_L_REG:
179         case ZPA2326_REF_P_H_REG:
180         case ZPA2326_DEVICE_ID_REG:
181         case ZPA2326_RES_CONF_REG:
182         case ZPA2326_CTRL_REG0_REG:
183         case ZPA2326_CTRL_REG1_REG:
184         case ZPA2326_CTRL_REG2_REG:
185         case ZPA2326_CTRL_REG3_REG:
186         case ZPA2326_INT_SOURCE_REG:
187         case ZPA2326_THS_P_LOW_REG:
188         case ZPA2326_THS_P_HIGH_REG:
189         case ZPA2326_STATUS_REG:
190         case ZPA2326_PRESS_OUT_XL_REG:
191         case ZPA2326_PRESS_OUT_L_REG:
192         case ZPA2326_PRESS_OUT_H_REG:
193         case ZPA2326_TEMP_OUT_L_REG:
194         case ZPA2326_TEMP_OUT_H_REG:
195                 return true;
196
197         default:
198                 return false;
199         }
200 }
201 EXPORT_SYMBOL_GPL(zpa2326_isreg_readable);
202
203 bool zpa2326_isreg_precious(struct device *dev, unsigned int reg)
204 {
205         switch (reg) {
206         case ZPA2326_INT_SOURCE_REG:
207         case ZPA2326_PRESS_OUT_H_REG:
208                 return true;
209
210         default:
211                 return false;
212         }
213 }
214 EXPORT_SYMBOL_GPL(zpa2326_isreg_precious);
215
216 /**
217  * zpa2326_enable_device() - Enable device, i.e. get out of low power mode.
218  * @indio_dev: The IIO device associated with the hardware to enable.
219  *
220  * Required to access complete register space and to perform any sampling
221  * or control operations.
222  *
223  * Return: Zero when successful, a negative error code otherwise.
224  */
225 static int zpa2326_enable_device(const struct iio_dev *indio_dev)
226 {
227         int err;
228
229         err = regmap_write(((struct zpa2326_private *)
230                             iio_priv(indio_dev))->regmap,
231                             ZPA2326_CTRL_REG0_REG, ZPA2326_CTRL_REG0_ENABLE);
232         if (err) {
233                 zpa2326_err(indio_dev, "failed to enable device (%d)", err);
234                 return err;
235         }
236
237         zpa2326_dbg(indio_dev, "enabled");
238
239         return 0;
240 }
241
242 /**
243  * zpa2326_sleep() - Disable device, i.e. switch to low power mode.
244  * @indio_dev: The IIO device associated with the hardware to disable.
245  *
246  * Only %ZPA2326_DEVICE_ID_REG and %ZPA2326_CTRL_REG0_REG registers may be
247  * accessed once device is in the disabled state.
248  *
249  * Return: Zero when successful, a negative error code otherwise.
250  */
251 static int zpa2326_sleep(const struct iio_dev *indio_dev)
252 {
253         int err;
254
255         err = regmap_write(((struct zpa2326_private *)
256                             iio_priv(indio_dev))->regmap,
257                             ZPA2326_CTRL_REG0_REG, 0);
258         if (err) {
259                 zpa2326_err(indio_dev, "failed to sleep (%d)", err);
260                 return err;
261         }
262
263         zpa2326_dbg(indio_dev, "sleeping");
264
265         return 0;
266 }
267
268 /**
269  * zpa2326_reset_device() - Reset device to default hardware state.
270  * @indio_dev: The IIO device associated with the hardware to reset.
271  *
272  * Disable sampling and empty hardware FIFO.
273  * Device must be enabled before reset, i.e. not in low power mode.
274  *
275  * Return: Zero when successful, a negative error code otherwise.
276  */
277 static int zpa2326_reset_device(const struct iio_dev *indio_dev)
278 {
279         int err;
280
281         err = regmap_write(((struct zpa2326_private *)
282                             iio_priv(indio_dev))->regmap,
283                             ZPA2326_CTRL_REG2_REG, ZPA2326_CTRL_REG2_SWRESET);
284         if (err) {
285                 zpa2326_err(indio_dev, "failed to reset device (%d)", err);
286                 return err;
287         }
288
289         usleep_range(ZPA2326_TPUP_USEC_MIN, ZPA2326_TPUP_USEC_MAX);
290
291         zpa2326_dbg(indio_dev, "reset");
292
293         return 0;
294 }
295
296 /**
297  * zpa2326_start_oneshot() - Start a single sampling cycle, i.e. in one shot
298  *                           mode.
299  * @indio_dev: The IIO device associated with the sampling hardware.
300  *
301  * Device must have been previously enabled and configured for one shot mode.
302  * Device will be switched back to low power mode at end of cycle.
303  *
304  * Return: Zero when successful, a negative error code otherwise.
305  */
306 static int zpa2326_start_oneshot(const struct iio_dev *indio_dev)
307 {
308         int err;
309
310         err = regmap_write(((struct zpa2326_private *)
311                             iio_priv(indio_dev))->regmap,
312                             ZPA2326_CTRL_REG0_REG,
313                             ZPA2326_CTRL_REG0_ENABLE |
314                             ZPA2326_CTRL_REG0_ONE_SHOT);
315         if (err) {
316                 zpa2326_err(indio_dev, "failed to start one shot cycle (%d)",
317                             err);
318                 return err;
319         }
320
321         zpa2326_dbg(indio_dev, "one shot cycle started");
322
323         return 0;
324 }
325
326 /**
327  * zpa2326_power_on() - Power on device to allow subsequent configuration.
328  * @indio_dev: The IIO device associated with the sampling hardware.
329  * @private:   Internal private state related to @indio_dev.
330  *
331  * Sampling will be disabled, preventing strange things from happening in our
332  * back. Hardware FIFO content will be cleared.
333  * When successful, device will be left in the enabled state to allow further
334  * configuration.
335  *
336  * Return: Zero when successful, a negative error code otherwise.
337  */
338 static int zpa2326_power_on(const struct iio_dev         *indio_dev,
339                             const struct zpa2326_private *private)
340 {
341         int err;
342
343         err = regulator_enable(private->vref);
344         if (err)
345                 return err;
346
347         err = regulator_enable(private->vdd);
348         if (err)
349                 goto vref;
350
351         zpa2326_dbg(indio_dev, "powered on");
352
353         err = zpa2326_enable_device(indio_dev);
354         if (err)
355                 goto vdd;
356
357         err = zpa2326_reset_device(indio_dev);
358         if (err)
359                 goto sleep;
360
361         return 0;
362
363 sleep:
364         zpa2326_sleep(indio_dev);
365 vdd:
366         regulator_disable(private->vdd);
367 vref:
368         regulator_disable(private->vref);
369
370         zpa2326_dbg(indio_dev, "powered off");
371
372         return err;
373 }
374
375 /**
376  * zpa2326_power_off() - Power off device, i.e. disable attached power
377  *                       regulators.
378  * @indio_dev: The IIO device associated with the sampling hardware.
379  * @private:   Internal private state related to @indio_dev.
380  *
381  * Return: Zero when successful, a negative error code otherwise.
382  */
383 static void zpa2326_power_off(const struct iio_dev         *indio_dev,
384                               const struct zpa2326_private *private)
385 {
386         regulator_disable(private->vdd);
387         regulator_disable(private->vref);
388
389         zpa2326_dbg(indio_dev, "powered off");
390 }
391
392 /**
393  * zpa2326_config_oneshot() - Setup device for one shot / on demand mode.
394  * @indio_dev: The IIO device associated with the sampling hardware.
395  * @irq:       Optional interrupt line the hardware uses to notify new data
396  *             samples are ready. Negative or zero values indicate no interrupts
397  *             are available, meaning polling is required.
398  *
399  * Output Data Rate is configured for the highest possible rate so that
400  * conversion time and power consumption are reduced to a minimum.
401  * Note that hardware internal averaging machinery (not implemented in this
402  * driver) is not applicable in this mode.
403  *
404  * Device must have been previously enabled before calling
405  * zpa2326_config_oneshot().
406  *
407  * Return: Zero when successful, a negative error code otherwise.
408  */
409 static int zpa2326_config_oneshot(const struct iio_dev *indio_dev,
410                                   int                   irq)
411 {
412         struct regmap                  *regs = ((struct zpa2326_private *)
413                                                 iio_priv(indio_dev))->regmap;
414         const struct zpa2326_frequency *freq = zpa2326_highest_frequency();
415         int                             err;
416
417         /* Setup highest available Output Data Rate for one shot mode. */
418         err = regmap_write(regs, ZPA2326_CTRL_REG3_REG, freq->odr);
419         if (err)
420                 return err;
421
422         if (irq > 0) {
423                 /* Request interrupt when new sample is available. */
424                 err = regmap_write(regs, ZPA2326_CTRL_REG1_REG,
425                                    (u8)~ZPA2326_CTRL_REG1_MASK_DATA_READY);
426
427                 if (err) {
428                         dev_err(indio_dev->dev.parent,
429                                 "failed to setup one shot mode (%d)", err);
430                         return err;
431                 }
432         }
433
434         zpa2326_dbg(indio_dev, "one shot mode setup @%dHz", freq->hz);
435
436         return 0;
437 }
438
439 /**
440  * zpa2326_clear_fifo() - Clear remaining entries in hardware FIFO.
441  * @indio_dev: The IIO device associated with the sampling hardware.
442  * @min_count: Number of samples present within hardware FIFO.
443  *
444  * @min_count argument is a hint corresponding to the known minimum number of
445  * samples currently living in the FIFO. This allows to reduce the number of bus
446  * accesses by skipping status register read operation as long as we know for
447  * sure there are still entries left.
448  *
449  * Return: Zero when successful, a negative error code otherwise.
450  */
451 static int zpa2326_clear_fifo(const struct iio_dev *indio_dev,
452                               unsigned int          min_count)
453 {
454         struct regmap *regs = ((struct zpa2326_private *)
455                                iio_priv(indio_dev))->regmap;
456         int            err;
457         unsigned int   val;
458
459         if (!min_count) {
460                 /*
461                  * No hint: read status register to determine whether FIFO is
462                  * empty or not.
463                  */
464                 err = regmap_read(regs, ZPA2326_STATUS_REG, &val);
465
466                 if (err < 0)
467                         goto err;
468
469                 if (val & ZPA2326_STATUS_FIFO_E)
470                         /* Fifo is empty: nothing to trash. */
471                         return 0;
472         }
473
474         /* Clear FIFO. */
475         do {
476                 /*
477                  * A single fetch from pressure MSB register is enough to pop
478                  * values out of FIFO.
479                  */
480                 err = regmap_read(regs, ZPA2326_PRESS_OUT_H_REG, &val);
481                 if (err < 0)
482                         goto err;
483
484                 if (min_count) {
485                         /*
486                          * We know for sure there are at least min_count entries
487                          * left in FIFO. Skip status register read.
488                          */
489                         min_count--;
490                         continue;
491                 }
492
493                 err = regmap_read(regs, ZPA2326_STATUS_REG, &val);
494                 if (err < 0)
495                         goto err;
496
497         } while (!(val & ZPA2326_STATUS_FIFO_E));
498
499         zpa2326_dbg(indio_dev, "FIFO cleared");
500
501         return 0;
502
503 err:
504         zpa2326_err(indio_dev, "failed to clear FIFO (%d)", err);
505
506         return err;
507 }
508
509 /**
510  * zpa2326_dequeue_pressure() - Retrieve the most recent pressure sample from
511  *                              hardware FIFO.
512  * @indio_dev: The IIO device associated with the sampling hardware.
513  * @pressure:  Sampled pressure output.
514  *
515  * Note that ZPA2326 hardware FIFO stores pressure samples only.
516  *
517  * Return: Zero when successful, a negative error code otherwise.
518  */
519 static int zpa2326_dequeue_pressure(const struct iio_dev *indio_dev,
520                                     u32                  *pressure)
521 {
522         struct regmap *regs = ((struct zpa2326_private *)
523                                iio_priv(indio_dev))->regmap;
524         unsigned int   val;
525         int            err;
526         int            cleared = -1;
527
528         err = regmap_read(regs, ZPA2326_STATUS_REG, &val);
529         if (err < 0)
530                 return err;
531
532         *pressure = 0;
533
534         if (val & ZPA2326_STATUS_P_OR) {
535                 /*
536                  * Fifo overrun : first sample dequeued from FIFO is the
537                  * newest.
538                  */
539                 zpa2326_warn(indio_dev, "FIFO overflow");
540
541                 err = regmap_bulk_read(regs, ZPA2326_PRESS_OUT_XL_REG, pressure,
542                                        3);
543                 if (err)
544                         return err;
545
546 #define ZPA2326_FIFO_DEPTH (16U)
547                 /* Hardware FIFO may hold no more than 16 pressure samples. */
548                 return zpa2326_clear_fifo(indio_dev, ZPA2326_FIFO_DEPTH - 1);
549         }
550
551         /*
552          * Fifo has not overflown : retrieve newest sample. We need to pop
553          * values out until FIFO is empty : last fetched pressure is the newest.
554          * In nominal cases, we should find a single queued sample only.
555          */
556         do {
557                 err = regmap_bulk_read(regs, ZPA2326_PRESS_OUT_XL_REG, pressure,
558                                        3);
559                 if (err)
560                         return err;
561
562                 err = regmap_read(regs, ZPA2326_STATUS_REG, &val);
563                 if (err < 0)
564                         return err;
565
566                 cleared++;
567         } while (!(val & ZPA2326_STATUS_FIFO_E));
568
569         if (cleared)
570                 /*
571                  * Samples were pushed by hardware during previous rounds but we
572                  * didn't consume them fast enough: inform user.
573                  */
574                 zpa2326_dbg(indio_dev, "cleared %d FIFO entries", cleared);
575
576         return 0;
577 }
578
579 /**
580  * zpa2326_fill_sample_buffer() - Enqueue new channel samples to IIO buffer.
581  * @indio_dev: The IIO device associated with the sampling hardware.
582  * @private:   Internal private state related to @indio_dev.
583  *
584  * Return: Zero when successful, a negative error code otherwise.
585  */
586 static int zpa2326_fill_sample_buffer(struct iio_dev               *indio_dev,
587                                       const struct zpa2326_private *private)
588 {
589         struct {
590                 u32 pressure;
591                 u16 temperature;
592                 u64 timestamp;
593         }   sample;
594         int err;
595
596         if (test_bit(0, indio_dev->active_scan_mask)) {
597                 /* Get current pressure from hardware FIFO. */
598                 err = zpa2326_dequeue_pressure(indio_dev, &sample.pressure);
599                 if (err) {
600                         zpa2326_warn(indio_dev, "failed to fetch pressure (%d)",
601                                      err);
602                         return err;
603                 }
604         }
605
606         if (test_bit(1, indio_dev->active_scan_mask)) {
607                 /* Get current temperature. */
608                 err = regmap_bulk_read(private->regmap, ZPA2326_TEMP_OUT_L_REG,
609                                        &sample.temperature, 2);
610                 if (err) {
611                         zpa2326_warn(indio_dev,
612                                      "failed to fetch temperature (%d)", err);
613                         return err;
614                 }
615         }
616
617         /*
618          * Now push samples using timestamp stored either :
619          *   - by hardware interrupt handler if interrupt is available: see
620          *     zpa2326_handle_irq(),
621          *   - or oneshot completion polling machinery : see
622          *     zpa2326_trigger_handler().
623          */
624         zpa2326_dbg(indio_dev, "filling raw samples buffer");
625
626         iio_push_to_buffers_with_timestamp(indio_dev, &sample,
627                                            private->timestamp);
628
629         return 0;
630 }
631
632 #ifdef CONFIG_PM
633 static int zpa2326_runtime_suspend(struct device *parent)
634 {
635         const struct iio_dev *indio_dev = dev_get_drvdata(parent);
636
637         if (pm_runtime_autosuspend_expiration(parent))
638                 /* Userspace changed autosuspend delay. */
639                 return -EAGAIN;
640
641         zpa2326_power_off(indio_dev, iio_priv(indio_dev));
642
643         return 0;
644 }
645
646 static int zpa2326_runtime_resume(struct device *parent)
647 {
648         const struct iio_dev *indio_dev = dev_get_drvdata(parent);
649
650         return zpa2326_power_on(indio_dev, iio_priv(indio_dev));
651 }
652
653 const struct dev_pm_ops zpa2326_pm_ops = {
654         SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
655                                 pm_runtime_force_resume)
656         SET_RUNTIME_PM_OPS(zpa2326_runtime_suspend, zpa2326_runtime_resume,
657                            NULL)
658 };
659 EXPORT_SYMBOL_GPL(zpa2326_pm_ops);
660
661 /**
662  * zpa2326_resume() - Request the PM layer to power supply the device.
663  * @indio_dev: The IIO device associated with the sampling hardware.
664  *
665  * Return:
666  *  < 0 - a negative error code meaning failure ;
667  *    0 - success, device has just been powered up ;
668  *    1 - success, device was already powered.
669  */
670 static int zpa2326_resume(const struct iio_dev *indio_dev)
671 {
672         int err;
673
674         err = pm_runtime_get_sync(indio_dev->dev.parent);
675         if (err < 0) {
676                 pm_runtime_put(indio_dev->dev.parent);
677                 return err;
678         }
679
680         if (err > 0) {
681                 /*
682                  * Device was already power supplied: get it out of low power
683                  * mode and inform caller.
684                  */
685                 zpa2326_enable_device(indio_dev);
686                 return 1;
687         }
688
689         /* Inform caller device has just been brought back to life. */
690         return 0;
691 }
692
693 /**
694  * zpa2326_suspend() - Schedule a power down using autosuspend feature of PM
695  *                     layer.
696  * @indio_dev: The IIO device associated with the sampling hardware.
697  *
698  * Device is switched to low power mode at first to save power even when
699  * attached regulator is a "dummy" one.
700  */
701 static void zpa2326_suspend(struct iio_dev *indio_dev)
702 {
703         struct device *parent = indio_dev->dev.parent;
704
705         zpa2326_sleep(indio_dev);
706
707         pm_runtime_mark_last_busy(parent);
708         pm_runtime_put_autosuspend(parent);
709 }
710
711 static void zpa2326_init_runtime(struct device *parent)
712 {
713         pm_runtime_get_noresume(parent);
714         pm_runtime_set_active(parent);
715         pm_runtime_enable(parent);
716         pm_runtime_set_autosuspend_delay(parent, 1000);
717         pm_runtime_use_autosuspend(parent);
718         pm_runtime_mark_last_busy(parent);
719         pm_runtime_put_autosuspend(parent);
720 }
721
722 static void zpa2326_fini_runtime(struct device *parent)
723 {
724         pm_runtime_disable(parent);
725         pm_runtime_set_suspended(parent);
726 }
727 #else /* !CONFIG_PM */
728 static int zpa2326_resume(const struct iio_dev *indio_dev)
729 {
730         zpa2326_enable_device(indio_dev);
731
732         return 0;
733 }
734
735 static void zpa2326_suspend(struct iio_dev *indio_dev)
736 {
737         zpa2326_sleep(indio_dev);
738 }
739
740 #define zpa2326_init_runtime(_parent)
741 #define zpa2326_fini_runtime(_parent)
742 #endif /* !CONFIG_PM */
743
744 /**
745  * zpa2326_handle_irq() - Process hardware interrupts.
746  * @irq:  Interrupt line the hardware uses to notify new data has arrived.
747  * @data: The IIO device associated with the sampling hardware.
748  *
749  * Timestamp buffered samples as soon as possible then schedule threaded bottom
750  * half.
751  *
752  * Return: Always successful.
753  */
754 static irqreturn_t zpa2326_handle_irq(int irq, void *data)
755 {
756         struct iio_dev *indio_dev = data;
757
758         if (iio_buffer_enabled(indio_dev)) {
759                 /* Timestamping needed for buffered sampling only. */
760                 ((struct zpa2326_private *)
761                  iio_priv(indio_dev))->timestamp = iio_get_time_ns(indio_dev);
762         }
763
764         return IRQ_WAKE_THREAD;
765 }
766
767 /**
768  * zpa2326_handle_threaded_irq() - Interrupt bottom-half handler.
769  * @irq:  Interrupt line the hardware uses to notify new data has arrived.
770  * @data: The IIO device associated with the sampling hardware.
771  *
772  * Mainly ensures interrupt is caused by a real "new sample available"
773  * condition. This relies upon the ability to perform blocking / sleeping bus
774  * accesses to slave's registers. This is why zpa2326_handle_threaded_irq() is
775  * called from within a thread, i.e. not called from hard interrupt context.
776  *
777  * When device is using its own internal hardware trigger in continuous sampling
778  * mode, data are available into hardware FIFO once interrupt has occurred. All
779  * we have to do is to dispatch the trigger, which in turn will fetch data and
780  * fill IIO buffer.
781  *
782  * When not using its own internal hardware trigger, the device has been
783  * configured in one-shot mode either by an external trigger or the IIO read_raw
784  * hook. This means one of the latter is currently waiting for sampling
785  * completion, in which case we must simply wake it up.
786  *
787  * See zpa2326_trigger_handler().
788  *
789  * Return:
790  *   %IRQ_NONE - no consistent interrupt happened ;
791  *   %IRQ_HANDLED - there was new samples available.
792  */
793 static irqreturn_t zpa2326_handle_threaded_irq(int irq, void *data)
794 {
795         struct iio_dev         *indio_dev = data;
796         struct zpa2326_private *priv = iio_priv(indio_dev);
797         unsigned int            val;
798         bool                    cont;
799         irqreturn_t             ret = IRQ_NONE;
800
801         /*
802          * Are we using our own internal trigger in triggered buffer mode, i.e.,
803          * currently working in continuous sampling mode ?
804          */
805         cont = (iio_buffer_enabled(indio_dev) &&
806                 iio_trigger_using_own(indio_dev));
807
808         /*
809          * Device works according to a level interrupt scheme: reading interrupt
810          * status de-asserts interrupt line.
811          */
812         priv->result = regmap_read(priv->regmap, ZPA2326_INT_SOURCE_REG, &val);
813         if (priv->result < 0) {
814                 if (cont)
815                         return IRQ_NONE;
816
817                 goto complete;
818         }
819
820         /* Data ready is the only interrupt source we requested. */
821         if (!(val & ZPA2326_INT_SOURCE_DATA_READY)) {
822                 /*
823                  * Interrupt happened but no new sample available: likely caused
824                  * by spurious interrupts, in which case, returning IRQ_NONE
825                  * allows to benefit from the generic spurious interrupts
826                  * handling.
827                  */
828                 zpa2326_warn(indio_dev, "unexpected interrupt status %02x",
829                              val);
830
831                 if (cont)
832                         return IRQ_NONE;
833
834                 priv->result = -ENODATA;
835                 goto complete;
836         }
837
838         /* New sample available: dispatch internal trigger consumers. */
839         iio_trigger_poll_chained(priv->trigger);
840
841         if (cont)
842                 /*
843                  * Internal hardware trigger has been scheduled above : it will
844                  * fetch data on its own.
845                  */
846                 return IRQ_HANDLED;
847
848         ret = IRQ_HANDLED;
849
850 complete:
851         /*
852          * Wake up direct or externaly triggered buffer mode waiters: see
853          * zpa2326_sample_oneshot() and zpa2326_trigger_handler().
854          */
855         complete(&priv->data_ready);
856
857         return ret;
858 }
859
860 /**
861  * zpa2326_wait_oneshot_completion() - Wait for oneshot data ready interrupt.
862  * @indio_dev: The IIO device associated with the sampling hardware.
863  * @private:   Internal private state related to @indio_dev.
864  *
865  * Return: Zero when successful, a negative error code otherwise.
866  */
867 static int zpa2326_wait_oneshot_completion(const struct iio_dev   *indio_dev,
868                                            struct zpa2326_private *private)
869 {
870         unsigned int val;
871         long     timeout;
872
873         zpa2326_dbg(indio_dev, "waiting for one shot completion interrupt");
874
875         timeout = wait_for_completion_interruptible_timeout(
876                 &private->data_ready, ZPA2326_CONVERSION_JIFFIES);
877         if (timeout > 0)
878                 /*
879                  * Interrupt handler completed before timeout: return operation
880                  * status.
881                  */
882                 return private->result;
883
884         /* Clear all interrupts just to be sure. */
885         regmap_read(private->regmap, ZPA2326_INT_SOURCE_REG, &val);
886
887         if (!timeout) {
888                 /* Timed out. */
889                 zpa2326_warn(indio_dev, "no one shot interrupt occurred (%ld)",
890                              timeout);
891                 return -ETIME;
892         }
893
894         zpa2326_warn(indio_dev, "wait for one shot interrupt cancelled");
895         return -ERESTARTSYS;
896 }
897
898 static int zpa2326_init_managed_irq(struct device          *parent,
899                                     struct iio_dev         *indio_dev,
900                                     struct zpa2326_private *private,
901                                     int                     irq)
902 {
903         int err;
904
905         private->irq = irq;
906
907         if (irq <= 0) {
908                 /*
909                  * Platform declared no interrupt line: device will be polled
910                  * for data availability.
911                  */
912                 dev_info(parent, "no interrupt found, running in polling mode");
913                 return 0;
914         }
915
916         init_completion(&private->data_ready);
917
918         /* Request handler to be scheduled into threaded interrupt context. */
919         err = devm_request_threaded_irq(parent, irq, zpa2326_handle_irq,
920                                         zpa2326_handle_threaded_irq,
921                                         IRQF_TRIGGER_RISING | IRQF_ONESHOT,
922                                         dev_name(parent), indio_dev);
923         if (err) {
924                 dev_err(parent, "failed to request interrupt %d (%d)", irq,
925                         err);
926                 return err;
927         }
928
929         dev_info(parent, "using interrupt %d", irq);
930
931         return 0;
932 }
933
934 /**
935  * zpa2326_poll_oneshot_completion() - Actively poll for one shot data ready.
936  * @indio_dev: The IIO device associated with the sampling hardware.
937  *
938  * Loop over registers content to detect end of sampling cycle. Used when DT
939  * declared no valid interrupt lines.
940  *
941  * Return: Zero when successful, a negative error code otherwise.
942  */
943 static int zpa2326_poll_oneshot_completion(const struct iio_dev *indio_dev)
944 {
945         unsigned long  tmout = jiffies + ZPA2326_CONVERSION_JIFFIES;
946         struct regmap *regs = ((struct zpa2326_private *)
947                                iio_priv(indio_dev))->regmap;
948         unsigned int   val;
949         int            err;
950
951         zpa2326_dbg(indio_dev, "polling for one shot completion");
952
953         /*
954          * At least, 100 ms is needed for the device to complete its one-shot
955          * cycle.
956          */
957         if (msleep_interruptible(100))
958                 return -ERESTARTSYS;
959
960         /* Poll for conversion completion in hardware. */
961         while (true) {
962                 err = regmap_read(regs, ZPA2326_CTRL_REG0_REG, &val);
963                 if (err < 0)
964                         goto err;
965
966                 if (!(val & ZPA2326_CTRL_REG0_ONE_SHOT))
967                         /* One-shot bit self clears at conversion end. */
968                         break;
969
970                 if (time_after(jiffies, tmout)) {
971                         /* Prevent from waiting forever : let's time out. */
972                         err = -ETIME;
973                         goto err;
974                 }
975
976                 usleep_range(10000, 20000);
977         }
978
979         /*
980          * In oneshot mode, pressure sample availability guarantees that
981          * temperature conversion has also completed : just check pressure
982          * status bit to keep things simple.
983          */
984         err = regmap_read(regs, ZPA2326_STATUS_REG, &val);
985         if (err < 0)
986                 goto err;
987
988         if (!(val & ZPA2326_STATUS_P_DA)) {
989                 /* No sample available. */
990                 err = -ENODATA;
991                 goto err;
992         }
993
994         return 0;
995
996 err:
997         zpa2326_warn(indio_dev, "failed to poll one shot completion (%d)", err);
998
999         return err;
1000 }
1001
1002 /**
1003  * zpa2326_fetch_raw_sample() - Retrieve a raw sample and convert it to CPU
1004  *                              endianness.
1005  * @indio_dev: The IIO device associated with the sampling hardware.
1006  * @type:      Type of measurement / channel to fetch from.
1007  * @value:     Sample output.
1008  *
1009  * Return: Zero when successful, a negative error code otherwise.
1010  */
1011 static int zpa2326_fetch_raw_sample(const struct iio_dev *indio_dev,
1012                                     enum iio_chan_type    type,
1013                                     int                  *value)
1014 {
1015         struct regmap *regs = ((struct zpa2326_private *)
1016                                iio_priv(indio_dev))->regmap;
1017         int            err;
1018
1019         switch (type) {
1020         case IIO_PRESSURE:
1021                 zpa2326_dbg(indio_dev, "fetching raw pressure sample");
1022
1023                 err = regmap_bulk_read(regs, ZPA2326_PRESS_OUT_XL_REG, value,
1024                                        3);
1025                 if (err) {
1026                         zpa2326_warn(indio_dev, "failed to fetch pressure (%d)",
1027                                      err);
1028                         return err;
1029                 }
1030
1031                 /* Pressure is a 24 bits wide little-endian unsigned int. */
1032                 *value = (((u8 *)value)[2] << 16) | (((u8 *)value)[1] << 8) |
1033                          ((u8 *)value)[0];
1034
1035                 return IIO_VAL_INT;
1036
1037         case IIO_TEMP:
1038                 zpa2326_dbg(indio_dev, "fetching raw temperature sample");
1039
1040                 err = regmap_bulk_read(regs, ZPA2326_TEMP_OUT_L_REG, value, 2);
1041                 if (err) {
1042                         zpa2326_warn(indio_dev,
1043                                      "failed to fetch temperature (%d)", err);
1044                         return err;
1045                 }
1046
1047                 /* Temperature is a 16 bits wide little-endian signed int. */
1048                 *value = (int)le16_to_cpup((__le16 *)value);
1049
1050                 return IIO_VAL_INT;
1051
1052         default:
1053                 return -EINVAL;
1054         }
1055 }
1056
1057 /**
1058  * zpa2326_sample_oneshot() - Perform a complete one shot sampling cycle.
1059  * @indio_dev: The IIO device associated with the sampling hardware.
1060  * @type:      Type of measurement / channel to fetch from.
1061  * @value:     Sample output.
1062  *
1063  * Return: Zero when successful, a negative error code otherwise.
1064  */
1065 static int zpa2326_sample_oneshot(struct iio_dev     *indio_dev,
1066                                   enum iio_chan_type  type,
1067                                   int                *value)
1068 {
1069         int                     ret;
1070         struct zpa2326_private *priv;
1071
1072         ret = iio_device_claim_direct_mode(indio_dev);
1073         if (ret)
1074                 return ret;
1075
1076         ret = zpa2326_resume(indio_dev);
1077         if (ret < 0)
1078                 goto release;
1079
1080         priv = iio_priv(indio_dev);
1081
1082         if (ret > 0) {
1083                 /*
1084                  * We were already power supplied. Just clear hardware FIFO to
1085                  * get rid of samples acquired during previous rounds (if any).
1086                  * Sampling operation always generates both temperature and
1087                  * pressure samples. The latter are always enqueued into
1088                  * hardware FIFO. This may lead to situations were pressure
1089                  * samples still sit into FIFO when previous cycle(s) fetched
1090                  * temperature data only.
1091                  * Hence, we need to clear hardware FIFO content to prevent from
1092                  * getting outdated values at the end of current cycle.
1093                  */
1094                 if (type == IIO_PRESSURE) {
1095                         ret = zpa2326_clear_fifo(indio_dev, 0);
1096                         if (ret)
1097                                 goto suspend;
1098                 }
1099         } else {
1100                 /*
1101                  * We have just been power supplied, i.e. device is in default
1102                  * "out of reset" state, meaning we need to reconfigure it
1103                  * entirely.
1104                  */
1105                 ret = zpa2326_config_oneshot(indio_dev, priv->irq);
1106                 if (ret)
1107                         goto suspend;
1108         }
1109
1110         /* Start a sampling cycle in oneshot mode. */
1111         ret = zpa2326_start_oneshot(indio_dev);
1112         if (ret)
1113                 goto suspend;
1114
1115         /* Wait for sampling cycle to complete. */
1116         if (priv->irq > 0)
1117                 ret = zpa2326_wait_oneshot_completion(indio_dev, priv);
1118         else
1119                 ret = zpa2326_poll_oneshot_completion(indio_dev);
1120
1121         if (ret)
1122                 goto suspend;
1123
1124         /* Retrieve raw sample value and convert it to CPU endianness. */
1125         ret = zpa2326_fetch_raw_sample(indio_dev, type, value);
1126
1127 suspend:
1128         zpa2326_suspend(indio_dev);
1129 release:
1130         iio_device_release_direct_mode(indio_dev);
1131
1132         return ret;
1133 }
1134
1135 /**
1136  * zpa2326_trigger_handler() - Perform an IIO buffered sampling round in one
1137  *                             shot mode.
1138  * @irq:  The software interrupt assigned to @data
1139  * @data: The IIO poll function dispatched by external trigger our device is
1140  *        attached to.
1141  *
1142  * Bottom-half handler called by the IIO trigger to which our device is
1143  * currently attached. Allows us to synchronize this device buffered sampling
1144  * either with external events (such as timer expiration, external device sample
1145  * ready, etc...) or with its own interrupt (internal hardware trigger).
1146  *
1147  * When using an external trigger, basically run the same sequence of operations
1148  * as for zpa2326_sample_oneshot() with the following hereafter. Hardware FIFO
1149  * is not cleared since already done at buffering enable time and samples
1150  * dequeueing always retrieves the most recent value.
1151  *
1152  * Otherwise, when internal hardware trigger has dispatched us, just fetch data
1153  * from hardware FIFO.
1154  *
1155  * Fetched data will pushed unprocessed to IIO buffer since samples conversion
1156  * is delegated to userspace in buffered mode (endianness, etc...).
1157  *
1158  * Return:
1159  *   %IRQ_NONE - no consistent interrupt happened ;
1160  *   %IRQ_HANDLED - there was new samples available.
1161  */
1162 static irqreturn_t zpa2326_trigger_handler(int irq, void *data)
1163 {
1164         struct iio_dev         *indio_dev = ((struct iio_poll_func *)
1165                                              data)->indio_dev;
1166         struct zpa2326_private *priv = iio_priv(indio_dev);
1167         bool                    cont;
1168
1169         /*
1170          * We have been dispatched, meaning we are in triggered buffer mode.
1171          * Using our own internal trigger implies we are currently in continuous
1172          * hardware sampling mode.
1173          */
1174         cont = iio_trigger_using_own(indio_dev);
1175
1176         if (!cont) {
1177                 /* On demand sampling : start a one shot cycle. */
1178                 if (zpa2326_start_oneshot(indio_dev))
1179                         goto out;
1180
1181                 /* Wait for sampling cycle to complete. */
1182                 if (priv->irq <= 0) {
1183                         /* No interrupt available: poll for completion. */
1184                         if (zpa2326_poll_oneshot_completion(indio_dev))
1185                                 goto out;
1186
1187                         /* Only timestamp sample once it is ready. */
1188                         priv->timestamp = iio_get_time_ns(indio_dev);
1189                 } else {
1190                         /* Interrupt handlers will timestamp for us. */
1191                         if (zpa2326_wait_oneshot_completion(indio_dev, priv))
1192                                 goto out;
1193                 }
1194         }
1195
1196         /* Enqueue to IIO buffer / userspace. */
1197         zpa2326_fill_sample_buffer(indio_dev, priv);
1198
1199 out:
1200         if (!cont)
1201                 /* Don't switch to low power if sampling continuously. */
1202                 zpa2326_sleep(indio_dev);
1203
1204         /* Inform attached trigger we are done. */
1205         iio_trigger_notify_done(indio_dev->trig);
1206
1207         return IRQ_HANDLED;
1208 }
1209
1210 /**
1211  * zpa2326_preenable_buffer() - Prepare device for configuring triggered
1212  *                              sampling
1213  * modes.
1214  * @indio_dev: The IIO device associated with the sampling hardware.
1215  *
1216  * Basically power up device.
1217  * Called with IIO device's lock held.
1218  *
1219  * Return: Zero when successful, a negative error code otherwise.
1220  */
1221 static int zpa2326_preenable_buffer(struct iio_dev *indio_dev)
1222 {
1223         int ret = zpa2326_resume(indio_dev);
1224
1225         if (ret < 0)
1226                 return ret;
1227
1228         /* Tell zpa2326_postenable_buffer() if we have just been powered on. */
1229         ((struct zpa2326_private *)
1230          iio_priv(indio_dev))->waken = iio_priv(indio_dev);
1231
1232         return 0;
1233 }
1234
1235 /**
1236  * zpa2326_postenable_buffer() - Configure device for triggered sampling.
1237  * @indio_dev: The IIO device associated with the sampling hardware.
1238  *
1239  * Basically setup one-shot mode if plugging external trigger.
1240  * Otherwise, let internal trigger configure continuous sampling :
1241  * see zpa2326_set_trigger_state().
1242  *
1243  * If an error is returned, IIO layer will call our postdisable hook for us,
1244  * i.e. no need to explicitly power device off here.
1245  * Called with IIO device's lock held.
1246  *
1247  * Called with IIO device's lock held.
1248  *
1249  * Return: Zero when successful, a negative error code otherwise.
1250  */
1251 static int zpa2326_postenable_buffer(struct iio_dev *indio_dev)
1252 {
1253         const struct zpa2326_private *priv = iio_priv(indio_dev);
1254         int                           err;
1255
1256         if (!priv->waken) {
1257                 /*
1258                  * We were already power supplied. Just clear hardware FIFO to
1259                  * get rid of samples acquired during previous rounds (if any).
1260                  */
1261                 err = zpa2326_clear_fifo(indio_dev, 0);
1262                 if (err)
1263                         goto err;
1264         }
1265
1266         if (!iio_trigger_using_own(indio_dev) && priv->waken) {
1267                 /*
1268                  * We are using an external trigger and we have just been
1269                  * powered up: reconfigure one-shot mode.
1270                  */
1271                 err = zpa2326_config_oneshot(indio_dev, priv->irq);
1272                 if (err)
1273                         goto err;
1274         }
1275
1276         /* Plug our own trigger event handler. */
1277         err = iio_triggered_buffer_postenable(indio_dev);
1278         if (err)
1279                 goto err;
1280
1281         return 0;
1282
1283 err:
1284         zpa2326_err(indio_dev, "failed to enable buffering (%d)", err);
1285
1286         return err;
1287 }
1288
1289 static int zpa2326_postdisable_buffer(struct iio_dev *indio_dev)
1290 {
1291         zpa2326_suspend(indio_dev);
1292
1293         return 0;
1294 }
1295
1296 static const struct iio_buffer_setup_ops zpa2326_buffer_setup_ops = {
1297         .preenable   = zpa2326_preenable_buffer,
1298         .postenable  = zpa2326_postenable_buffer,
1299         .predisable  = iio_triggered_buffer_predisable,
1300         .postdisable = zpa2326_postdisable_buffer
1301 };
1302
1303 /**
1304  * zpa2326_set_trigger_state() - Start / stop continuous sampling.
1305  * @trig:  The trigger being attached to IIO device associated with the sampling
1306  *         hardware.
1307  * @state: Tell whether to start (true) or stop (false)
1308  *
1309  * Basically enable / disable hardware continuous sampling mode.
1310  *
1311  * Called with IIO device's lock held at postenable() or predisable() time.
1312  *
1313  * Return: Zero when successful, a negative error code otherwise.
1314  */
1315 static int zpa2326_set_trigger_state(struct iio_trigger *trig, bool state)
1316 {
1317         const struct iio_dev         *indio_dev = dev_get_drvdata(
1318                                                         trig->dev.parent);
1319         const struct zpa2326_private *priv = iio_priv(indio_dev);
1320         int                           err;
1321
1322         if (!state) {
1323                 /*
1324                  * Switch trigger off : in case of failure, interrupt is left
1325                  * disabled in order to prevent handler from accessing released
1326                  * resources.
1327                  */
1328                 unsigned int val;
1329
1330                 /*
1331                  * As device is working in continuous mode, handlers may be
1332                  * accessing resources we are currently freeing...
1333                  * Prevent this by disabling interrupt handlers and ensure
1334                  * the device will generate no more interrupts unless explicitly
1335                  * required to, i.e. by restoring back to default one shot mode.
1336                  */
1337                 disable_irq(priv->irq);
1338
1339                 /*
1340                  * Disable continuous sampling mode to restore settings for
1341                  * one shot / direct sampling operations.
1342                  */
1343                 err = regmap_write(priv->regmap, ZPA2326_CTRL_REG3_REG,
1344                                    zpa2326_highest_frequency()->odr);
1345                 if (err)
1346                         return err;
1347
1348                 /*
1349                  * Now that device won't generate interrupts on its own,
1350                  * acknowledge any currently active interrupts (may happen on
1351                  * rare occasions while stopping continuous mode).
1352                  */
1353                 err = regmap_read(priv->regmap, ZPA2326_INT_SOURCE_REG, &val);
1354                 if (err < 0)
1355                         return err;
1356
1357                 /*
1358                  * Re-enable interrupts only if we can guarantee the device will
1359                  * generate no more interrupts to prevent handlers from
1360                  * accessing released resources.
1361                  */
1362                 enable_irq(priv->irq);
1363
1364                 zpa2326_dbg(indio_dev, "continuous mode stopped");
1365         } else {
1366                 /*
1367                  * Switch trigger on : start continuous sampling at required
1368                  * frequency.
1369                  */
1370
1371                 if (priv->waken) {
1372                         /* Enable interrupt if getting out of reset. */
1373                         err = regmap_write(priv->regmap, ZPA2326_CTRL_REG1_REG,
1374                                            (u8)
1375                                            ~ZPA2326_CTRL_REG1_MASK_DATA_READY);
1376                         if (err)
1377                                 return err;
1378                 }
1379
1380                 /* Enable continuous sampling at specified frequency. */
1381                 err = regmap_write(priv->regmap, ZPA2326_CTRL_REG3_REG,
1382                                    ZPA2326_CTRL_REG3_ENABLE_MEAS |
1383                                    priv->frequency->odr);
1384                 if (err)
1385                         return err;
1386
1387                 zpa2326_dbg(indio_dev, "continuous mode setup @%dHz",
1388                             priv->frequency->hz);
1389         }
1390
1391         return 0;
1392 }
1393
1394 static const struct iio_trigger_ops zpa2326_trigger_ops = {
1395         .owner             = THIS_MODULE,
1396         .set_trigger_state = zpa2326_set_trigger_state,
1397 };
1398
1399 /**
1400  * zpa2326_init_trigger() - Create an interrupt driven / hardware trigger
1401  *                          allowing to notify external devices a new sample is
1402  *                          ready.
1403  * @parent:    Hardware sampling device @indio_dev is a child of.
1404  * @indio_dev: The IIO device associated with the sampling hardware.
1405  * @private:   Internal private state related to @indio_dev.
1406  * @irq:       Optional interrupt line the hardware uses to notify new data
1407  *             samples are ready. Negative or zero values indicate no interrupts
1408  *             are available, meaning polling is required.
1409  *
1410  * Only relevant when DT declares a valid interrupt line.
1411  *
1412  * Return: Zero when successful, a negative error code otherwise.
1413  */
1414 static int zpa2326_init_managed_trigger(struct device          *parent,
1415                                         struct iio_dev         *indio_dev,
1416                                         struct zpa2326_private *private,
1417                                         int                     irq)
1418 {
1419         struct iio_trigger *trigger;
1420         int                 ret;
1421
1422         if (irq <= 0)
1423                 return 0;
1424
1425         trigger = devm_iio_trigger_alloc(parent, "%s-dev%d",
1426                                          indio_dev->name, indio_dev->id);
1427         if (!trigger)
1428                 return -ENOMEM;
1429
1430         /* Basic setup. */
1431         trigger->dev.parent = parent;
1432         trigger->ops = &zpa2326_trigger_ops;
1433
1434         private->trigger = trigger;
1435
1436         /* Register to triggers space. */
1437         ret = devm_iio_trigger_register(parent, trigger);
1438         if (ret)
1439                 dev_err(parent, "failed to register hardware trigger (%d)",
1440                         ret);
1441
1442         return ret;
1443 }
1444
1445 static int zpa2326_get_frequency(const struct iio_dev *indio_dev)
1446 {
1447         return ((struct zpa2326_private *)iio_priv(indio_dev))->frequency->hz;
1448 }
1449
1450 static int zpa2326_set_frequency(struct iio_dev *indio_dev, int hz)
1451 {
1452         struct zpa2326_private *priv = iio_priv(indio_dev);
1453         int                     freq;
1454         int                     err;
1455
1456         /* Check if requested frequency is supported. */
1457         for (freq = 0; freq < ARRAY_SIZE(zpa2326_sampling_frequencies); freq++)
1458                 if (zpa2326_sampling_frequencies[freq].hz == hz)
1459                         break;
1460         if (freq == ARRAY_SIZE(zpa2326_sampling_frequencies))
1461                 return -EINVAL;
1462
1463         /* Don't allow changing frequency if buffered sampling is ongoing. */
1464         err = iio_device_claim_direct_mode(indio_dev);
1465         if (err)
1466                 return err;
1467
1468         priv->frequency = &zpa2326_sampling_frequencies[freq];
1469
1470         iio_device_release_direct_mode(indio_dev);
1471
1472         return 0;
1473 }
1474
1475 /* Expose supported hardware sampling frequencies (Hz) through sysfs. */
1476 static IIO_CONST_ATTR_SAMP_FREQ_AVAIL("1 5 11 23");
1477
1478 static struct attribute *zpa2326_attributes[] = {
1479         &iio_const_attr_sampling_frequency_available.dev_attr.attr,
1480         NULL
1481 };
1482
1483 static const struct attribute_group zpa2326_attribute_group = {
1484         .attrs = zpa2326_attributes,
1485 };
1486
1487 static int zpa2326_read_raw(struct iio_dev             *indio_dev,
1488                             struct iio_chan_spec const *chan,
1489                             int                        *val,
1490                             int                        *val2,
1491                             long                        mask)
1492 {
1493         switch (mask) {
1494         case IIO_CHAN_INFO_RAW:
1495                 return zpa2326_sample_oneshot(indio_dev, chan->type, val);
1496
1497         case IIO_CHAN_INFO_SCALE:
1498                 switch (chan->type) {
1499                 case IIO_PRESSURE:
1500                         /*
1501                          * Pressure resolution is 1/64 Pascal. Scale to kPascal
1502                          * as required by IIO ABI.
1503                          */
1504                         *val = 1;
1505                         *val2 = 64000;
1506                         return IIO_VAL_FRACTIONAL;
1507
1508                 case IIO_TEMP:
1509                         /*
1510                          * Temperature follows the equation:
1511                          *     Temp[degC] = Tempcode * 0.00649 - 176.83
1512                          * where:
1513                          *     Tempcode is composed the raw sampled 16 bits.
1514                          *
1515                          * Hence, to produce a temperature in milli-degrees
1516                          * Celsius according to IIO ABI, we need to apply the
1517                          * following equation to raw samples:
1518                          *     Temp[milli degC] = (Tempcode + Offset) * Scale
1519                          * where:
1520                          *     Offset = -176.83 / 0.00649
1521                          *     Scale = 0.00649 * 1000
1522                          */
1523                         *val = 6;
1524                         *val2 = 490000;
1525                         return IIO_VAL_INT_PLUS_MICRO;
1526
1527                 default:
1528                         return -EINVAL;
1529                 }
1530
1531         case IIO_CHAN_INFO_OFFSET:
1532                 switch (chan->type) {
1533                 case IIO_TEMP:
1534                         *val = -17683000;
1535                         *val2 = 649;
1536                         return IIO_VAL_FRACTIONAL;
1537
1538                 default:
1539                         return -EINVAL;
1540                 }
1541
1542         case IIO_CHAN_INFO_SAMP_FREQ:
1543                 *val = zpa2326_get_frequency(indio_dev);
1544                 return IIO_VAL_INT;
1545
1546         default:
1547                 return -EINVAL;
1548         }
1549 }
1550
1551 static int zpa2326_write_raw(struct iio_dev             *indio_dev,
1552                              const struct iio_chan_spec *chan,
1553                              int                         val,
1554                              int                         val2,
1555                              long                        mask)
1556 {
1557         if ((mask != IIO_CHAN_INFO_SAMP_FREQ) || val2)
1558                 return -EINVAL;
1559
1560         return zpa2326_set_frequency(indio_dev, val);
1561 }
1562
1563 static const struct iio_chan_spec zpa2326_channels[] = {
1564         [0] = {
1565                 .type                    = IIO_PRESSURE,
1566                 .scan_index              = 0,
1567                 .scan_type               = {
1568                         .sign                   = 'u',
1569                         .realbits               = 24,
1570                         .storagebits            = 32,
1571                         .endianness             = IIO_LE,
1572                 },
1573                 .info_mask_separate      = BIT(IIO_CHAN_INFO_RAW) |
1574                                            BIT(IIO_CHAN_INFO_SCALE),
1575                 .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ),
1576         },
1577         [1] = {
1578                 .type                    = IIO_TEMP,
1579                 .scan_index              = 1,
1580                 .scan_type               = {
1581                         .sign                   = 's',
1582                         .realbits               = 16,
1583                         .storagebits            = 16,
1584                         .endianness             = IIO_LE,
1585                 },
1586                 .info_mask_separate      = BIT(IIO_CHAN_INFO_RAW) |
1587                                            BIT(IIO_CHAN_INFO_SCALE) |
1588                                            BIT(IIO_CHAN_INFO_OFFSET),
1589                 .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ),
1590         },
1591         [2] = IIO_CHAN_SOFT_TIMESTAMP(2),
1592 };
1593
1594 static const struct iio_info zpa2326_info = {
1595         .driver_module = THIS_MODULE,
1596         .attrs         = &zpa2326_attribute_group,
1597         .read_raw      = zpa2326_read_raw,
1598         .write_raw     = zpa2326_write_raw,
1599 };
1600
1601 static struct iio_dev *zpa2326_create_managed_iiodev(struct device *device,
1602                                                      const char    *name,
1603                                                      struct regmap *regmap)
1604 {
1605         struct iio_dev *indio_dev;
1606
1607         /* Allocate space to hold IIO device internal state. */
1608         indio_dev = devm_iio_device_alloc(device,
1609                                           sizeof(struct zpa2326_private));
1610         if (!indio_dev)
1611                 return NULL;
1612
1613         /* Setup for userspace synchronous on demand sampling. */
1614         indio_dev->modes = INDIO_DIRECT_MODE;
1615         indio_dev->dev.parent = device;
1616         indio_dev->channels = zpa2326_channels;
1617         indio_dev->num_channels = ARRAY_SIZE(zpa2326_channels);
1618         indio_dev->name = name;
1619         indio_dev->info = &zpa2326_info;
1620
1621         return indio_dev;
1622 }
1623
1624 int zpa2326_probe(struct device *parent,
1625                   const char    *name,
1626                   int            irq,
1627                   unsigned int   hwid,
1628                   struct regmap *regmap)
1629 {
1630         struct iio_dev         *indio_dev;
1631         struct zpa2326_private *priv;
1632         int                     err;
1633         unsigned int            id;
1634
1635         indio_dev = zpa2326_create_managed_iiodev(parent, name, regmap);
1636         if (!indio_dev)
1637                 return -ENOMEM;
1638
1639         priv = iio_priv(indio_dev);
1640
1641         priv->vref = devm_regulator_get(parent, "vref");
1642         if (IS_ERR(priv->vref))
1643                 return PTR_ERR(priv->vref);
1644
1645         priv->vdd = devm_regulator_get(parent, "vdd");
1646         if (IS_ERR(priv->vdd))
1647                 return PTR_ERR(priv->vdd);
1648
1649         /* Set default hardware sampling frequency to highest rate supported. */
1650         priv->frequency = zpa2326_highest_frequency();
1651
1652         /*
1653          * Plug device's underlying bus abstraction : this MUST be set before
1654          * registering interrupt handlers since an interrupt might happen if
1655          * power up sequence is not properly applied.
1656          */
1657         priv->regmap = regmap;
1658
1659         err = devm_iio_triggered_buffer_setup(parent, indio_dev, NULL,
1660                                               zpa2326_trigger_handler,
1661                                               &zpa2326_buffer_setup_ops);
1662         if (err)
1663                 return err;
1664
1665         err = zpa2326_init_managed_trigger(parent, indio_dev, priv, irq);
1666         if (err)
1667                 return err;
1668
1669         err = zpa2326_init_managed_irq(parent, indio_dev, priv, irq);
1670         if (err)
1671                 return err;
1672
1673         /* Power up to check device ID and perform initial hardware setup. */
1674         err = zpa2326_power_on(indio_dev, priv);
1675         if (err)
1676                 return err;
1677
1678         /* Read id register to check we are talking to the right slave. */
1679         err = regmap_read(regmap, ZPA2326_DEVICE_ID_REG, &id);
1680         if (err)
1681                 goto sleep;
1682
1683         if (id != hwid) {
1684                 dev_err(parent, "found device with unexpected id %02x", id);
1685                 err = -ENODEV;
1686                 goto sleep;
1687         }
1688
1689         err = zpa2326_config_oneshot(indio_dev, irq);
1690         if (err)
1691                 goto sleep;
1692
1693         /* Setup done : go sleeping. Device will be awaken upon user request. */
1694         err = zpa2326_sleep(indio_dev);
1695         if (err)
1696                 goto poweroff;
1697
1698         dev_set_drvdata(parent, indio_dev);
1699
1700         zpa2326_init_runtime(parent);
1701
1702         err = iio_device_register(indio_dev);
1703         if (err) {
1704                 zpa2326_fini_runtime(parent);
1705                 goto poweroff;
1706         }
1707
1708         return 0;
1709
1710 sleep:
1711         /* Put to sleep just in case power regulators are "dummy" ones. */
1712         zpa2326_sleep(indio_dev);
1713 poweroff:
1714         zpa2326_power_off(indio_dev, priv);
1715
1716         return err;
1717 }
1718 EXPORT_SYMBOL_GPL(zpa2326_probe);
1719
1720 void zpa2326_remove(const struct device *parent)
1721 {
1722         struct iio_dev *indio_dev = dev_get_drvdata(parent);
1723
1724         iio_device_unregister(indio_dev);
1725         zpa2326_fini_runtime(indio_dev->dev.parent);
1726         zpa2326_sleep(indio_dev);
1727         zpa2326_power_off(indio_dev, iio_priv(indio_dev));
1728 }
1729 EXPORT_SYMBOL_GPL(zpa2326_remove);
1730
1731 MODULE_AUTHOR("Gregor Boirie <gregor.boirie@parrot.com>");
1732 MODULE_DESCRIPTION("Core driver for Murata ZPA2326 pressure sensor");
1733 MODULE_LICENSE("GPL v2");