xref: /linux/drivers/iio/industrialio-core.c (revision c6c47852c1769125a40f45662ef63d51f588f7c4)
1d2912cb1SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
265659a8dSAndy Shevchenko /*
365659a8dSAndy Shevchenko  * The industrial I/O core
4a980e046SJonathan Cameron  *
5a980e046SJonathan Cameron  * Copyright (c) 2008 Jonathan Cameron
6a980e046SJonathan Cameron  *
7a980e046SJonathan Cameron  * Based on elements of hwmon and input subsystems.
8a980e046SJonathan Cameron  */
9a980e046SJonathan Cameron 
103176dd5dSSachin Kamat #define pr_fmt(fmt) "iio-core: " fmt
113176dd5dSSachin Kamat 
1205f59abaSAndy Shevchenko #include <linux/anon_inodes.h>
1305f59abaSAndy Shevchenko #include <linux/cdev.h>
1442ea5992SNuno Sa #include <linux/cleanup.h>
1505f59abaSAndy Shevchenko #include <linux/debugfs.h>
1605f59abaSAndy Shevchenko #include <linux/device.h>
1705f59abaSAndy Shevchenko #include <linux/err.h>
1805f59abaSAndy Shevchenko #include <linux/fs.h>
19a980e046SJonathan Cameron #include <linux/idr.h>
20a980e046SJonathan Cameron #include <linux/kdev_t.h>
2105f59abaSAndy Shevchenko #include <linux/kernel.h>
2205f59abaSAndy Shevchenko #include <linux/module.h>
2305f59abaSAndy Shevchenko #include <linux/mutex.h>
24a980e046SJonathan Cameron #include <linux/poll.h>
25fb158971SAndy Shevchenko #include <linux/property.h>
26a980e046SJonathan Cameron #include <linux/sched.h>
27a980e046SJonathan Cameron #include <linux/slab.h>
2805f59abaSAndy Shevchenko #include <linux/wait.h>
2905f59abaSAndy Shevchenko 
309e69c935SLars-Peter Clausen #include <linux/iio/buffer.h>
3133dd94cbSJonathan Cameron #include <linux/iio/buffer_impl.h>
3205f59abaSAndy Shevchenko #include <linux/iio/events.h>
3305f59abaSAndy Shevchenko #include <linux/iio/iio-opaque.h>
3405f59abaSAndy Shevchenko #include <linux/iio/iio.h>
3505f59abaSAndy Shevchenko #include <linux/iio/sysfs.h>
3605f59abaSAndy Shevchenko 
3705f59abaSAndy Shevchenko #include "iio_core.h"
3805f59abaSAndy Shevchenko #include "iio_core_trigger.h"
39a980e046SJonathan Cameron 
40a980e046SJonathan Cameron /* IDA to assign each registered device a unique id */
41a980e046SJonathan Cameron static DEFINE_IDA(iio_ida);
42a980e046SJonathan Cameron 
43a980e046SJonathan Cameron static dev_t iio_devt;
44a980e046SJonathan Cameron 
45a980e046SJonathan Cameron #define IIO_DEV_MAX 256
4689b1b86fSRicardo B. Marliere const struct bus_type iio_bus_type = {
47a980e046SJonathan Cameron 	.name = "iio",
48a980e046SJonathan Cameron };
49a980e046SJonathan Cameron EXPORT_SYMBOL(iio_bus_type);
50a980e046SJonathan Cameron 
51a980e046SJonathan Cameron static struct dentry *iio_debugfs_dentry;
52a980e046SJonathan Cameron 
53a980e046SJonathan Cameron static const char * const iio_direction[] = {
54a980e046SJonathan Cameron 	[0] = "in",
55a980e046SJonathan Cameron 	[1] = "out",
56a980e046SJonathan Cameron };
57a980e046SJonathan Cameron 
58a980e046SJonathan Cameron static const char * const iio_chan_type_name_spec[] = {
59a980e046SJonathan Cameron 	[IIO_VOLTAGE] = "voltage",
60a980e046SJonathan Cameron 	[IIO_CURRENT] = "current",
61a980e046SJonathan Cameron 	[IIO_POWER] = "power",
62a980e046SJonathan Cameron 	[IIO_ACCEL] = "accel",
63a980e046SJonathan Cameron 	[IIO_ANGL_VEL] = "anglvel",
64a980e046SJonathan Cameron 	[IIO_MAGN] = "magn",
65a980e046SJonathan Cameron 	[IIO_LIGHT] = "illuminance",
66a980e046SJonathan Cameron 	[IIO_INTENSITY] = "intensity",
67a980e046SJonathan Cameron 	[IIO_PROXIMITY] = "proximity",
68a980e046SJonathan Cameron 	[IIO_TEMP] = "temp",
69a980e046SJonathan Cameron 	[IIO_INCLI] = "incli",
70a980e046SJonathan Cameron 	[IIO_ROT] = "rot",
71a980e046SJonathan Cameron 	[IIO_ANGL] = "angl",
72a980e046SJonathan Cameron 	[IIO_TIMESTAMP] = "timestamp",
73a980e046SJonathan Cameron 	[IIO_CAPACITANCE] = "capacitance",
74a6b12855SMichael Hennerich 	[IIO_ALTVOLTAGE] = "altvoltage",
7521cd1fabSJon Brenner 	[IIO_CCT] = "cct",
76c4f0c693SLars-Peter Clausen 	[IIO_PRESSURE] = "pressure",
77ac216aa2SHarald Geyer 	[IIO_HUMIDITYRELATIVE] = "humidityrelative",
7855aebeb9SDaniel Baluta 	[IIO_ACTIVITY] = "activity",
79a88bfe78SIrina Tirdea 	[IIO_STEPS] = "steps",
8072c66644SIrina Tirdea 	[IIO_ENERGY] = "energy",
81cc3c9eecSIrina Tirdea 	[IIO_DISTANCE] = "distance",
825a1a9329SIrina Tirdea 	[IIO_VELOCITY] = "velocity",
838ff6b3bcSMatt Ranostay 	[IIO_CONCENTRATION] = "concentration",
84d38d5469SMatt Ranostay 	[IIO_RESISTANCE] = "resistance",
85ecb3a7ccSMatt Ranostay 	[IIO_PH] = "ph",
86d409404cSPeter Meerwald-Stadler 	[IIO_UVINDEX] = "uvindex",
874b9d2090SMatt Ranostay 	[IIO_ELECTRICALCONDUCTIVITY] = "electricalconductivity",
881a8f324aSWilliam Breathitt Gray 	[IIO_COUNT] = "count",
891a8f324aSWilliam Breathitt Gray 	[IIO_INDEX] = "index",
90571299d0SSong Hongyan 	[IIO_GRAVITY]  = "gravity",
913055a6cfSEugen Hristev 	[IIO_POSITIONRELATIVE]  = "positionrelative",
92c73314e6SMathieu Othacehe 	[IIO_PHASE] = "phase",
9317abc9ecSTomasz Duszynski 	[IIO_MASSCONCENTRATION] = "massconcentration",
94744f4990SRamona Bolboaca 	[IIO_DELTA_ANGL] = "deltaangl",
9594a39f2cSRamona Bolboaca 	[IIO_DELTA_VELOCITY] = "deltavelocity",
9642f31175SBasavaraj Natikar 	[IIO_COLORTEMP] = "colortemp",
9706790d4cSBasavaraj Natikar 	[IIO_CHROMATICITY] = "chromaticity",
98a980e046SJonathan Cameron };
99a980e046SJonathan Cameron 
100a980e046SJonathan Cameron static const char * const iio_modifier_names[] = {
101a980e046SJonathan Cameron 	[IIO_MOD_X] = "x",
102a980e046SJonathan Cameron 	[IIO_MOD_Y] = "y",
103a980e046SJonathan Cameron 	[IIO_MOD_Z] = "z",
1044b8d8015SPeter Meerwald 	[IIO_MOD_X_AND_Y] = "x&y",
1054b8d8015SPeter Meerwald 	[IIO_MOD_X_AND_Z] = "x&z",
1064b8d8015SPeter Meerwald 	[IIO_MOD_Y_AND_Z] = "y&z",
1074b8d8015SPeter Meerwald 	[IIO_MOD_X_AND_Y_AND_Z] = "x&y&z",
1084b8d8015SPeter Meerwald 	[IIO_MOD_X_OR_Y] = "x|y",
1094b8d8015SPeter Meerwald 	[IIO_MOD_X_OR_Z] = "x|z",
1104b8d8015SPeter Meerwald 	[IIO_MOD_Y_OR_Z] = "y|z",
1114b8d8015SPeter Meerwald 	[IIO_MOD_X_OR_Y_OR_Z] = "x|y|z",
1128f5879b2SJonathan Cameron 	[IIO_MOD_ROOT_SUM_SQUARED_X_Y] = "sqrt(x^2+y^2)",
113cf82cb81SJonathan Cameron 	[IIO_MOD_SUM_SQUARED_X_Y_Z] = "x^2+y^2+z^2",
114a980e046SJonathan Cameron 	[IIO_MOD_LIGHT_BOTH] = "both",
115a980e046SJonathan Cameron 	[IIO_MOD_LIGHT_IR] = "ir",
11621cd1fabSJon Brenner 	[IIO_MOD_LIGHT_CLEAR] = "clear",
11721cd1fabSJon Brenner 	[IIO_MOD_LIGHT_RED] = "red",
11821cd1fabSJon Brenner 	[IIO_MOD_LIGHT_GREEN] = "green",
11921cd1fabSJon Brenner 	[IIO_MOD_LIGHT_BLUE] = "blue",
1202c5ff1f9SPeter Meerwald-Stadler 	[IIO_MOD_LIGHT_UV] = "uv",
121b89710bdSJavier Carrasco 	[IIO_MOD_LIGHT_UVA] = "uva",
122b89710bdSJavier Carrasco 	[IIO_MOD_LIGHT_UVB] = "uvb",
123c0e4e0fdSMaxime Roussin-Bélanger 	[IIO_MOD_LIGHT_DUV] = "duv",
1245082f405SSrinivas Pandruvada 	[IIO_MOD_QUATERNION] = "quaternion",
125638b43b3SPeter Meerwald 	[IIO_MOD_TEMP_AMBIENT] = "ambient",
126638b43b3SPeter Meerwald 	[IIO_MOD_TEMP_OBJECT] = "object",
12711b8ddabSReyad Attiyat 	[IIO_MOD_NORTH_MAGN] = "from_north_magnetic",
12811b8ddabSReyad Attiyat 	[IIO_MOD_NORTH_TRUE] = "from_north_true",
12911b8ddabSReyad Attiyat 	[IIO_MOD_NORTH_MAGN_TILT_COMP] = "from_north_magnetic_tilt_comp",
13011b8ddabSReyad Attiyat 	[IIO_MOD_NORTH_TRUE_TILT_COMP] = "from_north_true_tilt_comp",
13155aebeb9SDaniel Baluta 	[IIO_MOD_RUNNING] = "running",
13255aebeb9SDaniel Baluta 	[IIO_MOD_JOGGING] = "jogging",
13355aebeb9SDaniel Baluta 	[IIO_MOD_WALKING] = "walking",
13455aebeb9SDaniel Baluta 	[IIO_MOD_STILL] = "still",
1355a1a9329SIrina Tirdea 	[IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z] = "sqrt(x^2+y^2+z^2)",
1361ce87f21SLars-Peter Clausen 	[IIO_MOD_I] = "i",
1371ce87f21SLars-Peter Clausen 	[IIO_MOD_Q] = "q",
1388ff6b3bcSMatt Ranostay 	[IIO_MOD_CO2] = "co2",
1398ff6b3bcSMatt Ranostay 	[IIO_MOD_VOC] = "voc",
14017abc9ecSTomasz Duszynski 	[IIO_MOD_PM1] = "pm1",
14117abc9ecSTomasz Duszynski 	[IIO_MOD_PM2P5] = "pm2p5",
14217abc9ecSTomasz Duszynski 	[IIO_MOD_PM4] = "pm4",
14317abc9ecSTomasz Duszynski 	[IIO_MOD_PM10] = "pm10",
14425f02d32SMatt Ranostay 	[IIO_MOD_ETHANOL] = "ethanol",
14525f02d32SMatt Ranostay 	[IIO_MOD_H2] = "h2",
1464ffa22fdSMatt Ranostay 	[IIO_MOD_O2] = "o2",
147bcc57a48SAndrea Merello 	[IIO_MOD_LINEAR_X] = "linear_x",
148bcc57a48SAndrea Merello 	[IIO_MOD_LINEAR_Y] = "linear_y",
149bcc57a48SAndrea Merello 	[IIO_MOD_LINEAR_Z] = "linear_z",
150dcedf145SAndrea Merello 	[IIO_MOD_PITCH] = "pitch",
151dcedf145SAndrea Merello 	[IIO_MOD_YAW] = "yaw",
152dcedf145SAndrea Merello 	[IIO_MOD_ROLL] = "roll",
153a980e046SJonathan Cameron };
154a980e046SJonathan Cameron 
155a980e046SJonathan Cameron /* relies on pairs of these shared then separate */
156a980e046SJonathan Cameron static const char * const iio_chan_info_postfix[] = {
157a980e046SJonathan Cameron 	[IIO_CHAN_INFO_RAW] = "raw",
158a980e046SJonathan Cameron 	[IIO_CHAN_INFO_PROCESSED] = "input",
159a980e046SJonathan Cameron 	[IIO_CHAN_INFO_SCALE] = "scale",
160a980e046SJonathan Cameron 	[IIO_CHAN_INFO_OFFSET] = "offset",
161a980e046SJonathan Cameron 	[IIO_CHAN_INFO_CALIBSCALE] = "calibscale",
162a980e046SJonathan Cameron 	[IIO_CHAN_INFO_CALIBBIAS] = "calibbias",
163a980e046SJonathan Cameron 	[IIO_CHAN_INFO_PEAK] = "peak_raw",
164a980e046SJonathan Cameron 	[IIO_CHAN_INFO_PEAK_SCALE] = "peak_scale",
165a980e046SJonathan Cameron 	[IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW] = "quadrature_correction_raw",
166a980e046SJonathan Cameron 	[IIO_CHAN_INFO_AVERAGE_RAW] = "mean_raw",
167a980e046SJonathan Cameron 	[IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY]
168a980e046SJonathan Cameron 	= "filter_low_pass_3db_frequency",
1693f7f642bSMartin Fuzzey 	[IIO_CHAN_INFO_HIGH_PASS_FILTER_3DB_FREQUENCY]
1703f7f642bSMartin Fuzzey 	= "filter_high_pass_3db_frequency",
171a980e046SJonathan Cameron 	[IIO_CHAN_INFO_SAMP_FREQ] = "sampling_frequency",
172a6b12855SMichael Hennerich 	[IIO_CHAN_INFO_FREQUENCY] = "frequency",
173a6b12855SMichael Hennerich 	[IIO_CHAN_INFO_PHASE] = "phase",
174b65d6212SMichael Hennerich 	[IIO_CHAN_INFO_HARDWAREGAIN] = "hardwaregain",
1757c9ab035Ssrinivas pandruvada 	[IIO_CHAN_INFO_HYSTERESIS] = "hysteresis",
1761c71a286SYe Xiang 	[IIO_CHAN_INFO_HYSTERESIS_RELATIVE] = "hysteresis_relative",
177899d90bdSPeter Meerwald 	[IIO_CHAN_INFO_INT_TIME] = "integration_time",
178a88bfe78SIrina Tirdea 	[IIO_CHAN_INFO_ENABLE] = "en",
179bcdf28fbSIrina Tirdea 	[IIO_CHAN_INFO_CALIBHEIGHT] = "calibheight",
180d37f6836SIrina Tirdea 	[IIO_CHAN_INFO_CALIBWEIGHT] = "calibweight",
1812f0ecb7cSIrina Tirdea 	[IIO_CHAN_INFO_DEBOUNCE_COUNT] = "debounce_count",
1822f0ecb7cSIrina Tirdea 	[IIO_CHAN_INFO_DEBOUNCE_TIME] = "debounce_time",
183c8a85854SVianney le Clément de Saint-Marcq 	[IIO_CHAN_INFO_CALIBEMISSIVITY] = "calibemissivity",
184faaa4495SIrina Tirdea 	[IIO_CHAN_INFO_OVERSAMPLING_RATIO] = "oversampling_ratio",
185ddfb97d8SAndrea Merello 	[IIO_CHAN_INFO_THERMOCOUPLE_TYPE] = "thermocouple_type",
186dde8ceecSCrt Mori 	[IIO_CHAN_INFO_CALIBAMBIENT] = "calibambient",
1875c64990bSJonathan Cameron 	[IIO_CHAN_INFO_ZEROPOINT] = "zeropoint",
1885bc2ea60SJavier Carrasco 	[IIO_CHAN_INFO_TROUGH] = "trough_raw",
189a980e046SJonathan Cameron };
19015ea2878SJonathan Cameron /**
19115ea2878SJonathan Cameron  * iio_device_id() - query the unique ID for the device
19215ea2878SJonathan Cameron  * @indio_dev:		Device structure whose ID is being queried
19315ea2878SJonathan Cameron  *
19415ea2878SJonathan Cameron  * The IIO device ID is a unique index used for example for the naming
19565659a8dSAndy Shevchenko  * of the character device /dev/iio\:device[ID].
19665659a8dSAndy Shevchenko  *
19765659a8dSAndy Shevchenko  * Returns: Unique ID for the device.
19815ea2878SJonathan Cameron  */
19915ea2878SJonathan Cameron int iio_device_id(struct iio_dev *indio_dev)
20015ea2878SJonathan Cameron {
20115ea2878SJonathan Cameron 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
20215ea2878SJonathan Cameron 
20315ea2878SJonathan Cameron 	return iio_dev_opaque->id;
20415ea2878SJonathan Cameron }
20515ea2878SJonathan Cameron EXPORT_SYMBOL_GPL(iio_device_id);
206a980e046SJonathan Cameron 
207d9a0e73cSLars-Peter Clausen /**
2082f53b4adSMiquel Raynal  * iio_buffer_enabled() - helper function to test if the buffer is enabled
2092f53b4adSMiquel Raynal  * @indio_dev:		IIO device structure for device
21065659a8dSAndy Shevchenko  *
21165659a8dSAndy Shevchenko  * Returns: True, if the buffer is enabled.
2122f53b4adSMiquel Raynal  */
2132f53b4adSMiquel Raynal bool iio_buffer_enabled(struct iio_dev *indio_dev)
2142f53b4adSMiquel Raynal {
21551570c9dSMiquel Raynal 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
21651570c9dSMiquel Raynal 
217e7748c17SDavid Lechner 	return iio_dev_opaque->currentmode & INDIO_ALL_BUFFER_MODES;
2182f53b4adSMiquel Raynal }
2192f53b4adSMiquel Raynal EXPORT_SYMBOL_GPL(iio_buffer_enabled);
2202f53b4adSMiquel Raynal 
22196fb1b67SAlexandru Ardelean #if defined(CONFIG_DEBUG_FS)
222c9561fd2SJonathan Cameron /*
22396fb1b67SAlexandru Ardelean  * There's also a CONFIG_DEBUG_FS guard in include/linux/iio/iio.h for
22496fb1b67SAlexandru Ardelean  * iio_get_debugfs_dentry() to make it inline if CONFIG_DEBUG_FS is undefined
22596fb1b67SAlexandru Ardelean  */
22696fb1b67SAlexandru Ardelean struct dentry *iio_get_debugfs_dentry(struct iio_dev *indio_dev)
22796fb1b67SAlexandru Ardelean {
22896fb1b67SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2299d9ec8d0SJoe Simmons-Talbott 
23096fb1b67SAlexandru Ardelean 	return iio_dev_opaque->debugfs_dentry;
23196fb1b67SAlexandru Ardelean }
23296fb1b67SAlexandru Ardelean EXPORT_SYMBOL_GPL(iio_get_debugfs_dentry);
23396fb1b67SAlexandru Ardelean #endif
23496fb1b67SAlexandru Ardelean 
235a7e57dceSSachin Kamat /**
236a7e57dceSSachin Kamat  * iio_find_channel_from_si() - get channel from its scan index
237a7e57dceSSachin Kamat  * @indio_dev:		device
238a7e57dceSSachin Kamat  * @si:			scan index to match
23965659a8dSAndy Shevchenko  *
24065659a8dSAndy Shevchenko  * Returns:
24165659a8dSAndy Shevchenko  * Constant pointer to iio_chan_spec, if scan index matches, NULL on failure.
242a7e57dceSSachin Kamat  */
243a980e046SJonathan Cameron const struct iio_chan_spec
244a980e046SJonathan Cameron *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
245a980e046SJonathan Cameron {
246a980e046SJonathan Cameron 	int i;
247a980e046SJonathan Cameron 
248a980e046SJonathan Cameron 	for (i = 0; i < indio_dev->num_channels; i++)
249a980e046SJonathan Cameron 		if (indio_dev->channels[i].scan_index == si)
250a980e046SJonathan Cameron 			return &indio_dev->channels[i];
251a980e046SJonathan Cameron 	return NULL;
252a980e046SJonathan Cameron }
253a980e046SJonathan Cameron 
254a980e046SJonathan Cameron /* This turns up an awful lot */
255a980e046SJonathan Cameron ssize_t iio_read_const_attr(struct device *dev,
256a980e046SJonathan Cameron 			    struct device_attribute *attr,
257a980e046SJonathan Cameron 			    char *buf)
258a980e046SJonathan Cameron {
25983ca56b6SLars-Peter Clausen 	return sysfs_emit(buf, "%s\n", to_iio_const_attr(attr)->string);
260a980e046SJonathan Cameron }
261a980e046SJonathan Cameron EXPORT_SYMBOL(iio_read_const_attr);
262a980e046SJonathan Cameron 
26369f0793eSGwendal Grignou /**
26469f0793eSGwendal Grignou  * iio_device_set_clock() - Set current timestamping clock for the device
26569f0793eSGwendal Grignou  * @indio_dev: IIO device structure containing the device
26665659a8dSAndy Shevchenko  * @clock_id: timestamping clock POSIX identifier to set.
26765659a8dSAndy Shevchenko  *
26865659a8dSAndy Shevchenko  * Returns: 0 on success, or a negative error code.
26969f0793eSGwendal Grignou  */
27069f0793eSGwendal Grignou int iio_device_set_clock(struct iio_dev *indio_dev, clockid_t clock_id)
271bc2b7dabSGregor Boirie {
272bc2b7dabSGregor Boirie 	int ret;
273fa83c3baSAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
274fa83c3baSAlexandru Ardelean 	const struct iio_event_interface *ev_int = iio_dev_opaque->event_interface;
275bc2b7dabSGregor Boirie 
27616afe125SNuno Sá 	ret = mutex_lock_interruptible(&iio_dev_opaque->mlock);
277bc2b7dabSGregor Boirie 	if (ret)
278bc2b7dabSGregor Boirie 		return ret;
279bc2b7dabSGregor Boirie 	if ((ev_int && iio_event_enabled(ev_int)) ||
280bc2b7dabSGregor Boirie 	    iio_buffer_enabled(indio_dev)) {
28116afe125SNuno Sá 		mutex_unlock(&iio_dev_opaque->mlock);
282bc2b7dabSGregor Boirie 		return -EBUSY;
283bc2b7dabSGregor Boirie 	}
28462a486c4SJonathan Cameron 	iio_dev_opaque->clock_id = clock_id;
28516afe125SNuno Sá 	mutex_unlock(&iio_dev_opaque->mlock);
286bc2b7dabSGregor Boirie 
287bc2b7dabSGregor Boirie 	return 0;
288bc2b7dabSGregor Boirie }
28969f0793eSGwendal Grignou EXPORT_SYMBOL(iio_device_set_clock);
290bc2b7dabSGregor Boirie 
291bc2b7dabSGregor Boirie /**
29262a486c4SJonathan Cameron  * iio_device_get_clock() - Retrieve current timestamping clock for the device
29362a486c4SJonathan Cameron  * @indio_dev: IIO device structure containing the device
29465659a8dSAndy Shevchenko  *
29565659a8dSAndy Shevchenko  * Returns: Clock ID of the current timestamping clock for the device.
29662a486c4SJonathan Cameron  */
29762a486c4SJonathan Cameron clockid_t iio_device_get_clock(const struct iio_dev *indio_dev)
29862a486c4SJonathan Cameron {
29962a486c4SJonathan Cameron 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
30062a486c4SJonathan Cameron 
30162a486c4SJonathan Cameron 	return iio_dev_opaque->clock_id;
30262a486c4SJonathan Cameron }
30362a486c4SJonathan Cameron EXPORT_SYMBOL(iio_device_get_clock);
30462a486c4SJonathan Cameron 
30562a486c4SJonathan Cameron /**
306bc2b7dabSGregor Boirie  * iio_get_time_ns() - utility function to get a time stamp for events etc
307bc2b7dabSGregor Boirie  * @indio_dev: device
30865659a8dSAndy Shevchenko  *
30965659a8dSAndy Shevchenko  * Returns: Timestamp of the event in nanoseconds.
310bc2b7dabSGregor Boirie  */
311bc2b7dabSGregor Boirie s64 iio_get_time_ns(const struct iio_dev *indio_dev)
312bc2b7dabSGregor Boirie {
31345e7f5d2SArnd Bergmann 	struct timespec64 tp;
314bc2b7dabSGregor Boirie 
315bc2b7dabSGregor Boirie 	switch (iio_device_get_clock(indio_dev)) {
316bc2b7dabSGregor Boirie 	case CLOCK_REALTIME:
31745e7f5d2SArnd Bergmann 		return ktime_get_real_ns();
318bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC:
31945e7f5d2SArnd Bergmann 		return ktime_get_ns();
320bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC_RAW:
32145e7f5d2SArnd Bergmann 		return ktime_get_raw_ns();
322bc2b7dabSGregor Boirie 	case CLOCK_REALTIME_COARSE:
32345e7f5d2SArnd Bergmann 		return ktime_to_ns(ktime_get_coarse_real());
324bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC_COARSE:
32545e7f5d2SArnd Bergmann 		ktime_get_coarse_ts64(&tp);
32645e7f5d2SArnd Bergmann 		return timespec64_to_ns(&tp);
327bc2b7dabSGregor Boirie 	case CLOCK_BOOTTIME:
3289285ec4cSJason A. Donenfeld 		return ktime_get_boottime_ns();
329bc2b7dabSGregor Boirie 	case CLOCK_TAI:
3309285ec4cSJason A. Donenfeld 		return ktime_get_clocktai_ns();
331bc2b7dabSGregor Boirie 	default:
332bc2b7dabSGregor Boirie 		BUG();
333bc2b7dabSGregor Boirie 	}
334bc2b7dabSGregor Boirie }
335bc2b7dabSGregor Boirie EXPORT_SYMBOL(iio_get_time_ns);
336bc2b7dabSGregor Boirie 
337a980e046SJonathan Cameron static int __init iio_init(void)
338a980e046SJonathan Cameron {
339a980e046SJonathan Cameron 	int ret;
340a980e046SJonathan Cameron 
341a980e046SJonathan Cameron 	/* Register sysfs bus */
342a980e046SJonathan Cameron 	ret  = bus_register(&iio_bus_type);
343a980e046SJonathan Cameron 	if (ret < 0) {
3443176dd5dSSachin Kamat 		pr_err("could not register bus type\n");
345a980e046SJonathan Cameron 		goto error_nothing;
346a980e046SJonathan Cameron 	}
347a980e046SJonathan Cameron 
348a980e046SJonathan Cameron 	ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
349a980e046SJonathan Cameron 	if (ret < 0) {
3503176dd5dSSachin Kamat 		pr_err("failed to allocate char dev region\n");
351a980e046SJonathan Cameron 		goto error_unregister_bus_type;
352a980e046SJonathan Cameron 	}
353a980e046SJonathan Cameron 
354a980e046SJonathan Cameron 	iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
355a980e046SJonathan Cameron 
356a980e046SJonathan Cameron 	return 0;
357a980e046SJonathan Cameron 
358a980e046SJonathan Cameron error_unregister_bus_type:
359a980e046SJonathan Cameron 	bus_unregister(&iio_bus_type);
360a980e046SJonathan Cameron error_nothing:
361a980e046SJonathan Cameron 	return ret;
362a980e046SJonathan Cameron }
363a980e046SJonathan Cameron 
364a980e046SJonathan Cameron static void __exit iio_exit(void)
365a980e046SJonathan Cameron {
366a980e046SJonathan Cameron 	if (iio_devt)
367a980e046SJonathan Cameron 		unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
368a980e046SJonathan Cameron 	bus_unregister(&iio_bus_type);
369a980e046SJonathan Cameron 	debugfs_remove(iio_debugfs_dentry);
370a980e046SJonathan Cameron }
371a980e046SJonathan Cameron 
372a980e046SJonathan Cameron #if defined(CONFIG_DEBUG_FS)
373a980e046SJonathan Cameron static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
374a980e046SJonathan Cameron 			      size_t count, loff_t *ppos)
375a980e046SJonathan Cameron {
376a980e046SJonathan Cameron 	struct iio_dev *indio_dev = file->private_data;
37796fb1b67SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
378abeba59fSJoe Simmons-Talbott 	unsigned int val = 0;
379a980e046SJonathan Cameron 	int ret;
380a980e046SJonathan Cameron 
3812ddc982aSAlexandru Tachici 	if (*ppos > 0)
3822ddc982aSAlexandru Tachici 		return simple_read_from_buffer(userbuf, count, ppos,
38396fb1b67SAlexandru Ardelean 					       iio_dev_opaque->read_buf,
38496fb1b67SAlexandru Ardelean 					       iio_dev_opaque->read_buf_len);
3852ddc982aSAlexandru Tachici 
386a980e046SJonathan Cameron 	ret = indio_dev->info->debugfs_reg_access(indio_dev,
38796fb1b67SAlexandru Ardelean 						  iio_dev_opaque->cached_reg_addr,
388a980e046SJonathan Cameron 						  0, &val);
3893d62c78aSMatt Fornero 	if (ret) {
390a980e046SJonathan Cameron 		dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
3913d62c78aSMatt Fornero 		return ret;
3923d62c78aSMatt Fornero 	}
393a980e046SJonathan Cameron 
39496fb1b67SAlexandru Ardelean 	iio_dev_opaque->read_buf_len = snprintf(iio_dev_opaque->read_buf,
39596fb1b67SAlexandru Ardelean 						sizeof(iio_dev_opaque->read_buf),
3962ddc982aSAlexandru Tachici 						"0x%X\n", val);
397a980e046SJonathan Cameron 
3982ddc982aSAlexandru Tachici 	return simple_read_from_buffer(userbuf, count, ppos,
39996fb1b67SAlexandru Ardelean 				       iio_dev_opaque->read_buf,
40096fb1b67SAlexandru Ardelean 				       iio_dev_opaque->read_buf_len);
401a980e046SJonathan Cameron }
402a980e046SJonathan Cameron 
403a980e046SJonathan Cameron static ssize_t iio_debugfs_write_reg(struct file *file,
404a980e046SJonathan Cameron 		     const char __user *userbuf, size_t count, loff_t *ppos)
405a980e046SJonathan Cameron {
406a980e046SJonathan Cameron 	struct iio_dev *indio_dev = file->private_data;
40796fb1b67SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
408abeba59fSJoe Simmons-Talbott 	unsigned int reg, val;
409a980e046SJonathan Cameron 	char buf[80];
410a980e046SJonathan Cameron 	int ret;
411a980e046SJonathan Cameron 
412cb1d1753SAndy Shevchenko 	count = min(count, sizeof(buf) - 1);
413a980e046SJonathan Cameron 	if (copy_from_user(buf, userbuf, count))
414a980e046SJonathan Cameron 		return -EFAULT;
415a980e046SJonathan Cameron 
416a980e046SJonathan Cameron 	buf[count] = 0;
417a980e046SJonathan Cameron 
418a980e046SJonathan Cameron 	ret = sscanf(buf, "%i %i", &reg, &val);
419a980e046SJonathan Cameron 
420a980e046SJonathan Cameron 	switch (ret) {
421a980e046SJonathan Cameron 	case 1:
42296fb1b67SAlexandru Ardelean 		iio_dev_opaque->cached_reg_addr = reg;
423a980e046SJonathan Cameron 		break;
424a980e046SJonathan Cameron 	case 2:
42596fb1b67SAlexandru Ardelean 		iio_dev_opaque->cached_reg_addr = reg;
426a980e046SJonathan Cameron 		ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
427a980e046SJonathan Cameron 							  val, NULL);
428a980e046SJonathan Cameron 		if (ret) {
429a980e046SJonathan Cameron 			dev_err(indio_dev->dev.parent, "%s: write failed\n",
430a980e046SJonathan Cameron 				__func__);
431a980e046SJonathan Cameron 			return ret;
432a980e046SJonathan Cameron 		}
433a980e046SJonathan Cameron 		break;
434a980e046SJonathan Cameron 	default:
435a980e046SJonathan Cameron 		return -EINVAL;
436a980e046SJonathan Cameron 	}
437a980e046SJonathan Cameron 
438a980e046SJonathan Cameron 	return count;
439a980e046SJonathan Cameron }
440a980e046SJonathan Cameron 
441a980e046SJonathan Cameron static const struct file_operations iio_debugfs_reg_fops = {
4425a28c873SAxel Lin 	.open = simple_open,
443a980e046SJonathan Cameron 	.read = iio_debugfs_read_reg,
444a980e046SJonathan Cameron 	.write = iio_debugfs_write_reg,
445a980e046SJonathan Cameron };
446a980e046SJonathan Cameron 
447a980e046SJonathan Cameron static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
448a980e046SJonathan Cameron {
44996fb1b67SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
4509d9ec8d0SJoe Simmons-Talbott 
45196fb1b67SAlexandru Ardelean 	debugfs_remove_recursive(iio_dev_opaque->debugfs_dentry);
452a980e046SJonathan Cameron }
453a980e046SJonathan Cameron 
4548915aacaSGreg Kroah-Hartman static void iio_device_register_debugfs(struct iio_dev *indio_dev)
455a980e046SJonathan Cameron {
45696fb1b67SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque;
45796fb1b67SAlexandru Ardelean 
458a980e046SJonathan Cameron 	if (indio_dev->info->debugfs_reg_access == NULL)
4598915aacaSGreg Kroah-Hartman 		return;
460a980e046SJonathan Cameron 
461abd5a2fbSAxel Lin 	if (!iio_debugfs_dentry)
4628915aacaSGreg Kroah-Hartman 		return;
463a980e046SJonathan Cameron 
46496fb1b67SAlexandru Ardelean 	iio_dev_opaque = to_iio_dev_opaque(indio_dev);
46596fb1b67SAlexandru Ardelean 
46696fb1b67SAlexandru Ardelean 	iio_dev_opaque->debugfs_dentry =
467a980e046SJonathan Cameron 		debugfs_create_dir(dev_name(&indio_dev->dev),
468a980e046SJonathan Cameron 				   iio_debugfs_dentry);
469a980e046SJonathan Cameron 
4708915aacaSGreg Kroah-Hartman 	debugfs_create_file("direct_reg_access", 0644,
47196fb1b67SAlexandru Ardelean 			    iio_dev_opaque->debugfs_dentry, indio_dev,
4728915aacaSGreg Kroah-Hartman 			    &iio_debugfs_reg_fops);
473a980e046SJonathan Cameron }
474a980e046SJonathan Cameron #else
4758915aacaSGreg Kroah-Hartman static void iio_device_register_debugfs(struct iio_dev *indio_dev)
476a980e046SJonathan Cameron {
477a980e046SJonathan Cameron }
478a980e046SJonathan Cameron 
479a980e046SJonathan Cameron static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
480a980e046SJonathan Cameron {
481a980e046SJonathan Cameron }
482a980e046SJonathan Cameron #endif /* CONFIG_DEBUG_FS */
483a980e046SJonathan Cameron 
484a980e046SJonathan Cameron static ssize_t iio_read_channel_ext_info(struct device *dev,
485a980e046SJonathan Cameron 				     struct device_attribute *attr,
486a980e046SJonathan Cameron 				     char *buf)
487a980e046SJonathan Cameron {
488e53f5ac5SLars-Peter Clausen 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
489a980e046SJonathan Cameron 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
490a980e046SJonathan Cameron 	const struct iio_chan_spec_ext_info *ext_info;
491a980e046SJonathan Cameron 
492a980e046SJonathan Cameron 	ext_info = &this_attr->c->ext_info[this_attr->address];
493a980e046SJonathan Cameron 
494fc6d1139SMichael Hennerich 	return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
495a980e046SJonathan Cameron }
496a980e046SJonathan Cameron 
497a980e046SJonathan Cameron static ssize_t iio_write_channel_ext_info(struct device *dev,
498a980e046SJonathan Cameron 				     struct device_attribute *attr,
499b662f4baSAndy Shevchenko 				     const char *buf, size_t len)
500a980e046SJonathan Cameron {
501e53f5ac5SLars-Peter Clausen 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
502a980e046SJonathan Cameron 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
503a980e046SJonathan Cameron 	const struct iio_chan_spec_ext_info *ext_info;
504a980e046SJonathan Cameron 
505a980e046SJonathan Cameron 	ext_info = &this_attr->c->ext_info[this_attr->address];
506a980e046SJonathan Cameron 
507fc6d1139SMichael Hennerich 	return ext_info->write(indio_dev, ext_info->private,
508fc6d1139SMichael Hennerich 			       this_attr->c, buf, len);
509a980e046SJonathan Cameron }
510a980e046SJonathan Cameron 
5115212cc8aSLars-Peter Clausen ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
5125212cc8aSLars-Peter Clausen 	uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
5135212cc8aSLars-Peter Clausen {
5145212cc8aSLars-Peter Clausen 	const struct iio_enum *e = (const struct iio_enum *)priv;
5155212cc8aSLars-Peter Clausen 	unsigned int i;
5165212cc8aSLars-Peter Clausen 	size_t len = 0;
5175212cc8aSLars-Peter Clausen 
5185212cc8aSLars-Peter Clausen 	if (!e->num_items)
5195212cc8aSLars-Peter Clausen 		return 0;
5205212cc8aSLars-Peter Clausen 
521d9a0e73cSLars-Peter Clausen 	for (i = 0; i < e->num_items; ++i) {
522d9a0e73cSLars-Peter Clausen 		if (!e->items[i])
523d9a0e73cSLars-Peter Clausen 			continue;
5240207483bSLars-Peter Clausen 		len += sysfs_emit_at(buf, len, "%s ", e->items[i]);
525d9a0e73cSLars-Peter Clausen 	}
5265212cc8aSLars-Peter Clausen 
5275212cc8aSLars-Peter Clausen 	/* replace last space with a newline */
5285212cc8aSLars-Peter Clausen 	buf[len - 1] = '\n';
5295212cc8aSLars-Peter Clausen 
5305212cc8aSLars-Peter Clausen 	return len;
5315212cc8aSLars-Peter Clausen }
5325212cc8aSLars-Peter Clausen EXPORT_SYMBOL_GPL(iio_enum_available_read);
5335212cc8aSLars-Peter Clausen 
5345212cc8aSLars-Peter Clausen ssize_t iio_enum_read(struct iio_dev *indio_dev,
5355212cc8aSLars-Peter Clausen 	uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
5365212cc8aSLars-Peter Clausen {
5375212cc8aSLars-Peter Clausen 	const struct iio_enum *e = (const struct iio_enum *)priv;
5385212cc8aSLars-Peter Clausen 	int i;
5395212cc8aSLars-Peter Clausen 
5405212cc8aSLars-Peter Clausen 	if (!e->get)
5415212cc8aSLars-Peter Clausen 		return -EINVAL;
5425212cc8aSLars-Peter Clausen 
5435212cc8aSLars-Peter Clausen 	i = e->get(indio_dev, chan);
5445212cc8aSLars-Peter Clausen 	if (i < 0)
5455212cc8aSLars-Peter Clausen 		return i;
5461702df5dSAndy Shevchenko 	if (i >= e->num_items || !e->items[i])
5475212cc8aSLars-Peter Clausen 		return -EINVAL;
5485212cc8aSLars-Peter Clausen 
54983ca56b6SLars-Peter Clausen 	return sysfs_emit(buf, "%s\n", e->items[i]);
5505212cc8aSLars-Peter Clausen }
5515212cc8aSLars-Peter Clausen EXPORT_SYMBOL_GPL(iio_enum_read);
5525212cc8aSLars-Peter Clausen 
5535212cc8aSLars-Peter Clausen ssize_t iio_enum_write(struct iio_dev *indio_dev,
5545212cc8aSLars-Peter Clausen 	uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
5555212cc8aSLars-Peter Clausen 	size_t len)
5565212cc8aSLars-Peter Clausen {
5575212cc8aSLars-Peter Clausen 	const struct iio_enum *e = (const struct iio_enum *)priv;
5585212cc8aSLars-Peter Clausen 	int ret;
5595212cc8aSLars-Peter Clausen 
5605212cc8aSLars-Peter Clausen 	if (!e->set)
5615212cc8aSLars-Peter Clausen 		return -EINVAL;
5625212cc8aSLars-Peter Clausen 
563122fb873SAndy Shevchenko 	ret = __sysfs_match_string(e->items, e->num_items, buf);
56402e9a0ffSAndy Shevchenko 	if (ret < 0)
56502e9a0ffSAndy Shevchenko 		return ret;
5665212cc8aSLars-Peter Clausen 
56702e9a0ffSAndy Shevchenko 	ret = e->set(indio_dev, chan, ret);
5685212cc8aSLars-Peter Clausen 	return ret ? ret : len;
5695212cc8aSLars-Peter Clausen }
5705212cc8aSLars-Peter Clausen EXPORT_SYMBOL_GPL(iio_enum_write);
5715212cc8aSLars-Peter Clausen 
572dfc57732SGregor Boirie static const struct iio_mount_matrix iio_mount_idmatrix = {
573dfc57732SGregor Boirie 	.rotation = {
574dfc57732SGregor Boirie 		"1", "0", "0",
575dfc57732SGregor Boirie 		"0", "1", "0",
576dfc57732SGregor Boirie 		"0", "0", "1"
577dfc57732SGregor Boirie 	}
578dfc57732SGregor Boirie };
579dfc57732SGregor Boirie 
580dfc57732SGregor Boirie static int iio_setup_mount_idmatrix(const struct device *dev,
581dfc57732SGregor Boirie 				    struct iio_mount_matrix *matrix)
582dfc57732SGregor Boirie {
583dfc57732SGregor Boirie 	*matrix = iio_mount_idmatrix;
584dfc57732SGregor Boirie 	dev_info(dev, "mounting matrix not found: using identity...\n");
585dfc57732SGregor Boirie 	return 0;
586dfc57732SGregor Boirie }
587dfc57732SGregor Boirie 
588dfc57732SGregor Boirie ssize_t iio_show_mount_matrix(struct iio_dev *indio_dev, uintptr_t priv,
589dfc57732SGregor Boirie 			      const struct iio_chan_spec *chan, char *buf)
590dfc57732SGregor Boirie {
591b662f4baSAndy Shevchenko 	const struct iio_mount_matrix *mtx;
592dfc57732SGregor Boirie 
593b662f4baSAndy Shevchenko 	mtx = ((iio_get_mount_matrix_t *)priv)(indio_dev, chan);
594dfc57732SGregor Boirie 	if (IS_ERR(mtx))
595dfc57732SGregor Boirie 		return PTR_ERR(mtx);
596dfc57732SGregor Boirie 
597dfc57732SGregor Boirie 	if (!mtx)
598dfc57732SGregor Boirie 		mtx = &iio_mount_idmatrix;
599dfc57732SGregor Boirie 
60083ca56b6SLars-Peter Clausen 	return sysfs_emit(buf, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
601dfc57732SGregor Boirie 			  mtx->rotation[0], mtx->rotation[1], mtx->rotation[2],
602dfc57732SGregor Boirie 			  mtx->rotation[3], mtx->rotation[4], mtx->rotation[5],
603dfc57732SGregor Boirie 			  mtx->rotation[6], mtx->rotation[7], mtx->rotation[8]);
604dfc57732SGregor Boirie }
605dfc57732SGregor Boirie EXPORT_SYMBOL_GPL(iio_show_mount_matrix);
606dfc57732SGregor Boirie 
607dfc57732SGregor Boirie /**
608fb158971SAndy Shevchenko  * iio_read_mount_matrix() - retrieve iio device mounting matrix from
609fb158971SAndy Shevchenko  *                           device "mount-matrix" property
610dfc57732SGregor Boirie  * @dev:	device the mounting matrix property is assigned to
611dfc57732SGregor Boirie  * @matrix:	where to store retrieved matrix
612dfc57732SGregor Boirie  *
613dfc57732SGregor Boirie  * If device is assigned no mounting matrix property, a default 3x3 identity
614dfc57732SGregor Boirie  * matrix will be filled in.
615dfc57732SGregor Boirie  *
61665659a8dSAndy Shevchenko  * Returns: 0 if success, or a negative error code on failure.
617dfc57732SGregor Boirie  */
618b892770aSAndy Shevchenko int iio_read_mount_matrix(struct device *dev, struct iio_mount_matrix *matrix)
619dfc57732SGregor Boirie {
620fb158971SAndy Shevchenko 	size_t len = ARRAY_SIZE(iio_mount_idmatrix.rotation);
621fb158971SAndy Shevchenko 	int err;
622dfc57732SGregor Boirie 
623b892770aSAndy Shevchenko 	err = device_property_read_string_array(dev, "mount-matrix", matrix->rotation, len);
624fb158971SAndy Shevchenko 	if (err == len)
625dfc57732SGregor Boirie 		return 0;
626dfc57732SGregor Boirie 
627dfc57732SGregor Boirie 	if (err >= 0)
628dfc57732SGregor Boirie 		/* Invalid number of matrix entries. */
629dfc57732SGregor Boirie 		return -EINVAL;
630dfc57732SGregor Boirie 
631dfc57732SGregor Boirie 	if (err != -EINVAL)
632dfc57732SGregor Boirie 		/* Invalid matrix declaration format. */
633dfc57732SGregor Boirie 		return err;
634dfc57732SGregor Boirie 
635dfc57732SGregor Boirie 	/* Matrix was not declared at all: fallback to identity. */
636dfc57732SGregor Boirie 	return iio_setup_mount_idmatrix(dev, matrix);
637dfc57732SGregor Boirie }
638fb158971SAndy Shevchenko EXPORT_SYMBOL(iio_read_mount_matrix);
639dfc57732SGregor Boirie 
6406b92ba0aSLars-Peter Clausen static ssize_t __iio_format_value(char *buf, size_t offset, unsigned int type,
64151239600SJonathan Cameron 				  int size, const int *vals)
64251239600SJonathan Cameron {
64351239600SJonathan Cameron 	int tmp0, tmp1;
6440e7a3978SAnand Ashok Dumbre 	s64 tmp2;
64551239600SJonathan Cameron 	bool scale_db = false;
64651239600SJonathan Cameron 
64751239600SJonathan Cameron 	switch (type) {
64851239600SJonathan Cameron 	case IIO_VAL_INT:
6496b92ba0aSLars-Peter Clausen 		return sysfs_emit_at(buf, offset, "%d", vals[0]);
65051239600SJonathan Cameron 	case IIO_VAL_INT_PLUS_MICRO_DB:
65151239600SJonathan Cameron 		scale_db = true;
652df561f66SGustavo A. R. Silva 		fallthrough;
65351239600SJonathan Cameron 	case IIO_VAL_INT_PLUS_MICRO:
65451239600SJonathan Cameron 		if (vals[1] < 0)
6556b92ba0aSLars-Peter Clausen 			return sysfs_emit_at(buf, offset, "-%d.%06u%s",
6566b92ba0aSLars-Peter Clausen 					     abs(vals[0]), -vals[1],
65751239600SJonathan Cameron 					     scale_db ? " dB" : "");
6586b92ba0aSLars-Peter Clausen 		else
6596b92ba0aSLars-Peter Clausen 			return sysfs_emit_at(buf, offset, "%d.%06u%s", vals[0],
6606b92ba0aSLars-Peter Clausen 					     vals[1], scale_db ? " dB" : "");
66151239600SJonathan Cameron 	case IIO_VAL_INT_PLUS_NANO:
66251239600SJonathan Cameron 		if (vals[1] < 0)
6636b92ba0aSLars-Peter Clausen 			return sysfs_emit_at(buf, offset, "-%d.%09u",
6646b92ba0aSLars-Peter Clausen 					     abs(vals[0]), -vals[1]);
66551239600SJonathan Cameron 		else
6666b92ba0aSLars-Peter Clausen 			return sysfs_emit_at(buf, offset, "%d.%09u", vals[0],
6676b92ba0aSLars-Peter Clausen 					     vals[1]);
66851239600SJonathan Cameron 	case IIO_VAL_FRACTIONAL:
6690e7a3978SAnand Ashok Dumbre 		tmp2 = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
67051239600SJonathan Cameron 		tmp1 = vals[1];
6710e7a3978SAnand Ashok Dumbre 		tmp0 = (int)div_s64_rem(tmp2, 1000000000, &tmp1);
6720e7a3978SAnand Ashok Dumbre 		if ((tmp2 < 0) && (tmp0 == 0))
6736b92ba0aSLars-Peter Clausen 			return sysfs_emit_at(buf, offset, "-0.%09u", abs(tmp1));
6740e7a3978SAnand Ashok Dumbre 		else
6756b92ba0aSLars-Peter Clausen 			return sysfs_emit_at(buf, offset, "%d.%09u", tmp0,
6766b92ba0aSLars-Peter Clausen 					     abs(tmp1));
67751239600SJonathan Cameron 	case IIO_VAL_FRACTIONAL_LOG2:
6782646a95dSLars-Peter Clausen 		tmp2 = shift_right((s64)vals[0] * 1000000000LL, vals[1]);
6792646a95dSLars-Peter Clausen 		tmp0 = (int)div_s64_rem(tmp2, 1000000000LL, &tmp1);
68038a52cdeSLars-Peter Clausen 		if (tmp0 == 0 && tmp2 < 0)
6816b92ba0aSLars-Peter Clausen 			return sysfs_emit_at(buf, offset, "-0.%09u", abs(tmp1));
68238a52cdeSLars-Peter Clausen 		else
6836b92ba0aSLars-Peter Clausen 			return sysfs_emit_at(buf, offset, "%d.%09u", tmp0,
6846b92ba0aSLars-Peter Clausen 					     abs(tmp1));
68551239600SJonathan Cameron 	case IIO_VAL_INT_MULTIPLE:
68651239600SJonathan Cameron 	{
68751239600SJonathan Cameron 		int i;
68851239600SJonathan Cameron 		int l = 0;
68951239600SJonathan Cameron 
6906b92ba0aSLars-Peter Clausen 		for (i = 0; i < size; ++i)
6916b92ba0aSLars-Peter Clausen 			l += sysfs_emit_at(buf, offset + l, "%d ", vals[i]);
69251239600SJonathan Cameron 		return l;
69351239600SJonathan Cameron 	}
6948cb34036SAndrea Merello 	case IIO_VAL_CHAR:
6956b92ba0aSLars-Peter Clausen 		return sysfs_emit_at(buf, offset, "%c", (char)vals[0]);
6966bb835f3SAndriy Tryshnivskyy 	case IIO_VAL_INT_64:
6976bb835f3SAndriy Tryshnivskyy 		tmp2 = (s64)((((u64)vals[1]) << 32) | (u32)vals[0]);
6986bb835f3SAndriy Tryshnivskyy 		return sysfs_emit_at(buf, offset, "%lld", tmp2);
69951239600SJonathan Cameron 	default:
70051239600SJonathan Cameron 		return 0;
70151239600SJonathan Cameron 	}
70251239600SJonathan Cameron }
70351239600SJonathan Cameron 
7043661f3f5SLars-Peter Clausen /**
7053661f3f5SLars-Peter Clausen  * iio_format_value() - Formats a IIO value into its string representation
7062498dcf6SCristina Opriceana  * @buf:	The buffer to which the formatted value gets written
70751239600SJonathan Cameron  *		which is assumed to be big enough (i.e. PAGE_SIZE).
708c175cb7cSRandy Dunlap  * @type:	One of the IIO_VAL_* constants. This decides how the val
7092498dcf6SCristina Opriceana  *		and val2 parameters are formatted.
7102498dcf6SCristina Opriceana  * @size:	Number of IIO value entries contained in vals
7112498dcf6SCristina Opriceana  * @vals:	Pointer to the values, exact meaning depends on the
7122498dcf6SCristina Opriceana  *		type parameter.
7132498dcf6SCristina Opriceana  *
71465659a8dSAndy Shevchenko  * Returns:
71565659a8dSAndy Shevchenko  * 0 by default, a negative number on failure or the total number of characters
71665659a8dSAndy Shevchenko  * written for a type that belongs to the IIO_VAL_* constant.
7173661f3f5SLars-Peter Clausen  */
7189fbfb4b3SSrinivas Pandruvada ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
719a980e046SJonathan Cameron {
72051239600SJonathan Cameron 	ssize_t len;
721a980e046SJonathan Cameron 
7226b92ba0aSLars-Peter Clausen 	len = __iio_format_value(buf, 0, type, size, vals);
72351239600SJonathan Cameron 	if (len >= PAGE_SIZE - 1)
72451239600SJonathan Cameron 		return -EFBIG;
7259fbfb4b3SSrinivas Pandruvada 
7266b92ba0aSLars-Peter Clausen 	return len + sysfs_emit_at(buf, len, "\n");
72767eedba3SMichael Hennerich }
7287d2c2acaSAndrew F. Davis EXPORT_SYMBOL_GPL(iio_format_value);
729a980e046SJonathan Cameron 
7300214b27fSSean Anderson ssize_t do_iio_read_channel_label(struct iio_dev *indio_dev,
7310214b27fSSean Anderson 				  const struct iio_chan_spec *c,
7320214b27fSSean Anderson 				  char *buf)
7330214b27fSSean Anderson {
7340214b27fSSean Anderson 	if (indio_dev->info->read_label)
7350214b27fSSean Anderson 		return indio_dev->info->read_label(indio_dev, c, buf);
7360214b27fSSean Anderson 
7370214b27fSSean Anderson 	if (c->extend_name)
7380214b27fSSean Anderson 		return sysfs_emit(buf, "%s\n", c->extend_name);
7390214b27fSSean Anderson 
7400214b27fSSean Anderson 	return -EINVAL;
7410214b27fSSean Anderson }
7420214b27fSSean Anderson 
7431d4ef9b3SCristian Pop static ssize_t iio_read_channel_label(struct device *dev,
7441d4ef9b3SCristian Pop 				      struct device_attribute *attr,
7451d4ef9b3SCristian Pop 				      char *buf)
7461d4ef9b3SCristian Pop {
7470214b27fSSean Anderson 	return do_iio_read_channel_label(dev_to_iio_dev(dev),
7480214b27fSSean Anderson 					 to_iio_dev_attr(attr)->c, buf);
7491d4ef9b3SCristian Pop }
7501d4ef9b3SCristian Pop 
7513661f3f5SLars-Peter Clausen static ssize_t iio_read_channel_info(struct device *dev,
7523661f3f5SLars-Peter Clausen 				     struct device_attribute *attr,
7533661f3f5SLars-Peter Clausen 				     char *buf)
7543661f3f5SLars-Peter Clausen {
7553661f3f5SLars-Peter Clausen 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
7563661f3f5SLars-Peter Clausen 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
7579fbfb4b3SSrinivas Pandruvada 	int vals[INDIO_MAX_RAW_ELEMENTS];
7589fbfb4b3SSrinivas Pandruvada 	int ret;
7599fbfb4b3SSrinivas Pandruvada 	int val_len = 2;
7609fbfb4b3SSrinivas Pandruvada 
7619fbfb4b3SSrinivas Pandruvada 	if (indio_dev->info->read_raw_multi)
7629fbfb4b3SSrinivas Pandruvada 		ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
7639fbfb4b3SSrinivas Pandruvada 							INDIO_MAX_RAW_ELEMENTS,
7649fbfb4b3SSrinivas Pandruvada 							vals, &val_len,
7659fbfb4b3SSrinivas Pandruvada 							this_attr->address);
766c4ec8dedSJulien Stephan 	else if (indio_dev->info->read_raw)
7679fbfb4b3SSrinivas Pandruvada 		ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
7689fbfb4b3SSrinivas Pandruvada 				    &vals[0], &vals[1], this_attr->address);
769c4ec8dedSJulien Stephan 	else
770c4ec8dedSJulien Stephan 		return -EINVAL;
7713661f3f5SLars-Peter Clausen 
7723661f3f5SLars-Peter Clausen 	if (ret < 0)
7733661f3f5SLars-Peter Clausen 		return ret;
7743661f3f5SLars-Peter Clausen 
7759fbfb4b3SSrinivas Pandruvada 	return iio_format_value(buf, ret, val_len, vals);
7763661f3f5SLars-Peter Clausen }
7773661f3f5SLars-Peter Clausen 
778eda20ba1SLars-Peter Clausen static ssize_t iio_format_list(char *buf, const int *vals, int type, int length,
779eda20ba1SLars-Peter Clausen 			       const char *prefix, const char *suffix)
78051239600SJonathan Cameron {
781eda20ba1SLars-Peter Clausen 	ssize_t len;
782e08b60d3SLars-Peter Clausen 	int stride;
78351239600SJonathan Cameron 	int i;
784eda20ba1SLars-Peter Clausen 
78551239600SJonathan Cameron 	switch (type) {
78651239600SJonathan Cameron 	case IIO_VAL_INT:
787e08b60d3SLars-Peter Clausen 		stride = 1;
78851239600SJonathan Cameron 		break;
78951239600SJonathan Cameron 	default:
790e08b60d3SLars-Peter Clausen 		stride = 2;
791e08b60d3SLars-Peter Clausen 		break;
792e08b60d3SLars-Peter Clausen 	}
793e08b60d3SLars-Peter Clausen 
7946b92ba0aSLars-Peter Clausen 	len = sysfs_emit(buf, prefix);
795e08b60d3SLars-Peter Clausen 
796e08b60d3SLars-Peter Clausen 	for (i = 0; i <= length - stride; i += stride) {
797e08b60d3SLars-Peter Clausen 		if (i != 0) {
7986b92ba0aSLars-Peter Clausen 			len += sysfs_emit_at(buf, len, " ");
79951239600SJonathan Cameron 			if (len >= PAGE_SIZE)
80051239600SJonathan Cameron 				return -EFBIG;
80151239600SJonathan Cameron 		}
802e08b60d3SLars-Peter Clausen 
8036b92ba0aSLars-Peter Clausen 		len += __iio_format_value(buf, len, type, stride, &vals[i]);
804e08b60d3SLars-Peter Clausen 		if (len >= PAGE_SIZE)
805e08b60d3SLars-Peter Clausen 			return -EFBIG;
80651239600SJonathan Cameron 	}
80751239600SJonathan Cameron 
8086b92ba0aSLars-Peter Clausen 	len += sysfs_emit_at(buf, len, "%s\n", suffix);
809e08b60d3SLars-Peter Clausen 
81051239600SJonathan Cameron 	return len;
81151239600SJonathan Cameron }
81251239600SJonathan Cameron 
813eda20ba1SLars-Peter Clausen static ssize_t iio_format_avail_list(char *buf, const int *vals,
814eda20ba1SLars-Peter Clausen 				     int type, int length)
815eda20ba1SLars-Peter Clausen {
816eda20ba1SLars-Peter Clausen 
817eda20ba1SLars-Peter Clausen 	return iio_format_list(buf, vals, type, length, "", "");
818eda20ba1SLars-Peter Clausen }
819eda20ba1SLars-Peter Clausen 
82051239600SJonathan Cameron static ssize_t iio_format_avail_range(char *buf, const int *vals, int type)
82151239600SJonathan Cameron {
8225e1f9185SFawzi Khaber 	int length;
8235e1f9185SFawzi Khaber 
8245e1f9185SFawzi Khaber 	/*
8255e1f9185SFawzi Khaber 	 * length refers to the array size , not the number of elements.
8265e1f9185SFawzi Khaber 	 * The purpose is to print the range [min , step ,max] so length should
8275e1f9185SFawzi Khaber 	 * be 3 in case of int, and 6 for other types.
8285e1f9185SFawzi Khaber 	 */
8295e1f9185SFawzi Khaber 	switch (type) {
8305e1f9185SFawzi Khaber 	case IIO_VAL_INT:
8315e1f9185SFawzi Khaber 		length = 3;
8325e1f9185SFawzi Khaber 		break;
8335e1f9185SFawzi Khaber 	default:
8345e1f9185SFawzi Khaber 		length = 6;
8355e1f9185SFawzi Khaber 		break;
8365e1f9185SFawzi Khaber 	}
8375e1f9185SFawzi Khaber 
8385e1f9185SFawzi Khaber 	return iio_format_list(buf, vals, type, length, "[", "]");
83951239600SJonathan Cameron }
84051239600SJonathan Cameron 
84151239600SJonathan Cameron static ssize_t iio_read_channel_info_avail(struct device *dev,
84251239600SJonathan Cameron 					   struct device_attribute *attr,
84351239600SJonathan Cameron 					   char *buf)
84451239600SJonathan Cameron {
84551239600SJonathan Cameron 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
84651239600SJonathan Cameron 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
84751239600SJonathan Cameron 	const int *vals;
84851239600SJonathan Cameron 	int ret;
84951239600SJonathan Cameron 	int length;
85051239600SJonathan Cameron 	int type;
85151239600SJonathan Cameron 
852c4ec8dedSJulien Stephan 	if (!indio_dev->info->read_avail)
853c4ec8dedSJulien Stephan 		return -EINVAL;
854c4ec8dedSJulien Stephan 
85551239600SJonathan Cameron 	ret = indio_dev->info->read_avail(indio_dev, this_attr->c,
85651239600SJonathan Cameron 					  &vals, &type, &length,
85751239600SJonathan Cameron 					  this_attr->address);
85851239600SJonathan Cameron 
85951239600SJonathan Cameron 	if (ret < 0)
86051239600SJonathan Cameron 		return ret;
86151239600SJonathan Cameron 	switch (ret) {
86251239600SJonathan Cameron 	case IIO_AVAIL_LIST:
86351239600SJonathan Cameron 		return iio_format_avail_list(buf, vals, type, length);
86451239600SJonathan Cameron 	case IIO_AVAIL_RANGE:
86551239600SJonathan Cameron 		return iio_format_avail_range(buf, vals, type);
86651239600SJonathan Cameron 	default:
86751239600SJonathan Cameron 		return -EINVAL;
86851239600SJonathan Cameron 	}
86951239600SJonathan Cameron }
87051239600SJonathan Cameron 
8716807d721SLars-Peter Clausen /**
872b8528224SBeniamin Bia  * __iio_str_to_fixpoint() - Parse a fixed-point number from a string
8736807d721SLars-Peter Clausen  * @str: The string to parse
8746807d721SLars-Peter Clausen  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
8756807d721SLars-Peter Clausen  * @integer: The integer part of the number
8766807d721SLars-Peter Clausen  * @fract: The fractional part of the number
877b8528224SBeniamin Bia  * @scale_db: True if this should parse as dB
8786807d721SLars-Peter Clausen  *
87965659a8dSAndy Shevchenko  * Returns:
88065659a8dSAndy Shevchenko  * 0 on success, or a negative error code if the string could not be parsed.
8816807d721SLars-Peter Clausen  */
882b8528224SBeniamin Bia static int __iio_str_to_fixpoint(const char *str, int fract_mult,
883b8528224SBeniamin Bia 				 int *integer, int *fract, bool scale_db)
8846807d721SLars-Peter Clausen {
8856807d721SLars-Peter Clausen 	int i = 0, f = 0;
8866807d721SLars-Peter Clausen 	bool integer_part = true, negative = false;
8876807d721SLars-Peter Clausen 
888f47dff32SSean Nyekjaer 	if (fract_mult == 0) {
889f47dff32SSean Nyekjaer 		*fract = 0;
890f47dff32SSean Nyekjaer 
891f47dff32SSean Nyekjaer 		return kstrtoint(str, 0, integer);
892f47dff32SSean Nyekjaer 	}
893f47dff32SSean Nyekjaer 
8946807d721SLars-Peter Clausen 	if (str[0] == '-') {
8956807d721SLars-Peter Clausen 		negative = true;
8966807d721SLars-Peter Clausen 		str++;
8976807d721SLars-Peter Clausen 	} else if (str[0] == '+') {
8986807d721SLars-Peter Clausen 		str++;
8996807d721SLars-Peter Clausen 	}
9006807d721SLars-Peter Clausen 
9016807d721SLars-Peter Clausen 	while (*str) {
9026807d721SLars-Peter Clausen 		if ('0' <= *str && *str <= '9') {
9036807d721SLars-Peter Clausen 			if (integer_part) {
9046807d721SLars-Peter Clausen 				i = i * 10 + *str - '0';
9056807d721SLars-Peter Clausen 			} else {
9066807d721SLars-Peter Clausen 				f += fract_mult * (*str - '0');
9076807d721SLars-Peter Clausen 				fract_mult /= 10;
9086807d721SLars-Peter Clausen 			}
9096807d721SLars-Peter Clausen 		} else if (*str == '\n') {
9106807d721SLars-Peter Clausen 			if (*(str + 1) == '\0')
9116807d721SLars-Peter Clausen 				break;
9126807d721SLars-Peter Clausen 			return -EINVAL;
913b8528224SBeniamin Bia 		} else if (!strncmp(str, " dB", sizeof(" dB") - 1) && scale_db) {
914b8528224SBeniamin Bia 			/* Ignore the dB suffix */
915b8528224SBeniamin Bia 			str += sizeof(" dB") - 1;
916b8528224SBeniamin Bia 			continue;
917b8528224SBeniamin Bia 		} else if (!strncmp(str, "dB", sizeof("dB") - 1) && scale_db) {
918b8528224SBeniamin Bia 			/* Ignore the dB suffix */
919b8528224SBeniamin Bia 			str += sizeof("dB") - 1;
920b8528224SBeniamin Bia 			continue;
9216807d721SLars-Peter Clausen 		} else if (*str == '.' && integer_part) {
9226807d721SLars-Peter Clausen 			integer_part = false;
9236807d721SLars-Peter Clausen 		} else {
9246807d721SLars-Peter Clausen 			return -EINVAL;
9256807d721SLars-Peter Clausen 		}
9266807d721SLars-Peter Clausen 		str++;
9276807d721SLars-Peter Clausen 	}
9286807d721SLars-Peter Clausen 
9296807d721SLars-Peter Clausen 	if (negative) {
9306807d721SLars-Peter Clausen 		if (i)
9316807d721SLars-Peter Clausen 			i = -i;
9326807d721SLars-Peter Clausen 		else
9336807d721SLars-Peter Clausen 			f = -f;
9346807d721SLars-Peter Clausen 	}
9356807d721SLars-Peter Clausen 
9366807d721SLars-Peter Clausen 	*integer = i;
9376807d721SLars-Peter Clausen 	*fract = f;
9386807d721SLars-Peter Clausen 
9396807d721SLars-Peter Clausen 	return 0;
9406807d721SLars-Peter Clausen }
941b8528224SBeniamin Bia 
942b8528224SBeniamin Bia /**
943b8528224SBeniamin Bia  * iio_str_to_fixpoint() - Parse a fixed-point number from a string
944b8528224SBeniamin Bia  * @str: The string to parse
945b8528224SBeniamin Bia  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
946b8528224SBeniamin Bia  * @integer: The integer part of the number
947b8528224SBeniamin Bia  * @fract: The fractional part of the number
948b8528224SBeniamin Bia  *
94965659a8dSAndy Shevchenko  * Returns:
95065659a8dSAndy Shevchenko  * 0 on success, or a negative error code if the string could not be parsed.
951b8528224SBeniamin Bia  */
952b8528224SBeniamin Bia int iio_str_to_fixpoint(const char *str, int fract_mult,
953b8528224SBeniamin Bia 			int *integer, int *fract)
954b8528224SBeniamin Bia {
955b8528224SBeniamin Bia 	return __iio_str_to_fixpoint(str, fract_mult, integer, fract, false);
956b8528224SBeniamin Bia }
9576807d721SLars-Peter Clausen EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
9586807d721SLars-Peter Clausen 
959a980e046SJonathan Cameron static ssize_t iio_write_channel_info(struct device *dev,
960a980e046SJonathan Cameron 				      struct device_attribute *attr,
961a980e046SJonathan Cameron 				      const char *buf,
962a980e046SJonathan Cameron 				      size_t len)
963a980e046SJonathan Cameron {
964e53f5ac5SLars-Peter Clausen 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
965a980e046SJonathan Cameron 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
9666807d721SLars-Peter Clausen 	int ret, fract_mult = 100000;
9678cb34036SAndrea Merello 	int integer, fract = 0;
9688cb34036SAndrea Merello 	bool is_char = false;
969b8528224SBeniamin Bia 	bool scale_db = false;
970a980e046SJonathan Cameron 
971a980e046SJonathan Cameron 	/* Assumes decimal - precision based on number of digits */
972a980e046SJonathan Cameron 	if (!indio_dev->info->write_raw)
973a980e046SJonathan Cameron 		return -EINVAL;
974a980e046SJonathan Cameron 
975a980e046SJonathan Cameron 	if (indio_dev->info->write_raw_get_fmt)
976a980e046SJonathan Cameron 		switch (indio_dev->info->write_raw_get_fmt(indio_dev,
977a980e046SJonathan Cameron 			this_attr->c, this_attr->address)) {
978f47dff32SSean Nyekjaer 		case IIO_VAL_INT:
979f47dff32SSean Nyekjaer 			fract_mult = 0;
980f47dff32SSean Nyekjaer 			break;
981b8528224SBeniamin Bia 		case IIO_VAL_INT_PLUS_MICRO_DB:
982b8528224SBeniamin Bia 			scale_db = true;
983df561f66SGustavo A. R. Silva 			fallthrough;
984a980e046SJonathan Cameron 		case IIO_VAL_INT_PLUS_MICRO:
985a980e046SJonathan Cameron 			fract_mult = 100000;
986a980e046SJonathan Cameron 			break;
987a980e046SJonathan Cameron 		case IIO_VAL_INT_PLUS_NANO:
988a980e046SJonathan Cameron 			fract_mult = 100000000;
989a980e046SJonathan Cameron 			break;
9908cb34036SAndrea Merello 		case IIO_VAL_CHAR:
9918cb34036SAndrea Merello 			is_char = true;
9928cb34036SAndrea Merello 			break;
993a980e046SJonathan Cameron 		default:
994a980e046SJonathan Cameron 			return -EINVAL;
995a980e046SJonathan Cameron 		}
996a980e046SJonathan Cameron 
9978cb34036SAndrea Merello 	if (is_char) {
9988cb34036SAndrea Merello 		char ch;
9998cb34036SAndrea Merello 
10008cb34036SAndrea Merello 		if (sscanf(buf, "%c", &ch) != 1)
10018cb34036SAndrea Merello 			return -EINVAL;
10028cb34036SAndrea Merello 		integer = ch;
10038cb34036SAndrea Merello 	} else {
1004b8528224SBeniamin Bia 		ret = __iio_str_to_fixpoint(buf, fract_mult, &integer, &fract,
1005b8528224SBeniamin Bia 					    scale_db);
1006b8528224SBeniamin Bia 		if (ret)
1007b8528224SBeniamin Bia 			return ret;
10085403f280SMircea Caprioru 	}
1009a980e046SJonathan Cameron 
1010a980e046SJonathan Cameron 	ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
1011a980e046SJonathan Cameron 					 integer, fract, this_attr->address);
1012a980e046SJonathan Cameron 	if (ret)
1013a980e046SJonathan Cameron 		return ret;
1014a980e046SJonathan Cameron 
1015a980e046SJonathan Cameron 	return len;
1016a980e046SJonathan Cameron }
1017a980e046SJonathan Cameron 
1018a980e046SJonathan Cameron static
1019a980e046SJonathan Cameron int __iio_device_attr_init(struct device_attribute *dev_attr,
1020a980e046SJonathan Cameron 			   const char *postfix,
1021a980e046SJonathan Cameron 			   struct iio_chan_spec const *chan,
1022a980e046SJonathan Cameron 			   ssize_t (*readfunc)(struct device *dev,
1023a980e046SJonathan Cameron 					       struct device_attribute *attr,
1024a980e046SJonathan Cameron 					       char *buf),
1025a980e046SJonathan Cameron 			   ssize_t (*writefunc)(struct device *dev,
1026a980e046SJonathan Cameron 						struct device_attribute *attr,
1027a980e046SJonathan Cameron 						const char *buf,
1028a980e046SJonathan Cameron 						size_t len),
10293704432fSJonathan Cameron 			   enum iio_shared_by shared_by)
1030a980e046SJonathan Cameron {
10313704432fSJonathan Cameron 	int ret = 0;
10327bbcf7e1SLars-Peter Clausen 	char *name = NULL;
10333704432fSJonathan Cameron 	char *full_postfix;
10349d9ec8d0SJoe Simmons-Talbott 
1035a980e046SJonathan Cameron 	sysfs_attr_init(&dev_attr->attr);
1036a980e046SJonathan Cameron 
1037a980e046SJonathan Cameron 	/* Build up postfix of <extend_name>_<modifier>_postfix */
10383704432fSJonathan Cameron 	if (chan->modified && (shared_by == IIO_SEPARATE)) {
1039a980e046SJonathan Cameron 		if (chan->extend_name)
1040a980e046SJonathan Cameron 			full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
1041b662f4baSAndy Shevchenko 						 iio_modifier_names[chan->channel2],
1042a980e046SJonathan Cameron 						 chan->extend_name,
1043a980e046SJonathan Cameron 						 postfix);
1044a980e046SJonathan Cameron 		else
1045a980e046SJonathan Cameron 			full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
1046b662f4baSAndy Shevchenko 						 iio_modifier_names[chan->channel2],
1047a980e046SJonathan Cameron 						 postfix);
1048a980e046SJonathan Cameron 	} else {
104977bfa8baSLars-Peter Clausen 		if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
1050a980e046SJonathan Cameron 			full_postfix = kstrdup(postfix, GFP_KERNEL);
1051a980e046SJonathan Cameron 		else
1052a980e046SJonathan Cameron 			full_postfix = kasprintf(GFP_KERNEL,
1053a980e046SJonathan Cameron 						 "%s_%s",
1054a980e046SJonathan Cameron 						 chan->extend_name,
1055a980e046SJonathan Cameron 						 postfix);
1056a980e046SJonathan Cameron 	}
10573704432fSJonathan Cameron 	if (full_postfix == NULL)
10583704432fSJonathan Cameron 		return -ENOMEM;
1059a980e046SJonathan Cameron 
1060a980e046SJonathan Cameron 	if (chan->differential) { /* Differential can not have modifier */
10613704432fSJonathan Cameron 		switch (shared_by) {
1062c006ec83SJonathan Cameron 		case IIO_SHARED_BY_ALL:
10637bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1064c006ec83SJonathan Cameron 			break;
1065c006ec83SJonathan Cameron 		case IIO_SHARED_BY_DIR:
10667bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL, "%s_%s",
1067c006ec83SJonathan Cameron 						iio_direction[chan->output],
1068c006ec83SJonathan Cameron 						full_postfix);
1069c006ec83SJonathan Cameron 			break;
10703704432fSJonathan Cameron 		case IIO_SHARED_BY_TYPE:
10717bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
1072a980e046SJonathan Cameron 					    iio_direction[chan->output],
1073a980e046SJonathan Cameron 					    iio_chan_type_name_spec[chan->type],
1074a980e046SJonathan Cameron 					    iio_chan_type_name_spec[chan->type],
1075a980e046SJonathan Cameron 					    full_postfix);
10763704432fSJonathan Cameron 			break;
10773704432fSJonathan Cameron 		case IIO_SEPARATE:
10783704432fSJonathan Cameron 			if (!chan->indexed) {
1079231bfe53SDan Carpenter 				WARN(1, "Differential channels must be indexed\n");
10803704432fSJonathan Cameron 				ret = -EINVAL;
10813704432fSJonathan Cameron 				goto error_free_full_postfix;
10823704432fSJonathan Cameron 			}
10837bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL,
10843704432fSJonathan Cameron 					    "%s_%s%d-%s%d_%s",
1085a980e046SJonathan Cameron 					    iio_direction[chan->output],
1086a980e046SJonathan Cameron 					    iio_chan_type_name_spec[chan->type],
1087a980e046SJonathan Cameron 					    chan->channel,
1088a980e046SJonathan Cameron 					    iio_chan_type_name_spec[chan->type],
1089a980e046SJonathan Cameron 					    chan->channel2,
1090a980e046SJonathan Cameron 					    full_postfix);
10913704432fSJonathan Cameron 			break;
1092a980e046SJonathan Cameron 		}
1093a980e046SJonathan Cameron 	} else { /* Single ended */
10943704432fSJonathan Cameron 		switch (shared_by) {
1095c006ec83SJonathan Cameron 		case IIO_SHARED_BY_ALL:
10967bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1097c006ec83SJonathan Cameron 			break;
1098c006ec83SJonathan Cameron 		case IIO_SHARED_BY_DIR:
10997bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL, "%s_%s",
1100c006ec83SJonathan Cameron 						iio_direction[chan->output],
1101c006ec83SJonathan Cameron 						full_postfix);
1102c006ec83SJonathan Cameron 			break;
11033704432fSJonathan Cameron 		case IIO_SHARED_BY_TYPE:
11047bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1105a980e046SJonathan Cameron 					    iio_direction[chan->output],
1106a980e046SJonathan Cameron 					    iio_chan_type_name_spec[chan->type],
1107a980e046SJonathan Cameron 					    full_postfix);
11083704432fSJonathan Cameron 			break;
11093704432fSJonathan Cameron 
11103704432fSJonathan Cameron 		case IIO_SEPARATE:
11113704432fSJonathan Cameron 			if (chan->indexed)
11127bbcf7e1SLars-Peter Clausen 				name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
1113a980e046SJonathan Cameron 						    iio_direction[chan->output],
1114a980e046SJonathan Cameron 						    iio_chan_type_name_spec[chan->type],
1115a980e046SJonathan Cameron 						    chan->channel,
1116a980e046SJonathan Cameron 						    full_postfix);
1117a980e046SJonathan Cameron 			else
11187bbcf7e1SLars-Peter Clausen 				name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1119a980e046SJonathan Cameron 						    iio_direction[chan->output],
1120a980e046SJonathan Cameron 						    iio_chan_type_name_spec[chan->type],
1121a980e046SJonathan Cameron 						    full_postfix);
11223704432fSJonathan Cameron 			break;
11233704432fSJonathan Cameron 		}
1124a980e046SJonathan Cameron 	}
11257bbcf7e1SLars-Peter Clausen 	if (name == NULL) {
1126a980e046SJonathan Cameron 		ret = -ENOMEM;
1127a980e046SJonathan Cameron 		goto error_free_full_postfix;
1128a980e046SJonathan Cameron 	}
11297bbcf7e1SLars-Peter Clausen 	dev_attr->attr.name = name;
1130a980e046SJonathan Cameron 
1131a980e046SJonathan Cameron 	if (readfunc) {
11329cf0b618SJoe Simmons-Talbott 		dev_attr->attr.mode |= 0444;
1133a980e046SJonathan Cameron 		dev_attr->show = readfunc;
1134a980e046SJonathan Cameron 	}
1135a980e046SJonathan Cameron 
1136a980e046SJonathan Cameron 	if (writefunc) {
11379cf0b618SJoe Simmons-Talbott 		dev_attr->attr.mode |= 0200;
1138a980e046SJonathan Cameron 		dev_attr->store = writefunc;
1139a980e046SJonathan Cameron 	}
11407bbcf7e1SLars-Peter Clausen 
1141a980e046SJonathan Cameron error_free_full_postfix:
1142a980e046SJonathan Cameron 	kfree(full_postfix);
11433704432fSJonathan Cameron 
1144a980e046SJonathan Cameron 	return ret;
1145a980e046SJonathan Cameron }
1146a980e046SJonathan Cameron 
1147a980e046SJonathan Cameron static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
1148a980e046SJonathan Cameron {
1149a980e046SJonathan Cameron 	kfree(dev_attr->attr.name);
1150a980e046SJonathan Cameron }
1151a980e046SJonathan Cameron 
1152a980e046SJonathan Cameron int __iio_add_chan_devattr(const char *postfix,
1153a980e046SJonathan Cameron 			   struct iio_chan_spec const *chan,
1154a980e046SJonathan Cameron 			   ssize_t (*readfunc)(struct device *dev,
1155a980e046SJonathan Cameron 					       struct device_attribute *attr,
1156a980e046SJonathan Cameron 					       char *buf),
1157a980e046SJonathan Cameron 			   ssize_t (*writefunc)(struct device *dev,
1158a980e046SJonathan Cameron 						struct device_attribute *attr,
1159a980e046SJonathan Cameron 						const char *buf,
1160a980e046SJonathan Cameron 						size_t len),
1161a980e046SJonathan Cameron 			   u64 mask,
11623704432fSJonathan Cameron 			   enum iio_shared_by shared_by,
1163a980e046SJonathan Cameron 			   struct device *dev,
11643e3d11b2SAlexandru Ardelean 			   struct iio_buffer *buffer,
1165a980e046SJonathan Cameron 			   struct list_head *attr_list)
1166a980e046SJonathan Cameron {
1167a980e046SJonathan Cameron 	int ret;
1168a980e046SJonathan Cameron 	struct iio_dev_attr *iio_attr, *t;
1169a980e046SJonathan Cameron 
1170670c1103SSachin Kamat 	iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
117192825ff9SHartmut Knaack 	if (iio_attr == NULL)
117292825ff9SHartmut Knaack 		return -ENOMEM;
1173a980e046SJonathan Cameron 	ret = __iio_device_attr_init(&iio_attr->dev_attr,
1174a980e046SJonathan Cameron 				     postfix, chan,
11753704432fSJonathan Cameron 				     readfunc, writefunc, shared_by);
1176a980e046SJonathan Cameron 	if (ret)
1177a980e046SJonathan Cameron 		goto error_iio_dev_attr_free;
1178a980e046SJonathan Cameron 	iio_attr->c = chan;
1179a980e046SJonathan Cameron 	iio_attr->address = mask;
11803e3d11b2SAlexandru Ardelean 	iio_attr->buffer = buffer;
1181a980e046SJonathan Cameron 	list_for_each_entry(t, attr_list, l)
1182a980e046SJonathan Cameron 		if (strcmp(t->dev_attr.attr.name,
1183a980e046SJonathan Cameron 			   iio_attr->dev_attr.attr.name) == 0) {
11843704432fSJonathan Cameron 			if (shared_by == IIO_SEPARATE)
1185a980e046SJonathan Cameron 				dev_err(dev, "tried to double register : %s\n",
1186a980e046SJonathan Cameron 					t->dev_attr.attr.name);
1187a980e046SJonathan Cameron 			ret = -EBUSY;
1188a980e046SJonathan Cameron 			goto error_device_attr_deinit;
1189a980e046SJonathan Cameron 		}
1190a980e046SJonathan Cameron 	list_add(&iio_attr->l, attr_list);
1191a980e046SJonathan Cameron 
1192a980e046SJonathan Cameron 	return 0;
1193a980e046SJonathan Cameron 
1194a980e046SJonathan Cameron error_device_attr_deinit:
1195a980e046SJonathan Cameron 	__iio_device_attr_deinit(&iio_attr->dev_attr);
1196a980e046SJonathan Cameron error_iio_dev_attr_free:
1197a980e046SJonathan Cameron 	kfree(iio_attr);
1198a980e046SJonathan Cameron 	return ret;
1199a980e046SJonathan Cameron }
1200a980e046SJonathan Cameron 
12011d4ef9b3SCristian Pop static int iio_device_add_channel_label(struct iio_dev *indio_dev,
12021d4ef9b3SCristian Pop 					 struct iio_chan_spec const *chan)
12031d4ef9b3SCristian Pop {
12041d4ef9b3SCristian Pop 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
12051d4ef9b3SCristian Pop 	int ret;
12061d4ef9b3SCristian Pop 
120713efdc3dSPaul Cercueil 	if (!indio_dev->info->read_label && !chan->extend_name)
12081d4ef9b3SCristian Pop 		return 0;
12091d4ef9b3SCristian Pop 
12101d4ef9b3SCristian Pop 	ret = __iio_add_chan_devattr("label",
12111d4ef9b3SCristian Pop 				     chan,
12121d4ef9b3SCristian Pop 				     &iio_read_channel_label,
12131d4ef9b3SCristian Pop 				     NULL,
12141d4ef9b3SCristian Pop 				     0,
12151d4ef9b3SCristian Pop 				     IIO_SEPARATE,
12161d4ef9b3SCristian Pop 				     &indio_dev->dev,
12173e3d11b2SAlexandru Ardelean 				     NULL,
12181d4ef9b3SCristian Pop 				     &iio_dev_opaque->channel_attr_list);
12191d4ef9b3SCristian Pop 	if (ret < 0)
12201d4ef9b3SCristian Pop 		return ret;
12211d4ef9b3SCristian Pop 
12221d4ef9b3SCristian Pop 	return 1;
12231d4ef9b3SCristian Pop }
12241d4ef9b3SCristian Pop 
12253704432fSJonathan Cameron static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
12263704432fSJonathan Cameron 					 struct iio_chan_spec const *chan,
12273704432fSJonathan Cameron 					 enum iio_shared_by shared_by,
12283704432fSJonathan Cameron 					 const long *infomask)
12293704432fSJonathan Cameron {
1230207c2d27SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
12313704432fSJonathan Cameron 	int i, ret, attrcount = 0;
12323704432fSJonathan Cameron 
12331016d567SOrson Zhai 	for_each_set_bit(i, infomask, sizeof(*infomask)*8) {
1234ef4b4856SJonathan Cameron 		if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1235ef4b4856SJonathan Cameron 			return -EINVAL;
12363704432fSJonathan Cameron 		ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
12373704432fSJonathan Cameron 					     chan,
12383704432fSJonathan Cameron 					     &iio_read_channel_info,
12393704432fSJonathan Cameron 					     &iio_write_channel_info,
12403704432fSJonathan Cameron 					     i,
12413704432fSJonathan Cameron 					     shared_by,
12423704432fSJonathan Cameron 					     &indio_dev->dev,
12433e3d11b2SAlexandru Ardelean 					     NULL,
1244207c2d27SAlexandru Ardelean 					     &iio_dev_opaque->channel_attr_list);
12453704432fSJonathan Cameron 		if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
12463704432fSJonathan Cameron 			continue;
12471702df5dSAndy Shevchenko 		if (ret < 0)
12483704432fSJonathan Cameron 			return ret;
12493704432fSJonathan Cameron 		attrcount++;
12503704432fSJonathan Cameron 	}
12513704432fSJonathan Cameron 
12523704432fSJonathan Cameron 	return attrcount;
12533704432fSJonathan Cameron }
12543704432fSJonathan Cameron 
125551239600SJonathan Cameron static int iio_device_add_info_mask_type_avail(struct iio_dev *indio_dev,
125651239600SJonathan Cameron 					       struct iio_chan_spec const *chan,
125751239600SJonathan Cameron 					       enum iio_shared_by shared_by,
125851239600SJonathan Cameron 					       const long *infomask)
125951239600SJonathan Cameron {
1260207c2d27SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
126151239600SJonathan Cameron 	int i, ret, attrcount = 0;
126251239600SJonathan Cameron 	char *avail_postfix;
126351239600SJonathan Cameron 
12641016d567SOrson Zhai 	for_each_set_bit(i, infomask, sizeof(*infomask) * 8) {
1265936d3e53SYoung Xiao 		if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1266936d3e53SYoung Xiao 			return -EINVAL;
126751239600SJonathan Cameron 		avail_postfix = kasprintf(GFP_KERNEL,
126851239600SJonathan Cameron 					  "%s_available",
126951239600SJonathan Cameron 					  iio_chan_info_postfix[i]);
127051239600SJonathan Cameron 		if (!avail_postfix)
127151239600SJonathan Cameron 			return -ENOMEM;
127251239600SJonathan Cameron 
127351239600SJonathan Cameron 		ret = __iio_add_chan_devattr(avail_postfix,
127451239600SJonathan Cameron 					     chan,
127551239600SJonathan Cameron 					     &iio_read_channel_info_avail,
127651239600SJonathan Cameron 					     NULL,
127751239600SJonathan Cameron 					     i,
127851239600SJonathan Cameron 					     shared_by,
127951239600SJonathan Cameron 					     &indio_dev->dev,
12803e3d11b2SAlexandru Ardelean 					     NULL,
1281207c2d27SAlexandru Ardelean 					     &iio_dev_opaque->channel_attr_list);
128251239600SJonathan Cameron 		kfree(avail_postfix);
128351239600SJonathan Cameron 		if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
128451239600SJonathan Cameron 			continue;
12851702df5dSAndy Shevchenko 		if (ret < 0)
128651239600SJonathan Cameron 			return ret;
128751239600SJonathan Cameron 		attrcount++;
128851239600SJonathan Cameron 	}
128951239600SJonathan Cameron 
129051239600SJonathan Cameron 	return attrcount;
129151239600SJonathan Cameron }
129251239600SJonathan Cameron 
1293a980e046SJonathan Cameron static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
1294a980e046SJonathan Cameron 					struct iio_chan_spec const *chan)
1295a980e046SJonathan Cameron {
1296207c2d27SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1297a980e046SJonathan Cameron 	int ret, attrcount = 0;
1298a980e046SJonathan Cameron 	const struct iio_chan_spec_ext_info *ext_info;
1299a980e046SJonathan Cameron 
1300a980e046SJonathan Cameron 	if (chan->channel < 0)
1301a980e046SJonathan Cameron 		return 0;
13023704432fSJonathan Cameron 	ret = iio_device_add_info_mask_type(indio_dev, chan,
13033704432fSJonathan Cameron 					    IIO_SEPARATE,
13043704432fSJonathan Cameron 					    &chan->info_mask_separate);
13058655cc49SJonathan Cameron 	if (ret < 0)
13063704432fSJonathan Cameron 		return ret;
13073704432fSJonathan Cameron 	attrcount += ret;
13083704432fSJonathan Cameron 
130951239600SJonathan Cameron 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
131051239600SJonathan Cameron 						  IIO_SEPARATE,
1311682ca76bSJoe Simmons-Talbott 						  &chan->info_mask_separate_available);
131251239600SJonathan Cameron 	if (ret < 0)
131351239600SJonathan Cameron 		return ret;
131451239600SJonathan Cameron 	attrcount += ret;
131551239600SJonathan Cameron 
13163704432fSJonathan Cameron 	ret = iio_device_add_info_mask_type(indio_dev, chan,
13173704432fSJonathan Cameron 					    IIO_SHARED_BY_TYPE,
13183704432fSJonathan Cameron 					    &chan->info_mask_shared_by_type);
13193704432fSJonathan Cameron 	if (ret < 0)
13203704432fSJonathan Cameron 		return ret;
13213704432fSJonathan Cameron 	attrcount += ret;
1322a980e046SJonathan Cameron 
132351239600SJonathan Cameron 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
132451239600SJonathan Cameron 						  IIO_SHARED_BY_TYPE,
1325682ca76bSJoe Simmons-Talbott 						  &chan->info_mask_shared_by_type_available);
132651239600SJonathan Cameron 	if (ret < 0)
132751239600SJonathan Cameron 		return ret;
132851239600SJonathan Cameron 	attrcount += ret;
132951239600SJonathan Cameron 
1330c006ec83SJonathan Cameron 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1331c006ec83SJonathan Cameron 					    IIO_SHARED_BY_DIR,
1332c006ec83SJonathan Cameron 					    &chan->info_mask_shared_by_dir);
1333c006ec83SJonathan Cameron 	if (ret < 0)
1334c006ec83SJonathan Cameron 		return ret;
1335c006ec83SJonathan Cameron 	attrcount += ret;
1336c006ec83SJonathan Cameron 
133751239600SJonathan Cameron 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
133851239600SJonathan Cameron 						  IIO_SHARED_BY_DIR,
133951239600SJonathan Cameron 						  &chan->info_mask_shared_by_dir_available);
134051239600SJonathan Cameron 	if (ret < 0)
134151239600SJonathan Cameron 		return ret;
134251239600SJonathan Cameron 	attrcount += ret;
134351239600SJonathan Cameron 
1344c006ec83SJonathan Cameron 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1345c006ec83SJonathan Cameron 					    IIO_SHARED_BY_ALL,
1346c006ec83SJonathan Cameron 					    &chan->info_mask_shared_by_all);
1347c006ec83SJonathan Cameron 	if (ret < 0)
1348c006ec83SJonathan Cameron 		return ret;
1349c006ec83SJonathan Cameron 	attrcount += ret;
1350c006ec83SJonathan Cameron 
135151239600SJonathan Cameron 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
135251239600SJonathan Cameron 						  IIO_SHARED_BY_ALL,
135351239600SJonathan Cameron 						  &chan->info_mask_shared_by_all_available);
135451239600SJonathan Cameron 	if (ret < 0)
135551239600SJonathan Cameron 		return ret;
135651239600SJonathan Cameron 	attrcount += ret;
135751239600SJonathan Cameron 
13581d4ef9b3SCristian Pop 	ret = iio_device_add_channel_label(indio_dev, chan);
13591d4ef9b3SCristian Pop 	if (ret < 0)
13601d4ef9b3SCristian Pop 		return ret;
13611d4ef9b3SCristian Pop 	attrcount += ret;
13621d4ef9b3SCristian Pop 
1363a980e046SJonathan Cameron 	if (chan->ext_info) {
1364a980e046SJonathan Cameron 		unsigned int i = 0;
13659d9ec8d0SJoe Simmons-Talbott 
1366a980e046SJonathan Cameron 		for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
1367a980e046SJonathan Cameron 			ret = __iio_add_chan_devattr(ext_info->name,
1368a980e046SJonathan Cameron 					chan,
1369a980e046SJonathan Cameron 					ext_info->read ?
1370a980e046SJonathan Cameron 					    &iio_read_channel_ext_info : NULL,
1371a980e046SJonathan Cameron 					ext_info->write ?
1372a980e046SJonathan Cameron 					    &iio_write_channel_ext_info : NULL,
1373a980e046SJonathan Cameron 					i,
1374a980e046SJonathan Cameron 					ext_info->shared,
1375a980e046SJonathan Cameron 					&indio_dev->dev,
13763e3d11b2SAlexandru Ardelean 					NULL,
1377207c2d27SAlexandru Ardelean 					&iio_dev_opaque->channel_attr_list);
1378a980e046SJonathan Cameron 			i++;
1379a980e046SJonathan Cameron 			if (ret == -EBUSY && ext_info->shared)
1380a980e046SJonathan Cameron 				continue;
1381a980e046SJonathan Cameron 
1382a980e046SJonathan Cameron 			if (ret)
13833704432fSJonathan Cameron 				return ret;
1384a980e046SJonathan Cameron 
1385a980e046SJonathan Cameron 			attrcount++;
1386a980e046SJonathan Cameron 		}
1387a980e046SJonathan Cameron 	}
1388a980e046SJonathan Cameron 
13893704432fSJonathan Cameron 	return attrcount;
1390a980e046SJonathan Cameron }
1391a980e046SJonathan Cameron 
139284088ebdSLars-Peter Clausen /**
139384088ebdSLars-Peter Clausen  * iio_free_chan_devattr_list() - Free a list of IIO device attributes
139484088ebdSLars-Peter Clausen  * @attr_list: List of IIO device attributes
139584088ebdSLars-Peter Clausen  *
139684088ebdSLars-Peter Clausen  * This function frees the memory allocated for each of the IIO device
1397c1b03ab5SMartin Fuzzey  * attributes in the list.
139884088ebdSLars-Peter Clausen  */
139984088ebdSLars-Peter Clausen void iio_free_chan_devattr_list(struct list_head *attr_list)
1400a980e046SJonathan Cameron {
140184088ebdSLars-Peter Clausen 	struct iio_dev_attr *p, *n;
140284088ebdSLars-Peter Clausen 
140384088ebdSLars-Peter Clausen 	list_for_each_entry_safe(p, n, attr_list, l) {
140415097c7aSAlexandru Ardelean 		kfree_const(p->dev_attr.attr.name);
1405c1b03ab5SMartin Fuzzey 		list_del(&p->l);
1406a980e046SJonathan Cameron 		kfree(p);
1407a980e046SJonathan Cameron 	}
140884088ebdSLars-Peter Clausen }
1409a980e046SJonathan Cameron 
14109cf0b618SJoe Simmons-Talbott static ssize_t name_show(struct device *dev, struct device_attribute *attr,
1411a980e046SJonathan Cameron 			 char *buf)
1412a980e046SJonathan Cameron {
1413e53f5ac5SLars-Peter Clausen 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
14149d9ec8d0SJoe Simmons-Talbott 
141583ca56b6SLars-Peter Clausen 	return sysfs_emit(buf, "%s\n", indio_dev->name);
1416a980e046SJonathan Cameron }
1417a980e046SJonathan Cameron 
14189cf0b618SJoe Simmons-Talbott static DEVICE_ATTR_RO(name);
1419a980e046SJonathan Cameron 
14209cf0b618SJoe Simmons-Talbott static ssize_t label_show(struct device *dev, struct device_attribute *attr,
14212c3d0c9fSPhil Reid 			  char *buf)
14222c3d0c9fSPhil Reid {
14232c3d0c9fSPhil Reid 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
14249d9ec8d0SJoe Simmons-Talbott 
142583ca56b6SLars-Peter Clausen 	return sysfs_emit(buf, "%s\n", indio_dev->label);
14262c3d0c9fSPhil Reid }
14272c3d0c9fSPhil Reid 
14289cf0b618SJoe Simmons-Talbott static DEVICE_ATTR_RO(label);
14292c3d0c9fSPhil Reid 
1430971ddd4bSAndy Shevchenko static const char * const clock_names[] = {
1431971ddd4bSAndy Shevchenko 	[CLOCK_REALTIME]	 	= "realtime",
1432971ddd4bSAndy Shevchenko 	[CLOCK_MONOTONIC]	 	= "monotonic",
1433971ddd4bSAndy Shevchenko 	[CLOCK_PROCESS_CPUTIME_ID]	= "process_cputime_id",
1434971ddd4bSAndy Shevchenko 	[CLOCK_THREAD_CPUTIME_ID]	= "thread_cputime_id",
1435971ddd4bSAndy Shevchenko 	[CLOCK_MONOTONIC_RAW]	 	= "monotonic_raw",
1436971ddd4bSAndy Shevchenko 	[CLOCK_REALTIME_COARSE]	 	= "realtime_coarse",
1437971ddd4bSAndy Shevchenko 	[CLOCK_MONOTONIC_COARSE] 	= "monotonic_coarse",
1438971ddd4bSAndy Shevchenko 	[CLOCK_BOOTTIME]	 	= "boottime",
1439971ddd4bSAndy Shevchenko 	[CLOCK_REALTIME_ALARM]		= "realtime_alarm",
1440971ddd4bSAndy Shevchenko 	[CLOCK_BOOTTIME_ALARM]		= "boottime_alarm",
1441971ddd4bSAndy Shevchenko 	[CLOCK_SGI_CYCLE]		= "sgi_cycle",
1442971ddd4bSAndy Shevchenko 	[CLOCK_TAI]		 	= "tai",
1443971ddd4bSAndy Shevchenko };
1444971ddd4bSAndy Shevchenko 
14459cf0b618SJoe Simmons-Talbott static ssize_t current_timestamp_clock_show(struct device *dev,
1446bc2b7dabSGregor Boirie 					    struct device_attribute *attr,
1447bc2b7dabSGregor Boirie 					    char *buf)
1448bc2b7dabSGregor Boirie {
1449bc2b7dabSGregor Boirie 	const struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1450bc2b7dabSGregor Boirie 	const clockid_t clk = iio_device_get_clock(indio_dev);
1451bc2b7dabSGregor Boirie 
1452bc2b7dabSGregor Boirie 	switch (clk) {
1453bc2b7dabSGregor Boirie 	case CLOCK_REALTIME:
1454bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC:
1455bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC_RAW:
1456bc2b7dabSGregor Boirie 	case CLOCK_REALTIME_COARSE:
1457bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC_COARSE:
1458bc2b7dabSGregor Boirie 	case CLOCK_BOOTTIME:
1459bc2b7dabSGregor Boirie 	case CLOCK_TAI:
1460bc2b7dabSGregor Boirie 		break;
1461bc2b7dabSGregor Boirie 	default:
1462bc2b7dabSGregor Boirie 		BUG();
1463bc2b7dabSGregor Boirie 	}
1464bc2b7dabSGregor Boirie 
1465971ddd4bSAndy Shevchenko 	return sysfs_emit(buf, "%s\n", clock_names[clk]);
1466bc2b7dabSGregor Boirie }
1467bc2b7dabSGregor Boirie 
14689cf0b618SJoe Simmons-Talbott static ssize_t current_timestamp_clock_store(struct device *dev,
1469bc2b7dabSGregor Boirie 					     struct device_attribute *attr,
1470bc2b7dabSGregor Boirie 					     const char *buf, size_t len)
1471bc2b7dabSGregor Boirie {
1472bc2b7dabSGregor Boirie 	clockid_t clk;
1473bc2b7dabSGregor Boirie 	int ret;
1474bc2b7dabSGregor Boirie 
1475971ddd4bSAndy Shevchenko 	ret = sysfs_match_string(clock_names, buf);
1476971ddd4bSAndy Shevchenko 	if (ret < 0)
1477971ddd4bSAndy Shevchenko 		return ret;
1478971ddd4bSAndy Shevchenko 	clk = ret;
1479971ddd4bSAndy Shevchenko 
1480971ddd4bSAndy Shevchenko 	switch (clk) {
1481971ddd4bSAndy Shevchenko 	case CLOCK_REALTIME:
1482971ddd4bSAndy Shevchenko 	case CLOCK_MONOTONIC:
1483971ddd4bSAndy Shevchenko 	case CLOCK_MONOTONIC_RAW:
1484971ddd4bSAndy Shevchenko 	case CLOCK_REALTIME_COARSE:
1485971ddd4bSAndy Shevchenko 	case CLOCK_MONOTONIC_COARSE:
1486971ddd4bSAndy Shevchenko 	case CLOCK_BOOTTIME:
1487971ddd4bSAndy Shevchenko 	case CLOCK_TAI:
1488971ddd4bSAndy Shevchenko 		break;
1489971ddd4bSAndy Shevchenko 	default:
1490bc2b7dabSGregor Boirie 		return -EINVAL;
1491971ddd4bSAndy Shevchenko 	}
1492bc2b7dabSGregor Boirie 
1493bc2b7dabSGregor Boirie 	ret = iio_device_set_clock(dev_to_iio_dev(dev), clk);
1494bc2b7dabSGregor Boirie 	if (ret)
1495bc2b7dabSGregor Boirie 		return ret;
1496bc2b7dabSGregor Boirie 
1497bc2b7dabSGregor Boirie 	return len;
1498bc2b7dabSGregor Boirie }
1499bc2b7dabSGregor Boirie 
150032f17172SAlexandru Ardelean int iio_device_register_sysfs_group(struct iio_dev *indio_dev,
150132f17172SAlexandru Ardelean 				    const struct attribute_group *group)
150232f17172SAlexandru Ardelean {
150332f17172SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
150432f17172SAlexandru Ardelean 	const struct attribute_group **new, **old = iio_dev_opaque->groups;
150532f17172SAlexandru Ardelean 	unsigned int cnt = iio_dev_opaque->groupcounter;
150632f17172SAlexandru Ardelean 
15075a0821e0SAndy Shevchenko 	new = krealloc_array(old, cnt + 2, sizeof(*new), GFP_KERNEL);
150832f17172SAlexandru Ardelean 	if (!new)
150932f17172SAlexandru Ardelean 		return -ENOMEM;
151032f17172SAlexandru Ardelean 
151132f17172SAlexandru Ardelean 	new[iio_dev_opaque->groupcounter++] = group;
151232f17172SAlexandru Ardelean 	new[iio_dev_opaque->groupcounter] = NULL;
151332f17172SAlexandru Ardelean 
151432f17172SAlexandru Ardelean 	iio_dev_opaque->groups = new;
151532f17172SAlexandru Ardelean 
151632f17172SAlexandru Ardelean 	return 0;
151732f17172SAlexandru Ardelean }
151832f17172SAlexandru Ardelean 
15199cf0b618SJoe Simmons-Talbott static DEVICE_ATTR_RW(current_timestamp_clock);
1520bc2b7dabSGregor Boirie 
1521a980e046SJonathan Cameron static int iio_device_register_sysfs(struct iio_dev *indio_dev)
1522a980e046SJonathan Cameron {
1523207c2d27SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1524a980e046SJonathan Cameron 	int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
152584088ebdSLars-Peter Clausen 	struct iio_dev_attr *p;
1526bc2b7dabSGregor Boirie 	struct attribute **attr, *clk = NULL;
1527a980e046SJonathan Cameron 
1528a980e046SJonathan Cameron 	/* First count elements in any existing group */
1529a980e046SJonathan Cameron 	if (indio_dev->info->attrs) {
1530a980e046SJonathan Cameron 		attr = indio_dev->info->attrs->attrs;
1531a980e046SJonathan Cameron 		while (*attr++ != NULL)
1532a980e046SJonathan Cameron 			attrcount_orig++;
1533a980e046SJonathan Cameron 	}
1534a980e046SJonathan Cameron 	attrcount = attrcount_orig;
1535a980e046SJonathan Cameron 	/*
1536a980e046SJonathan Cameron 	 * New channel registration method - relies on the fact a group does
1537d25b3808SPeter Meerwald 	 * not need to be initialized if its name is NULL.
1538a980e046SJonathan Cameron 	 */
1539a980e046SJonathan Cameron 	if (indio_dev->channels)
1540a980e046SJonathan Cameron 		for (i = 0; i < indio_dev->num_channels; i++) {
1541bc2b7dabSGregor Boirie 			const struct iio_chan_spec *chan =
1542bc2b7dabSGregor Boirie 				&indio_dev->channels[i];
1543bc2b7dabSGregor Boirie 
1544bc2b7dabSGregor Boirie 			if (chan->type == IIO_TIMESTAMP)
1545bc2b7dabSGregor Boirie 				clk = &dev_attr_current_timestamp_clock.attr;
1546bc2b7dabSGregor Boirie 
1547bc2b7dabSGregor Boirie 			ret = iio_device_add_channel_sysfs(indio_dev, chan);
1548a980e046SJonathan Cameron 			if (ret < 0)
1549a980e046SJonathan Cameron 				goto error_clear_attrs;
1550a980e046SJonathan Cameron 			attrcount += ret;
1551a980e046SJonathan Cameron 		}
1552a980e046SJonathan Cameron 
1553fa83c3baSAlexandru Ardelean 	if (iio_dev_opaque->event_interface)
1554bc2b7dabSGregor Boirie 		clk = &dev_attr_current_timestamp_clock.attr;
1555bc2b7dabSGregor Boirie 
1556a980e046SJonathan Cameron 	if (indio_dev->name)
1557a980e046SJonathan Cameron 		attrcount++;
15582c3d0c9fSPhil Reid 	if (indio_dev->label)
15592c3d0c9fSPhil Reid 		attrcount++;
1560bc2b7dabSGregor Boirie 	if (clk)
1561bc2b7dabSGregor Boirie 		attrcount++;
1562a980e046SJonathan Cameron 
1563207c2d27SAlexandru Ardelean 	iio_dev_opaque->chan_attr_group.attrs =
1564207c2d27SAlexandru Ardelean 		kcalloc(attrcount + 1,
1565207c2d27SAlexandru Ardelean 			sizeof(iio_dev_opaque->chan_attr_group.attrs[0]),
1566a980e046SJonathan Cameron 			GFP_KERNEL);
1567207c2d27SAlexandru Ardelean 	if (iio_dev_opaque->chan_attr_group.attrs == NULL) {
1568a980e046SJonathan Cameron 		ret = -ENOMEM;
1569a980e046SJonathan Cameron 		goto error_clear_attrs;
1570a980e046SJonathan Cameron 	}
1571e0d27ea3SAndrea Merello 	/* Copy across original attributes, and point to original binary attributes */
157218b4c9cdSHans de Goede 	if (indio_dev->info->attrs) {
1573207c2d27SAlexandru Ardelean 		memcpy(iio_dev_opaque->chan_attr_group.attrs,
1574a980e046SJonathan Cameron 		       indio_dev->info->attrs->attrs,
1575207c2d27SAlexandru Ardelean 		       sizeof(iio_dev_opaque->chan_attr_group.attrs[0])
1576a980e046SJonathan Cameron 		       *attrcount_orig);
157718b4c9cdSHans de Goede 		iio_dev_opaque->chan_attr_group.is_visible =
157818b4c9cdSHans de Goede 			indio_dev->info->attrs->is_visible;
1579e0d27ea3SAndrea Merello 		iio_dev_opaque->chan_attr_group.bin_attrs =
1580e0d27ea3SAndrea Merello 			indio_dev->info->attrs->bin_attrs;
158118b4c9cdSHans de Goede 	}
1582a980e046SJonathan Cameron 	attrn = attrcount_orig;
1583a980e046SJonathan Cameron 	/* Add all elements from the list. */
1584207c2d27SAlexandru Ardelean 	list_for_each_entry(p, &iio_dev_opaque->channel_attr_list, l)
1585207c2d27SAlexandru Ardelean 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1586a980e046SJonathan Cameron 	if (indio_dev->name)
1587207c2d27SAlexandru Ardelean 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
15882c3d0c9fSPhil Reid 	if (indio_dev->label)
1589207c2d27SAlexandru Ardelean 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_label.attr;
1590bc2b7dabSGregor Boirie 	if (clk)
1591207c2d27SAlexandru Ardelean 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = clk;
1592a980e046SJonathan Cameron 
159332f17172SAlexandru Ardelean 	ret = iio_device_register_sysfs_group(indio_dev,
159432f17172SAlexandru Ardelean 					      &iio_dev_opaque->chan_attr_group);
159532f17172SAlexandru Ardelean 	if (ret)
159695a0d596SDinghao Liu 		goto error_free_chan_attrs;
1597a980e046SJonathan Cameron 
1598a980e046SJonathan Cameron 	return 0;
1599a980e046SJonathan Cameron 
160095a0d596SDinghao Liu error_free_chan_attrs:
160195a0d596SDinghao Liu 	kfree(iio_dev_opaque->chan_attr_group.attrs);
160295a0d596SDinghao Liu 	iio_dev_opaque->chan_attr_group.attrs = NULL;
1603a980e046SJonathan Cameron error_clear_attrs:
1604207c2d27SAlexandru Ardelean 	iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1605a980e046SJonathan Cameron 
1606a980e046SJonathan Cameron 	return ret;
1607a980e046SJonathan Cameron }
1608a980e046SJonathan Cameron 
1609a980e046SJonathan Cameron static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
1610a980e046SJonathan Cameron {
1611207c2d27SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1612a980e046SJonathan Cameron 
1613207c2d27SAlexandru Ardelean 	iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1614207c2d27SAlexandru Ardelean 	kfree(iio_dev_opaque->chan_attr_group.attrs);
1615207c2d27SAlexandru Ardelean 	iio_dev_opaque->chan_attr_group.attrs = NULL;
161632f17172SAlexandru Ardelean 	kfree(iio_dev_opaque->groups);
161719833c40SYang Yingliang 	iio_dev_opaque->groups = NULL;
1618a980e046SJonathan Cameron }
1619a980e046SJonathan Cameron 
1620a980e046SJonathan Cameron static void iio_dev_release(struct device *device)
1621a980e046SJonathan Cameron {
1622e53f5ac5SLars-Peter Clausen 	struct iio_dev *indio_dev = dev_to_iio_dev(device);
16236d4ebd56SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
16246d4ebd56SAlexandru Ardelean 
1625d89e119aSBenjamin Gaignard 	if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1626a980e046SJonathan Cameron 		iio_device_unregister_trigger_consumer(indio_dev);
1627a980e046SJonathan Cameron 	iio_device_unregister_eventset(indio_dev);
1628a980e046SJonathan Cameron 	iio_device_unregister_sysfs(indio_dev);
1629e407fd65SLars-Peter Clausen 
1630218bc53dSAlexandru Ardelean 	iio_device_detach_buffers(indio_dev);
16319e69c935SLars-Peter Clausen 
16322bc9cd66SVincent Whitchurch 	lockdep_unregister_key(&iio_dev_opaque->mlock_key);
16332bc9cd66SVincent Whitchurch 
1634319dbcd8Skeliu 	ida_free(&iio_ida, iio_dev_opaque->id);
16356d4ebd56SAlexandru Ardelean 	kfree(iio_dev_opaque);
1636a980e046SJonathan Cameron }
1637a980e046SJonathan Cameron 
16383c33b7b8SLars-Peter Clausen const struct device_type iio_device_type = {
1639a980e046SJonathan Cameron 	.name = "iio_device",
1640a980e046SJonathan Cameron 	.release = iio_dev_release,
1641a980e046SJonathan Cameron };
1642a980e046SJonathan Cameron 
1643a7e57dceSSachin Kamat /**
1644a7e57dceSSachin Kamat  * iio_device_alloc() - allocate an iio_dev from a driver
1645c9561fd2SJonathan Cameron  * @parent:		Parent device.
1646a7e57dceSSachin Kamat  * @sizeof_priv:	Space to allocate for private structure.
164765659a8dSAndy Shevchenko  *
164865659a8dSAndy Shevchenko  * Returns:
164965659a8dSAndy Shevchenko  * Pointer to allocated iio_dev on success, NULL on failure.
165065659a8dSAndy Shevchenko  */
165178289b4aSAlexandru Ardelean struct iio_dev *iio_device_alloc(struct device *parent, int sizeof_priv)
1652a980e046SJonathan Cameron {
16536d4ebd56SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque;
16540d596bb2SAlexandru Ardelean 	struct iio_dev *indio_dev;
1655a980e046SJonathan Cameron 	size_t alloc_size;
1656a980e046SJonathan Cameron 
16575c4e4115SAndy Shevchenko 	if (sizeof_priv)
16585c4e4115SAndy Shevchenko 		alloc_size = ALIGN(sizeof(*iio_dev_opaque), IIO_DMA_MINALIGN) + sizeof_priv;
16595c4e4115SAndy Shevchenko 	else
16605c4e4115SAndy Shevchenko 		alloc_size = sizeof(*iio_dev_opaque);
1661a980e046SJonathan Cameron 
16626d4ebd56SAlexandru Ardelean 	iio_dev_opaque = kzalloc(alloc_size, GFP_KERNEL);
16636d4ebd56SAlexandru Ardelean 	if (!iio_dev_opaque)
16640d4b2184SJonathan Cameron 		return NULL;
1665a980e046SJonathan Cameron 
16660d596bb2SAlexandru Ardelean 	indio_dev = &iio_dev_opaque->indio_dev;
1667f0245ab3SAndy Shevchenko 
1668f0245ab3SAndy Shevchenko 	if (sizeof_priv)
16690d596bb2SAlexandru Ardelean 		indio_dev->priv = (char *)iio_dev_opaque +
1670f0245ab3SAndy Shevchenko 			ALIGN(sizeof(*iio_dev_opaque), IIO_DMA_MINALIGN);
16716d4ebd56SAlexandru Ardelean 
16720d596bb2SAlexandru Ardelean 	indio_dev->dev.parent = parent;
16730d596bb2SAlexandru Ardelean 	indio_dev->dev.type = &iio_device_type;
16740d596bb2SAlexandru Ardelean 	indio_dev->dev.bus = &iio_bus_type;
16750d596bb2SAlexandru Ardelean 	device_initialize(&indio_dev->dev);
167616afe125SNuno Sá 	mutex_init(&iio_dev_opaque->mlock);
1677b804e2b7SJonathan Cameron 	mutex_init(&iio_dev_opaque->info_exist_lock);
1678207c2d27SAlexandru Ardelean 	INIT_LIST_HEAD(&iio_dev_opaque->channel_attr_list);
1679a980e046SJonathan Cameron 
1680319dbcd8Skeliu 	iio_dev_opaque->id = ida_alloc(&iio_ida, GFP_KERNEL);
168115ea2878SJonathan Cameron 	if (iio_dev_opaque->id < 0) {
1682a980e046SJonathan Cameron 		/* cannot use a dev_err as the name isn't available */
16833176dd5dSSachin Kamat 		pr_err("failed to get device id\n");
16846d4ebd56SAlexandru Ardelean 		kfree(iio_dev_opaque);
1685a980e046SJonathan Cameron 		return NULL;
1686a980e046SJonathan Cameron 	}
1687fe6f45f6SYang Yingliang 
1688fe6f45f6SYang Yingliang 	if (dev_set_name(&indio_dev->dev, "iio:device%d", iio_dev_opaque->id)) {
1689319dbcd8Skeliu 		ida_free(&iio_ida, iio_dev_opaque->id);
1690fe6f45f6SYang Yingliang 		kfree(iio_dev_opaque);
1691fe6f45f6SYang Yingliang 		return NULL;
1692fe6f45f6SYang Yingliang 	}
1693fe6f45f6SYang Yingliang 
16946a8c6b26SAlexandru Ardelean 	INIT_LIST_HEAD(&iio_dev_opaque->buffer_list);
16958dedcc3eSAlexandru Ardelean 	INIT_LIST_HEAD(&iio_dev_opaque->ioctl_handlers);
1696a980e046SJonathan Cameron 
16972bc9cd66SVincent Whitchurch 	lockdep_register_key(&iio_dev_opaque->mlock_key);
169816afe125SNuno Sá 	lockdep_set_class(&iio_dev_opaque->mlock, &iio_dev_opaque->mlock_key);
16992bc9cd66SVincent Whitchurch 
17000d596bb2SAlexandru Ardelean 	return indio_dev;
1701a980e046SJonathan Cameron }
17027cbb7537SLars-Peter Clausen EXPORT_SYMBOL(iio_device_alloc);
1703a980e046SJonathan Cameron 
1704a7e57dceSSachin Kamat /**
1705a7e57dceSSachin Kamat  * iio_device_free() - free an iio_dev from a driver
1706a7e57dceSSachin Kamat  * @dev:		the iio_dev associated with the device
170765659a8dSAndy Shevchenko  */
17087cbb7537SLars-Peter Clausen void iio_device_free(struct iio_dev *dev)
1709a980e046SJonathan Cameron {
1710e407fd65SLars-Peter Clausen 	if (dev)
1711e407fd65SLars-Peter Clausen 		put_device(&dev->dev);
1712a980e046SJonathan Cameron }
17137cbb7537SLars-Peter Clausen EXPORT_SYMBOL(iio_device_free);
1714a980e046SJonathan Cameron 
1715cf5724e9SYicong Yang static void devm_iio_device_release(void *iio_dev)
17169dabaf5eSGrygorii Strashko {
1717cf5724e9SYicong Yang 	iio_device_free(iio_dev);
17189dabaf5eSGrygorii Strashko }
17199dabaf5eSGrygorii Strashko 
1720a7e57dceSSachin Kamat /**
1721a7e57dceSSachin Kamat  * devm_iio_device_alloc - Resource-managed iio_device_alloc()
172278289b4aSAlexandru Ardelean  * @parent:		Device to allocate iio_dev for, and parent for this IIO device
1723a7e57dceSSachin Kamat  * @sizeof_priv:	Space to allocate for private structure.
1724a7e57dceSSachin Kamat  *
1725a7e57dceSSachin Kamat  * Managed iio_device_alloc. iio_dev allocated with this function is
1726a7e57dceSSachin Kamat  * automatically freed on driver detach.
1727a7e57dceSSachin Kamat  *
172865659a8dSAndy Shevchenko  * Returns:
1729a7e57dceSSachin Kamat  * Pointer to allocated iio_dev on success, NULL on failure.
1730a7e57dceSSachin Kamat  */
173178289b4aSAlexandru Ardelean struct iio_dev *devm_iio_device_alloc(struct device *parent, int sizeof_priv)
17329dabaf5eSGrygorii Strashko {
1733cf5724e9SYicong Yang 	struct iio_dev *iio_dev;
1734cf5724e9SYicong Yang 	int ret;
17359dabaf5eSGrygorii Strashko 
173678289b4aSAlexandru Ardelean 	iio_dev = iio_device_alloc(parent, sizeof_priv);
1737cf5724e9SYicong Yang 	if (!iio_dev)
1738cf5724e9SYicong Yang 		return NULL;
1739cf5724e9SYicong Yang 
1740cf5724e9SYicong Yang 	ret = devm_add_action_or_reset(parent, devm_iio_device_release,
1741cf5724e9SYicong Yang 				       iio_dev);
1742cf5724e9SYicong Yang 	if (ret)
174343fa7394SDan Carpenter 		return NULL;
17449dabaf5eSGrygorii Strashko 
17459dabaf5eSGrygorii Strashko 	return iio_dev;
17469dabaf5eSGrygorii Strashko }
17479dabaf5eSGrygorii Strashko EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
17489dabaf5eSGrygorii Strashko 
1749a7e57dceSSachin Kamat /**
1750a980e046SJonathan Cameron  * iio_chrdev_open() - chrdev file open for buffer access and ioctls
17512498dcf6SCristina Opriceana  * @inode:	Inode structure for identifying the device in the file system
17522498dcf6SCristina Opriceana  * @filp:	File structure for iio device used to keep and later access
17532498dcf6SCristina Opriceana  *		private data
17542498dcf6SCristina Opriceana  *
175565659a8dSAndy Shevchenko  * Returns: 0 on success or -EBUSY if the device is already opened
175665659a8dSAndy Shevchenko  */
1757a980e046SJonathan Cameron static int iio_chrdev_open(struct inode *inode, struct file *filp)
1758a980e046SJonathan Cameron {
1759396f7234SJonathan Cameron 	struct iio_dev_opaque *iio_dev_opaque =
1760396f7234SJonathan Cameron 		container_of(inode->i_cdev, struct iio_dev_opaque, chrdev);
1761396f7234SJonathan Cameron 	struct iio_dev *indio_dev = &iio_dev_opaque->indio_dev;
1762be24dcb1SAlexandru Ardelean 	struct iio_dev_buffer_pair *ib;
1763a980e046SJonathan Cameron 
17648b1c82cbSJonathan Cameron 	if (test_and_set_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags))
1765a980e046SJonathan Cameron 		return -EBUSY;
1766a980e046SJonathan Cameron 
1767cadc2125SLars-Peter Clausen 	iio_device_get(indio_dev);
1768cadc2125SLars-Peter Clausen 
1769be24dcb1SAlexandru Ardelean 	ib = kmalloc(sizeof(*ib), GFP_KERNEL);
1770be24dcb1SAlexandru Ardelean 	if (!ib) {
1771be24dcb1SAlexandru Ardelean 		iio_device_put(indio_dev);
17728b1c82cbSJonathan Cameron 		clear_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags);
1773be24dcb1SAlexandru Ardelean 		return -ENOMEM;
1774be24dcb1SAlexandru Ardelean 	}
1775be24dcb1SAlexandru Ardelean 
1776be24dcb1SAlexandru Ardelean 	ib->indio_dev = indio_dev;
1777be24dcb1SAlexandru Ardelean 	ib->buffer = indio_dev->buffer;
1778be24dcb1SAlexandru Ardelean 
1779be24dcb1SAlexandru Ardelean 	filp->private_data = ib;
1780a980e046SJonathan Cameron 
1781a980e046SJonathan Cameron 	return 0;
1782a980e046SJonathan Cameron }
1783a980e046SJonathan Cameron 
1784a980e046SJonathan Cameron /**
1785a980e046SJonathan Cameron  * iio_chrdev_release() - chrdev file close buffer access and ioctls
17862498dcf6SCristina Opriceana  * @inode:	Inode structure pointer for the char device
17872498dcf6SCristina Opriceana  * @filp:	File structure pointer for the char device
17882498dcf6SCristina Opriceana  *
178965659a8dSAndy Shevchenko  * Returns: 0 for successful release.
17902498dcf6SCristina Opriceana  */
1791a980e046SJonathan Cameron static int iio_chrdev_release(struct inode *inode, struct file *filp)
1792a980e046SJonathan Cameron {
1793be24dcb1SAlexandru Ardelean 	struct iio_dev_buffer_pair *ib = filp->private_data;
1794396f7234SJonathan Cameron 	struct iio_dev_opaque *iio_dev_opaque =
1795396f7234SJonathan Cameron 		container_of(inode->i_cdev, struct iio_dev_opaque, chrdev);
1796396f7234SJonathan Cameron 	struct iio_dev *indio_dev = &iio_dev_opaque->indio_dev;
17979d9ec8d0SJoe Simmons-Talbott 
1798be24dcb1SAlexandru Ardelean 	kfree(ib);
17998b1c82cbSJonathan Cameron 	clear_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags);
1800cadc2125SLars-Peter Clausen 	iio_device_put(indio_dev);
1801cadc2125SLars-Peter Clausen 
1802a980e046SJonathan Cameron 	return 0;
1803a980e046SJonathan Cameron }
1804a980e046SJonathan Cameron 
18058dedcc3eSAlexandru Ardelean void iio_device_ioctl_handler_register(struct iio_dev *indio_dev,
18068dedcc3eSAlexandru Ardelean 				       struct iio_ioctl_handler *h)
18078dedcc3eSAlexandru Ardelean {
18088dedcc3eSAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
18098dedcc3eSAlexandru Ardelean 
18108dedcc3eSAlexandru Ardelean 	list_add_tail(&h->entry, &iio_dev_opaque->ioctl_handlers);
18118dedcc3eSAlexandru Ardelean }
18128dedcc3eSAlexandru Ardelean 
18138dedcc3eSAlexandru Ardelean void iio_device_ioctl_handler_unregister(struct iio_ioctl_handler *h)
18148dedcc3eSAlexandru Ardelean {
18158dedcc3eSAlexandru Ardelean 	list_del(&h->entry);
18168dedcc3eSAlexandru Ardelean }
18178dedcc3eSAlexandru Ardelean 
1818a980e046SJonathan Cameron static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1819a980e046SJonathan Cameron {
1820be24dcb1SAlexandru Ardelean 	struct iio_dev_buffer_pair *ib = filp->private_data;
1821be24dcb1SAlexandru Ardelean 	struct iio_dev *indio_dev = ib->indio_dev;
18228dedcc3eSAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
18238dedcc3eSAlexandru Ardelean 	struct iio_ioctl_handler *h;
182442ea5992SNuno Sa 	int ret;
1825a980e046SJonathan Cameron 
182642ea5992SNuno Sa 	guard(mutex)(&iio_dev_opaque->info_exist_lock);
182765659a8dSAndy Shevchenko 	/*
18288dedcc3eSAlexandru Ardelean 	 * The NULL check here is required to prevent crashing when a device
18298dedcc3eSAlexandru Ardelean 	 * is being removed while userspace would still have open file handles
18308dedcc3eSAlexandru Ardelean 	 * to try to access this device.
18318dedcc3eSAlexandru Ardelean 	 */
1832f18e7a06SLars-Peter Clausen 	if (!indio_dev->info)
183342ea5992SNuno Sa 		return -ENODEV;
1834f18e7a06SLars-Peter Clausen 
18358dedcc3eSAlexandru Ardelean 	list_for_each_entry(h, &iio_dev_opaque->ioctl_handlers, entry) {
18368dedcc3eSAlexandru Ardelean 		ret = h->ioctl(indio_dev, filp, cmd, arg);
18378dedcc3eSAlexandru Ardelean 		if (ret != IIO_IOCTL_UNHANDLED)
183842ea5992SNuno Sa 			return ret;
1839a980e046SJonathan Cameron 	}
18408dedcc3eSAlexandru Ardelean 
184142ea5992SNuno Sa 	return -ENODEV;
1842a980e046SJonathan Cameron }
1843a980e046SJonathan Cameron 
1844a980e046SJonathan Cameron static const struct file_operations iio_buffer_fileops = {
1845a980e046SJonathan Cameron 	.owner = THIS_MODULE,
1846a980e046SJonathan Cameron 	.llseek = noop_llseek,
1847ee8caea0SAlexandru Ardelean 	.read = iio_buffer_read_outer_addr,
18489eeee3b0SMihail Chindris 	.write = iio_buffer_write_outer_addr,
1849ee8caea0SAlexandru Ardelean 	.poll = iio_buffer_poll_addr,
1850a980e046SJonathan Cameron 	.unlocked_ioctl = iio_ioctl,
18511832f2d8SArnd Bergmann 	.compat_ioctl = compat_ptr_ioctl,
1852ee8caea0SAlexandru Ardelean 	.open = iio_chrdev_open,
1853ee8caea0SAlexandru Ardelean 	.release = iio_chrdev_release,
1854a980e046SJonathan Cameron };
1855a980e046SJonathan Cameron 
18568ebaa3ffSAlexandru Ardelean static const struct file_operations iio_event_fileops = {
18578ebaa3ffSAlexandru Ardelean 	.owner = THIS_MODULE,
18588ebaa3ffSAlexandru Ardelean 	.llseek = noop_llseek,
18598ebaa3ffSAlexandru Ardelean 	.unlocked_ioctl = iio_ioctl,
18608ebaa3ffSAlexandru Ardelean 	.compat_ioctl = compat_ptr_ioctl,
18618ebaa3ffSAlexandru Ardelean 	.open = iio_chrdev_open,
18628ebaa3ffSAlexandru Ardelean 	.release = iio_chrdev_release,
18638ebaa3ffSAlexandru Ardelean };
18648ebaa3ffSAlexandru Ardelean 
18658f5d8727SVlad Dogaru static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
18668f5d8727SVlad Dogaru {
18678f5d8727SVlad Dogaru 	int i, j;
18688f5d8727SVlad Dogaru 	const struct iio_chan_spec *channels = indio_dev->channels;
18698f5d8727SVlad Dogaru 
18708f5d8727SVlad Dogaru 	if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
18718f5d8727SVlad Dogaru 		return 0;
18728f5d8727SVlad Dogaru 
18738f5d8727SVlad Dogaru 	for (i = 0; i < indio_dev->num_channels - 1; i++) {
18748f5d8727SVlad Dogaru 		if (channels[i].scan_index < 0)
18758f5d8727SVlad Dogaru 			continue;
18768f5d8727SVlad Dogaru 		for (j = i + 1; j < indio_dev->num_channels; j++)
18778f5d8727SVlad Dogaru 			if (channels[i].scan_index == channels[j].scan_index) {
18788f5d8727SVlad Dogaru 				dev_err(&indio_dev->dev,
18798f5d8727SVlad Dogaru 					"Duplicate scan index %d\n",
18808f5d8727SVlad Dogaru 					channels[i].scan_index);
18818f5d8727SVlad Dogaru 				return -EINVAL;
18828f5d8727SVlad Dogaru 			}
18838f5d8727SVlad Dogaru 	}
18848f5d8727SVlad Dogaru 
18858f5d8727SVlad Dogaru 	return 0;
18868f5d8727SVlad Dogaru }
18878f5d8727SVlad Dogaru 
18880e0761f8SPaul Cercueil static int iio_check_extended_name(const struct iio_dev *indio_dev)
18890e0761f8SPaul Cercueil {
18900e0761f8SPaul Cercueil 	unsigned int i;
18910e0761f8SPaul Cercueil 
18920e0761f8SPaul Cercueil 	if (!indio_dev->info->read_label)
18930e0761f8SPaul Cercueil 		return 0;
18940e0761f8SPaul Cercueil 
18950e0761f8SPaul Cercueil 	for (i = 0; i < indio_dev->num_channels; i++) {
18960e0761f8SPaul Cercueil 		if (indio_dev->channels[i].extend_name) {
18970e0761f8SPaul Cercueil 			dev_err(&indio_dev->dev,
18980e0761f8SPaul Cercueil 				"Cannot use labels and extend_name at the same time\n");
18990e0761f8SPaul Cercueil 			return -EINVAL;
19000e0761f8SPaul Cercueil 		}
19010e0761f8SPaul Cercueil 	}
19020e0761f8SPaul Cercueil 
19030e0761f8SPaul Cercueil 	return 0;
19040e0761f8SPaul Cercueil }
19050e0761f8SPaul Cercueil 
1906a980e046SJonathan Cameron static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1907a980e046SJonathan Cameron 
19082718f154SMatti Vaittinen static void iio_sanity_check_avail_scan_masks(struct iio_dev *indio_dev)
19092718f154SMatti Vaittinen {
19102718f154SMatti Vaittinen 	unsigned int num_masks, masklength, longs_per_mask;
19112718f154SMatti Vaittinen 	const unsigned long *av_masks;
19122718f154SMatti Vaittinen 	int i;
19132718f154SMatti Vaittinen 
19142718f154SMatti Vaittinen 	av_masks = indio_dev->available_scan_masks;
1915*c6c47852SNuno Sa 	masklength = iio_get_masklength(indio_dev);
19162718f154SMatti Vaittinen 	longs_per_mask = BITS_TO_LONGS(masklength);
19172718f154SMatti Vaittinen 
19182718f154SMatti Vaittinen 	/*
19192718f154SMatti Vaittinen 	 * The code determining how many available_scan_masks is in the array
19202718f154SMatti Vaittinen 	 * will be assuming the end of masks when first long with all bits
19212718f154SMatti Vaittinen 	 * zeroed is encountered. This is incorrect for masks where mask
19222718f154SMatti Vaittinen 	 * consists of more than one long, and where some of the available masks
19232718f154SMatti Vaittinen 	 * has long worth of bits zeroed (but has subsequent bit(s) set). This
19242718f154SMatti Vaittinen 	 * is a safety measure against bug where array of masks is terminated by
19252718f154SMatti Vaittinen 	 * a single zero while mask width is greater than width of a long.
19262718f154SMatti Vaittinen 	 */
19272718f154SMatti Vaittinen 	if (longs_per_mask > 1)
19282718f154SMatti Vaittinen 		dev_warn(indio_dev->dev.parent,
19292718f154SMatti Vaittinen 			 "multi long available scan masks not fully supported\n");
19302718f154SMatti Vaittinen 
19312718f154SMatti Vaittinen 	if (bitmap_empty(av_masks, masklength))
19322718f154SMatti Vaittinen 		dev_warn(indio_dev->dev.parent, "empty scan mask\n");
19332718f154SMatti Vaittinen 
19342718f154SMatti Vaittinen 	for (num_masks = 0; *av_masks; num_masks++)
19352718f154SMatti Vaittinen 		av_masks += longs_per_mask;
19362718f154SMatti Vaittinen 
19372718f154SMatti Vaittinen 	if (num_masks < 2)
19382718f154SMatti Vaittinen 		return;
19392718f154SMatti Vaittinen 
19402718f154SMatti Vaittinen 	av_masks = indio_dev->available_scan_masks;
19412718f154SMatti Vaittinen 
19422718f154SMatti Vaittinen 	/*
19432718f154SMatti Vaittinen 	 * Go through all the masks from first to one before the last, and see
19442718f154SMatti Vaittinen 	 * that no mask found later from the available_scan_masks array is a
19452718f154SMatti Vaittinen 	 * subset of mask found earlier. If this happens, then the mask found
19462718f154SMatti Vaittinen 	 * later will never get used because scanning the array is stopped when
19472718f154SMatti Vaittinen 	 * the first suitable mask is found. Drivers should order the array of
19482718f154SMatti Vaittinen 	 * available masks in the order of preference (presumably the least
19492718f154SMatti Vaittinen 	 * costy to access masks first).
19502718f154SMatti Vaittinen 	 */
19512718f154SMatti Vaittinen 	for (i = 0; i < num_masks - 1; i++) {
19522718f154SMatti Vaittinen 		const unsigned long *mask1;
19532718f154SMatti Vaittinen 		int j;
19542718f154SMatti Vaittinen 
19552718f154SMatti Vaittinen 		mask1 = av_masks + i * longs_per_mask;
19562718f154SMatti Vaittinen 		for (j = i + 1; j < num_masks; j++) {
19572718f154SMatti Vaittinen 			const unsigned long *mask2;
19582718f154SMatti Vaittinen 
19592718f154SMatti Vaittinen 			mask2 = av_masks + j * longs_per_mask;
19602718f154SMatti Vaittinen 			if (bitmap_subset(mask2, mask1, masklength))
19612718f154SMatti Vaittinen 				dev_warn(indio_dev->dev.parent,
19622718f154SMatti Vaittinen 					 "available_scan_mask %d subset of %d. Never used\n",
19632718f154SMatti Vaittinen 					 j, i);
19642718f154SMatti Vaittinen 		}
19652718f154SMatti Vaittinen 	}
19662718f154SMatti Vaittinen }
19672718f154SMatti Vaittinen 
196863b19547SJonathan Cameron int __iio_device_register(struct iio_dev *indio_dev, struct module *this_mod)
1969a980e046SJonathan Cameron {
19708ebaa3ffSAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1971b2a69969SMilan Zamazal 	struct fwnode_handle *fwnode = NULL;
1972a980e046SJonathan Cameron 	int ret;
1973a980e046SJonathan Cameron 
1974a17cb784SAlexandru Ardelean 	if (!indio_dev->info)
1975a17cb784SAlexandru Ardelean 		return -EINVAL;
1976a17cb784SAlexandru Ardelean 
19776eaf9f6aSJonathan Cameron 	iio_dev_opaque->driver_module = this_mod;
197817d82b47SGuenter Roeck 
197981366556SAndy Shevchenko 	/* If the calling driver did not initialize firmware node, do it here */
198081366556SAndy Shevchenko 	if (dev_fwnode(&indio_dev->dev))
198181366556SAndy Shevchenko 		fwnode = dev_fwnode(&indio_dev->dev);
1982b2a69969SMilan Zamazal 	/* The default dummy IIO device has no parent */
1983b2a69969SMilan Zamazal 	else if (indio_dev->dev.parent)
198481366556SAndy Shevchenko 		fwnode = dev_fwnode(indio_dev->dev.parent);
198581366556SAndy Shevchenko 	device_set_node(&indio_dev->dev, fwnode);
198681366556SAndy Shevchenko 
198781366556SAndy Shevchenko 	fwnode_property_read_string(fwnode, "label", &indio_dev->label);
19882c3d0c9fSPhil Reid 
19898f5d8727SVlad Dogaru 	ret = iio_check_unique_scan_index(indio_dev);
19908f5d8727SVlad Dogaru 	if (ret < 0)
19918f5d8727SVlad Dogaru 		return ret;
19928f5d8727SVlad Dogaru 
19930e0761f8SPaul Cercueil 	ret = iio_check_extended_name(indio_dev);
19940e0761f8SPaul Cercueil 	if (ret < 0)
19950e0761f8SPaul Cercueil 		return ret;
19960e0761f8SPaul Cercueil 
19978915aacaSGreg Kroah-Hartman 	iio_device_register_debugfs(indio_dev);
19983e1b6c95SLars-Peter Clausen 
1999ee708e6bSAlexandru Ardelean 	ret = iio_buffers_alloc_sysfs_and_mask(indio_dev);
20003e1b6c95SLars-Peter Clausen 	if (ret) {
20013e1b6c95SLars-Peter Clausen 		dev_err(indio_dev->dev.parent,
20023e1b6c95SLars-Peter Clausen 			"Failed to create buffer sysfs interfaces\n");
20033e1b6c95SLars-Peter Clausen 		goto error_unreg_debugfs;
20043e1b6c95SLars-Peter Clausen 	}
20053e1b6c95SLars-Peter Clausen 
20062718f154SMatti Vaittinen 	if (indio_dev->available_scan_masks)
20072718f154SMatti Vaittinen 		iio_sanity_check_avail_scan_masks(indio_dev);
20082718f154SMatti Vaittinen 
2009a980e046SJonathan Cameron 	ret = iio_device_register_sysfs(indio_dev);
2010a980e046SJonathan Cameron 	if (ret) {
2011a980e046SJonathan Cameron 		dev_err(indio_dev->dev.parent,
2012a980e046SJonathan Cameron 			"Failed to register sysfs interfaces\n");
20133e1b6c95SLars-Peter Clausen 		goto error_buffer_free_sysfs;
2014a980e046SJonathan Cameron 	}
2015a980e046SJonathan Cameron 	ret = iio_device_register_eventset(indio_dev);
2016a980e046SJonathan Cameron 	if (ret) {
2017a980e046SJonathan Cameron 		dev_err(indio_dev->dev.parent,
2018a980e046SJonathan Cameron 			"Failed to register event set\n");
2019a980e046SJonathan Cameron 		goto error_free_sysfs;
2020a980e046SJonathan Cameron 	}
2021d89e119aSBenjamin Gaignard 	if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
2022a980e046SJonathan Cameron 		iio_device_register_trigger_consumer(indio_dev);
2023a980e046SJonathan Cameron 
2024a980e046SJonathan Cameron 	if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
2025a980e046SJonathan Cameron 		indio_dev->setup_ops == NULL)
2026a980e046SJonathan Cameron 		indio_dev->setup_ops = &noop_ring_setup_ops;
2027a980e046SJonathan Cameron 
2028ee708e6bSAlexandru Ardelean 	if (iio_dev_opaque->attached_buffers_cnt)
2029396f7234SJonathan Cameron 		cdev_init(&iio_dev_opaque->chrdev, &iio_buffer_fileops);
20308ebaa3ffSAlexandru Ardelean 	else if (iio_dev_opaque->event_interface)
2031396f7234SJonathan Cameron 		cdev_init(&iio_dev_opaque->chrdev, &iio_event_fileops);
203263b19547SJonathan Cameron 
2033ee708e6bSAlexandru Ardelean 	if (iio_dev_opaque->attached_buffers_cnt || iio_dev_opaque->event_interface) {
203415ea2878SJonathan Cameron 		indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), iio_dev_opaque->id);
2035396f7234SJonathan Cameron 		iio_dev_opaque->chrdev.owner = this_mod;
20368ebaa3ffSAlexandru Ardelean 	}
203738923911SLogan Gunthorpe 
203832f17172SAlexandru Ardelean 	/* assign device groups now; they should be all registered now */
203932f17172SAlexandru Ardelean 	indio_dev->dev.groups = iio_dev_opaque->groups;
204032f17172SAlexandru Ardelean 
2041396f7234SJonathan Cameron 	ret = cdev_device_add(&iio_dev_opaque->chrdev, &indio_dev->dev);
2042a980e046SJonathan Cameron 	if (ret < 0)
20430d5b7daeSLars-Peter Clausen 		goto error_unreg_eventset;
2044a980e046SJonathan Cameron 
20450d5b7daeSLars-Peter Clausen 	return 0;
204638923911SLogan Gunthorpe 
2047a980e046SJonathan Cameron error_unreg_eventset:
2048a980e046SJonathan Cameron 	iio_device_unregister_eventset(indio_dev);
2049a980e046SJonathan Cameron error_free_sysfs:
2050a980e046SJonathan Cameron 	iio_device_unregister_sysfs(indio_dev);
20513e1b6c95SLars-Peter Clausen error_buffer_free_sysfs:
2052ee708e6bSAlexandru Ardelean 	iio_buffers_free_sysfs_and_mask(indio_dev);
2053a980e046SJonathan Cameron error_unreg_debugfs:
2054a980e046SJonathan Cameron 	iio_device_unregister_debugfs(indio_dev);
2055a980e046SJonathan Cameron 	return ret;
2056a980e046SJonathan Cameron }
205763b19547SJonathan Cameron EXPORT_SYMBOL(__iio_device_register);
2058a980e046SJonathan Cameron 
2059a7e57dceSSachin Kamat /**
2060a7e57dceSSachin Kamat  * iio_device_unregister() - unregister a device from the IIO subsystem
2061a7e57dceSSachin Kamat  * @indio_dev:		Device structure representing the device.
206265659a8dSAndy Shevchenko  */
2063a980e046SJonathan Cameron void iio_device_unregister(struct iio_dev *indio_dev)
2064a980e046SJonathan Cameron {
2065396f7234SJonathan Cameron 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2066396f7234SJonathan Cameron 
2067396f7234SJonathan Cameron 	cdev_device_del(&iio_dev_opaque->chrdev, &indio_dev->dev);
2068a87c82e4SLars-Peter Clausen 
206942ea5992SNuno Sa 	scoped_guard(mutex, &iio_dev_opaque->info_exist_lock) {
2070bc4c9612SLars-Peter Clausen 		iio_device_unregister_debugfs(indio_dev);
20710d5b7daeSLars-Peter Clausen 
2072a87c82e4SLars-Peter Clausen 		iio_disable_all_buffers(indio_dev);
2073a87c82e4SLars-Peter Clausen 
2074a980e046SJonathan Cameron 		indio_dev->info = NULL;
2075d2f0a48fSLars-Peter Clausen 
2076d2f0a48fSLars-Peter Clausen 		iio_device_wakeup_eventset(indio_dev);
2077d2f0a48fSLars-Peter Clausen 		iio_buffer_wakeup_poll(indio_dev);
207842ea5992SNuno Sa 	}
20793e1b6c95SLars-Peter Clausen 
2080ee708e6bSAlexandru Ardelean 	iio_buffers_free_sysfs_and_mask(indio_dev);
2081a980e046SJonathan Cameron }
2082a980e046SJonathan Cameron EXPORT_SYMBOL(iio_device_unregister);
20838caa07c0SSachin Kamat 
2084cf5724e9SYicong Yang static void devm_iio_device_unreg(void *indio_dev)
20858caa07c0SSachin Kamat {
2086cf5724e9SYicong Yang 	iio_device_unregister(indio_dev);
20878caa07c0SSachin Kamat }
20888caa07c0SSachin Kamat 
208963b19547SJonathan Cameron int __devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev,
209063b19547SJonathan Cameron 			       struct module *this_mod)
20918caa07c0SSachin Kamat {
20928caa07c0SSachin Kamat 	int ret;
20938caa07c0SSachin Kamat 
209463b19547SJonathan Cameron 	ret = __iio_device_register(indio_dev, this_mod);
2095cf5724e9SYicong Yang 	if (ret)
20968caa07c0SSachin Kamat 		return ret;
2097cf5724e9SYicong Yang 
2098cf5724e9SYicong Yang 	return devm_add_action_or_reset(dev, devm_iio_device_unreg, indio_dev);
20998caa07c0SSachin Kamat }
210063b19547SJonathan Cameron EXPORT_SYMBOL_GPL(__devm_iio_device_register);
21018caa07c0SSachin Kamat 
21028caa07c0SSachin Kamat /**
210308a33805SAlison Schofield  * iio_device_claim_direct_mode - Keep device in direct mode
210408a33805SAlison Schofield  * @indio_dev:	the iio_dev associated with the device
210508a33805SAlison Schofield  *
210608a33805SAlison Schofield  * If the device is in direct mode it is guaranteed to stay
210708a33805SAlison Schofield  * that way until iio_device_release_direct_mode() is called.
210808a33805SAlison Schofield  *
210908a33805SAlison Schofield  * Use with iio_device_release_direct_mode()
211008a33805SAlison Schofield  *
211165659a8dSAndy Shevchenko  * Returns: 0 on success, -EBUSY on failure.
211208a33805SAlison Schofield  */
211308a33805SAlison Schofield int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
211408a33805SAlison Schofield {
211516afe125SNuno Sá 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
211616afe125SNuno Sá 
211716afe125SNuno Sá 	mutex_lock(&iio_dev_opaque->mlock);
211808a33805SAlison Schofield 
211908a33805SAlison Schofield 	if (iio_buffer_enabled(indio_dev)) {
212016afe125SNuno Sá 		mutex_unlock(&iio_dev_opaque->mlock);
212108a33805SAlison Schofield 		return -EBUSY;
212208a33805SAlison Schofield 	}
212308a33805SAlison Schofield 	return 0;
212408a33805SAlison Schofield }
212508a33805SAlison Schofield EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
212608a33805SAlison Schofield 
212708a33805SAlison Schofield /**
212808a33805SAlison Schofield  * iio_device_release_direct_mode - releases claim on direct mode
212908a33805SAlison Schofield  * @indio_dev:	the iio_dev associated with the device
213008a33805SAlison Schofield  *
213108a33805SAlison Schofield  * Release the claim. Device is no longer guaranteed to stay
213208a33805SAlison Schofield  * in direct mode.
213308a33805SAlison Schofield  *
213408a33805SAlison Schofield  * Use with iio_device_claim_direct_mode()
213508a33805SAlison Schofield  */
213608a33805SAlison Schofield void iio_device_release_direct_mode(struct iio_dev *indio_dev)
213708a33805SAlison Schofield {
213816afe125SNuno Sá 	mutex_unlock(&to_iio_dev_opaque(indio_dev)->mlock);
213908a33805SAlison Schofield }
214008a33805SAlison Schofield EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
214108a33805SAlison Schofield 
21428c576f87SMiquel Raynal /**
21430a856542SNuno Sá  * iio_device_claim_buffer_mode - Keep device in buffer mode
21440a856542SNuno Sá  * @indio_dev:	the iio_dev associated with the device
21450a856542SNuno Sá  *
21460a856542SNuno Sá  * If the device is in buffer mode it is guaranteed to stay
21470a856542SNuno Sá  * that way until iio_device_release_buffer_mode() is called.
21480a856542SNuno Sá  *
21490a856542SNuno Sá  * Use with iio_device_release_buffer_mode().
21500a856542SNuno Sá  *
21510a856542SNuno Sá  * Returns: 0 on success, -EBUSY on failure.
21520a856542SNuno Sá  */
21530a856542SNuno Sá int iio_device_claim_buffer_mode(struct iio_dev *indio_dev)
21540a856542SNuno Sá {
215516afe125SNuno Sá 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
215616afe125SNuno Sá 
215716afe125SNuno Sá 	mutex_lock(&iio_dev_opaque->mlock);
21580a856542SNuno Sá 
21590a856542SNuno Sá 	if (iio_buffer_enabled(indio_dev))
21600a856542SNuno Sá 		return 0;
21610a856542SNuno Sá 
216216afe125SNuno Sá 	mutex_unlock(&iio_dev_opaque->mlock);
21630a856542SNuno Sá 	return -EBUSY;
21640a856542SNuno Sá }
21650a856542SNuno Sá EXPORT_SYMBOL_GPL(iio_device_claim_buffer_mode);
21660a856542SNuno Sá 
21670a856542SNuno Sá /**
21680a856542SNuno Sá  * iio_device_release_buffer_mode - releases claim on buffer mode
21690a856542SNuno Sá  * @indio_dev:	the iio_dev associated with the device
21700a856542SNuno Sá  *
21710a856542SNuno Sá  * Release the claim. Device is no longer guaranteed to stay
21720a856542SNuno Sá  * in buffer mode.
21730a856542SNuno Sá  *
21740a856542SNuno Sá  * Use with iio_device_claim_buffer_mode().
21750a856542SNuno Sá  */
21760a856542SNuno Sá void iio_device_release_buffer_mode(struct iio_dev *indio_dev)
21770a856542SNuno Sá {
217816afe125SNuno Sá 	mutex_unlock(&to_iio_dev_opaque(indio_dev)->mlock);
21790a856542SNuno Sá }
21800a856542SNuno Sá EXPORT_SYMBOL_GPL(iio_device_release_buffer_mode);
21810a856542SNuno Sá 
21820a856542SNuno Sá /**
21838c576f87SMiquel Raynal  * iio_device_get_current_mode() - helper function providing read-only access to
218451570c9dSMiquel Raynal  *				   the opaque @currentmode variable
21858c576f87SMiquel Raynal  * @indio_dev:			   IIO device structure for device
21868c576f87SMiquel Raynal  */
21878c576f87SMiquel Raynal int iio_device_get_current_mode(struct iio_dev *indio_dev)
21888c576f87SMiquel Raynal {
218951570c9dSMiquel Raynal 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
219051570c9dSMiquel Raynal 
219151570c9dSMiquel Raynal 	return iio_dev_opaque->currentmode;
21928c576f87SMiquel Raynal }
21938c576f87SMiquel Raynal EXPORT_SYMBOL_GPL(iio_device_get_current_mode);
21948c576f87SMiquel Raynal 
2195a980e046SJonathan Cameron subsys_initcall(iio_init);
2196a980e046SJonathan Cameron module_exit(iio_exit);
2197a980e046SJonathan Cameron 
2198c8b95952SJonathan Cameron MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
2199a980e046SJonathan Cameron MODULE_DESCRIPTION("Industrial I/O core");
2200a980e046SJonathan Cameron MODULE_LICENSE("GPL");
2201