Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Murata ZPA2326 pressure and temperature sensor IIO driver
0004  *
0005  * Copyright (c) 2016 Parrot S.A.
0006  *
0007  * Author: Gregor Boirie <gregor.boirie@parrot.com>
0008  */
0009 
0010 /**
0011  * DOC: ZPA2326 theory of operations
0012  *
0013  * This driver supports %INDIO_DIRECT_MODE and %INDIO_BUFFER_TRIGGERED IIO
0014  * modes.
0015  * A internal hardware trigger is also implemented to dispatch registered IIO
0016  * trigger consumers upon "sample ready" interrupts.
0017  *
0018  * ZPA2326 hardware supports 2 sampling mode: one shot and continuous.
0019  *
0020  * A complete one shot sampling cycle gets device out of low power mode,
0021  * performs pressure and temperature measurements, then automatically switches
0022  * back to low power mode. It is meant for on demand sampling with optimal power
0023  * saving at the cost of lower sampling rate and higher software overhead.
0024  * This is a natural candidate for IIO read_raw hook implementation
0025  * (%INDIO_DIRECT_MODE). It is also used for triggered buffering support to
0026  * ensure explicit synchronization with external trigger events
0027  * (%INDIO_BUFFER_TRIGGERED).
0028  *
0029  * The continuous mode works according to a periodic hardware measurement
0030  * process continuously pushing samples into an internal hardware FIFO (for
0031  * pressure samples only). Measurement cycle completion may be signaled by a
0032  * "sample ready" interrupt.
0033  * Typical software sequence of operations :
0034  * - get device out of low power mode,
0035  * - setup hardware sampling period,
0036  * - at end of period, upon data ready interrupt: pop pressure samples out of
0037  *   hardware FIFO and fetch temperature sample
0038  * - when no longer needed, stop sampling process by putting device into
0039  *   low power mode.
0040  * This mode is used to implement %INDIO_BUFFER_TRIGGERED mode if device tree
0041  * declares a valid interrupt line. In this case, the internal hardware trigger
0042  * drives acquisition.
0043  *
0044  * Note that hardware sampling frequency is taken into account only when
0045  * internal hardware trigger is attached as the highest sampling rate seems to
0046  * be the most energy efficient.
0047  *
0048  * TODO:
0049  *   preset pressure threshold crossing / IIO events ;
0050  *   differential pressure sampling ;
0051  *   hardware samples averaging.
0052  */
0053 
0054 #include <linux/module.h>
0055 #include <linux/kernel.h>
0056 #include <linux/delay.h>
0057 #include <linux/interrupt.h>
0058 #include <linux/regulator/consumer.h>
0059 #include <linux/pm_runtime.h>
0060 #include <linux/regmap.h>
0061 #include <linux/iio/iio.h>
0062 #include <linux/iio/sysfs.h>
0063 #include <linux/iio/buffer.h>
0064 #include <linux/iio/trigger.h>
0065 #include <linux/iio/trigger_consumer.h>
0066 #include <linux/iio/triggered_buffer.h>
0067 #include <asm/unaligned.h>
0068 #include "zpa2326.h"
0069 
0070 /* 200 ms should be enough for the longest conversion time in one-shot mode. */
0071 #define ZPA2326_CONVERSION_JIFFIES (HZ / 5)
0072 
0073 /* There should be a 1 ms delay (Tpup) after getting out of reset. */
0074 #define ZPA2326_TPUP_USEC_MIN      (1000)
0075 #define ZPA2326_TPUP_USEC_MAX      (2000)
0076 
0077 /**
0078  * struct zpa2326_frequency - Hardware sampling frequency descriptor
0079  * @hz : Frequency in Hertz.
0080  * @odr: Output Data Rate word as expected by %ZPA2326_CTRL_REG3_REG.
0081  */
0082 struct zpa2326_frequency {
0083     int hz;
0084     u16 odr;
0085 };
0086 
0087 /*
0088  * Keep these in strict ascending order: last array entry is expected to
0089  * correspond to the highest sampling frequency.
0090  */
0091 static const struct zpa2326_frequency zpa2326_sampling_frequencies[] = {
0092     { .hz = 1,  .odr = 1 << ZPA2326_CTRL_REG3_ODR_SHIFT },
0093     { .hz = 5,  .odr = 5 << ZPA2326_CTRL_REG3_ODR_SHIFT },
0094     { .hz = 11, .odr = 6 << ZPA2326_CTRL_REG3_ODR_SHIFT },
0095     { .hz = 23, .odr = 7 << ZPA2326_CTRL_REG3_ODR_SHIFT },
0096 };
0097 
0098 /* Return the highest hardware sampling frequency available. */
0099 static const struct zpa2326_frequency *zpa2326_highest_frequency(void)
0100 {
0101     return &zpa2326_sampling_frequencies[
0102         ARRAY_SIZE(zpa2326_sampling_frequencies) - 1];
0103 }
0104 
0105 /**
0106  * struct zpa2326_private - Per-device internal private state
0107  * @timestamp:  Buffered samples ready datum.
0108  * @regmap:     Underlying I2C / SPI bus adapter used to abstract slave register
0109  *              accesses.
0110  * @result:     Allows sampling logic to get completion status of operations
0111  *              that interrupt handlers perform asynchronously.
0112  * @data_ready: Interrupt handler uses this to wake user context up at sampling
0113  *              operation completion.
0114  * @trigger:    Optional hardware / interrupt driven trigger used to notify
0115  *              external devices a new sample is ready.
0116  * @waken:      Flag indicating whether or not device has just been powered on.
0117  * @irq:        Optional interrupt line: negative or zero if not declared into
0118  *              DT, in which case sampling logic keeps polling status register
0119  *              to detect completion.
0120  * @frequency:  Current hardware sampling frequency.
0121  * @vref:       Power / voltage reference.
0122  * @vdd:        Power supply.
0123  */
0124 struct zpa2326_private {
0125     s64                             timestamp;
0126     struct regmap                  *regmap;
0127     int                             result;
0128     struct completion               data_ready;
0129     struct iio_trigger             *trigger;
0130     bool                            waken;
0131     int                             irq;
0132     const struct zpa2326_frequency *frequency;
0133     struct regulator               *vref;
0134     struct regulator               *vdd;
0135 };
0136 
0137 #define zpa2326_err(idev, fmt, ...)                 \
0138     dev_err(idev->dev.parent, fmt "\n", ##__VA_ARGS__)
0139 
0140 #define zpa2326_warn(idev, fmt, ...)                    \
0141     dev_warn(idev->dev.parent, fmt "\n", ##__VA_ARGS__)
0142 
0143 #define zpa2326_dbg(idev, fmt, ...)                 \
0144     dev_dbg(idev->dev.parent, fmt "\n", ##__VA_ARGS__)
0145 
0146 bool zpa2326_isreg_writeable(struct device *dev, unsigned int reg)
0147 {
0148     switch (reg) {
0149     case ZPA2326_REF_P_XL_REG:
0150     case ZPA2326_REF_P_L_REG:
0151     case ZPA2326_REF_P_H_REG:
0152     case ZPA2326_RES_CONF_REG:
0153     case ZPA2326_CTRL_REG0_REG:
0154     case ZPA2326_CTRL_REG1_REG:
0155     case ZPA2326_CTRL_REG2_REG:
0156     case ZPA2326_CTRL_REG3_REG:
0157     case ZPA2326_THS_P_LOW_REG:
0158     case ZPA2326_THS_P_HIGH_REG:
0159         return true;
0160 
0161     default:
0162         return false;
0163     }
0164 }
0165 EXPORT_SYMBOL_NS_GPL(zpa2326_isreg_writeable, IIO_ZPA2326);
0166 
0167 bool zpa2326_isreg_readable(struct device *dev, unsigned int reg)
0168 {
0169     switch (reg) {
0170     case ZPA2326_REF_P_XL_REG:
0171     case ZPA2326_REF_P_L_REG:
0172     case ZPA2326_REF_P_H_REG:
0173     case ZPA2326_DEVICE_ID_REG:
0174     case ZPA2326_RES_CONF_REG:
0175     case ZPA2326_CTRL_REG0_REG:
0176     case ZPA2326_CTRL_REG1_REG:
0177     case ZPA2326_CTRL_REG2_REG:
0178     case ZPA2326_CTRL_REG3_REG:
0179     case ZPA2326_INT_SOURCE_REG:
0180     case ZPA2326_THS_P_LOW_REG:
0181     case ZPA2326_THS_P_HIGH_REG:
0182     case ZPA2326_STATUS_REG:
0183     case ZPA2326_PRESS_OUT_XL_REG:
0184     case ZPA2326_PRESS_OUT_L_REG:
0185     case ZPA2326_PRESS_OUT_H_REG:
0186     case ZPA2326_TEMP_OUT_L_REG:
0187     case ZPA2326_TEMP_OUT_H_REG:
0188         return true;
0189 
0190     default:
0191         return false;
0192     }
0193 }
0194 EXPORT_SYMBOL_NS_GPL(zpa2326_isreg_readable, IIO_ZPA2326);
0195 
0196 bool zpa2326_isreg_precious(struct device *dev, unsigned int reg)
0197 {
0198     switch (reg) {
0199     case ZPA2326_INT_SOURCE_REG:
0200     case ZPA2326_PRESS_OUT_H_REG:
0201         return true;
0202 
0203     default:
0204         return false;
0205     }
0206 }
0207 EXPORT_SYMBOL_NS_GPL(zpa2326_isreg_precious, IIO_ZPA2326);
0208 
0209 /**
0210  * zpa2326_enable_device() - Enable device, i.e. get out of low power mode.
0211  * @indio_dev: The IIO device associated with the hardware to enable.
0212  *
0213  * Required to access complete register space and to perform any sampling
0214  * or control operations.
0215  *
0216  * Return: Zero when successful, a negative error code otherwise.
0217  */
0218 static int zpa2326_enable_device(const struct iio_dev *indio_dev)
0219 {
0220     int err;
0221 
0222     err = regmap_write(((struct zpa2326_private *)
0223                 iio_priv(indio_dev))->regmap,
0224                 ZPA2326_CTRL_REG0_REG, ZPA2326_CTRL_REG0_ENABLE);
0225     if (err) {
0226         zpa2326_err(indio_dev, "failed to enable device (%d)", err);
0227         return err;
0228     }
0229 
0230     zpa2326_dbg(indio_dev, "enabled");
0231 
0232     return 0;
0233 }
0234 
0235 /**
0236  * zpa2326_sleep() - Disable device, i.e. switch to low power mode.
0237  * @indio_dev: The IIO device associated with the hardware to disable.
0238  *
0239  * Only %ZPA2326_DEVICE_ID_REG and %ZPA2326_CTRL_REG0_REG registers may be
0240  * accessed once device is in the disabled state.
0241  *
0242  * Return: Zero when successful, a negative error code otherwise.
0243  */
0244 static int zpa2326_sleep(const struct iio_dev *indio_dev)
0245 {
0246     int err;
0247 
0248     err = regmap_write(((struct zpa2326_private *)
0249                 iio_priv(indio_dev))->regmap,
0250                 ZPA2326_CTRL_REG0_REG, 0);
0251     if (err) {
0252         zpa2326_err(indio_dev, "failed to sleep (%d)", err);
0253         return err;
0254     }
0255 
0256     zpa2326_dbg(indio_dev, "sleeping");
0257 
0258     return 0;
0259 }
0260 
0261 /**
0262  * zpa2326_reset_device() - Reset device to default hardware state.
0263  * @indio_dev: The IIO device associated with the hardware to reset.
0264  *
0265  * Disable sampling and empty hardware FIFO.
0266  * Device must be enabled before reset, i.e. not in low power mode.
0267  *
0268  * Return: Zero when successful, a negative error code otherwise.
0269  */
0270 static int zpa2326_reset_device(const struct iio_dev *indio_dev)
0271 {
0272     int err;
0273 
0274     err = regmap_write(((struct zpa2326_private *)
0275                 iio_priv(indio_dev))->regmap,
0276                 ZPA2326_CTRL_REG2_REG, ZPA2326_CTRL_REG2_SWRESET);
0277     if (err) {
0278         zpa2326_err(indio_dev, "failed to reset device (%d)", err);
0279         return err;
0280     }
0281 
0282     usleep_range(ZPA2326_TPUP_USEC_MIN, ZPA2326_TPUP_USEC_MAX);
0283 
0284     zpa2326_dbg(indio_dev, "reset");
0285 
0286     return 0;
0287 }
0288 
0289 /**
0290  * zpa2326_start_oneshot() - Start a single sampling cycle, i.e. in one shot
0291  *                           mode.
0292  * @indio_dev: The IIO device associated with the sampling hardware.
0293  *
0294  * Device must have been previously enabled and configured for one shot mode.
0295  * Device will be switched back to low power mode at end of cycle.
0296  *
0297  * Return: Zero when successful, a negative error code otherwise.
0298  */
0299 static int zpa2326_start_oneshot(const struct iio_dev *indio_dev)
0300 {
0301     int err;
0302 
0303     err = regmap_write(((struct zpa2326_private *)
0304                 iio_priv(indio_dev))->regmap,
0305                 ZPA2326_CTRL_REG0_REG,
0306                 ZPA2326_CTRL_REG0_ENABLE |
0307                 ZPA2326_CTRL_REG0_ONE_SHOT);
0308     if (err) {
0309         zpa2326_err(indio_dev, "failed to start one shot cycle (%d)",
0310                 err);
0311         return err;
0312     }
0313 
0314     zpa2326_dbg(indio_dev, "one shot cycle started");
0315 
0316     return 0;
0317 }
0318 
0319 /**
0320  * zpa2326_power_on() - Power on device to allow subsequent configuration.
0321  * @indio_dev: The IIO device associated with the sampling hardware.
0322  * @private:   Internal private state related to @indio_dev.
0323  *
0324  * Sampling will be disabled, preventing strange things from happening in our
0325  * back. Hardware FIFO content will be cleared.
0326  * When successful, device will be left in the enabled state to allow further
0327  * configuration.
0328  *
0329  * Return: Zero when successful, a negative error code otherwise.
0330  */
0331 static int zpa2326_power_on(const struct iio_dev         *indio_dev,
0332                 const struct zpa2326_private *private)
0333 {
0334     int err;
0335 
0336     err = regulator_enable(private->vref);
0337     if (err)
0338         return err;
0339 
0340     err = regulator_enable(private->vdd);
0341     if (err)
0342         goto vref;
0343 
0344     zpa2326_dbg(indio_dev, "powered on");
0345 
0346     err = zpa2326_enable_device(indio_dev);
0347     if (err)
0348         goto vdd;
0349 
0350     err = zpa2326_reset_device(indio_dev);
0351     if (err)
0352         goto sleep;
0353 
0354     return 0;
0355 
0356 sleep:
0357     zpa2326_sleep(indio_dev);
0358 vdd:
0359     regulator_disable(private->vdd);
0360 vref:
0361     regulator_disable(private->vref);
0362 
0363     zpa2326_dbg(indio_dev, "powered off");
0364 
0365     return err;
0366 }
0367 
0368 /**
0369  * zpa2326_power_off() - Power off device, i.e. disable attached power
0370  *                       regulators.
0371  * @indio_dev: The IIO device associated with the sampling hardware.
0372  * @private:   Internal private state related to @indio_dev.
0373  *
0374  * Return: Zero when successful, a negative error code otherwise.
0375  */
0376 static void zpa2326_power_off(const struct iio_dev         *indio_dev,
0377                   const struct zpa2326_private *private)
0378 {
0379     regulator_disable(private->vdd);
0380     regulator_disable(private->vref);
0381 
0382     zpa2326_dbg(indio_dev, "powered off");
0383 }
0384 
0385 /**
0386  * zpa2326_config_oneshot() - Setup device for one shot / on demand mode.
0387  * @indio_dev: The IIO device associated with the sampling hardware.
0388  * @irq:       Optional interrupt line the hardware uses to notify new data
0389  *             samples are ready. Negative or zero values indicate no interrupts
0390  *             are available, meaning polling is required.
0391  *
0392  * Output Data Rate is configured for the highest possible rate so that
0393  * conversion time and power consumption are reduced to a minimum.
0394  * Note that hardware internal averaging machinery (not implemented in this
0395  * driver) is not applicable in this mode.
0396  *
0397  * Device must have been previously enabled before calling
0398  * zpa2326_config_oneshot().
0399  *
0400  * Return: Zero when successful, a negative error code otherwise.
0401  */
0402 static int zpa2326_config_oneshot(const struct iio_dev *indio_dev,
0403                   int                   irq)
0404 {
0405     struct regmap                  *regs = ((struct zpa2326_private *)
0406                         iio_priv(indio_dev))->regmap;
0407     const struct zpa2326_frequency *freq = zpa2326_highest_frequency();
0408     int                             err;
0409 
0410     /* Setup highest available Output Data Rate for one shot mode. */
0411     err = regmap_write(regs, ZPA2326_CTRL_REG3_REG, freq->odr);
0412     if (err)
0413         return err;
0414 
0415     if (irq > 0) {
0416         /* Request interrupt when new sample is available. */
0417         err = regmap_write(regs, ZPA2326_CTRL_REG1_REG,
0418                    (u8)~ZPA2326_CTRL_REG1_MASK_DATA_READY);
0419 
0420         if (err) {
0421             dev_err(indio_dev->dev.parent,
0422                 "failed to setup one shot mode (%d)", err);
0423             return err;
0424         }
0425     }
0426 
0427     zpa2326_dbg(indio_dev, "one shot mode setup @%dHz", freq->hz);
0428 
0429     return 0;
0430 }
0431 
0432 /**
0433  * zpa2326_clear_fifo() - Clear remaining entries in hardware FIFO.
0434  * @indio_dev: The IIO device associated with the sampling hardware.
0435  * @min_count: Number of samples present within hardware FIFO.
0436  *
0437  * @min_count argument is a hint corresponding to the known minimum number of
0438  * samples currently living in the FIFO. This allows to reduce the number of bus
0439  * accesses by skipping status register read operation as long as we know for
0440  * sure there are still entries left.
0441  *
0442  * Return: Zero when successful, a negative error code otherwise.
0443  */
0444 static int zpa2326_clear_fifo(const struct iio_dev *indio_dev,
0445                   unsigned int          min_count)
0446 {
0447     struct regmap *regs = ((struct zpa2326_private *)
0448                    iio_priv(indio_dev))->regmap;
0449     int            err;
0450     unsigned int   val;
0451 
0452     if (!min_count) {
0453         /*
0454          * No hint: read status register to determine whether FIFO is
0455          * empty or not.
0456          */
0457         err = regmap_read(regs, ZPA2326_STATUS_REG, &val);
0458 
0459         if (err < 0)
0460             goto err;
0461 
0462         if (val & ZPA2326_STATUS_FIFO_E)
0463             /* Fifo is empty: nothing to trash. */
0464             return 0;
0465     }
0466 
0467     /* Clear FIFO. */
0468     do {
0469         /*
0470          * A single fetch from pressure MSB register is enough to pop
0471          * values out of FIFO.
0472          */
0473         err = regmap_read(regs, ZPA2326_PRESS_OUT_H_REG, &val);
0474         if (err < 0)
0475             goto err;
0476 
0477         if (min_count) {
0478             /*
0479              * We know for sure there are at least min_count entries
0480              * left in FIFO. Skip status register read.
0481              */
0482             min_count--;
0483             continue;
0484         }
0485 
0486         err = regmap_read(regs, ZPA2326_STATUS_REG, &val);
0487         if (err < 0)
0488             goto err;
0489 
0490     } while (!(val & ZPA2326_STATUS_FIFO_E));
0491 
0492     zpa2326_dbg(indio_dev, "FIFO cleared");
0493 
0494     return 0;
0495 
0496 err:
0497     zpa2326_err(indio_dev, "failed to clear FIFO (%d)", err);
0498 
0499     return err;
0500 }
0501 
0502 /**
0503  * zpa2326_dequeue_pressure() - Retrieve the most recent pressure sample from
0504  *                              hardware FIFO.
0505  * @indio_dev: The IIO device associated with the sampling hardware.
0506  * @pressure:  Sampled pressure output.
0507  *
0508  * Note that ZPA2326 hardware FIFO stores pressure samples only.
0509  *
0510  * Return: Zero when successful, a negative error code otherwise.
0511  */
0512 static int zpa2326_dequeue_pressure(const struct iio_dev *indio_dev,
0513                     u32                  *pressure)
0514 {
0515     struct regmap *regs = ((struct zpa2326_private *)
0516                    iio_priv(indio_dev))->regmap;
0517     unsigned int   val;
0518     int            err;
0519     int            cleared = -1;
0520 
0521     err = regmap_read(regs, ZPA2326_STATUS_REG, &val);
0522     if (err < 0)
0523         return err;
0524 
0525     *pressure = 0;
0526 
0527     if (val & ZPA2326_STATUS_P_OR) {
0528         /*
0529          * Fifo overrun : first sample dequeued from FIFO is the
0530          * newest.
0531          */
0532         zpa2326_warn(indio_dev, "FIFO overflow");
0533 
0534         err = regmap_bulk_read(regs, ZPA2326_PRESS_OUT_XL_REG, pressure,
0535                        3);
0536         if (err)
0537             return err;
0538 
0539 #define ZPA2326_FIFO_DEPTH (16U)
0540         /* Hardware FIFO may hold no more than 16 pressure samples. */
0541         return zpa2326_clear_fifo(indio_dev, ZPA2326_FIFO_DEPTH - 1);
0542     }
0543 
0544     /*
0545      * Fifo has not overflown : retrieve newest sample. We need to pop
0546      * values out until FIFO is empty : last fetched pressure is the newest.
0547      * In nominal cases, we should find a single queued sample only.
0548      */
0549     do {
0550         err = regmap_bulk_read(regs, ZPA2326_PRESS_OUT_XL_REG, pressure,
0551                        3);
0552         if (err)
0553             return err;
0554 
0555         err = regmap_read(regs, ZPA2326_STATUS_REG, &val);
0556         if (err < 0)
0557             return err;
0558 
0559         cleared++;
0560     } while (!(val & ZPA2326_STATUS_FIFO_E));
0561 
0562     if (cleared)
0563         /*
0564          * Samples were pushed by hardware during previous rounds but we
0565          * didn't consume them fast enough: inform user.
0566          */
0567         zpa2326_dbg(indio_dev, "cleared %d FIFO entries", cleared);
0568 
0569     return 0;
0570 }
0571 
0572 /**
0573  * zpa2326_fill_sample_buffer() - Enqueue new channel samples to IIO buffer.
0574  * @indio_dev: The IIO device associated with the sampling hardware.
0575  * @private:   Internal private state related to @indio_dev.
0576  *
0577  * Return: Zero when successful, a negative error code otherwise.
0578  */
0579 static int zpa2326_fill_sample_buffer(struct iio_dev               *indio_dev,
0580                       const struct zpa2326_private *private)
0581 {
0582     struct {
0583         u32 pressure;
0584         u16 temperature;
0585         u64 timestamp;
0586     }   sample;
0587     int err;
0588 
0589     if (test_bit(0, indio_dev->active_scan_mask)) {
0590         /* Get current pressure from hardware FIFO. */
0591         err = zpa2326_dequeue_pressure(indio_dev, &sample.pressure);
0592         if (err) {
0593             zpa2326_warn(indio_dev, "failed to fetch pressure (%d)",
0594                      err);
0595             return err;
0596         }
0597     }
0598 
0599     if (test_bit(1, indio_dev->active_scan_mask)) {
0600         /* Get current temperature. */
0601         err = regmap_bulk_read(private->regmap, ZPA2326_TEMP_OUT_L_REG,
0602                        &sample.temperature, 2);
0603         if (err) {
0604             zpa2326_warn(indio_dev,
0605                      "failed to fetch temperature (%d)", err);
0606             return err;
0607         }
0608     }
0609 
0610     /*
0611      * Now push samples using timestamp stored either :
0612      *   - by hardware interrupt handler if interrupt is available: see
0613      *     zpa2326_handle_irq(),
0614      *   - or oneshot completion polling machinery : see
0615      *     zpa2326_trigger_handler().
0616      */
0617     zpa2326_dbg(indio_dev, "filling raw samples buffer");
0618 
0619     iio_push_to_buffers_with_timestamp(indio_dev, &sample,
0620                        private->timestamp);
0621 
0622     return 0;
0623 }
0624 
0625 #ifdef CONFIG_PM
0626 static int zpa2326_runtime_suspend(struct device *parent)
0627 {
0628     const struct iio_dev *indio_dev = dev_get_drvdata(parent);
0629 
0630     if (pm_runtime_autosuspend_expiration(parent))
0631         /* Userspace changed autosuspend delay. */
0632         return -EAGAIN;
0633 
0634     zpa2326_power_off(indio_dev, iio_priv(indio_dev));
0635 
0636     return 0;
0637 }
0638 
0639 static int zpa2326_runtime_resume(struct device *parent)
0640 {
0641     const struct iio_dev *indio_dev = dev_get_drvdata(parent);
0642 
0643     return zpa2326_power_on(indio_dev, iio_priv(indio_dev));
0644 }
0645 
0646 const struct dev_pm_ops zpa2326_pm_ops = {
0647     SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
0648                 pm_runtime_force_resume)
0649     SET_RUNTIME_PM_OPS(zpa2326_runtime_suspend, zpa2326_runtime_resume,
0650                NULL)
0651 };
0652 EXPORT_SYMBOL_NS_GPL(zpa2326_pm_ops, IIO_ZPA2326);
0653 
0654 /**
0655  * zpa2326_resume() - Request the PM layer to power supply the device.
0656  * @indio_dev: The IIO device associated with the sampling hardware.
0657  *
0658  * Return:
0659  *  < 0 - a negative error code meaning failure ;
0660  *    0 - success, device has just been powered up ;
0661  *    1 - success, device was already powered.
0662  */
0663 static int zpa2326_resume(const struct iio_dev *indio_dev)
0664 {
0665     int err;
0666 
0667     err = pm_runtime_get_sync(indio_dev->dev.parent);
0668     if (err < 0) {
0669         pm_runtime_put(indio_dev->dev.parent);
0670         return err;
0671     }
0672 
0673     if (err > 0) {
0674         /*
0675          * Device was already power supplied: get it out of low power
0676          * mode and inform caller.
0677          */
0678         zpa2326_enable_device(indio_dev);
0679         return 1;
0680     }
0681 
0682     /* Inform caller device has just been brought back to life. */
0683     return 0;
0684 }
0685 
0686 /**
0687  * zpa2326_suspend() - Schedule a power down using autosuspend feature of PM
0688  *                     layer.
0689  * @indio_dev: The IIO device associated with the sampling hardware.
0690  *
0691  * Device is switched to low power mode at first to save power even when
0692  * attached regulator is a "dummy" one.
0693  */
0694 static void zpa2326_suspend(struct iio_dev *indio_dev)
0695 {
0696     struct device *parent = indio_dev->dev.parent;
0697 
0698     zpa2326_sleep(indio_dev);
0699 
0700     pm_runtime_mark_last_busy(parent);
0701     pm_runtime_put_autosuspend(parent);
0702 }
0703 
0704 static void zpa2326_init_runtime(struct device *parent)
0705 {
0706     pm_runtime_get_noresume(parent);
0707     pm_runtime_set_active(parent);
0708     pm_runtime_enable(parent);
0709     pm_runtime_set_autosuspend_delay(parent, 1000);
0710     pm_runtime_use_autosuspend(parent);
0711     pm_runtime_mark_last_busy(parent);
0712     pm_runtime_put_autosuspend(parent);
0713 }
0714 
0715 static void zpa2326_fini_runtime(struct device *parent)
0716 {
0717     pm_runtime_disable(parent);
0718     pm_runtime_set_suspended(parent);
0719 }
0720 #else /* !CONFIG_PM */
0721 static int zpa2326_resume(const struct iio_dev *indio_dev)
0722 {
0723     zpa2326_enable_device(indio_dev);
0724 
0725     return 0;
0726 }
0727 
0728 static void zpa2326_suspend(struct iio_dev *indio_dev)
0729 {
0730     zpa2326_sleep(indio_dev);
0731 }
0732 
0733 #define zpa2326_init_runtime(_parent)
0734 #define zpa2326_fini_runtime(_parent)
0735 #endif /* !CONFIG_PM */
0736 
0737 /**
0738  * zpa2326_handle_irq() - Process hardware interrupts.
0739  * @irq:  Interrupt line the hardware uses to notify new data has arrived.
0740  * @data: The IIO device associated with the sampling hardware.
0741  *
0742  * Timestamp buffered samples as soon as possible then schedule threaded bottom
0743  * half.
0744  *
0745  * Return: Always successful.
0746  */
0747 static irqreturn_t zpa2326_handle_irq(int irq, void *data)
0748 {
0749     struct iio_dev *indio_dev = data;
0750 
0751     if (iio_buffer_enabled(indio_dev)) {
0752         /* Timestamping needed for buffered sampling only. */
0753         ((struct zpa2326_private *)
0754          iio_priv(indio_dev))->timestamp = iio_get_time_ns(indio_dev);
0755     }
0756 
0757     return IRQ_WAKE_THREAD;
0758 }
0759 
0760 /**
0761  * zpa2326_handle_threaded_irq() - Interrupt bottom-half handler.
0762  * @irq:  Interrupt line the hardware uses to notify new data has arrived.
0763  * @data: The IIO device associated with the sampling hardware.
0764  *
0765  * Mainly ensures interrupt is caused by a real "new sample available"
0766  * condition. This relies upon the ability to perform blocking / sleeping bus
0767  * accesses to slave's registers. This is why zpa2326_handle_threaded_irq() is
0768  * called from within a thread, i.e. not called from hard interrupt context.
0769  *
0770  * When device is using its own internal hardware trigger in continuous sampling
0771  * mode, data are available into hardware FIFO once interrupt has occurred. All
0772  * we have to do is to dispatch the trigger, which in turn will fetch data and
0773  * fill IIO buffer.
0774  *
0775  * When not using its own internal hardware trigger, the device has been
0776  * configured in one-shot mode either by an external trigger or the IIO read_raw
0777  * hook. This means one of the latter is currently waiting for sampling
0778  * completion, in which case we must simply wake it up.
0779  *
0780  * See zpa2326_trigger_handler().
0781  *
0782  * Return:
0783  *   %IRQ_NONE - no consistent interrupt happened ;
0784  *   %IRQ_HANDLED - there was new samples available.
0785  */
0786 static irqreturn_t zpa2326_handle_threaded_irq(int irq, void *data)
0787 {
0788     struct iio_dev         *indio_dev = data;
0789     struct zpa2326_private *priv = iio_priv(indio_dev);
0790     unsigned int            val;
0791     bool                    cont;
0792     irqreturn_t             ret = IRQ_NONE;
0793 
0794     /*
0795      * Are we using our own internal trigger in triggered buffer mode, i.e.,
0796      * currently working in continuous sampling mode ?
0797      */
0798     cont = (iio_buffer_enabled(indio_dev) &&
0799         iio_trigger_using_own(indio_dev));
0800 
0801     /*
0802      * Device works according to a level interrupt scheme: reading interrupt
0803      * status de-asserts interrupt line.
0804      */
0805     priv->result = regmap_read(priv->regmap, ZPA2326_INT_SOURCE_REG, &val);
0806     if (priv->result < 0) {
0807         if (cont)
0808             return IRQ_NONE;
0809 
0810         goto complete;
0811     }
0812 
0813     /* Data ready is the only interrupt source we requested. */
0814     if (!(val & ZPA2326_INT_SOURCE_DATA_READY)) {
0815         /*
0816          * Interrupt happened but no new sample available: likely caused
0817          * by spurious interrupts, in which case, returning IRQ_NONE
0818          * allows to benefit from the generic spurious interrupts
0819          * handling.
0820          */
0821         zpa2326_warn(indio_dev, "unexpected interrupt status %02x",
0822                  val);
0823 
0824         if (cont)
0825             return IRQ_NONE;
0826 
0827         priv->result = -ENODATA;
0828         goto complete;
0829     }
0830 
0831     /* New sample available: dispatch internal trigger consumers. */
0832     iio_trigger_poll_chained(priv->trigger);
0833 
0834     if (cont)
0835         /*
0836          * Internal hardware trigger has been scheduled above : it will
0837          * fetch data on its own.
0838          */
0839         return IRQ_HANDLED;
0840 
0841     ret = IRQ_HANDLED;
0842 
0843 complete:
0844     /*
0845      * Wake up direct or externaly triggered buffer mode waiters: see
0846      * zpa2326_sample_oneshot() and zpa2326_trigger_handler().
0847      */
0848     complete(&priv->data_ready);
0849 
0850     return ret;
0851 }
0852 
0853 /**
0854  * zpa2326_wait_oneshot_completion() - Wait for oneshot data ready interrupt.
0855  * @indio_dev: The IIO device associated with the sampling hardware.
0856  * @private:   Internal private state related to @indio_dev.
0857  *
0858  * Return: Zero when successful, a negative error code otherwise.
0859  */
0860 static int zpa2326_wait_oneshot_completion(const struct iio_dev   *indio_dev,
0861                        struct zpa2326_private *private)
0862 {
0863     unsigned int val;
0864     long     timeout;
0865 
0866     zpa2326_dbg(indio_dev, "waiting for one shot completion interrupt");
0867 
0868     timeout = wait_for_completion_interruptible_timeout(
0869         &private->data_ready, ZPA2326_CONVERSION_JIFFIES);
0870     if (timeout > 0)
0871         /*
0872          * Interrupt handler completed before timeout: return operation
0873          * status.
0874          */
0875         return private->result;
0876 
0877     /* Clear all interrupts just to be sure. */
0878     regmap_read(private->regmap, ZPA2326_INT_SOURCE_REG, &val);
0879 
0880     if (!timeout) {
0881         /* Timed out. */
0882         zpa2326_warn(indio_dev, "no one shot interrupt occurred (%ld)",
0883                  timeout);
0884         return -ETIME;
0885     }
0886 
0887     zpa2326_warn(indio_dev, "wait for one shot interrupt cancelled");
0888     return -ERESTARTSYS;
0889 }
0890 
0891 static int zpa2326_init_managed_irq(struct device          *parent,
0892                     struct iio_dev         *indio_dev,
0893                     struct zpa2326_private *private,
0894                     int                     irq)
0895 {
0896     int err;
0897 
0898     private->irq = irq;
0899 
0900     if (irq <= 0) {
0901         /*
0902          * Platform declared no interrupt line: device will be polled
0903          * for data availability.
0904          */
0905         dev_info(parent, "no interrupt found, running in polling mode");
0906         return 0;
0907     }
0908 
0909     init_completion(&private->data_ready);
0910 
0911     /* Request handler to be scheduled into threaded interrupt context. */
0912     err = devm_request_threaded_irq(parent, irq, zpa2326_handle_irq,
0913                     zpa2326_handle_threaded_irq,
0914                     IRQF_TRIGGER_RISING | IRQF_ONESHOT,
0915                     dev_name(parent), indio_dev);
0916     if (err) {
0917         dev_err(parent, "failed to request interrupt %d (%d)", irq,
0918             err);
0919         return err;
0920     }
0921 
0922     dev_info(parent, "using interrupt %d", irq);
0923 
0924     return 0;
0925 }
0926 
0927 /**
0928  * zpa2326_poll_oneshot_completion() - Actively poll for one shot data ready.
0929  * @indio_dev: The IIO device associated with the sampling hardware.
0930  *
0931  * Loop over registers content to detect end of sampling cycle. Used when DT
0932  * declared no valid interrupt lines.
0933  *
0934  * Return: Zero when successful, a negative error code otherwise.
0935  */
0936 static int zpa2326_poll_oneshot_completion(const struct iio_dev *indio_dev)
0937 {
0938     unsigned long  tmout = jiffies + ZPA2326_CONVERSION_JIFFIES;
0939     struct regmap *regs = ((struct zpa2326_private *)
0940                    iio_priv(indio_dev))->regmap;
0941     unsigned int   val;
0942     int            err;
0943 
0944     zpa2326_dbg(indio_dev, "polling for one shot completion");
0945 
0946     /*
0947      * At least, 100 ms is needed for the device to complete its one-shot
0948      * cycle.
0949      */
0950     if (msleep_interruptible(100))
0951         return -ERESTARTSYS;
0952 
0953     /* Poll for conversion completion in hardware. */
0954     while (true) {
0955         err = regmap_read(regs, ZPA2326_CTRL_REG0_REG, &val);
0956         if (err < 0)
0957             goto err;
0958 
0959         if (!(val & ZPA2326_CTRL_REG0_ONE_SHOT))
0960             /* One-shot bit self clears at conversion end. */
0961             break;
0962 
0963         if (time_after(jiffies, tmout)) {
0964             /* Prevent from waiting forever : let's time out. */
0965             err = -ETIME;
0966             goto err;
0967         }
0968 
0969         usleep_range(10000, 20000);
0970     }
0971 
0972     /*
0973      * In oneshot mode, pressure sample availability guarantees that
0974      * temperature conversion has also completed : just check pressure
0975      * status bit to keep things simple.
0976      */
0977     err = regmap_read(regs, ZPA2326_STATUS_REG, &val);
0978     if (err < 0)
0979         goto err;
0980 
0981     if (!(val & ZPA2326_STATUS_P_DA)) {
0982         /* No sample available. */
0983         err = -ENODATA;
0984         goto err;
0985     }
0986 
0987     return 0;
0988 
0989 err:
0990     zpa2326_warn(indio_dev, "failed to poll one shot completion (%d)", err);
0991 
0992     return err;
0993 }
0994 
0995 /**
0996  * zpa2326_fetch_raw_sample() - Retrieve a raw sample and convert it to CPU
0997  *                              endianness.
0998  * @indio_dev: The IIO device associated with the sampling hardware.
0999  * @type:      Type of measurement / channel to fetch from.
1000  * @value:     Sample output.
1001  *
1002  * Return: Zero when successful, a negative error code otherwise.
1003  */
1004 static int zpa2326_fetch_raw_sample(const struct iio_dev *indio_dev,
1005                     enum iio_chan_type    type,
1006                     int                  *value)
1007 {
1008     struct regmap *regs = ((struct zpa2326_private *)
1009                    iio_priv(indio_dev))->regmap;
1010     int            err;
1011     u8             v[3];
1012 
1013     switch (type) {
1014     case IIO_PRESSURE:
1015         zpa2326_dbg(indio_dev, "fetching raw pressure sample");
1016 
1017         err = regmap_bulk_read(regs, ZPA2326_PRESS_OUT_XL_REG, v, sizeof(v));
1018         if (err) {
1019             zpa2326_warn(indio_dev, "failed to fetch pressure (%d)",
1020                      err);
1021             return err;
1022         }
1023 
1024         *value = get_unaligned_le24(&v[0]);
1025 
1026         return IIO_VAL_INT;
1027 
1028     case IIO_TEMP:
1029         zpa2326_dbg(indio_dev, "fetching raw temperature sample");
1030 
1031         err = regmap_bulk_read(regs, ZPA2326_TEMP_OUT_L_REG, value, 2);
1032         if (err) {
1033             zpa2326_warn(indio_dev,
1034                      "failed to fetch temperature (%d)", err);
1035             return err;
1036         }
1037 
1038         /* Temperature is a 16 bits wide little-endian signed int. */
1039         *value = (int)le16_to_cpup((__le16 *)value);
1040 
1041         return IIO_VAL_INT;
1042 
1043     default:
1044         return -EINVAL;
1045     }
1046 }
1047 
1048 /**
1049  * zpa2326_sample_oneshot() - Perform a complete one shot sampling cycle.
1050  * @indio_dev: The IIO device associated with the sampling hardware.
1051  * @type:      Type of measurement / channel to fetch from.
1052  * @value:     Sample output.
1053  *
1054  * Return: Zero when successful, a negative error code otherwise.
1055  */
1056 static int zpa2326_sample_oneshot(struct iio_dev     *indio_dev,
1057                   enum iio_chan_type  type,
1058                   int                *value)
1059 {
1060     int                     ret;
1061     struct zpa2326_private *priv;
1062 
1063     ret = iio_device_claim_direct_mode(indio_dev);
1064     if (ret)
1065         return ret;
1066 
1067     ret = zpa2326_resume(indio_dev);
1068     if (ret < 0)
1069         goto release;
1070 
1071     priv = iio_priv(indio_dev);
1072 
1073     if (ret > 0) {
1074         /*
1075          * We were already power supplied. Just clear hardware FIFO to
1076          * get rid of samples acquired during previous rounds (if any).
1077          * Sampling operation always generates both temperature and
1078          * pressure samples. The latter are always enqueued into
1079          * hardware FIFO. This may lead to situations were pressure
1080          * samples still sit into FIFO when previous cycle(s) fetched
1081          * temperature data only.
1082          * Hence, we need to clear hardware FIFO content to prevent from
1083          * getting outdated values at the end of current cycle.
1084          */
1085         if (type == IIO_PRESSURE) {
1086             ret = zpa2326_clear_fifo(indio_dev, 0);
1087             if (ret)
1088                 goto suspend;
1089         }
1090     } else {
1091         /*
1092          * We have just been power supplied, i.e. device is in default
1093          * "out of reset" state, meaning we need to reconfigure it
1094          * entirely.
1095          */
1096         ret = zpa2326_config_oneshot(indio_dev, priv->irq);
1097         if (ret)
1098             goto suspend;
1099     }
1100 
1101     /* Start a sampling cycle in oneshot mode. */
1102     ret = zpa2326_start_oneshot(indio_dev);
1103     if (ret)
1104         goto suspend;
1105 
1106     /* Wait for sampling cycle to complete. */
1107     if (priv->irq > 0)
1108         ret = zpa2326_wait_oneshot_completion(indio_dev, priv);
1109     else
1110         ret = zpa2326_poll_oneshot_completion(indio_dev);
1111 
1112     if (ret)
1113         goto suspend;
1114 
1115     /* Retrieve raw sample value and convert it to CPU endianness. */
1116     ret = zpa2326_fetch_raw_sample(indio_dev, type, value);
1117 
1118 suspend:
1119     zpa2326_suspend(indio_dev);
1120 release:
1121     iio_device_release_direct_mode(indio_dev);
1122 
1123     return ret;
1124 }
1125 
1126 /**
1127  * zpa2326_trigger_handler() - Perform an IIO buffered sampling round in one
1128  *                             shot mode.
1129  * @irq:  The software interrupt assigned to @data
1130  * @data: The IIO poll function dispatched by external trigger our device is
1131  *        attached to.
1132  *
1133  * Bottom-half handler called by the IIO trigger to which our device is
1134  * currently attached. Allows us to synchronize this device buffered sampling
1135  * either with external events (such as timer expiration, external device sample
1136  * ready, etc...) or with its own interrupt (internal hardware trigger).
1137  *
1138  * When using an external trigger, basically run the same sequence of operations
1139  * as for zpa2326_sample_oneshot() with the following hereafter. Hardware FIFO
1140  * is not cleared since already done at buffering enable time and samples
1141  * dequeueing always retrieves the most recent value.
1142  *
1143  * Otherwise, when internal hardware trigger has dispatched us, just fetch data
1144  * from hardware FIFO.
1145  *
1146  * Fetched data will pushed unprocessed to IIO buffer since samples conversion
1147  * is delegated to userspace in buffered mode (endianness, etc...).
1148  *
1149  * Return:
1150  *   %IRQ_NONE - no consistent interrupt happened ;
1151  *   %IRQ_HANDLED - there was new samples available.
1152  */
1153 static irqreturn_t zpa2326_trigger_handler(int irq, void *data)
1154 {
1155     struct iio_dev         *indio_dev = ((struct iio_poll_func *)
1156                          data)->indio_dev;
1157     struct zpa2326_private *priv = iio_priv(indio_dev);
1158     bool                    cont;
1159 
1160     /*
1161      * We have been dispatched, meaning we are in triggered buffer mode.
1162      * Using our own internal trigger implies we are currently in continuous
1163      * hardware sampling mode.
1164      */
1165     cont = iio_trigger_using_own(indio_dev);
1166 
1167     if (!cont) {
1168         /* On demand sampling : start a one shot cycle. */
1169         if (zpa2326_start_oneshot(indio_dev))
1170             goto out;
1171 
1172         /* Wait for sampling cycle to complete. */
1173         if (priv->irq <= 0) {
1174             /* No interrupt available: poll for completion. */
1175             if (zpa2326_poll_oneshot_completion(indio_dev))
1176                 goto out;
1177 
1178             /* Only timestamp sample once it is ready. */
1179             priv->timestamp = iio_get_time_ns(indio_dev);
1180         } else {
1181             /* Interrupt handlers will timestamp for us. */
1182             if (zpa2326_wait_oneshot_completion(indio_dev, priv))
1183                 goto out;
1184         }
1185     }
1186 
1187     /* Enqueue to IIO buffer / userspace. */
1188     zpa2326_fill_sample_buffer(indio_dev, priv);
1189 
1190 out:
1191     if (!cont)
1192         /* Don't switch to low power if sampling continuously. */
1193         zpa2326_sleep(indio_dev);
1194 
1195     /* Inform attached trigger we are done. */
1196     iio_trigger_notify_done(indio_dev->trig);
1197 
1198     return IRQ_HANDLED;
1199 }
1200 
1201 /**
1202  * zpa2326_preenable_buffer() - Prepare device for configuring triggered
1203  *                              sampling
1204  * modes.
1205  * @indio_dev: The IIO device associated with the sampling hardware.
1206  *
1207  * Basically power up device.
1208  * Called with IIO device's lock held.
1209  *
1210  * Return: Zero when successful, a negative error code otherwise.
1211  */
1212 static int zpa2326_preenable_buffer(struct iio_dev *indio_dev)
1213 {
1214     int ret = zpa2326_resume(indio_dev);
1215 
1216     if (ret < 0)
1217         return ret;
1218 
1219     /* Tell zpa2326_postenable_buffer() if we have just been powered on. */
1220     ((struct zpa2326_private *)
1221      iio_priv(indio_dev))->waken = iio_priv(indio_dev);
1222 
1223     return 0;
1224 }
1225 
1226 /**
1227  * zpa2326_postenable_buffer() - Configure device for triggered sampling.
1228  * @indio_dev: The IIO device associated with the sampling hardware.
1229  *
1230  * Basically setup one-shot mode if plugging external trigger.
1231  * Otherwise, let internal trigger configure continuous sampling :
1232  * see zpa2326_set_trigger_state().
1233  *
1234  * If an error is returned, IIO layer will call our postdisable hook for us,
1235  * i.e. no need to explicitly power device off here.
1236  * Called with IIO device's lock held.
1237  *
1238  * Called with IIO device's lock held.
1239  *
1240  * Return: Zero when successful, a negative error code otherwise.
1241  */
1242 static int zpa2326_postenable_buffer(struct iio_dev *indio_dev)
1243 {
1244     const struct zpa2326_private *priv = iio_priv(indio_dev);
1245     int                           err;
1246 
1247     if (!priv->waken) {
1248         /*
1249          * We were already power supplied. Just clear hardware FIFO to
1250          * get rid of samples acquired during previous rounds (if any).
1251          */
1252         err = zpa2326_clear_fifo(indio_dev, 0);
1253         if (err) {
1254             zpa2326_err(indio_dev,
1255                     "failed to enable buffering (%d)", err);
1256             return err;
1257         }
1258     }
1259 
1260     if (!iio_trigger_using_own(indio_dev) && priv->waken) {
1261         /*
1262          * We are using an external trigger and we have just been
1263          * powered up: reconfigure one-shot mode.
1264          */
1265         err = zpa2326_config_oneshot(indio_dev, priv->irq);
1266         if (err) {
1267             zpa2326_err(indio_dev,
1268                     "failed to enable buffering (%d)", err);
1269             return err;
1270         }
1271     }
1272 
1273     return 0;
1274 }
1275 
1276 static int zpa2326_postdisable_buffer(struct iio_dev *indio_dev)
1277 {
1278     zpa2326_suspend(indio_dev);
1279 
1280     return 0;
1281 }
1282 
1283 static const struct iio_buffer_setup_ops zpa2326_buffer_setup_ops = {
1284     .preenable   = zpa2326_preenable_buffer,
1285     .postenable  = zpa2326_postenable_buffer,
1286     .postdisable = zpa2326_postdisable_buffer
1287 };
1288 
1289 /**
1290  * zpa2326_set_trigger_state() - Start / stop continuous sampling.
1291  * @trig:  The trigger being attached to IIO device associated with the sampling
1292  *         hardware.
1293  * @state: Tell whether to start (true) or stop (false)
1294  *
1295  * Basically enable / disable hardware continuous sampling mode.
1296  *
1297  * Called with IIO device's lock held at postenable() or predisable() time.
1298  *
1299  * Return: Zero when successful, a negative error code otherwise.
1300  */
1301 static int zpa2326_set_trigger_state(struct iio_trigger *trig, bool state)
1302 {
1303     const struct iio_dev         *indio_dev = dev_get_drvdata(
1304                             trig->dev.parent);
1305     const struct zpa2326_private *priv = iio_priv(indio_dev);
1306     int                           err;
1307 
1308     if (!state) {
1309         /*
1310          * Switch trigger off : in case of failure, interrupt is left
1311          * disabled in order to prevent handler from accessing released
1312          * resources.
1313          */
1314         unsigned int val;
1315 
1316         /*
1317          * As device is working in continuous mode, handlers may be
1318          * accessing resources we are currently freeing...
1319          * Prevent this by disabling interrupt handlers and ensure
1320          * the device will generate no more interrupts unless explicitly
1321          * required to, i.e. by restoring back to default one shot mode.
1322          */
1323         disable_irq(priv->irq);
1324 
1325         /*
1326          * Disable continuous sampling mode to restore settings for
1327          * one shot / direct sampling operations.
1328          */
1329         err = regmap_write(priv->regmap, ZPA2326_CTRL_REG3_REG,
1330                    zpa2326_highest_frequency()->odr);
1331         if (err)
1332             return err;
1333 
1334         /*
1335          * Now that device won't generate interrupts on its own,
1336          * acknowledge any currently active interrupts (may happen on
1337          * rare occasions while stopping continuous mode).
1338          */
1339         err = regmap_read(priv->regmap, ZPA2326_INT_SOURCE_REG, &val);
1340         if (err < 0)
1341             return err;
1342 
1343         /*
1344          * Re-enable interrupts only if we can guarantee the device will
1345          * generate no more interrupts to prevent handlers from
1346          * accessing released resources.
1347          */
1348         enable_irq(priv->irq);
1349 
1350         zpa2326_dbg(indio_dev, "continuous mode stopped");
1351     } else {
1352         /*
1353          * Switch trigger on : start continuous sampling at required
1354          * frequency.
1355          */
1356 
1357         if (priv->waken) {
1358             /* Enable interrupt if getting out of reset. */
1359             err = regmap_write(priv->regmap, ZPA2326_CTRL_REG1_REG,
1360                        (u8)
1361                        ~ZPA2326_CTRL_REG1_MASK_DATA_READY);
1362             if (err)
1363                 return err;
1364         }
1365 
1366         /* Enable continuous sampling at specified frequency. */
1367         err = regmap_write(priv->regmap, ZPA2326_CTRL_REG3_REG,
1368                    ZPA2326_CTRL_REG3_ENABLE_MEAS |
1369                    priv->frequency->odr);
1370         if (err)
1371             return err;
1372 
1373         zpa2326_dbg(indio_dev, "continuous mode setup @%dHz",
1374                 priv->frequency->hz);
1375     }
1376 
1377     return 0;
1378 }
1379 
1380 static const struct iio_trigger_ops zpa2326_trigger_ops = {
1381     .set_trigger_state = zpa2326_set_trigger_state,
1382 };
1383 
1384 /**
1385  * zpa2326_init_managed_trigger() - Create interrupt driven / hardware trigger
1386  *                          allowing to notify external devices a new sample is
1387  *                          ready.
1388  * @parent:    Hardware sampling device @indio_dev is a child of.
1389  * @indio_dev: The IIO device associated with the sampling hardware.
1390  * @private:   Internal private state related to @indio_dev.
1391  * @irq:       Optional interrupt line the hardware uses to notify new data
1392  *             samples are ready. Negative or zero values indicate no interrupts
1393  *             are available, meaning polling is required.
1394  *
1395  * Only relevant when DT declares a valid interrupt line.
1396  *
1397  * Return: Zero when successful, a negative error code otherwise.
1398  */
1399 static int zpa2326_init_managed_trigger(struct device          *parent,
1400                     struct iio_dev         *indio_dev,
1401                     struct zpa2326_private *private,
1402                     int                     irq)
1403 {
1404     struct iio_trigger *trigger;
1405     int                 ret;
1406 
1407     if (irq <= 0)
1408         return 0;
1409 
1410     trigger = devm_iio_trigger_alloc(parent, "%s-dev%d",
1411                      indio_dev->name,
1412                      iio_device_id(indio_dev));
1413     if (!trigger)
1414         return -ENOMEM;
1415 
1416     /* Basic setup. */
1417     trigger->ops = &zpa2326_trigger_ops;
1418 
1419     private->trigger = trigger;
1420 
1421     /* Register to triggers space. */
1422     ret = devm_iio_trigger_register(parent, trigger);
1423     if (ret)
1424         dev_err(parent, "failed to register hardware trigger (%d)",
1425             ret);
1426 
1427     return ret;
1428 }
1429 
1430 static int zpa2326_get_frequency(const struct iio_dev *indio_dev)
1431 {
1432     return ((struct zpa2326_private *)iio_priv(indio_dev))->frequency->hz;
1433 }
1434 
1435 static int zpa2326_set_frequency(struct iio_dev *indio_dev, int hz)
1436 {
1437     struct zpa2326_private *priv = iio_priv(indio_dev);
1438     int                     freq;
1439     int                     err;
1440 
1441     /* Check if requested frequency is supported. */
1442     for (freq = 0; freq < ARRAY_SIZE(zpa2326_sampling_frequencies); freq++)
1443         if (zpa2326_sampling_frequencies[freq].hz == hz)
1444             break;
1445     if (freq == ARRAY_SIZE(zpa2326_sampling_frequencies))
1446         return -EINVAL;
1447 
1448     /* Don't allow changing frequency if buffered sampling is ongoing. */
1449     err = iio_device_claim_direct_mode(indio_dev);
1450     if (err)
1451         return err;
1452 
1453     priv->frequency = &zpa2326_sampling_frequencies[freq];
1454 
1455     iio_device_release_direct_mode(indio_dev);
1456 
1457     return 0;
1458 }
1459 
1460 /* Expose supported hardware sampling frequencies (Hz) through sysfs. */
1461 static IIO_CONST_ATTR_SAMP_FREQ_AVAIL("1 5 11 23");
1462 
1463 static struct attribute *zpa2326_attributes[] = {
1464     &iio_const_attr_sampling_frequency_available.dev_attr.attr,
1465     NULL
1466 };
1467 
1468 static const struct attribute_group zpa2326_attribute_group = {
1469     .attrs = zpa2326_attributes,
1470 };
1471 
1472 static int zpa2326_read_raw(struct iio_dev             *indio_dev,
1473                 struct iio_chan_spec const *chan,
1474                 int                        *val,
1475                 int                        *val2,
1476                 long                        mask)
1477 {
1478     switch (mask) {
1479     case IIO_CHAN_INFO_RAW:
1480         return zpa2326_sample_oneshot(indio_dev, chan->type, val);
1481 
1482     case IIO_CHAN_INFO_SCALE:
1483         switch (chan->type) {
1484         case IIO_PRESSURE:
1485             /*
1486              * Pressure resolution is 1/64 Pascal. Scale to kPascal
1487              * as required by IIO ABI.
1488              */
1489             *val = 1;
1490             *val2 = 64000;
1491             return IIO_VAL_FRACTIONAL;
1492 
1493         case IIO_TEMP:
1494             /*
1495              * Temperature follows the equation:
1496              *     Temp[degC] = Tempcode * 0.00649 - 176.83
1497              * where:
1498              *     Tempcode is composed the raw sampled 16 bits.
1499              *
1500              * Hence, to produce a temperature in milli-degrees
1501              * Celsius according to IIO ABI, we need to apply the
1502              * following equation to raw samples:
1503              *     Temp[milli degC] = (Tempcode + Offset) * Scale
1504              * where:
1505              *     Offset = -176.83 / 0.00649
1506              *     Scale = 0.00649 * 1000
1507              */
1508             *val = 6;
1509             *val2 = 490000;
1510             return IIO_VAL_INT_PLUS_MICRO;
1511 
1512         default:
1513             return -EINVAL;
1514         }
1515 
1516     case IIO_CHAN_INFO_OFFSET:
1517         switch (chan->type) {
1518         case IIO_TEMP:
1519             *val = -17683000;
1520             *val2 = 649;
1521             return IIO_VAL_FRACTIONAL;
1522 
1523         default:
1524             return -EINVAL;
1525         }
1526 
1527     case IIO_CHAN_INFO_SAMP_FREQ:
1528         *val = zpa2326_get_frequency(indio_dev);
1529         return IIO_VAL_INT;
1530 
1531     default:
1532         return -EINVAL;
1533     }
1534 }
1535 
1536 static int zpa2326_write_raw(struct iio_dev             *indio_dev,
1537                  const struct iio_chan_spec *chan,
1538                  int                         val,
1539                  int                         val2,
1540                  long                        mask)
1541 {
1542     if ((mask != IIO_CHAN_INFO_SAMP_FREQ) || val2)
1543         return -EINVAL;
1544 
1545     return zpa2326_set_frequency(indio_dev, val);
1546 }
1547 
1548 static const struct iio_chan_spec zpa2326_channels[] = {
1549     [0] = {
1550         .type                    = IIO_PRESSURE,
1551         .scan_index              = 0,
1552         .scan_type               = {
1553             .sign                   = 'u',
1554             .realbits               = 24,
1555             .storagebits            = 32,
1556             .endianness             = IIO_LE,
1557         },
1558         .info_mask_separate      = BIT(IIO_CHAN_INFO_RAW) |
1559                        BIT(IIO_CHAN_INFO_SCALE),
1560         .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ),
1561     },
1562     [1] = {
1563         .type                    = IIO_TEMP,
1564         .scan_index              = 1,
1565         .scan_type               = {
1566             .sign                   = 's',
1567             .realbits               = 16,
1568             .storagebits            = 16,
1569             .endianness             = IIO_LE,
1570         },
1571         .info_mask_separate      = BIT(IIO_CHAN_INFO_RAW) |
1572                        BIT(IIO_CHAN_INFO_SCALE) |
1573                        BIT(IIO_CHAN_INFO_OFFSET),
1574         .info_mask_shared_by_all = BIT(IIO_CHAN_INFO_SAMP_FREQ),
1575     },
1576     [2] = IIO_CHAN_SOFT_TIMESTAMP(2),
1577 };
1578 
1579 static const struct iio_info zpa2326_info = {
1580     .attrs         = &zpa2326_attribute_group,
1581     .read_raw      = zpa2326_read_raw,
1582     .write_raw     = zpa2326_write_raw,
1583 };
1584 
1585 static struct iio_dev *zpa2326_create_managed_iiodev(struct device *device,
1586                              const char    *name,
1587                              struct regmap *regmap)
1588 {
1589     struct iio_dev *indio_dev;
1590 
1591     /* Allocate space to hold IIO device internal state. */
1592     indio_dev = devm_iio_device_alloc(device,
1593                       sizeof(struct zpa2326_private));
1594     if (!indio_dev)
1595         return NULL;
1596 
1597     /* Setup for userspace synchronous on demand sampling. */
1598     indio_dev->modes = INDIO_DIRECT_MODE;
1599     indio_dev->channels = zpa2326_channels;
1600     indio_dev->num_channels = ARRAY_SIZE(zpa2326_channels);
1601     indio_dev->name = name;
1602     indio_dev->info = &zpa2326_info;
1603 
1604     return indio_dev;
1605 }
1606 
1607 int zpa2326_probe(struct device *parent,
1608           const char    *name,
1609           int            irq,
1610           unsigned int   hwid,
1611           struct regmap *regmap)
1612 {
1613     struct iio_dev         *indio_dev;
1614     struct zpa2326_private *priv;
1615     int                     err;
1616     unsigned int            id;
1617 
1618     indio_dev = zpa2326_create_managed_iiodev(parent, name, regmap);
1619     if (!indio_dev)
1620         return -ENOMEM;
1621 
1622     priv = iio_priv(indio_dev);
1623 
1624     priv->vref = devm_regulator_get(parent, "vref");
1625     if (IS_ERR(priv->vref))
1626         return PTR_ERR(priv->vref);
1627 
1628     priv->vdd = devm_regulator_get(parent, "vdd");
1629     if (IS_ERR(priv->vdd))
1630         return PTR_ERR(priv->vdd);
1631 
1632     /* Set default hardware sampling frequency to highest rate supported. */
1633     priv->frequency = zpa2326_highest_frequency();
1634 
1635     /*
1636      * Plug device's underlying bus abstraction : this MUST be set before
1637      * registering interrupt handlers since an interrupt might happen if
1638      * power up sequence is not properly applied.
1639      */
1640     priv->regmap = regmap;
1641 
1642     err = devm_iio_triggered_buffer_setup(parent, indio_dev, NULL,
1643                           zpa2326_trigger_handler,
1644                           &zpa2326_buffer_setup_ops);
1645     if (err)
1646         return err;
1647 
1648     err = zpa2326_init_managed_trigger(parent, indio_dev, priv, irq);
1649     if (err)
1650         return err;
1651 
1652     err = zpa2326_init_managed_irq(parent, indio_dev, priv, irq);
1653     if (err)
1654         return err;
1655 
1656     /* Power up to check device ID and perform initial hardware setup. */
1657     err = zpa2326_power_on(indio_dev, priv);
1658     if (err)
1659         return err;
1660 
1661     /* Read id register to check we are talking to the right slave. */
1662     err = regmap_read(regmap, ZPA2326_DEVICE_ID_REG, &id);
1663     if (err)
1664         goto sleep;
1665 
1666     if (id != hwid) {
1667         dev_err(parent, "found device with unexpected id %02x", id);
1668         err = -ENODEV;
1669         goto sleep;
1670     }
1671 
1672     err = zpa2326_config_oneshot(indio_dev, irq);
1673     if (err)
1674         goto sleep;
1675 
1676     /* Setup done : go sleeping. Device will be awaken upon user request. */
1677     err = zpa2326_sleep(indio_dev);
1678     if (err)
1679         goto poweroff;
1680 
1681     dev_set_drvdata(parent, indio_dev);
1682 
1683     zpa2326_init_runtime(parent);
1684 
1685     err = iio_device_register(indio_dev);
1686     if (err) {
1687         zpa2326_fini_runtime(parent);
1688         goto poweroff;
1689     }
1690 
1691     return 0;
1692 
1693 sleep:
1694     /* Put to sleep just in case power regulators are "dummy" ones. */
1695     zpa2326_sleep(indio_dev);
1696 poweroff:
1697     zpa2326_power_off(indio_dev, priv);
1698 
1699     return err;
1700 }
1701 EXPORT_SYMBOL_NS_GPL(zpa2326_probe, IIO_ZPA2326);
1702 
1703 void zpa2326_remove(const struct device *parent)
1704 {
1705     struct iio_dev *indio_dev = dev_get_drvdata(parent);
1706 
1707     iio_device_unregister(indio_dev);
1708     zpa2326_fini_runtime(indio_dev->dev.parent);
1709     zpa2326_sleep(indio_dev);
1710     zpa2326_power_off(indio_dev, iio_priv(indio_dev));
1711 }
1712 EXPORT_SYMBOL_NS_GPL(zpa2326_remove, IIO_ZPA2326);
1713 
1714 MODULE_AUTHOR("Gregor Boirie <gregor.boirie@parrot.com>");
1715 MODULE_DESCRIPTION("Core driver for Murata ZPA2326 pressure sensor");
1716 MODULE_LICENSE("GPL v2");