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