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