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