xref: /openbmc/linux/drivers/iio/industrialio-core.c (revision f97cee494dc92395a668445bcd24d34c89f4ff8c)
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_INT_TIME] = "integration_time",
161 	[IIO_CHAN_INFO_ENABLE] = "en",
162 	[IIO_CHAN_INFO_CALIBHEIGHT] = "calibheight",
163 	[IIO_CHAN_INFO_CALIBWEIGHT] = "calibweight",
164 	[IIO_CHAN_INFO_DEBOUNCE_COUNT] = "debounce_count",
165 	[IIO_CHAN_INFO_DEBOUNCE_TIME] = "debounce_time",
166 	[IIO_CHAN_INFO_CALIBEMISSIVITY] = "calibemissivity",
167 	[IIO_CHAN_INFO_OVERSAMPLING_RATIO] = "oversampling_ratio",
168 	[IIO_CHAN_INFO_THERMOCOUPLE_TYPE] = "thermocouple_type",
169 	[IIO_CHAN_INFO_CALIBAMBIENT] = "calibambient",
170 };
171 
172 #if defined(CONFIG_DEBUG_FS)
173 /*
174  * There's also a CONFIG_DEBUG_FS guard in include/linux/iio/iio.h for
175  * iio_get_debugfs_dentry() to make it inline if CONFIG_DEBUG_FS is undefined
176  */
177 struct dentry *iio_get_debugfs_dentry(struct iio_dev *indio_dev)
178 {
179 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
180 	return iio_dev_opaque->debugfs_dentry;
181 }
182 EXPORT_SYMBOL_GPL(iio_get_debugfs_dentry);
183 #endif
184 
185 /**
186  * iio_find_channel_from_si() - get channel from its scan index
187  * @indio_dev:		device
188  * @si:			scan index to match
189  */
190 const struct iio_chan_spec
191 *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
192 {
193 	int i;
194 
195 	for (i = 0; i < indio_dev->num_channels; i++)
196 		if (indio_dev->channels[i].scan_index == si)
197 			return &indio_dev->channels[i];
198 	return NULL;
199 }
200 
201 /* This turns up an awful lot */
202 ssize_t iio_read_const_attr(struct device *dev,
203 			    struct device_attribute *attr,
204 			    char *buf)
205 {
206 	return sprintf(buf, "%s\n", to_iio_const_attr(attr)->string);
207 }
208 EXPORT_SYMBOL(iio_read_const_attr);
209 
210 /**
211  * iio_device_set_clock() - Set current timestamping clock for the device
212  * @indio_dev: IIO device structure containing the device
213  * @clock_id: timestamping clock posix identifier to set.
214  */
215 int iio_device_set_clock(struct iio_dev *indio_dev, clockid_t clock_id)
216 {
217 	int ret;
218 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
219 	const struct iio_event_interface *ev_int = iio_dev_opaque->event_interface;
220 
221 	ret = mutex_lock_interruptible(&indio_dev->mlock);
222 	if (ret)
223 		return ret;
224 	if ((ev_int && iio_event_enabled(ev_int)) ||
225 	    iio_buffer_enabled(indio_dev)) {
226 		mutex_unlock(&indio_dev->mlock);
227 		return -EBUSY;
228 	}
229 	indio_dev->clock_id = clock_id;
230 	mutex_unlock(&indio_dev->mlock);
231 
232 	return 0;
233 }
234 EXPORT_SYMBOL(iio_device_set_clock);
235 
236 /**
237  * iio_get_time_ns() - utility function to get a time stamp for events etc
238  * @indio_dev: device
239  */
240 s64 iio_get_time_ns(const struct iio_dev *indio_dev)
241 {
242 	struct timespec64 tp;
243 
244 	switch (iio_device_get_clock(indio_dev)) {
245 	case CLOCK_REALTIME:
246 		return ktime_get_real_ns();
247 	case CLOCK_MONOTONIC:
248 		return ktime_get_ns();
249 	case CLOCK_MONOTONIC_RAW:
250 		return ktime_get_raw_ns();
251 	case CLOCK_REALTIME_COARSE:
252 		return ktime_to_ns(ktime_get_coarse_real());
253 	case CLOCK_MONOTONIC_COARSE:
254 		ktime_get_coarse_ts64(&tp);
255 		return timespec64_to_ns(&tp);
256 	case CLOCK_BOOTTIME:
257 		return ktime_get_boottime_ns();
258 	case CLOCK_TAI:
259 		return ktime_get_clocktai_ns();
260 	default:
261 		BUG();
262 	}
263 }
264 EXPORT_SYMBOL(iio_get_time_ns);
265 
266 /**
267  * iio_get_time_res() - utility function to get time stamp clock resolution in
268  *                      nano seconds.
269  * @indio_dev: device
270  */
271 unsigned int iio_get_time_res(const struct iio_dev *indio_dev)
272 {
273 	switch (iio_device_get_clock(indio_dev)) {
274 	case CLOCK_REALTIME:
275 	case CLOCK_MONOTONIC:
276 	case CLOCK_MONOTONIC_RAW:
277 	case CLOCK_BOOTTIME:
278 	case CLOCK_TAI:
279 		return hrtimer_resolution;
280 	case CLOCK_REALTIME_COARSE:
281 	case CLOCK_MONOTONIC_COARSE:
282 		return LOW_RES_NSEC;
283 	default:
284 		BUG();
285 	}
286 }
287 EXPORT_SYMBOL(iio_get_time_res);
288 
289 static int __init iio_init(void)
290 {
291 	int ret;
292 
293 	/* Register sysfs bus */
294 	ret  = bus_register(&iio_bus_type);
295 	if (ret < 0) {
296 		pr_err("could not register bus type\n");
297 		goto error_nothing;
298 	}
299 
300 	ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
301 	if (ret < 0) {
302 		pr_err("failed to allocate char dev region\n");
303 		goto error_unregister_bus_type;
304 	}
305 
306 	iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
307 
308 	return 0;
309 
310 error_unregister_bus_type:
311 	bus_unregister(&iio_bus_type);
312 error_nothing:
313 	return ret;
314 }
315 
316 static void __exit iio_exit(void)
317 {
318 	if (iio_devt)
319 		unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
320 	bus_unregister(&iio_bus_type);
321 	debugfs_remove(iio_debugfs_dentry);
322 }
323 
324 #if defined(CONFIG_DEBUG_FS)
325 static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
326 			      size_t count, loff_t *ppos)
327 {
328 	struct iio_dev *indio_dev = file->private_data;
329 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
330 	unsigned val = 0;
331 	int ret;
332 
333 	if (*ppos > 0)
334 		return simple_read_from_buffer(userbuf, count, ppos,
335 					       iio_dev_opaque->read_buf,
336 					       iio_dev_opaque->read_buf_len);
337 
338 	ret = indio_dev->info->debugfs_reg_access(indio_dev,
339 						  iio_dev_opaque->cached_reg_addr,
340 						  0, &val);
341 	if (ret) {
342 		dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
343 		return ret;
344 	}
345 
346 	iio_dev_opaque->read_buf_len = snprintf(iio_dev_opaque->read_buf,
347 					      sizeof(iio_dev_opaque->read_buf),
348 					      "0x%X\n", val);
349 
350 	return simple_read_from_buffer(userbuf, count, ppos,
351 				       iio_dev_opaque->read_buf,
352 				       iio_dev_opaque->read_buf_len);
353 }
354 
355 static ssize_t iio_debugfs_write_reg(struct file *file,
356 		     const char __user *userbuf, size_t count, loff_t *ppos)
357 {
358 	struct iio_dev *indio_dev = file->private_data;
359 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
360 	unsigned reg, val;
361 	char buf[80];
362 	int ret;
363 
364 	count = min_t(size_t, count, (sizeof(buf)-1));
365 	if (copy_from_user(buf, userbuf, count))
366 		return -EFAULT;
367 
368 	buf[count] = 0;
369 
370 	ret = sscanf(buf, "%i %i", &reg, &val);
371 
372 	switch (ret) {
373 	case 1:
374 		iio_dev_opaque->cached_reg_addr = reg;
375 		break;
376 	case 2:
377 		iio_dev_opaque->cached_reg_addr = reg;
378 		ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
379 							  val, NULL);
380 		if (ret) {
381 			dev_err(indio_dev->dev.parent, "%s: write failed\n",
382 				__func__);
383 			return ret;
384 		}
385 		break;
386 	default:
387 		return -EINVAL;
388 	}
389 
390 	return count;
391 }
392 
393 static const struct file_operations iio_debugfs_reg_fops = {
394 	.open = simple_open,
395 	.read = iio_debugfs_read_reg,
396 	.write = iio_debugfs_write_reg,
397 };
398 
399 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
400 {
401 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
402 	debugfs_remove_recursive(iio_dev_opaque->debugfs_dentry);
403 }
404 
405 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
406 {
407 	struct iio_dev_opaque *iio_dev_opaque;
408 
409 	if (indio_dev->info->debugfs_reg_access == NULL)
410 		return;
411 
412 	if (!iio_debugfs_dentry)
413 		return;
414 
415 	iio_dev_opaque = to_iio_dev_opaque(indio_dev);
416 
417 	iio_dev_opaque->debugfs_dentry =
418 		debugfs_create_dir(dev_name(&indio_dev->dev),
419 				   iio_debugfs_dentry);
420 
421 	debugfs_create_file("direct_reg_access", 0644,
422 			    iio_dev_opaque->debugfs_dentry, indio_dev,
423 			    &iio_debugfs_reg_fops);
424 }
425 #else
426 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
427 {
428 }
429 
430 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
431 {
432 }
433 #endif /* CONFIG_DEBUG_FS */
434 
435 static ssize_t iio_read_channel_ext_info(struct device *dev,
436 				     struct device_attribute *attr,
437 				     char *buf)
438 {
439 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
440 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
441 	const struct iio_chan_spec_ext_info *ext_info;
442 
443 	ext_info = &this_attr->c->ext_info[this_attr->address];
444 
445 	return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
446 }
447 
448 static ssize_t iio_write_channel_ext_info(struct device *dev,
449 				     struct device_attribute *attr,
450 				     const char *buf,
451 					 size_t len)
452 {
453 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
454 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
455 	const struct iio_chan_spec_ext_info *ext_info;
456 
457 	ext_info = &this_attr->c->ext_info[this_attr->address];
458 
459 	return ext_info->write(indio_dev, ext_info->private,
460 			       this_attr->c, buf, len);
461 }
462 
463 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
464 	uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
465 {
466 	const struct iio_enum *e = (const struct iio_enum *)priv;
467 	unsigned int i;
468 	size_t len = 0;
469 
470 	if (!e->num_items)
471 		return 0;
472 
473 	for (i = 0; i < e->num_items; ++i)
474 		len += scnprintf(buf + len, PAGE_SIZE - len, "%s ", e->items[i]);
475 
476 	/* replace last space with a newline */
477 	buf[len - 1] = '\n';
478 
479 	return len;
480 }
481 EXPORT_SYMBOL_GPL(iio_enum_available_read);
482 
483 ssize_t iio_enum_read(struct iio_dev *indio_dev,
484 	uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
485 {
486 	const struct iio_enum *e = (const struct iio_enum *)priv;
487 	int i;
488 
489 	if (!e->get)
490 		return -EINVAL;
491 
492 	i = e->get(indio_dev, chan);
493 	if (i < 0)
494 		return i;
495 	else if (i >= e->num_items)
496 		return -EINVAL;
497 
498 	return snprintf(buf, PAGE_SIZE, "%s\n", e->items[i]);
499 }
500 EXPORT_SYMBOL_GPL(iio_enum_read);
501 
502 ssize_t iio_enum_write(struct iio_dev *indio_dev,
503 	uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
504 	size_t len)
505 {
506 	const struct iio_enum *e = (const struct iio_enum *)priv;
507 	int ret;
508 
509 	if (!e->set)
510 		return -EINVAL;
511 
512 	ret = __sysfs_match_string(e->items, e->num_items, buf);
513 	if (ret < 0)
514 		return ret;
515 
516 	ret = e->set(indio_dev, chan, ret);
517 	return ret ? ret : len;
518 }
519 EXPORT_SYMBOL_GPL(iio_enum_write);
520 
521 static const struct iio_mount_matrix iio_mount_idmatrix = {
522 	.rotation = {
523 		"1", "0", "0",
524 		"0", "1", "0",
525 		"0", "0", "1"
526 	}
527 };
528 
529 static int iio_setup_mount_idmatrix(const struct device *dev,
530 				    struct iio_mount_matrix *matrix)
531 {
532 	*matrix = iio_mount_idmatrix;
533 	dev_info(dev, "mounting matrix not found: using identity...\n");
534 	return 0;
535 }
536 
537 ssize_t iio_show_mount_matrix(struct iio_dev *indio_dev, uintptr_t priv,
538 			      const struct iio_chan_spec *chan, char *buf)
539 {
540 	const struct iio_mount_matrix *mtx = ((iio_get_mount_matrix_t *)
541 					      priv)(indio_dev, chan);
542 
543 	if (IS_ERR(mtx))
544 		return PTR_ERR(mtx);
545 
546 	if (!mtx)
547 		mtx = &iio_mount_idmatrix;
548 
549 	return snprintf(buf, PAGE_SIZE, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
550 			mtx->rotation[0], mtx->rotation[1], mtx->rotation[2],
551 			mtx->rotation[3], mtx->rotation[4], mtx->rotation[5],
552 			mtx->rotation[6], mtx->rotation[7], mtx->rotation[8]);
553 }
554 EXPORT_SYMBOL_GPL(iio_show_mount_matrix);
555 
556 /**
557  * iio_read_mount_matrix() - retrieve iio device mounting matrix from
558  *                           device "mount-matrix" property
559  * @dev:	device the mounting matrix property is assigned to
560  * @propname:	device specific mounting matrix property name
561  * @matrix:	where to store retrieved matrix
562  *
563  * If device is assigned no mounting matrix property, a default 3x3 identity
564  * matrix will be filled in.
565  *
566  * Return: 0 if success, or a negative error code on failure.
567  */
568 int iio_read_mount_matrix(struct device *dev, const char *propname,
569 			  struct iio_mount_matrix *matrix)
570 {
571 	size_t len = ARRAY_SIZE(iio_mount_idmatrix.rotation);
572 	int err;
573 
574 	err = device_property_read_string_array(dev, propname,
575 						matrix->rotation, len);
576 	if (err == len)
577 		return 0;
578 
579 	if (err >= 0)
580 		/* Invalid number of matrix entries. */
581 		return -EINVAL;
582 
583 	if (err != -EINVAL)
584 		/* Invalid matrix declaration format. */
585 		return err;
586 
587 	/* Matrix was not declared at all: fallback to identity. */
588 	return iio_setup_mount_idmatrix(dev, matrix);
589 }
590 EXPORT_SYMBOL(iio_read_mount_matrix);
591 
592 static ssize_t __iio_format_value(char *buf, size_t len, unsigned int type,
593 				  int size, const int *vals)
594 {
595 	unsigned long long tmp;
596 	int tmp0, tmp1;
597 	s64 tmp2;
598 	bool scale_db = false;
599 
600 	switch (type) {
601 	case IIO_VAL_INT:
602 		return scnprintf(buf, len, "%d", vals[0]);
603 	case IIO_VAL_INT_PLUS_MICRO_DB:
604 		scale_db = true;
605 		fallthrough;
606 	case IIO_VAL_INT_PLUS_MICRO:
607 		if (vals[1] < 0)
608 			return scnprintf(buf, len, "-%d.%06u%s", abs(vals[0]),
609 					-vals[1], scale_db ? " dB" : "");
610 		else
611 			return scnprintf(buf, len, "%d.%06u%s", vals[0], vals[1],
612 					scale_db ? " dB" : "");
613 	case IIO_VAL_INT_PLUS_NANO:
614 		if (vals[1] < 0)
615 			return scnprintf(buf, len, "-%d.%09u", abs(vals[0]),
616 					-vals[1]);
617 		else
618 			return scnprintf(buf, len, "%d.%09u", vals[0], vals[1]);
619 	case IIO_VAL_FRACTIONAL:
620 		tmp2 = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
621 		tmp1 = vals[1];
622 		tmp0 = (int)div_s64_rem(tmp2, 1000000000, &tmp1);
623 		if ((tmp2 < 0) && (tmp0 == 0))
624 			return snprintf(buf, len, "-0.%09u", abs(tmp1));
625 		else
626 			return snprintf(buf, len, "%d.%09u", tmp0, abs(tmp1));
627 	case IIO_VAL_FRACTIONAL_LOG2:
628 		tmp = shift_right((s64)vals[0] * 1000000000LL, vals[1]);
629 		tmp0 = (int)div_s64_rem(tmp, 1000000000LL, &tmp1);
630 		return scnprintf(buf, len, "%d.%09u", tmp0, abs(tmp1));
631 	case IIO_VAL_INT_MULTIPLE:
632 	{
633 		int i;
634 		int l = 0;
635 
636 		for (i = 0; i < size; ++i) {
637 			l += scnprintf(&buf[l], len - l, "%d ", vals[i]);
638 			if (l >= len)
639 				break;
640 		}
641 		return l;
642 	}
643 	case IIO_VAL_CHAR:
644 		return scnprintf(buf, len, "%c", (char)vals[0]);
645 	default:
646 		return 0;
647 	}
648 }
649 
650 /**
651  * iio_format_value() - Formats a IIO value into its string representation
652  * @buf:	The buffer to which the formatted value gets written
653  *		which is assumed to be big enough (i.e. PAGE_SIZE).
654  * @type:	One of the IIO_VAL_* constants. This decides how the val
655  *		and val2 parameters are formatted.
656  * @size:	Number of IIO value entries contained in vals
657  * @vals:	Pointer to the values, exact meaning depends on the
658  *		type parameter.
659  *
660  * Return: 0 by default, a negative number on failure or the
661  *	   total number of characters written for a type that belongs
662  *	   to the IIO_VAL_* constant.
663  */
664 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
665 {
666 	ssize_t len;
667 
668 	len = __iio_format_value(buf, PAGE_SIZE, type, size, vals);
669 	if (len >= PAGE_SIZE - 1)
670 		return -EFBIG;
671 
672 	return len + sprintf(buf + len, "\n");
673 }
674 EXPORT_SYMBOL_GPL(iio_format_value);
675 
676 static ssize_t iio_read_channel_label(struct device *dev,
677 				      struct device_attribute *attr,
678 				      char *buf)
679 {
680 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
681 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
682 
683 	if (!indio_dev->info->read_label)
684 		return -EINVAL;
685 
686 	return indio_dev->info->read_label(indio_dev, this_attr->c, buf);
687 }
688 
689 static ssize_t iio_read_channel_info(struct device *dev,
690 				     struct device_attribute *attr,
691 				     char *buf)
692 {
693 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
694 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
695 	int vals[INDIO_MAX_RAW_ELEMENTS];
696 	int ret;
697 	int val_len = 2;
698 
699 	if (indio_dev->info->read_raw_multi)
700 		ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
701 							INDIO_MAX_RAW_ELEMENTS,
702 							vals, &val_len,
703 							this_attr->address);
704 	else
705 		ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
706 				    &vals[0], &vals[1], this_attr->address);
707 
708 	if (ret < 0)
709 		return ret;
710 
711 	return iio_format_value(buf, ret, val_len, vals);
712 }
713 
714 static ssize_t iio_format_avail_list(char *buf, const int *vals,
715 				     int type, int length)
716 {
717 	int i;
718 	ssize_t len = 0;
719 
720 	switch (type) {
721 	case IIO_VAL_INT:
722 		for (i = 0; i < length; i++) {
723 			len += __iio_format_value(buf + len, PAGE_SIZE - len,
724 						  type, 1, &vals[i]);
725 			if (len >= PAGE_SIZE)
726 				return -EFBIG;
727 			if (i < length - 1)
728 				len += scnprintf(buf + len, PAGE_SIZE - len,
729 						" ");
730 			else
731 				len += scnprintf(buf + len, PAGE_SIZE - len,
732 						"\n");
733 			if (len >= PAGE_SIZE)
734 				return -EFBIG;
735 		}
736 		break;
737 	default:
738 		for (i = 0; i < length / 2; i++) {
739 			len += __iio_format_value(buf + len, PAGE_SIZE - len,
740 						  type, 2, &vals[i * 2]);
741 			if (len >= PAGE_SIZE)
742 				return -EFBIG;
743 			if (i < length / 2 - 1)
744 				len += scnprintf(buf + len, PAGE_SIZE - len,
745 						" ");
746 			else
747 				len += scnprintf(buf + len, PAGE_SIZE - len,
748 						"\n");
749 			if (len >= PAGE_SIZE)
750 				return -EFBIG;
751 		}
752 	}
753 
754 	return len;
755 }
756 
757 static ssize_t iio_format_avail_range(char *buf, const int *vals, int type)
758 {
759 	int i;
760 	ssize_t len;
761 
762 	len = snprintf(buf, PAGE_SIZE, "[");
763 	switch (type) {
764 	case IIO_VAL_INT:
765 		for (i = 0; i < 3; i++) {
766 			len += __iio_format_value(buf + len, PAGE_SIZE - len,
767 						  type, 1, &vals[i]);
768 			if (len >= PAGE_SIZE)
769 				return -EFBIG;
770 			if (i < 2)
771 				len += scnprintf(buf + len, PAGE_SIZE - len,
772 						" ");
773 			else
774 				len += scnprintf(buf + len, PAGE_SIZE - len,
775 						"]\n");
776 			if (len >= PAGE_SIZE)
777 				return -EFBIG;
778 		}
779 		break;
780 	default:
781 		for (i = 0; i < 3; i++) {
782 			len += __iio_format_value(buf + len, PAGE_SIZE - len,
783 						  type, 2, &vals[i * 2]);
784 			if (len >= PAGE_SIZE)
785 				return -EFBIG;
786 			if (i < 2)
787 				len += scnprintf(buf + len, PAGE_SIZE - len,
788 						" ");
789 			else
790 				len += scnprintf(buf + len, PAGE_SIZE - len,
791 						"]\n");
792 			if (len >= PAGE_SIZE)
793 				return -EFBIG;
794 		}
795 	}
796 
797 	return len;
798 }
799 
800 static ssize_t iio_read_channel_info_avail(struct device *dev,
801 					   struct device_attribute *attr,
802 					   char *buf)
803 {
804 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
805 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
806 	const int *vals;
807 	int ret;
808 	int length;
809 	int type;
810 
811 	ret = indio_dev->info->read_avail(indio_dev, this_attr->c,
812 					  &vals, &type, &length,
813 					  this_attr->address);
814 
815 	if (ret < 0)
816 		return ret;
817 	switch (ret) {
818 	case IIO_AVAIL_LIST:
819 		return iio_format_avail_list(buf, vals, type, length);
820 	case IIO_AVAIL_RANGE:
821 		return iio_format_avail_range(buf, vals, type);
822 	default:
823 		return -EINVAL;
824 	}
825 }
826 
827 /**
828  * __iio_str_to_fixpoint() - Parse a fixed-point number from a string
829  * @str: The string to parse
830  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
831  * @integer: The integer part of the number
832  * @fract: The fractional part of the number
833  * @scale_db: True if this should parse as dB
834  *
835  * Returns 0 on success, or a negative error code if the string could not be
836  * parsed.
837  */
838 static int __iio_str_to_fixpoint(const char *str, int fract_mult,
839 				 int *integer, int *fract, bool scale_db)
840 {
841 	int i = 0, f = 0;
842 	bool integer_part = true, negative = false;
843 
844 	if (fract_mult == 0) {
845 		*fract = 0;
846 
847 		return kstrtoint(str, 0, integer);
848 	}
849 
850 	if (str[0] == '-') {
851 		negative = true;
852 		str++;
853 	} else if (str[0] == '+') {
854 		str++;
855 	}
856 
857 	while (*str) {
858 		if ('0' <= *str && *str <= '9') {
859 			if (integer_part) {
860 				i = i * 10 + *str - '0';
861 			} else {
862 				f += fract_mult * (*str - '0');
863 				fract_mult /= 10;
864 			}
865 		} else if (*str == '\n') {
866 			if (*(str + 1) == '\0')
867 				break;
868 			else
869 				return -EINVAL;
870 		} else if (!strncmp(str, " dB", sizeof(" dB") - 1) && scale_db) {
871 			/* Ignore the dB suffix */
872 			str += sizeof(" dB") - 1;
873 			continue;
874 		} else if (!strncmp(str, "dB", sizeof("dB") - 1) && scale_db) {
875 			/* Ignore the dB suffix */
876 			str += sizeof("dB") - 1;
877 			continue;
878 		} else if (*str == '.' && integer_part) {
879 			integer_part = false;
880 		} else {
881 			return -EINVAL;
882 		}
883 		str++;
884 	}
885 
886 	if (negative) {
887 		if (i)
888 			i = -i;
889 		else
890 			f = -f;
891 	}
892 
893 	*integer = i;
894 	*fract = f;
895 
896 	return 0;
897 }
898 
899 /**
900  * iio_str_to_fixpoint() - Parse a fixed-point number from a string
901  * @str: The string to parse
902  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
903  * @integer: The integer part of the number
904  * @fract: The fractional part of the number
905  *
906  * Returns 0 on success, or a negative error code if the string could not be
907  * parsed.
908  */
909 int iio_str_to_fixpoint(const char *str, int fract_mult,
910 			int *integer, int *fract)
911 {
912 	return __iio_str_to_fixpoint(str, fract_mult, integer, fract, false);
913 }
914 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
915 
916 static ssize_t iio_write_channel_info(struct device *dev,
917 				      struct device_attribute *attr,
918 				      const char *buf,
919 				      size_t len)
920 {
921 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
922 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
923 	int ret, fract_mult = 100000;
924 	int integer, fract = 0;
925 	bool is_char = false;
926 	bool scale_db = false;
927 
928 	/* Assumes decimal - precision based on number of digits */
929 	if (!indio_dev->info->write_raw)
930 		return -EINVAL;
931 
932 	if (indio_dev->info->write_raw_get_fmt)
933 		switch (indio_dev->info->write_raw_get_fmt(indio_dev,
934 			this_attr->c, this_attr->address)) {
935 		case IIO_VAL_INT:
936 			fract_mult = 0;
937 			break;
938 		case IIO_VAL_INT_PLUS_MICRO_DB:
939 			scale_db = true;
940 			fallthrough;
941 		case IIO_VAL_INT_PLUS_MICRO:
942 			fract_mult = 100000;
943 			break;
944 		case IIO_VAL_INT_PLUS_NANO:
945 			fract_mult = 100000000;
946 			break;
947 		case IIO_VAL_CHAR:
948 			is_char = true;
949 			break;
950 		default:
951 			return -EINVAL;
952 		}
953 
954 	if (is_char) {
955 		char ch;
956 
957 		if (sscanf(buf, "%c", &ch) != 1)
958 			return -EINVAL;
959 		integer = ch;
960 	} else {
961 		ret = __iio_str_to_fixpoint(buf, fract_mult, &integer, &fract,
962 					    scale_db);
963 		if (ret)
964 			return ret;
965 	}
966 
967 	ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
968 					 integer, fract, this_attr->address);
969 	if (ret)
970 		return ret;
971 
972 	return len;
973 }
974 
975 static
976 int __iio_device_attr_init(struct device_attribute *dev_attr,
977 			   const char *postfix,
978 			   struct iio_chan_spec const *chan,
979 			   ssize_t (*readfunc)(struct device *dev,
980 					       struct device_attribute *attr,
981 					       char *buf),
982 			   ssize_t (*writefunc)(struct device *dev,
983 						struct device_attribute *attr,
984 						const char *buf,
985 						size_t len),
986 			   enum iio_shared_by shared_by)
987 {
988 	int ret = 0;
989 	char *name = NULL;
990 	char *full_postfix;
991 	sysfs_attr_init(&dev_attr->attr);
992 
993 	/* Build up postfix of <extend_name>_<modifier>_postfix */
994 	if (chan->modified && (shared_by == IIO_SEPARATE)) {
995 		if (chan->extend_name)
996 			full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
997 						 iio_modifier_names[chan
998 								    ->channel2],
999 						 chan->extend_name,
1000 						 postfix);
1001 		else
1002 			full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
1003 						 iio_modifier_names[chan
1004 								    ->channel2],
1005 						 postfix);
1006 	} else {
1007 		if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
1008 			full_postfix = kstrdup(postfix, GFP_KERNEL);
1009 		else
1010 			full_postfix = kasprintf(GFP_KERNEL,
1011 						 "%s_%s",
1012 						 chan->extend_name,
1013 						 postfix);
1014 	}
1015 	if (full_postfix == NULL)
1016 		return -ENOMEM;
1017 
1018 	if (chan->differential) { /* Differential can not have modifier */
1019 		switch (shared_by) {
1020 		case IIO_SHARED_BY_ALL:
1021 			name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1022 			break;
1023 		case IIO_SHARED_BY_DIR:
1024 			name = kasprintf(GFP_KERNEL, "%s_%s",
1025 						iio_direction[chan->output],
1026 						full_postfix);
1027 			break;
1028 		case IIO_SHARED_BY_TYPE:
1029 			name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
1030 					    iio_direction[chan->output],
1031 					    iio_chan_type_name_spec[chan->type],
1032 					    iio_chan_type_name_spec[chan->type],
1033 					    full_postfix);
1034 			break;
1035 		case IIO_SEPARATE:
1036 			if (!chan->indexed) {
1037 				WARN(1, "Differential channels must be indexed\n");
1038 				ret = -EINVAL;
1039 				goto error_free_full_postfix;
1040 			}
1041 			name = kasprintf(GFP_KERNEL,
1042 					    "%s_%s%d-%s%d_%s",
1043 					    iio_direction[chan->output],
1044 					    iio_chan_type_name_spec[chan->type],
1045 					    chan->channel,
1046 					    iio_chan_type_name_spec[chan->type],
1047 					    chan->channel2,
1048 					    full_postfix);
1049 			break;
1050 		}
1051 	} else { /* Single ended */
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",
1063 					    iio_direction[chan->output],
1064 					    iio_chan_type_name_spec[chan->type],
1065 					    full_postfix);
1066 			break;
1067 
1068 		case IIO_SEPARATE:
1069 			if (chan->indexed)
1070 				name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
1071 						    iio_direction[chan->output],
1072 						    iio_chan_type_name_spec[chan->type],
1073 						    chan->channel,
1074 						    full_postfix);
1075 			else
1076 				name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1077 						    iio_direction[chan->output],
1078 						    iio_chan_type_name_spec[chan->type],
1079 						    full_postfix);
1080 			break;
1081 		}
1082 	}
1083 	if (name == NULL) {
1084 		ret = -ENOMEM;
1085 		goto error_free_full_postfix;
1086 	}
1087 	dev_attr->attr.name = name;
1088 
1089 	if (readfunc) {
1090 		dev_attr->attr.mode |= S_IRUGO;
1091 		dev_attr->show = readfunc;
1092 	}
1093 
1094 	if (writefunc) {
1095 		dev_attr->attr.mode |= S_IWUSR;
1096 		dev_attr->store = writefunc;
1097 	}
1098 
1099 error_free_full_postfix:
1100 	kfree(full_postfix);
1101 
1102 	return ret;
1103 }
1104 
1105 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
1106 {
1107 	kfree(dev_attr->attr.name);
1108 }
1109 
1110 int __iio_add_chan_devattr(const char *postfix,
1111 			   struct iio_chan_spec const *chan,
1112 			   ssize_t (*readfunc)(struct device *dev,
1113 					       struct device_attribute *attr,
1114 					       char *buf),
1115 			   ssize_t (*writefunc)(struct device *dev,
1116 						struct device_attribute *attr,
1117 						const char *buf,
1118 						size_t len),
1119 			   u64 mask,
1120 			   enum iio_shared_by shared_by,
1121 			   struct device *dev,
1122 			   struct list_head *attr_list)
1123 {
1124 	int ret;
1125 	struct iio_dev_attr *iio_attr, *t;
1126 
1127 	iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
1128 	if (iio_attr == NULL)
1129 		return -ENOMEM;
1130 	ret = __iio_device_attr_init(&iio_attr->dev_attr,
1131 				     postfix, chan,
1132 				     readfunc, writefunc, shared_by);
1133 	if (ret)
1134 		goto error_iio_dev_attr_free;
1135 	iio_attr->c = chan;
1136 	iio_attr->address = mask;
1137 	list_for_each_entry(t, attr_list, l)
1138 		if (strcmp(t->dev_attr.attr.name,
1139 			   iio_attr->dev_attr.attr.name) == 0) {
1140 			if (shared_by == IIO_SEPARATE)
1141 				dev_err(dev, "tried to double register : %s\n",
1142 					t->dev_attr.attr.name);
1143 			ret = -EBUSY;
1144 			goto error_device_attr_deinit;
1145 		}
1146 	list_add(&iio_attr->l, attr_list);
1147 
1148 	return 0;
1149 
1150 error_device_attr_deinit:
1151 	__iio_device_attr_deinit(&iio_attr->dev_attr);
1152 error_iio_dev_attr_free:
1153 	kfree(iio_attr);
1154 	return ret;
1155 }
1156 
1157 static int iio_device_add_channel_label(struct iio_dev *indio_dev,
1158 					 struct iio_chan_spec const *chan)
1159 {
1160 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1161 	int ret;
1162 
1163 	if (!indio_dev->info->read_label)
1164 		return 0;
1165 
1166 	ret = __iio_add_chan_devattr("label",
1167 				     chan,
1168 				     &iio_read_channel_label,
1169 				     NULL,
1170 				     0,
1171 				     IIO_SEPARATE,
1172 				     &indio_dev->dev,
1173 				     &iio_dev_opaque->channel_attr_list);
1174 	if (ret < 0)
1175 		return ret;
1176 
1177 	return 1;
1178 }
1179 
1180 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
1181 					 struct iio_chan_spec const *chan,
1182 					 enum iio_shared_by shared_by,
1183 					 const long *infomask)
1184 {
1185 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1186 	int i, ret, attrcount = 0;
1187 
1188 	for_each_set_bit(i, infomask, sizeof(*infomask)*8) {
1189 		if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1190 			return -EINVAL;
1191 		ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
1192 					     chan,
1193 					     &iio_read_channel_info,
1194 					     &iio_write_channel_info,
1195 					     i,
1196 					     shared_by,
1197 					     &indio_dev->dev,
1198 					     &iio_dev_opaque->channel_attr_list);
1199 		if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1200 			continue;
1201 		else if (ret < 0)
1202 			return ret;
1203 		attrcount++;
1204 	}
1205 
1206 	return attrcount;
1207 }
1208 
1209 static int iio_device_add_info_mask_type_avail(struct iio_dev *indio_dev,
1210 					       struct iio_chan_spec const *chan,
1211 					       enum iio_shared_by shared_by,
1212 					       const long *infomask)
1213 {
1214 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1215 	int i, ret, attrcount = 0;
1216 	char *avail_postfix;
1217 
1218 	for_each_set_bit(i, infomask, sizeof(*infomask) * 8) {
1219 		if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1220 			return -EINVAL;
1221 		avail_postfix = kasprintf(GFP_KERNEL,
1222 					  "%s_available",
1223 					  iio_chan_info_postfix[i]);
1224 		if (!avail_postfix)
1225 			return -ENOMEM;
1226 
1227 		ret = __iio_add_chan_devattr(avail_postfix,
1228 					     chan,
1229 					     &iio_read_channel_info_avail,
1230 					     NULL,
1231 					     i,
1232 					     shared_by,
1233 					     &indio_dev->dev,
1234 					     &iio_dev_opaque->channel_attr_list);
1235 		kfree(avail_postfix);
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_channel_sysfs(struct iio_dev *indio_dev,
1247 					struct iio_chan_spec const *chan)
1248 {
1249 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1250 	int ret, attrcount = 0;
1251 	const struct iio_chan_spec_ext_info *ext_info;
1252 
1253 	if (chan->channel < 0)
1254 		return 0;
1255 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1256 					    IIO_SEPARATE,
1257 					    &chan->info_mask_separate);
1258 	if (ret < 0)
1259 		return ret;
1260 	attrcount += ret;
1261 
1262 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1263 						  IIO_SEPARATE,
1264 						  &chan->
1265 						  info_mask_separate_available);
1266 	if (ret < 0)
1267 		return ret;
1268 	attrcount += ret;
1269 
1270 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1271 					    IIO_SHARED_BY_TYPE,
1272 					    &chan->info_mask_shared_by_type);
1273 	if (ret < 0)
1274 		return ret;
1275 	attrcount += ret;
1276 
1277 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1278 						  IIO_SHARED_BY_TYPE,
1279 						  &chan->
1280 						  info_mask_shared_by_type_available);
1281 	if (ret < 0)
1282 		return ret;
1283 	attrcount += ret;
1284 
1285 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1286 					    IIO_SHARED_BY_DIR,
1287 					    &chan->info_mask_shared_by_dir);
1288 	if (ret < 0)
1289 		return ret;
1290 	attrcount += ret;
1291 
1292 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1293 						  IIO_SHARED_BY_DIR,
1294 						  &chan->info_mask_shared_by_dir_available);
1295 	if (ret < 0)
1296 		return ret;
1297 	attrcount += ret;
1298 
1299 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1300 					    IIO_SHARED_BY_ALL,
1301 					    &chan->info_mask_shared_by_all);
1302 	if (ret < 0)
1303 		return ret;
1304 	attrcount += ret;
1305 
1306 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1307 						  IIO_SHARED_BY_ALL,
1308 						  &chan->info_mask_shared_by_all_available);
1309 	if (ret < 0)
1310 		return ret;
1311 	attrcount += ret;
1312 
1313 	ret = iio_device_add_channel_label(indio_dev, chan);
1314 	if (ret < 0)
1315 		return ret;
1316 	attrcount += ret;
1317 
1318 	if (chan->ext_info) {
1319 		unsigned int i = 0;
1320 		for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
1321 			ret = __iio_add_chan_devattr(ext_info->name,
1322 					chan,
1323 					ext_info->read ?
1324 					    &iio_read_channel_ext_info : NULL,
1325 					ext_info->write ?
1326 					    &iio_write_channel_ext_info : NULL,
1327 					i,
1328 					ext_info->shared,
1329 					&indio_dev->dev,
1330 					&iio_dev_opaque->channel_attr_list);
1331 			i++;
1332 			if (ret == -EBUSY && ext_info->shared)
1333 				continue;
1334 
1335 			if (ret)
1336 				return ret;
1337 
1338 			attrcount++;
1339 		}
1340 	}
1341 
1342 	return attrcount;
1343 }
1344 
1345 /**
1346  * iio_free_chan_devattr_list() - Free a list of IIO device attributes
1347  * @attr_list: List of IIO device attributes
1348  *
1349  * This function frees the memory allocated for each of the IIO device
1350  * attributes in the list.
1351  */
1352 void iio_free_chan_devattr_list(struct list_head *attr_list)
1353 {
1354 	struct iio_dev_attr *p, *n;
1355 
1356 	list_for_each_entry_safe(p, n, attr_list, l) {
1357 		kfree(p->dev_attr.attr.name);
1358 		list_del(&p->l);
1359 		kfree(p);
1360 	}
1361 }
1362 
1363 static ssize_t iio_show_dev_name(struct device *dev,
1364 				 struct device_attribute *attr,
1365 				 char *buf)
1366 {
1367 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1368 	return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->name);
1369 }
1370 
1371 static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
1372 
1373 static ssize_t iio_show_dev_label(struct device *dev,
1374 				 struct device_attribute *attr,
1375 				 char *buf)
1376 {
1377 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1378 	return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->label);
1379 }
1380 
1381 static DEVICE_ATTR(label, S_IRUGO, iio_show_dev_label, NULL);
1382 
1383 static ssize_t iio_show_timestamp_clock(struct device *dev,
1384 					struct device_attribute *attr,
1385 					char *buf)
1386 {
1387 	const struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1388 	const clockid_t clk = iio_device_get_clock(indio_dev);
1389 	const char *name;
1390 	ssize_t sz;
1391 
1392 	switch (clk) {
1393 	case CLOCK_REALTIME:
1394 		name = "realtime\n";
1395 		sz = sizeof("realtime\n");
1396 		break;
1397 	case CLOCK_MONOTONIC:
1398 		name = "monotonic\n";
1399 		sz = sizeof("monotonic\n");
1400 		break;
1401 	case CLOCK_MONOTONIC_RAW:
1402 		name = "monotonic_raw\n";
1403 		sz = sizeof("monotonic_raw\n");
1404 		break;
1405 	case CLOCK_REALTIME_COARSE:
1406 		name = "realtime_coarse\n";
1407 		sz = sizeof("realtime_coarse\n");
1408 		break;
1409 	case CLOCK_MONOTONIC_COARSE:
1410 		name = "monotonic_coarse\n";
1411 		sz = sizeof("monotonic_coarse\n");
1412 		break;
1413 	case CLOCK_BOOTTIME:
1414 		name = "boottime\n";
1415 		sz = sizeof("boottime\n");
1416 		break;
1417 	case CLOCK_TAI:
1418 		name = "tai\n";
1419 		sz = sizeof("tai\n");
1420 		break;
1421 	default:
1422 		BUG();
1423 	}
1424 
1425 	memcpy(buf, name, sz);
1426 	return sz;
1427 }
1428 
1429 static ssize_t iio_store_timestamp_clock(struct device *dev,
1430 					 struct device_attribute *attr,
1431 					 const char *buf, size_t len)
1432 {
1433 	clockid_t clk;
1434 	int ret;
1435 
1436 	if (sysfs_streq(buf, "realtime"))
1437 		clk = CLOCK_REALTIME;
1438 	else if (sysfs_streq(buf, "monotonic"))
1439 		clk = CLOCK_MONOTONIC;
1440 	else if (sysfs_streq(buf, "monotonic_raw"))
1441 		clk = CLOCK_MONOTONIC_RAW;
1442 	else if (sysfs_streq(buf, "realtime_coarse"))
1443 		clk = CLOCK_REALTIME_COARSE;
1444 	else if (sysfs_streq(buf, "monotonic_coarse"))
1445 		clk = CLOCK_MONOTONIC_COARSE;
1446 	else if (sysfs_streq(buf, "boottime"))
1447 		clk = CLOCK_BOOTTIME;
1448 	else if (sysfs_streq(buf, "tai"))
1449 		clk = CLOCK_TAI;
1450 	else
1451 		return -EINVAL;
1452 
1453 	ret = iio_device_set_clock(dev_to_iio_dev(dev), clk);
1454 	if (ret)
1455 		return ret;
1456 
1457 	return len;
1458 }
1459 
1460 static DEVICE_ATTR(current_timestamp_clock, S_IRUGO | S_IWUSR,
1461 		   iio_show_timestamp_clock, iio_store_timestamp_clock);
1462 
1463 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
1464 {
1465 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1466 	int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
1467 	struct iio_dev_attr *p;
1468 	struct attribute **attr, *clk = NULL;
1469 
1470 	/* First count elements in any existing group */
1471 	if (indio_dev->info->attrs) {
1472 		attr = indio_dev->info->attrs->attrs;
1473 		while (*attr++ != NULL)
1474 			attrcount_orig++;
1475 	}
1476 	attrcount = attrcount_orig;
1477 	/*
1478 	 * New channel registration method - relies on the fact a group does
1479 	 * not need to be initialized if its name is NULL.
1480 	 */
1481 	if (indio_dev->channels)
1482 		for (i = 0; i < indio_dev->num_channels; i++) {
1483 			const struct iio_chan_spec *chan =
1484 				&indio_dev->channels[i];
1485 
1486 			if (chan->type == IIO_TIMESTAMP)
1487 				clk = &dev_attr_current_timestamp_clock.attr;
1488 
1489 			ret = iio_device_add_channel_sysfs(indio_dev, chan);
1490 			if (ret < 0)
1491 				goto error_clear_attrs;
1492 			attrcount += ret;
1493 		}
1494 
1495 	if (iio_dev_opaque->event_interface)
1496 		clk = &dev_attr_current_timestamp_clock.attr;
1497 
1498 	if (indio_dev->name)
1499 		attrcount++;
1500 	if (indio_dev->label)
1501 		attrcount++;
1502 	if (clk)
1503 		attrcount++;
1504 
1505 	iio_dev_opaque->chan_attr_group.attrs =
1506 		kcalloc(attrcount + 1,
1507 			sizeof(iio_dev_opaque->chan_attr_group.attrs[0]),
1508 			GFP_KERNEL);
1509 	if (iio_dev_opaque->chan_attr_group.attrs == NULL) {
1510 		ret = -ENOMEM;
1511 		goto error_clear_attrs;
1512 	}
1513 	/* Copy across original attributes */
1514 	if (indio_dev->info->attrs)
1515 		memcpy(iio_dev_opaque->chan_attr_group.attrs,
1516 		       indio_dev->info->attrs->attrs,
1517 		       sizeof(iio_dev_opaque->chan_attr_group.attrs[0])
1518 		       *attrcount_orig);
1519 	attrn = attrcount_orig;
1520 	/* Add all elements from the list. */
1521 	list_for_each_entry(p, &iio_dev_opaque->channel_attr_list, l)
1522 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1523 	if (indio_dev->name)
1524 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
1525 	if (indio_dev->label)
1526 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_label.attr;
1527 	if (clk)
1528 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = clk;
1529 
1530 	indio_dev->groups[indio_dev->groupcounter++] =
1531 		&iio_dev_opaque->chan_attr_group;
1532 
1533 	return 0;
1534 
1535 error_clear_attrs:
1536 	iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1537 
1538 	return ret;
1539 }
1540 
1541 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
1542 {
1543 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1544 
1545 	iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1546 	kfree(iio_dev_opaque->chan_attr_group.attrs);
1547 	iio_dev_opaque->chan_attr_group.attrs = NULL;
1548 }
1549 
1550 static void iio_dev_release(struct device *device)
1551 {
1552 	struct iio_dev *indio_dev = dev_to_iio_dev(device);
1553 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1554 
1555 	if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1556 		iio_device_unregister_trigger_consumer(indio_dev);
1557 	iio_device_unregister_eventset(indio_dev);
1558 	iio_device_unregister_sysfs(indio_dev);
1559 
1560 	iio_buffer_put(indio_dev->buffer);
1561 
1562 	ida_simple_remove(&iio_ida, indio_dev->id);
1563 	kfree(iio_dev_opaque);
1564 }
1565 
1566 struct device_type iio_device_type = {
1567 	.name = "iio_device",
1568 	.release = iio_dev_release,
1569 };
1570 
1571 /**
1572  * iio_device_alloc() - allocate an iio_dev from a driver
1573  * @parent:		Parent device.
1574  * @sizeof_priv:	Space to allocate for private structure.
1575  **/
1576 struct iio_dev *iio_device_alloc(struct device *parent, int sizeof_priv)
1577 {
1578 	struct iio_dev_opaque *iio_dev_opaque;
1579 	struct iio_dev *dev;
1580 	size_t alloc_size;
1581 
1582 	alloc_size = sizeof(struct iio_dev_opaque);
1583 	if (sizeof_priv) {
1584 		alloc_size = ALIGN(alloc_size, IIO_ALIGN);
1585 		alloc_size += sizeof_priv;
1586 	}
1587 
1588 	iio_dev_opaque = kzalloc(alloc_size, GFP_KERNEL);
1589 	if (!iio_dev_opaque)
1590 		return NULL;
1591 
1592 	dev = &iio_dev_opaque->indio_dev;
1593 	dev->priv = (char *)iio_dev_opaque +
1594 		ALIGN(sizeof(struct iio_dev_opaque), IIO_ALIGN);
1595 
1596 	dev->dev.parent = parent;
1597 	dev->dev.groups = dev->groups;
1598 	dev->dev.type = &iio_device_type;
1599 	dev->dev.bus = &iio_bus_type;
1600 	device_initialize(&dev->dev);
1601 	dev_set_drvdata(&dev->dev, (void *)dev);
1602 	mutex_init(&dev->mlock);
1603 	mutex_init(&dev->info_exist_lock);
1604 	INIT_LIST_HEAD(&iio_dev_opaque->channel_attr_list);
1605 
1606 	dev->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
1607 	if (dev->id < 0) {
1608 		/* cannot use a dev_err as the name isn't available */
1609 		pr_err("failed to get device id\n");
1610 		kfree(iio_dev_opaque);
1611 		return NULL;
1612 	}
1613 	dev_set_name(&dev->dev, "iio:device%d", dev->id);
1614 	INIT_LIST_HEAD(&iio_dev_opaque->buffer_list);
1615 	INIT_LIST_HEAD(&iio_dev_opaque->ioctl_handlers);
1616 
1617 	return dev;
1618 }
1619 EXPORT_SYMBOL(iio_device_alloc);
1620 
1621 /**
1622  * iio_device_free() - free an iio_dev from a driver
1623  * @dev:		the iio_dev associated with the device
1624  **/
1625 void iio_device_free(struct iio_dev *dev)
1626 {
1627 	if (dev)
1628 		put_device(&dev->dev);
1629 }
1630 EXPORT_SYMBOL(iio_device_free);
1631 
1632 static void devm_iio_device_release(struct device *dev, void *res)
1633 {
1634 	iio_device_free(*(struct iio_dev **)res);
1635 }
1636 
1637 /**
1638  * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1639  * @parent:		Device to allocate iio_dev for, and parent for this IIO device
1640  * @sizeof_priv:	Space to allocate for private structure.
1641  *
1642  * Managed iio_device_alloc. iio_dev allocated with this function is
1643  * automatically freed on driver detach.
1644  *
1645  * RETURNS:
1646  * Pointer to allocated iio_dev on success, NULL on failure.
1647  */
1648 struct iio_dev *devm_iio_device_alloc(struct device *parent, int sizeof_priv)
1649 {
1650 	struct iio_dev **ptr, *iio_dev;
1651 
1652 	ptr = devres_alloc(devm_iio_device_release, sizeof(*ptr),
1653 			   GFP_KERNEL);
1654 	if (!ptr)
1655 		return NULL;
1656 
1657 	iio_dev = iio_device_alloc(parent, sizeof_priv);
1658 	if (iio_dev) {
1659 		*ptr = iio_dev;
1660 		devres_add(parent, ptr);
1661 	} else {
1662 		devres_free(ptr);
1663 	}
1664 
1665 	return iio_dev;
1666 }
1667 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1668 
1669 /**
1670  * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1671  * @inode:	Inode structure for identifying the device in the file system
1672  * @filp:	File structure for iio device used to keep and later access
1673  *		private data
1674  *
1675  * Return: 0 on success or -EBUSY if the device is already opened
1676  **/
1677 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1678 {
1679 	struct iio_dev *indio_dev = container_of(inode->i_cdev,
1680 						struct iio_dev, chrdev);
1681 
1682 	if (test_and_set_bit(IIO_BUSY_BIT_POS, &indio_dev->flags))
1683 		return -EBUSY;
1684 
1685 	iio_device_get(indio_dev);
1686 
1687 	filp->private_data = indio_dev;
1688 
1689 	return 0;
1690 }
1691 
1692 /**
1693  * iio_chrdev_release() - chrdev file close buffer access and ioctls
1694  * @inode:	Inode structure pointer for the char device
1695  * @filp:	File structure pointer for the char device
1696  *
1697  * Return: 0 for successful release
1698  */
1699 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1700 {
1701 	struct iio_dev *indio_dev = container_of(inode->i_cdev,
1702 						struct iio_dev, chrdev);
1703 	clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
1704 	iio_device_put(indio_dev);
1705 
1706 	return 0;
1707 }
1708 
1709 void iio_device_ioctl_handler_register(struct iio_dev *indio_dev,
1710 				       struct iio_ioctl_handler *h)
1711 {
1712 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1713 
1714 	list_add_tail(&h->entry, &iio_dev_opaque->ioctl_handlers);
1715 }
1716 
1717 void iio_device_ioctl_handler_unregister(struct iio_ioctl_handler *h)
1718 {
1719 	list_del(&h->entry);
1720 }
1721 
1722 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1723 {
1724 	struct iio_dev *indio_dev = filp->private_data;
1725 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1726 	struct iio_ioctl_handler *h;
1727 	int ret = -ENODEV;
1728 
1729 	mutex_lock(&indio_dev->info_exist_lock);
1730 
1731 	/**
1732 	 * The NULL check here is required to prevent crashing when a device
1733 	 * is being removed while userspace would still have open file handles
1734 	 * to try to access this device.
1735 	 */
1736 	if (!indio_dev->info)
1737 		goto out_unlock;
1738 
1739 	ret = -EINVAL;
1740 	list_for_each_entry(h, &iio_dev_opaque->ioctl_handlers, entry) {
1741 		ret = h->ioctl(indio_dev, filp, cmd, arg);
1742 		if (ret != IIO_IOCTL_UNHANDLED)
1743 			break;
1744 	}
1745 
1746 	if (ret == IIO_IOCTL_UNHANDLED)
1747 		ret = -EINVAL;
1748 
1749 out_unlock:
1750 	mutex_unlock(&indio_dev->info_exist_lock);
1751 
1752 	return ret;
1753 }
1754 
1755 static const struct file_operations iio_buffer_fileops = {
1756 	.owner = THIS_MODULE,
1757 	.llseek = noop_llseek,
1758 	.read = iio_buffer_read_outer_addr,
1759 	.poll = iio_buffer_poll_addr,
1760 	.unlocked_ioctl = iio_ioctl,
1761 	.compat_ioctl = compat_ptr_ioctl,
1762 	.open = iio_chrdev_open,
1763 	.release = iio_chrdev_release,
1764 };
1765 
1766 static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1767 {
1768 	int i, j;
1769 	const struct iio_chan_spec *channels = indio_dev->channels;
1770 
1771 	if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1772 		return 0;
1773 
1774 	for (i = 0; i < indio_dev->num_channels - 1; i++) {
1775 		if (channels[i].scan_index < 0)
1776 			continue;
1777 		for (j = i + 1; j < indio_dev->num_channels; j++)
1778 			if (channels[i].scan_index == channels[j].scan_index) {
1779 				dev_err(&indio_dev->dev,
1780 					"Duplicate scan index %d\n",
1781 					channels[i].scan_index);
1782 				return -EINVAL;
1783 			}
1784 	}
1785 
1786 	return 0;
1787 }
1788 
1789 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1790 
1791 int __iio_device_register(struct iio_dev *indio_dev, struct module *this_mod)
1792 {
1793 	int ret;
1794 
1795 	if (!indio_dev->info)
1796 		return -EINVAL;
1797 
1798 	indio_dev->driver_module = this_mod;
1799 	/* If the calling driver did not initialize of_node, do it here */
1800 	if (!indio_dev->dev.of_node && indio_dev->dev.parent)
1801 		indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
1802 
1803 	indio_dev->label = of_get_property(indio_dev->dev.of_node, "label",
1804 					   NULL);
1805 
1806 	ret = iio_check_unique_scan_index(indio_dev);
1807 	if (ret < 0)
1808 		return ret;
1809 
1810 	/* configure elements for the chrdev */
1811 	indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), indio_dev->id);
1812 
1813 	iio_device_register_debugfs(indio_dev);
1814 
1815 	ret = iio_buffer_alloc_sysfs_and_mask(indio_dev);
1816 	if (ret) {
1817 		dev_err(indio_dev->dev.parent,
1818 			"Failed to create buffer sysfs interfaces\n");
1819 		goto error_unreg_debugfs;
1820 	}
1821 
1822 	ret = iio_device_register_sysfs(indio_dev);
1823 	if (ret) {
1824 		dev_err(indio_dev->dev.parent,
1825 			"Failed to register sysfs interfaces\n");
1826 		goto error_buffer_free_sysfs;
1827 	}
1828 	ret = iio_device_register_eventset(indio_dev);
1829 	if (ret) {
1830 		dev_err(indio_dev->dev.parent,
1831 			"Failed to register event set\n");
1832 		goto error_free_sysfs;
1833 	}
1834 	if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1835 		iio_device_register_trigger_consumer(indio_dev);
1836 
1837 	if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1838 		indio_dev->setup_ops == NULL)
1839 		indio_dev->setup_ops = &noop_ring_setup_ops;
1840 
1841 	cdev_init(&indio_dev->chrdev, &iio_buffer_fileops);
1842 
1843 	indio_dev->chrdev.owner = this_mod;
1844 
1845 	ret = cdev_device_add(&indio_dev->chrdev, &indio_dev->dev);
1846 	if (ret < 0)
1847 		goto error_unreg_eventset;
1848 
1849 	return 0;
1850 
1851 error_unreg_eventset:
1852 	iio_device_unregister_eventset(indio_dev);
1853 error_free_sysfs:
1854 	iio_device_unregister_sysfs(indio_dev);
1855 error_buffer_free_sysfs:
1856 	iio_buffer_free_sysfs_and_mask(indio_dev);
1857 error_unreg_debugfs:
1858 	iio_device_unregister_debugfs(indio_dev);
1859 	return ret;
1860 }
1861 EXPORT_SYMBOL(__iio_device_register);
1862 
1863 /**
1864  * iio_device_unregister() - unregister a device from the IIO subsystem
1865  * @indio_dev:		Device structure representing the device.
1866  **/
1867 void iio_device_unregister(struct iio_dev *indio_dev)
1868 {
1869 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1870 	struct iio_ioctl_handler *h, *t;
1871 
1872 	cdev_device_del(&indio_dev->chrdev, &indio_dev->dev);
1873 
1874 	mutex_lock(&indio_dev->info_exist_lock);
1875 
1876 	iio_device_unregister_debugfs(indio_dev);
1877 
1878 	iio_disable_all_buffers(indio_dev);
1879 
1880 	indio_dev->info = NULL;
1881 
1882 	list_for_each_entry_safe(h, t, &iio_dev_opaque->ioctl_handlers, entry)
1883 		list_del(&h->entry);
1884 
1885 	iio_device_wakeup_eventset(indio_dev);
1886 	iio_buffer_wakeup_poll(indio_dev);
1887 
1888 	mutex_unlock(&indio_dev->info_exist_lock);
1889 
1890 	iio_buffer_free_sysfs_and_mask(indio_dev);
1891 }
1892 EXPORT_SYMBOL(iio_device_unregister);
1893 
1894 static void devm_iio_device_unreg(struct device *dev, void *res)
1895 {
1896 	iio_device_unregister(*(struct iio_dev **)res);
1897 }
1898 
1899 int __devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev,
1900 			       struct module *this_mod)
1901 {
1902 	struct iio_dev **ptr;
1903 	int ret;
1904 
1905 	ptr = devres_alloc(devm_iio_device_unreg, sizeof(*ptr), GFP_KERNEL);
1906 	if (!ptr)
1907 		return -ENOMEM;
1908 
1909 	*ptr = indio_dev;
1910 	ret = __iio_device_register(indio_dev, this_mod);
1911 	if (!ret)
1912 		devres_add(dev, ptr);
1913 	else
1914 		devres_free(ptr);
1915 
1916 	return ret;
1917 }
1918 EXPORT_SYMBOL_GPL(__devm_iio_device_register);
1919 
1920 /**
1921  * iio_device_claim_direct_mode - Keep device in direct mode
1922  * @indio_dev:	the iio_dev associated with the device
1923  *
1924  * If the device is in direct mode it is guaranteed to stay
1925  * that way until iio_device_release_direct_mode() is called.
1926  *
1927  * Use with iio_device_release_direct_mode()
1928  *
1929  * Returns: 0 on success, -EBUSY on failure
1930  */
1931 int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
1932 {
1933 	mutex_lock(&indio_dev->mlock);
1934 
1935 	if (iio_buffer_enabled(indio_dev)) {
1936 		mutex_unlock(&indio_dev->mlock);
1937 		return -EBUSY;
1938 	}
1939 	return 0;
1940 }
1941 EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
1942 
1943 /**
1944  * iio_device_release_direct_mode - releases claim on direct mode
1945  * @indio_dev:	the iio_dev associated with the device
1946  *
1947  * Release the claim. Device is no longer guaranteed to stay
1948  * in direct mode.
1949  *
1950  * Use with iio_device_claim_direct_mode()
1951  */
1952 void iio_device_release_direct_mode(struct iio_dev *indio_dev)
1953 {
1954 	mutex_unlock(&indio_dev->mlock);
1955 }
1956 EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
1957 
1958 subsys_initcall(iio_init);
1959 module_exit(iio_exit);
1960 
1961 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1962 MODULE_DESCRIPTION("Industrial I/O core");
1963 MODULE_LICENSE("GPL");
1964