1 // SPDX-License-Identifier: GPL-2.0-only
2 /* The industrial I/O core
3  *
4  * Copyright (c) 2008 Jonathan Cameron
5  *
6  * Based on elements of hwmon and input subsystems.
7  */
8 
9 #define pr_fmt(fmt) "iio-core: " fmt
10 
11 #include <linux/kernel.h>
12 #include <linux/module.h>
13 #include <linux/idr.h>
14 #include <linux/kdev_t.h>
15 #include <linux/err.h>
16 #include <linux/device.h>
17 #include <linux/fs.h>
18 #include <linux/poll.h>
19 #include <linux/property.h>
20 #include <linux/sched.h>
21 #include <linux/wait.h>
22 #include <linux/cdev.h>
23 #include <linux/slab.h>
24 #include <linux/anon_inodes.h>
25 #include <linux/debugfs.h>
26 #include <linux/mutex.h>
27 #include <linux/iio/iio.h>
28 #include <linux/iio/iio-opaque.h>
29 #include "iio_core.h"
30 #include "iio_core_trigger.h"
31 #include <linux/iio/sysfs.h>
32 #include <linux/iio/events.h>
33 #include <linux/iio/buffer.h>
34 #include <linux/iio/buffer_impl.h>
35 
36 /* IDA to assign each registered device a unique id */
37 static DEFINE_IDA(iio_ida);
38 
39 static dev_t iio_devt;
40 
41 #define IIO_DEV_MAX 256
42 struct bus_type iio_bus_type = {
43 	.name = "iio",
44 };
45 EXPORT_SYMBOL(iio_bus_type);
46 
47 static struct dentry *iio_debugfs_dentry;
48 
49 static const char * const iio_direction[] = {
50 	[0] = "in",
51 	[1] = "out",
52 };
53 
54 static const char * const iio_chan_type_name_spec[] = {
55 	[IIO_VOLTAGE] = "voltage",
56 	[IIO_CURRENT] = "current",
57 	[IIO_POWER] = "power",
58 	[IIO_ACCEL] = "accel",
59 	[IIO_ANGL_VEL] = "anglvel",
60 	[IIO_MAGN] = "magn",
61 	[IIO_LIGHT] = "illuminance",
62 	[IIO_INTENSITY] = "intensity",
63 	[IIO_PROXIMITY] = "proximity",
64 	[IIO_TEMP] = "temp",
65 	[IIO_INCLI] = "incli",
66 	[IIO_ROT] = "rot",
67 	[IIO_ANGL] = "angl",
68 	[IIO_TIMESTAMP] = "timestamp",
69 	[IIO_CAPACITANCE] = "capacitance",
70 	[IIO_ALTVOLTAGE] = "altvoltage",
71 	[IIO_CCT] = "cct",
72 	[IIO_PRESSURE] = "pressure",
73 	[IIO_HUMIDITYRELATIVE] = "humidityrelative",
74 	[IIO_ACTIVITY] = "activity",
75 	[IIO_STEPS] = "steps",
76 	[IIO_ENERGY] = "energy",
77 	[IIO_DISTANCE] = "distance",
78 	[IIO_VELOCITY] = "velocity",
79 	[IIO_CONCENTRATION] = "concentration",
80 	[IIO_RESISTANCE] = "resistance",
81 	[IIO_PH] = "ph",
82 	[IIO_UVINDEX] = "uvindex",
83 	[IIO_ELECTRICALCONDUCTIVITY] = "electricalconductivity",
84 	[IIO_COUNT] = "count",
85 	[IIO_INDEX] = "index",
86 	[IIO_GRAVITY]  = "gravity",
87 	[IIO_POSITIONRELATIVE]  = "positionrelative",
88 	[IIO_PHASE] = "phase",
89 	[IIO_MASSCONCENTRATION] = "massconcentration",
90 };
91 
92 static const char * const iio_modifier_names[] = {
93 	[IIO_MOD_X] = "x",
94 	[IIO_MOD_Y] = "y",
95 	[IIO_MOD_Z] = "z",
96 	[IIO_MOD_X_AND_Y] = "x&y",
97 	[IIO_MOD_X_AND_Z] = "x&z",
98 	[IIO_MOD_Y_AND_Z] = "y&z",
99 	[IIO_MOD_X_AND_Y_AND_Z] = "x&y&z",
100 	[IIO_MOD_X_OR_Y] = "x|y",
101 	[IIO_MOD_X_OR_Z] = "x|z",
102 	[IIO_MOD_Y_OR_Z] = "y|z",
103 	[IIO_MOD_X_OR_Y_OR_Z] = "x|y|z",
104 	[IIO_MOD_ROOT_SUM_SQUARED_X_Y] = "sqrt(x^2+y^2)",
105 	[IIO_MOD_SUM_SQUARED_X_Y_Z] = "x^2+y^2+z^2",
106 	[IIO_MOD_LIGHT_BOTH] = "both",
107 	[IIO_MOD_LIGHT_IR] = "ir",
108 	[IIO_MOD_LIGHT_CLEAR] = "clear",
109 	[IIO_MOD_LIGHT_RED] = "red",
110 	[IIO_MOD_LIGHT_GREEN] = "green",
111 	[IIO_MOD_LIGHT_BLUE] = "blue",
112 	[IIO_MOD_LIGHT_UV] = "uv",
113 	[IIO_MOD_LIGHT_DUV] = "duv",
114 	[IIO_MOD_QUATERNION] = "quaternion",
115 	[IIO_MOD_TEMP_AMBIENT] = "ambient",
116 	[IIO_MOD_TEMP_OBJECT] = "object",
117 	[IIO_MOD_NORTH_MAGN] = "from_north_magnetic",
118 	[IIO_MOD_NORTH_TRUE] = "from_north_true",
119 	[IIO_MOD_NORTH_MAGN_TILT_COMP] = "from_north_magnetic_tilt_comp",
120 	[IIO_MOD_NORTH_TRUE_TILT_COMP] = "from_north_true_tilt_comp",
121 	[IIO_MOD_RUNNING] = "running",
122 	[IIO_MOD_JOGGING] = "jogging",
123 	[IIO_MOD_WALKING] = "walking",
124 	[IIO_MOD_STILL] = "still",
125 	[IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z] = "sqrt(x^2+y^2+z^2)",
126 	[IIO_MOD_I] = "i",
127 	[IIO_MOD_Q] = "q",
128 	[IIO_MOD_CO2] = "co2",
129 	[IIO_MOD_VOC] = "voc",
130 	[IIO_MOD_PM1] = "pm1",
131 	[IIO_MOD_PM2P5] = "pm2p5",
132 	[IIO_MOD_PM4] = "pm4",
133 	[IIO_MOD_PM10] = "pm10",
134 	[IIO_MOD_ETHANOL] = "ethanol",
135 	[IIO_MOD_H2] = "h2",
136 	[IIO_MOD_O2] = "o2",
137 };
138 
139 /* relies on pairs of these shared then separate */
140 static const char * const iio_chan_info_postfix[] = {
141 	[IIO_CHAN_INFO_RAW] = "raw",
142 	[IIO_CHAN_INFO_PROCESSED] = "input",
143 	[IIO_CHAN_INFO_SCALE] = "scale",
144 	[IIO_CHAN_INFO_OFFSET] = "offset",
145 	[IIO_CHAN_INFO_CALIBSCALE] = "calibscale",
146 	[IIO_CHAN_INFO_CALIBBIAS] = "calibbias",
147 	[IIO_CHAN_INFO_PEAK] = "peak_raw",
148 	[IIO_CHAN_INFO_PEAK_SCALE] = "peak_scale",
149 	[IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW] = "quadrature_correction_raw",
150 	[IIO_CHAN_INFO_AVERAGE_RAW] = "mean_raw",
151 	[IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY]
152 	= "filter_low_pass_3db_frequency",
153 	[IIO_CHAN_INFO_HIGH_PASS_FILTER_3DB_FREQUENCY]
154 	= "filter_high_pass_3db_frequency",
155 	[IIO_CHAN_INFO_SAMP_FREQ] = "sampling_frequency",
156 	[IIO_CHAN_INFO_FREQUENCY] = "frequency",
157 	[IIO_CHAN_INFO_PHASE] = "phase",
158 	[IIO_CHAN_INFO_HARDWAREGAIN] = "hardwaregain",
159 	[IIO_CHAN_INFO_HYSTERESIS] = "hysteresis",
160 	[IIO_CHAN_INFO_HYSTERESIS_RELATIVE] = "hysteresis_relative",
161 	[IIO_CHAN_INFO_INT_TIME] = "integration_time",
162 	[IIO_CHAN_INFO_ENABLE] = "en",
163 	[IIO_CHAN_INFO_CALIBHEIGHT] = "calibheight",
164 	[IIO_CHAN_INFO_CALIBWEIGHT] = "calibweight",
165 	[IIO_CHAN_INFO_DEBOUNCE_COUNT] = "debounce_count",
166 	[IIO_CHAN_INFO_DEBOUNCE_TIME] = "debounce_time",
167 	[IIO_CHAN_INFO_CALIBEMISSIVITY] = "calibemissivity",
168 	[IIO_CHAN_INFO_OVERSAMPLING_RATIO] = "oversampling_ratio",
169 	[IIO_CHAN_INFO_THERMOCOUPLE_TYPE] = "thermocouple_type",
170 	[IIO_CHAN_INFO_CALIBAMBIENT] = "calibambient",
171 };
172 /**
173  * iio_device_id() - query the unique ID for the device
174  * @indio_dev:		Device structure whose ID is being queried
175  *
176  * The IIO device ID is a unique index used for example for the naming
177  * of the character device /dev/iio\:device[ID]
178  */
179 int iio_device_id(struct iio_dev *indio_dev)
180 {
181 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
182 
183 	return iio_dev_opaque->id;
184 }
185 EXPORT_SYMBOL_GPL(iio_device_id);
186 
187 /**
188  * iio_buffer_enabled() - helper function to test if the buffer is enabled
189  * @indio_dev:		IIO device structure for device
190  */
191 bool iio_buffer_enabled(struct iio_dev *indio_dev)
192 {
193 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
194 
195 	return iio_dev_opaque->currentmode
196 		& (INDIO_BUFFER_TRIGGERED | INDIO_BUFFER_HARDWARE |
197 		   INDIO_BUFFER_SOFTWARE);
198 }
199 EXPORT_SYMBOL_GPL(iio_buffer_enabled);
200 
201 /**
202  * iio_sysfs_match_string_with_gaps - matches given string in an array with gaps
203  * @array: array of strings
204  * @n: number of strings in the array
205  * @str: string to match with
206  *
207  * Returns index of @str in the @array or -EINVAL, similar to match_string().
208  * Uses sysfs_streq instead of strcmp for matching.
209  *
210  * This routine will look for a string in an array of strings.
211  * The search will continue until the element is found or the n-th element
212  * is reached, regardless of any NULL elements in the array.
213  */
214 static int iio_sysfs_match_string_with_gaps(const char * const *array, size_t n,
215 					    const char *str)
216 {
217 	const char *item;
218 	int index;
219 
220 	for (index = 0; index < n; index++) {
221 		item = array[index];
222 		if (!item)
223 			continue;
224 		if (sysfs_streq(item, str))
225 			return index;
226 	}
227 
228 	return -EINVAL;
229 }
230 
231 #if defined(CONFIG_DEBUG_FS)
232 /*
233  * There's also a CONFIG_DEBUG_FS guard in include/linux/iio/iio.h for
234  * iio_get_debugfs_dentry() to make it inline if CONFIG_DEBUG_FS is undefined
235  */
236 struct dentry *iio_get_debugfs_dentry(struct iio_dev *indio_dev)
237 {
238 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
239 	return iio_dev_opaque->debugfs_dentry;
240 }
241 EXPORT_SYMBOL_GPL(iio_get_debugfs_dentry);
242 #endif
243 
244 /**
245  * iio_find_channel_from_si() - get channel from its scan index
246  * @indio_dev:		device
247  * @si:			scan index to match
248  */
249 const struct iio_chan_spec
250 *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
251 {
252 	int i;
253 
254 	for (i = 0; i < indio_dev->num_channels; i++)
255 		if (indio_dev->channels[i].scan_index == si)
256 			return &indio_dev->channels[i];
257 	return NULL;
258 }
259 
260 /* This turns up an awful lot */
261 ssize_t iio_read_const_attr(struct device *dev,
262 			    struct device_attribute *attr,
263 			    char *buf)
264 {
265 	return sysfs_emit(buf, "%s\n", to_iio_const_attr(attr)->string);
266 }
267 EXPORT_SYMBOL(iio_read_const_attr);
268 
269 /**
270  * iio_device_set_clock() - Set current timestamping clock for the device
271  * @indio_dev: IIO device structure containing the device
272  * @clock_id: timestamping clock posix identifier to set.
273  */
274 int iio_device_set_clock(struct iio_dev *indio_dev, clockid_t clock_id)
275 {
276 	int ret;
277 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
278 	const struct iio_event_interface *ev_int = iio_dev_opaque->event_interface;
279 
280 	ret = mutex_lock_interruptible(&indio_dev->mlock);
281 	if (ret)
282 		return ret;
283 	if ((ev_int && iio_event_enabled(ev_int)) ||
284 	    iio_buffer_enabled(indio_dev)) {
285 		mutex_unlock(&indio_dev->mlock);
286 		return -EBUSY;
287 	}
288 	iio_dev_opaque->clock_id = clock_id;
289 	mutex_unlock(&indio_dev->mlock);
290 
291 	return 0;
292 }
293 EXPORT_SYMBOL(iio_device_set_clock);
294 
295 /**
296  * iio_device_get_clock() - Retrieve current timestamping clock for the device
297  * @indio_dev: IIO device structure containing the device
298  */
299 clockid_t iio_device_get_clock(const struct iio_dev *indio_dev)
300 {
301 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
302 
303 	return iio_dev_opaque->clock_id;
304 }
305 EXPORT_SYMBOL(iio_device_get_clock);
306 
307 /**
308  * iio_get_time_ns() - utility function to get a time stamp for events etc
309  * @indio_dev: device
310  */
311 s64 iio_get_time_ns(const struct iio_dev *indio_dev)
312 {
313 	struct timespec64 tp;
314 
315 	switch (iio_device_get_clock(indio_dev)) {
316 	case CLOCK_REALTIME:
317 		return ktime_get_real_ns();
318 	case CLOCK_MONOTONIC:
319 		return ktime_get_ns();
320 	case CLOCK_MONOTONIC_RAW:
321 		return ktime_get_raw_ns();
322 	case CLOCK_REALTIME_COARSE:
323 		return ktime_to_ns(ktime_get_coarse_real());
324 	case CLOCK_MONOTONIC_COARSE:
325 		ktime_get_coarse_ts64(&tp);
326 		return timespec64_to_ns(&tp);
327 	case CLOCK_BOOTTIME:
328 		return ktime_get_boottime_ns();
329 	case CLOCK_TAI:
330 		return ktime_get_clocktai_ns();
331 	default:
332 		BUG();
333 	}
334 }
335 EXPORT_SYMBOL(iio_get_time_ns);
336 
337 static int __init iio_init(void)
338 {
339 	int ret;
340 
341 	/* Register sysfs bus */
342 	ret  = bus_register(&iio_bus_type);
343 	if (ret < 0) {
344 		pr_err("could not register bus type\n");
345 		goto error_nothing;
346 	}
347 
348 	ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
349 	if (ret < 0) {
350 		pr_err("failed to allocate char dev region\n");
351 		goto error_unregister_bus_type;
352 	}
353 
354 	iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
355 
356 	return 0;
357 
358 error_unregister_bus_type:
359 	bus_unregister(&iio_bus_type);
360 error_nothing:
361 	return ret;
362 }
363 
364 static void __exit iio_exit(void)
365 {
366 	if (iio_devt)
367 		unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
368 	bus_unregister(&iio_bus_type);
369 	debugfs_remove(iio_debugfs_dentry);
370 }
371 
372 #if defined(CONFIG_DEBUG_FS)
373 static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
374 			      size_t count, loff_t *ppos)
375 {
376 	struct iio_dev *indio_dev = file->private_data;
377 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
378 	unsigned int val = 0;
379 	int ret;
380 
381 	if (*ppos > 0)
382 		return simple_read_from_buffer(userbuf, count, ppos,
383 					       iio_dev_opaque->read_buf,
384 					       iio_dev_opaque->read_buf_len);
385 
386 	ret = indio_dev->info->debugfs_reg_access(indio_dev,
387 						  iio_dev_opaque->cached_reg_addr,
388 						  0, &val);
389 	if (ret) {
390 		dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
391 		return ret;
392 	}
393 
394 	iio_dev_opaque->read_buf_len = snprintf(iio_dev_opaque->read_buf,
395 					      sizeof(iio_dev_opaque->read_buf),
396 					      "0x%X\n", val);
397 
398 	return simple_read_from_buffer(userbuf, count, ppos,
399 				       iio_dev_opaque->read_buf,
400 				       iio_dev_opaque->read_buf_len);
401 }
402 
403 static ssize_t iio_debugfs_write_reg(struct file *file,
404 		     const char __user *userbuf, size_t count, loff_t *ppos)
405 {
406 	struct iio_dev *indio_dev = file->private_data;
407 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
408 	unsigned int reg, val;
409 	char buf[80];
410 	int ret;
411 
412 	count = min_t(size_t, count, (sizeof(buf)-1));
413 	if (copy_from_user(buf, userbuf, count))
414 		return -EFAULT;
415 
416 	buf[count] = 0;
417 
418 	ret = sscanf(buf, "%i %i", &reg, &val);
419 
420 	switch (ret) {
421 	case 1:
422 		iio_dev_opaque->cached_reg_addr = reg;
423 		break;
424 	case 2:
425 		iio_dev_opaque->cached_reg_addr = reg;
426 		ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
427 							  val, NULL);
428 		if (ret) {
429 			dev_err(indio_dev->dev.parent, "%s: write failed\n",
430 				__func__);
431 			return ret;
432 		}
433 		break;
434 	default:
435 		return -EINVAL;
436 	}
437 
438 	return count;
439 }
440 
441 static const struct file_operations iio_debugfs_reg_fops = {
442 	.open = simple_open,
443 	.read = iio_debugfs_read_reg,
444 	.write = iio_debugfs_write_reg,
445 };
446 
447 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
448 {
449 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
450 	debugfs_remove_recursive(iio_dev_opaque->debugfs_dentry);
451 }
452 
453 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
454 {
455 	struct iio_dev_opaque *iio_dev_opaque;
456 
457 	if (indio_dev->info->debugfs_reg_access == NULL)
458 		return;
459 
460 	if (!iio_debugfs_dentry)
461 		return;
462 
463 	iio_dev_opaque = to_iio_dev_opaque(indio_dev);
464 
465 	iio_dev_opaque->debugfs_dentry =
466 		debugfs_create_dir(dev_name(&indio_dev->dev),
467 				   iio_debugfs_dentry);
468 
469 	debugfs_create_file("direct_reg_access", 0644,
470 			    iio_dev_opaque->debugfs_dentry, indio_dev,
471 			    &iio_debugfs_reg_fops);
472 }
473 #else
474 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
475 {
476 }
477 
478 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
479 {
480 }
481 #endif /* CONFIG_DEBUG_FS */
482 
483 static ssize_t iio_read_channel_ext_info(struct device *dev,
484 				     struct device_attribute *attr,
485 				     char *buf)
486 {
487 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
488 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
489 	const struct iio_chan_spec_ext_info *ext_info;
490 
491 	ext_info = &this_attr->c->ext_info[this_attr->address];
492 
493 	return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
494 }
495 
496 static ssize_t iio_write_channel_ext_info(struct device *dev,
497 				     struct device_attribute *attr,
498 				     const char *buf,
499 					 size_t len)
500 {
501 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
502 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
503 	const struct iio_chan_spec_ext_info *ext_info;
504 
505 	ext_info = &this_attr->c->ext_info[this_attr->address];
506 
507 	return ext_info->write(indio_dev, ext_info->private,
508 			       this_attr->c, buf, len);
509 }
510 
511 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
512 	uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
513 {
514 	const struct iio_enum *e = (const struct iio_enum *)priv;
515 	unsigned int i;
516 	size_t len = 0;
517 
518 	if (!e->num_items)
519 		return 0;
520 
521 	for (i = 0; i < e->num_items; ++i) {
522 		if (!e->items[i])
523 			continue;
524 		len += sysfs_emit_at(buf, len, "%s ", e->items[i]);
525 	}
526 
527 	/* replace last space with a newline */
528 	buf[len - 1] = '\n';
529 
530 	return len;
531 }
532 EXPORT_SYMBOL_GPL(iio_enum_available_read);
533 
534 ssize_t iio_enum_read(struct iio_dev *indio_dev,
535 	uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
536 {
537 	const struct iio_enum *e = (const struct iio_enum *)priv;
538 	int i;
539 
540 	if (!e->get)
541 		return -EINVAL;
542 
543 	i = e->get(indio_dev, chan);
544 	if (i < 0)
545 		return i;
546 	else if (i >= e->num_items || !e->items[i])
547 		return -EINVAL;
548 
549 	return sysfs_emit(buf, "%s\n", e->items[i]);
550 }
551 EXPORT_SYMBOL_GPL(iio_enum_read);
552 
553 ssize_t iio_enum_write(struct iio_dev *indio_dev,
554 	uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
555 	size_t len)
556 {
557 	const struct iio_enum *e = (const struct iio_enum *)priv;
558 	int ret;
559 
560 	if (!e->set)
561 		return -EINVAL;
562 
563 	ret = iio_sysfs_match_string_with_gaps(e->items, e->num_items, buf);
564 	if (ret < 0)
565 		return ret;
566 
567 	ret = e->set(indio_dev, chan, ret);
568 	return ret ? ret : len;
569 }
570 EXPORT_SYMBOL_GPL(iio_enum_write);
571 
572 static const struct iio_mount_matrix iio_mount_idmatrix = {
573 	.rotation = {
574 		"1", "0", "0",
575 		"0", "1", "0",
576 		"0", "0", "1"
577 	}
578 };
579 
580 static int iio_setup_mount_idmatrix(const struct device *dev,
581 				    struct iio_mount_matrix *matrix)
582 {
583 	*matrix = iio_mount_idmatrix;
584 	dev_info(dev, "mounting matrix not found: using identity...\n");
585 	return 0;
586 }
587 
588 ssize_t iio_show_mount_matrix(struct iio_dev *indio_dev, uintptr_t priv,
589 			      const struct iio_chan_spec *chan, char *buf)
590 {
591 	const struct iio_mount_matrix *mtx = ((iio_get_mount_matrix_t *)
592 					      priv)(indio_dev, chan);
593 
594 	if (IS_ERR(mtx))
595 		return PTR_ERR(mtx);
596 
597 	if (!mtx)
598 		mtx = &iio_mount_idmatrix;
599 
600 	return sysfs_emit(buf, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
601 			  mtx->rotation[0], mtx->rotation[1], mtx->rotation[2],
602 			  mtx->rotation[3], mtx->rotation[4], mtx->rotation[5],
603 			  mtx->rotation[6], mtx->rotation[7], mtx->rotation[8]);
604 }
605 EXPORT_SYMBOL_GPL(iio_show_mount_matrix);
606 
607 /**
608  * iio_read_mount_matrix() - retrieve iio device mounting matrix from
609  *                           device "mount-matrix" property
610  * @dev:	device the mounting matrix property is assigned to
611  * @matrix:	where to store retrieved matrix
612  *
613  * If device is assigned no mounting matrix property, a default 3x3 identity
614  * matrix will be filled in.
615  *
616  * Return: 0 if success, or a negative error code on failure.
617  */
618 int iio_read_mount_matrix(struct device *dev, struct iio_mount_matrix *matrix)
619 {
620 	size_t len = ARRAY_SIZE(iio_mount_idmatrix.rotation);
621 	int err;
622 
623 	err = device_property_read_string_array(dev, "mount-matrix", matrix->rotation, len);
624 	if (err == len)
625 		return 0;
626 
627 	if (err >= 0)
628 		/* Invalid number of matrix entries. */
629 		return -EINVAL;
630 
631 	if (err != -EINVAL)
632 		/* Invalid matrix declaration format. */
633 		return err;
634 
635 	/* Matrix was not declared at all: fallback to identity. */
636 	return iio_setup_mount_idmatrix(dev, matrix);
637 }
638 EXPORT_SYMBOL(iio_read_mount_matrix);
639 
640 static ssize_t __iio_format_value(char *buf, size_t offset, unsigned int type,
641 				  int size, const int *vals)
642 {
643 	int tmp0, tmp1;
644 	s64 tmp2;
645 	bool scale_db = false;
646 
647 	switch (type) {
648 	case IIO_VAL_INT:
649 		return sysfs_emit_at(buf, offset, "%d", vals[0]);
650 	case IIO_VAL_INT_PLUS_MICRO_DB:
651 		scale_db = true;
652 		fallthrough;
653 	case IIO_VAL_INT_PLUS_MICRO:
654 		if (vals[1] < 0)
655 			return sysfs_emit_at(buf, offset, "-%d.%06u%s",
656 					     abs(vals[0]), -vals[1],
657 					     scale_db ? " dB" : "");
658 		else
659 			return sysfs_emit_at(buf, offset, "%d.%06u%s", vals[0],
660 					     vals[1], scale_db ? " dB" : "");
661 	case IIO_VAL_INT_PLUS_NANO:
662 		if (vals[1] < 0)
663 			return sysfs_emit_at(buf, offset, "-%d.%09u",
664 					     abs(vals[0]), -vals[1]);
665 		else
666 			return sysfs_emit_at(buf, offset, "%d.%09u", vals[0],
667 					     vals[1]);
668 	case IIO_VAL_FRACTIONAL:
669 		tmp2 = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
670 		tmp1 = vals[1];
671 		tmp0 = (int)div_s64_rem(tmp2, 1000000000, &tmp1);
672 		if ((tmp2 < 0) && (tmp0 == 0))
673 			return sysfs_emit_at(buf, offset, "-0.%09u", abs(tmp1));
674 		else
675 			return sysfs_emit_at(buf, offset, "%d.%09u", tmp0,
676 					     abs(tmp1));
677 	case IIO_VAL_FRACTIONAL_LOG2:
678 		tmp2 = shift_right((s64)vals[0] * 1000000000LL, vals[1]);
679 		tmp0 = (int)div_s64_rem(tmp2, 1000000000LL, &tmp1);
680 		if (tmp0 == 0 && tmp2 < 0)
681 			return sysfs_emit_at(buf, offset, "-0.%09u", abs(tmp1));
682 		else
683 			return sysfs_emit_at(buf, offset, "%d.%09u", tmp0,
684 					     abs(tmp1));
685 	case IIO_VAL_INT_MULTIPLE:
686 	{
687 		int i;
688 		int l = 0;
689 
690 		for (i = 0; i < size; ++i)
691 			l += sysfs_emit_at(buf, offset + l, "%d ", vals[i]);
692 		return l;
693 	}
694 	case IIO_VAL_CHAR:
695 		return sysfs_emit_at(buf, offset, "%c", (char)vals[0]);
696 	case IIO_VAL_INT_64:
697 		tmp2 = (s64)((((u64)vals[1]) << 32) | (u32)vals[0]);
698 		return sysfs_emit_at(buf, offset, "%lld", tmp2);
699 	default:
700 		return 0;
701 	}
702 }
703 
704 /**
705  * iio_format_value() - Formats a IIO value into its string representation
706  * @buf:	The buffer to which the formatted value gets written
707  *		which is assumed to be big enough (i.e. PAGE_SIZE).
708  * @type:	One of the IIO_VAL_* constants. This decides how the val
709  *		and val2 parameters are formatted.
710  * @size:	Number of IIO value entries contained in vals
711  * @vals:	Pointer to the values, exact meaning depends on the
712  *		type parameter.
713  *
714  * Return: 0 by default, a negative number on failure or the
715  *	   total number of characters written for a type that belongs
716  *	   to the IIO_VAL_* constant.
717  */
718 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
719 {
720 	ssize_t len;
721 
722 	len = __iio_format_value(buf, 0, type, size, vals);
723 	if (len >= PAGE_SIZE - 1)
724 		return -EFBIG;
725 
726 	return len + sysfs_emit_at(buf, len, "\n");
727 }
728 EXPORT_SYMBOL_GPL(iio_format_value);
729 
730 static ssize_t iio_read_channel_label(struct device *dev,
731 				      struct device_attribute *attr,
732 				      char *buf)
733 {
734 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
735 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
736 
737 	if (indio_dev->info->read_label)
738 		return indio_dev->info->read_label(indio_dev, this_attr->c, buf);
739 
740 	if (this_attr->c->extend_name)
741 		return sysfs_emit(buf, "%s\n", this_attr->c->extend_name);
742 
743 	return -EINVAL;
744 }
745 
746 static ssize_t iio_read_channel_info(struct device *dev,
747 				     struct device_attribute *attr,
748 				     char *buf)
749 {
750 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
751 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
752 	int vals[INDIO_MAX_RAW_ELEMENTS];
753 	int ret;
754 	int val_len = 2;
755 
756 	if (indio_dev->info->read_raw_multi)
757 		ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
758 							INDIO_MAX_RAW_ELEMENTS,
759 							vals, &val_len,
760 							this_attr->address);
761 	else
762 		ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
763 				    &vals[0], &vals[1], this_attr->address);
764 
765 	if (ret < 0)
766 		return ret;
767 
768 	return iio_format_value(buf, ret, val_len, vals);
769 }
770 
771 static ssize_t iio_format_list(char *buf, const int *vals, int type, int length,
772 			       const char *prefix, const char *suffix)
773 {
774 	ssize_t len;
775 	int stride;
776 	int i;
777 
778 	switch (type) {
779 	case IIO_VAL_INT:
780 		stride = 1;
781 		break;
782 	default:
783 		stride = 2;
784 		break;
785 	}
786 
787 	len = sysfs_emit(buf, prefix);
788 
789 	for (i = 0; i <= length - stride; i += stride) {
790 		if (i != 0) {
791 			len += sysfs_emit_at(buf, len, " ");
792 			if (len >= PAGE_SIZE)
793 				return -EFBIG;
794 		}
795 
796 		len += __iio_format_value(buf, len, type, stride, &vals[i]);
797 		if (len >= PAGE_SIZE)
798 			return -EFBIG;
799 	}
800 
801 	len += sysfs_emit_at(buf, len, "%s\n", suffix);
802 
803 	return len;
804 }
805 
806 static ssize_t iio_format_avail_list(char *buf, const int *vals,
807 				     int type, int length)
808 {
809 
810 	return iio_format_list(buf, vals, type, length, "", "");
811 }
812 
813 static ssize_t iio_format_avail_range(char *buf, const int *vals, int type)
814 {
815 	int length;
816 
817 	/*
818 	 * length refers to the array size , not the number of elements.
819 	 * The purpose is to print the range [min , step ,max] so length should
820 	 * be 3 in case of int, and 6 for other types.
821 	 */
822 	switch (type) {
823 	case IIO_VAL_INT:
824 		length = 3;
825 		break;
826 	default:
827 		length = 6;
828 		break;
829 	}
830 
831 	return iio_format_list(buf, vals, type, length, "[", "]");
832 }
833 
834 static ssize_t iio_read_channel_info_avail(struct device *dev,
835 					   struct device_attribute *attr,
836 					   char *buf)
837 {
838 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
839 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
840 	const int *vals;
841 	int ret;
842 	int length;
843 	int type;
844 
845 	ret = indio_dev->info->read_avail(indio_dev, this_attr->c,
846 					  &vals, &type, &length,
847 					  this_attr->address);
848 
849 	if (ret < 0)
850 		return ret;
851 	switch (ret) {
852 	case IIO_AVAIL_LIST:
853 		return iio_format_avail_list(buf, vals, type, length);
854 	case IIO_AVAIL_RANGE:
855 		return iio_format_avail_range(buf, vals, type);
856 	default:
857 		return -EINVAL;
858 	}
859 }
860 
861 /**
862  * __iio_str_to_fixpoint() - Parse a fixed-point number from a string
863  * @str: The string to parse
864  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
865  * @integer: The integer part of the number
866  * @fract: The fractional part of the number
867  * @scale_db: True if this should parse as dB
868  *
869  * Returns 0 on success, or a negative error code if the string could not be
870  * parsed.
871  */
872 static int __iio_str_to_fixpoint(const char *str, int fract_mult,
873 				 int *integer, int *fract, bool scale_db)
874 {
875 	int i = 0, f = 0;
876 	bool integer_part = true, negative = false;
877 
878 	if (fract_mult == 0) {
879 		*fract = 0;
880 
881 		return kstrtoint(str, 0, integer);
882 	}
883 
884 	if (str[0] == '-') {
885 		negative = true;
886 		str++;
887 	} else if (str[0] == '+') {
888 		str++;
889 	}
890 
891 	while (*str) {
892 		if ('0' <= *str && *str <= '9') {
893 			if (integer_part) {
894 				i = i * 10 + *str - '0';
895 			} else {
896 				f += fract_mult * (*str - '0');
897 				fract_mult /= 10;
898 			}
899 		} else if (*str == '\n') {
900 			if (*(str + 1) == '\0')
901 				break;
902 			return -EINVAL;
903 		} else if (!strncmp(str, " dB", sizeof(" dB") - 1) && scale_db) {
904 			/* Ignore the dB suffix */
905 			str += sizeof(" dB") - 1;
906 			continue;
907 		} else if (!strncmp(str, "dB", sizeof("dB") - 1) && scale_db) {
908 			/* Ignore the dB suffix */
909 			str += sizeof("dB") - 1;
910 			continue;
911 		} else if (*str == '.' && integer_part) {
912 			integer_part = false;
913 		} else {
914 			return -EINVAL;
915 		}
916 		str++;
917 	}
918 
919 	if (negative) {
920 		if (i)
921 			i = -i;
922 		else
923 			f = -f;
924 	}
925 
926 	*integer = i;
927 	*fract = f;
928 
929 	return 0;
930 }
931 
932 /**
933  * iio_str_to_fixpoint() - Parse a fixed-point number from a string
934  * @str: The string to parse
935  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
936  * @integer: The integer part of the number
937  * @fract: The fractional part of the number
938  *
939  * Returns 0 on success, or a negative error code if the string could not be
940  * parsed.
941  */
942 int iio_str_to_fixpoint(const char *str, int fract_mult,
943 			int *integer, int *fract)
944 {
945 	return __iio_str_to_fixpoint(str, fract_mult, integer, fract, false);
946 }
947 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
948 
949 static ssize_t iio_write_channel_info(struct device *dev,
950 				      struct device_attribute *attr,
951 				      const char *buf,
952 				      size_t len)
953 {
954 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
955 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
956 	int ret, fract_mult = 100000;
957 	int integer, fract = 0;
958 	bool is_char = false;
959 	bool scale_db = false;
960 
961 	/* Assumes decimal - precision based on number of digits */
962 	if (!indio_dev->info->write_raw)
963 		return -EINVAL;
964 
965 	if (indio_dev->info->write_raw_get_fmt)
966 		switch (indio_dev->info->write_raw_get_fmt(indio_dev,
967 			this_attr->c, this_attr->address)) {
968 		case IIO_VAL_INT:
969 			fract_mult = 0;
970 			break;
971 		case IIO_VAL_INT_PLUS_MICRO_DB:
972 			scale_db = true;
973 			fallthrough;
974 		case IIO_VAL_INT_PLUS_MICRO:
975 			fract_mult = 100000;
976 			break;
977 		case IIO_VAL_INT_PLUS_NANO:
978 			fract_mult = 100000000;
979 			break;
980 		case IIO_VAL_CHAR:
981 			is_char = true;
982 			break;
983 		default:
984 			return -EINVAL;
985 		}
986 
987 	if (is_char) {
988 		char ch;
989 
990 		if (sscanf(buf, "%c", &ch) != 1)
991 			return -EINVAL;
992 		integer = ch;
993 	} else {
994 		ret = __iio_str_to_fixpoint(buf, fract_mult, &integer, &fract,
995 					    scale_db);
996 		if (ret)
997 			return ret;
998 	}
999 
1000 	ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
1001 					 integer, fract, this_attr->address);
1002 	if (ret)
1003 		return ret;
1004 
1005 	return len;
1006 }
1007 
1008 static
1009 int __iio_device_attr_init(struct device_attribute *dev_attr,
1010 			   const char *postfix,
1011 			   struct iio_chan_spec const *chan,
1012 			   ssize_t (*readfunc)(struct device *dev,
1013 					       struct device_attribute *attr,
1014 					       char *buf),
1015 			   ssize_t (*writefunc)(struct device *dev,
1016 						struct device_attribute *attr,
1017 						const char *buf,
1018 						size_t len),
1019 			   enum iio_shared_by shared_by)
1020 {
1021 	int ret = 0;
1022 	char *name = NULL;
1023 	char *full_postfix;
1024 	sysfs_attr_init(&dev_attr->attr);
1025 
1026 	/* Build up postfix of <extend_name>_<modifier>_postfix */
1027 	if (chan->modified && (shared_by == IIO_SEPARATE)) {
1028 		if (chan->extend_name)
1029 			full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
1030 						 iio_modifier_names[chan
1031 								    ->channel2],
1032 						 chan->extend_name,
1033 						 postfix);
1034 		else
1035 			full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
1036 						 iio_modifier_names[chan
1037 								    ->channel2],
1038 						 postfix);
1039 	} else {
1040 		if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
1041 			full_postfix = kstrdup(postfix, GFP_KERNEL);
1042 		else
1043 			full_postfix = kasprintf(GFP_KERNEL,
1044 						 "%s_%s",
1045 						 chan->extend_name,
1046 						 postfix);
1047 	}
1048 	if (full_postfix == NULL)
1049 		return -ENOMEM;
1050 
1051 	if (chan->differential) { /* Differential can not have modifier */
1052 		switch (shared_by) {
1053 		case IIO_SHARED_BY_ALL:
1054 			name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1055 			break;
1056 		case IIO_SHARED_BY_DIR:
1057 			name = kasprintf(GFP_KERNEL, "%s_%s",
1058 						iio_direction[chan->output],
1059 						full_postfix);
1060 			break;
1061 		case IIO_SHARED_BY_TYPE:
1062 			name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
1063 					    iio_direction[chan->output],
1064 					    iio_chan_type_name_spec[chan->type],
1065 					    iio_chan_type_name_spec[chan->type],
1066 					    full_postfix);
1067 			break;
1068 		case IIO_SEPARATE:
1069 			if (!chan->indexed) {
1070 				WARN(1, "Differential channels must be indexed\n");
1071 				ret = -EINVAL;
1072 				goto error_free_full_postfix;
1073 			}
1074 			name = kasprintf(GFP_KERNEL,
1075 					    "%s_%s%d-%s%d_%s",
1076 					    iio_direction[chan->output],
1077 					    iio_chan_type_name_spec[chan->type],
1078 					    chan->channel,
1079 					    iio_chan_type_name_spec[chan->type],
1080 					    chan->channel2,
1081 					    full_postfix);
1082 			break;
1083 		}
1084 	} else { /* Single ended */
1085 		switch (shared_by) {
1086 		case IIO_SHARED_BY_ALL:
1087 			name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1088 			break;
1089 		case IIO_SHARED_BY_DIR:
1090 			name = kasprintf(GFP_KERNEL, "%s_%s",
1091 						iio_direction[chan->output],
1092 						full_postfix);
1093 			break;
1094 		case IIO_SHARED_BY_TYPE:
1095 			name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1096 					    iio_direction[chan->output],
1097 					    iio_chan_type_name_spec[chan->type],
1098 					    full_postfix);
1099 			break;
1100 
1101 		case IIO_SEPARATE:
1102 			if (chan->indexed)
1103 				name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
1104 						    iio_direction[chan->output],
1105 						    iio_chan_type_name_spec[chan->type],
1106 						    chan->channel,
1107 						    full_postfix);
1108 			else
1109 				name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1110 						    iio_direction[chan->output],
1111 						    iio_chan_type_name_spec[chan->type],
1112 						    full_postfix);
1113 			break;
1114 		}
1115 	}
1116 	if (name == NULL) {
1117 		ret = -ENOMEM;
1118 		goto error_free_full_postfix;
1119 	}
1120 	dev_attr->attr.name = name;
1121 
1122 	if (readfunc) {
1123 		dev_attr->attr.mode |= 0444;
1124 		dev_attr->show = readfunc;
1125 	}
1126 
1127 	if (writefunc) {
1128 		dev_attr->attr.mode |= 0200;
1129 		dev_attr->store = writefunc;
1130 	}
1131 
1132 error_free_full_postfix:
1133 	kfree(full_postfix);
1134 
1135 	return ret;
1136 }
1137 
1138 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
1139 {
1140 	kfree(dev_attr->attr.name);
1141 }
1142 
1143 int __iio_add_chan_devattr(const char *postfix,
1144 			   struct iio_chan_spec const *chan,
1145 			   ssize_t (*readfunc)(struct device *dev,
1146 					       struct device_attribute *attr,
1147 					       char *buf),
1148 			   ssize_t (*writefunc)(struct device *dev,
1149 						struct device_attribute *attr,
1150 						const char *buf,
1151 						size_t len),
1152 			   u64 mask,
1153 			   enum iio_shared_by shared_by,
1154 			   struct device *dev,
1155 			   struct iio_buffer *buffer,
1156 			   struct list_head *attr_list)
1157 {
1158 	int ret;
1159 	struct iio_dev_attr *iio_attr, *t;
1160 
1161 	iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
1162 	if (iio_attr == NULL)
1163 		return -ENOMEM;
1164 	ret = __iio_device_attr_init(&iio_attr->dev_attr,
1165 				     postfix, chan,
1166 				     readfunc, writefunc, shared_by);
1167 	if (ret)
1168 		goto error_iio_dev_attr_free;
1169 	iio_attr->c = chan;
1170 	iio_attr->address = mask;
1171 	iio_attr->buffer = buffer;
1172 	list_for_each_entry(t, attr_list, l)
1173 		if (strcmp(t->dev_attr.attr.name,
1174 			   iio_attr->dev_attr.attr.name) == 0) {
1175 			if (shared_by == IIO_SEPARATE)
1176 				dev_err(dev, "tried to double register : %s\n",
1177 					t->dev_attr.attr.name);
1178 			ret = -EBUSY;
1179 			goto error_device_attr_deinit;
1180 		}
1181 	list_add(&iio_attr->l, attr_list);
1182 
1183 	return 0;
1184 
1185 error_device_attr_deinit:
1186 	__iio_device_attr_deinit(&iio_attr->dev_attr);
1187 error_iio_dev_attr_free:
1188 	kfree(iio_attr);
1189 	return ret;
1190 }
1191 
1192 static int iio_device_add_channel_label(struct iio_dev *indio_dev,
1193 					 struct iio_chan_spec const *chan)
1194 {
1195 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1196 	int ret;
1197 
1198 	if (!indio_dev->info->read_label && !chan->extend_name)
1199 		return 0;
1200 
1201 	ret = __iio_add_chan_devattr("label",
1202 				     chan,
1203 				     &iio_read_channel_label,
1204 				     NULL,
1205 				     0,
1206 				     IIO_SEPARATE,
1207 				     &indio_dev->dev,
1208 				     NULL,
1209 				     &iio_dev_opaque->channel_attr_list);
1210 	if (ret < 0)
1211 		return ret;
1212 
1213 	return 1;
1214 }
1215 
1216 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
1217 					 struct iio_chan_spec const *chan,
1218 					 enum iio_shared_by shared_by,
1219 					 const long *infomask)
1220 {
1221 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1222 	int i, ret, attrcount = 0;
1223 
1224 	for_each_set_bit(i, infomask, sizeof(*infomask)*8) {
1225 		if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1226 			return -EINVAL;
1227 		ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
1228 					     chan,
1229 					     &iio_read_channel_info,
1230 					     &iio_write_channel_info,
1231 					     i,
1232 					     shared_by,
1233 					     &indio_dev->dev,
1234 					     NULL,
1235 					     &iio_dev_opaque->channel_attr_list);
1236 		if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1237 			continue;
1238 		else if (ret < 0)
1239 			return ret;
1240 		attrcount++;
1241 	}
1242 
1243 	return attrcount;
1244 }
1245 
1246 static int iio_device_add_info_mask_type_avail(struct iio_dev *indio_dev,
1247 					       struct iio_chan_spec const *chan,
1248 					       enum iio_shared_by shared_by,
1249 					       const long *infomask)
1250 {
1251 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1252 	int i, ret, attrcount = 0;
1253 	char *avail_postfix;
1254 
1255 	for_each_set_bit(i, infomask, sizeof(*infomask) * 8) {
1256 		if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1257 			return -EINVAL;
1258 		avail_postfix = kasprintf(GFP_KERNEL,
1259 					  "%s_available",
1260 					  iio_chan_info_postfix[i]);
1261 		if (!avail_postfix)
1262 			return -ENOMEM;
1263 
1264 		ret = __iio_add_chan_devattr(avail_postfix,
1265 					     chan,
1266 					     &iio_read_channel_info_avail,
1267 					     NULL,
1268 					     i,
1269 					     shared_by,
1270 					     &indio_dev->dev,
1271 					     NULL,
1272 					     &iio_dev_opaque->channel_attr_list);
1273 		kfree(avail_postfix);
1274 		if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1275 			continue;
1276 		else if (ret < 0)
1277 			return ret;
1278 		attrcount++;
1279 	}
1280 
1281 	return attrcount;
1282 }
1283 
1284 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
1285 					struct iio_chan_spec const *chan)
1286 {
1287 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1288 	int ret, attrcount = 0;
1289 	const struct iio_chan_spec_ext_info *ext_info;
1290 
1291 	if (chan->channel < 0)
1292 		return 0;
1293 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1294 					    IIO_SEPARATE,
1295 					    &chan->info_mask_separate);
1296 	if (ret < 0)
1297 		return ret;
1298 	attrcount += ret;
1299 
1300 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1301 						  IIO_SEPARATE,
1302 						  &chan->
1303 						  info_mask_separate_available);
1304 	if (ret < 0)
1305 		return ret;
1306 	attrcount += ret;
1307 
1308 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1309 					    IIO_SHARED_BY_TYPE,
1310 					    &chan->info_mask_shared_by_type);
1311 	if (ret < 0)
1312 		return ret;
1313 	attrcount += ret;
1314 
1315 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1316 						  IIO_SHARED_BY_TYPE,
1317 						  &chan->
1318 						  info_mask_shared_by_type_available);
1319 	if (ret < 0)
1320 		return ret;
1321 	attrcount += ret;
1322 
1323 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1324 					    IIO_SHARED_BY_DIR,
1325 					    &chan->info_mask_shared_by_dir);
1326 	if (ret < 0)
1327 		return ret;
1328 	attrcount += ret;
1329 
1330 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1331 						  IIO_SHARED_BY_DIR,
1332 						  &chan->info_mask_shared_by_dir_available);
1333 	if (ret < 0)
1334 		return ret;
1335 	attrcount += ret;
1336 
1337 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1338 					    IIO_SHARED_BY_ALL,
1339 					    &chan->info_mask_shared_by_all);
1340 	if (ret < 0)
1341 		return ret;
1342 	attrcount += ret;
1343 
1344 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1345 						  IIO_SHARED_BY_ALL,
1346 						  &chan->info_mask_shared_by_all_available);
1347 	if (ret < 0)
1348 		return ret;
1349 	attrcount += ret;
1350 
1351 	ret = iio_device_add_channel_label(indio_dev, chan);
1352 	if (ret < 0)
1353 		return ret;
1354 	attrcount += ret;
1355 
1356 	if (chan->ext_info) {
1357 		unsigned int i = 0;
1358 		for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
1359 			ret = __iio_add_chan_devattr(ext_info->name,
1360 					chan,
1361 					ext_info->read ?
1362 					    &iio_read_channel_ext_info : NULL,
1363 					ext_info->write ?
1364 					    &iio_write_channel_ext_info : NULL,
1365 					i,
1366 					ext_info->shared,
1367 					&indio_dev->dev,
1368 					NULL,
1369 					&iio_dev_opaque->channel_attr_list);
1370 			i++;
1371 			if (ret == -EBUSY && ext_info->shared)
1372 				continue;
1373 
1374 			if (ret)
1375 				return ret;
1376 
1377 			attrcount++;
1378 		}
1379 	}
1380 
1381 	return attrcount;
1382 }
1383 
1384 /**
1385  * iio_free_chan_devattr_list() - Free a list of IIO device attributes
1386  * @attr_list: List of IIO device attributes
1387  *
1388  * This function frees the memory allocated for each of the IIO device
1389  * attributes in the list.
1390  */
1391 void iio_free_chan_devattr_list(struct list_head *attr_list)
1392 {
1393 	struct iio_dev_attr *p, *n;
1394 
1395 	list_for_each_entry_safe(p, n, attr_list, l) {
1396 		kfree_const(p->dev_attr.attr.name);
1397 		list_del(&p->l);
1398 		kfree(p);
1399 	}
1400 }
1401 
1402 static ssize_t name_show(struct device *dev, struct device_attribute *attr,
1403 			 char *buf)
1404 {
1405 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1406 	return sysfs_emit(buf, "%s\n", indio_dev->name);
1407 }
1408 
1409 static DEVICE_ATTR_RO(name);
1410 
1411 static ssize_t label_show(struct device *dev, struct device_attribute *attr,
1412 			  char *buf)
1413 {
1414 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1415 	return sysfs_emit(buf, "%s\n", indio_dev->label);
1416 }
1417 
1418 static DEVICE_ATTR_RO(label);
1419 
1420 static ssize_t current_timestamp_clock_show(struct device *dev,
1421 					    struct device_attribute *attr,
1422 					    char *buf)
1423 {
1424 	const struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1425 	const clockid_t clk = iio_device_get_clock(indio_dev);
1426 	const char *name;
1427 	ssize_t sz;
1428 
1429 	switch (clk) {
1430 	case CLOCK_REALTIME:
1431 		name = "realtime\n";
1432 		sz = sizeof("realtime\n");
1433 		break;
1434 	case CLOCK_MONOTONIC:
1435 		name = "monotonic\n";
1436 		sz = sizeof("monotonic\n");
1437 		break;
1438 	case CLOCK_MONOTONIC_RAW:
1439 		name = "monotonic_raw\n";
1440 		sz = sizeof("monotonic_raw\n");
1441 		break;
1442 	case CLOCK_REALTIME_COARSE:
1443 		name = "realtime_coarse\n";
1444 		sz = sizeof("realtime_coarse\n");
1445 		break;
1446 	case CLOCK_MONOTONIC_COARSE:
1447 		name = "monotonic_coarse\n";
1448 		sz = sizeof("monotonic_coarse\n");
1449 		break;
1450 	case CLOCK_BOOTTIME:
1451 		name = "boottime\n";
1452 		sz = sizeof("boottime\n");
1453 		break;
1454 	case CLOCK_TAI:
1455 		name = "tai\n";
1456 		sz = sizeof("tai\n");
1457 		break;
1458 	default:
1459 		BUG();
1460 	}
1461 
1462 	memcpy(buf, name, sz);
1463 	return sz;
1464 }
1465 
1466 static ssize_t current_timestamp_clock_store(struct device *dev,
1467 					     struct device_attribute *attr,
1468 					     const char *buf, size_t len)
1469 {
1470 	clockid_t clk;
1471 	int ret;
1472 
1473 	if (sysfs_streq(buf, "realtime"))
1474 		clk = CLOCK_REALTIME;
1475 	else if (sysfs_streq(buf, "monotonic"))
1476 		clk = CLOCK_MONOTONIC;
1477 	else if (sysfs_streq(buf, "monotonic_raw"))
1478 		clk = CLOCK_MONOTONIC_RAW;
1479 	else if (sysfs_streq(buf, "realtime_coarse"))
1480 		clk = CLOCK_REALTIME_COARSE;
1481 	else if (sysfs_streq(buf, "monotonic_coarse"))
1482 		clk = CLOCK_MONOTONIC_COARSE;
1483 	else if (sysfs_streq(buf, "boottime"))
1484 		clk = CLOCK_BOOTTIME;
1485 	else if (sysfs_streq(buf, "tai"))
1486 		clk = CLOCK_TAI;
1487 	else
1488 		return -EINVAL;
1489 
1490 	ret = iio_device_set_clock(dev_to_iio_dev(dev), clk);
1491 	if (ret)
1492 		return ret;
1493 
1494 	return len;
1495 }
1496 
1497 int iio_device_register_sysfs_group(struct iio_dev *indio_dev,
1498 				    const struct attribute_group *group)
1499 {
1500 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1501 	const struct attribute_group **new, **old = iio_dev_opaque->groups;
1502 	unsigned int cnt = iio_dev_opaque->groupcounter;
1503 
1504 	new = krealloc(old, sizeof(*new) * (cnt + 2), GFP_KERNEL);
1505 	if (!new)
1506 		return -ENOMEM;
1507 
1508 	new[iio_dev_opaque->groupcounter++] = group;
1509 	new[iio_dev_opaque->groupcounter] = NULL;
1510 
1511 	iio_dev_opaque->groups = new;
1512 
1513 	return 0;
1514 }
1515 
1516 static DEVICE_ATTR_RW(current_timestamp_clock);
1517 
1518 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
1519 {
1520 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1521 	int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
1522 	struct iio_dev_attr *p;
1523 	struct attribute **attr, *clk = NULL;
1524 
1525 	/* First count elements in any existing group */
1526 	if (indio_dev->info->attrs) {
1527 		attr = indio_dev->info->attrs->attrs;
1528 		while (*attr++ != NULL)
1529 			attrcount_orig++;
1530 	}
1531 	attrcount = attrcount_orig;
1532 	/*
1533 	 * New channel registration method - relies on the fact a group does
1534 	 * not need to be initialized if its name is NULL.
1535 	 */
1536 	if (indio_dev->channels)
1537 		for (i = 0; i < indio_dev->num_channels; i++) {
1538 			const struct iio_chan_spec *chan =
1539 				&indio_dev->channels[i];
1540 
1541 			if (chan->type == IIO_TIMESTAMP)
1542 				clk = &dev_attr_current_timestamp_clock.attr;
1543 
1544 			ret = iio_device_add_channel_sysfs(indio_dev, chan);
1545 			if (ret < 0)
1546 				goto error_clear_attrs;
1547 			attrcount += ret;
1548 		}
1549 
1550 	if (iio_dev_opaque->event_interface)
1551 		clk = &dev_attr_current_timestamp_clock.attr;
1552 
1553 	if (indio_dev->name)
1554 		attrcount++;
1555 	if (indio_dev->label)
1556 		attrcount++;
1557 	if (clk)
1558 		attrcount++;
1559 
1560 	iio_dev_opaque->chan_attr_group.attrs =
1561 		kcalloc(attrcount + 1,
1562 			sizeof(iio_dev_opaque->chan_attr_group.attrs[0]),
1563 			GFP_KERNEL);
1564 	if (iio_dev_opaque->chan_attr_group.attrs == NULL) {
1565 		ret = -ENOMEM;
1566 		goto error_clear_attrs;
1567 	}
1568 	/* Copy across original attributes */
1569 	if (indio_dev->info->attrs) {
1570 		memcpy(iio_dev_opaque->chan_attr_group.attrs,
1571 		       indio_dev->info->attrs->attrs,
1572 		       sizeof(iio_dev_opaque->chan_attr_group.attrs[0])
1573 		       *attrcount_orig);
1574 		iio_dev_opaque->chan_attr_group.is_visible =
1575 			indio_dev->info->attrs->is_visible;
1576 	}
1577 	attrn = attrcount_orig;
1578 	/* Add all elements from the list. */
1579 	list_for_each_entry(p, &iio_dev_opaque->channel_attr_list, l)
1580 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1581 	if (indio_dev->name)
1582 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
1583 	if (indio_dev->label)
1584 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_label.attr;
1585 	if (clk)
1586 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = clk;
1587 
1588 	ret = iio_device_register_sysfs_group(indio_dev,
1589 					      &iio_dev_opaque->chan_attr_group);
1590 	if (ret)
1591 		goto error_clear_attrs;
1592 
1593 	return 0;
1594 
1595 error_clear_attrs:
1596 	iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1597 
1598 	return ret;
1599 }
1600 
1601 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
1602 {
1603 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1604 
1605 	iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1606 	kfree(iio_dev_opaque->chan_attr_group.attrs);
1607 	iio_dev_opaque->chan_attr_group.attrs = NULL;
1608 	kfree(iio_dev_opaque->groups);
1609 	iio_dev_opaque->groups = NULL;
1610 }
1611 
1612 static void iio_dev_release(struct device *device)
1613 {
1614 	struct iio_dev *indio_dev = dev_to_iio_dev(device);
1615 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1616 
1617 	if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1618 		iio_device_unregister_trigger_consumer(indio_dev);
1619 	iio_device_unregister_eventset(indio_dev);
1620 	iio_device_unregister_sysfs(indio_dev);
1621 
1622 	iio_device_detach_buffers(indio_dev);
1623 
1624 	ida_free(&iio_ida, iio_dev_opaque->id);
1625 	kfree(iio_dev_opaque);
1626 }
1627 
1628 const struct device_type iio_device_type = {
1629 	.name = "iio_device",
1630 	.release = iio_dev_release,
1631 };
1632 
1633 /**
1634  * iio_device_alloc() - allocate an iio_dev from a driver
1635  * @parent:		Parent device.
1636  * @sizeof_priv:	Space to allocate for private structure.
1637  **/
1638 struct iio_dev *iio_device_alloc(struct device *parent, int sizeof_priv)
1639 {
1640 	struct iio_dev_opaque *iio_dev_opaque;
1641 	struct iio_dev *indio_dev;
1642 	size_t alloc_size;
1643 
1644 	alloc_size = sizeof(struct iio_dev_opaque);
1645 	if (sizeof_priv) {
1646 		alloc_size = ALIGN(alloc_size, IIO_DMA_MINALIGN);
1647 		alloc_size += sizeof_priv;
1648 	}
1649 
1650 	iio_dev_opaque = kzalloc(alloc_size, GFP_KERNEL);
1651 	if (!iio_dev_opaque)
1652 		return NULL;
1653 
1654 	indio_dev = &iio_dev_opaque->indio_dev;
1655 	indio_dev->priv = (char *)iio_dev_opaque +
1656 		ALIGN(sizeof(struct iio_dev_opaque), IIO_DMA_MINALIGN);
1657 
1658 	indio_dev->dev.parent = parent;
1659 	indio_dev->dev.type = &iio_device_type;
1660 	indio_dev->dev.bus = &iio_bus_type;
1661 	device_initialize(&indio_dev->dev);
1662 	mutex_init(&indio_dev->mlock);
1663 	mutex_init(&iio_dev_opaque->info_exist_lock);
1664 	INIT_LIST_HEAD(&iio_dev_opaque->channel_attr_list);
1665 
1666 	iio_dev_opaque->id = ida_alloc(&iio_ida, GFP_KERNEL);
1667 	if (iio_dev_opaque->id < 0) {
1668 		/* cannot use a dev_err as the name isn't available */
1669 		pr_err("failed to get device id\n");
1670 		kfree(iio_dev_opaque);
1671 		return NULL;
1672 	}
1673 
1674 	if (dev_set_name(&indio_dev->dev, "iio:device%d", iio_dev_opaque->id)) {
1675 		ida_free(&iio_ida, iio_dev_opaque->id);
1676 		kfree(iio_dev_opaque);
1677 		return NULL;
1678 	}
1679 
1680 	INIT_LIST_HEAD(&iio_dev_opaque->buffer_list);
1681 	INIT_LIST_HEAD(&iio_dev_opaque->ioctl_handlers);
1682 
1683 	return indio_dev;
1684 }
1685 EXPORT_SYMBOL(iio_device_alloc);
1686 
1687 /**
1688  * iio_device_free() - free an iio_dev from a driver
1689  * @dev:		the iio_dev associated with the device
1690  **/
1691 void iio_device_free(struct iio_dev *dev)
1692 {
1693 	if (dev)
1694 		put_device(&dev->dev);
1695 }
1696 EXPORT_SYMBOL(iio_device_free);
1697 
1698 static void devm_iio_device_release(void *iio_dev)
1699 {
1700 	iio_device_free(iio_dev);
1701 }
1702 
1703 /**
1704  * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1705  * @parent:		Device to allocate iio_dev for, and parent for this IIO device
1706  * @sizeof_priv:	Space to allocate for private structure.
1707  *
1708  * Managed iio_device_alloc. iio_dev allocated with this function is
1709  * automatically freed on driver detach.
1710  *
1711  * RETURNS:
1712  * Pointer to allocated iio_dev on success, NULL on failure.
1713  */
1714 struct iio_dev *devm_iio_device_alloc(struct device *parent, int sizeof_priv)
1715 {
1716 	struct iio_dev *iio_dev;
1717 	int ret;
1718 
1719 	iio_dev = iio_device_alloc(parent, sizeof_priv);
1720 	if (!iio_dev)
1721 		return NULL;
1722 
1723 	ret = devm_add_action_or_reset(parent, devm_iio_device_release,
1724 				       iio_dev);
1725 	if (ret)
1726 		return NULL;
1727 
1728 	return iio_dev;
1729 }
1730 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1731 
1732 /**
1733  * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1734  * @inode:	Inode structure for identifying the device in the file system
1735  * @filp:	File structure for iio device used to keep and later access
1736  *		private data
1737  *
1738  * Return: 0 on success or -EBUSY if the device is already opened
1739  **/
1740 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1741 {
1742 	struct iio_dev_opaque *iio_dev_opaque =
1743 		container_of(inode->i_cdev, struct iio_dev_opaque, chrdev);
1744 	struct iio_dev *indio_dev = &iio_dev_opaque->indio_dev;
1745 	struct iio_dev_buffer_pair *ib;
1746 
1747 	if (test_and_set_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags))
1748 		return -EBUSY;
1749 
1750 	iio_device_get(indio_dev);
1751 
1752 	ib = kmalloc(sizeof(*ib), GFP_KERNEL);
1753 	if (!ib) {
1754 		iio_device_put(indio_dev);
1755 		clear_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags);
1756 		return -ENOMEM;
1757 	}
1758 
1759 	ib->indio_dev = indio_dev;
1760 	ib->buffer = indio_dev->buffer;
1761 
1762 	filp->private_data = ib;
1763 
1764 	return 0;
1765 }
1766 
1767 /**
1768  * iio_chrdev_release() - chrdev file close buffer access and ioctls
1769  * @inode:	Inode structure pointer for the char device
1770  * @filp:	File structure pointer for the char device
1771  *
1772  * Return: 0 for successful release
1773  */
1774 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1775 {
1776 	struct iio_dev_buffer_pair *ib = filp->private_data;
1777 	struct iio_dev_opaque *iio_dev_opaque =
1778 		container_of(inode->i_cdev, struct iio_dev_opaque, chrdev);
1779 	struct iio_dev *indio_dev = &iio_dev_opaque->indio_dev;
1780 	kfree(ib);
1781 	clear_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags);
1782 	iio_device_put(indio_dev);
1783 
1784 	return 0;
1785 }
1786 
1787 void iio_device_ioctl_handler_register(struct iio_dev *indio_dev,
1788 				       struct iio_ioctl_handler *h)
1789 {
1790 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1791 
1792 	list_add_tail(&h->entry, &iio_dev_opaque->ioctl_handlers);
1793 }
1794 
1795 void iio_device_ioctl_handler_unregister(struct iio_ioctl_handler *h)
1796 {
1797 	list_del(&h->entry);
1798 }
1799 
1800 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1801 {
1802 	struct iio_dev_buffer_pair *ib = filp->private_data;
1803 	struct iio_dev *indio_dev = ib->indio_dev;
1804 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1805 	struct iio_ioctl_handler *h;
1806 	int ret = -ENODEV;
1807 
1808 	mutex_lock(&iio_dev_opaque->info_exist_lock);
1809 
1810 	/**
1811 	 * The NULL check here is required to prevent crashing when a device
1812 	 * is being removed while userspace would still have open file handles
1813 	 * to try to access this device.
1814 	 */
1815 	if (!indio_dev->info)
1816 		goto out_unlock;
1817 
1818 	list_for_each_entry(h, &iio_dev_opaque->ioctl_handlers, entry) {
1819 		ret = h->ioctl(indio_dev, filp, cmd, arg);
1820 		if (ret != IIO_IOCTL_UNHANDLED)
1821 			break;
1822 	}
1823 
1824 	if (ret == IIO_IOCTL_UNHANDLED)
1825 		ret = -ENODEV;
1826 
1827 out_unlock:
1828 	mutex_unlock(&iio_dev_opaque->info_exist_lock);
1829 
1830 	return ret;
1831 }
1832 
1833 static const struct file_operations iio_buffer_fileops = {
1834 	.owner = THIS_MODULE,
1835 	.llseek = noop_llseek,
1836 	.read = iio_buffer_read_outer_addr,
1837 	.write = iio_buffer_write_outer_addr,
1838 	.poll = iio_buffer_poll_addr,
1839 	.unlocked_ioctl = iio_ioctl,
1840 	.compat_ioctl = compat_ptr_ioctl,
1841 	.open = iio_chrdev_open,
1842 	.release = iio_chrdev_release,
1843 };
1844 
1845 static const struct file_operations iio_event_fileops = {
1846 	.owner = THIS_MODULE,
1847 	.llseek = noop_llseek,
1848 	.unlocked_ioctl = iio_ioctl,
1849 	.compat_ioctl = compat_ptr_ioctl,
1850 	.open = iio_chrdev_open,
1851 	.release = iio_chrdev_release,
1852 };
1853 
1854 static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1855 {
1856 	int i, j;
1857 	const struct iio_chan_spec *channels = indio_dev->channels;
1858 
1859 	if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1860 		return 0;
1861 
1862 	for (i = 0; i < indio_dev->num_channels - 1; i++) {
1863 		if (channels[i].scan_index < 0)
1864 			continue;
1865 		for (j = i + 1; j < indio_dev->num_channels; j++)
1866 			if (channels[i].scan_index == channels[j].scan_index) {
1867 				dev_err(&indio_dev->dev,
1868 					"Duplicate scan index %d\n",
1869 					channels[i].scan_index);
1870 				return -EINVAL;
1871 			}
1872 	}
1873 
1874 	return 0;
1875 }
1876 
1877 static int iio_check_extended_name(const struct iio_dev *indio_dev)
1878 {
1879 	unsigned int i;
1880 
1881 	if (!indio_dev->info->read_label)
1882 		return 0;
1883 
1884 	for (i = 0; i < indio_dev->num_channels; i++) {
1885 		if (indio_dev->channels[i].extend_name) {
1886 			dev_err(&indio_dev->dev,
1887 				"Cannot use labels and extend_name at the same time\n");
1888 			return -EINVAL;
1889 		}
1890 	}
1891 
1892 	return 0;
1893 }
1894 
1895 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1896 
1897 int __iio_device_register(struct iio_dev *indio_dev, struct module *this_mod)
1898 {
1899 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1900 	struct fwnode_handle *fwnode;
1901 	int ret;
1902 
1903 	if (!indio_dev->info)
1904 		return -EINVAL;
1905 
1906 	iio_dev_opaque->driver_module = this_mod;
1907 
1908 	/* If the calling driver did not initialize firmware node, do it here */
1909 	if (dev_fwnode(&indio_dev->dev))
1910 		fwnode = dev_fwnode(&indio_dev->dev);
1911 	else
1912 		fwnode = dev_fwnode(indio_dev->dev.parent);
1913 	device_set_node(&indio_dev->dev, fwnode);
1914 
1915 	fwnode_property_read_string(fwnode, "label", &indio_dev->label);
1916 
1917 	ret = iio_check_unique_scan_index(indio_dev);
1918 	if (ret < 0)
1919 		return ret;
1920 
1921 	ret = iio_check_extended_name(indio_dev);
1922 	if (ret < 0)
1923 		return ret;
1924 
1925 	iio_device_register_debugfs(indio_dev);
1926 
1927 	ret = iio_buffers_alloc_sysfs_and_mask(indio_dev);
1928 	if (ret) {
1929 		dev_err(indio_dev->dev.parent,
1930 			"Failed to create buffer sysfs interfaces\n");
1931 		goto error_unreg_debugfs;
1932 	}
1933 
1934 	ret = iio_device_register_sysfs(indio_dev);
1935 	if (ret) {
1936 		dev_err(indio_dev->dev.parent,
1937 			"Failed to register sysfs interfaces\n");
1938 		goto error_buffer_free_sysfs;
1939 	}
1940 	ret = iio_device_register_eventset(indio_dev);
1941 	if (ret) {
1942 		dev_err(indio_dev->dev.parent,
1943 			"Failed to register event set\n");
1944 		goto error_free_sysfs;
1945 	}
1946 	if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1947 		iio_device_register_trigger_consumer(indio_dev);
1948 
1949 	if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1950 		indio_dev->setup_ops == NULL)
1951 		indio_dev->setup_ops = &noop_ring_setup_ops;
1952 
1953 	if (iio_dev_opaque->attached_buffers_cnt)
1954 		cdev_init(&iio_dev_opaque->chrdev, &iio_buffer_fileops);
1955 	else if (iio_dev_opaque->event_interface)
1956 		cdev_init(&iio_dev_opaque->chrdev, &iio_event_fileops);
1957 
1958 	if (iio_dev_opaque->attached_buffers_cnt || iio_dev_opaque->event_interface) {
1959 		indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), iio_dev_opaque->id);
1960 		iio_dev_opaque->chrdev.owner = this_mod;
1961 	}
1962 
1963 	/* assign device groups now; they should be all registered now */
1964 	indio_dev->dev.groups = iio_dev_opaque->groups;
1965 
1966 	ret = cdev_device_add(&iio_dev_opaque->chrdev, &indio_dev->dev);
1967 	if (ret < 0)
1968 		goto error_unreg_eventset;
1969 
1970 	return 0;
1971 
1972 error_unreg_eventset:
1973 	iio_device_unregister_eventset(indio_dev);
1974 error_free_sysfs:
1975 	iio_device_unregister_sysfs(indio_dev);
1976 error_buffer_free_sysfs:
1977 	iio_buffers_free_sysfs_and_mask(indio_dev);
1978 error_unreg_debugfs:
1979 	iio_device_unregister_debugfs(indio_dev);
1980 	return ret;
1981 }
1982 EXPORT_SYMBOL(__iio_device_register);
1983 
1984 /**
1985  * iio_device_unregister() - unregister a device from the IIO subsystem
1986  * @indio_dev:		Device structure representing the device.
1987  **/
1988 void iio_device_unregister(struct iio_dev *indio_dev)
1989 {
1990 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1991 
1992 	cdev_device_del(&iio_dev_opaque->chrdev, &indio_dev->dev);
1993 
1994 	mutex_lock(&iio_dev_opaque->info_exist_lock);
1995 
1996 	iio_device_unregister_debugfs(indio_dev);
1997 
1998 	iio_disable_all_buffers(indio_dev);
1999 
2000 	indio_dev->info = NULL;
2001 
2002 	iio_device_wakeup_eventset(indio_dev);
2003 	iio_buffer_wakeup_poll(indio_dev);
2004 
2005 	mutex_unlock(&iio_dev_opaque->info_exist_lock);
2006 
2007 	iio_buffers_free_sysfs_and_mask(indio_dev);
2008 }
2009 EXPORT_SYMBOL(iio_device_unregister);
2010 
2011 static void devm_iio_device_unreg(void *indio_dev)
2012 {
2013 	iio_device_unregister(indio_dev);
2014 }
2015 
2016 int __devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev,
2017 			       struct module *this_mod)
2018 {
2019 	int ret;
2020 
2021 	ret = __iio_device_register(indio_dev, this_mod);
2022 	if (ret)
2023 		return ret;
2024 
2025 	return devm_add_action_or_reset(dev, devm_iio_device_unreg, indio_dev);
2026 }
2027 EXPORT_SYMBOL_GPL(__devm_iio_device_register);
2028 
2029 /**
2030  * iio_device_claim_direct_mode - Keep device in direct mode
2031  * @indio_dev:	the iio_dev associated with the device
2032  *
2033  * If the device is in direct mode it is guaranteed to stay
2034  * that way until iio_device_release_direct_mode() is called.
2035  *
2036  * Use with iio_device_release_direct_mode()
2037  *
2038  * Returns: 0 on success, -EBUSY on failure
2039  */
2040 int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
2041 {
2042 	mutex_lock(&indio_dev->mlock);
2043 
2044 	if (iio_buffer_enabled(indio_dev)) {
2045 		mutex_unlock(&indio_dev->mlock);
2046 		return -EBUSY;
2047 	}
2048 	return 0;
2049 }
2050 EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
2051 
2052 /**
2053  * iio_device_release_direct_mode - releases claim on direct mode
2054  * @indio_dev:	the iio_dev associated with the device
2055  *
2056  * Release the claim. Device is no longer guaranteed to stay
2057  * in direct mode.
2058  *
2059  * Use with iio_device_claim_direct_mode()
2060  */
2061 void iio_device_release_direct_mode(struct iio_dev *indio_dev)
2062 {
2063 	mutex_unlock(&indio_dev->mlock);
2064 }
2065 EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
2066 
2067 /**
2068  * iio_device_get_current_mode() - helper function providing read-only access to
2069  *				   the opaque @currentmode variable
2070  * @indio_dev:			   IIO device structure for device
2071  */
2072 int iio_device_get_current_mode(struct iio_dev *indio_dev)
2073 {
2074 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2075 
2076 	return iio_dev_opaque->currentmode;
2077 }
2078 EXPORT_SYMBOL_GPL(iio_device_get_current_mode);
2079 
2080 subsys_initcall(iio_init);
2081 module_exit(iio_exit);
2082 
2083 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
2084 MODULE_DESCRIPTION("Industrial I/O core");
2085 MODULE_LICENSE("GPL");
2086