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