Merge tag 'block-5.11-2021-01-10' of git://git.kernel.dk/linux-block
[linux/fpc-iii.git] / drivers / iio / industrialio-core.c
blobc2e4c267c36b2aac324e0c7363a0caee04bf1adb
1 // SPDX-License-Identifier: GPL-2.0-only
2 /* The industrial I/O core
4 * Copyright (c) 2008 Jonathan Cameron
6 * Based on elements of hwmon and input subsystems.
7 */
9 #define pr_fmt(fmt) "iio-core: " fmt
11 #include <linux/kernel.h>
12 #include <linux/module.h>
13 #include <linux/idr.h>
14 #include <linux/kdev_t.h>
15 #include <linux/err.h>
16 #include <linux/device.h>
17 #include <linux/fs.h>
18 #include <linux/poll.h>
19 #include <linux/property.h>
20 #include <linux/sched.h>
21 #include <linux/wait.h>
22 #include <linux/cdev.h>
23 #include <linux/slab.h>
24 #include <linux/anon_inodes.h>
25 #include <linux/debugfs.h>
26 #include <linux/mutex.h>
27 #include <linux/iio/iio.h>
28 #include <linux/iio/iio-opaque.h>
29 #include "iio_core.h"
30 #include "iio_core_trigger.h"
31 #include <linux/iio/sysfs.h>
32 #include <linux/iio/events.h>
33 #include <linux/iio/buffer.h>
34 #include <linux/iio/buffer_impl.h>
36 /* IDA to assign each registered device a unique id */
37 static DEFINE_IDA(iio_ida);
39 static dev_t iio_devt;
41 #define IIO_DEV_MAX 256
42 struct bus_type iio_bus_type = {
43 .name = "iio",
45 EXPORT_SYMBOL(iio_bus_type);
47 static struct dentry *iio_debugfs_dentry;
49 static const char * const iio_direction[] = {
50 [0] = "in",
51 [1] = "out",
54 static const char * const iio_chan_type_name_spec[] = {
55 [IIO_VOLTAGE] = "voltage",
56 [IIO_CURRENT] = "current",
57 [IIO_POWER] = "power",
58 [IIO_ACCEL] = "accel",
59 [IIO_ANGL_VEL] = "anglvel",
60 [IIO_MAGN] = "magn",
61 [IIO_LIGHT] = "illuminance",
62 [IIO_INTENSITY] = "intensity",
63 [IIO_PROXIMITY] = "proximity",
64 [IIO_TEMP] = "temp",
65 [IIO_INCLI] = "incli",
66 [IIO_ROT] = "rot",
67 [IIO_ANGL] = "angl",
68 [IIO_TIMESTAMP] = "timestamp",
69 [IIO_CAPACITANCE] = "capacitance",
70 [IIO_ALTVOLTAGE] = "altvoltage",
71 [IIO_CCT] = "cct",
72 [IIO_PRESSURE] = "pressure",
73 [IIO_HUMIDITYRELATIVE] = "humidityrelative",
74 [IIO_ACTIVITY] = "activity",
75 [IIO_STEPS] = "steps",
76 [IIO_ENERGY] = "energy",
77 [IIO_DISTANCE] = "distance",
78 [IIO_VELOCITY] = "velocity",
79 [IIO_CONCENTRATION] = "concentration",
80 [IIO_RESISTANCE] = "resistance",
81 [IIO_PH] = "ph",
82 [IIO_UVINDEX] = "uvindex",
83 [IIO_ELECTRICALCONDUCTIVITY] = "electricalconductivity",
84 [IIO_COUNT] = "count",
85 [IIO_INDEX] = "index",
86 [IIO_GRAVITY] = "gravity",
87 [IIO_POSITIONRELATIVE] = "positionrelative",
88 [IIO_PHASE] = "phase",
89 [IIO_MASSCONCENTRATION] = "massconcentration",
92 static const char * const iio_modifier_names[] = {
93 [IIO_MOD_X] = "x",
94 [IIO_MOD_Y] = "y",
95 [IIO_MOD_Z] = "z",
96 [IIO_MOD_X_AND_Y] = "x&y",
97 [IIO_MOD_X_AND_Z] = "x&z",
98 [IIO_MOD_Y_AND_Z] = "y&z",
99 [IIO_MOD_X_AND_Y_AND_Z] = "x&y&z",
100 [IIO_MOD_X_OR_Y] = "x|y",
101 [IIO_MOD_X_OR_Z] = "x|z",
102 [IIO_MOD_Y_OR_Z] = "y|z",
103 [IIO_MOD_X_OR_Y_OR_Z] = "x|y|z",
104 [IIO_MOD_ROOT_SUM_SQUARED_X_Y] = "sqrt(x^2+y^2)",
105 [IIO_MOD_SUM_SQUARED_X_Y_Z] = "x^2+y^2+z^2",
106 [IIO_MOD_LIGHT_BOTH] = "both",
107 [IIO_MOD_LIGHT_IR] = "ir",
108 [IIO_MOD_LIGHT_CLEAR] = "clear",
109 [IIO_MOD_LIGHT_RED] = "red",
110 [IIO_MOD_LIGHT_GREEN] = "green",
111 [IIO_MOD_LIGHT_BLUE] = "blue",
112 [IIO_MOD_LIGHT_UV] = "uv",
113 [IIO_MOD_LIGHT_DUV] = "duv",
114 [IIO_MOD_QUATERNION] = "quaternion",
115 [IIO_MOD_TEMP_AMBIENT] = "ambient",
116 [IIO_MOD_TEMP_OBJECT] = "object",
117 [IIO_MOD_NORTH_MAGN] = "from_north_magnetic",
118 [IIO_MOD_NORTH_TRUE] = "from_north_true",
119 [IIO_MOD_NORTH_MAGN_TILT_COMP] = "from_north_magnetic_tilt_comp",
120 [IIO_MOD_NORTH_TRUE_TILT_COMP] = "from_north_true_tilt_comp",
121 [IIO_MOD_RUNNING] = "running",
122 [IIO_MOD_JOGGING] = "jogging",
123 [IIO_MOD_WALKING] = "walking",
124 [IIO_MOD_STILL] = "still",
125 [IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z] = "sqrt(x^2+y^2+z^2)",
126 [IIO_MOD_I] = "i",
127 [IIO_MOD_Q] = "q",
128 [IIO_MOD_CO2] = "co2",
129 [IIO_MOD_VOC] = "voc",
130 [IIO_MOD_PM1] = "pm1",
131 [IIO_MOD_PM2P5] = "pm2p5",
132 [IIO_MOD_PM4] = "pm4",
133 [IIO_MOD_PM10] = "pm10",
134 [IIO_MOD_ETHANOL] = "ethanol",
135 [IIO_MOD_H2] = "h2",
136 [IIO_MOD_O2] = "o2",
139 /* relies on pairs of these shared then separate */
140 static const char * const iio_chan_info_postfix[] = {
141 [IIO_CHAN_INFO_RAW] = "raw",
142 [IIO_CHAN_INFO_PROCESSED] = "input",
143 [IIO_CHAN_INFO_SCALE] = "scale",
144 [IIO_CHAN_INFO_OFFSET] = "offset",
145 [IIO_CHAN_INFO_CALIBSCALE] = "calibscale",
146 [IIO_CHAN_INFO_CALIBBIAS] = "calibbias",
147 [IIO_CHAN_INFO_PEAK] = "peak_raw",
148 [IIO_CHAN_INFO_PEAK_SCALE] = "peak_scale",
149 [IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW] = "quadrature_correction_raw",
150 [IIO_CHAN_INFO_AVERAGE_RAW] = "mean_raw",
151 [IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY]
152 = "filter_low_pass_3db_frequency",
153 [IIO_CHAN_INFO_HIGH_PASS_FILTER_3DB_FREQUENCY]
154 = "filter_high_pass_3db_frequency",
155 [IIO_CHAN_INFO_SAMP_FREQ] = "sampling_frequency",
156 [IIO_CHAN_INFO_FREQUENCY] = "frequency",
157 [IIO_CHAN_INFO_PHASE] = "phase",
158 [IIO_CHAN_INFO_HARDWAREGAIN] = "hardwaregain",
159 [IIO_CHAN_INFO_HYSTERESIS] = "hysteresis",
160 [IIO_CHAN_INFO_INT_TIME] = "integration_time",
161 [IIO_CHAN_INFO_ENABLE] = "en",
162 [IIO_CHAN_INFO_CALIBHEIGHT] = "calibheight",
163 [IIO_CHAN_INFO_CALIBWEIGHT] = "calibweight",
164 [IIO_CHAN_INFO_DEBOUNCE_COUNT] = "debounce_count",
165 [IIO_CHAN_INFO_DEBOUNCE_TIME] = "debounce_time",
166 [IIO_CHAN_INFO_CALIBEMISSIVITY] = "calibemissivity",
167 [IIO_CHAN_INFO_OVERSAMPLING_RATIO] = "oversampling_ratio",
168 [IIO_CHAN_INFO_THERMOCOUPLE_TYPE] = "thermocouple_type",
169 [IIO_CHAN_INFO_CALIBAMBIENT] = "calibambient",
172 #if defined(CONFIG_DEBUG_FS)
174 * There's also a CONFIG_DEBUG_FS guard in include/linux/iio/iio.h for
175 * iio_get_debugfs_dentry() to make it inline if CONFIG_DEBUG_FS is undefined
177 struct dentry *iio_get_debugfs_dentry(struct iio_dev *indio_dev)
179 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
180 return iio_dev_opaque->debugfs_dentry;
182 EXPORT_SYMBOL_GPL(iio_get_debugfs_dentry);
183 #endif
186 * iio_find_channel_from_si() - get channel from its scan index
187 * @indio_dev: device
188 * @si: scan index to match
190 const struct iio_chan_spec
191 *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
193 int i;
195 for (i = 0; i < indio_dev->num_channels; i++)
196 if (indio_dev->channels[i].scan_index == si)
197 return &indio_dev->channels[i];
198 return NULL;
201 /* This turns up an awful lot */
202 ssize_t iio_read_const_attr(struct device *dev,
203 struct device_attribute *attr,
204 char *buf)
206 return sprintf(buf, "%s\n", to_iio_const_attr(attr)->string);
208 EXPORT_SYMBOL(iio_read_const_attr);
211 * iio_device_set_clock() - Set current timestamping clock for the device
212 * @indio_dev: IIO device structure containing the device
213 * @clock_id: timestamping clock posix identifier to set.
215 int iio_device_set_clock(struct iio_dev *indio_dev, clockid_t clock_id)
217 int ret;
218 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
219 const struct iio_event_interface *ev_int = iio_dev_opaque->event_interface;
221 ret = mutex_lock_interruptible(&indio_dev->mlock);
222 if (ret)
223 return ret;
224 if ((ev_int && iio_event_enabled(ev_int)) ||
225 iio_buffer_enabled(indio_dev)) {
226 mutex_unlock(&indio_dev->mlock);
227 return -EBUSY;
229 indio_dev->clock_id = clock_id;
230 mutex_unlock(&indio_dev->mlock);
232 return 0;
234 EXPORT_SYMBOL(iio_device_set_clock);
237 * iio_get_time_ns() - utility function to get a time stamp for events etc
238 * @indio_dev: device
240 s64 iio_get_time_ns(const struct iio_dev *indio_dev)
242 struct timespec64 tp;
244 switch (iio_device_get_clock(indio_dev)) {
245 case CLOCK_REALTIME:
246 return ktime_get_real_ns();
247 case CLOCK_MONOTONIC:
248 return ktime_get_ns();
249 case CLOCK_MONOTONIC_RAW:
250 return ktime_get_raw_ns();
251 case CLOCK_REALTIME_COARSE:
252 return ktime_to_ns(ktime_get_coarse_real());
253 case CLOCK_MONOTONIC_COARSE:
254 ktime_get_coarse_ts64(&tp);
255 return timespec64_to_ns(&tp);
256 case CLOCK_BOOTTIME:
257 return ktime_get_boottime_ns();
258 case CLOCK_TAI:
259 return ktime_get_clocktai_ns();
260 default:
261 BUG();
264 EXPORT_SYMBOL(iio_get_time_ns);
267 * iio_get_time_res() - utility function to get time stamp clock resolution in
268 * nano seconds.
269 * @indio_dev: device
271 unsigned int iio_get_time_res(const struct iio_dev *indio_dev)
273 switch (iio_device_get_clock(indio_dev)) {
274 case CLOCK_REALTIME:
275 case CLOCK_MONOTONIC:
276 case CLOCK_MONOTONIC_RAW:
277 case CLOCK_BOOTTIME:
278 case CLOCK_TAI:
279 return hrtimer_resolution;
280 case CLOCK_REALTIME_COARSE:
281 case CLOCK_MONOTONIC_COARSE:
282 return LOW_RES_NSEC;
283 default:
284 BUG();
287 EXPORT_SYMBOL(iio_get_time_res);
289 static int __init iio_init(void)
291 int ret;
293 /* Register sysfs bus */
294 ret = bus_register(&iio_bus_type);
295 if (ret < 0) {
296 pr_err("could not register bus type\n");
297 goto error_nothing;
300 ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
301 if (ret < 0) {
302 pr_err("failed to allocate char dev region\n");
303 goto error_unregister_bus_type;
306 iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
308 return 0;
310 error_unregister_bus_type:
311 bus_unregister(&iio_bus_type);
312 error_nothing:
313 return ret;
316 static void __exit iio_exit(void)
318 if (iio_devt)
319 unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
320 bus_unregister(&iio_bus_type);
321 debugfs_remove(iio_debugfs_dentry);
324 #if defined(CONFIG_DEBUG_FS)
325 static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
326 size_t count, loff_t *ppos)
328 struct iio_dev *indio_dev = file->private_data;
329 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
330 unsigned val = 0;
331 int ret;
333 if (*ppos > 0)
334 return simple_read_from_buffer(userbuf, count, ppos,
335 iio_dev_opaque->read_buf,
336 iio_dev_opaque->read_buf_len);
338 ret = indio_dev->info->debugfs_reg_access(indio_dev,
339 iio_dev_opaque->cached_reg_addr,
340 0, &val);
341 if (ret) {
342 dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
343 return ret;
346 iio_dev_opaque->read_buf_len = snprintf(iio_dev_opaque->read_buf,
347 sizeof(iio_dev_opaque->read_buf),
348 "0x%X\n", val);
350 return simple_read_from_buffer(userbuf, count, ppos,
351 iio_dev_opaque->read_buf,
352 iio_dev_opaque->read_buf_len);
355 static ssize_t iio_debugfs_write_reg(struct file *file,
356 const char __user *userbuf, size_t count, loff_t *ppos)
358 struct iio_dev *indio_dev = file->private_data;
359 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
360 unsigned reg, val;
361 char buf[80];
362 int ret;
364 count = min_t(size_t, count, (sizeof(buf)-1));
365 if (copy_from_user(buf, userbuf, count))
366 return -EFAULT;
368 buf[count] = 0;
370 ret = sscanf(buf, "%i %i", &reg, &val);
372 switch (ret) {
373 case 1:
374 iio_dev_opaque->cached_reg_addr = reg;
375 break;
376 case 2:
377 iio_dev_opaque->cached_reg_addr = reg;
378 ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
379 val, NULL);
380 if (ret) {
381 dev_err(indio_dev->dev.parent, "%s: write failed\n",
382 __func__);
383 return ret;
385 break;
386 default:
387 return -EINVAL;
390 return count;
393 static const struct file_operations iio_debugfs_reg_fops = {
394 .open = simple_open,
395 .read = iio_debugfs_read_reg,
396 .write = iio_debugfs_write_reg,
399 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
401 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
402 debugfs_remove_recursive(iio_dev_opaque->debugfs_dentry);
405 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
407 struct iio_dev_opaque *iio_dev_opaque;
409 if (indio_dev->info->debugfs_reg_access == NULL)
410 return;
412 if (!iio_debugfs_dentry)
413 return;
415 iio_dev_opaque = to_iio_dev_opaque(indio_dev);
417 iio_dev_opaque->debugfs_dentry =
418 debugfs_create_dir(dev_name(&indio_dev->dev),
419 iio_debugfs_dentry);
421 debugfs_create_file("direct_reg_access", 0644,
422 iio_dev_opaque->debugfs_dentry, indio_dev,
423 &iio_debugfs_reg_fops);
425 #else
426 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
430 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
433 #endif /* CONFIG_DEBUG_FS */
435 static ssize_t iio_read_channel_ext_info(struct device *dev,
436 struct device_attribute *attr,
437 char *buf)
439 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
440 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
441 const struct iio_chan_spec_ext_info *ext_info;
443 ext_info = &this_attr->c->ext_info[this_attr->address];
445 return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
448 static ssize_t iio_write_channel_ext_info(struct device *dev,
449 struct device_attribute *attr,
450 const char *buf,
451 size_t len)
453 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
454 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
455 const struct iio_chan_spec_ext_info *ext_info;
457 ext_info = &this_attr->c->ext_info[this_attr->address];
459 return ext_info->write(indio_dev, ext_info->private,
460 this_attr->c, buf, len);
463 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
464 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
466 const struct iio_enum *e = (const struct iio_enum *)priv;
467 unsigned int i;
468 size_t len = 0;
470 if (!e->num_items)
471 return 0;
473 for (i = 0; i < e->num_items; ++i)
474 len += scnprintf(buf + len, PAGE_SIZE - len, "%s ", e->items[i]);
476 /* replace last space with a newline */
477 buf[len - 1] = '\n';
479 return len;
481 EXPORT_SYMBOL_GPL(iio_enum_available_read);
483 ssize_t iio_enum_read(struct iio_dev *indio_dev,
484 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
486 const struct iio_enum *e = (const struct iio_enum *)priv;
487 int i;
489 if (!e->get)
490 return -EINVAL;
492 i = e->get(indio_dev, chan);
493 if (i < 0)
494 return i;
495 else if (i >= e->num_items)
496 return -EINVAL;
498 return snprintf(buf, PAGE_SIZE, "%s\n", e->items[i]);
500 EXPORT_SYMBOL_GPL(iio_enum_read);
502 ssize_t iio_enum_write(struct iio_dev *indio_dev,
503 uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
504 size_t len)
506 const struct iio_enum *e = (const struct iio_enum *)priv;
507 int ret;
509 if (!e->set)
510 return -EINVAL;
512 ret = __sysfs_match_string(e->items, e->num_items, buf);
513 if (ret < 0)
514 return ret;
516 ret = e->set(indio_dev, chan, ret);
517 return ret ? ret : len;
519 EXPORT_SYMBOL_GPL(iio_enum_write);
521 static const struct iio_mount_matrix iio_mount_idmatrix = {
522 .rotation = {
523 "1", "0", "0",
524 "0", "1", "0",
525 "0", "0", "1"
529 static int iio_setup_mount_idmatrix(const struct device *dev,
530 struct iio_mount_matrix *matrix)
532 *matrix = iio_mount_idmatrix;
533 dev_info(dev, "mounting matrix not found: using identity...\n");
534 return 0;
537 ssize_t iio_show_mount_matrix(struct iio_dev *indio_dev, uintptr_t priv,
538 const struct iio_chan_spec *chan, char *buf)
540 const struct iio_mount_matrix *mtx = ((iio_get_mount_matrix_t *)
541 priv)(indio_dev, chan);
543 if (IS_ERR(mtx))
544 return PTR_ERR(mtx);
546 if (!mtx)
547 mtx = &iio_mount_idmatrix;
549 return snprintf(buf, PAGE_SIZE, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
550 mtx->rotation[0], mtx->rotation[1], mtx->rotation[2],
551 mtx->rotation[3], mtx->rotation[4], mtx->rotation[5],
552 mtx->rotation[6], mtx->rotation[7], mtx->rotation[8]);
554 EXPORT_SYMBOL_GPL(iio_show_mount_matrix);
557 * iio_read_mount_matrix() - retrieve iio device mounting matrix from
558 * device "mount-matrix" property
559 * @dev: device the mounting matrix property is assigned to
560 * @propname: device specific mounting matrix property name
561 * @matrix: where to store retrieved matrix
563 * If device is assigned no mounting matrix property, a default 3x3 identity
564 * matrix will be filled in.
566 * Return: 0 if success, or a negative error code on failure.
568 int iio_read_mount_matrix(struct device *dev, const char *propname,
569 struct iio_mount_matrix *matrix)
571 size_t len = ARRAY_SIZE(iio_mount_idmatrix.rotation);
572 int err;
574 err = device_property_read_string_array(dev, propname,
575 matrix->rotation, len);
576 if (err == len)
577 return 0;
579 if (err >= 0)
580 /* Invalid number of matrix entries. */
581 return -EINVAL;
583 if (err != -EINVAL)
584 /* Invalid matrix declaration format. */
585 return err;
587 /* Matrix was not declared at all: fallback to identity. */
588 return iio_setup_mount_idmatrix(dev, matrix);
590 EXPORT_SYMBOL(iio_read_mount_matrix);
592 static ssize_t __iio_format_value(char *buf, size_t len, unsigned int type,
593 int size, const int *vals)
595 unsigned long long tmp;
596 int tmp0, tmp1;
597 s64 tmp2;
598 bool scale_db = false;
600 switch (type) {
601 case IIO_VAL_INT:
602 return scnprintf(buf, len, "%d", vals[0]);
603 case IIO_VAL_INT_PLUS_MICRO_DB:
604 scale_db = true;
605 fallthrough;
606 case IIO_VAL_INT_PLUS_MICRO:
607 if (vals[1] < 0)
608 return scnprintf(buf, len, "-%d.%06u%s", abs(vals[0]),
609 -vals[1], scale_db ? " dB" : "");
610 else
611 return scnprintf(buf, len, "%d.%06u%s", vals[0], vals[1],
612 scale_db ? " dB" : "");
613 case IIO_VAL_INT_PLUS_NANO:
614 if (vals[1] < 0)
615 return scnprintf(buf, len, "-%d.%09u", abs(vals[0]),
616 -vals[1]);
617 else
618 return scnprintf(buf, len, "%d.%09u", vals[0], vals[1]);
619 case IIO_VAL_FRACTIONAL:
620 tmp2 = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
621 tmp1 = vals[1];
622 tmp0 = (int)div_s64_rem(tmp2, 1000000000, &tmp1);
623 if ((tmp2 < 0) && (tmp0 == 0))
624 return snprintf(buf, len, "-0.%09u", abs(tmp1));
625 else
626 return snprintf(buf, len, "%d.%09u", tmp0, abs(tmp1));
627 case IIO_VAL_FRACTIONAL_LOG2:
628 tmp = shift_right((s64)vals[0] * 1000000000LL, vals[1]);
629 tmp0 = (int)div_s64_rem(tmp, 1000000000LL, &tmp1);
630 return scnprintf(buf, len, "%d.%09u", tmp0, abs(tmp1));
631 case IIO_VAL_INT_MULTIPLE:
633 int i;
634 int l = 0;
636 for (i = 0; i < size; ++i) {
637 l += scnprintf(&buf[l], len - l, "%d ", vals[i]);
638 if (l >= len)
639 break;
641 return l;
643 case IIO_VAL_CHAR:
644 return scnprintf(buf, len, "%c", (char)vals[0]);
645 default:
646 return 0;
651 * iio_format_value() - Formats a IIO value into its string representation
652 * @buf: The buffer to which the formatted value gets written
653 * which is assumed to be big enough (i.e. PAGE_SIZE).
654 * @type: One of the IIO_VAL_* constants. This decides how the val
655 * and val2 parameters are formatted.
656 * @size: Number of IIO value entries contained in vals
657 * @vals: Pointer to the values, exact meaning depends on the
658 * type parameter.
660 * Return: 0 by default, a negative number on failure or the
661 * total number of characters written for a type that belongs
662 * to the IIO_VAL_* constant.
664 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
666 ssize_t len;
668 len = __iio_format_value(buf, PAGE_SIZE, type, size, vals);
669 if (len >= PAGE_SIZE - 1)
670 return -EFBIG;
672 return len + sprintf(buf + len, "\n");
674 EXPORT_SYMBOL_GPL(iio_format_value);
676 static ssize_t iio_read_channel_label(struct device *dev,
677 struct device_attribute *attr,
678 char *buf)
680 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
681 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
683 if (!indio_dev->info->read_label)
684 return -EINVAL;
686 return indio_dev->info->read_label(indio_dev, this_attr->c, buf);
689 static ssize_t iio_read_channel_info(struct device *dev,
690 struct device_attribute *attr,
691 char *buf)
693 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
694 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
695 int vals[INDIO_MAX_RAW_ELEMENTS];
696 int ret;
697 int val_len = 2;
699 if (indio_dev->info->read_raw_multi)
700 ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
701 INDIO_MAX_RAW_ELEMENTS,
702 vals, &val_len,
703 this_attr->address);
704 else
705 ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
706 &vals[0], &vals[1], this_attr->address);
708 if (ret < 0)
709 return ret;
711 return iio_format_value(buf, ret, val_len, vals);
714 static ssize_t iio_format_list(char *buf, const int *vals, int type, int length,
715 const char *prefix, const char *suffix)
717 ssize_t len;
718 int stride;
719 int i;
721 switch (type) {
722 case IIO_VAL_INT:
723 stride = 1;
724 break;
725 default:
726 stride = 2;
727 break;
730 len = scnprintf(buf, PAGE_SIZE, prefix);
732 for (i = 0; i <= length - stride; i += stride) {
733 if (i != 0) {
734 len += scnprintf(buf + len, PAGE_SIZE - len, " ");
735 if (len >= PAGE_SIZE)
736 return -EFBIG;
739 len += __iio_format_value(buf + len, PAGE_SIZE - len, type,
740 stride, &vals[i]);
741 if (len >= PAGE_SIZE)
742 return -EFBIG;
745 len += scnprintf(buf + len, PAGE_SIZE - len, "%s\n", suffix);
747 return len;
750 static ssize_t iio_format_avail_list(char *buf, const int *vals,
751 int type, int length)
754 return iio_format_list(buf, vals, type, length, "", "");
757 static ssize_t iio_format_avail_range(char *buf, const int *vals, int type)
759 return iio_format_list(buf, vals, type, 3, "[", "]");
762 static ssize_t iio_read_channel_info_avail(struct device *dev,
763 struct device_attribute *attr,
764 char *buf)
766 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
767 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
768 const int *vals;
769 int ret;
770 int length;
771 int type;
773 ret = indio_dev->info->read_avail(indio_dev, this_attr->c,
774 &vals, &type, &length,
775 this_attr->address);
777 if (ret < 0)
778 return ret;
779 switch (ret) {
780 case IIO_AVAIL_LIST:
781 return iio_format_avail_list(buf, vals, type, length);
782 case IIO_AVAIL_RANGE:
783 return iio_format_avail_range(buf, vals, type);
784 default:
785 return -EINVAL;
790 * __iio_str_to_fixpoint() - Parse a fixed-point number from a string
791 * @str: The string to parse
792 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
793 * @integer: The integer part of the number
794 * @fract: The fractional part of the number
795 * @scale_db: True if this should parse as dB
797 * Returns 0 on success, or a negative error code if the string could not be
798 * parsed.
800 static int __iio_str_to_fixpoint(const char *str, int fract_mult,
801 int *integer, int *fract, bool scale_db)
803 int i = 0, f = 0;
804 bool integer_part = true, negative = false;
806 if (fract_mult == 0) {
807 *fract = 0;
809 return kstrtoint(str, 0, integer);
812 if (str[0] == '-') {
813 negative = true;
814 str++;
815 } else if (str[0] == '+') {
816 str++;
819 while (*str) {
820 if ('0' <= *str && *str <= '9') {
821 if (integer_part) {
822 i = i * 10 + *str - '0';
823 } else {
824 f += fract_mult * (*str - '0');
825 fract_mult /= 10;
827 } else if (*str == '\n') {
828 if (*(str + 1) == '\0')
829 break;
830 else
831 return -EINVAL;
832 } else if (!strncmp(str, " dB", sizeof(" dB") - 1) && scale_db) {
833 /* Ignore the dB suffix */
834 str += sizeof(" dB") - 1;
835 continue;
836 } else if (!strncmp(str, "dB", sizeof("dB") - 1) && scale_db) {
837 /* Ignore the dB suffix */
838 str += sizeof("dB") - 1;
839 continue;
840 } else if (*str == '.' && integer_part) {
841 integer_part = false;
842 } else {
843 return -EINVAL;
845 str++;
848 if (negative) {
849 if (i)
850 i = -i;
851 else
852 f = -f;
855 *integer = i;
856 *fract = f;
858 return 0;
862 * iio_str_to_fixpoint() - Parse a fixed-point number from a string
863 * @str: The string to parse
864 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
865 * @integer: The integer part of the number
866 * @fract: The fractional part of the number
868 * Returns 0 on success, or a negative error code if the string could not be
869 * parsed.
871 int iio_str_to_fixpoint(const char *str, int fract_mult,
872 int *integer, int *fract)
874 return __iio_str_to_fixpoint(str, fract_mult, integer, fract, false);
876 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
878 static ssize_t iio_write_channel_info(struct device *dev,
879 struct device_attribute *attr,
880 const char *buf,
881 size_t len)
883 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
884 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
885 int ret, fract_mult = 100000;
886 int integer, fract = 0;
887 bool is_char = false;
888 bool scale_db = false;
890 /* Assumes decimal - precision based on number of digits */
891 if (!indio_dev->info->write_raw)
892 return -EINVAL;
894 if (indio_dev->info->write_raw_get_fmt)
895 switch (indio_dev->info->write_raw_get_fmt(indio_dev,
896 this_attr->c, this_attr->address)) {
897 case IIO_VAL_INT:
898 fract_mult = 0;
899 break;
900 case IIO_VAL_INT_PLUS_MICRO_DB:
901 scale_db = true;
902 fallthrough;
903 case IIO_VAL_INT_PLUS_MICRO:
904 fract_mult = 100000;
905 break;
906 case IIO_VAL_INT_PLUS_NANO:
907 fract_mult = 100000000;
908 break;
909 case IIO_VAL_CHAR:
910 is_char = true;
911 break;
912 default:
913 return -EINVAL;
916 if (is_char) {
917 char ch;
919 if (sscanf(buf, "%c", &ch) != 1)
920 return -EINVAL;
921 integer = ch;
922 } else {
923 ret = __iio_str_to_fixpoint(buf, fract_mult, &integer, &fract,
924 scale_db);
925 if (ret)
926 return ret;
929 ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
930 integer, fract, this_attr->address);
931 if (ret)
932 return ret;
934 return len;
937 static
938 int __iio_device_attr_init(struct device_attribute *dev_attr,
939 const char *postfix,
940 struct iio_chan_spec const *chan,
941 ssize_t (*readfunc)(struct device *dev,
942 struct device_attribute *attr,
943 char *buf),
944 ssize_t (*writefunc)(struct device *dev,
945 struct device_attribute *attr,
946 const char *buf,
947 size_t len),
948 enum iio_shared_by shared_by)
950 int ret = 0;
951 char *name = NULL;
952 char *full_postfix;
953 sysfs_attr_init(&dev_attr->attr);
955 /* Build up postfix of <extend_name>_<modifier>_postfix */
956 if (chan->modified && (shared_by == IIO_SEPARATE)) {
957 if (chan->extend_name)
958 full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
959 iio_modifier_names[chan
960 ->channel2],
961 chan->extend_name,
962 postfix);
963 else
964 full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
965 iio_modifier_names[chan
966 ->channel2],
967 postfix);
968 } else {
969 if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
970 full_postfix = kstrdup(postfix, GFP_KERNEL);
971 else
972 full_postfix = kasprintf(GFP_KERNEL,
973 "%s_%s",
974 chan->extend_name,
975 postfix);
977 if (full_postfix == NULL)
978 return -ENOMEM;
980 if (chan->differential) { /* Differential can not have modifier */
981 switch (shared_by) {
982 case IIO_SHARED_BY_ALL:
983 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
984 break;
985 case IIO_SHARED_BY_DIR:
986 name = kasprintf(GFP_KERNEL, "%s_%s",
987 iio_direction[chan->output],
988 full_postfix);
989 break;
990 case IIO_SHARED_BY_TYPE:
991 name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
992 iio_direction[chan->output],
993 iio_chan_type_name_spec[chan->type],
994 iio_chan_type_name_spec[chan->type],
995 full_postfix);
996 break;
997 case IIO_SEPARATE:
998 if (!chan->indexed) {
999 WARN(1, "Differential channels must be indexed\n");
1000 ret = -EINVAL;
1001 goto error_free_full_postfix;
1003 name = kasprintf(GFP_KERNEL,
1004 "%s_%s%d-%s%d_%s",
1005 iio_direction[chan->output],
1006 iio_chan_type_name_spec[chan->type],
1007 chan->channel,
1008 iio_chan_type_name_spec[chan->type],
1009 chan->channel2,
1010 full_postfix);
1011 break;
1013 } else { /* Single ended */
1014 switch (shared_by) {
1015 case IIO_SHARED_BY_ALL:
1016 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1017 break;
1018 case IIO_SHARED_BY_DIR:
1019 name = kasprintf(GFP_KERNEL, "%s_%s",
1020 iio_direction[chan->output],
1021 full_postfix);
1022 break;
1023 case IIO_SHARED_BY_TYPE:
1024 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1025 iio_direction[chan->output],
1026 iio_chan_type_name_spec[chan->type],
1027 full_postfix);
1028 break;
1030 case IIO_SEPARATE:
1031 if (chan->indexed)
1032 name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
1033 iio_direction[chan->output],
1034 iio_chan_type_name_spec[chan->type],
1035 chan->channel,
1036 full_postfix);
1037 else
1038 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1039 iio_direction[chan->output],
1040 iio_chan_type_name_spec[chan->type],
1041 full_postfix);
1042 break;
1045 if (name == NULL) {
1046 ret = -ENOMEM;
1047 goto error_free_full_postfix;
1049 dev_attr->attr.name = name;
1051 if (readfunc) {
1052 dev_attr->attr.mode |= S_IRUGO;
1053 dev_attr->show = readfunc;
1056 if (writefunc) {
1057 dev_attr->attr.mode |= S_IWUSR;
1058 dev_attr->store = writefunc;
1061 error_free_full_postfix:
1062 kfree(full_postfix);
1064 return ret;
1067 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
1069 kfree(dev_attr->attr.name);
1072 int __iio_add_chan_devattr(const char *postfix,
1073 struct iio_chan_spec const *chan,
1074 ssize_t (*readfunc)(struct device *dev,
1075 struct device_attribute *attr,
1076 char *buf),
1077 ssize_t (*writefunc)(struct device *dev,
1078 struct device_attribute *attr,
1079 const char *buf,
1080 size_t len),
1081 u64 mask,
1082 enum iio_shared_by shared_by,
1083 struct device *dev,
1084 struct list_head *attr_list)
1086 int ret;
1087 struct iio_dev_attr *iio_attr, *t;
1089 iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
1090 if (iio_attr == NULL)
1091 return -ENOMEM;
1092 ret = __iio_device_attr_init(&iio_attr->dev_attr,
1093 postfix, chan,
1094 readfunc, writefunc, shared_by);
1095 if (ret)
1096 goto error_iio_dev_attr_free;
1097 iio_attr->c = chan;
1098 iio_attr->address = mask;
1099 list_for_each_entry(t, attr_list, l)
1100 if (strcmp(t->dev_attr.attr.name,
1101 iio_attr->dev_attr.attr.name) == 0) {
1102 if (shared_by == IIO_SEPARATE)
1103 dev_err(dev, "tried to double register : %s\n",
1104 t->dev_attr.attr.name);
1105 ret = -EBUSY;
1106 goto error_device_attr_deinit;
1108 list_add(&iio_attr->l, attr_list);
1110 return 0;
1112 error_device_attr_deinit:
1113 __iio_device_attr_deinit(&iio_attr->dev_attr);
1114 error_iio_dev_attr_free:
1115 kfree(iio_attr);
1116 return ret;
1119 static int iio_device_add_channel_label(struct iio_dev *indio_dev,
1120 struct iio_chan_spec const *chan)
1122 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1123 int ret;
1125 if (!indio_dev->info->read_label)
1126 return 0;
1128 ret = __iio_add_chan_devattr("label",
1129 chan,
1130 &iio_read_channel_label,
1131 NULL,
1133 IIO_SEPARATE,
1134 &indio_dev->dev,
1135 &iio_dev_opaque->channel_attr_list);
1136 if (ret < 0)
1137 return ret;
1139 return 1;
1142 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
1143 struct iio_chan_spec const *chan,
1144 enum iio_shared_by shared_by,
1145 const long *infomask)
1147 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1148 int i, ret, attrcount = 0;
1150 for_each_set_bit(i, infomask, sizeof(*infomask)*8) {
1151 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1152 return -EINVAL;
1153 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
1154 chan,
1155 &iio_read_channel_info,
1156 &iio_write_channel_info,
1158 shared_by,
1159 &indio_dev->dev,
1160 &iio_dev_opaque->channel_attr_list);
1161 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1162 continue;
1163 else if (ret < 0)
1164 return ret;
1165 attrcount++;
1168 return attrcount;
1171 static int iio_device_add_info_mask_type_avail(struct iio_dev *indio_dev,
1172 struct iio_chan_spec const *chan,
1173 enum iio_shared_by shared_by,
1174 const long *infomask)
1176 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1177 int i, ret, attrcount = 0;
1178 char *avail_postfix;
1180 for_each_set_bit(i, infomask, sizeof(*infomask) * 8) {
1181 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1182 return -EINVAL;
1183 avail_postfix = kasprintf(GFP_KERNEL,
1184 "%s_available",
1185 iio_chan_info_postfix[i]);
1186 if (!avail_postfix)
1187 return -ENOMEM;
1189 ret = __iio_add_chan_devattr(avail_postfix,
1190 chan,
1191 &iio_read_channel_info_avail,
1192 NULL,
1194 shared_by,
1195 &indio_dev->dev,
1196 &iio_dev_opaque->channel_attr_list);
1197 kfree(avail_postfix);
1198 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1199 continue;
1200 else if (ret < 0)
1201 return ret;
1202 attrcount++;
1205 return attrcount;
1208 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
1209 struct iio_chan_spec const *chan)
1211 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1212 int ret, attrcount = 0;
1213 const struct iio_chan_spec_ext_info *ext_info;
1215 if (chan->channel < 0)
1216 return 0;
1217 ret = iio_device_add_info_mask_type(indio_dev, chan,
1218 IIO_SEPARATE,
1219 &chan->info_mask_separate);
1220 if (ret < 0)
1221 return ret;
1222 attrcount += ret;
1224 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1225 IIO_SEPARATE,
1226 &chan->
1227 info_mask_separate_available);
1228 if (ret < 0)
1229 return ret;
1230 attrcount += ret;
1232 ret = iio_device_add_info_mask_type(indio_dev, chan,
1233 IIO_SHARED_BY_TYPE,
1234 &chan->info_mask_shared_by_type);
1235 if (ret < 0)
1236 return ret;
1237 attrcount += ret;
1239 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1240 IIO_SHARED_BY_TYPE,
1241 &chan->
1242 info_mask_shared_by_type_available);
1243 if (ret < 0)
1244 return ret;
1245 attrcount += ret;
1247 ret = iio_device_add_info_mask_type(indio_dev, chan,
1248 IIO_SHARED_BY_DIR,
1249 &chan->info_mask_shared_by_dir);
1250 if (ret < 0)
1251 return ret;
1252 attrcount += ret;
1254 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1255 IIO_SHARED_BY_DIR,
1256 &chan->info_mask_shared_by_dir_available);
1257 if (ret < 0)
1258 return ret;
1259 attrcount += ret;
1261 ret = iio_device_add_info_mask_type(indio_dev, chan,
1262 IIO_SHARED_BY_ALL,
1263 &chan->info_mask_shared_by_all);
1264 if (ret < 0)
1265 return ret;
1266 attrcount += ret;
1268 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1269 IIO_SHARED_BY_ALL,
1270 &chan->info_mask_shared_by_all_available);
1271 if (ret < 0)
1272 return ret;
1273 attrcount += ret;
1275 ret = iio_device_add_channel_label(indio_dev, chan);
1276 if (ret < 0)
1277 return ret;
1278 attrcount += ret;
1280 if (chan->ext_info) {
1281 unsigned int i = 0;
1282 for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
1283 ret = __iio_add_chan_devattr(ext_info->name,
1284 chan,
1285 ext_info->read ?
1286 &iio_read_channel_ext_info : NULL,
1287 ext_info->write ?
1288 &iio_write_channel_ext_info : NULL,
1290 ext_info->shared,
1291 &indio_dev->dev,
1292 &iio_dev_opaque->channel_attr_list);
1293 i++;
1294 if (ret == -EBUSY && ext_info->shared)
1295 continue;
1297 if (ret)
1298 return ret;
1300 attrcount++;
1304 return attrcount;
1308 * iio_free_chan_devattr_list() - Free a list of IIO device attributes
1309 * @attr_list: List of IIO device attributes
1311 * This function frees the memory allocated for each of the IIO device
1312 * attributes in the list.
1314 void iio_free_chan_devattr_list(struct list_head *attr_list)
1316 struct iio_dev_attr *p, *n;
1318 list_for_each_entry_safe(p, n, attr_list, l) {
1319 kfree(p->dev_attr.attr.name);
1320 list_del(&p->l);
1321 kfree(p);
1325 static ssize_t iio_show_dev_name(struct device *dev,
1326 struct device_attribute *attr,
1327 char *buf)
1329 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1330 return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->name);
1333 static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
1335 static ssize_t iio_show_dev_label(struct device *dev,
1336 struct device_attribute *attr,
1337 char *buf)
1339 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1340 return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->label);
1343 static DEVICE_ATTR(label, S_IRUGO, iio_show_dev_label, NULL);
1345 static ssize_t iio_show_timestamp_clock(struct device *dev,
1346 struct device_attribute *attr,
1347 char *buf)
1349 const struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1350 const clockid_t clk = iio_device_get_clock(indio_dev);
1351 const char *name;
1352 ssize_t sz;
1354 switch (clk) {
1355 case CLOCK_REALTIME:
1356 name = "realtime\n";
1357 sz = sizeof("realtime\n");
1358 break;
1359 case CLOCK_MONOTONIC:
1360 name = "monotonic\n";
1361 sz = sizeof("monotonic\n");
1362 break;
1363 case CLOCK_MONOTONIC_RAW:
1364 name = "monotonic_raw\n";
1365 sz = sizeof("monotonic_raw\n");
1366 break;
1367 case CLOCK_REALTIME_COARSE:
1368 name = "realtime_coarse\n";
1369 sz = sizeof("realtime_coarse\n");
1370 break;
1371 case CLOCK_MONOTONIC_COARSE:
1372 name = "monotonic_coarse\n";
1373 sz = sizeof("monotonic_coarse\n");
1374 break;
1375 case CLOCK_BOOTTIME:
1376 name = "boottime\n";
1377 sz = sizeof("boottime\n");
1378 break;
1379 case CLOCK_TAI:
1380 name = "tai\n";
1381 sz = sizeof("tai\n");
1382 break;
1383 default:
1384 BUG();
1387 memcpy(buf, name, sz);
1388 return sz;
1391 static ssize_t iio_store_timestamp_clock(struct device *dev,
1392 struct device_attribute *attr,
1393 const char *buf, size_t len)
1395 clockid_t clk;
1396 int ret;
1398 if (sysfs_streq(buf, "realtime"))
1399 clk = CLOCK_REALTIME;
1400 else if (sysfs_streq(buf, "monotonic"))
1401 clk = CLOCK_MONOTONIC;
1402 else if (sysfs_streq(buf, "monotonic_raw"))
1403 clk = CLOCK_MONOTONIC_RAW;
1404 else if (sysfs_streq(buf, "realtime_coarse"))
1405 clk = CLOCK_REALTIME_COARSE;
1406 else if (sysfs_streq(buf, "monotonic_coarse"))
1407 clk = CLOCK_MONOTONIC_COARSE;
1408 else if (sysfs_streq(buf, "boottime"))
1409 clk = CLOCK_BOOTTIME;
1410 else if (sysfs_streq(buf, "tai"))
1411 clk = CLOCK_TAI;
1412 else
1413 return -EINVAL;
1415 ret = iio_device_set_clock(dev_to_iio_dev(dev), clk);
1416 if (ret)
1417 return ret;
1419 return len;
1422 static DEVICE_ATTR(current_timestamp_clock, S_IRUGO | S_IWUSR,
1423 iio_show_timestamp_clock, iio_store_timestamp_clock);
1425 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
1427 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1428 int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
1429 struct iio_dev_attr *p;
1430 struct attribute **attr, *clk = NULL;
1432 /* First count elements in any existing group */
1433 if (indio_dev->info->attrs) {
1434 attr = indio_dev->info->attrs->attrs;
1435 while (*attr++ != NULL)
1436 attrcount_orig++;
1438 attrcount = attrcount_orig;
1440 * New channel registration method - relies on the fact a group does
1441 * not need to be initialized if its name is NULL.
1443 if (indio_dev->channels)
1444 for (i = 0; i < indio_dev->num_channels; i++) {
1445 const struct iio_chan_spec *chan =
1446 &indio_dev->channels[i];
1448 if (chan->type == IIO_TIMESTAMP)
1449 clk = &dev_attr_current_timestamp_clock.attr;
1451 ret = iio_device_add_channel_sysfs(indio_dev, chan);
1452 if (ret < 0)
1453 goto error_clear_attrs;
1454 attrcount += ret;
1457 if (iio_dev_opaque->event_interface)
1458 clk = &dev_attr_current_timestamp_clock.attr;
1460 if (indio_dev->name)
1461 attrcount++;
1462 if (indio_dev->label)
1463 attrcount++;
1464 if (clk)
1465 attrcount++;
1467 iio_dev_opaque->chan_attr_group.attrs =
1468 kcalloc(attrcount + 1,
1469 sizeof(iio_dev_opaque->chan_attr_group.attrs[0]),
1470 GFP_KERNEL);
1471 if (iio_dev_opaque->chan_attr_group.attrs == NULL) {
1472 ret = -ENOMEM;
1473 goto error_clear_attrs;
1475 /* Copy across original attributes */
1476 if (indio_dev->info->attrs)
1477 memcpy(iio_dev_opaque->chan_attr_group.attrs,
1478 indio_dev->info->attrs->attrs,
1479 sizeof(iio_dev_opaque->chan_attr_group.attrs[0])
1480 *attrcount_orig);
1481 attrn = attrcount_orig;
1482 /* Add all elements from the list. */
1483 list_for_each_entry(p, &iio_dev_opaque->channel_attr_list, l)
1484 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1485 if (indio_dev->name)
1486 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
1487 if (indio_dev->label)
1488 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_label.attr;
1489 if (clk)
1490 iio_dev_opaque->chan_attr_group.attrs[attrn++] = clk;
1492 indio_dev->groups[indio_dev->groupcounter++] =
1493 &iio_dev_opaque->chan_attr_group;
1495 return 0;
1497 error_clear_attrs:
1498 iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1500 return ret;
1503 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
1505 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1507 iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1508 kfree(iio_dev_opaque->chan_attr_group.attrs);
1509 iio_dev_opaque->chan_attr_group.attrs = NULL;
1512 static void iio_dev_release(struct device *device)
1514 struct iio_dev *indio_dev = dev_to_iio_dev(device);
1515 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1517 if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1518 iio_device_unregister_trigger_consumer(indio_dev);
1519 iio_device_unregister_eventset(indio_dev);
1520 iio_device_unregister_sysfs(indio_dev);
1522 iio_buffer_put(indio_dev->buffer);
1524 ida_simple_remove(&iio_ida, indio_dev->id);
1525 kfree(iio_dev_opaque);
1528 struct device_type iio_device_type = {
1529 .name = "iio_device",
1530 .release = iio_dev_release,
1534 * iio_device_alloc() - allocate an iio_dev from a driver
1535 * @parent: Parent device.
1536 * @sizeof_priv: Space to allocate for private structure.
1538 struct iio_dev *iio_device_alloc(struct device *parent, int sizeof_priv)
1540 struct iio_dev_opaque *iio_dev_opaque;
1541 struct iio_dev *dev;
1542 size_t alloc_size;
1544 alloc_size = sizeof(struct iio_dev_opaque);
1545 if (sizeof_priv) {
1546 alloc_size = ALIGN(alloc_size, IIO_ALIGN);
1547 alloc_size += sizeof_priv;
1550 iio_dev_opaque = kzalloc(alloc_size, GFP_KERNEL);
1551 if (!iio_dev_opaque)
1552 return NULL;
1554 dev = &iio_dev_opaque->indio_dev;
1555 dev->priv = (char *)iio_dev_opaque +
1556 ALIGN(sizeof(struct iio_dev_opaque), IIO_ALIGN);
1558 dev->dev.parent = parent;
1559 dev->dev.groups = dev->groups;
1560 dev->dev.type = &iio_device_type;
1561 dev->dev.bus = &iio_bus_type;
1562 device_initialize(&dev->dev);
1563 dev_set_drvdata(&dev->dev, (void *)dev);
1564 mutex_init(&dev->mlock);
1565 mutex_init(&dev->info_exist_lock);
1566 INIT_LIST_HEAD(&iio_dev_opaque->channel_attr_list);
1568 dev->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
1569 if (dev->id < 0) {
1570 /* cannot use a dev_err as the name isn't available */
1571 pr_err("failed to get device id\n");
1572 kfree(iio_dev_opaque);
1573 return NULL;
1575 dev_set_name(&dev->dev, "iio:device%d", dev->id);
1576 INIT_LIST_HEAD(&iio_dev_opaque->buffer_list);
1577 INIT_LIST_HEAD(&iio_dev_opaque->ioctl_handlers);
1579 return dev;
1581 EXPORT_SYMBOL(iio_device_alloc);
1584 * iio_device_free() - free an iio_dev from a driver
1585 * @dev: the iio_dev associated with the device
1587 void iio_device_free(struct iio_dev *dev)
1589 if (dev)
1590 put_device(&dev->dev);
1592 EXPORT_SYMBOL(iio_device_free);
1594 static void devm_iio_device_release(struct device *dev, void *res)
1596 iio_device_free(*(struct iio_dev **)res);
1600 * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1601 * @parent: Device to allocate iio_dev for, and parent for this IIO device
1602 * @sizeof_priv: Space to allocate for private structure.
1604 * Managed iio_device_alloc. iio_dev allocated with this function is
1605 * automatically freed on driver detach.
1607 * RETURNS:
1608 * Pointer to allocated iio_dev on success, NULL on failure.
1610 struct iio_dev *devm_iio_device_alloc(struct device *parent, int sizeof_priv)
1612 struct iio_dev **ptr, *iio_dev;
1614 ptr = devres_alloc(devm_iio_device_release, sizeof(*ptr),
1615 GFP_KERNEL);
1616 if (!ptr)
1617 return NULL;
1619 iio_dev = iio_device_alloc(parent, sizeof_priv);
1620 if (iio_dev) {
1621 *ptr = iio_dev;
1622 devres_add(parent, ptr);
1623 } else {
1624 devres_free(ptr);
1627 return iio_dev;
1629 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1632 * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1633 * @inode: Inode structure for identifying the device in the file system
1634 * @filp: File structure for iio device used to keep and later access
1635 * private data
1637 * Return: 0 on success or -EBUSY if the device is already opened
1639 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1641 struct iio_dev *indio_dev = container_of(inode->i_cdev,
1642 struct iio_dev, chrdev);
1644 if (test_and_set_bit(IIO_BUSY_BIT_POS, &indio_dev->flags))
1645 return -EBUSY;
1647 iio_device_get(indio_dev);
1649 filp->private_data = indio_dev;
1651 return 0;
1655 * iio_chrdev_release() - chrdev file close buffer access and ioctls
1656 * @inode: Inode structure pointer for the char device
1657 * @filp: File structure pointer for the char device
1659 * Return: 0 for successful release
1661 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1663 struct iio_dev *indio_dev = container_of(inode->i_cdev,
1664 struct iio_dev, chrdev);
1665 clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
1666 iio_device_put(indio_dev);
1668 return 0;
1671 void iio_device_ioctl_handler_register(struct iio_dev *indio_dev,
1672 struct iio_ioctl_handler *h)
1674 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1676 list_add_tail(&h->entry, &iio_dev_opaque->ioctl_handlers);
1679 void iio_device_ioctl_handler_unregister(struct iio_ioctl_handler *h)
1681 list_del(&h->entry);
1684 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1686 struct iio_dev *indio_dev = filp->private_data;
1687 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1688 struct iio_ioctl_handler *h;
1689 int ret = -ENODEV;
1691 mutex_lock(&indio_dev->info_exist_lock);
1694 * The NULL check here is required to prevent crashing when a device
1695 * is being removed while userspace would still have open file handles
1696 * to try to access this device.
1698 if (!indio_dev->info)
1699 goto out_unlock;
1701 ret = -EINVAL;
1702 list_for_each_entry(h, &iio_dev_opaque->ioctl_handlers, entry) {
1703 ret = h->ioctl(indio_dev, filp, cmd, arg);
1704 if (ret != IIO_IOCTL_UNHANDLED)
1705 break;
1708 if (ret == IIO_IOCTL_UNHANDLED)
1709 ret = -EINVAL;
1711 out_unlock:
1712 mutex_unlock(&indio_dev->info_exist_lock);
1714 return ret;
1717 static const struct file_operations iio_buffer_fileops = {
1718 .owner = THIS_MODULE,
1719 .llseek = noop_llseek,
1720 .read = iio_buffer_read_outer_addr,
1721 .poll = iio_buffer_poll_addr,
1722 .unlocked_ioctl = iio_ioctl,
1723 .compat_ioctl = compat_ptr_ioctl,
1724 .open = iio_chrdev_open,
1725 .release = iio_chrdev_release,
1728 static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1730 int i, j;
1731 const struct iio_chan_spec *channels = indio_dev->channels;
1733 if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1734 return 0;
1736 for (i = 0; i < indio_dev->num_channels - 1; i++) {
1737 if (channels[i].scan_index < 0)
1738 continue;
1739 for (j = i + 1; j < indio_dev->num_channels; j++)
1740 if (channels[i].scan_index == channels[j].scan_index) {
1741 dev_err(&indio_dev->dev,
1742 "Duplicate scan index %d\n",
1743 channels[i].scan_index);
1744 return -EINVAL;
1748 return 0;
1751 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1753 int __iio_device_register(struct iio_dev *indio_dev, struct module *this_mod)
1755 int ret;
1757 if (!indio_dev->info)
1758 return -EINVAL;
1760 indio_dev->driver_module = this_mod;
1761 /* If the calling driver did not initialize of_node, do it here */
1762 if (!indio_dev->dev.of_node && indio_dev->dev.parent)
1763 indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
1765 indio_dev->label = of_get_property(indio_dev->dev.of_node, "label",
1766 NULL);
1768 ret = iio_check_unique_scan_index(indio_dev);
1769 if (ret < 0)
1770 return ret;
1772 /* configure elements for the chrdev */
1773 indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), indio_dev->id);
1775 iio_device_register_debugfs(indio_dev);
1777 ret = iio_buffer_alloc_sysfs_and_mask(indio_dev);
1778 if (ret) {
1779 dev_err(indio_dev->dev.parent,
1780 "Failed to create buffer sysfs interfaces\n");
1781 goto error_unreg_debugfs;
1784 ret = iio_device_register_sysfs(indio_dev);
1785 if (ret) {
1786 dev_err(indio_dev->dev.parent,
1787 "Failed to register sysfs interfaces\n");
1788 goto error_buffer_free_sysfs;
1790 ret = iio_device_register_eventset(indio_dev);
1791 if (ret) {
1792 dev_err(indio_dev->dev.parent,
1793 "Failed to register event set\n");
1794 goto error_free_sysfs;
1796 if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1797 iio_device_register_trigger_consumer(indio_dev);
1799 if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1800 indio_dev->setup_ops == NULL)
1801 indio_dev->setup_ops = &noop_ring_setup_ops;
1803 cdev_init(&indio_dev->chrdev, &iio_buffer_fileops);
1805 indio_dev->chrdev.owner = this_mod;
1807 ret = cdev_device_add(&indio_dev->chrdev, &indio_dev->dev);
1808 if (ret < 0)
1809 goto error_unreg_eventset;
1811 return 0;
1813 error_unreg_eventset:
1814 iio_device_unregister_eventset(indio_dev);
1815 error_free_sysfs:
1816 iio_device_unregister_sysfs(indio_dev);
1817 error_buffer_free_sysfs:
1818 iio_buffer_free_sysfs_and_mask(indio_dev);
1819 error_unreg_debugfs:
1820 iio_device_unregister_debugfs(indio_dev);
1821 return ret;
1823 EXPORT_SYMBOL(__iio_device_register);
1826 * iio_device_unregister() - unregister a device from the IIO subsystem
1827 * @indio_dev: Device structure representing the device.
1829 void iio_device_unregister(struct iio_dev *indio_dev)
1831 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1832 struct iio_ioctl_handler *h, *t;
1834 cdev_device_del(&indio_dev->chrdev, &indio_dev->dev);
1836 mutex_lock(&indio_dev->info_exist_lock);
1838 iio_device_unregister_debugfs(indio_dev);
1840 iio_disable_all_buffers(indio_dev);
1842 indio_dev->info = NULL;
1844 list_for_each_entry_safe(h, t, &iio_dev_opaque->ioctl_handlers, entry)
1845 list_del(&h->entry);
1847 iio_device_wakeup_eventset(indio_dev);
1848 iio_buffer_wakeup_poll(indio_dev);
1850 mutex_unlock(&indio_dev->info_exist_lock);
1852 iio_buffer_free_sysfs_and_mask(indio_dev);
1854 EXPORT_SYMBOL(iio_device_unregister);
1856 static void devm_iio_device_unreg(struct device *dev, void *res)
1858 iio_device_unregister(*(struct iio_dev **)res);
1861 int __devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev,
1862 struct module *this_mod)
1864 struct iio_dev **ptr;
1865 int ret;
1867 ptr = devres_alloc(devm_iio_device_unreg, sizeof(*ptr), GFP_KERNEL);
1868 if (!ptr)
1869 return -ENOMEM;
1871 *ptr = indio_dev;
1872 ret = __iio_device_register(indio_dev, this_mod);
1873 if (!ret)
1874 devres_add(dev, ptr);
1875 else
1876 devres_free(ptr);
1878 return ret;
1880 EXPORT_SYMBOL_GPL(__devm_iio_device_register);
1883 * iio_device_claim_direct_mode - Keep device in direct mode
1884 * @indio_dev: the iio_dev associated with the device
1886 * If the device is in direct mode it is guaranteed to stay
1887 * that way until iio_device_release_direct_mode() is called.
1889 * Use with iio_device_release_direct_mode()
1891 * Returns: 0 on success, -EBUSY on failure
1893 int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
1895 mutex_lock(&indio_dev->mlock);
1897 if (iio_buffer_enabled(indio_dev)) {
1898 mutex_unlock(&indio_dev->mlock);
1899 return -EBUSY;
1901 return 0;
1903 EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
1906 * iio_device_release_direct_mode - releases claim on direct mode
1907 * @indio_dev: the iio_dev associated with the device
1909 * Release the claim. Device is no longer guaranteed to stay
1910 * in direct mode.
1912 * Use with iio_device_claim_direct_mode()
1914 void iio_device_release_direct_mode(struct iio_dev *indio_dev)
1916 mutex_unlock(&indio_dev->mlock);
1918 EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
1920 subsys_initcall(iio_init);
1921 module_exit(iio_exit);
1923 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1924 MODULE_DESCRIPTION("Industrial I/O core");
1925 MODULE_LICENSE("GPL");