xref: /linux/drivers/iio/industrialio-core.c (revision d9a0e73c0c879358ca6607fad9a01248a3b27bfc)
1d2912cb1SThomas Gleixner // SPDX-License-Identifier: GPL-2.0-only
2a980e046SJonathan Cameron /* The industrial I/O core
3a980e046SJonathan Cameron  *
4a980e046SJonathan Cameron  * Copyright (c) 2008 Jonathan Cameron
5a980e046SJonathan Cameron  *
6a980e046SJonathan Cameron  * Based on elements of hwmon and input subsystems.
7a980e046SJonathan Cameron  */
8a980e046SJonathan Cameron 
93176dd5dSSachin Kamat #define pr_fmt(fmt) "iio-core: " fmt
103176dd5dSSachin Kamat 
11a980e046SJonathan Cameron #include <linux/kernel.h>
12a980e046SJonathan Cameron #include <linux/module.h>
13a980e046SJonathan Cameron #include <linux/idr.h>
14a980e046SJonathan Cameron #include <linux/kdev_t.h>
15a980e046SJonathan Cameron #include <linux/err.h>
16a980e046SJonathan Cameron #include <linux/device.h>
17a980e046SJonathan Cameron #include <linux/fs.h>
18a980e046SJonathan Cameron #include <linux/poll.h>
19fb158971SAndy Shevchenko #include <linux/property.h>
20a980e046SJonathan Cameron #include <linux/sched.h>
21a980e046SJonathan Cameron #include <linux/wait.h>
22a980e046SJonathan Cameron #include <linux/cdev.h>
23a980e046SJonathan Cameron #include <linux/slab.h>
24a980e046SJonathan Cameron #include <linux/anon_inodes.h>
25a980e046SJonathan Cameron #include <linux/debugfs.h>
2608a33805SAlison Schofield #include <linux/mutex.h>
27a980e046SJonathan Cameron #include <linux/iio/iio.h>
286d4ebd56SAlexandru Ardelean #include <linux/iio/iio-opaque.h>
29a980e046SJonathan Cameron #include "iio_core.h"
30a980e046SJonathan Cameron #include "iio_core_trigger.h"
31a980e046SJonathan Cameron #include <linux/iio/sysfs.h>
32a980e046SJonathan Cameron #include <linux/iio/events.h>
339e69c935SLars-Peter Clausen #include <linux/iio/buffer.h>
3433dd94cbSJonathan Cameron #include <linux/iio/buffer_impl.h>
35a980e046SJonathan Cameron 
36a980e046SJonathan Cameron /* IDA to assign each registered device a unique id */
37a980e046SJonathan Cameron static DEFINE_IDA(iio_ida);
38a980e046SJonathan Cameron 
39a980e046SJonathan Cameron static dev_t iio_devt;
40a980e046SJonathan Cameron 
41a980e046SJonathan Cameron #define IIO_DEV_MAX 256
42a980e046SJonathan Cameron struct bus_type iio_bus_type = {
43a980e046SJonathan Cameron 	.name = "iio",
44a980e046SJonathan Cameron };
45a980e046SJonathan Cameron EXPORT_SYMBOL(iio_bus_type);
46a980e046SJonathan Cameron 
47a980e046SJonathan Cameron static struct dentry *iio_debugfs_dentry;
48a980e046SJonathan Cameron 
49a980e046SJonathan Cameron static const char * const iio_direction[] = {
50a980e046SJonathan Cameron 	[0] = "in",
51a980e046SJonathan Cameron 	[1] = "out",
52a980e046SJonathan Cameron };
53a980e046SJonathan Cameron 
54a980e046SJonathan Cameron static const char * const iio_chan_type_name_spec[] = {
55a980e046SJonathan Cameron 	[IIO_VOLTAGE] = "voltage",
56a980e046SJonathan Cameron 	[IIO_CURRENT] = "current",
57a980e046SJonathan Cameron 	[IIO_POWER] = "power",
58a980e046SJonathan Cameron 	[IIO_ACCEL] = "accel",
59a980e046SJonathan Cameron 	[IIO_ANGL_VEL] = "anglvel",
60a980e046SJonathan Cameron 	[IIO_MAGN] = "magn",
61a980e046SJonathan Cameron 	[IIO_LIGHT] = "illuminance",
62a980e046SJonathan Cameron 	[IIO_INTENSITY] = "intensity",
63a980e046SJonathan Cameron 	[IIO_PROXIMITY] = "proximity",
64a980e046SJonathan Cameron 	[IIO_TEMP] = "temp",
65a980e046SJonathan Cameron 	[IIO_INCLI] = "incli",
66a980e046SJonathan Cameron 	[IIO_ROT] = "rot",
67a980e046SJonathan Cameron 	[IIO_ANGL] = "angl",
68a980e046SJonathan Cameron 	[IIO_TIMESTAMP] = "timestamp",
69a980e046SJonathan Cameron 	[IIO_CAPACITANCE] = "capacitance",
70a6b12855SMichael Hennerich 	[IIO_ALTVOLTAGE] = "altvoltage",
7121cd1fabSJon Brenner 	[IIO_CCT] = "cct",
72c4f0c693SLars-Peter Clausen 	[IIO_PRESSURE] = "pressure",
73ac216aa2SHarald Geyer 	[IIO_HUMIDITYRELATIVE] = "humidityrelative",
7455aebeb9SDaniel Baluta 	[IIO_ACTIVITY] = "activity",
75a88bfe78SIrina Tirdea 	[IIO_STEPS] = "steps",
7672c66644SIrina Tirdea 	[IIO_ENERGY] = "energy",
77cc3c9eecSIrina Tirdea 	[IIO_DISTANCE] = "distance",
785a1a9329SIrina Tirdea 	[IIO_VELOCITY] = "velocity",
798ff6b3bcSMatt Ranostay 	[IIO_CONCENTRATION] = "concentration",
80d38d5469SMatt Ranostay 	[IIO_RESISTANCE] = "resistance",
81ecb3a7ccSMatt Ranostay 	[IIO_PH] = "ph",
82d409404cSPeter Meerwald-Stadler 	[IIO_UVINDEX] = "uvindex",
834b9d2090SMatt Ranostay 	[IIO_ELECTRICALCONDUCTIVITY] = "electricalconductivity",
841a8f324aSWilliam Breathitt Gray 	[IIO_COUNT] = "count",
851a8f324aSWilliam Breathitt Gray 	[IIO_INDEX] = "index",
86571299d0SSong Hongyan 	[IIO_GRAVITY]  = "gravity",
873055a6cfSEugen Hristev 	[IIO_POSITIONRELATIVE]  = "positionrelative",
88c73314e6SMathieu Othacehe 	[IIO_PHASE] = "phase",
8917abc9ecSTomasz Duszynski 	[IIO_MASSCONCENTRATION] = "massconcentration",
90a980e046SJonathan Cameron };
91a980e046SJonathan Cameron 
92a980e046SJonathan Cameron static const char * const iio_modifier_names[] = {
93a980e046SJonathan Cameron 	[IIO_MOD_X] = "x",
94a980e046SJonathan Cameron 	[IIO_MOD_Y] = "y",
95a980e046SJonathan Cameron 	[IIO_MOD_Z] = "z",
964b8d8015SPeter Meerwald 	[IIO_MOD_X_AND_Y] = "x&y",
974b8d8015SPeter Meerwald 	[IIO_MOD_X_AND_Z] = "x&z",
984b8d8015SPeter Meerwald 	[IIO_MOD_Y_AND_Z] = "y&z",
994b8d8015SPeter Meerwald 	[IIO_MOD_X_AND_Y_AND_Z] = "x&y&z",
1004b8d8015SPeter Meerwald 	[IIO_MOD_X_OR_Y] = "x|y",
1014b8d8015SPeter Meerwald 	[IIO_MOD_X_OR_Z] = "x|z",
1024b8d8015SPeter Meerwald 	[IIO_MOD_Y_OR_Z] = "y|z",
1034b8d8015SPeter Meerwald 	[IIO_MOD_X_OR_Y_OR_Z] = "x|y|z",
1048f5879b2SJonathan Cameron 	[IIO_MOD_ROOT_SUM_SQUARED_X_Y] = "sqrt(x^2+y^2)",
105cf82cb81SJonathan Cameron 	[IIO_MOD_SUM_SQUARED_X_Y_Z] = "x^2+y^2+z^2",
106a980e046SJonathan Cameron 	[IIO_MOD_LIGHT_BOTH] = "both",
107a980e046SJonathan Cameron 	[IIO_MOD_LIGHT_IR] = "ir",
10821cd1fabSJon Brenner 	[IIO_MOD_LIGHT_CLEAR] = "clear",
10921cd1fabSJon Brenner 	[IIO_MOD_LIGHT_RED] = "red",
11021cd1fabSJon Brenner 	[IIO_MOD_LIGHT_GREEN] = "green",
11121cd1fabSJon Brenner 	[IIO_MOD_LIGHT_BLUE] = "blue",
1122c5ff1f9SPeter Meerwald-Stadler 	[IIO_MOD_LIGHT_UV] = "uv",
113c0e4e0fdSMaxime Roussin-Bélanger 	[IIO_MOD_LIGHT_DUV] = "duv",
1145082f405SSrinivas Pandruvada 	[IIO_MOD_QUATERNION] = "quaternion",
115638b43b3SPeter Meerwald 	[IIO_MOD_TEMP_AMBIENT] = "ambient",
116638b43b3SPeter Meerwald 	[IIO_MOD_TEMP_OBJECT] = "object",
11711b8ddabSReyad Attiyat 	[IIO_MOD_NORTH_MAGN] = "from_north_magnetic",
11811b8ddabSReyad Attiyat 	[IIO_MOD_NORTH_TRUE] = "from_north_true",
11911b8ddabSReyad Attiyat 	[IIO_MOD_NORTH_MAGN_TILT_COMP] = "from_north_magnetic_tilt_comp",
12011b8ddabSReyad Attiyat 	[IIO_MOD_NORTH_TRUE_TILT_COMP] = "from_north_true_tilt_comp",
12155aebeb9SDaniel Baluta 	[IIO_MOD_RUNNING] = "running",
12255aebeb9SDaniel Baluta 	[IIO_MOD_JOGGING] = "jogging",
12355aebeb9SDaniel Baluta 	[IIO_MOD_WALKING] = "walking",
12455aebeb9SDaniel Baluta 	[IIO_MOD_STILL] = "still",
1255a1a9329SIrina Tirdea 	[IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z] = "sqrt(x^2+y^2+z^2)",
1261ce87f21SLars-Peter Clausen 	[IIO_MOD_I] = "i",
1271ce87f21SLars-Peter Clausen 	[IIO_MOD_Q] = "q",
1288ff6b3bcSMatt Ranostay 	[IIO_MOD_CO2] = "co2",
1298ff6b3bcSMatt Ranostay 	[IIO_MOD_VOC] = "voc",
13017abc9ecSTomasz Duszynski 	[IIO_MOD_PM1] = "pm1",
13117abc9ecSTomasz Duszynski 	[IIO_MOD_PM2P5] = "pm2p5",
13217abc9ecSTomasz Duszynski 	[IIO_MOD_PM4] = "pm4",
13317abc9ecSTomasz Duszynski 	[IIO_MOD_PM10] = "pm10",
13425f02d32SMatt Ranostay 	[IIO_MOD_ETHANOL] = "ethanol",
13525f02d32SMatt Ranostay 	[IIO_MOD_H2] = "h2",
1364ffa22fdSMatt Ranostay 	[IIO_MOD_O2] = "o2",
137a980e046SJonathan Cameron };
138a980e046SJonathan Cameron 
139a980e046SJonathan Cameron /* relies on pairs of these shared then separate */
140a980e046SJonathan Cameron static const char * const iio_chan_info_postfix[] = {
141a980e046SJonathan Cameron 	[IIO_CHAN_INFO_RAW] = "raw",
142a980e046SJonathan Cameron 	[IIO_CHAN_INFO_PROCESSED] = "input",
143a980e046SJonathan Cameron 	[IIO_CHAN_INFO_SCALE] = "scale",
144a980e046SJonathan Cameron 	[IIO_CHAN_INFO_OFFSET] = "offset",
145a980e046SJonathan Cameron 	[IIO_CHAN_INFO_CALIBSCALE] = "calibscale",
146a980e046SJonathan Cameron 	[IIO_CHAN_INFO_CALIBBIAS] = "calibbias",
147a980e046SJonathan Cameron 	[IIO_CHAN_INFO_PEAK] = "peak_raw",
148a980e046SJonathan Cameron 	[IIO_CHAN_INFO_PEAK_SCALE] = "peak_scale",
149a980e046SJonathan Cameron 	[IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW] = "quadrature_correction_raw",
150a980e046SJonathan Cameron 	[IIO_CHAN_INFO_AVERAGE_RAW] = "mean_raw",
151a980e046SJonathan Cameron 	[IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY]
152a980e046SJonathan Cameron 	= "filter_low_pass_3db_frequency",
1533f7f642bSMartin Fuzzey 	[IIO_CHAN_INFO_HIGH_PASS_FILTER_3DB_FREQUENCY]
1543f7f642bSMartin Fuzzey 	= "filter_high_pass_3db_frequency",
155a980e046SJonathan Cameron 	[IIO_CHAN_INFO_SAMP_FREQ] = "sampling_frequency",
156a6b12855SMichael Hennerich 	[IIO_CHAN_INFO_FREQUENCY] = "frequency",
157a6b12855SMichael Hennerich 	[IIO_CHAN_INFO_PHASE] = "phase",
158b65d6212SMichael Hennerich 	[IIO_CHAN_INFO_HARDWAREGAIN] = "hardwaregain",
1597c9ab035Ssrinivas pandruvada 	[IIO_CHAN_INFO_HYSTERESIS] = "hysteresis",
160899d90bdSPeter Meerwald 	[IIO_CHAN_INFO_INT_TIME] = "integration_time",
161a88bfe78SIrina Tirdea 	[IIO_CHAN_INFO_ENABLE] = "en",
162bcdf28fbSIrina Tirdea 	[IIO_CHAN_INFO_CALIBHEIGHT] = "calibheight",
163d37f6836SIrina Tirdea 	[IIO_CHAN_INFO_CALIBWEIGHT] = "calibweight",
1642f0ecb7cSIrina Tirdea 	[IIO_CHAN_INFO_DEBOUNCE_COUNT] = "debounce_count",
1652f0ecb7cSIrina Tirdea 	[IIO_CHAN_INFO_DEBOUNCE_TIME] = "debounce_time",
166c8a85854SVianney le Clément de Saint-Marcq 	[IIO_CHAN_INFO_CALIBEMISSIVITY] = "calibemissivity",
167faaa4495SIrina Tirdea 	[IIO_CHAN_INFO_OVERSAMPLING_RATIO] = "oversampling_ratio",
168ddfb97d8SAndrea Merello 	[IIO_CHAN_INFO_THERMOCOUPLE_TYPE] = "thermocouple_type",
169dde8ceecSCrt Mori 	[IIO_CHAN_INFO_CALIBAMBIENT] = "calibambient",
170a980e046SJonathan Cameron };
171a980e046SJonathan Cameron 
172*d9a0e73cSLars-Peter Clausen /**
173*d9a0e73cSLars-Peter Clausen  * iio_sysfs_match_string_with_gaps - matches given string in an array with gaps
174*d9a0e73cSLars-Peter Clausen  * @array: array of strings
175*d9a0e73cSLars-Peter Clausen  * @n: number of strings in the array
176*d9a0e73cSLars-Peter Clausen  * @str: string to match with
177*d9a0e73cSLars-Peter Clausen  *
178*d9a0e73cSLars-Peter Clausen  * Returns index of @str in the @array or -EINVAL, similar to match_string().
179*d9a0e73cSLars-Peter Clausen  * Uses sysfs_streq instead of strcmp for matching.
180*d9a0e73cSLars-Peter Clausen  *
181*d9a0e73cSLars-Peter Clausen  * This routine will look for a string in an array of strings.
182*d9a0e73cSLars-Peter Clausen  * The search will continue until the element is found or the n-th element
183*d9a0e73cSLars-Peter Clausen  * is reached, regardless of any NULL elements in the array.
184*d9a0e73cSLars-Peter Clausen  */
185*d9a0e73cSLars-Peter Clausen static int iio_sysfs_match_string_with_gaps(const char * const *array, size_t n,
186*d9a0e73cSLars-Peter Clausen 					    const char *str)
187*d9a0e73cSLars-Peter Clausen {
188*d9a0e73cSLars-Peter Clausen 	const char *item;
189*d9a0e73cSLars-Peter Clausen 	int index;
190*d9a0e73cSLars-Peter Clausen 
191*d9a0e73cSLars-Peter Clausen 	for (index = 0; index < n; index++) {
192*d9a0e73cSLars-Peter Clausen 		item = array[index];
193*d9a0e73cSLars-Peter Clausen 		if (!item)
194*d9a0e73cSLars-Peter Clausen 			continue;
195*d9a0e73cSLars-Peter Clausen 		if (sysfs_streq(item, str))
196*d9a0e73cSLars-Peter Clausen 			return index;
197*d9a0e73cSLars-Peter Clausen 	}
198*d9a0e73cSLars-Peter Clausen 
199*d9a0e73cSLars-Peter Clausen 	return -EINVAL;
200*d9a0e73cSLars-Peter Clausen }
201*d9a0e73cSLars-Peter Clausen 
20296fb1b67SAlexandru Ardelean #if defined(CONFIG_DEBUG_FS)
203c9561fd2SJonathan Cameron /*
20496fb1b67SAlexandru Ardelean  * There's also a CONFIG_DEBUG_FS guard in include/linux/iio/iio.h for
20596fb1b67SAlexandru Ardelean  * iio_get_debugfs_dentry() to make it inline if CONFIG_DEBUG_FS is undefined
20696fb1b67SAlexandru Ardelean  */
20796fb1b67SAlexandru Ardelean struct dentry *iio_get_debugfs_dentry(struct iio_dev *indio_dev)
20896fb1b67SAlexandru Ardelean {
20996fb1b67SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
21096fb1b67SAlexandru Ardelean 	return iio_dev_opaque->debugfs_dentry;
21196fb1b67SAlexandru Ardelean }
21296fb1b67SAlexandru Ardelean EXPORT_SYMBOL_GPL(iio_get_debugfs_dentry);
21396fb1b67SAlexandru Ardelean #endif
21496fb1b67SAlexandru Ardelean 
215a7e57dceSSachin Kamat /**
216a7e57dceSSachin Kamat  * iio_find_channel_from_si() - get channel from its scan index
217a7e57dceSSachin Kamat  * @indio_dev:		device
218a7e57dceSSachin Kamat  * @si:			scan index to match
219a7e57dceSSachin Kamat  */
220a980e046SJonathan Cameron const struct iio_chan_spec
221a980e046SJonathan Cameron *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
222a980e046SJonathan Cameron {
223a980e046SJonathan Cameron 	int i;
224a980e046SJonathan Cameron 
225a980e046SJonathan Cameron 	for (i = 0; i < indio_dev->num_channels; i++)
226a980e046SJonathan Cameron 		if (indio_dev->channels[i].scan_index == si)
227a980e046SJonathan Cameron 			return &indio_dev->channels[i];
228a980e046SJonathan Cameron 	return NULL;
229a980e046SJonathan Cameron }
230a980e046SJonathan Cameron 
231a980e046SJonathan Cameron /* This turns up an awful lot */
232a980e046SJonathan Cameron ssize_t iio_read_const_attr(struct device *dev,
233a980e046SJonathan Cameron 			    struct device_attribute *attr,
234a980e046SJonathan Cameron 			    char *buf)
235a980e046SJonathan Cameron {
236a980e046SJonathan Cameron 	return sprintf(buf, "%s\n", to_iio_const_attr(attr)->string);
237a980e046SJonathan Cameron }
238a980e046SJonathan Cameron EXPORT_SYMBOL(iio_read_const_attr);
239a980e046SJonathan Cameron 
24069f0793eSGwendal Grignou /**
24169f0793eSGwendal Grignou  * iio_device_set_clock() - Set current timestamping clock for the device
24269f0793eSGwendal Grignou  * @indio_dev: IIO device structure containing the device
24369f0793eSGwendal Grignou  * @clock_id: timestamping clock posix identifier to set.
24469f0793eSGwendal Grignou  */
24569f0793eSGwendal Grignou int iio_device_set_clock(struct iio_dev *indio_dev, clockid_t clock_id)
246bc2b7dabSGregor Boirie {
247bc2b7dabSGregor Boirie 	int ret;
248fa83c3baSAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
249fa83c3baSAlexandru Ardelean 	const struct iio_event_interface *ev_int = iio_dev_opaque->event_interface;
250bc2b7dabSGregor Boirie 
251bc2b7dabSGregor Boirie 	ret = mutex_lock_interruptible(&indio_dev->mlock);
252bc2b7dabSGregor Boirie 	if (ret)
253bc2b7dabSGregor Boirie 		return ret;
254bc2b7dabSGregor Boirie 	if ((ev_int && iio_event_enabled(ev_int)) ||
255bc2b7dabSGregor Boirie 	    iio_buffer_enabled(indio_dev)) {
256bc2b7dabSGregor Boirie 		mutex_unlock(&indio_dev->mlock);
257bc2b7dabSGregor Boirie 		return -EBUSY;
258bc2b7dabSGregor Boirie 	}
259bc2b7dabSGregor Boirie 	indio_dev->clock_id = clock_id;
260bc2b7dabSGregor Boirie 	mutex_unlock(&indio_dev->mlock);
261bc2b7dabSGregor Boirie 
262bc2b7dabSGregor Boirie 	return 0;
263bc2b7dabSGregor Boirie }
26469f0793eSGwendal Grignou EXPORT_SYMBOL(iio_device_set_clock);
265bc2b7dabSGregor Boirie 
266bc2b7dabSGregor Boirie /**
267bc2b7dabSGregor Boirie  * iio_get_time_ns() - utility function to get a time stamp for events etc
268bc2b7dabSGregor Boirie  * @indio_dev: device
269bc2b7dabSGregor Boirie  */
270bc2b7dabSGregor Boirie s64 iio_get_time_ns(const struct iio_dev *indio_dev)
271bc2b7dabSGregor Boirie {
27245e7f5d2SArnd Bergmann 	struct timespec64 tp;
273bc2b7dabSGregor Boirie 
274bc2b7dabSGregor Boirie 	switch (iio_device_get_clock(indio_dev)) {
275bc2b7dabSGregor Boirie 	case CLOCK_REALTIME:
27645e7f5d2SArnd Bergmann 		return ktime_get_real_ns();
277bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC:
27845e7f5d2SArnd Bergmann 		return ktime_get_ns();
279bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC_RAW:
28045e7f5d2SArnd Bergmann 		return ktime_get_raw_ns();
281bc2b7dabSGregor Boirie 	case CLOCK_REALTIME_COARSE:
28245e7f5d2SArnd Bergmann 		return ktime_to_ns(ktime_get_coarse_real());
283bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC_COARSE:
28445e7f5d2SArnd Bergmann 		ktime_get_coarse_ts64(&tp);
28545e7f5d2SArnd Bergmann 		return timespec64_to_ns(&tp);
286bc2b7dabSGregor Boirie 	case CLOCK_BOOTTIME:
2879285ec4cSJason A. Donenfeld 		return ktime_get_boottime_ns();
288bc2b7dabSGregor Boirie 	case CLOCK_TAI:
2899285ec4cSJason A. Donenfeld 		return ktime_get_clocktai_ns();
290bc2b7dabSGregor Boirie 	default:
291bc2b7dabSGregor Boirie 		BUG();
292bc2b7dabSGregor Boirie 	}
293bc2b7dabSGregor Boirie }
294bc2b7dabSGregor Boirie EXPORT_SYMBOL(iio_get_time_ns);
295bc2b7dabSGregor Boirie 
296bc2b7dabSGregor Boirie /**
297bc2b7dabSGregor Boirie  * iio_get_time_res() - utility function to get time stamp clock resolution in
298bc2b7dabSGregor Boirie  *                      nano seconds.
299bc2b7dabSGregor Boirie  * @indio_dev: device
300bc2b7dabSGregor Boirie  */
301bc2b7dabSGregor Boirie unsigned int iio_get_time_res(const struct iio_dev *indio_dev)
302bc2b7dabSGregor Boirie {
303bc2b7dabSGregor Boirie 	switch (iio_device_get_clock(indio_dev)) {
304bc2b7dabSGregor Boirie 	case CLOCK_REALTIME:
305bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC:
306bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC_RAW:
307bc2b7dabSGregor Boirie 	case CLOCK_BOOTTIME:
308bc2b7dabSGregor Boirie 	case CLOCK_TAI:
309bc2b7dabSGregor Boirie 		return hrtimer_resolution;
310bc2b7dabSGregor Boirie 	case CLOCK_REALTIME_COARSE:
311bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC_COARSE:
312bc2b7dabSGregor Boirie 		return LOW_RES_NSEC;
313bc2b7dabSGregor Boirie 	default:
314bc2b7dabSGregor Boirie 		BUG();
315bc2b7dabSGregor Boirie 	}
316bc2b7dabSGregor Boirie }
317bc2b7dabSGregor Boirie EXPORT_SYMBOL(iio_get_time_res);
318bc2b7dabSGregor Boirie 
319a980e046SJonathan Cameron static int __init iio_init(void)
320a980e046SJonathan Cameron {
321a980e046SJonathan Cameron 	int ret;
322a980e046SJonathan Cameron 
323a980e046SJonathan Cameron 	/* Register sysfs bus */
324a980e046SJonathan Cameron 	ret  = bus_register(&iio_bus_type);
325a980e046SJonathan Cameron 	if (ret < 0) {
3263176dd5dSSachin Kamat 		pr_err("could not register bus type\n");
327a980e046SJonathan Cameron 		goto error_nothing;
328a980e046SJonathan Cameron 	}
329a980e046SJonathan Cameron 
330a980e046SJonathan Cameron 	ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
331a980e046SJonathan Cameron 	if (ret < 0) {
3323176dd5dSSachin Kamat 		pr_err("failed to allocate char dev region\n");
333a980e046SJonathan Cameron 		goto error_unregister_bus_type;
334a980e046SJonathan Cameron 	}
335a980e046SJonathan Cameron 
336a980e046SJonathan Cameron 	iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
337a980e046SJonathan Cameron 
338a980e046SJonathan Cameron 	return 0;
339a980e046SJonathan Cameron 
340a980e046SJonathan Cameron error_unregister_bus_type:
341a980e046SJonathan Cameron 	bus_unregister(&iio_bus_type);
342a980e046SJonathan Cameron error_nothing:
343a980e046SJonathan Cameron 	return ret;
344a980e046SJonathan Cameron }
345a980e046SJonathan Cameron 
346a980e046SJonathan Cameron static void __exit iio_exit(void)
347a980e046SJonathan Cameron {
348a980e046SJonathan Cameron 	if (iio_devt)
349a980e046SJonathan Cameron 		unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
350a980e046SJonathan Cameron 	bus_unregister(&iio_bus_type);
351a980e046SJonathan Cameron 	debugfs_remove(iio_debugfs_dentry);
352a980e046SJonathan Cameron }
353a980e046SJonathan Cameron 
354a980e046SJonathan Cameron #if defined(CONFIG_DEBUG_FS)
355a980e046SJonathan Cameron static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
356a980e046SJonathan Cameron 			      size_t count, loff_t *ppos)
357a980e046SJonathan Cameron {
358a980e046SJonathan Cameron 	struct iio_dev *indio_dev = file->private_data;
35996fb1b67SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
360a980e046SJonathan Cameron 	unsigned val = 0;
361a980e046SJonathan Cameron 	int ret;
362a980e046SJonathan Cameron 
3632ddc982aSAlexandru Tachici 	if (*ppos > 0)
3642ddc982aSAlexandru Tachici 		return simple_read_from_buffer(userbuf, count, ppos,
36596fb1b67SAlexandru Ardelean 					       iio_dev_opaque->read_buf,
36696fb1b67SAlexandru Ardelean 					       iio_dev_opaque->read_buf_len);
3672ddc982aSAlexandru Tachici 
368a980e046SJonathan Cameron 	ret = indio_dev->info->debugfs_reg_access(indio_dev,
36996fb1b67SAlexandru Ardelean 						  iio_dev_opaque->cached_reg_addr,
370a980e046SJonathan Cameron 						  0, &val);
3713d62c78aSMatt Fornero 	if (ret) {
372a980e046SJonathan Cameron 		dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
3733d62c78aSMatt Fornero 		return ret;
3743d62c78aSMatt Fornero 	}
375a980e046SJonathan Cameron 
37696fb1b67SAlexandru Ardelean 	iio_dev_opaque->read_buf_len = snprintf(iio_dev_opaque->read_buf,
37796fb1b67SAlexandru Ardelean 					      sizeof(iio_dev_opaque->read_buf),
3782ddc982aSAlexandru Tachici 					      "0x%X\n", val);
379a980e046SJonathan Cameron 
3802ddc982aSAlexandru Tachici 	return simple_read_from_buffer(userbuf, count, ppos,
38196fb1b67SAlexandru Ardelean 				       iio_dev_opaque->read_buf,
38296fb1b67SAlexandru Ardelean 				       iio_dev_opaque->read_buf_len);
383a980e046SJonathan Cameron }
384a980e046SJonathan Cameron 
385a980e046SJonathan Cameron static ssize_t iio_debugfs_write_reg(struct file *file,
386a980e046SJonathan Cameron 		     const char __user *userbuf, size_t count, loff_t *ppos)
387a980e046SJonathan Cameron {
388a980e046SJonathan Cameron 	struct iio_dev *indio_dev = file->private_data;
38996fb1b67SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
390a980e046SJonathan Cameron 	unsigned reg, val;
391a980e046SJonathan Cameron 	char buf[80];
392a980e046SJonathan Cameron 	int ret;
393a980e046SJonathan Cameron 
394a980e046SJonathan Cameron 	count = min_t(size_t, count, (sizeof(buf)-1));
395a980e046SJonathan Cameron 	if (copy_from_user(buf, userbuf, count))
396a980e046SJonathan Cameron 		return -EFAULT;
397a980e046SJonathan Cameron 
398a980e046SJonathan Cameron 	buf[count] = 0;
399a980e046SJonathan Cameron 
400a980e046SJonathan Cameron 	ret = sscanf(buf, "%i %i", &reg, &val);
401a980e046SJonathan Cameron 
402a980e046SJonathan Cameron 	switch (ret) {
403a980e046SJonathan Cameron 	case 1:
40496fb1b67SAlexandru Ardelean 		iio_dev_opaque->cached_reg_addr = reg;
405a980e046SJonathan Cameron 		break;
406a980e046SJonathan Cameron 	case 2:
40796fb1b67SAlexandru Ardelean 		iio_dev_opaque->cached_reg_addr = reg;
408a980e046SJonathan Cameron 		ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
409a980e046SJonathan Cameron 							  val, NULL);
410a980e046SJonathan Cameron 		if (ret) {
411a980e046SJonathan Cameron 			dev_err(indio_dev->dev.parent, "%s: write failed\n",
412a980e046SJonathan Cameron 				__func__);
413a980e046SJonathan Cameron 			return ret;
414a980e046SJonathan Cameron 		}
415a980e046SJonathan Cameron 		break;
416a980e046SJonathan Cameron 	default:
417a980e046SJonathan Cameron 		return -EINVAL;
418a980e046SJonathan Cameron 	}
419a980e046SJonathan Cameron 
420a980e046SJonathan Cameron 	return count;
421a980e046SJonathan Cameron }
422a980e046SJonathan Cameron 
423a980e046SJonathan Cameron static const struct file_operations iio_debugfs_reg_fops = {
4245a28c873SAxel Lin 	.open = simple_open,
425a980e046SJonathan Cameron 	.read = iio_debugfs_read_reg,
426a980e046SJonathan Cameron 	.write = iio_debugfs_write_reg,
427a980e046SJonathan Cameron };
428a980e046SJonathan Cameron 
429a980e046SJonathan Cameron static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
430a980e046SJonathan Cameron {
43196fb1b67SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
43296fb1b67SAlexandru Ardelean 	debugfs_remove_recursive(iio_dev_opaque->debugfs_dentry);
433a980e046SJonathan Cameron }
434a980e046SJonathan Cameron 
4358915aacaSGreg Kroah-Hartman static void iio_device_register_debugfs(struct iio_dev *indio_dev)
436a980e046SJonathan Cameron {
43796fb1b67SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque;
43896fb1b67SAlexandru Ardelean 
439a980e046SJonathan Cameron 	if (indio_dev->info->debugfs_reg_access == NULL)
4408915aacaSGreg Kroah-Hartman 		return;
441a980e046SJonathan Cameron 
442abd5a2fbSAxel Lin 	if (!iio_debugfs_dentry)
4438915aacaSGreg Kroah-Hartman 		return;
444a980e046SJonathan Cameron 
44596fb1b67SAlexandru Ardelean 	iio_dev_opaque = to_iio_dev_opaque(indio_dev);
44696fb1b67SAlexandru Ardelean 
44796fb1b67SAlexandru Ardelean 	iio_dev_opaque->debugfs_dentry =
448a980e046SJonathan Cameron 		debugfs_create_dir(dev_name(&indio_dev->dev),
449a980e046SJonathan Cameron 				   iio_debugfs_dentry);
450a980e046SJonathan Cameron 
4518915aacaSGreg Kroah-Hartman 	debugfs_create_file("direct_reg_access", 0644,
45296fb1b67SAlexandru Ardelean 			    iio_dev_opaque->debugfs_dentry, indio_dev,
4538915aacaSGreg Kroah-Hartman 			    &iio_debugfs_reg_fops);
454a980e046SJonathan Cameron }
455a980e046SJonathan Cameron #else
4568915aacaSGreg Kroah-Hartman static void iio_device_register_debugfs(struct iio_dev *indio_dev)
457a980e046SJonathan Cameron {
458a980e046SJonathan Cameron }
459a980e046SJonathan Cameron 
460a980e046SJonathan Cameron static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
461a980e046SJonathan Cameron {
462a980e046SJonathan Cameron }
463a980e046SJonathan Cameron #endif /* CONFIG_DEBUG_FS */
464a980e046SJonathan Cameron 
465a980e046SJonathan Cameron static ssize_t iio_read_channel_ext_info(struct device *dev,
466a980e046SJonathan Cameron 				     struct device_attribute *attr,
467a980e046SJonathan Cameron 				     char *buf)
468a980e046SJonathan Cameron {
469e53f5ac5SLars-Peter Clausen 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
470a980e046SJonathan Cameron 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
471a980e046SJonathan Cameron 	const struct iio_chan_spec_ext_info *ext_info;
472a980e046SJonathan Cameron 
473a980e046SJonathan Cameron 	ext_info = &this_attr->c->ext_info[this_attr->address];
474a980e046SJonathan Cameron 
475fc6d1139SMichael Hennerich 	return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
476a980e046SJonathan Cameron }
477a980e046SJonathan Cameron 
478a980e046SJonathan Cameron static ssize_t iio_write_channel_ext_info(struct device *dev,
479a980e046SJonathan Cameron 				     struct device_attribute *attr,
480a980e046SJonathan Cameron 				     const char *buf,
481a980e046SJonathan Cameron 					 size_t len)
482a980e046SJonathan Cameron {
483e53f5ac5SLars-Peter Clausen 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
484a980e046SJonathan Cameron 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
485a980e046SJonathan Cameron 	const struct iio_chan_spec_ext_info *ext_info;
486a980e046SJonathan Cameron 
487a980e046SJonathan Cameron 	ext_info = &this_attr->c->ext_info[this_attr->address];
488a980e046SJonathan Cameron 
489fc6d1139SMichael Hennerich 	return ext_info->write(indio_dev, ext_info->private,
490fc6d1139SMichael Hennerich 			       this_attr->c, buf, len);
491a980e046SJonathan Cameron }
492a980e046SJonathan Cameron 
4935212cc8aSLars-Peter Clausen ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
4945212cc8aSLars-Peter Clausen 	uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
4955212cc8aSLars-Peter Clausen {
4965212cc8aSLars-Peter Clausen 	const struct iio_enum *e = (const struct iio_enum *)priv;
4975212cc8aSLars-Peter Clausen 	unsigned int i;
4985212cc8aSLars-Peter Clausen 	size_t len = 0;
4995212cc8aSLars-Peter Clausen 
5005212cc8aSLars-Peter Clausen 	if (!e->num_items)
5015212cc8aSLars-Peter Clausen 		return 0;
5025212cc8aSLars-Peter Clausen 
503*d9a0e73cSLars-Peter Clausen 	for (i = 0; i < e->num_items; ++i) {
504*d9a0e73cSLars-Peter Clausen 		if (!e->items[i])
505*d9a0e73cSLars-Peter Clausen 			continue;
50674dcd439SLars-Peter Clausen 		len += scnprintf(buf + len, PAGE_SIZE - len, "%s ", e->items[i]);
507*d9a0e73cSLars-Peter Clausen 	}
5085212cc8aSLars-Peter Clausen 
5095212cc8aSLars-Peter Clausen 	/* replace last space with a newline */
5105212cc8aSLars-Peter Clausen 	buf[len - 1] = '\n';
5115212cc8aSLars-Peter Clausen 
5125212cc8aSLars-Peter Clausen 	return len;
5135212cc8aSLars-Peter Clausen }
5145212cc8aSLars-Peter Clausen EXPORT_SYMBOL_GPL(iio_enum_available_read);
5155212cc8aSLars-Peter Clausen 
5165212cc8aSLars-Peter Clausen ssize_t iio_enum_read(struct iio_dev *indio_dev,
5175212cc8aSLars-Peter Clausen 	uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
5185212cc8aSLars-Peter Clausen {
5195212cc8aSLars-Peter Clausen 	const struct iio_enum *e = (const struct iio_enum *)priv;
5205212cc8aSLars-Peter Clausen 	int i;
5215212cc8aSLars-Peter Clausen 
5225212cc8aSLars-Peter Clausen 	if (!e->get)
5235212cc8aSLars-Peter Clausen 		return -EINVAL;
5245212cc8aSLars-Peter Clausen 
5255212cc8aSLars-Peter Clausen 	i = e->get(indio_dev, chan);
5265212cc8aSLars-Peter Clausen 	if (i < 0)
5275212cc8aSLars-Peter Clausen 		return i;
528*d9a0e73cSLars-Peter Clausen 	else if (i >= e->num_items || !e->items[i])
5295212cc8aSLars-Peter Clausen 		return -EINVAL;
5305212cc8aSLars-Peter Clausen 
531598db581SKees Cook 	return snprintf(buf, PAGE_SIZE, "%s\n", e->items[i]);
5325212cc8aSLars-Peter Clausen }
5335212cc8aSLars-Peter Clausen EXPORT_SYMBOL_GPL(iio_enum_read);
5345212cc8aSLars-Peter Clausen 
5355212cc8aSLars-Peter Clausen ssize_t iio_enum_write(struct iio_dev *indio_dev,
5365212cc8aSLars-Peter Clausen 	uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
5375212cc8aSLars-Peter Clausen 	size_t len)
5385212cc8aSLars-Peter Clausen {
5395212cc8aSLars-Peter Clausen 	const struct iio_enum *e = (const struct iio_enum *)priv;
5405212cc8aSLars-Peter Clausen 	int ret;
5415212cc8aSLars-Peter Clausen 
5425212cc8aSLars-Peter Clausen 	if (!e->set)
5435212cc8aSLars-Peter Clausen 		return -EINVAL;
5445212cc8aSLars-Peter Clausen 
545*d9a0e73cSLars-Peter Clausen 	ret = iio_sysfs_match_string_with_gaps(e->items, e->num_items, buf);
54602e9a0ffSAndy Shevchenko 	if (ret < 0)
54702e9a0ffSAndy Shevchenko 		return ret;
5485212cc8aSLars-Peter Clausen 
54902e9a0ffSAndy Shevchenko 	ret = e->set(indio_dev, chan, ret);
5505212cc8aSLars-Peter Clausen 	return ret ? ret : len;
5515212cc8aSLars-Peter Clausen }
5525212cc8aSLars-Peter Clausen EXPORT_SYMBOL_GPL(iio_enum_write);
5535212cc8aSLars-Peter Clausen 
554dfc57732SGregor Boirie static const struct iio_mount_matrix iio_mount_idmatrix = {
555dfc57732SGregor Boirie 	.rotation = {
556dfc57732SGregor Boirie 		"1", "0", "0",
557dfc57732SGregor Boirie 		"0", "1", "0",
558dfc57732SGregor Boirie 		"0", "0", "1"
559dfc57732SGregor Boirie 	}
560dfc57732SGregor Boirie };
561dfc57732SGregor Boirie 
562dfc57732SGregor Boirie static int iio_setup_mount_idmatrix(const struct device *dev,
563dfc57732SGregor Boirie 				    struct iio_mount_matrix *matrix)
564dfc57732SGregor Boirie {
565dfc57732SGregor Boirie 	*matrix = iio_mount_idmatrix;
566dfc57732SGregor Boirie 	dev_info(dev, "mounting matrix not found: using identity...\n");
567dfc57732SGregor Boirie 	return 0;
568dfc57732SGregor Boirie }
569dfc57732SGregor Boirie 
570dfc57732SGregor Boirie ssize_t iio_show_mount_matrix(struct iio_dev *indio_dev, uintptr_t priv,
571dfc57732SGregor Boirie 			      const struct iio_chan_spec *chan, char *buf)
572dfc57732SGregor Boirie {
573dfc57732SGregor Boirie 	const struct iio_mount_matrix *mtx = ((iio_get_mount_matrix_t *)
574dfc57732SGregor Boirie 					      priv)(indio_dev, chan);
575dfc57732SGregor Boirie 
576dfc57732SGregor Boirie 	if (IS_ERR(mtx))
577dfc57732SGregor Boirie 		return PTR_ERR(mtx);
578dfc57732SGregor Boirie 
579dfc57732SGregor Boirie 	if (!mtx)
580dfc57732SGregor Boirie 		mtx = &iio_mount_idmatrix;
581dfc57732SGregor Boirie 
582dfc57732SGregor Boirie 	return snprintf(buf, PAGE_SIZE, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
583dfc57732SGregor Boirie 			mtx->rotation[0], mtx->rotation[1], mtx->rotation[2],
584dfc57732SGregor Boirie 			mtx->rotation[3], mtx->rotation[4], mtx->rotation[5],
585dfc57732SGregor Boirie 			mtx->rotation[6], mtx->rotation[7], mtx->rotation[8]);
586dfc57732SGregor Boirie }
587dfc57732SGregor Boirie EXPORT_SYMBOL_GPL(iio_show_mount_matrix);
588dfc57732SGregor Boirie 
589dfc57732SGregor Boirie /**
590fb158971SAndy Shevchenko  * iio_read_mount_matrix() - retrieve iio device mounting matrix from
591fb158971SAndy Shevchenko  *                           device "mount-matrix" property
592dfc57732SGregor Boirie  * @dev:	device the mounting matrix property is assigned to
593dfc57732SGregor Boirie  * @propname:	device specific mounting matrix property name
594dfc57732SGregor Boirie  * @matrix:	where to store retrieved matrix
595dfc57732SGregor Boirie  *
596dfc57732SGregor Boirie  * If device is assigned no mounting matrix property, a default 3x3 identity
597dfc57732SGregor Boirie  * matrix will be filled in.
598dfc57732SGregor Boirie  *
599dfc57732SGregor Boirie  * Return: 0 if success, or a negative error code on failure.
600dfc57732SGregor Boirie  */
601fb158971SAndy Shevchenko int iio_read_mount_matrix(struct device *dev, const char *propname,
602dfc57732SGregor Boirie 			  struct iio_mount_matrix *matrix)
603dfc57732SGregor Boirie {
604fb158971SAndy Shevchenko 	size_t len = ARRAY_SIZE(iio_mount_idmatrix.rotation);
605fb158971SAndy Shevchenko 	int err;
606dfc57732SGregor Boirie 
607fb158971SAndy Shevchenko 	err = device_property_read_string_array(dev, propname,
608fb158971SAndy Shevchenko 						matrix->rotation, len);
609fb158971SAndy Shevchenko 	if (err == len)
610dfc57732SGregor Boirie 		return 0;
611dfc57732SGregor Boirie 
612dfc57732SGregor Boirie 	if (err >= 0)
613dfc57732SGregor Boirie 		/* Invalid number of matrix entries. */
614dfc57732SGregor Boirie 		return -EINVAL;
615dfc57732SGregor Boirie 
616dfc57732SGregor Boirie 	if (err != -EINVAL)
617dfc57732SGregor Boirie 		/* Invalid matrix declaration format. */
618dfc57732SGregor Boirie 		return err;
619dfc57732SGregor Boirie 
620dfc57732SGregor Boirie 	/* Matrix was not declared at all: fallback to identity. */
621dfc57732SGregor Boirie 	return iio_setup_mount_idmatrix(dev, matrix);
622dfc57732SGregor Boirie }
623fb158971SAndy Shevchenko EXPORT_SYMBOL(iio_read_mount_matrix);
624dfc57732SGregor Boirie 
62551239600SJonathan Cameron static ssize_t __iio_format_value(char *buf, size_t len, unsigned int type,
62651239600SJonathan Cameron 				  int size, const int *vals)
62751239600SJonathan Cameron {
62851239600SJonathan Cameron 	unsigned long long tmp;
62951239600SJonathan Cameron 	int tmp0, tmp1;
6300e7a3978SAnand Ashok Dumbre 	s64 tmp2;
63151239600SJonathan Cameron 	bool scale_db = false;
63251239600SJonathan Cameron 
63351239600SJonathan Cameron 	switch (type) {
63451239600SJonathan Cameron 	case IIO_VAL_INT:
63535a4eeb0STakashi Iwai 		return scnprintf(buf, len, "%d", vals[0]);
63651239600SJonathan Cameron 	case IIO_VAL_INT_PLUS_MICRO_DB:
63751239600SJonathan Cameron 		scale_db = true;
638df561f66SGustavo A. R. Silva 		fallthrough;
63951239600SJonathan Cameron 	case IIO_VAL_INT_PLUS_MICRO:
64051239600SJonathan Cameron 		if (vals[1] < 0)
64135a4eeb0STakashi Iwai 			return scnprintf(buf, len, "-%d.%06u%s", abs(vals[0]),
64251239600SJonathan Cameron 					-vals[1], scale_db ? " dB" : "");
64351239600SJonathan Cameron 		else
64435a4eeb0STakashi Iwai 			return scnprintf(buf, len, "%d.%06u%s", vals[0], vals[1],
64551239600SJonathan Cameron 					scale_db ? " dB" : "");
64651239600SJonathan Cameron 	case IIO_VAL_INT_PLUS_NANO:
64751239600SJonathan Cameron 		if (vals[1] < 0)
64835a4eeb0STakashi Iwai 			return scnprintf(buf, len, "-%d.%09u", abs(vals[0]),
64951239600SJonathan Cameron 					-vals[1]);
65051239600SJonathan Cameron 		else
65135a4eeb0STakashi Iwai 			return scnprintf(buf, len, "%d.%09u", vals[0], vals[1]);
65251239600SJonathan Cameron 	case IIO_VAL_FRACTIONAL:
6530e7a3978SAnand Ashok Dumbre 		tmp2 = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
65451239600SJonathan Cameron 		tmp1 = vals[1];
6550e7a3978SAnand Ashok Dumbre 		tmp0 = (int)div_s64_rem(tmp2, 1000000000, &tmp1);
6560e7a3978SAnand Ashok Dumbre 		if ((tmp2 < 0) && (tmp0 == 0))
6570e7a3978SAnand Ashok Dumbre 			return snprintf(buf, len, "-0.%09u", abs(tmp1));
6580e7a3978SAnand Ashok Dumbre 		else
6590e7a3978SAnand Ashok Dumbre 			return snprintf(buf, len, "%d.%09u", tmp0, abs(tmp1));
66051239600SJonathan Cameron 	case IIO_VAL_FRACTIONAL_LOG2:
6617fd6592dSNikolaus Schulz 		tmp = shift_right((s64)vals[0] * 1000000000LL, vals[1]);
6627fd6592dSNikolaus Schulz 		tmp0 = (int)div_s64_rem(tmp, 1000000000LL, &tmp1);
66335a4eeb0STakashi Iwai 		return scnprintf(buf, len, "%d.%09u", tmp0, abs(tmp1));
66451239600SJonathan Cameron 	case IIO_VAL_INT_MULTIPLE:
66551239600SJonathan Cameron 	{
66651239600SJonathan Cameron 		int i;
66751239600SJonathan Cameron 		int l = 0;
66851239600SJonathan Cameron 
66951239600SJonathan Cameron 		for (i = 0; i < size; ++i) {
67035a4eeb0STakashi Iwai 			l += scnprintf(&buf[l], len - l, "%d ", vals[i]);
67151239600SJonathan Cameron 			if (l >= len)
67251239600SJonathan Cameron 				break;
67351239600SJonathan Cameron 		}
67451239600SJonathan Cameron 		return l;
67551239600SJonathan Cameron 	}
6768cb34036SAndrea Merello 	case IIO_VAL_CHAR:
67735a4eeb0STakashi Iwai 		return scnprintf(buf, len, "%c", (char)vals[0]);
67851239600SJonathan Cameron 	default:
67951239600SJonathan Cameron 		return 0;
68051239600SJonathan Cameron 	}
68151239600SJonathan Cameron }
68251239600SJonathan Cameron 
6833661f3f5SLars-Peter Clausen /**
6843661f3f5SLars-Peter Clausen  * iio_format_value() - Formats a IIO value into its string representation
6852498dcf6SCristina Opriceana  * @buf:	The buffer to which the formatted value gets written
68651239600SJonathan Cameron  *		which is assumed to be big enough (i.e. PAGE_SIZE).
687c175cb7cSRandy Dunlap  * @type:	One of the IIO_VAL_* constants. This decides how the val
6882498dcf6SCristina Opriceana  *		and val2 parameters are formatted.
6892498dcf6SCristina Opriceana  * @size:	Number of IIO value entries contained in vals
6902498dcf6SCristina Opriceana  * @vals:	Pointer to the values, exact meaning depends on the
6912498dcf6SCristina Opriceana  *		type parameter.
6922498dcf6SCristina Opriceana  *
6932498dcf6SCristina Opriceana  * Return: 0 by default, a negative number on failure or the
6942498dcf6SCristina Opriceana  *	   total number of characters written for a type that belongs
695c175cb7cSRandy Dunlap  *	   to the IIO_VAL_* constant.
6963661f3f5SLars-Peter Clausen  */
6979fbfb4b3SSrinivas Pandruvada ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
698a980e046SJonathan Cameron {
69951239600SJonathan Cameron 	ssize_t len;
700a980e046SJonathan Cameron 
70151239600SJonathan Cameron 	len = __iio_format_value(buf, PAGE_SIZE, type, size, vals);
70251239600SJonathan Cameron 	if (len >= PAGE_SIZE - 1)
70351239600SJonathan Cameron 		return -EFBIG;
7049fbfb4b3SSrinivas Pandruvada 
70551239600SJonathan Cameron 	return len + sprintf(buf + len, "\n");
70667eedba3SMichael Hennerich }
7077d2c2acaSAndrew F. Davis EXPORT_SYMBOL_GPL(iio_format_value);
708a980e046SJonathan Cameron 
7091d4ef9b3SCristian Pop static ssize_t iio_read_channel_label(struct device *dev,
7101d4ef9b3SCristian Pop 				      struct device_attribute *attr,
7111d4ef9b3SCristian Pop 				      char *buf)
7121d4ef9b3SCristian Pop {
7131d4ef9b3SCristian Pop 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
7141d4ef9b3SCristian Pop 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
7151d4ef9b3SCristian Pop 
7161d4ef9b3SCristian Pop 	if (!indio_dev->info->read_label)
7171d4ef9b3SCristian Pop 		return -EINVAL;
7181d4ef9b3SCristian Pop 
7191d4ef9b3SCristian Pop 	return indio_dev->info->read_label(indio_dev, this_attr->c, buf);
7201d4ef9b3SCristian Pop }
7211d4ef9b3SCristian Pop 
7223661f3f5SLars-Peter Clausen static ssize_t iio_read_channel_info(struct device *dev,
7233661f3f5SLars-Peter Clausen 				     struct device_attribute *attr,
7243661f3f5SLars-Peter Clausen 				     char *buf)
7253661f3f5SLars-Peter Clausen {
7263661f3f5SLars-Peter Clausen 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
7273661f3f5SLars-Peter Clausen 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
7289fbfb4b3SSrinivas Pandruvada 	int vals[INDIO_MAX_RAW_ELEMENTS];
7299fbfb4b3SSrinivas Pandruvada 	int ret;
7309fbfb4b3SSrinivas Pandruvada 	int val_len = 2;
7319fbfb4b3SSrinivas Pandruvada 
7329fbfb4b3SSrinivas Pandruvada 	if (indio_dev->info->read_raw_multi)
7339fbfb4b3SSrinivas Pandruvada 		ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
7349fbfb4b3SSrinivas Pandruvada 							INDIO_MAX_RAW_ELEMENTS,
7359fbfb4b3SSrinivas Pandruvada 							vals, &val_len,
7369fbfb4b3SSrinivas Pandruvada 							this_attr->address);
7379fbfb4b3SSrinivas Pandruvada 	else
7389fbfb4b3SSrinivas Pandruvada 		ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
7399fbfb4b3SSrinivas Pandruvada 				    &vals[0], &vals[1], this_attr->address);
7403661f3f5SLars-Peter Clausen 
7413661f3f5SLars-Peter Clausen 	if (ret < 0)
7423661f3f5SLars-Peter Clausen 		return ret;
7433661f3f5SLars-Peter Clausen 
7449fbfb4b3SSrinivas Pandruvada 	return iio_format_value(buf, ret, val_len, vals);
7453661f3f5SLars-Peter Clausen }
7463661f3f5SLars-Peter Clausen 
747eda20ba1SLars-Peter Clausen static ssize_t iio_format_list(char *buf, const int *vals, int type, int length,
748eda20ba1SLars-Peter Clausen 			       const char *prefix, const char *suffix)
74951239600SJonathan Cameron {
750eda20ba1SLars-Peter Clausen 	ssize_t len;
751e08b60d3SLars-Peter Clausen 	int stride;
75251239600SJonathan Cameron 	int i;
753eda20ba1SLars-Peter Clausen 
75451239600SJonathan Cameron 	switch (type) {
75551239600SJonathan Cameron 	case IIO_VAL_INT:
756e08b60d3SLars-Peter Clausen 		stride = 1;
75751239600SJonathan Cameron 		break;
75851239600SJonathan Cameron 	default:
759e08b60d3SLars-Peter Clausen 		stride = 2;
760e08b60d3SLars-Peter Clausen 		break;
761e08b60d3SLars-Peter Clausen 	}
762e08b60d3SLars-Peter Clausen 
763e08b60d3SLars-Peter Clausen 	len = scnprintf(buf, PAGE_SIZE, prefix);
764e08b60d3SLars-Peter Clausen 
765e08b60d3SLars-Peter Clausen 	for (i = 0; i <= length - stride; i += stride) {
766e08b60d3SLars-Peter Clausen 		if (i != 0) {
767e08b60d3SLars-Peter Clausen 			len += scnprintf(buf + len, PAGE_SIZE - len, " ");
76851239600SJonathan Cameron 			if (len >= PAGE_SIZE)
76951239600SJonathan Cameron 				return -EFBIG;
77051239600SJonathan Cameron 		}
771e08b60d3SLars-Peter Clausen 
772e08b60d3SLars-Peter Clausen 		len += __iio_format_value(buf + len, PAGE_SIZE - len, type,
773e08b60d3SLars-Peter Clausen 					  stride, &vals[i]);
774e08b60d3SLars-Peter Clausen 		if (len >= PAGE_SIZE)
775e08b60d3SLars-Peter Clausen 			return -EFBIG;
77651239600SJonathan Cameron 	}
77751239600SJonathan Cameron 
778e08b60d3SLars-Peter Clausen 	len += scnprintf(buf + len, PAGE_SIZE - len, "%s\n", suffix);
779e08b60d3SLars-Peter Clausen 
78051239600SJonathan Cameron 	return len;
78151239600SJonathan Cameron }
78251239600SJonathan Cameron 
783eda20ba1SLars-Peter Clausen static ssize_t iio_format_avail_list(char *buf, const int *vals,
784eda20ba1SLars-Peter Clausen 				     int type, int length)
785eda20ba1SLars-Peter Clausen {
786eda20ba1SLars-Peter Clausen 
787eda20ba1SLars-Peter Clausen 	return iio_format_list(buf, vals, type, length, "", "");
788eda20ba1SLars-Peter Clausen }
789eda20ba1SLars-Peter Clausen 
79051239600SJonathan Cameron static ssize_t iio_format_avail_range(char *buf, const int *vals, int type)
79151239600SJonathan Cameron {
792eda20ba1SLars-Peter Clausen 	return iio_format_list(buf, vals, type, 3, "[", "]");
79351239600SJonathan Cameron }
79451239600SJonathan Cameron 
79551239600SJonathan Cameron static ssize_t iio_read_channel_info_avail(struct device *dev,
79651239600SJonathan Cameron 					   struct device_attribute *attr,
79751239600SJonathan Cameron 					   char *buf)
79851239600SJonathan Cameron {
79951239600SJonathan Cameron 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
80051239600SJonathan Cameron 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
80151239600SJonathan Cameron 	const int *vals;
80251239600SJonathan Cameron 	int ret;
80351239600SJonathan Cameron 	int length;
80451239600SJonathan Cameron 	int type;
80551239600SJonathan Cameron 
80651239600SJonathan Cameron 	ret = indio_dev->info->read_avail(indio_dev, this_attr->c,
80751239600SJonathan Cameron 					  &vals, &type, &length,
80851239600SJonathan Cameron 					  this_attr->address);
80951239600SJonathan Cameron 
81051239600SJonathan Cameron 	if (ret < 0)
81151239600SJonathan Cameron 		return ret;
81251239600SJonathan Cameron 	switch (ret) {
81351239600SJonathan Cameron 	case IIO_AVAIL_LIST:
81451239600SJonathan Cameron 		return iio_format_avail_list(buf, vals, type, length);
81551239600SJonathan Cameron 	case IIO_AVAIL_RANGE:
81651239600SJonathan Cameron 		return iio_format_avail_range(buf, vals, type);
81751239600SJonathan Cameron 	default:
81851239600SJonathan Cameron 		return -EINVAL;
81951239600SJonathan Cameron 	}
82051239600SJonathan Cameron }
82151239600SJonathan Cameron 
8226807d721SLars-Peter Clausen /**
823b8528224SBeniamin Bia  * __iio_str_to_fixpoint() - Parse a fixed-point number from a string
8246807d721SLars-Peter Clausen  * @str: The string to parse
8256807d721SLars-Peter Clausen  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
8266807d721SLars-Peter Clausen  * @integer: The integer part of the number
8276807d721SLars-Peter Clausen  * @fract: The fractional part of the number
828b8528224SBeniamin Bia  * @scale_db: True if this should parse as dB
8296807d721SLars-Peter Clausen  *
8306807d721SLars-Peter Clausen  * Returns 0 on success, or a negative error code if the string could not be
8316807d721SLars-Peter Clausen  * parsed.
8326807d721SLars-Peter Clausen  */
833b8528224SBeniamin Bia static int __iio_str_to_fixpoint(const char *str, int fract_mult,
834b8528224SBeniamin Bia 				 int *integer, int *fract, bool scale_db)
8356807d721SLars-Peter Clausen {
8366807d721SLars-Peter Clausen 	int i = 0, f = 0;
8376807d721SLars-Peter Clausen 	bool integer_part = true, negative = false;
8386807d721SLars-Peter Clausen 
839f47dff32SSean Nyekjaer 	if (fract_mult == 0) {
840f47dff32SSean Nyekjaer 		*fract = 0;
841f47dff32SSean Nyekjaer 
842f47dff32SSean Nyekjaer 		return kstrtoint(str, 0, integer);
843f47dff32SSean Nyekjaer 	}
844f47dff32SSean Nyekjaer 
8456807d721SLars-Peter Clausen 	if (str[0] == '-') {
8466807d721SLars-Peter Clausen 		negative = true;
8476807d721SLars-Peter Clausen 		str++;
8486807d721SLars-Peter Clausen 	} else if (str[0] == '+') {
8496807d721SLars-Peter Clausen 		str++;
8506807d721SLars-Peter Clausen 	}
8516807d721SLars-Peter Clausen 
8526807d721SLars-Peter Clausen 	while (*str) {
8536807d721SLars-Peter Clausen 		if ('0' <= *str && *str <= '9') {
8546807d721SLars-Peter Clausen 			if (integer_part) {
8556807d721SLars-Peter Clausen 				i = i * 10 + *str - '0';
8566807d721SLars-Peter Clausen 			} else {
8576807d721SLars-Peter Clausen 				f += fract_mult * (*str - '0');
8586807d721SLars-Peter Clausen 				fract_mult /= 10;
8596807d721SLars-Peter Clausen 			}
8606807d721SLars-Peter Clausen 		} else if (*str == '\n') {
8616807d721SLars-Peter Clausen 			if (*(str + 1) == '\0')
8626807d721SLars-Peter Clausen 				break;
8636807d721SLars-Peter Clausen 			else
8646807d721SLars-Peter Clausen 				return -EINVAL;
865b8528224SBeniamin Bia 		} else if (!strncmp(str, " dB", sizeof(" dB") - 1) && scale_db) {
866b8528224SBeniamin Bia 			/* Ignore the dB suffix */
867b8528224SBeniamin Bia 			str += sizeof(" dB") - 1;
868b8528224SBeniamin Bia 			continue;
869b8528224SBeniamin Bia 		} else if (!strncmp(str, "dB", sizeof("dB") - 1) && scale_db) {
870b8528224SBeniamin Bia 			/* Ignore the dB suffix */
871b8528224SBeniamin Bia 			str += sizeof("dB") - 1;
872b8528224SBeniamin Bia 			continue;
8736807d721SLars-Peter Clausen 		} else if (*str == '.' && integer_part) {
8746807d721SLars-Peter Clausen 			integer_part = false;
8756807d721SLars-Peter Clausen 		} else {
8766807d721SLars-Peter Clausen 			return -EINVAL;
8776807d721SLars-Peter Clausen 		}
8786807d721SLars-Peter Clausen 		str++;
8796807d721SLars-Peter Clausen 	}
8806807d721SLars-Peter Clausen 
8816807d721SLars-Peter Clausen 	if (negative) {
8826807d721SLars-Peter Clausen 		if (i)
8836807d721SLars-Peter Clausen 			i = -i;
8846807d721SLars-Peter Clausen 		else
8856807d721SLars-Peter Clausen 			f = -f;
8866807d721SLars-Peter Clausen 	}
8876807d721SLars-Peter Clausen 
8886807d721SLars-Peter Clausen 	*integer = i;
8896807d721SLars-Peter Clausen 	*fract = f;
8906807d721SLars-Peter Clausen 
8916807d721SLars-Peter Clausen 	return 0;
8926807d721SLars-Peter Clausen }
893b8528224SBeniamin Bia 
894b8528224SBeniamin Bia /**
895b8528224SBeniamin Bia  * iio_str_to_fixpoint() - Parse a fixed-point number from a string
896b8528224SBeniamin Bia  * @str: The string to parse
897b8528224SBeniamin Bia  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
898b8528224SBeniamin Bia  * @integer: The integer part of the number
899b8528224SBeniamin Bia  * @fract: The fractional part of the number
900b8528224SBeniamin Bia  *
901b8528224SBeniamin Bia  * Returns 0 on success, or a negative error code if the string could not be
902b8528224SBeniamin Bia  * parsed.
903b8528224SBeniamin Bia  */
904b8528224SBeniamin Bia int iio_str_to_fixpoint(const char *str, int fract_mult,
905b8528224SBeniamin Bia 			int *integer, int *fract)
906b8528224SBeniamin Bia {
907b8528224SBeniamin Bia 	return __iio_str_to_fixpoint(str, fract_mult, integer, fract, false);
908b8528224SBeniamin Bia }
9096807d721SLars-Peter Clausen EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
9106807d721SLars-Peter Clausen 
911a980e046SJonathan Cameron static ssize_t iio_write_channel_info(struct device *dev,
912a980e046SJonathan Cameron 				      struct device_attribute *attr,
913a980e046SJonathan Cameron 				      const char *buf,
914a980e046SJonathan Cameron 				      size_t len)
915a980e046SJonathan Cameron {
916e53f5ac5SLars-Peter Clausen 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
917a980e046SJonathan Cameron 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
9186807d721SLars-Peter Clausen 	int ret, fract_mult = 100000;
9198cb34036SAndrea Merello 	int integer, fract = 0;
9208cb34036SAndrea Merello 	bool is_char = false;
921b8528224SBeniamin Bia 	bool scale_db = false;
922a980e046SJonathan Cameron 
923a980e046SJonathan Cameron 	/* Assumes decimal - precision based on number of digits */
924a980e046SJonathan Cameron 	if (!indio_dev->info->write_raw)
925a980e046SJonathan Cameron 		return -EINVAL;
926a980e046SJonathan Cameron 
927a980e046SJonathan Cameron 	if (indio_dev->info->write_raw_get_fmt)
928a980e046SJonathan Cameron 		switch (indio_dev->info->write_raw_get_fmt(indio_dev,
929a980e046SJonathan Cameron 			this_attr->c, this_attr->address)) {
930f47dff32SSean Nyekjaer 		case IIO_VAL_INT:
931f47dff32SSean Nyekjaer 			fract_mult = 0;
932f47dff32SSean Nyekjaer 			break;
933b8528224SBeniamin Bia 		case IIO_VAL_INT_PLUS_MICRO_DB:
934b8528224SBeniamin Bia 			scale_db = true;
935df561f66SGustavo A. R. Silva 			fallthrough;
936a980e046SJonathan Cameron 		case IIO_VAL_INT_PLUS_MICRO:
937a980e046SJonathan Cameron 			fract_mult = 100000;
938a980e046SJonathan Cameron 			break;
939a980e046SJonathan Cameron 		case IIO_VAL_INT_PLUS_NANO:
940a980e046SJonathan Cameron 			fract_mult = 100000000;
941a980e046SJonathan Cameron 			break;
9428cb34036SAndrea Merello 		case IIO_VAL_CHAR:
9438cb34036SAndrea Merello 			is_char = true;
9448cb34036SAndrea Merello 			break;
945a980e046SJonathan Cameron 		default:
946a980e046SJonathan Cameron 			return -EINVAL;
947a980e046SJonathan Cameron 		}
948a980e046SJonathan Cameron 
9498cb34036SAndrea Merello 	if (is_char) {
9508cb34036SAndrea Merello 		char ch;
9518cb34036SAndrea Merello 
9528cb34036SAndrea Merello 		if (sscanf(buf, "%c", &ch) != 1)
9538cb34036SAndrea Merello 			return -EINVAL;
9548cb34036SAndrea Merello 		integer = ch;
9558cb34036SAndrea Merello 	} else {
956b8528224SBeniamin Bia 		ret = __iio_str_to_fixpoint(buf, fract_mult, &integer, &fract,
957b8528224SBeniamin Bia 					    scale_db);
958b8528224SBeniamin Bia 		if (ret)
959b8528224SBeniamin Bia 			return ret;
9605403f280SMircea Caprioru 	}
961a980e046SJonathan Cameron 
962a980e046SJonathan Cameron 	ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
963a980e046SJonathan Cameron 					 integer, fract, this_attr->address);
964a980e046SJonathan Cameron 	if (ret)
965a980e046SJonathan Cameron 		return ret;
966a980e046SJonathan Cameron 
967a980e046SJonathan Cameron 	return len;
968a980e046SJonathan Cameron }
969a980e046SJonathan Cameron 
970a980e046SJonathan Cameron static
971a980e046SJonathan Cameron int __iio_device_attr_init(struct device_attribute *dev_attr,
972a980e046SJonathan Cameron 			   const char *postfix,
973a980e046SJonathan Cameron 			   struct iio_chan_spec const *chan,
974a980e046SJonathan Cameron 			   ssize_t (*readfunc)(struct device *dev,
975a980e046SJonathan Cameron 					       struct device_attribute *attr,
976a980e046SJonathan Cameron 					       char *buf),
977a980e046SJonathan Cameron 			   ssize_t (*writefunc)(struct device *dev,
978a980e046SJonathan Cameron 						struct device_attribute *attr,
979a980e046SJonathan Cameron 						const char *buf,
980a980e046SJonathan Cameron 						size_t len),
9813704432fSJonathan Cameron 			   enum iio_shared_by shared_by)
982a980e046SJonathan Cameron {
9833704432fSJonathan Cameron 	int ret = 0;
9847bbcf7e1SLars-Peter Clausen 	char *name = NULL;
9853704432fSJonathan Cameron 	char *full_postfix;
986a980e046SJonathan Cameron 	sysfs_attr_init(&dev_attr->attr);
987a980e046SJonathan Cameron 
988a980e046SJonathan Cameron 	/* Build up postfix of <extend_name>_<modifier>_postfix */
9893704432fSJonathan Cameron 	if (chan->modified && (shared_by == IIO_SEPARATE)) {
990a980e046SJonathan Cameron 		if (chan->extend_name)
991a980e046SJonathan Cameron 			full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
992a980e046SJonathan Cameron 						 iio_modifier_names[chan
993a980e046SJonathan Cameron 								    ->channel2],
994a980e046SJonathan Cameron 						 chan->extend_name,
995a980e046SJonathan Cameron 						 postfix);
996a980e046SJonathan Cameron 		else
997a980e046SJonathan Cameron 			full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
998a980e046SJonathan Cameron 						 iio_modifier_names[chan
999a980e046SJonathan Cameron 								    ->channel2],
1000a980e046SJonathan Cameron 						 postfix);
1001a980e046SJonathan Cameron 	} else {
100277bfa8baSLars-Peter Clausen 		if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
1003a980e046SJonathan Cameron 			full_postfix = kstrdup(postfix, GFP_KERNEL);
1004a980e046SJonathan Cameron 		else
1005a980e046SJonathan Cameron 			full_postfix = kasprintf(GFP_KERNEL,
1006a980e046SJonathan Cameron 						 "%s_%s",
1007a980e046SJonathan Cameron 						 chan->extend_name,
1008a980e046SJonathan Cameron 						 postfix);
1009a980e046SJonathan Cameron 	}
10103704432fSJonathan Cameron 	if (full_postfix == NULL)
10113704432fSJonathan Cameron 		return -ENOMEM;
1012a980e046SJonathan Cameron 
1013a980e046SJonathan Cameron 	if (chan->differential) { /* Differential can not have modifier */
10143704432fSJonathan Cameron 		switch (shared_by) {
1015c006ec83SJonathan Cameron 		case IIO_SHARED_BY_ALL:
10167bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1017c006ec83SJonathan Cameron 			break;
1018c006ec83SJonathan Cameron 		case IIO_SHARED_BY_DIR:
10197bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL, "%s_%s",
1020c006ec83SJonathan Cameron 						iio_direction[chan->output],
1021c006ec83SJonathan Cameron 						full_postfix);
1022c006ec83SJonathan Cameron 			break;
10233704432fSJonathan Cameron 		case IIO_SHARED_BY_TYPE:
10247bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
1025a980e046SJonathan Cameron 					    iio_direction[chan->output],
1026a980e046SJonathan Cameron 					    iio_chan_type_name_spec[chan->type],
1027a980e046SJonathan Cameron 					    iio_chan_type_name_spec[chan->type],
1028a980e046SJonathan Cameron 					    full_postfix);
10293704432fSJonathan Cameron 			break;
10303704432fSJonathan Cameron 		case IIO_SEPARATE:
10313704432fSJonathan Cameron 			if (!chan->indexed) {
1032231bfe53SDan Carpenter 				WARN(1, "Differential channels must be indexed\n");
10333704432fSJonathan Cameron 				ret = -EINVAL;
10343704432fSJonathan Cameron 				goto error_free_full_postfix;
10353704432fSJonathan Cameron 			}
10367bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL,
10373704432fSJonathan Cameron 					    "%s_%s%d-%s%d_%s",
1038a980e046SJonathan Cameron 					    iio_direction[chan->output],
1039a980e046SJonathan Cameron 					    iio_chan_type_name_spec[chan->type],
1040a980e046SJonathan Cameron 					    chan->channel,
1041a980e046SJonathan Cameron 					    iio_chan_type_name_spec[chan->type],
1042a980e046SJonathan Cameron 					    chan->channel2,
1043a980e046SJonathan Cameron 					    full_postfix);
10443704432fSJonathan Cameron 			break;
1045a980e046SJonathan Cameron 		}
1046a980e046SJonathan Cameron 	} else { /* Single ended */
10473704432fSJonathan Cameron 		switch (shared_by) {
1048c006ec83SJonathan Cameron 		case IIO_SHARED_BY_ALL:
10497bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1050c006ec83SJonathan Cameron 			break;
1051c006ec83SJonathan Cameron 		case IIO_SHARED_BY_DIR:
10527bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL, "%s_%s",
1053c006ec83SJonathan Cameron 						iio_direction[chan->output],
1054c006ec83SJonathan Cameron 						full_postfix);
1055c006ec83SJonathan Cameron 			break;
10563704432fSJonathan Cameron 		case IIO_SHARED_BY_TYPE:
10577bbcf7e1SLars-Peter Clausen 			name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1058a980e046SJonathan Cameron 					    iio_direction[chan->output],
1059a980e046SJonathan Cameron 					    iio_chan_type_name_spec[chan->type],
1060a980e046SJonathan Cameron 					    full_postfix);
10613704432fSJonathan Cameron 			break;
10623704432fSJonathan Cameron 
10633704432fSJonathan Cameron 		case IIO_SEPARATE:
10643704432fSJonathan Cameron 			if (chan->indexed)
10657bbcf7e1SLars-Peter Clausen 				name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
1066a980e046SJonathan Cameron 						    iio_direction[chan->output],
1067a980e046SJonathan Cameron 						    iio_chan_type_name_spec[chan->type],
1068a980e046SJonathan Cameron 						    chan->channel,
1069a980e046SJonathan Cameron 						    full_postfix);
1070a980e046SJonathan Cameron 			else
10717bbcf7e1SLars-Peter Clausen 				name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1072a980e046SJonathan Cameron 						    iio_direction[chan->output],
1073a980e046SJonathan Cameron 						    iio_chan_type_name_spec[chan->type],
1074a980e046SJonathan Cameron 						    full_postfix);
10753704432fSJonathan Cameron 			break;
10763704432fSJonathan Cameron 		}
1077a980e046SJonathan Cameron 	}
10787bbcf7e1SLars-Peter Clausen 	if (name == NULL) {
1079a980e046SJonathan Cameron 		ret = -ENOMEM;
1080a980e046SJonathan Cameron 		goto error_free_full_postfix;
1081a980e046SJonathan Cameron 	}
10827bbcf7e1SLars-Peter Clausen 	dev_attr->attr.name = name;
1083a980e046SJonathan Cameron 
1084a980e046SJonathan Cameron 	if (readfunc) {
1085a980e046SJonathan Cameron 		dev_attr->attr.mode |= S_IRUGO;
1086a980e046SJonathan Cameron 		dev_attr->show = readfunc;
1087a980e046SJonathan Cameron 	}
1088a980e046SJonathan Cameron 
1089a980e046SJonathan Cameron 	if (writefunc) {
1090a980e046SJonathan Cameron 		dev_attr->attr.mode |= S_IWUSR;
1091a980e046SJonathan Cameron 		dev_attr->store = writefunc;
1092a980e046SJonathan Cameron 	}
10937bbcf7e1SLars-Peter Clausen 
1094a980e046SJonathan Cameron error_free_full_postfix:
1095a980e046SJonathan Cameron 	kfree(full_postfix);
10963704432fSJonathan Cameron 
1097a980e046SJonathan Cameron 	return ret;
1098a980e046SJonathan Cameron }
1099a980e046SJonathan Cameron 
1100a980e046SJonathan Cameron static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
1101a980e046SJonathan Cameron {
1102a980e046SJonathan Cameron 	kfree(dev_attr->attr.name);
1103a980e046SJonathan Cameron }
1104a980e046SJonathan Cameron 
1105a980e046SJonathan Cameron int __iio_add_chan_devattr(const char *postfix,
1106a980e046SJonathan Cameron 			   struct iio_chan_spec const *chan,
1107a980e046SJonathan Cameron 			   ssize_t (*readfunc)(struct device *dev,
1108a980e046SJonathan Cameron 					       struct device_attribute *attr,
1109a980e046SJonathan Cameron 					       char *buf),
1110a980e046SJonathan Cameron 			   ssize_t (*writefunc)(struct device *dev,
1111a980e046SJonathan Cameron 						struct device_attribute *attr,
1112a980e046SJonathan Cameron 						const char *buf,
1113a980e046SJonathan Cameron 						size_t len),
1114a980e046SJonathan Cameron 			   u64 mask,
11153704432fSJonathan Cameron 			   enum iio_shared_by shared_by,
1116a980e046SJonathan Cameron 			   struct device *dev,
1117a980e046SJonathan Cameron 			   struct list_head *attr_list)
1118a980e046SJonathan Cameron {
1119a980e046SJonathan Cameron 	int ret;
1120a980e046SJonathan Cameron 	struct iio_dev_attr *iio_attr, *t;
1121a980e046SJonathan Cameron 
1122670c1103SSachin Kamat 	iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
112392825ff9SHartmut Knaack 	if (iio_attr == NULL)
112492825ff9SHartmut Knaack 		return -ENOMEM;
1125a980e046SJonathan Cameron 	ret = __iio_device_attr_init(&iio_attr->dev_attr,
1126a980e046SJonathan Cameron 				     postfix, chan,
11273704432fSJonathan Cameron 				     readfunc, writefunc, shared_by);
1128a980e046SJonathan Cameron 	if (ret)
1129a980e046SJonathan Cameron 		goto error_iio_dev_attr_free;
1130a980e046SJonathan Cameron 	iio_attr->c = chan;
1131a980e046SJonathan Cameron 	iio_attr->address = mask;
1132a980e046SJonathan Cameron 	list_for_each_entry(t, attr_list, l)
1133a980e046SJonathan Cameron 		if (strcmp(t->dev_attr.attr.name,
1134a980e046SJonathan Cameron 			   iio_attr->dev_attr.attr.name) == 0) {
11353704432fSJonathan Cameron 			if (shared_by == IIO_SEPARATE)
1136a980e046SJonathan Cameron 				dev_err(dev, "tried to double register : %s\n",
1137a980e046SJonathan Cameron 					t->dev_attr.attr.name);
1138a980e046SJonathan Cameron 			ret = -EBUSY;
1139a980e046SJonathan Cameron 			goto error_device_attr_deinit;
1140a980e046SJonathan Cameron 		}
1141a980e046SJonathan Cameron 	list_add(&iio_attr->l, attr_list);
1142a980e046SJonathan Cameron 
1143a980e046SJonathan Cameron 	return 0;
1144a980e046SJonathan Cameron 
1145a980e046SJonathan Cameron error_device_attr_deinit:
1146a980e046SJonathan Cameron 	__iio_device_attr_deinit(&iio_attr->dev_attr);
1147a980e046SJonathan Cameron error_iio_dev_attr_free:
1148a980e046SJonathan Cameron 	kfree(iio_attr);
1149a980e046SJonathan Cameron 	return ret;
1150a980e046SJonathan Cameron }
1151a980e046SJonathan Cameron 
11521d4ef9b3SCristian Pop static int iio_device_add_channel_label(struct iio_dev *indio_dev,
11531d4ef9b3SCristian Pop 					 struct iio_chan_spec const *chan)
11541d4ef9b3SCristian Pop {
11551d4ef9b3SCristian Pop 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
11561d4ef9b3SCristian Pop 	int ret;
11571d4ef9b3SCristian Pop 
11581d4ef9b3SCristian Pop 	if (!indio_dev->info->read_label)
11591d4ef9b3SCristian Pop 		return 0;
11601d4ef9b3SCristian Pop 
11611d4ef9b3SCristian Pop 	ret = __iio_add_chan_devattr("label",
11621d4ef9b3SCristian Pop 				     chan,
11631d4ef9b3SCristian Pop 				     &iio_read_channel_label,
11641d4ef9b3SCristian Pop 				     NULL,
11651d4ef9b3SCristian Pop 				     0,
11661d4ef9b3SCristian Pop 				     IIO_SEPARATE,
11671d4ef9b3SCristian Pop 				     &indio_dev->dev,
11681d4ef9b3SCristian Pop 				     &iio_dev_opaque->channel_attr_list);
11691d4ef9b3SCristian Pop 	if (ret < 0)
11701d4ef9b3SCristian Pop 		return ret;
11711d4ef9b3SCristian Pop 
11721d4ef9b3SCristian Pop 	return 1;
11731d4ef9b3SCristian Pop }
11741d4ef9b3SCristian Pop 
11753704432fSJonathan Cameron static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
11763704432fSJonathan Cameron 					 struct iio_chan_spec const *chan,
11773704432fSJonathan Cameron 					 enum iio_shared_by shared_by,
11783704432fSJonathan Cameron 					 const long *infomask)
11793704432fSJonathan Cameron {
1180207c2d27SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
11813704432fSJonathan Cameron 	int i, ret, attrcount = 0;
11823704432fSJonathan Cameron 
11831016d567SOrson Zhai 	for_each_set_bit(i, infomask, sizeof(*infomask)*8) {
1184ef4b4856SJonathan Cameron 		if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1185ef4b4856SJonathan Cameron 			return -EINVAL;
11863704432fSJonathan Cameron 		ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
11873704432fSJonathan Cameron 					     chan,
11883704432fSJonathan Cameron 					     &iio_read_channel_info,
11893704432fSJonathan Cameron 					     &iio_write_channel_info,
11903704432fSJonathan Cameron 					     i,
11913704432fSJonathan Cameron 					     shared_by,
11923704432fSJonathan Cameron 					     &indio_dev->dev,
1193207c2d27SAlexandru Ardelean 					     &iio_dev_opaque->channel_attr_list);
11943704432fSJonathan Cameron 		if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
11953704432fSJonathan Cameron 			continue;
11963704432fSJonathan Cameron 		else if (ret < 0)
11973704432fSJonathan Cameron 			return ret;
11983704432fSJonathan Cameron 		attrcount++;
11993704432fSJonathan Cameron 	}
12003704432fSJonathan Cameron 
12013704432fSJonathan Cameron 	return attrcount;
12023704432fSJonathan Cameron }
12033704432fSJonathan Cameron 
120451239600SJonathan Cameron static int iio_device_add_info_mask_type_avail(struct iio_dev *indio_dev,
120551239600SJonathan Cameron 					       struct iio_chan_spec const *chan,
120651239600SJonathan Cameron 					       enum iio_shared_by shared_by,
120751239600SJonathan Cameron 					       const long *infomask)
120851239600SJonathan Cameron {
1209207c2d27SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
121051239600SJonathan Cameron 	int i, ret, attrcount = 0;
121151239600SJonathan Cameron 	char *avail_postfix;
121251239600SJonathan Cameron 
12131016d567SOrson Zhai 	for_each_set_bit(i, infomask, sizeof(*infomask) * 8) {
1214936d3e53SYoung Xiao 		if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1215936d3e53SYoung Xiao 			return -EINVAL;
121651239600SJonathan Cameron 		avail_postfix = kasprintf(GFP_KERNEL,
121751239600SJonathan Cameron 					  "%s_available",
121851239600SJonathan Cameron 					  iio_chan_info_postfix[i]);
121951239600SJonathan Cameron 		if (!avail_postfix)
122051239600SJonathan Cameron 			return -ENOMEM;
122151239600SJonathan Cameron 
122251239600SJonathan Cameron 		ret = __iio_add_chan_devattr(avail_postfix,
122351239600SJonathan Cameron 					     chan,
122451239600SJonathan Cameron 					     &iio_read_channel_info_avail,
122551239600SJonathan Cameron 					     NULL,
122651239600SJonathan Cameron 					     i,
122751239600SJonathan Cameron 					     shared_by,
122851239600SJonathan Cameron 					     &indio_dev->dev,
1229207c2d27SAlexandru Ardelean 					     &iio_dev_opaque->channel_attr_list);
123051239600SJonathan Cameron 		kfree(avail_postfix);
123151239600SJonathan Cameron 		if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
123251239600SJonathan Cameron 			continue;
123351239600SJonathan Cameron 		else if (ret < 0)
123451239600SJonathan Cameron 			return ret;
123551239600SJonathan Cameron 		attrcount++;
123651239600SJonathan Cameron 	}
123751239600SJonathan Cameron 
123851239600SJonathan Cameron 	return attrcount;
123951239600SJonathan Cameron }
124051239600SJonathan Cameron 
1241a980e046SJonathan Cameron static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
1242a980e046SJonathan Cameron 					struct iio_chan_spec const *chan)
1243a980e046SJonathan Cameron {
1244207c2d27SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1245a980e046SJonathan Cameron 	int ret, attrcount = 0;
1246a980e046SJonathan Cameron 	const struct iio_chan_spec_ext_info *ext_info;
1247a980e046SJonathan Cameron 
1248a980e046SJonathan Cameron 	if (chan->channel < 0)
1249a980e046SJonathan Cameron 		return 0;
12503704432fSJonathan Cameron 	ret = iio_device_add_info_mask_type(indio_dev, chan,
12513704432fSJonathan Cameron 					    IIO_SEPARATE,
12523704432fSJonathan Cameron 					    &chan->info_mask_separate);
12538655cc49SJonathan Cameron 	if (ret < 0)
12543704432fSJonathan Cameron 		return ret;
12553704432fSJonathan Cameron 	attrcount += ret;
12563704432fSJonathan Cameron 
125751239600SJonathan Cameron 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
125851239600SJonathan Cameron 						  IIO_SEPARATE,
125951239600SJonathan Cameron 						  &chan->
126051239600SJonathan Cameron 						  info_mask_separate_available);
126151239600SJonathan Cameron 	if (ret < 0)
126251239600SJonathan Cameron 		return ret;
126351239600SJonathan Cameron 	attrcount += ret;
126451239600SJonathan Cameron 
12653704432fSJonathan Cameron 	ret = iio_device_add_info_mask_type(indio_dev, chan,
12663704432fSJonathan Cameron 					    IIO_SHARED_BY_TYPE,
12673704432fSJonathan Cameron 					    &chan->info_mask_shared_by_type);
12683704432fSJonathan Cameron 	if (ret < 0)
12693704432fSJonathan Cameron 		return ret;
12703704432fSJonathan Cameron 	attrcount += ret;
1271a980e046SJonathan Cameron 
127251239600SJonathan Cameron 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
127351239600SJonathan Cameron 						  IIO_SHARED_BY_TYPE,
127451239600SJonathan Cameron 						  &chan->
127551239600SJonathan Cameron 						  info_mask_shared_by_type_available);
127651239600SJonathan Cameron 	if (ret < 0)
127751239600SJonathan Cameron 		return ret;
127851239600SJonathan Cameron 	attrcount += ret;
127951239600SJonathan Cameron 
1280c006ec83SJonathan Cameron 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1281c006ec83SJonathan Cameron 					    IIO_SHARED_BY_DIR,
1282c006ec83SJonathan Cameron 					    &chan->info_mask_shared_by_dir);
1283c006ec83SJonathan Cameron 	if (ret < 0)
1284c006ec83SJonathan Cameron 		return ret;
1285c006ec83SJonathan Cameron 	attrcount += ret;
1286c006ec83SJonathan Cameron 
128751239600SJonathan Cameron 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
128851239600SJonathan Cameron 						  IIO_SHARED_BY_DIR,
128951239600SJonathan Cameron 						  &chan->info_mask_shared_by_dir_available);
129051239600SJonathan Cameron 	if (ret < 0)
129151239600SJonathan Cameron 		return ret;
129251239600SJonathan Cameron 	attrcount += ret;
129351239600SJonathan Cameron 
1294c006ec83SJonathan Cameron 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1295c006ec83SJonathan Cameron 					    IIO_SHARED_BY_ALL,
1296c006ec83SJonathan Cameron 					    &chan->info_mask_shared_by_all);
1297c006ec83SJonathan Cameron 	if (ret < 0)
1298c006ec83SJonathan Cameron 		return ret;
1299c006ec83SJonathan Cameron 	attrcount += ret;
1300c006ec83SJonathan Cameron 
130151239600SJonathan Cameron 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
130251239600SJonathan Cameron 						  IIO_SHARED_BY_ALL,
130351239600SJonathan Cameron 						  &chan->info_mask_shared_by_all_available);
130451239600SJonathan Cameron 	if (ret < 0)
130551239600SJonathan Cameron 		return ret;
130651239600SJonathan Cameron 	attrcount += ret;
130751239600SJonathan Cameron 
13081d4ef9b3SCristian Pop 	ret = iio_device_add_channel_label(indio_dev, chan);
13091d4ef9b3SCristian Pop 	if (ret < 0)
13101d4ef9b3SCristian Pop 		return ret;
13111d4ef9b3SCristian Pop 	attrcount += ret;
13121d4ef9b3SCristian Pop 
1313a980e046SJonathan Cameron 	if (chan->ext_info) {
1314a980e046SJonathan Cameron 		unsigned int i = 0;
1315a980e046SJonathan Cameron 		for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
1316a980e046SJonathan Cameron 			ret = __iio_add_chan_devattr(ext_info->name,
1317a980e046SJonathan Cameron 					chan,
1318a980e046SJonathan Cameron 					ext_info->read ?
1319a980e046SJonathan Cameron 					    &iio_read_channel_ext_info : NULL,
1320a980e046SJonathan Cameron 					ext_info->write ?
1321a980e046SJonathan Cameron 					    &iio_write_channel_ext_info : NULL,
1322a980e046SJonathan Cameron 					i,
1323a980e046SJonathan Cameron 					ext_info->shared,
1324a980e046SJonathan Cameron 					&indio_dev->dev,
1325207c2d27SAlexandru Ardelean 					&iio_dev_opaque->channel_attr_list);
1326a980e046SJonathan Cameron 			i++;
1327a980e046SJonathan Cameron 			if (ret == -EBUSY && ext_info->shared)
1328a980e046SJonathan Cameron 				continue;
1329a980e046SJonathan Cameron 
1330a980e046SJonathan Cameron 			if (ret)
13313704432fSJonathan Cameron 				return ret;
1332a980e046SJonathan Cameron 
1333a980e046SJonathan Cameron 			attrcount++;
1334a980e046SJonathan Cameron 		}
1335a980e046SJonathan Cameron 	}
1336a980e046SJonathan Cameron 
13373704432fSJonathan Cameron 	return attrcount;
1338a980e046SJonathan Cameron }
1339a980e046SJonathan Cameron 
134084088ebdSLars-Peter Clausen /**
134184088ebdSLars-Peter Clausen  * iio_free_chan_devattr_list() - Free a list of IIO device attributes
134284088ebdSLars-Peter Clausen  * @attr_list: List of IIO device attributes
134384088ebdSLars-Peter Clausen  *
134484088ebdSLars-Peter Clausen  * This function frees the memory allocated for each of the IIO device
1345c1b03ab5SMartin Fuzzey  * attributes in the list.
134684088ebdSLars-Peter Clausen  */
134784088ebdSLars-Peter Clausen void iio_free_chan_devattr_list(struct list_head *attr_list)
1348a980e046SJonathan Cameron {
134984088ebdSLars-Peter Clausen 	struct iio_dev_attr *p, *n;
135084088ebdSLars-Peter Clausen 
135184088ebdSLars-Peter Clausen 	list_for_each_entry_safe(p, n, attr_list, l) {
1352a980e046SJonathan Cameron 		kfree(p->dev_attr.attr.name);
1353c1b03ab5SMartin Fuzzey 		list_del(&p->l);
1354a980e046SJonathan Cameron 		kfree(p);
1355a980e046SJonathan Cameron 	}
135684088ebdSLars-Peter Clausen }
1357a980e046SJonathan Cameron 
1358a980e046SJonathan Cameron static ssize_t iio_show_dev_name(struct device *dev,
1359a980e046SJonathan Cameron 				 struct device_attribute *attr,
1360a980e046SJonathan Cameron 				 char *buf)
1361a980e046SJonathan Cameron {
1362e53f5ac5SLars-Peter Clausen 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1363598db581SKees Cook 	return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->name);
1364a980e046SJonathan Cameron }
1365a980e046SJonathan Cameron 
1366a980e046SJonathan Cameron static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
1367a980e046SJonathan Cameron 
13682c3d0c9fSPhil Reid static ssize_t iio_show_dev_label(struct device *dev,
13692c3d0c9fSPhil Reid 				 struct device_attribute *attr,
13702c3d0c9fSPhil Reid 				 char *buf)
13712c3d0c9fSPhil Reid {
13722c3d0c9fSPhil Reid 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
13732c3d0c9fSPhil Reid 	return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->label);
13742c3d0c9fSPhil Reid }
13752c3d0c9fSPhil Reid 
13762c3d0c9fSPhil Reid static DEVICE_ATTR(label, S_IRUGO, iio_show_dev_label, NULL);
13772c3d0c9fSPhil Reid 
1378bc2b7dabSGregor Boirie static ssize_t iio_show_timestamp_clock(struct device *dev,
1379bc2b7dabSGregor Boirie 					struct device_attribute *attr,
1380bc2b7dabSGregor Boirie 					char *buf)
1381bc2b7dabSGregor Boirie {
1382bc2b7dabSGregor Boirie 	const struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1383bc2b7dabSGregor Boirie 	const clockid_t clk = iio_device_get_clock(indio_dev);
1384bc2b7dabSGregor Boirie 	const char *name;
1385bc2b7dabSGregor Boirie 	ssize_t sz;
1386bc2b7dabSGregor Boirie 
1387bc2b7dabSGregor Boirie 	switch (clk) {
1388bc2b7dabSGregor Boirie 	case CLOCK_REALTIME:
1389bc2b7dabSGregor Boirie 		name = "realtime\n";
1390bc2b7dabSGregor Boirie 		sz = sizeof("realtime\n");
1391bc2b7dabSGregor Boirie 		break;
1392bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC:
1393bc2b7dabSGregor Boirie 		name = "monotonic\n";
1394bc2b7dabSGregor Boirie 		sz = sizeof("monotonic\n");
1395bc2b7dabSGregor Boirie 		break;
1396bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC_RAW:
1397bc2b7dabSGregor Boirie 		name = "monotonic_raw\n";
1398bc2b7dabSGregor Boirie 		sz = sizeof("monotonic_raw\n");
1399bc2b7dabSGregor Boirie 		break;
1400bc2b7dabSGregor Boirie 	case CLOCK_REALTIME_COARSE:
1401bc2b7dabSGregor Boirie 		name = "realtime_coarse\n";
1402bc2b7dabSGregor Boirie 		sz = sizeof("realtime_coarse\n");
1403bc2b7dabSGregor Boirie 		break;
1404bc2b7dabSGregor Boirie 	case CLOCK_MONOTONIC_COARSE:
1405bc2b7dabSGregor Boirie 		name = "monotonic_coarse\n";
1406bc2b7dabSGregor Boirie 		sz = sizeof("monotonic_coarse\n");
1407bc2b7dabSGregor Boirie 		break;
1408bc2b7dabSGregor Boirie 	case CLOCK_BOOTTIME:
1409bc2b7dabSGregor Boirie 		name = "boottime\n";
1410bc2b7dabSGregor Boirie 		sz = sizeof("boottime\n");
1411bc2b7dabSGregor Boirie 		break;
1412bc2b7dabSGregor Boirie 	case CLOCK_TAI:
1413bc2b7dabSGregor Boirie 		name = "tai\n";
1414bc2b7dabSGregor Boirie 		sz = sizeof("tai\n");
1415bc2b7dabSGregor Boirie 		break;
1416bc2b7dabSGregor Boirie 	default:
1417bc2b7dabSGregor Boirie 		BUG();
1418bc2b7dabSGregor Boirie 	}
1419bc2b7dabSGregor Boirie 
1420bc2b7dabSGregor Boirie 	memcpy(buf, name, sz);
1421bc2b7dabSGregor Boirie 	return sz;
1422bc2b7dabSGregor Boirie }
1423bc2b7dabSGregor Boirie 
1424bc2b7dabSGregor Boirie static ssize_t iio_store_timestamp_clock(struct device *dev,
1425bc2b7dabSGregor Boirie 					 struct device_attribute *attr,
1426bc2b7dabSGregor Boirie 					 const char *buf, size_t len)
1427bc2b7dabSGregor Boirie {
1428bc2b7dabSGregor Boirie 	clockid_t clk;
1429bc2b7dabSGregor Boirie 	int ret;
1430bc2b7dabSGregor Boirie 
1431bc2b7dabSGregor Boirie 	if (sysfs_streq(buf, "realtime"))
1432bc2b7dabSGregor Boirie 		clk = CLOCK_REALTIME;
1433bc2b7dabSGregor Boirie 	else if (sysfs_streq(buf, "monotonic"))
1434bc2b7dabSGregor Boirie 		clk = CLOCK_MONOTONIC;
1435bc2b7dabSGregor Boirie 	else if (sysfs_streq(buf, "monotonic_raw"))
1436bc2b7dabSGregor Boirie 		clk = CLOCK_MONOTONIC_RAW;
1437bc2b7dabSGregor Boirie 	else if (sysfs_streq(buf, "realtime_coarse"))
1438bc2b7dabSGregor Boirie 		clk = CLOCK_REALTIME_COARSE;
1439bc2b7dabSGregor Boirie 	else if (sysfs_streq(buf, "monotonic_coarse"))
1440bc2b7dabSGregor Boirie 		clk = CLOCK_MONOTONIC_COARSE;
1441bc2b7dabSGregor Boirie 	else if (sysfs_streq(buf, "boottime"))
1442bc2b7dabSGregor Boirie 		clk = CLOCK_BOOTTIME;
1443bc2b7dabSGregor Boirie 	else if (sysfs_streq(buf, "tai"))
1444bc2b7dabSGregor Boirie 		clk = CLOCK_TAI;
1445bc2b7dabSGregor Boirie 	else
1446bc2b7dabSGregor Boirie 		return -EINVAL;
1447bc2b7dabSGregor Boirie 
1448bc2b7dabSGregor Boirie 	ret = iio_device_set_clock(dev_to_iio_dev(dev), clk);
1449bc2b7dabSGregor Boirie 	if (ret)
1450bc2b7dabSGregor Boirie 		return ret;
1451bc2b7dabSGregor Boirie 
1452bc2b7dabSGregor Boirie 	return len;
1453bc2b7dabSGregor Boirie }
1454bc2b7dabSGregor Boirie 
1455bc2b7dabSGregor Boirie static DEVICE_ATTR(current_timestamp_clock, S_IRUGO | S_IWUSR,
1456bc2b7dabSGregor Boirie 		   iio_show_timestamp_clock, iio_store_timestamp_clock);
1457bc2b7dabSGregor Boirie 
1458a980e046SJonathan Cameron static int iio_device_register_sysfs(struct iio_dev *indio_dev)
1459a980e046SJonathan Cameron {
1460207c2d27SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1461a980e046SJonathan Cameron 	int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
146284088ebdSLars-Peter Clausen 	struct iio_dev_attr *p;
1463bc2b7dabSGregor Boirie 	struct attribute **attr, *clk = NULL;
1464a980e046SJonathan Cameron 
1465a980e046SJonathan Cameron 	/* First count elements in any existing group */
1466a980e046SJonathan Cameron 	if (indio_dev->info->attrs) {
1467a980e046SJonathan Cameron 		attr = indio_dev->info->attrs->attrs;
1468a980e046SJonathan Cameron 		while (*attr++ != NULL)
1469a980e046SJonathan Cameron 			attrcount_orig++;
1470a980e046SJonathan Cameron 	}
1471a980e046SJonathan Cameron 	attrcount = attrcount_orig;
1472a980e046SJonathan Cameron 	/*
1473a980e046SJonathan Cameron 	 * New channel registration method - relies on the fact a group does
1474d25b3808SPeter Meerwald 	 * not need to be initialized if its name is NULL.
1475a980e046SJonathan Cameron 	 */
1476a980e046SJonathan Cameron 	if (indio_dev->channels)
1477a980e046SJonathan Cameron 		for (i = 0; i < indio_dev->num_channels; i++) {
1478bc2b7dabSGregor Boirie 			const struct iio_chan_spec *chan =
1479bc2b7dabSGregor Boirie 				&indio_dev->channels[i];
1480bc2b7dabSGregor Boirie 
1481bc2b7dabSGregor Boirie 			if (chan->type == IIO_TIMESTAMP)
1482bc2b7dabSGregor Boirie 				clk = &dev_attr_current_timestamp_clock.attr;
1483bc2b7dabSGregor Boirie 
1484bc2b7dabSGregor Boirie 			ret = iio_device_add_channel_sysfs(indio_dev, chan);
1485a980e046SJonathan Cameron 			if (ret < 0)
1486a980e046SJonathan Cameron 				goto error_clear_attrs;
1487a980e046SJonathan Cameron 			attrcount += ret;
1488a980e046SJonathan Cameron 		}
1489a980e046SJonathan Cameron 
1490fa83c3baSAlexandru Ardelean 	if (iio_dev_opaque->event_interface)
1491bc2b7dabSGregor Boirie 		clk = &dev_attr_current_timestamp_clock.attr;
1492bc2b7dabSGregor Boirie 
1493a980e046SJonathan Cameron 	if (indio_dev->name)
1494a980e046SJonathan Cameron 		attrcount++;
14952c3d0c9fSPhil Reid 	if (indio_dev->label)
14962c3d0c9fSPhil Reid 		attrcount++;
1497bc2b7dabSGregor Boirie 	if (clk)
1498bc2b7dabSGregor Boirie 		attrcount++;
1499a980e046SJonathan Cameron 
1500207c2d27SAlexandru Ardelean 	iio_dev_opaque->chan_attr_group.attrs =
1501207c2d27SAlexandru Ardelean 		kcalloc(attrcount + 1,
1502207c2d27SAlexandru Ardelean 			sizeof(iio_dev_opaque->chan_attr_group.attrs[0]),
1503a980e046SJonathan Cameron 			GFP_KERNEL);
1504207c2d27SAlexandru Ardelean 	if (iio_dev_opaque->chan_attr_group.attrs == NULL) {
1505a980e046SJonathan Cameron 		ret = -ENOMEM;
1506a980e046SJonathan Cameron 		goto error_clear_attrs;
1507a980e046SJonathan Cameron 	}
1508a980e046SJonathan Cameron 	/* Copy across original attributes */
150918b4c9cdSHans de Goede 	if (indio_dev->info->attrs) {
1510207c2d27SAlexandru Ardelean 		memcpy(iio_dev_opaque->chan_attr_group.attrs,
1511a980e046SJonathan Cameron 		       indio_dev->info->attrs->attrs,
1512207c2d27SAlexandru Ardelean 		       sizeof(iio_dev_opaque->chan_attr_group.attrs[0])
1513a980e046SJonathan Cameron 		       *attrcount_orig);
151418b4c9cdSHans de Goede 		iio_dev_opaque->chan_attr_group.is_visible =
151518b4c9cdSHans de Goede 			indio_dev->info->attrs->is_visible;
151618b4c9cdSHans de Goede 	}
1517a980e046SJonathan Cameron 	attrn = attrcount_orig;
1518a980e046SJonathan Cameron 	/* Add all elements from the list. */
1519207c2d27SAlexandru Ardelean 	list_for_each_entry(p, &iio_dev_opaque->channel_attr_list, l)
1520207c2d27SAlexandru Ardelean 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1521a980e046SJonathan Cameron 	if (indio_dev->name)
1522207c2d27SAlexandru Ardelean 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
15232c3d0c9fSPhil Reid 	if (indio_dev->label)
1524207c2d27SAlexandru Ardelean 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_label.attr;
1525bc2b7dabSGregor Boirie 	if (clk)
1526207c2d27SAlexandru Ardelean 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = clk;
1527a980e046SJonathan Cameron 
1528a980e046SJonathan Cameron 	indio_dev->groups[indio_dev->groupcounter++] =
1529207c2d27SAlexandru Ardelean 		&iio_dev_opaque->chan_attr_group;
1530a980e046SJonathan Cameron 
1531a980e046SJonathan Cameron 	return 0;
1532a980e046SJonathan Cameron 
1533a980e046SJonathan Cameron error_clear_attrs:
1534207c2d27SAlexandru Ardelean 	iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1535a980e046SJonathan Cameron 
1536a980e046SJonathan Cameron 	return ret;
1537a980e046SJonathan Cameron }
1538a980e046SJonathan Cameron 
1539a980e046SJonathan Cameron static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
1540a980e046SJonathan Cameron {
1541207c2d27SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1542a980e046SJonathan Cameron 
1543207c2d27SAlexandru Ardelean 	iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1544207c2d27SAlexandru Ardelean 	kfree(iio_dev_opaque->chan_attr_group.attrs);
1545207c2d27SAlexandru Ardelean 	iio_dev_opaque->chan_attr_group.attrs = NULL;
1546a980e046SJonathan Cameron }
1547a980e046SJonathan Cameron 
1548a980e046SJonathan Cameron static void iio_dev_release(struct device *device)
1549a980e046SJonathan Cameron {
1550e53f5ac5SLars-Peter Clausen 	struct iio_dev *indio_dev = dev_to_iio_dev(device);
15516d4ebd56SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
15526d4ebd56SAlexandru Ardelean 
1553d89e119aSBenjamin Gaignard 	if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1554a980e046SJonathan Cameron 		iio_device_unregister_trigger_consumer(indio_dev);
1555a980e046SJonathan Cameron 	iio_device_unregister_eventset(indio_dev);
1556a980e046SJonathan Cameron 	iio_device_unregister_sysfs(indio_dev);
1557e407fd65SLars-Peter Clausen 
15589e69c935SLars-Peter Clausen 	iio_buffer_put(indio_dev->buffer);
15599e69c935SLars-Peter Clausen 
1560e407fd65SLars-Peter Clausen 	ida_simple_remove(&iio_ida, indio_dev->id);
15616d4ebd56SAlexandru Ardelean 	kfree(iio_dev_opaque);
1562a980e046SJonathan Cameron }
1563a980e046SJonathan Cameron 
156417d82b47SGuenter Roeck struct device_type iio_device_type = {
1565a980e046SJonathan Cameron 	.name = "iio_device",
1566a980e046SJonathan Cameron 	.release = iio_dev_release,
1567a980e046SJonathan Cameron };
1568a980e046SJonathan Cameron 
1569a7e57dceSSachin Kamat /**
1570a7e57dceSSachin Kamat  * iio_device_alloc() - allocate an iio_dev from a driver
1571c9561fd2SJonathan Cameron  * @parent:		Parent device.
1572a7e57dceSSachin Kamat  * @sizeof_priv:	Space to allocate for private structure.
1573a7e57dceSSachin Kamat  **/
157478289b4aSAlexandru Ardelean struct iio_dev *iio_device_alloc(struct device *parent, int sizeof_priv)
1575a980e046SJonathan Cameron {
15766d4ebd56SAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque;
1577a980e046SJonathan Cameron 	struct iio_dev *dev;
1578a980e046SJonathan Cameron 	size_t alloc_size;
1579a980e046SJonathan Cameron 
15806d4ebd56SAlexandru Ardelean 	alloc_size = sizeof(struct iio_dev_opaque);
1581a980e046SJonathan Cameron 	if (sizeof_priv) {
1582a980e046SJonathan Cameron 		alloc_size = ALIGN(alloc_size, IIO_ALIGN);
1583a980e046SJonathan Cameron 		alloc_size += sizeof_priv;
1584a980e046SJonathan Cameron 	}
1585a980e046SJonathan Cameron 
15866d4ebd56SAlexandru Ardelean 	iio_dev_opaque = kzalloc(alloc_size, GFP_KERNEL);
15876d4ebd56SAlexandru Ardelean 	if (!iio_dev_opaque)
15880d4b2184SJonathan Cameron 		return NULL;
1589a980e046SJonathan Cameron 
15906d4ebd56SAlexandru Ardelean 	dev = &iio_dev_opaque->indio_dev;
15916d4ebd56SAlexandru Ardelean 	dev->priv = (char *)iio_dev_opaque +
15926d4ebd56SAlexandru Ardelean 		ALIGN(sizeof(struct iio_dev_opaque), IIO_ALIGN);
15936d4ebd56SAlexandru Ardelean 
15948525df47SAlexandru Ardelean 	dev->dev.parent = parent;
1595a980e046SJonathan Cameron 	dev->dev.groups = dev->groups;
159617d82b47SGuenter Roeck 	dev->dev.type = &iio_device_type;
1597a980e046SJonathan Cameron 	dev->dev.bus = &iio_bus_type;
1598a980e046SJonathan Cameron 	device_initialize(&dev->dev);
1599a980e046SJonathan Cameron 	dev_set_drvdata(&dev->dev, (void *)dev);
1600a980e046SJonathan Cameron 	mutex_init(&dev->mlock);
1601a980e046SJonathan Cameron 	mutex_init(&dev->info_exist_lock);
1602207c2d27SAlexandru Ardelean 	INIT_LIST_HEAD(&iio_dev_opaque->channel_attr_list);
1603a980e046SJonathan Cameron 
1604a980e046SJonathan Cameron 	dev->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
1605a980e046SJonathan Cameron 	if (dev->id < 0) {
1606a980e046SJonathan Cameron 		/* cannot use a dev_err as the name isn't available */
16073176dd5dSSachin Kamat 		pr_err("failed to get device id\n");
16086d4ebd56SAlexandru Ardelean 		kfree(iio_dev_opaque);
1609a980e046SJonathan Cameron 		return NULL;
1610a980e046SJonathan Cameron 	}
1611a980e046SJonathan Cameron 	dev_set_name(&dev->dev, "iio:device%d", dev->id);
16126a8c6b26SAlexandru Ardelean 	INIT_LIST_HEAD(&iio_dev_opaque->buffer_list);
16138dedcc3eSAlexandru Ardelean 	INIT_LIST_HEAD(&iio_dev_opaque->ioctl_handlers);
1614a980e046SJonathan Cameron 
1615a980e046SJonathan Cameron 	return dev;
1616a980e046SJonathan Cameron }
16177cbb7537SLars-Peter Clausen EXPORT_SYMBOL(iio_device_alloc);
1618a980e046SJonathan Cameron 
1619a7e57dceSSachin Kamat /**
1620a7e57dceSSachin Kamat  * iio_device_free() - free an iio_dev from a driver
1621a7e57dceSSachin Kamat  * @dev:		the iio_dev associated with the device
1622a7e57dceSSachin Kamat  **/
16237cbb7537SLars-Peter Clausen void iio_device_free(struct iio_dev *dev)
1624a980e046SJonathan Cameron {
1625e407fd65SLars-Peter Clausen 	if (dev)
1626e407fd65SLars-Peter Clausen 		put_device(&dev->dev);
1627a980e046SJonathan Cameron }
16287cbb7537SLars-Peter Clausen EXPORT_SYMBOL(iio_device_free);
1629a980e046SJonathan Cameron 
16309dabaf5eSGrygorii Strashko static void devm_iio_device_release(struct device *dev, void *res)
16319dabaf5eSGrygorii Strashko {
16329dabaf5eSGrygorii Strashko 	iio_device_free(*(struct iio_dev **)res);
16339dabaf5eSGrygorii Strashko }
16349dabaf5eSGrygorii Strashko 
1635a7e57dceSSachin Kamat /**
1636a7e57dceSSachin Kamat  * devm_iio_device_alloc - Resource-managed iio_device_alloc()
163778289b4aSAlexandru Ardelean  * @parent:		Device to allocate iio_dev for, and parent for this IIO device
1638a7e57dceSSachin Kamat  * @sizeof_priv:	Space to allocate for private structure.
1639a7e57dceSSachin Kamat  *
1640a7e57dceSSachin Kamat  * Managed iio_device_alloc. iio_dev allocated with this function is
1641a7e57dceSSachin Kamat  * automatically freed on driver detach.
1642a7e57dceSSachin Kamat  *
1643a7e57dceSSachin Kamat  * RETURNS:
1644a7e57dceSSachin Kamat  * Pointer to allocated iio_dev on success, NULL on failure.
1645a7e57dceSSachin Kamat  */
164678289b4aSAlexandru Ardelean struct iio_dev *devm_iio_device_alloc(struct device *parent, int sizeof_priv)
16479dabaf5eSGrygorii Strashko {
16489dabaf5eSGrygorii Strashko 	struct iio_dev **ptr, *iio_dev;
16499dabaf5eSGrygorii Strashko 
16509dabaf5eSGrygorii Strashko 	ptr = devres_alloc(devm_iio_device_release, sizeof(*ptr),
16519dabaf5eSGrygorii Strashko 			   GFP_KERNEL);
16529dabaf5eSGrygorii Strashko 	if (!ptr)
16539dabaf5eSGrygorii Strashko 		return NULL;
16549dabaf5eSGrygorii Strashko 
165578289b4aSAlexandru Ardelean 	iio_dev = iio_device_alloc(parent, sizeof_priv);
16569dabaf5eSGrygorii Strashko 	if (iio_dev) {
16579dabaf5eSGrygorii Strashko 		*ptr = iio_dev;
165878289b4aSAlexandru Ardelean 		devres_add(parent, ptr);
16599dabaf5eSGrygorii Strashko 	} else {
16609dabaf5eSGrygorii Strashko 		devres_free(ptr);
16619dabaf5eSGrygorii Strashko 	}
16629dabaf5eSGrygorii Strashko 
16639dabaf5eSGrygorii Strashko 	return iio_dev;
16649dabaf5eSGrygorii Strashko }
16659dabaf5eSGrygorii Strashko EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
16669dabaf5eSGrygorii Strashko 
1667a7e57dceSSachin Kamat /**
1668a980e046SJonathan Cameron  * iio_chrdev_open() - chrdev file open for buffer access and ioctls
16692498dcf6SCristina Opriceana  * @inode:	Inode structure for identifying the device in the file system
16702498dcf6SCristina Opriceana  * @filp:	File structure for iio device used to keep and later access
16712498dcf6SCristina Opriceana  *		private data
16722498dcf6SCristina Opriceana  *
16732498dcf6SCristina Opriceana  * Return: 0 on success or -EBUSY if the device is already opened
1674a980e046SJonathan Cameron  **/
1675a980e046SJonathan Cameron static int iio_chrdev_open(struct inode *inode, struct file *filp)
1676a980e046SJonathan Cameron {
1677a980e046SJonathan Cameron 	struct iio_dev *indio_dev = container_of(inode->i_cdev,
1678a980e046SJonathan Cameron 						struct iio_dev, chrdev);
1679a980e046SJonathan Cameron 
1680a980e046SJonathan Cameron 	if (test_and_set_bit(IIO_BUSY_BIT_POS, &indio_dev->flags))
1681a980e046SJonathan Cameron 		return -EBUSY;
1682a980e046SJonathan Cameron 
1683cadc2125SLars-Peter Clausen 	iio_device_get(indio_dev);
1684cadc2125SLars-Peter Clausen 
1685a980e046SJonathan Cameron 	filp->private_data = indio_dev;
1686a980e046SJonathan Cameron 
1687a980e046SJonathan Cameron 	return 0;
1688a980e046SJonathan Cameron }
1689a980e046SJonathan Cameron 
1690a980e046SJonathan Cameron /**
1691a980e046SJonathan Cameron  * iio_chrdev_release() - chrdev file close buffer access and ioctls
16922498dcf6SCristina Opriceana  * @inode:	Inode structure pointer for the char device
16932498dcf6SCristina Opriceana  * @filp:	File structure pointer for the char device
16942498dcf6SCristina Opriceana  *
16952498dcf6SCristina Opriceana  * Return: 0 for successful release
16962498dcf6SCristina Opriceana  */
1697a980e046SJonathan Cameron static int iio_chrdev_release(struct inode *inode, struct file *filp)
1698a980e046SJonathan Cameron {
1699a980e046SJonathan Cameron 	struct iio_dev *indio_dev = container_of(inode->i_cdev,
1700a980e046SJonathan Cameron 						struct iio_dev, chrdev);
1701a980e046SJonathan Cameron 	clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
1702cadc2125SLars-Peter Clausen 	iio_device_put(indio_dev);
1703cadc2125SLars-Peter Clausen 
1704a980e046SJonathan Cameron 	return 0;
1705a980e046SJonathan Cameron }
1706a980e046SJonathan Cameron 
17078dedcc3eSAlexandru Ardelean void iio_device_ioctl_handler_register(struct iio_dev *indio_dev,
17088dedcc3eSAlexandru Ardelean 				       struct iio_ioctl_handler *h)
17098dedcc3eSAlexandru Ardelean {
17108dedcc3eSAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
17118dedcc3eSAlexandru Ardelean 
17128dedcc3eSAlexandru Ardelean 	list_add_tail(&h->entry, &iio_dev_opaque->ioctl_handlers);
17138dedcc3eSAlexandru Ardelean }
17148dedcc3eSAlexandru Ardelean 
17158dedcc3eSAlexandru Ardelean void iio_device_ioctl_handler_unregister(struct iio_ioctl_handler *h)
17168dedcc3eSAlexandru Ardelean {
17178dedcc3eSAlexandru Ardelean 	list_del(&h->entry);
17188dedcc3eSAlexandru Ardelean }
17198dedcc3eSAlexandru Ardelean 
1720a980e046SJonathan Cameron static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1721a980e046SJonathan Cameron {
1722a980e046SJonathan Cameron 	struct iio_dev *indio_dev = filp->private_data;
17238dedcc3eSAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
17248dedcc3eSAlexandru Ardelean 	struct iio_ioctl_handler *h;
17258dedcc3eSAlexandru Ardelean 	int ret = -ENODEV;
1726a980e046SJonathan Cameron 
17278dedcc3eSAlexandru Ardelean 	mutex_lock(&indio_dev->info_exist_lock);
17288dedcc3eSAlexandru Ardelean 
17298dedcc3eSAlexandru Ardelean 	/**
17308dedcc3eSAlexandru Ardelean 	 * The NULL check here is required to prevent crashing when a device
17318dedcc3eSAlexandru Ardelean 	 * is being removed while userspace would still have open file handles
17328dedcc3eSAlexandru Ardelean 	 * to try to access this device.
17338dedcc3eSAlexandru Ardelean 	 */
1734f18e7a06SLars-Peter Clausen 	if (!indio_dev->info)
17358dedcc3eSAlexandru Ardelean 		goto out_unlock;
1736f18e7a06SLars-Peter Clausen 
17378dedcc3eSAlexandru Ardelean 	ret = -EINVAL;
17388dedcc3eSAlexandru Ardelean 	list_for_each_entry(h, &iio_dev_opaque->ioctl_handlers, entry) {
17398dedcc3eSAlexandru Ardelean 		ret = h->ioctl(indio_dev, filp, cmd, arg);
17408dedcc3eSAlexandru Ardelean 		if (ret != IIO_IOCTL_UNHANDLED)
17418dedcc3eSAlexandru Ardelean 			break;
1742a980e046SJonathan Cameron 	}
17438dedcc3eSAlexandru Ardelean 
174474d826daSAlexandru Ardelean 	if (ret == IIO_IOCTL_UNHANDLED)
174574d826daSAlexandru Ardelean 		ret = -EINVAL;
174674d826daSAlexandru Ardelean 
17478dedcc3eSAlexandru Ardelean out_unlock:
17488dedcc3eSAlexandru Ardelean 	mutex_unlock(&indio_dev->info_exist_lock);
17498dedcc3eSAlexandru Ardelean 
17508dedcc3eSAlexandru Ardelean 	return ret;
1751a980e046SJonathan Cameron }
1752a980e046SJonathan Cameron 
1753a980e046SJonathan Cameron static const struct file_operations iio_buffer_fileops = {
1754a980e046SJonathan Cameron 	.owner = THIS_MODULE,
1755a980e046SJonathan Cameron 	.llseek = noop_llseek,
1756ee8caea0SAlexandru Ardelean 	.read = iio_buffer_read_outer_addr,
1757ee8caea0SAlexandru Ardelean 	.poll = iio_buffer_poll_addr,
1758a980e046SJonathan Cameron 	.unlocked_ioctl = iio_ioctl,
17591832f2d8SArnd Bergmann 	.compat_ioctl = compat_ptr_ioctl,
1760ee8caea0SAlexandru Ardelean 	.open = iio_chrdev_open,
1761ee8caea0SAlexandru Ardelean 	.release = iio_chrdev_release,
1762a980e046SJonathan Cameron };
1763a980e046SJonathan Cameron 
17648f5d8727SVlad Dogaru static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
17658f5d8727SVlad Dogaru {
17668f5d8727SVlad Dogaru 	int i, j;
17678f5d8727SVlad Dogaru 	const struct iio_chan_spec *channels = indio_dev->channels;
17688f5d8727SVlad Dogaru 
17698f5d8727SVlad Dogaru 	if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
17708f5d8727SVlad Dogaru 		return 0;
17718f5d8727SVlad Dogaru 
17728f5d8727SVlad Dogaru 	for (i = 0; i < indio_dev->num_channels - 1; i++) {
17738f5d8727SVlad Dogaru 		if (channels[i].scan_index < 0)
17748f5d8727SVlad Dogaru 			continue;
17758f5d8727SVlad Dogaru 		for (j = i + 1; j < indio_dev->num_channels; j++)
17768f5d8727SVlad Dogaru 			if (channels[i].scan_index == channels[j].scan_index) {
17778f5d8727SVlad Dogaru 				dev_err(&indio_dev->dev,
17788f5d8727SVlad Dogaru 					"Duplicate scan index %d\n",
17798f5d8727SVlad Dogaru 					channels[i].scan_index);
17808f5d8727SVlad Dogaru 				return -EINVAL;
17818f5d8727SVlad Dogaru 			}
17828f5d8727SVlad Dogaru 	}
17838f5d8727SVlad Dogaru 
17848f5d8727SVlad Dogaru 	return 0;
17858f5d8727SVlad Dogaru }
17868f5d8727SVlad Dogaru 
1787a980e046SJonathan Cameron static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1788a980e046SJonathan Cameron 
178963b19547SJonathan Cameron int __iio_device_register(struct iio_dev *indio_dev, struct module *this_mod)
1790a980e046SJonathan Cameron {
1791a980e046SJonathan Cameron 	int ret;
1792a980e046SJonathan Cameron 
1793a17cb784SAlexandru Ardelean 	if (!indio_dev->info)
1794a17cb784SAlexandru Ardelean 		return -EINVAL;
1795a17cb784SAlexandru Ardelean 
179663b19547SJonathan Cameron 	indio_dev->driver_module = this_mod;
179717d82b47SGuenter Roeck 	/* If the calling driver did not initialize of_node, do it here */
179817d82b47SGuenter Roeck 	if (!indio_dev->dev.of_node && indio_dev->dev.parent)
179917d82b47SGuenter Roeck 		indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
180017d82b47SGuenter Roeck 
18012c3d0c9fSPhil Reid 	indio_dev->label = of_get_property(indio_dev->dev.of_node, "label",
18022c3d0c9fSPhil Reid 					   NULL);
18032c3d0c9fSPhil Reid 
18048f5d8727SVlad Dogaru 	ret = iio_check_unique_scan_index(indio_dev);
18058f5d8727SVlad Dogaru 	if (ret < 0)
18068f5d8727SVlad Dogaru 		return ret;
18078f5d8727SVlad Dogaru 
1808a980e046SJonathan Cameron 	/* configure elements for the chrdev */
1809a980e046SJonathan Cameron 	indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), indio_dev->id);
1810a980e046SJonathan Cameron 
18118915aacaSGreg Kroah-Hartman 	iio_device_register_debugfs(indio_dev);
18123e1b6c95SLars-Peter Clausen 
18133e1b6c95SLars-Peter Clausen 	ret = iio_buffer_alloc_sysfs_and_mask(indio_dev);
18143e1b6c95SLars-Peter Clausen 	if (ret) {
18153e1b6c95SLars-Peter Clausen 		dev_err(indio_dev->dev.parent,
18163e1b6c95SLars-Peter Clausen 			"Failed to create buffer sysfs interfaces\n");
18173e1b6c95SLars-Peter Clausen 		goto error_unreg_debugfs;
18183e1b6c95SLars-Peter Clausen 	}
18193e1b6c95SLars-Peter Clausen 
1820a980e046SJonathan Cameron 	ret = iio_device_register_sysfs(indio_dev);
1821a980e046SJonathan Cameron 	if (ret) {
1822a980e046SJonathan Cameron 		dev_err(indio_dev->dev.parent,
1823a980e046SJonathan Cameron 			"Failed to register sysfs interfaces\n");
18243e1b6c95SLars-Peter Clausen 		goto error_buffer_free_sysfs;
1825a980e046SJonathan Cameron 	}
1826a980e046SJonathan Cameron 	ret = iio_device_register_eventset(indio_dev);
1827a980e046SJonathan Cameron 	if (ret) {
1828a980e046SJonathan Cameron 		dev_err(indio_dev->dev.parent,
1829a980e046SJonathan Cameron 			"Failed to register event set\n");
1830a980e046SJonathan Cameron 		goto error_free_sysfs;
1831a980e046SJonathan Cameron 	}
1832d89e119aSBenjamin Gaignard 	if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1833a980e046SJonathan Cameron 		iio_device_register_trigger_consumer(indio_dev);
1834a980e046SJonathan Cameron 
1835a980e046SJonathan Cameron 	if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1836a980e046SJonathan Cameron 		indio_dev->setup_ops == NULL)
1837a980e046SJonathan Cameron 		indio_dev->setup_ops = &noop_ring_setup_ops;
1838a980e046SJonathan Cameron 
1839a980e046SJonathan Cameron 	cdev_init(&indio_dev->chrdev, &iio_buffer_fileops);
184063b19547SJonathan Cameron 
184163b19547SJonathan Cameron 	indio_dev->chrdev.owner = this_mod;
184238923911SLogan Gunthorpe 
184338923911SLogan Gunthorpe 	ret = cdev_device_add(&indio_dev->chrdev, &indio_dev->dev);
1844a980e046SJonathan Cameron 	if (ret < 0)
18450d5b7daeSLars-Peter Clausen 		goto error_unreg_eventset;
1846a980e046SJonathan Cameron 
18470d5b7daeSLars-Peter Clausen 	return 0;
184838923911SLogan Gunthorpe 
1849a980e046SJonathan Cameron error_unreg_eventset:
1850a980e046SJonathan Cameron 	iio_device_unregister_eventset(indio_dev);
1851a980e046SJonathan Cameron error_free_sysfs:
1852a980e046SJonathan Cameron 	iio_device_unregister_sysfs(indio_dev);
18533e1b6c95SLars-Peter Clausen error_buffer_free_sysfs:
18543e1b6c95SLars-Peter Clausen 	iio_buffer_free_sysfs_and_mask(indio_dev);
1855a980e046SJonathan Cameron error_unreg_debugfs:
1856a980e046SJonathan Cameron 	iio_device_unregister_debugfs(indio_dev);
1857a980e046SJonathan Cameron 	return ret;
1858a980e046SJonathan Cameron }
185963b19547SJonathan Cameron EXPORT_SYMBOL(__iio_device_register);
1860a980e046SJonathan Cameron 
1861a7e57dceSSachin Kamat /**
1862a7e57dceSSachin Kamat  * iio_device_unregister() - unregister a device from the IIO subsystem
1863a7e57dceSSachin Kamat  * @indio_dev:		Device structure representing the device.
1864a7e57dceSSachin Kamat  **/
1865a980e046SJonathan Cameron void iio_device_unregister(struct iio_dev *indio_dev)
1866a980e046SJonathan Cameron {
18678dedcc3eSAlexandru Ardelean 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
18688dedcc3eSAlexandru Ardelean 	struct iio_ioctl_handler *h, *t;
18698dedcc3eSAlexandru Ardelean 
187038923911SLogan Gunthorpe 	cdev_device_del(&indio_dev->chrdev, &indio_dev->dev);
1871a87c82e4SLars-Peter Clausen 
18727f75591fSFabrice Gasnier 	mutex_lock(&indio_dev->info_exist_lock);
18737f75591fSFabrice Gasnier 
1874bc4c9612SLars-Peter Clausen 	iio_device_unregister_debugfs(indio_dev);
18750d5b7daeSLars-Peter Clausen 
1876a87c82e4SLars-Peter Clausen 	iio_disable_all_buffers(indio_dev);
1877a87c82e4SLars-Peter Clausen 
1878a980e046SJonathan Cameron 	indio_dev->info = NULL;
1879d2f0a48fSLars-Peter Clausen 
18808dedcc3eSAlexandru Ardelean 	list_for_each_entry_safe(h, t, &iio_dev_opaque->ioctl_handlers, entry)
18818dedcc3eSAlexandru Ardelean 		list_del(&h->entry);
18828dedcc3eSAlexandru Ardelean 
1883d2f0a48fSLars-Peter Clausen 	iio_device_wakeup_eventset(indio_dev);
1884d2f0a48fSLars-Peter Clausen 	iio_buffer_wakeup_poll(indio_dev);
1885d2f0a48fSLars-Peter Clausen 
1886a980e046SJonathan Cameron 	mutex_unlock(&indio_dev->info_exist_lock);
18873e1b6c95SLars-Peter Clausen 
18883e1b6c95SLars-Peter Clausen 	iio_buffer_free_sysfs_and_mask(indio_dev);
1889a980e046SJonathan Cameron }
1890a980e046SJonathan Cameron EXPORT_SYMBOL(iio_device_unregister);
18918caa07c0SSachin Kamat 
18928caa07c0SSachin Kamat static void devm_iio_device_unreg(struct device *dev, void *res)
18938caa07c0SSachin Kamat {
18948caa07c0SSachin Kamat 	iio_device_unregister(*(struct iio_dev **)res);
18958caa07c0SSachin Kamat }
18968caa07c0SSachin Kamat 
189763b19547SJonathan Cameron int __devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev,
189863b19547SJonathan Cameron 			       struct module *this_mod)
18998caa07c0SSachin Kamat {
19008caa07c0SSachin Kamat 	struct iio_dev **ptr;
19018caa07c0SSachin Kamat 	int ret;
19028caa07c0SSachin Kamat 
19038caa07c0SSachin Kamat 	ptr = devres_alloc(devm_iio_device_unreg, sizeof(*ptr), GFP_KERNEL);
19048caa07c0SSachin Kamat 	if (!ptr)
19058caa07c0SSachin Kamat 		return -ENOMEM;
19068caa07c0SSachin Kamat 
19078caa07c0SSachin Kamat 	*ptr = indio_dev;
190863b19547SJonathan Cameron 	ret = __iio_device_register(indio_dev, this_mod);
19098caa07c0SSachin Kamat 	if (!ret)
19108caa07c0SSachin Kamat 		devres_add(dev, ptr);
19118caa07c0SSachin Kamat 	else
19128caa07c0SSachin Kamat 		devres_free(ptr);
19138caa07c0SSachin Kamat 
19148caa07c0SSachin Kamat 	return ret;
19158caa07c0SSachin Kamat }
191663b19547SJonathan Cameron EXPORT_SYMBOL_GPL(__devm_iio_device_register);
19178caa07c0SSachin Kamat 
19188caa07c0SSachin Kamat /**
191908a33805SAlison Schofield  * iio_device_claim_direct_mode - Keep device in direct mode
192008a33805SAlison Schofield  * @indio_dev:	the iio_dev associated with the device
192108a33805SAlison Schofield  *
192208a33805SAlison Schofield  * If the device is in direct mode it is guaranteed to stay
192308a33805SAlison Schofield  * that way until iio_device_release_direct_mode() is called.
192408a33805SAlison Schofield  *
192508a33805SAlison Schofield  * Use with iio_device_release_direct_mode()
192608a33805SAlison Schofield  *
192708a33805SAlison Schofield  * Returns: 0 on success, -EBUSY on failure
192808a33805SAlison Schofield  */
192908a33805SAlison Schofield int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
193008a33805SAlison Schofield {
193108a33805SAlison Schofield 	mutex_lock(&indio_dev->mlock);
193208a33805SAlison Schofield 
193308a33805SAlison Schofield 	if (iio_buffer_enabled(indio_dev)) {
193408a33805SAlison Schofield 		mutex_unlock(&indio_dev->mlock);
193508a33805SAlison Schofield 		return -EBUSY;
193608a33805SAlison Schofield 	}
193708a33805SAlison Schofield 	return 0;
193808a33805SAlison Schofield }
193908a33805SAlison Schofield EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
194008a33805SAlison Schofield 
194108a33805SAlison Schofield /**
194208a33805SAlison Schofield  * iio_device_release_direct_mode - releases claim on direct mode
194308a33805SAlison Schofield  * @indio_dev:	the iio_dev associated with the device
194408a33805SAlison Schofield  *
194508a33805SAlison Schofield  * Release the claim. Device is no longer guaranteed to stay
194608a33805SAlison Schofield  * in direct mode.
194708a33805SAlison Schofield  *
194808a33805SAlison Schofield  * Use with iio_device_claim_direct_mode()
194908a33805SAlison Schofield  */
195008a33805SAlison Schofield void iio_device_release_direct_mode(struct iio_dev *indio_dev)
195108a33805SAlison Schofield {
195208a33805SAlison Schofield 	mutex_unlock(&indio_dev->mlock);
195308a33805SAlison Schofield }
195408a33805SAlison Schofield EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
195508a33805SAlison Schofield 
1956a980e046SJonathan Cameron subsys_initcall(iio_init);
1957a980e046SJonathan Cameron module_exit(iio_exit);
1958a980e046SJonathan Cameron 
1959c8b95952SJonathan Cameron MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1960a980e046SJonathan Cameron MODULE_DESCRIPTION("Industrial I/O core");
1961a980e046SJonathan Cameron MODULE_LICENSE("GPL");
1962