brintos

brintos / linux-shallow public Read only

0
0
Text · 47.5 KiB · 950f8de Raw
1717 lines · c
1// SPDX-License-Identifier: GPL-2.0-only2/*3 * Murata ZPA2326 pressure and temperature sensor IIO driver4 *5 * Copyright (c) 2016 Parrot S.A.6 *7 * Author: Gregor Boirie <gregor.boirie@parrot.com>8 */9 10/**11 * DOC: ZPA2326 theory of operations12 *13 * This driver supports %INDIO_DIRECT_MODE and %INDIO_BUFFER_TRIGGERED IIO14 * modes.15 * A internal hardware trigger is also implemented to dispatch registered IIO16 * 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 switches22 * back to low power mode. It is meant for on demand sampling with optimal power23 * saving at the cost of lower sampling rate and higher software overhead.24 * This is a natural candidate for IIO read_raw hook implementation25 * (%INDIO_DIRECT_MODE). It is also used for triggered buffering support to26 * ensure explicit synchronization with external trigger events27 * (%INDIO_BUFFER_TRIGGERED).28 *29 * The continuous mode works according to a periodic hardware measurement30 * process continuously pushing samples into an internal hardware FIFO (for31 * pressure samples only). Measurement cycle completion may be signaled by a32 * "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 of37 *   hardware FIFO and fetch temperature sample38 * - when no longer needed, stop sampling process by putting device into39 *   low power mode.40 * This mode is used to implement %INDIO_BUFFER_TRIGGERED mode if device tree41 * declares a valid interrupt line. In this case, the internal hardware trigger42 * drives acquisition.43 *44 * Note that hardware sampling frequency is taken into account only when45 * internal hardware trigger is attached as the highest sampling rate seems to46 * 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 <linux/unaligned.h>68#include "zpa2326.h"69 70/* 200 ms should be enough for the longest conversion time in one-shot mode. */71#define ZPA2326_CONVERSION_JIFFIES (HZ / 5)72 73/* There should be a 1 ms delay (Tpup) after getting out of reset. */74#define ZPA2326_TPUP_USEC_MIN      (1000)75#define ZPA2326_TPUP_USEC_MAX      (2000)76 77/**78 * struct zpa2326_frequency - Hardware sampling frequency descriptor79 * @hz : Frequency in Hertz.80 * @odr: Output Data Rate word as expected by %ZPA2326_CTRL_REG3_REG.81 */82struct zpa2326_frequency {83	int hz;84	u16 odr;85};86 87/*88 * Keep these in strict ascending order: last array entry is expected to89 * correspond to the highest sampling frequency.90 */91static const struct zpa2326_frequency zpa2326_sampling_frequencies[] = {92	{ .hz = 1,  .odr = 1 << ZPA2326_CTRL_REG3_ODR_SHIFT },93	{ .hz = 5,  .odr = 5 << ZPA2326_CTRL_REG3_ODR_SHIFT },94	{ .hz = 11, .odr = 6 << ZPA2326_CTRL_REG3_ODR_SHIFT },95	{ .hz = 23, .odr = 7 << ZPA2326_CTRL_REG3_ODR_SHIFT },96};97 98/* Return the highest hardware sampling frequency available. */99static const struct zpa2326_frequency *zpa2326_highest_frequency(void)100{101	return &zpa2326_sampling_frequencies[102		ARRAY_SIZE(zpa2326_sampling_frequencies) - 1];103}104 105/**106 * struct zpa2326_private - Per-device internal private state107 * @timestamp:  Buffered samples ready datum.108 * @regmap:     Underlying I2C / SPI bus adapter used to abstract slave register109 *              accesses.110 * @result:     Allows sampling logic to get completion status of operations111 *              that interrupt handlers perform asynchronously.112 * @data_ready: Interrupt handler uses this to wake user context up at sampling113 *              operation completion.114 * @trigger:    Optional hardware / interrupt driven trigger used to notify115 *              external devices a new sample is ready.116 * @waken:      Flag indicating whether or not device has just been powered on.117 * @irq:        Optional interrupt line: negative or zero if not declared into118 *              DT, in which case sampling logic keeps polling status register119 *              to detect completion.120 * @frequency:  Current hardware sampling frequency.121 * @vref:       Power / voltage reference.122 * @vdd:        Power supply.123 */124struct zpa2326_private {125	s64                             timestamp;126	struct regmap                  *regmap;127	int                             result;128	struct completion               data_ready;129	struct iio_trigger             *trigger;130	bool                            waken;131	int                             irq;132	const struct zpa2326_frequency *frequency;133	struct regulator               *vref;134	struct regulator               *vdd;135};136 137#define zpa2326_err(idev, fmt, ...)					\138	dev_err(idev->dev.parent, fmt "\n", ##__VA_ARGS__)139 140#define zpa2326_warn(idev, fmt, ...)					\141	dev_warn(idev->dev.parent, fmt "\n", ##__VA_ARGS__)142 143#define zpa2326_dbg(idev, fmt, ...)					\144	dev_dbg(idev->dev.parent, fmt "\n", ##__VA_ARGS__)145 146bool zpa2326_isreg_writeable(struct device *dev, unsigned int reg)147{148	switch (reg) {149	case ZPA2326_REF_P_XL_REG:150	case ZPA2326_REF_P_L_REG:151	case ZPA2326_REF_P_H_REG:152	case ZPA2326_RES_CONF_REG:153	case ZPA2326_CTRL_REG0_REG:154	case ZPA2326_CTRL_REG1_REG:155	case ZPA2326_CTRL_REG2_REG:156	case ZPA2326_CTRL_REG3_REG:157	case ZPA2326_THS_P_LOW_REG:158	case ZPA2326_THS_P_HIGH_REG:159		return true;160 161	default:162		return false;163	}164}165EXPORT_SYMBOL_NS_GPL(zpa2326_isreg_writeable, IIO_ZPA2326);166 167bool zpa2326_isreg_readable(struct device *dev, unsigned int reg)168{169	switch (reg) {170	case ZPA2326_REF_P_XL_REG:171	case ZPA2326_REF_P_L_REG:172	case ZPA2326_REF_P_H_REG:173	case ZPA2326_DEVICE_ID_REG:174	case ZPA2326_RES_CONF_REG:175	case ZPA2326_CTRL_REG0_REG:176	case ZPA2326_CTRL_REG1_REG:177	case ZPA2326_CTRL_REG2_REG:178	case ZPA2326_CTRL_REG3_REG:179	case ZPA2326_INT_SOURCE_REG:180	case ZPA2326_THS_P_LOW_REG:181	case ZPA2326_THS_P_HIGH_REG:182	case ZPA2326_STATUS_REG:183	case ZPA2326_PRESS_OUT_XL_REG:184	case ZPA2326_PRESS_OUT_L_REG:185	case ZPA2326_PRESS_OUT_H_REG:186	case ZPA2326_TEMP_OUT_L_REG:187	case ZPA2326_TEMP_OUT_H_REG:188		return true;189 190	default:191		return false;192	}193}194EXPORT_SYMBOL_NS_GPL(zpa2326_isreg_readable, IIO_ZPA2326);195 196bool zpa2326_isreg_precious(struct device *dev, unsigned int reg)197{198	switch (reg) {199	case ZPA2326_INT_SOURCE_REG:200	case ZPA2326_PRESS_OUT_H_REG:201		return true;202 203	default:204		return false;205	}206}207EXPORT_SYMBOL_NS_GPL(zpa2326_isreg_precious, IIO_ZPA2326);208 209/**210 * zpa2326_enable_device() - Enable device, i.e. get out of low power mode.211 * @indio_dev: The IIO device associated with the hardware to enable.212 *213 * Required to access complete register space and to perform any sampling214 * or control operations.215 *216 * Return: Zero when successful, a negative error code otherwise.217 */218static int zpa2326_enable_device(const struct iio_dev *indio_dev)219{220	int err;221 222	err = regmap_write(((struct zpa2326_private *)223			    iio_priv(indio_dev))->regmap,224			    ZPA2326_CTRL_REG0_REG, ZPA2326_CTRL_REG0_ENABLE);225	if (err) {226		zpa2326_err(indio_dev, "failed to enable device (%d)", err);227		return err;228	}229 230	zpa2326_dbg(indio_dev, "enabled");231 232	return 0;233}234 235/**236 * zpa2326_sleep() - Disable device, i.e. switch to low power mode.237 * @indio_dev: The IIO device associated with the hardware to disable.238 *239 * Only %ZPA2326_DEVICE_ID_REG and %ZPA2326_CTRL_REG0_REG registers may be240 * accessed once device is in the disabled state.241 *242 * Return: Zero when successful, a negative error code otherwise.243 */244static int zpa2326_sleep(const struct iio_dev *indio_dev)245{246	int err;247 248	err = regmap_write(((struct zpa2326_private *)249			    iio_priv(indio_dev))->regmap,250			    ZPA2326_CTRL_REG0_REG, 0);251	if (err) {252		zpa2326_err(indio_dev, "failed to sleep (%d)", err);253		return err;254	}255 256	zpa2326_dbg(indio_dev, "sleeping");257 258	return 0;259}260 261/**262 * zpa2326_reset_device() - Reset device to default hardware state.263 * @indio_dev: The IIO device associated with the hardware to reset.264 *265 * Disable sampling and empty hardware FIFO.266 * Device must be enabled before reset, i.e. not in low power mode.267 *268 * Return: Zero when successful, a negative error code otherwise.269 */270static int zpa2326_reset_device(const struct iio_dev *indio_dev)271{272	int err;273 274	err = regmap_write(((struct zpa2326_private *)275			    iio_priv(indio_dev))->regmap,276			    ZPA2326_CTRL_REG2_REG, ZPA2326_CTRL_REG2_SWRESET);277	if (err) {278		zpa2326_err(indio_dev, "failed to reset device (%d)", err);279		return err;280	}281 282	usleep_range(ZPA2326_TPUP_USEC_MIN, ZPA2326_TPUP_USEC_MAX);283 284	zpa2326_dbg(indio_dev, "reset");285 286	return 0;287}288 289/**290 * zpa2326_start_oneshot() - Start a single sampling cycle, i.e. in one shot291 *                           mode.292 * @indio_dev: The IIO device associated with the sampling hardware.293 *294 * Device must have been previously enabled and configured for one shot mode.295 * Device will be switched back to low power mode at end of cycle.296 *297 * Return: Zero when successful, a negative error code otherwise.298 */299static int zpa2326_start_oneshot(const struct iio_dev *indio_dev)300{301	int err;302 303	err = regmap_write(((struct zpa2326_private *)304			    iio_priv(indio_dev))->regmap,305			    ZPA2326_CTRL_REG0_REG,306			    ZPA2326_CTRL_REG0_ENABLE |307			    ZPA2326_CTRL_REG0_ONE_SHOT);308	if (err) {309		zpa2326_err(indio_dev, "failed to start one shot cycle (%d)",310			    err);311		return err;312	}313 314	zpa2326_dbg(indio_dev, "one shot cycle started");315 316	return 0;317}318 319/**320 * zpa2326_power_on() - Power on device to allow subsequent configuration.321 * @indio_dev: The IIO device associated with the sampling hardware.322 * @private:   Internal private state related to @indio_dev.323 *324 * Sampling will be disabled, preventing strange things from happening in our325 * back. Hardware FIFO content will be cleared.326 * When successful, device will be left in the enabled state to allow further327 * configuration.328 *329 * Return: Zero when successful, a negative error code otherwise.330 */331static int zpa2326_power_on(const struct iio_dev         *indio_dev,332			    const struct zpa2326_private *private)333{334	int err;335 336	err = regulator_enable(private->vref);337	if (err)338		return err;339 340	err = regulator_enable(private->vdd);341	if (err)342		goto vref;343 344	zpa2326_dbg(indio_dev, "powered on");345 346	err = zpa2326_enable_device(indio_dev);347	if (err)348		goto vdd;349 350	err = zpa2326_reset_device(indio_dev);351	if (err)352		goto sleep;353 354	return 0;355 356sleep:357	zpa2326_sleep(indio_dev);358vdd:359	regulator_disable(private->vdd);360vref:361	regulator_disable(private->vref);362 363	zpa2326_dbg(indio_dev, "powered off");364 365	return err;366}367 368/**369 * zpa2326_power_off() - Power off device, i.e. disable attached power370 *                       regulators.371 * @indio_dev: The IIO device associated with the sampling hardware.372 * @private:   Internal private state related to @indio_dev.373 *374 * Return: Zero when successful, a negative error code otherwise.375 */376static void zpa2326_power_off(const struct iio_dev         *indio_dev,377			      const struct zpa2326_private *private)378{379	regulator_disable(private->vdd);380	regulator_disable(private->vref);381 382	zpa2326_dbg(indio_dev, "powered off");383}384 385/**386 * zpa2326_config_oneshot() - Setup device for one shot / on demand mode.387 * @indio_dev: The IIO device associated with the sampling hardware.388 * @irq:       Optional interrupt line the hardware uses to notify new data389 *             samples are ready. Negative or zero values indicate no interrupts390 *             are available, meaning polling is required.391 *392 * Output Data Rate is configured for the highest possible rate so that393 * conversion time and power consumption are reduced to a minimum.394 * Note that hardware internal averaging machinery (not implemented in this395 * driver) is not applicable in this mode.396 *397 * Device must have been previously enabled before calling398 * zpa2326_config_oneshot().399 *400 * Return: Zero when successful, a negative error code otherwise.401 */402static int zpa2326_config_oneshot(const struct iio_dev *indio_dev,403				  int                   irq)404{405	struct regmap                  *regs = ((struct zpa2326_private *)406						iio_priv(indio_dev))->regmap;407	const struct zpa2326_frequency *freq = zpa2326_highest_frequency();408	int                             err;409 410	/* Setup highest available Output Data Rate for one shot mode. */411	err = regmap_write(regs, ZPA2326_CTRL_REG3_REG, freq->odr);412	if (err)413		return err;414 415	if (irq > 0) {416		/* Request interrupt when new sample is available. */417		err = regmap_write(regs, ZPA2326_CTRL_REG1_REG,418				   (u8)~ZPA2326_CTRL_REG1_MASK_DATA_READY);419 420		if (err) {421			dev_err(indio_dev->dev.parent,422				"failed to setup one shot mode (%d)", err);423			return err;424		}425	}426 427	zpa2326_dbg(indio_dev, "one shot mode setup @%dHz", freq->hz);428 429	return 0;430}431 432/**433 * zpa2326_clear_fifo() - Clear remaining entries in hardware FIFO.434 * @indio_dev: The IIO device associated with the sampling hardware.435 * @min_count: Number of samples present within hardware FIFO.436 *437 * @min_count argument is a hint corresponding to the known minimum number of438 * samples currently living in the FIFO. This allows to reduce the number of bus439 * accesses by skipping status register read operation as long as we know for440 * sure there are still entries left.441 *442 * Return: Zero when successful, a negative error code otherwise.443 */444static int zpa2326_clear_fifo(const struct iio_dev *indio_dev,445			      unsigned int          min_count)446{447	struct regmap *regs = ((struct zpa2326_private *)448			       iio_priv(indio_dev))->regmap;449	int            err;450	unsigned int   val;451 452	if (!min_count) {453		/*454		 * No hint: read status register to determine whether FIFO is455		 * empty or not.456		 */457		err = regmap_read(regs, ZPA2326_STATUS_REG, &val);458 459		if (err < 0)460			goto err;461 462		if (val & ZPA2326_STATUS_FIFO_E)463			/* Fifo is empty: nothing to trash. */464			return 0;465	}466 467	/* Clear FIFO. */468	do {469		/*470		 * A single fetch from pressure MSB register is enough to pop471		 * values out of FIFO.472		 */473		err = regmap_read(regs, ZPA2326_PRESS_OUT_H_REG, &val);474		if (err < 0)475			goto err;476 477		if (min_count) {478			/*479			 * We know for sure there are at least min_count entries480			 * left in FIFO. Skip status register read.481			 */482			min_count--;483			continue;484		}485 486		err = regmap_read(regs, ZPA2326_STATUS_REG, &val);487		if (err < 0)488			goto err;489 490	} while (!(val & ZPA2326_STATUS_FIFO_E));491 492	zpa2326_dbg(indio_dev, "FIFO cleared");493 494	return 0;495 496err:497	zpa2326_err(indio_dev, "failed to clear FIFO (%d)", err);498 499	return err;500}501 502/**503 * zpa2326_dequeue_pressure() - Retrieve the most recent pressure sample from504 *                              hardware FIFO.505 * @indio_dev: The IIO device associated with the sampling hardware.506 * @pressure:  Sampled pressure output.507 *508 * Note that ZPA2326 hardware FIFO stores pressure samples only.509 *510 * Return: Zero when successful, a negative error code otherwise.511 */512static int zpa2326_dequeue_pressure(const struct iio_dev *indio_dev,513				    u32                  *pressure)514{515	struct regmap *regs = ((struct zpa2326_private *)516			       iio_priv(indio_dev))->regmap;517	unsigned int   val;518	int            err;519	int            cleared = -1;520 521	err = regmap_read(regs, ZPA2326_STATUS_REG, &val);522	if (err < 0)523		return err;524 525	*pressure = 0;526 527	if (val & ZPA2326_STATUS_P_OR) {528		/*529		 * Fifo overrun : first sample dequeued from FIFO is the530		 * newest.531		 */532		zpa2326_warn(indio_dev, "FIFO overflow");533 534		err = regmap_bulk_read(regs, ZPA2326_PRESS_OUT_XL_REG, pressure,535				       3);536		if (err)537			return err;538 539#define ZPA2326_FIFO_DEPTH (16U)540		/* Hardware FIFO may hold no more than 16 pressure samples. */541		return zpa2326_clear_fifo(indio_dev, ZPA2326_FIFO_DEPTH - 1);542	}543 544	/*545	 * Fifo has not overflown : retrieve newest sample. We need to pop546	 * values out until FIFO is empty : last fetched pressure is the newest.547	 * In nominal cases, we should find a single queued sample only.548	 */549	do {550		err = regmap_bulk_read(regs, ZPA2326_PRESS_OUT_XL_REG, pressure,551				       3);552		if (err)553			return err;554 555		err = regmap_read(regs, ZPA2326_STATUS_REG, &val);556		if (err < 0)557			return err;558 559		cleared++;560	} while (!(val & ZPA2326_STATUS_FIFO_E));561 562	if (cleared)563		/*564		 * Samples were pushed by hardware during previous rounds but we565		 * didn't consume them fast enough: inform user.566		 */567		zpa2326_dbg(indio_dev, "cleared %d FIFO entries", cleared);568 569	return 0;570}571 572/**573 * zpa2326_fill_sample_buffer() - Enqueue new channel samples to IIO buffer.574 * @indio_dev: The IIO device associated with the sampling hardware.575 * @private:   Internal private state related to @indio_dev.576 *577 * Return: Zero when successful, a negative error code otherwise.578 */579static int zpa2326_fill_sample_buffer(struct iio_dev               *indio_dev,580				      const struct zpa2326_private *private)581{582	struct {583		u32 pressure;584		u16 temperature;585		u64 timestamp;586	}   sample;587	int err;588 589	if (test_bit(0, indio_dev->active_scan_mask)) {590		/* Get current pressure from hardware FIFO. */591		err = zpa2326_dequeue_pressure(indio_dev, &sample.pressure);592		if (err) {593			zpa2326_warn(indio_dev, "failed to fetch pressure (%d)",594				     err);595			return err;596		}597	}598 599	if (test_bit(1, indio_dev->active_scan_mask)) {600		/* Get current temperature. */601		err = regmap_bulk_read(private->regmap, ZPA2326_TEMP_OUT_L_REG,602				       &sample.temperature, 2);603		if (err) {604			zpa2326_warn(indio_dev,605				     "failed to fetch temperature (%d)", err);606			return err;607		}608	}609 610	/*611	 * Now push samples using timestamp stored either :612	 *   - by hardware interrupt handler if interrupt is available: see613	 *     zpa2326_handle_irq(),614	 *   - or oneshot completion polling machinery : see615	 *     zpa2326_trigger_handler().616	 */617	zpa2326_dbg(indio_dev, "filling raw samples buffer");618 619	iio_push_to_buffers_with_timestamp(indio_dev, &sample,620					   private->timestamp);621 622	return 0;623}624 625#ifdef CONFIG_PM626static int zpa2326_runtime_suspend(struct device *parent)627{628	const struct iio_dev *indio_dev = dev_get_drvdata(parent);629 630	if (pm_runtime_autosuspend_expiration(parent))631		/* Userspace changed autosuspend delay. */632		return -EAGAIN;633 634	zpa2326_power_off(indio_dev, iio_priv(indio_dev));635 636	return 0;637}638 639static int zpa2326_runtime_resume(struct device *parent)640{641	const struct iio_dev *indio_dev = dev_get_drvdata(parent);642 643	return zpa2326_power_on(indio_dev, iio_priv(indio_dev));644}645 646const struct dev_pm_ops zpa2326_pm_ops = {647	SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,648				pm_runtime_force_resume)649	SET_RUNTIME_PM_OPS(zpa2326_runtime_suspend, zpa2326_runtime_resume,650			   NULL)651};652EXPORT_SYMBOL_NS_GPL(zpa2326_pm_ops, IIO_ZPA2326);653 654/**655 * zpa2326_resume() - Request the PM layer to power supply the device.656 * @indio_dev: The IIO device associated with the sampling hardware.657 *658 * Return:659 *  < 0 - a negative error code meaning failure ;660 *    0 - success, device has just been powered up ;661 *    1 - success, device was already powered.662 */663static int zpa2326_resume(const struct iio_dev *indio_dev)664{665	int err;666 667	err = pm_runtime_get_sync(indio_dev->dev.parent);668	if (err < 0) {669		pm_runtime_put(indio_dev->dev.parent);670		return err;671	}672 673	if (err > 0) {674		/*675		 * Device was already power supplied: get it out of low power676		 * mode and inform caller.677		 */678		zpa2326_enable_device(indio_dev);679		return 1;680	}681 682	/* Inform caller device has just been brought back to life. */683	return 0;684}685 686/**687 * zpa2326_suspend() - Schedule a power down using autosuspend feature of PM688 *                     layer.689 * @indio_dev: The IIO device associated with the sampling hardware.690 *691 * Device is switched to low power mode at first to save power even when692 * attached regulator is a "dummy" one.693 */694static void zpa2326_suspend(struct iio_dev *indio_dev)695{696	struct device *parent = indio_dev->dev.parent;697 698	zpa2326_sleep(indio_dev);699 700	pm_runtime_mark_last_busy(parent);701	pm_runtime_put_autosuspend(parent);702}703 704static void zpa2326_init_runtime(struct device *parent)705{706	pm_runtime_get_noresume(parent);707	pm_runtime_set_active(parent);708	pm_runtime_enable(parent);709	pm_runtime_set_autosuspend_delay(parent, 1000);710	pm_runtime_use_autosuspend(parent);711	pm_runtime_mark_last_busy(parent);712	pm_runtime_put_autosuspend(parent);713}714 715static void zpa2326_fini_runtime(struct device *parent)716{717	pm_runtime_disable(parent);718	pm_runtime_set_suspended(parent);719}720#else /* !CONFIG_PM */721static int zpa2326_resume(const struct iio_dev *indio_dev)722{723	zpa2326_enable_device(indio_dev);724 725	return 0;726}727 728static void zpa2326_suspend(struct iio_dev *indio_dev)729{730	zpa2326_sleep(indio_dev);731}732 733#define zpa2326_init_runtime(_parent)734#define zpa2326_fini_runtime(_parent)735#endif /* !CONFIG_PM */736 737/**738 * zpa2326_handle_irq() - Process hardware interrupts.739 * @irq:  Interrupt line the hardware uses to notify new data has arrived.740 * @data: The IIO device associated with the sampling hardware.741 *742 * Timestamp buffered samples as soon as possible then schedule threaded bottom743 * half.744 *745 * Return: Always successful.746 */747static irqreturn_t zpa2326_handle_irq(int irq, void *data)748{749	struct iio_dev *indio_dev = data;750 751	if (iio_buffer_enabled(indio_dev)) {752		/* Timestamping needed for buffered sampling only. */753		((struct zpa2326_private *)754		 iio_priv(indio_dev))->timestamp = iio_get_time_ns(indio_dev);755	}756 757	return IRQ_WAKE_THREAD;758}759 760/**761 * zpa2326_handle_threaded_irq() - Interrupt bottom-half handler.762 * @irq:  Interrupt line the hardware uses to notify new data has arrived.763 * @data: The IIO device associated with the sampling hardware.764 *765 * Mainly ensures interrupt is caused by a real "new sample available"766 * condition. This relies upon the ability to perform blocking / sleeping bus767 * accesses to slave's registers. This is why zpa2326_handle_threaded_irq() is768 * called from within a thread, i.e. not called from hard interrupt context.769 *770 * When device is using its own internal hardware trigger in continuous sampling771 * mode, data are available into hardware FIFO once interrupt has occurred. All772 * we have to do is to dispatch the trigger, which in turn will fetch data and773 * fill IIO buffer.774 *775 * When not using its own internal hardware trigger, the device has been776 * configured in one-shot mode either by an external trigger or the IIO read_raw777 * hook. This means one of the latter is currently waiting for sampling778 * completion, in which case we must simply wake it up.779 *780 * See zpa2326_trigger_handler().781 *782 * Return:783 *   %IRQ_NONE - no consistent interrupt happened ;784 *   %IRQ_HANDLED - there was new samples available.785 */786static irqreturn_t zpa2326_handle_threaded_irq(int irq, void *data)787{788	struct iio_dev         *indio_dev = data;789	struct zpa2326_private *priv = iio_priv(indio_dev);790	unsigned int            val;791	bool                    cont;792	irqreturn_t             ret = IRQ_NONE;793 794	/*795	 * Are we using our own internal trigger in triggered buffer mode, i.e.,796	 * currently working in continuous sampling mode ?797	 */798	cont = (iio_buffer_enabled(indio_dev) &&799		iio_trigger_using_own(indio_dev));800 801	/*802	 * Device works according to a level interrupt scheme: reading interrupt803	 * status de-asserts interrupt line.804	 */805	priv->result = regmap_read(priv->regmap, ZPA2326_INT_SOURCE_REG, &val);806	if (priv->result < 0) {807		if (cont)808			return IRQ_NONE;809 810		goto complete;811	}812 813	/* Data ready is the only interrupt source we requested. */814	if (!(val & ZPA2326_INT_SOURCE_DATA_READY)) {815		/*816		 * Interrupt happened but no new sample available: likely caused817		 * by spurious interrupts, in which case, returning IRQ_NONE818		 * allows to benefit from the generic spurious interrupts819		 * handling.820		 */821		zpa2326_warn(indio_dev, "unexpected interrupt status %02x",822			     val);823 824		if (cont)825			return IRQ_NONE;826 827		priv->result = -ENODATA;828		goto complete;829	}830 831	/* New sample available: dispatch internal trigger consumers. */832	iio_trigger_poll_nested(priv->trigger);833 834	if (cont)835		/*836		 * Internal hardware trigger has been scheduled above : it will837		 * fetch data on its own.838		 */839		return IRQ_HANDLED;840 841	ret = IRQ_HANDLED;842 843complete:844	/*845	 * Wake up direct or externaly triggered buffer mode waiters: see846	 * zpa2326_sample_oneshot() and zpa2326_trigger_handler().847	 */848	complete(&priv->data_ready);849 850	return ret;851}852 853/**854 * zpa2326_wait_oneshot_completion() - Wait for oneshot data ready interrupt.855 * @indio_dev: The IIO device associated with the sampling hardware.856 * @private:   Internal private state related to @indio_dev.857 *858 * Return: Zero when successful, a negative error code otherwise.859 */860static int zpa2326_wait_oneshot_completion(const struct iio_dev   *indio_dev,861					   struct zpa2326_private *private)862{863	unsigned int val;864	long time_left;865 866	zpa2326_dbg(indio_dev, "waiting for one shot completion interrupt");867 868	time_left = wait_for_completion_interruptible_timeout(869		&private->data_ready, ZPA2326_CONVERSION_JIFFIES);870	if (time_left > 0)871		/*872		 * Interrupt handler completed before timeout: return operation873		 * status.874		 */875		return private->result;876 877	/* Clear all interrupts just to be sure. */878	regmap_read(private->regmap, ZPA2326_INT_SOURCE_REG, &val);879 880	if (!time_left) {881		/* Timed out. */882		zpa2326_warn(indio_dev, "no one shot interrupt occurred (%ld)",883			     time_left);884		return -ETIME;885	}886 887	zpa2326_warn(indio_dev, "wait for one shot interrupt cancelled");888	return -ERESTARTSYS;889}890 891static int zpa2326_init_managed_irq(struct device          *parent,892				    struct iio_dev         *indio_dev,893				    struct zpa2326_private *private,894				    int                     irq)895{896	int err;897 898	private->irq = irq;899 900	if (irq <= 0) {901		/*902		 * Platform declared no interrupt line: device will be polled903		 * for data availability.904		 */905		dev_info(parent, "no interrupt found, running in polling mode");906		return 0;907	}908 909	init_completion(&private->data_ready);910 911	/* Request handler to be scheduled into threaded interrupt context. */912	err = devm_request_threaded_irq(parent, irq, zpa2326_handle_irq,913					zpa2326_handle_threaded_irq,914					IRQF_TRIGGER_RISING | IRQF_ONESHOT,915					dev_name(parent), indio_dev);916	if (err) {917		dev_err(parent, "failed to request interrupt %d (%d)", irq,918			err);919		return err;920	}921 922	dev_info(parent, "using interrupt %d", irq);923 924	return 0;925}926 927/**928 * zpa2326_poll_oneshot_completion() - Actively poll for one shot data ready.929 * @indio_dev: The IIO device associated with the sampling hardware.930 *931 * Loop over registers content to detect end of sampling cycle. Used when DT932 * declared no valid interrupt lines.933 *934 * Return: Zero when successful, a negative error code otherwise.935 */936static int zpa2326_poll_oneshot_completion(const struct iio_dev *indio_dev)937{938	unsigned long  tmout = jiffies + ZPA2326_CONVERSION_JIFFIES;939	struct regmap *regs = ((struct zpa2326_private *)940			       iio_priv(indio_dev))->regmap;941	unsigned int   val;942	int            err;943 944	zpa2326_dbg(indio_dev, "polling for one shot completion");945 946	/*947	 * At least, 100 ms is needed for the device to complete its one-shot948	 * cycle.949	 */950	if (msleep_interruptible(100))951		return -ERESTARTSYS;952 953	/* Poll for conversion completion in hardware. */954	while (true) {955		err = regmap_read(regs, ZPA2326_CTRL_REG0_REG, &val);956		if (err < 0)957			goto err;958 959		if (!(val & ZPA2326_CTRL_REG0_ONE_SHOT))960			/* One-shot bit self clears at conversion end. */961			break;962 963		if (time_after(jiffies, tmout)) {964			/* Prevent from waiting forever : let's time out. */965			err = -ETIME;966			goto err;967		}968 969		usleep_range(10000, 20000);970	}971 972	/*973	 * In oneshot mode, pressure sample availability guarantees that974	 * temperature conversion has also completed : just check pressure975	 * status bit to keep things simple.976	 */977	err = regmap_read(regs, ZPA2326_STATUS_REG, &val);978	if (err < 0)979		goto err;980 981	if (!(val & ZPA2326_STATUS_P_DA)) {982		/* No sample available. */983		err = -ENODATA;984		goto err;985	}986 987	return 0;988 989err:990	zpa2326_warn(indio_dev, "failed to poll one shot completion (%d)", err);991 992	return err;993}994 995/**996 * zpa2326_fetch_raw_sample() - Retrieve a raw sample and convert it to CPU997 *                              endianness.998 * @indio_dev: The IIO device associated with the sampling hardware.999 * @type:      Type of measurement / channel to fetch from.1000 * @value:     Sample output.1001 *1002 * Return: Zero when successful, a negative error code otherwise.1003 */1004static 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 */1056static 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 to1076		 * get rid of samples acquired during previous rounds (if any).1077		 * Sampling operation always generates both temperature and1078		 * pressure samples. The latter are always enqueued into1079		 * hardware FIFO. This may lead to situations were pressure1080		 * samples still sit into FIFO when previous cycle(s) fetched1081		 * temperature data only.1082		 * Hence, we need to clear hardware FIFO content to prevent from1083		 * 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 default1093		 * "out of reset" state, meaning we need to reconfigure it1094		 * 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	else1110		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 1118suspend:1119	zpa2326_suspend(indio_dev);1120release: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 one1128 *                             shot mode.1129 * @irq:  The software interrupt assigned to @data1130 * @data: The IIO poll function dispatched by external trigger our device is1131 *        attached to.1132 *1133 * Bottom-half handler called by the IIO trigger to which our device is1134 * currently attached. Allows us to synchronize this device buffered sampling1135 * either with external events (such as timer expiration, external device sample1136 * ready, etc...) or with its own interrupt (internal hardware trigger).1137 *1138 * When using an external trigger, basically run the same sequence of operations1139 * as for zpa2326_sample_oneshot() with the following hereafter. Hardware FIFO1140 * is not cleared since already done at buffering enable time and samples1141 * dequeueing always retrieves the most recent value.1142 *1143 * Otherwise, when internal hardware trigger has dispatched us, just fetch data1144 * from hardware FIFO.1145 *1146 * Fetched data will pushed unprocessed to IIO buffer since samples conversion1147 * 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 */1153static 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 continuous1163	 * 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 1190out: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 triggered1203 *                              sampling1204 * 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 */1212static 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 */1242static 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 to1250		 * 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 been1263		 * 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 1276static int zpa2326_postdisable_buffer(struct iio_dev *indio_dev)1277{1278	zpa2326_suspend(indio_dev);1279 1280	return 0;1281}1282 1283static const struct iio_buffer_setup_ops zpa2326_buffer_setup_ops = {1284	.preenable   = zpa2326_preenable_buffer,1285	.postenable  = zpa2326_postenable_buffer,1286	.postdisable = zpa2326_postdisable_buffer1287};1288 1289/**1290 * zpa2326_set_trigger_state() - Start / stop continuous sampling.1291 * @trig:  The trigger being attached to IIO device associated with the sampling1292 *         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 */1301static 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 left1311		 * disabled in order to prevent handler from accessing released1312		 * resources.1313		 */1314		unsigned int val;1315 1316		/*1317		 * As device is working in continuous mode, handlers may be1318		 * accessing resources we are currently freeing...1319		 * Prevent this by disabling interrupt handlers and ensure1320		 * the device will generate no more interrupts unless explicitly1321		 * 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 for1327		 * 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 on1337		 * 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 will1345		 * generate no more interrupts to prevent handlers from1346		 * 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 required1354		 * 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 1380static 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 trigger1386 *                          allowing to notify external devices a new sample is1387 *                          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 data1392 *             samples are ready. Negative or zero values indicate no interrupts1393 *             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 */1399static 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 1430static int zpa2326_get_frequency(const struct iio_dev *indio_dev)1431{1432	return ((struct zpa2326_private *)iio_priv(indio_dev))->frequency->hz;1433}1434 1435static 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. */1461static IIO_CONST_ATTR_SAMP_FREQ_AVAIL("1 5 11 23");1462 1463static struct attribute *zpa2326_attributes[] = {1464	&iio_const_attr_sampling_frequency_available.dev_attr.attr,1465	NULL1466};1467 1468static const struct attribute_group zpa2326_attribute_group = {1469	.attrs = zpa2326_attributes,1470};1471 1472static 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 kPascal1487			 * 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.831497			 * where:1498			 *     Tempcode is composed the raw sampled 16 bits.1499			 *1500			 * Hence, to produce a temperature in milli-degrees1501			 * Celsius according to IIO ABI, we need to apply the1502			 * following equation to raw samples:1503			 *     Temp[milli degC] = (Tempcode + Offset) * Scale1504			 * where:1505			 *     Offset = -176.83 / 0.006491506			 *     Scale = 0.00649 * 10001507			 */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 1536static 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 1548static 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 1579static 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 1585static 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 1607int 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 before1637	 * registering interrupt handlers since an interrupt might happen if1638	 * 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 1693sleep:1694	/* Put to sleep just in case power regulators are "dummy" ones. */1695	zpa2326_sleep(indio_dev);1696poweroff:1697	zpa2326_power_off(indio_dev, priv);1698 1699	return err;1700}1701EXPORT_SYMBOL_NS_GPL(zpa2326_probe, IIO_ZPA2326);1702 1703void 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}1712EXPORT_SYMBOL_NS_GPL(zpa2326_remove, IIO_ZPA2326);1713 1714MODULE_AUTHOR("Gregor Boirie <gregor.boirie@parrot.com>");1715MODULE_DESCRIPTION("Core driver for Murata ZPA2326 pressure sensor");1716MODULE_LICENSE("GPL v2");1717