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