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