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