• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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  */
iio_get_debugfs_dentry(struct iio_dev * indio_dev)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
iio_find_channel_from_si(struct iio_dev * indio_dev,int si)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 */
iio_read_const_attr(struct device * dev,struct device_attribute * attr,char * buf)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  */
iio_device_set_clock(struct iio_dev * indio_dev,clockid_t clock_id)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  */
iio_get_time_ns(const struct iio_dev * indio_dev)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  */
iio_get_time_res(const struct iio_dev * indio_dev)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 
iio_init(void)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 
iio_exit(void)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)
iio_debugfs_read_reg(struct file * file,char __user * userbuf,size_t count,loff_t * ppos)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 
iio_debugfs_write_reg(struct file * file,const char __user * userbuf,size_t count,loff_t * ppos)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 
iio_device_unregister_debugfs(struct iio_dev * indio_dev)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 
iio_device_register_debugfs(struct iio_dev * indio_dev)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
iio_device_register_debugfs(struct iio_dev * indio_dev)426 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
427 {
428 }
429 
iio_device_unregister_debugfs(struct iio_dev * indio_dev)430 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
431 {
432 }
433 #endif /* CONFIG_DEBUG_FS */
434 
iio_read_channel_ext_info(struct device * dev,struct device_attribute * attr,char * buf)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 
iio_write_channel_ext_info(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)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 
iio_enum_available_read(struct iio_dev * indio_dev,uintptr_t priv,const struct iio_chan_spec * chan,char * buf)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 
iio_enum_read(struct iio_dev * indio_dev,uintptr_t priv,const struct iio_chan_spec * chan,char * buf)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 
iio_enum_write(struct iio_dev * indio_dev,uintptr_t priv,const struct iio_chan_spec * chan,const char * buf,size_t len)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 
iio_setup_mount_idmatrix(const struct device * dev,struct iio_mount_matrix * matrix)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 
iio_show_mount_matrix(struct iio_dev * indio_dev,uintptr_t priv,const struct iio_chan_spec * chan,char * buf)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  */
iio_read_mount_matrix(struct device * dev,const char * propname,struct iio_mount_matrix * matrix)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 
__iio_format_value(char * buf,size_t len,unsigned int type,int size,const int * vals)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 	bool scale_db = false;
598 
599 	switch (type) {
600 	case IIO_VAL_INT:
601 		return scnprintf(buf, len, "%d", vals[0]);
602 	case IIO_VAL_INT_PLUS_MICRO_DB:
603 		scale_db = true;
604 		fallthrough;
605 	case IIO_VAL_INT_PLUS_MICRO:
606 		if (vals[1] < 0)
607 			return scnprintf(buf, len, "-%d.%06u%s", abs(vals[0]),
608 					-vals[1], scale_db ? " dB" : "");
609 		else
610 			return scnprintf(buf, len, "%d.%06u%s", vals[0], vals[1],
611 					scale_db ? " dB" : "");
612 	case IIO_VAL_INT_PLUS_NANO:
613 		if (vals[1] < 0)
614 			return scnprintf(buf, len, "-%d.%09u", abs(vals[0]),
615 					-vals[1]);
616 		else
617 			return scnprintf(buf, len, "%d.%09u", vals[0], vals[1]);
618 	case IIO_VAL_FRACTIONAL:
619 		tmp = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
620 		tmp1 = vals[1];
621 		tmp0 = (int)div_s64_rem(tmp, 1000000000, &tmp1);
622 		return scnprintf(buf, len, "%d.%09u", tmp0, abs(tmp1));
623 	case IIO_VAL_FRACTIONAL_LOG2:
624 		tmp = shift_right((s64)vals[0] * 1000000000LL, vals[1]);
625 		tmp0 = (int)div_s64_rem(tmp, 1000000000LL, &tmp1);
626 		return scnprintf(buf, len, "%d.%09u", tmp0, abs(tmp1));
627 	case IIO_VAL_INT_MULTIPLE:
628 	{
629 		int i;
630 		int l = 0;
631 
632 		for (i = 0; i < size; ++i) {
633 			l += scnprintf(&buf[l], len - l, "%d ", vals[i]);
634 			if (l >= len)
635 				break;
636 		}
637 		return l;
638 	}
639 	case IIO_VAL_CHAR:
640 		return scnprintf(buf, len, "%c", (char)vals[0]);
641 	default:
642 		return 0;
643 	}
644 }
645 
646 /**
647  * iio_format_value() - Formats a IIO value into its string representation
648  * @buf:	The buffer to which the formatted value gets written
649  *		which is assumed to be big enough (i.e. PAGE_SIZE).
650  * @type:	One of the IIO_VAL_* constants. This decides how the val
651  *		and val2 parameters are formatted.
652  * @size:	Number of IIO value entries contained in vals
653  * @vals:	Pointer to the values, exact meaning depends on the
654  *		type parameter.
655  *
656  * Return: 0 by default, a negative number on failure or the
657  *	   total number of characters written for a type that belongs
658  *	   to the IIO_VAL_* constant.
659  */
iio_format_value(char * buf,unsigned int type,int size,int * vals)660 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
661 {
662 	ssize_t len;
663 
664 	len = __iio_format_value(buf, PAGE_SIZE, type, size, vals);
665 	if (len >= PAGE_SIZE - 1)
666 		return -EFBIG;
667 
668 	return len + sprintf(buf + len, "\n");
669 }
670 EXPORT_SYMBOL_GPL(iio_format_value);
671 
iio_read_channel_info(struct device * dev,struct device_attribute * attr,char * buf)672 static ssize_t iio_read_channel_info(struct device *dev,
673 				     struct device_attribute *attr,
674 				     char *buf)
675 {
676 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
677 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
678 	int vals[INDIO_MAX_RAW_ELEMENTS];
679 	int ret;
680 	int val_len = 2;
681 
682 	if (indio_dev->info->read_raw_multi)
683 		ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
684 							INDIO_MAX_RAW_ELEMENTS,
685 							vals, &val_len,
686 							this_attr->address);
687 	else if (indio_dev->info->read_raw)
688 		ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
689 				    &vals[0], &vals[1], this_attr->address);
690 	else
691 		return -EINVAL;
692 
693 	if (ret < 0)
694 		return ret;
695 
696 	return iio_format_value(buf, ret, val_len, vals);
697 }
698 
iio_format_avail_list(char * buf,const int * vals,int type,int length)699 static ssize_t iio_format_avail_list(char *buf, const int *vals,
700 				     int type, int length)
701 {
702 	int i;
703 	ssize_t len = 0;
704 
705 	switch (type) {
706 	case IIO_VAL_INT:
707 		for (i = 0; i < length; i++) {
708 			len += __iio_format_value(buf + len, PAGE_SIZE - len,
709 						  type, 1, &vals[i]);
710 			if (len >= PAGE_SIZE)
711 				return -EFBIG;
712 			if (i < length - 1)
713 				len += scnprintf(buf + len, PAGE_SIZE - len,
714 						" ");
715 			else
716 				len += scnprintf(buf + len, PAGE_SIZE - len,
717 						"\n");
718 			if (len >= PAGE_SIZE)
719 				return -EFBIG;
720 		}
721 		break;
722 	default:
723 		for (i = 0; i < length / 2; i++) {
724 			len += __iio_format_value(buf + len, PAGE_SIZE - len,
725 						  type, 2, &vals[i * 2]);
726 			if (len >= PAGE_SIZE)
727 				return -EFBIG;
728 			if (i < length / 2 - 1)
729 				len += scnprintf(buf + len, PAGE_SIZE - len,
730 						" ");
731 			else
732 				len += scnprintf(buf + len, PAGE_SIZE - len,
733 						"\n");
734 			if (len >= PAGE_SIZE)
735 				return -EFBIG;
736 		}
737 	}
738 
739 	return len;
740 }
741 
iio_format_avail_range(char * buf,const int * vals,int type)742 static ssize_t iio_format_avail_range(char *buf, const int *vals, int type)
743 {
744 	int i;
745 	ssize_t len;
746 
747 	len = snprintf(buf, PAGE_SIZE, "[");
748 	switch (type) {
749 	case IIO_VAL_INT:
750 		for (i = 0; i < 3; i++) {
751 			len += __iio_format_value(buf + len, PAGE_SIZE - len,
752 						  type, 1, &vals[i]);
753 			if (len >= PAGE_SIZE)
754 				return -EFBIG;
755 			if (i < 2)
756 				len += scnprintf(buf + len, PAGE_SIZE - len,
757 						" ");
758 			else
759 				len += scnprintf(buf + len, PAGE_SIZE - len,
760 						"]\n");
761 			if (len >= PAGE_SIZE)
762 				return -EFBIG;
763 		}
764 		break;
765 	default:
766 		for (i = 0; i < 3; i++) {
767 			len += __iio_format_value(buf + len, PAGE_SIZE - len,
768 						  type, 2, &vals[i * 2]);
769 			if (len >= PAGE_SIZE)
770 				return -EFBIG;
771 			if (i < 2)
772 				len += scnprintf(buf + len, PAGE_SIZE - len,
773 						" ");
774 			else
775 				len += scnprintf(buf + len, PAGE_SIZE - len,
776 						"]\n");
777 			if (len >= PAGE_SIZE)
778 				return -EFBIG;
779 		}
780 	}
781 
782 	return len;
783 }
784 
iio_read_channel_info_avail(struct device * dev,struct device_attribute * attr,char * buf)785 static ssize_t iio_read_channel_info_avail(struct device *dev,
786 					   struct device_attribute *attr,
787 					   char *buf)
788 {
789 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
790 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
791 	const int *vals;
792 	int ret;
793 	int length;
794 	int type;
795 
796 	if (!indio_dev->info->read_avail)
797 		return -EINVAL;
798 
799 	ret = indio_dev->info->read_avail(indio_dev, this_attr->c,
800 					  &vals, &type, &length,
801 					  this_attr->address);
802 
803 	if (ret < 0)
804 		return ret;
805 	switch (ret) {
806 	case IIO_AVAIL_LIST:
807 		return iio_format_avail_list(buf, vals, type, length);
808 	case IIO_AVAIL_RANGE:
809 		return iio_format_avail_range(buf, vals, type);
810 	default:
811 		return -EINVAL;
812 	}
813 }
814 
815 /**
816  * __iio_str_to_fixpoint() - Parse a fixed-point number from a string
817  * @str: The string to parse
818  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
819  * @integer: The integer part of the number
820  * @fract: The fractional part of the number
821  * @scale_db: True if this should parse as dB
822  *
823  * Returns 0 on success, or a negative error code if the string could not be
824  * parsed.
825  */
__iio_str_to_fixpoint(const char * str,int fract_mult,int * integer,int * fract,bool scale_db)826 static int __iio_str_to_fixpoint(const char *str, int fract_mult,
827 				 int *integer, int *fract, bool scale_db)
828 {
829 	int i = 0, f = 0;
830 	bool integer_part = true, negative = false;
831 
832 	if (fract_mult == 0) {
833 		*fract = 0;
834 
835 		return kstrtoint(str, 0, integer);
836 	}
837 
838 	if (str[0] == '-') {
839 		negative = true;
840 		str++;
841 	} else if (str[0] == '+') {
842 		str++;
843 	}
844 
845 	while (*str) {
846 		if ('0' <= *str && *str <= '9') {
847 			if (integer_part) {
848 				i = i * 10 + *str - '0';
849 			} else {
850 				f += fract_mult * (*str - '0');
851 				fract_mult /= 10;
852 			}
853 		} else if (*str == '\n') {
854 			if (*(str + 1) == '\0')
855 				break;
856 			else
857 				return -EINVAL;
858 		} else if (!strncmp(str, " dB", sizeof(" dB") - 1) && scale_db) {
859 			/* Ignore the dB suffix */
860 			str += sizeof(" dB") - 1;
861 			continue;
862 		} else if (!strncmp(str, "dB", sizeof("dB") - 1) && scale_db) {
863 			/* Ignore the dB suffix */
864 			str += sizeof("dB") - 1;
865 			continue;
866 		} else if (*str == '.' && integer_part) {
867 			integer_part = false;
868 		} else {
869 			return -EINVAL;
870 		}
871 		str++;
872 	}
873 
874 	if (negative) {
875 		if (i)
876 			i = -i;
877 		else
878 			f = -f;
879 	}
880 
881 	*integer = i;
882 	*fract = f;
883 
884 	return 0;
885 }
886 
887 /**
888  * iio_str_to_fixpoint() - Parse a fixed-point number from a string
889  * @str: The string to parse
890  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
891  * @integer: The integer part of the number
892  * @fract: The fractional part of the number
893  *
894  * Returns 0 on success, or a negative error code if the string could not be
895  * parsed.
896  */
iio_str_to_fixpoint(const char * str,int fract_mult,int * integer,int * fract)897 int iio_str_to_fixpoint(const char *str, int fract_mult,
898 			int *integer, int *fract)
899 {
900 	return __iio_str_to_fixpoint(str, fract_mult, integer, fract, false);
901 }
902 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
903 
iio_write_channel_info(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)904 static ssize_t iio_write_channel_info(struct device *dev,
905 				      struct device_attribute *attr,
906 				      const char *buf,
907 				      size_t len)
908 {
909 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
910 	struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
911 	int ret, fract_mult = 100000;
912 	int integer, fract = 0;
913 	bool is_char = false;
914 	bool scale_db = false;
915 
916 	/* Assumes decimal - precision based on number of digits */
917 	if (!indio_dev->info->write_raw)
918 		return -EINVAL;
919 
920 	if (indio_dev->info->write_raw_get_fmt)
921 		switch (indio_dev->info->write_raw_get_fmt(indio_dev,
922 			this_attr->c, this_attr->address)) {
923 		case IIO_VAL_INT:
924 			fract_mult = 0;
925 			break;
926 		case IIO_VAL_INT_PLUS_MICRO_DB:
927 			scale_db = true;
928 			fallthrough;
929 		case IIO_VAL_INT_PLUS_MICRO:
930 			fract_mult = 100000;
931 			break;
932 		case IIO_VAL_INT_PLUS_NANO:
933 			fract_mult = 100000000;
934 			break;
935 		case IIO_VAL_CHAR:
936 			is_char = true;
937 			break;
938 		default:
939 			return -EINVAL;
940 		}
941 
942 	if (is_char) {
943 		char ch;
944 
945 		if (sscanf(buf, "%c", &ch) != 1)
946 			return -EINVAL;
947 		integer = ch;
948 	} else {
949 		ret = __iio_str_to_fixpoint(buf, fract_mult, &integer, &fract,
950 					    scale_db);
951 		if (ret)
952 			return ret;
953 	}
954 
955 	ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
956 					 integer, fract, this_attr->address);
957 	if (ret)
958 		return ret;
959 
960 	return len;
961 }
962 
963 static
__iio_device_attr_init(struct device_attribute * dev_attr,const char * postfix,struct iio_chan_spec const * chan,ssize_t (* readfunc)(struct device * dev,struct device_attribute * attr,char * buf),ssize_t (* writefunc)(struct device * dev,struct device_attribute * attr,const char * buf,size_t len),enum iio_shared_by shared_by)964 int __iio_device_attr_init(struct device_attribute *dev_attr,
965 			   const char *postfix,
966 			   struct iio_chan_spec const *chan,
967 			   ssize_t (*readfunc)(struct device *dev,
968 					       struct device_attribute *attr,
969 					       char *buf),
970 			   ssize_t (*writefunc)(struct device *dev,
971 						struct device_attribute *attr,
972 						const char *buf,
973 						size_t len),
974 			   enum iio_shared_by shared_by)
975 {
976 	int ret = 0;
977 	char *name = NULL;
978 	char *full_postfix;
979 	sysfs_attr_init(&dev_attr->attr);
980 
981 	/* Build up postfix of <extend_name>_<modifier>_postfix */
982 	if (chan->modified && (shared_by == IIO_SEPARATE)) {
983 		if (chan->extend_name)
984 			full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
985 						 iio_modifier_names[chan
986 								    ->channel2],
987 						 chan->extend_name,
988 						 postfix);
989 		else
990 			full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
991 						 iio_modifier_names[chan
992 								    ->channel2],
993 						 postfix);
994 	} else {
995 		if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
996 			full_postfix = kstrdup(postfix, GFP_KERNEL);
997 		else
998 			full_postfix = kasprintf(GFP_KERNEL,
999 						 "%s_%s",
1000 						 chan->extend_name,
1001 						 postfix);
1002 	}
1003 	if (full_postfix == NULL)
1004 		return -ENOMEM;
1005 
1006 	if (chan->differential) { /* Differential can not have modifier */
1007 		switch (shared_by) {
1008 		case IIO_SHARED_BY_ALL:
1009 			name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1010 			break;
1011 		case IIO_SHARED_BY_DIR:
1012 			name = kasprintf(GFP_KERNEL, "%s_%s",
1013 						iio_direction[chan->output],
1014 						full_postfix);
1015 			break;
1016 		case IIO_SHARED_BY_TYPE:
1017 			name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
1018 					    iio_direction[chan->output],
1019 					    iio_chan_type_name_spec[chan->type],
1020 					    iio_chan_type_name_spec[chan->type],
1021 					    full_postfix);
1022 			break;
1023 		case IIO_SEPARATE:
1024 			if (!chan->indexed) {
1025 				WARN(1, "Differential channels must be indexed\n");
1026 				ret = -EINVAL;
1027 				goto error_free_full_postfix;
1028 			}
1029 			name = kasprintf(GFP_KERNEL,
1030 					    "%s_%s%d-%s%d_%s",
1031 					    iio_direction[chan->output],
1032 					    iio_chan_type_name_spec[chan->type],
1033 					    chan->channel,
1034 					    iio_chan_type_name_spec[chan->type],
1035 					    chan->channel2,
1036 					    full_postfix);
1037 			break;
1038 		}
1039 	} else { /* Single ended */
1040 		switch (shared_by) {
1041 		case IIO_SHARED_BY_ALL:
1042 			name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1043 			break;
1044 		case IIO_SHARED_BY_DIR:
1045 			name = kasprintf(GFP_KERNEL, "%s_%s",
1046 						iio_direction[chan->output],
1047 						full_postfix);
1048 			break;
1049 		case IIO_SHARED_BY_TYPE:
1050 			name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1051 					    iio_direction[chan->output],
1052 					    iio_chan_type_name_spec[chan->type],
1053 					    full_postfix);
1054 			break;
1055 
1056 		case IIO_SEPARATE:
1057 			if (chan->indexed)
1058 				name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
1059 						    iio_direction[chan->output],
1060 						    iio_chan_type_name_spec[chan->type],
1061 						    chan->channel,
1062 						    full_postfix);
1063 			else
1064 				name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1065 						    iio_direction[chan->output],
1066 						    iio_chan_type_name_spec[chan->type],
1067 						    full_postfix);
1068 			break;
1069 		}
1070 	}
1071 	if (name == NULL) {
1072 		ret = -ENOMEM;
1073 		goto error_free_full_postfix;
1074 	}
1075 	dev_attr->attr.name = name;
1076 
1077 	if (readfunc) {
1078 		dev_attr->attr.mode |= S_IRUGO;
1079 		dev_attr->show = readfunc;
1080 	}
1081 
1082 	if (writefunc) {
1083 		dev_attr->attr.mode |= S_IWUSR;
1084 		dev_attr->store = writefunc;
1085 	}
1086 
1087 error_free_full_postfix:
1088 	kfree(full_postfix);
1089 
1090 	return ret;
1091 }
1092 
__iio_device_attr_deinit(struct device_attribute * dev_attr)1093 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
1094 {
1095 	kfree(dev_attr->attr.name);
1096 }
1097 
__iio_add_chan_devattr(const char * postfix,struct iio_chan_spec const * chan,ssize_t (* readfunc)(struct device * dev,struct device_attribute * attr,char * buf),ssize_t (* writefunc)(struct device * dev,struct device_attribute * attr,const char * buf,size_t len),u64 mask,enum iio_shared_by shared_by,struct device * dev,struct list_head * attr_list)1098 int __iio_add_chan_devattr(const char *postfix,
1099 			   struct iio_chan_spec const *chan,
1100 			   ssize_t (*readfunc)(struct device *dev,
1101 					       struct device_attribute *attr,
1102 					       char *buf),
1103 			   ssize_t (*writefunc)(struct device *dev,
1104 						struct device_attribute *attr,
1105 						const char *buf,
1106 						size_t len),
1107 			   u64 mask,
1108 			   enum iio_shared_by shared_by,
1109 			   struct device *dev,
1110 			   struct list_head *attr_list)
1111 {
1112 	int ret;
1113 	struct iio_dev_attr *iio_attr, *t;
1114 
1115 	iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
1116 	if (iio_attr == NULL)
1117 		return -ENOMEM;
1118 	ret = __iio_device_attr_init(&iio_attr->dev_attr,
1119 				     postfix, chan,
1120 				     readfunc, writefunc, shared_by);
1121 	if (ret)
1122 		goto error_iio_dev_attr_free;
1123 	iio_attr->c = chan;
1124 	iio_attr->address = mask;
1125 	list_for_each_entry(t, attr_list, l)
1126 		if (strcmp(t->dev_attr.attr.name,
1127 			   iio_attr->dev_attr.attr.name) == 0) {
1128 			if (shared_by == IIO_SEPARATE)
1129 				dev_err(dev, "tried to double register : %s\n",
1130 					t->dev_attr.attr.name);
1131 			ret = -EBUSY;
1132 			goto error_device_attr_deinit;
1133 		}
1134 	list_add(&iio_attr->l, attr_list);
1135 
1136 	return 0;
1137 
1138 error_device_attr_deinit:
1139 	__iio_device_attr_deinit(&iio_attr->dev_attr);
1140 error_iio_dev_attr_free:
1141 	kfree(iio_attr);
1142 	return ret;
1143 }
1144 
iio_device_add_info_mask_type(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,enum iio_shared_by shared_by,const long * infomask)1145 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
1146 					 struct iio_chan_spec const *chan,
1147 					 enum iio_shared_by shared_by,
1148 					 const long *infomask)
1149 {
1150 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1151 	int i, ret, attrcount = 0;
1152 
1153 	for_each_set_bit(i, infomask, sizeof(*infomask)*8) {
1154 		if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1155 			return -EINVAL;
1156 		ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
1157 					     chan,
1158 					     &iio_read_channel_info,
1159 					     &iio_write_channel_info,
1160 					     i,
1161 					     shared_by,
1162 					     &indio_dev->dev,
1163 					     &iio_dev_opaque->channel_attr_list);
1164 		if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1165 			continue;
1166 		else if (ret < 0)
1167 			return ret;
1168 		attrcount++;
1169 	}
1170 
1171 	return attrcount;
1172 }
1173 
iio_device_add_info_mask_type_avail(struct iio_dev * indio_dev,struct iio_chan_spec const * chan,enum iio_shared_by shared_by,const long * infomask)1174 static int iio_device_add_info_mask_type_avail(struct iio_dev *indio_dev,
1175 					       struct iio_chan_spec const *chan,
1176 					       enum iio_shared_by shared_by,
1177 					       const long *infomask)
1178 {
1179 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1180 	int i, ret, attrcount = 0;
1181 	char *avail_postfix;
1182 
1183 	for_each_set_bit(i, infomask, sizeof(*infomask) * 8) {
1184 		if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1185 			return -EINVAL;
1186 		avail_postfix = kasprintf(GFP_KERNEL,
1187 					  "%s_available",
1188 					  iio_chan_info_postfix[i]);
1189 		if (!avail_postfix)
1190 			return -ENOMEM;
1191 
1192 		ret = __iio_add_chan_devattr(avail_postfix,
1193 					     chan,
1194 					     &iio_read_channel_info_avail,
1195 					     NULL,
1196 					     i,
1197 					     shared_by,
1198 					     &indio_dev->dev,
1199 					     &iio_dev_opaque->channel_attr_list);
1200 		kfree(avail_postfix);
1201 		if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1202 			continue;
1203 		else if (ret < 0)
1204 			return ret;
1205 		attrcount++;
1206 	}
1207 
1208 	return attrcount;
1209 }
1210 
iio_device_add_channel_sysfs(struct iio_dev * indio_dev,struct iio_chan_spec const * chan)1211 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
1212 					struct iio_chan_spec const *chan)
1213 {
1214 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1215 	int ret, attrcount = 0;
1216 	const struct iio_chan_spec_ext_info *ext_info;
1217 
1218 	if (chan->channel < 0)
1219 		return 0;
1220 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1221 					    IIO_SEPARATE,
1222 					    &chan->info_mask_separate);
1223 	if (ret < 0)
1224 		return ret;
1225 	attrcount += ret;
1226 
1227 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1228 						  IIO_SEPARATE,
1229 						  &chan->
1230 						  info_mask_separate_available);
1231 	if (ret < 0)
1232 		return ret;
1233 	attrcount += ret;
1234 
1235 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1236 					    IIO_SHARED_BY_TYPE,
1237 					    &chan->info_mask_shared_by_type);
1238 	if (ret < 0)
1239 		return ret;
1240 	attrcount += ret;
1241 
1242 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1243 						  IIO_SHARED_BY_TYPE,
1244 						  &chan->
1245 						  info_mask_shared_by_type_available);
1246 	if (ret < 0)
1247 		return ret;
1248 	attrcount += ret;
1249 
1250 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1251 					    IIO_SHARED_BY_DIR,
1252 					    &chan->info_mask_shared_by_dir);
1253 	if (ret < 0)
1254 		return ret;
1255 	attrcount += ret;
1256 
1257 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1258 						  IIO_SHARED_BY_DIR,
1259 						  &chan->info_mask_shared_by_dir_available);
1260 	if (ret < 0)
1261 		return ret;
1262 	attrcount += ret;
1263 
1264 	ret = iio_device_add_info_mask_type(indio_dev, chan,
1265 					    IIO_SHARED_BY_ALL,
1266 					    &chan->info_mask_shared_by_all);
1267 	if (ret < 0)
1268 		return ret;
1269 	attrcount += ret;
1270 
1271 	ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1272 						  IIO_SHARED_BY_ALL,
1273 						  &chan->info_mask_shared_by_all_available);
1274 	if (ret < 0)
1275 		return ret;
1276 	attrcount += ret;
1277 
1278 	if (chan->ext_info) {
1279 		unsigned int i = 0;
1280 		for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
1281 			ret = __iio_add_chan_devattr(ext_info->name,
1282 					chan,
1283 					ext_info->read ?
1284 					    &iio_read_channel_ext_info : NULL,
1285 					ext_info->write ?
1286 					    &iio_write_channel_ext_info : NULL,
1287 					i,
1288 					ext_info->shared,
1289 					&indio_dev->dev,
1290 					&iio_dev_opaque->channel_attr_list);
1291 			i++;
1292 			if (ret == -EBUSY && ext_info->shared)
1293 				continue;
1294 
1295 			if (ret)
1296 				return ret;
1297 
1298 			attrcount++;
1299 		}
1300 	}
1301 
1302 	return attrcount;
1303 }
1304 
1305 /**
1306  * iio_free_chan_devattr_list() - Free a list of IIO device attributes
1307  * @attr_list: List of IIO device attributes
1308  *
1309  * This function frees the memory allocated for each of the IIO device
1310  * attributes in the list.
1311  */
iio_free_chan_devattr_list(struct list_head * attr_list)1312 void iio_free_chan_devattr_list(struct list_head *attr_list)
1313 {
1314 	struct iio_dev_attr *p, *n;
1315 
1316 	list_for_each_entry_safe(p, n, attr_list, l) {
1317 		kfree(p->dev_attr.attr.name);
1318 		list_del(&p->l);
1319 		kfree(p);
1320 	}
1321 }
1322 
iio_show_dev_name(struct device * dev,struct device_attribute * attr,char * buf)1323 static ssize_t iio_show_dev_name(struct device *dev,
1324 				 struct device_attribute *attr,
1325 				 char *buf)
1326 {
1327 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1328 	return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->name);
1329 }
1330 
1331 static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
1332 
iio_show_dev_label(struct device * dev,struct device_attribute * attr,char * buf)1333 static ssize_t iio_show_dev_label(struct device *dev,
1334 				 struct device_attribute *attr,
1335 				 char *buf)
1336 {
1337 	struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1338 	return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->label);
1339 }
1340 
1341 static DEVICE_ATTR(label, S_IRUGO, iio_show_dev_label, NULL);
1342 
iio_show_timestamp_clock(struct device * dev,struct device_attribute * attr,char * buf)1343 static ssize_t iio_show_timestamp_clock(struct device *dev,
1344 					struct device_attribute *attr,
1345 					char *buf)
1346 {
1347 	const struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1348 	const clockid_t clk = iio_device_get_clock(indio_dev);
1349 	const char *name;
1350 	ssize_t sz;
1351 
1352 	switch (clk) {
1353 	case CLOCK_REALTIME:
1354 		name = "realtime\n";
1355 		sz = sizeof("realtime\n");
1356 		break;
1357 	case CLOCK_MONOTONIC:
1358 		name = "monotonic\n";
1359 		sz = sizeof("monotonic\n");
1360 		break;
1361 	case CLOCK_MONOTONIC_RAW:
1362 		name = "monotonic_raw\n";
1363 		sz = sizeof("monotonic_raw\n");
1364 		break;
1365 	case CLOCK_REALTIME_COARSE:
1366 		name = "realtime_coarse\n";
1367 		sz = sizeof("realtime_coarse\n");
1368 		break;
1369 	case CLOCK_MONOTONIC_COARSE:
1370 		name = "monotonic_coarse\n";
1371 		sz = sizeof("monotonic_coarse\n");
1372 		break;
1373 	case CLOCK_BOOTTIME:
1374 		name = "boottime\n";
1375 		sz = sizeof("boottime\n");
1376 		break;
1377 	case CLOCK_TAI:
1378 		name = "tai\n";
1379 		sz = sizeof("tai\n");
1380 		break;
1381 	default:
1382 		BUG();
1383 	}
1384 
1385 	memcpy(buf, name, sz);
1386 	return sz;
1387 }
1388 
iio_store_timestamp_clock(struct device * dev,struct device_attribute * attr,const char * buf,size_t len)1389 static ssize_t iio_store_timestamp_clock(struct device *dev,
1390 					 struct device_attribute *attr,
1391 					 const char *buf, size_t len)
1392 {
1393 	clockid_t clk;
1394 	int ret;
1395 
1396 	if (sysfs_streq(buf, "realtime"))
1397 		clk = CLOCK_REALTIME;
1398 	else if (sysfs_streq(buf, "monotonic"))
1399 		clk = CLOCK_MONOTONIC;
1400 	else if (sysfs_streq(buf, "monotonic_raw"))
1401 		clk = CLOCK_MONOTONIC_RAW;
1402 	else if (sysfs_streq(buf, "realtime_coarse"))
1403 		clk = CLOCK_REALTIME_COARSE;
1404 	else if (sysfs_streq(buf, "monotonic_coarse"))
1405 		clk = CLOCK_MONOTONIC_COARSE;
1406 	else if (sysfs_streq(buf, "boottime"))
1407 		clk = CLOCK_BOOTTIME;
1408 	else if (sysfs_streq(buf, "tai"))
1409 		clk = CLOCK_TAI;
1410 	else
1411 		return -EINVAL;
1412 
1413 	ret = iio_device_set_clock(dev_to_iio_dev(dev), clk);
1414 	if (ret)
1415 		return ret;
1416 
1417 	return len;
1418 }
1419 
1420 static DEVICE_ATTR(current_timestamp_clock, S_IRUGO | S_IWUSR,
1421 		   iio_show_timestamp_clock, iio_store_timestamp_clock);
1422 
iio_device_register_sysfs(struct iio_dev * indio_dev)1423 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
1424 {
1425 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1426 	int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
1427 	struct iio_dev_attr *p;
1428 	struct attribute **attr, *clk = NULL;
1429 
1430 	/* First count elements in any existing group */
1431 	if (indio_dev->info->attrs) {
1432 		attr = indio_dev->info->attrs->attrs;
1433 		while (*attr++ != NULL)
1434 			attrcount_orig++;
1435 	}
1436 	attrcount = attrcount_orig;
1437 	/*
1438 	 * New channel registration method - relies on the fact a group does
1439 	 * not need to be initialized if its name is NULL.
1440 	 */
1441 	if (indio_dev->channels)
1442 		for (i = 0; i < indio_dev->num_channels; i++) {
1443 			const struct iio_chan_spec *chan =
1444 				&indio_dev->channels[i];
1445 
1446 			if (chan->type == IIO_TIMESTAMP)
1447 				clk = &dev_attr_current_timestamp_clock.attr;
1448 
1449 			ret = iio_device_add_channel_sysfs(indio_dev, chan);
1450 			if (ret < 0)
1451 				goto error_clear_attrs;
1452 			attrcount += ret;
1453 		}
1454 
1455 	if (iio_dev_opaque->event_interface)
1456 		clk = &dev_attr_current_timestamp_clock.attr;
1457 
1458 	if (indio_dev->name)
1459 		attrcount++;
1460 	if (indio_dev->label)
1461 		attrcount++;
1462 	if (clk)
1463 		attrcount++;
1464 
1465 	iio_dev_opaque->chan_attr_group.attrs =
1466 		kcalloc(attrcount + 1,
1467 			sizeof(iio_dev_opaque->chan_attr_group.attrs[0]),
1468 			GFP_KERNEL);
1469 	if (iio_dev_opaque->chan_attr_group.attrs == NULL) {
1470 		ret = -ENOMEM;
1471 		goto error_clear_attrs;
1472 	}
1473 	/* Copy across original attributes */
1474 	if (indio_dev->info->attrs)
1475 		memcpy(iio_dev_opaque->chan_attr_group.attrs,
1476 		       indio_dev->info->attrs->attrs,
1477 		       sizeof(iio_dev_opaque->chan_attr_group.attrs[0])
1478 		       *attrcount_orig);
1479 	attrn = attrcount_orig;
1480 	/* Add all elements from the list. */
1481 	list_for_each_entry(p, &iio_dev_opaque->channel_attr_list, l)
1482 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1483 	if (indio_dev->name)
1484 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
1485 	if (indio_dev->label)
1486 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_label.attr;
1487 	if (clk)
1488 		iio_dev_opaque->chan_attr_group.attrs[attrn++] = clk;
1489 
1490 	indio_dev->groups[indio_dev->groupcounter++] =
1491 		&iio_dev_opaque->chan_attr_group;
1492 
1493 	return 0;
1494 
1495 error_clear_attrs:
1496 	iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1497 
1498 	return ret;
1499 }
1500 
iio_device_unregister_sysfs(struct iio_dev * indio_dev)1501 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
1502 {
1503 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1504 
1505 	iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1506 	kfree(iio_dev_opaque->chan_attr_group.attrs);
1507 	iio_dev_opaque->chan_attr_group.attrs = NULL;
1508 }
1509 
iio_dev_release(struct device * device)1510 static void iio_dev_release(struct device *device)
1511 {
1512 	struct iio_dev *indio_dev = dev_to_iio_dev(device);
1513 	struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1514 
1515 	if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1516 		iio_device_unregister_trigger_consumer(indio_dev);
1517 	iio_device_unregister_eventset(indio_dev);
1518 	iio_device_unregister_sysfs(indio_dev);
1519 
1520 	iio_buffer_put(indio_dev->buffer);
1521 
1522 	ida_simple_remove(&iio_ida, indio_dev->id);
1523 	kfree(iio_dev_opaque);
1524 }
1525 
1526 struct device_type iio_device_type = {
1527 	.name = "iio_device",
1528 	.release = iio_dev_release,
1529 };
1530 
1531 /**
1532  * iio_device_alloc() - allocate an iio_dev from a driver
1533  * @parent:		Parent device.
1534  * @sizeof_priv:	Space to allocate for private structure.
1535  **/
iio_device_alloc(struct device * parent,int sizeof_priv)1536 struct iio_dev *iio_device_alloc(struct device *parent, int sizeof_priv)
1537 {
1538 	struct iio_dev_opaque *iio_dev_opaque;
1539 	struct iio_dev *dev;
1540 	size_t alloc_size;
1541 
1542 	alloc_size = sizeof(struct iio_dev_opaque);
1543 	if (sizeof_priv) {
1544 		alloc_size = ALIGN(alloc_size, IIO_ALIGN);
1545 		alloc_size += sizeof_priv;
1546 	}
1547 
1548 	iio_dev_opaque = kzalloc(alloc_size, GFP_KERNEL);
1549 	if (!iio_dev_opaque)
1550 		return NULL;
1551 
1552 	dev = &iio_dev_opaque->indio_dev;
1553 	dev->priv = (char *)iio_dev_opaque +
1554 		ALIGN(sizeof(struct iio_dev_opaque), IIO_ALIGN);
1555 
1556 	dev->dev.parent = parent;
1557 	dev->dev.groups = dev->groups;
1558 	dev->dev.type = &iio_device_type;
1559 	dev->dev.bus = &iio_bus_type;
1560 	device_initialize(&dev->dev);
1561 	dev_set_drvdata(&dev->dev, (void *)dev);
1562 	mutex_init(&dev->mlock);
1563 	mutex_init(&dev->info_exist_lock);
1564 	INIT_LIST_HEAD(&iio_dev_opaque->channel_attr_list);
1565 
1566 	dev->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
1567 	if (dev->id < 0) {
1568 		/* cannot use a dev_err as the name isn't available */
1569 		pr_err("failed to get device id\n");
1570 		kfree(iio_dev_opaque);
1571 		return NULL;
1572 	}
1573 	dev_set_name(&dev->dev, "iio:device%d", dev->id);
1574 	INIT_LIST_HEAD(&iio_dev_opaque->buffer_list);
1575 
1576 	return dev;
1577 }
1578 EXPORT_SYMBOL(iio_device_alloc);
1579 
1580 /**
1581  * iio_device_free() - free an iio_dev from a driver
1582  * @dev:		the iio_dev associated with the device
1583  **/
iio_device_free(struct iio_dev * dev)1584 void iio_device_free(struct iio_dev *dev)
1585 {
1586 	if (dev)
1587 		put_device(&dev->dev);
1588 }
1589 EXPORT_SYMBOL(iio_device_free);
1590 
devm_iio_device_release(struct device * dev,void * res)1591 static void devm_iio_device_release(struct device *dev, void *res)
1592 {
1593 	iio_device_free(*(struct iio_dev **)res);
1594 }
1595 
1596 /**
1597  * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1598  * @parent:		Device to allocate iio_dev for, and parent for this IIO device
1599  * @sizeof_priv:	Space to allocate for private structure.
1600  *
1601  * Managed iio_device_alloc. iio_dev allocated with this function is
1602  * automatically freed on driver detach.
1603  *
1604  * RETURNS:
1605  * Pointer to allocated iio_dev on success, NULL on failure.
1606  */
devm_iio_device_alloc(struct device * parent,int sizeof_priv)1607 struct iio_dev *devm_iio_device_alloc(struct device *parent, int sizeof_priv)
1608 {
1609 	struct iio_dev **ptr, *iio_dev;
1610 
1611 	ptr = devres_alloc(devm_iio_device_release, sizeof(*ptr),
1612 			   GFP_KERNEL);
1613 	if (!ptr)
1614 		return NULL;
1615 
1616 	iio_dev = iio_device_alloc(parent, sizeof_priv);
1617 	if (iio_dev) {
1618 		*ptr = iio_dev;
1619 		devres_add(parent, ptr);
1620 	} else {
1621 		devres_free(ptr);
1622 	}
1623 
1624 	return iio_dev;
1625 }
1626 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1627 
1628 /**
1629  * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1630  * @inode:	Inode structure for identifying the device in the file system
1631  * @filp:	File structure for iio device used to keep and later access
1632  *		private data
1633  *
1634  * Return: 0 on success or -EBUSY if the device is already opened
1635  **/
iio_chrdev_open(struct inode * inode,struct file * filp)1636 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1637 {
1638 	struct iio_dev *indio_dev = container_of(inode->i_cdev,
1639 						struct iio_dev, chrdev);
1640 
1641 	if (test_and_set_bit(IIO_BUSY_BIT_POS, &indio_dev->flags))
1642 		return -EBUSY;
1643 
1644 	iio_device_get(indio_dev);
1645 
1646 	filp->private_data = indio_dev;
1647 
1648 	return 0;
1649 }
1650 
1651 /**
1652  * iio_chrdev_release() - chrdev file close buffer access and ioctls
1653  * @inode:	Inode structure pointer for the char device
1654  * @filp:	File structure pointer for the char device
1655  *
1656  * Return: 0 for successful release
1657  */
iio_chrdev_release(struct inode * inode,struct file * filp)1658 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1659 {
1660 	struct iio_dev *indio_dev = container_of(inode->i_cdev,
1661 						struct iio_dev, chrdev);
1662 	clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
1663 	iio_device_put(indio_dev);
1664 
1665 	return 0;
1666 }
1667 
1668 /* Somewhat of a cross file organization violation - ioctls here are actually
1669  * event related */
iio_ioctl(struct file * filp,unsigned int cmd,unsigned long arg)1670 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1671 {
1672 	struct iio_dev *indio_dev = filp->private_data;
1673 	int __user *ip = (int __user *)arg;
1674 	int fd;
1675 
1676 	if (!indio_dev->info)
1677 		return -ENODEV;
1678 
1679 	if (cmd == IIO_GET_EVENT_FD_IOCTL) {
1680 		fd = iio_event_getfd(indio_dev);
1681 		if (fd < 0)
1682 			return fd;
1683 		if (copy_to_user(ip, &fd, sizeof(fd)))
1684 			return -EFAULT;
1685 		return 0;
1686 	}
1687 	return -EINVAL;
1688 }
1689 
1690 static const struct file_operations iio_buffer_fileops = {
1691 	.read = iio_buffer_read_outer_addr,
1692 	.release = iio_chrdev_release,
1693 	.open = iio_chrdev_open,
1694 	.poll = iio_buffer_poll_addr,
1695 	.owner = THIS_MODULE,
1696 	.llseek = noop_llseek,
1697 	.unlocked_ioctl = iio_ioctl,
1698 	.compat_ioctl = compat_ptr_ioctl,
1699 };
1700 
iio_check_unique_scan_index(struct iio_dev * indio_dev)1701 static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1702 {
1703 	int i, j;
1704 	const struct iio_chan_spec *channels = indio_dev->channels;
1705 
1706 	if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1707 		return 0;
1708 
1709 	for (i = 0; i < indio_dev->num_channels - 1; i++) {
1710 		if (channels[i].scan_index < 0)
1711 			continue;
1712 		for (j = i + 1; j < indio_dev->num_channels; j++)
1713 			if (channels[i].scan_index == channels[j].scan_index) {
1714 				dev_err(&indio_dev->dev,
1715 					"Duplicate scan index %d\n",
1716 					channels[i].scan_index);
1717 				return -EINVAL;
1718 			}
1719 	}
1720 
1721 	return 0;
1722 }
1723 
1724 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1725 
__iio_device_register(struct iio_dev * indio_dev,struct module * this_mod)1726 int __iio_device_register(struct iio_dev *indio_dev, struct module *this_mod)
1727 {
1728 	const char *label;
1729 	int ret;
1730 
1731 	if (!indio_dev->info)
1732 		return -EINVAL;
1733 
1734 	indio_dev->driver_module = this_mod;
1735 	/* If the calling driver did not initialize of_node, do it here */
1736 	if (!indio_dev->dev.of_node && indio_dev->dev.parent)
1737 		indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
1738 
1739 	label = of_get_property(indio_dev->dev.of_node, "label", NULL);
1740 	if (label)
1741 		indio_dev->label = label;
1742 
1743 	ret = iio_check_unique_scan_index(indio_dev);
1744 	if (ret < 0)
1745 		return ret;
1746 
1747 	/* configure elements for the chrdev */
1748 	indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), indio_dev->id);
1749 
1750 	iio_device_register_debugfs(indio_dev);
1751 
1752 	ret = iio_buffer_alloc_sysfs_and_mask(indio_dev);
1753 	if (ret) {
1754 		dev_err(indio_dev->dev.parent,
1755 			"Failed to create buffer sysfs interfaces\n");
1756 		goto error_unreg_debugfs;
1757 	}
1758 
1759 	ret = iio_device_register_sysfs(indio_dev);
1760 	if (ret) {
1761 		dev_err(indio_dev->dev.parent,
1762 			"Failed to register sysfs interfaces\n");
1763 		goto error_buffer_free_sysfs;
1764 	}
1765 	ret = iio_device_register_eventset(indio_dev);
1766 	if (ret) {
1767 		dev_err(indio_dev->dev.parent,
1768 			"Failed to register event set\n");
1769 		goto error_free_sysfs;
1770 	}
1771 	if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1772 		iio_device_register_trigger_consumer(indio_dev);
1773 
1774 	if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1775 		indio_dev->setup_ops == NULL)
1776 		indio_dev->setup_ops = &noop_ring_setup_ops;
1777 
1778 	cdev_init(&indio_dev->chrdev, &iio_buffer_fileops);
1779 
1780 	indio_dev->chrdev.owner = this_mod;
1781 
1782 	ret = cdev_device_add(&indio_dev->chrdev, &indio_dev->dev);
1783 	if (ret < 0)
1784 		goto error_unreg_eventset;
1785 
1786 	return 0;
1787 
1788 error_unreg_eventset:
1789 	iio_device_unregister_eventset(indio_dev);
1790 error_free_sysfs:
1791 	iio_device_unregister_sysfs(indio_dev);
1792 error_buffer_free_sysfs:
1793 	iio_buffer_free_sysfs_and_mask(indio_dev);
1794 error_unreg_debugfs:
1795 	iio_device_unregister_debugfs(indio_dev);
1796 	return ret;
1797 }
1798 EXPORT_SYMBOL(__iio_device_register);
1799 
1800 /**
1801  * iio_device_unregister() - unregister a device from the IIO subsystem
1802  * @indio_dev:		Device structure representing the device.
1803  **/
iio_device_unregister(struct iio_dev * indio_dev)1804 void iio_device_unregister(struct iio_dev *indio_dev)
1805 {
1806 	cdev_device_del(&indio_dev->chrdev, &indio_dev->dev);
1807 
1808 	mutex_lock(&indio_dev->info_exist_lock);
1809 
1810 	iio_device_unregister_debugfs(indio_dev);
1811 
1812 	iio_disable_all_buffers(indio_dev);
1813 
1814 	indio_dev->info = NULL;
1815 
1816 	iio_device_wakeup_eventset(indio_dev);
1817 	iio_buffer_wakeup_poll(indio_dev);
1818 
1819 	mutex_unlock(&indio_dev->info_exist_lock);
1820 
1821 	iio_buffer_free_sysfs_and_mask(indio_dev);
1822 }
1823 EXPORT_SYMBOL(iio_device_unregister);
1824 
devm_iio_device_unreg(struct device * dev,void * res)1825 static void devm_iio_device_unreg(struct device *dev, void *res)
1826 {
1827 	iio_device_unregister(*(struct iio_dev **)res);
1828 }
1829 
__devm_iio_device_register(struct device * dev,struct iio_dev * indio_dev,struct module * this_mod)1830 int __devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev,
1831 			       struct module *this_mod)
1832 {
1833 	struct iio_dev **ptr;
1834 	int ret;
1835 
1836 	ptr = devres_alloc(devm_iio_device_unreg, sizeof(*ptr), GFP_KERNEL);
1837 	if (!ptr)
1838 		return -ENOMEM;
1839 
1840 	*ptr = indio_dev;
1841 	ret = __iio_device_register(indio_dev, this_mod);
1842 	if (!ret)
1843 		devres_add(dev, ptr);
1844 	else
1845 		devres_free(ptr);
1846 
1847 	return ret;
1848 }
1849 EXPORT_SYMBOL_GPL(__devm_iio_device_register);
1850 
1851 /**
1852  * iio_device_claim_direct_mode - Keep device in direct mode
1853  * @indio_dev:	the iio_dev associated with the device
1854  *
1855  * If the device is in direct mode it is guaranteed to stay
1856  * that way until iio_device_release_direct_mode() is called.
1857  *
1858  * Use with iio_device_release_direct_mode()
1859  *
1860  * Returns: 0 on success, -EBUSY on failure
1861  */
iio_device_claim_direct_mode(struct iio_dev * indio_dev)1862 int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
1863 {
1864 	mutex_lock(&indio_dev->mlock);
1865 
1866 	if (iio_buffer_enabled(indio_dev)) {
1867 		mutex_unlock(&indio_dev->mlock);
1868 		return -EBUSY;
1869 	}
1870 	return 0;
1871 }
1872 EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
1873 
1874 /**
1875  * iio_device_release_direct_mode - releases claim on direct mode
1876  * @indio_dev:	the iio_dev associated with the device
1877  *
1878  * Release the claim. Device is no longer guaranteed to stay
1879  * in direct mode.
1880  *
1881  * Use with iio_device_claim_direct_mode()
1882  */
iio_device_release_direct_mode(struct iio_dev * indio_dev)1883 void iio_device_release_direct_mode(struct iio_dev *indio_dev)
1884 {
1885 	mutex_unlock(&indio_dev->mlock);
1886 }
1887 EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
1888 
1889 subsys_initcall(iio_init);
1890 module_exit(iio_exit);
1891 
1892 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1893 MODULE_DESCRIPTION("Industrial I/O core");
1894 MODULE_LICENSE("GPL");
1895