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.
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>
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>
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 = {
45 EXPORT_SYMBOL(iio_bus_type);
47 static struct dentry *iio_debugfs_dentry;
49 static const char * const iio_direction[] = {
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",
61 [IIO_LIGHT] = "illuminance",
62 [IIO_INTENSITY] = "intensity",
63 [IIO_PROXIMITY] = "proximity",
65 [IIO_INCLI] = "incli",
68 [IIO_TIMESTAMP] = "timestamp",
69 [IIO_CAPACITANCE] = "capacitance",
70 [IIO_ALTVOLTAGE] = "altvoltage",
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",
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[] = {
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)",
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",
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_HYSTERESIS_RELATIVE] = "hysteresis_relative",
161 [IIO_CHAN_INFO_INT_TIME] = "integration_time",
162 [IIO_CHAN_INFO_ENABLE] = "en",
163 [IIO_CHAN_INFO_CALIBHEIGHT] = "calibheight",
164 [IIO_CHAN_INFO_CALIBWEIGHT] = "calibweight",
165 [IIO_CHAN_INFO_DEBOUNCE_COUNT] = "debounce_count",
166 [IIO_CHAN_INFO_DEBOUNCE_TIME] = "debounce_time",
167 [IIO_CHAN_INFO_CALIBEMISSIVITY] = "calibemissivity",
168 [IIO_CHAN_INFO_OVERSAMPLING_RATIO] = "oversampling_ratio",
169 [IIO_CHAN_INFO_THERMOCOUPLE_TYPE] = "thermocouple_type",
170 [IIO_CHAN_INFO_CALIBAMBIENT] = "calibambient",
173 * iio_device_id() - query the unique ID for the device
174 * @indio_dev: Device structure whose ID is being queried
176 * The IIO device ID is a unique index used for example for the naming
177 * of the character device /dev/iio\:device[ID]
179 int iio_device_id(struct iio_dev *indio_dev)
181 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
183 return iio_dev_opaque->id;
185 EXPORT_SYMBOL_GPL(iio_device_id);
188 * iio_buffer_enabled() - helper function to test if the buffer is enabled
189 * @indio_dev: IIO device structure for device
191 bool iio_buffer_enabled(struct iio_dev *indio_dev)
193 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
195 return iio_dev_opaque->currentmode
196 & (INDIO_BUFFER_TRIGGERED | INDIO_BUFFER_HARDWARE |
197 INDIO_BUFFER_SOFTWARE);
199 EXPORT_SYMBOL_GPL(iio_buffer_enabled);
202 * iio_sysfs_match_string_with_gaps - matches given string in an array with gaps
203 * @array: array of strings
204 * @n: number of strings in the array
205 * @str: string to match with
207 * Returns index of @str in the @array or -EINVAL, similar to match_string().
208 * Uses sysfs_streq instead of strcmp for matching.
210 * This routine will look for a string in an array of strings.
211 * The search will continue until the element is found or the n-th element
212 * is reached, regardless of any NULL elements in the array.
214 static int iio_sysfs_match_string_with_gaps(const char * const *array, size_t n,
220 for (index = 0; index < n; index++) {
224 if (sysfs_streq(item, str))
231 #if defined(CONFIG_DEBUG_FS)
233 * There's also a CONFIG_DEBUG_FS guard in include/linux/iio/iio.h for
234 * iio_get_debugfs_dentry() to make it inline if CONFIG_DEBUG_FS is undefined
236 struct dentry *iio_get_debugfs_dentry(struct iio_dev *indio_dev)
238 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
239 return iio_dev_opaque->debugfs_dentry;
241 EXPORT_SYMBOL_GPL(iio_get_debugfs_dentry);
245 * iio_find_channel_from_si() - get channel from its scan index
247 * @si: scan index to match
249 const struct iio_chan_spec
250 *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
254 for (i = 0; i < indio_dev->num_channels; i++)
255 if (indio_dev->channels[i].scan_index == si)
256 return &indio_dev->channels[i];
260 /* This turns up an awful lot */
261 ssize_t iio_read_const_attr(struct device *dev,
262 struct device_attribute *attr,
265 return sysfs_emit(buf, "%s\n", to_iio_const_attr(attr)->string);
267 EXPORT_SYMBOL(iio_read_const_attr);
270 * iio_device_set_clock() - Set current timestamping clock for the device
271 * @indio_dev: IIO device structure containing the device
272 * @clock_id: timestamping clock posix identifier to set.
274 int iio_device_set_clock(struct iio_dev *indio_dev, clockid_t clock_id)
277 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
278 const struct iio_event_interface *ev_int = iio_dev_opaque->event_interface;
280 ret = mutex_lock_interruptible(&indio_dev->mlock);
283 if ((ev_int && iio_event_enabled(ev_int)) ||
284 iio_buffer_enabled(indio_dev)) {
285 mutex_unlock(&indio_dev->mlock);
288 iio_dev_opaque->clock_id = clock_id;
289 mutex_unlock(&indio_dev->mlock);
293 EXPORT_SYMBOL(iio_device_set_clock);
296 * iio_device_get_clock() - Retrieve current timestamping clock for the device
297 * @indio_dev: IIO device structure containing the device
299 clockid_t iio_device_get_clock(const struct iio_dev *indio_dev)
301 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
303 return iio_dev_opaque->clock_id;
305 EXPORT_SYMBOL(iio_device_get_clock);
308 * iio_get_time_ns() - utility function to get a time stamp for events etc
311 s64 iio_get_time_ns(const struct iio_dev *indio_dev)
313 struct timespec64 tp;
315 switch (iio_device_get_clock(indio_dev)) {
317 return ktime_get_real_ns();
318 case CLOCK_MONOTONIC:
319 return ktime_get_ns();
320 case CLOCK_MONOTONIC_RAW:
321 return ktime_get_raw_ns();
322 case CLOCK_REALTIME_COARSE:
323 return ktime_to_ns(ktime_get_coarse_real());
324 case CLOCK_MONOTONIC_COARSE:
325 ktime_get_coarse_ts64(&tp);
326 return timespec64_to_ns(&tp);
328 return ktime_get_boottime_ns();
330 return ktime_get_clocktai_ns();
335 EXPORT_SYMBOL(iio_get_time_ns);
337 static int __init iio_init(void)
341 /* Register sysfs bus */
342 ret = bus_register(&iio_bus_type);
344 pr_err("could not register bus type\n");
348 ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
350 pr_err("failed to allocate char dev region\n");
351 goto error_unregister_bus_type;
354 iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
358 error_unregister_bus_type:
359 bus_unregister(&iio_bus_type);
364 static void __exit iio_exit(void)
367 unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
368 bus_unregister(&iio_bus_type);
369 debugfs_remove(iio_debugfs_dentry);
372 #if defined(CONFIG_DEBUG_FS)
373 static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
374 size_t count, loff_t *ppos)
376 struct iio_dev *indio_dev = file->private_data;
377 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
378 unsigned int val = 0;
382 return simple_read_from_buffer(userbuf, count, ppos,
383 iio_dev_opaque->read_buf,
384 iio_dev_opaque->read_buf_len);
386 ret = indio_dev->info->debugfs_reg_access(indio_dev,
387 iio_dev_opaque->cached_reg_addr,
390 dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
394 iio_dev_opaque->read_buf_len = snprintf(iio_dev_opaque->read_buf,
395 sizeof(iio_dev_opaque->read_buf),
398 return simple_read_from_buffer(userbuf, count, ppos,
399 iio_dev_opaque->read_buf,
400 iio_dev_opaque->read_buf_len);
403 static ssize_t iio_debugfs_write_reg(struct file *file,
404 const char __user *userbuf, size_t count, loff_t *ppos)
406 struct iio_dev *indio_dev = file->private_data;
407 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
408 unsigned int reg, val;
412 count = min_t(size_t, count, (sizeof(buf)-1));
413 if (copy_from_user(buf, userbuf, count))
418 ret = sscanf(buf, "%i %i", ®, &val);
422 iio_dev_opaque->cached_reg_addr = reg;
425 iio_dev_opaque->cached_reg_addr = reg;
426 ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
429 dev_err(indio_dev->dev.parent, "%s: write failed\n",
441 static const struct file_operations iio_debugfs_reg_fops = {
443 .read = iio_debugfs_read_reg,
444 .write = iio_debugfs_write_reg,
447 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
449 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
450 debugfs_remove_recursive(iio_dev_opaque->debugfs_dentry);
453 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
455 struct iio_dev_opaque *iio_dev_opaque;
457 if (indio_dev->info->debugfs_reg_access == NULL)
460 if (!iio_debugfs_dentry)
463 iio_dev_opaque = to_iio_dev_opaque(indio_dev);
465 iio_dev_opaque->debugfs_dentry =
466 debugfs_create_dir(dev_name(&indio_dev->dev),
469 debugfs_create_file("direct_reg_access", 0644,
470 iio_dev_opaque->debugfs_dentry, indio_dev,
471 &iio_debugfs_reg_fops);
474 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
478 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
481 #endif /* CONFIG_DEBUG_FS */
483 static ssize_t iio_read_channel_ext_info(struct device *dev,
484 struct device_attribute *attr,
487 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
488 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
489 const struct iio_chan_spec_ext_info *ext_info;
491 ext_info = &this_attr->c->ext_info[this_attr->address];
493 return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
496 static ssize_t iio_write_channel_ext_info(struct device *dev,
497 struct device_attribute *attr,
501 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
502 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
503 const struct iio_chan_spec_ext_info *ext_info;
505 ext_info = &this_attr->c->ext_info[this_attr->address];
507 return ext_info->write(indio_dev, ext_info->private,
508 this_attr->c, buf, len);
511 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
512 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
514 const struct iio_enum *e = (const struct iio_enum *)priv;
521 for (i = 0; i < e->num_items; ++i) {
524 len += sysfs_emit_at(buf, len, "%s ", e->items[i]);
527 /* replace last space with a newline */
532 EXPORT_SYMBOL_GPL(iio_enum_available_read);
534 ssize_t iio_enum_read(struct iio_dev *indio_dev,
535 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
537 const struct iio_enum *e = (const struct iio_enum *)priv;
543 i = e->get(indio_dev, chan);
546 else if (i >= e->num_items || !e->items[i])
549 return sysfs_emit(buf, "%s\n", e->items[i]);
551 EXPORT_SYMBOL_GPL(iio_enum_read);
553 ssize_t iio_enum_write(struct iio_dev *indio_dev,
554 uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
557 const struct iio_enum *e = (const struct iio_enum *)priv;
563 ret = iio_sysfs_match_string_with_gaps(e->items, e->num_items, buf);
567 ret = e->set(indio_dev, chan, ret);
568 return ret ? ret : len;
570 EXPORT_SYMBOL_GPL(iio_enum_write);
572 static const struct iio_mount_matrix iio_mount_idmatrix = {
580 static int iio_setup_mount_idmatrix(const struct device *dev,
581 struct iio_mount_matrix *matrix)
583 *matrix = iio_mount_idmatrix;
584 dev_info(dev, "mounting matrix not found: using identity...\n");
588 ssize_t iio_show_mount_matrix(struct iio_dev *indio_dev, uintptr_t priv,
589 const struct iio_chan_spec *chan, char *buf)
591 const struct iio_mount_matrix *mtx = ((iio_get_mount_matrix_t *)
592 priv)(indio_dev, chan);
598 mtx = &iio_mount_idmatrix;
600 return sysfs_emit(buf, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
601 mtx->rotation[0], mtx->rotation[1], mtx->rotation[2],
602 mtx->rotation[3], mtx->rotation[4], mtx->rotation[5],
603 mtx->rotation[6], mtx->rotation[7], mtx->rotation[8]);
605 EXPORT_SYMBOL_GPL(iio_show_mount_matrix);
608 * iio_read_mount_matrix() - retrieve iio device mounting matrix from
609 * device "mount-matrix" property
610 * @dev: device the mounting matrix property is assigned to
611 * @matrix: where to store retrieved matrix
613 * If device is assigned no mounting matrix property, a default 3x3 identity
614 * matrix will be filled in.
616 * Return: 0 if success, or a negative error code on failure.
618 int iio_read_mount_matrix(struct device *dev, struct iio_mount_matrix *matrix)
620 size_t len = ARRAY_SIZE(iio_mount_idmatrix.rotation);
623 err = device_property_read_string_array(dev, "mount-matrix", matrix->rotation, len);
628 /* Invalid number of matrix entries. */
632 /* Invalid matrix declaration format. */
635 /* Matrix was not declared at all: fallback to identity. */
636 return iio_setup_mount_idmatrix(dev, matrix);
638 EXPORT_SYMBOL(iio_read_mount_matrix);
640 static ssize_t __iio_format_value(char *buf, size_t offset, unsigned int type,
641 int size, const int *vals)
645 bool scale_db = false;
649 return sysfs_emit_at(buf, offset, "%d", vals[0]);
650 case IIO_VAL_INT_PLUS_MICRO_DB:
653 case IIO_VAL_INT_PLUS_MICRO:
655 return sysfs_emit_at(buf, offset, "-%d.%06u%s",
656 abs(vals[0]), -vals[1],
657 scale_db ? " dB" : "");
659 return sysfs_emit_at(buf, offset, "%d.%06u%s", vals[0],
660 vals[1], scale_db ? " dB" : "");
661 case IIO_VAL_INT_PLUS_NANO:
663 return sysfs_emit_at(buf, offset, "-%d.%09u",
664 abs(vals[0]), -vals[1]);
666 return sysfs_emit_at(buf, offset, "%d.%09u", vals[0],
668 case IIO_VAL_FRACTIONAL:
669 tmp2 = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
671 tmp0 = (int)div_s64_rem(tmp2, 1000000000, &tmp1);
672 if ((tmp2 < 0) && (tmp0 == 0))
673 return sysfs_emit_at(buf, offset, "-0.%09u", abs(tmp1));
675 return sysfs_emit_at(buf, offset, "%d.%09u", tmp0,
677 case IIO_VAL_FRACTIONAL_LOG2:
678 tmp2 = shift_right((s64)vals[0] * 1000000000LL, vals[1]);
679 tmp0 = (int)div_s64_rem(tmp2, 1000000000LL, &tmp1);
680 if (tmp0 == 0 && tmp2 < 0)
681 return sysfs_emit_at(buf, offset, "-0.%09u", abs(tmp1));
683 return sysfs_emit_at(buf, offset, "%d.%09u", tmp0,
685 case IIO_VAL_INT_MULTIPLE:
690 for (i = 0; i < size; ++i)
691 l += sysfs_emit_at(buf, offset + l, "%d ", vals[i]);
695 return sysfs_emit_at(buf, offset, "%c", (char)vals[0]);
697 tmp2 = (s64)((((u64)vals[1]) << 32) | (u32)vals[0]);
698 return sysfs_emit_at(buf, offset, "%lld", tmp2);
705 * iio_format_value() - Formats a IIO value into its string representation
706 * @buf: The buffer to which the formatted value gets written
707 * which is assumed to be big enough (i.e. PAGE_SIZE).
708 * @type: One of the IIO_VAL_* constants. This decides how the val
709 * and val2 parameters are formatted.
710 * @size: Number of IIO value entries contained in vals
711 * @vals: Pointer to the values, exact meaning depends on the
714 * Return: 0 by default, a negative number on failure or the
715 * total number of characters written for a type that belongs
716 * to the IIO_VAL_* constant.
718 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
722 len = __iio_format_value(buf, 0, type, size, vals);
723 if (len >= PAGE_SIZE - 1)
726 return len + sysfs_emit_at(buf, len, "\n");
728 EXPORT_SYMBOL_GPL(iio_format_value);
730 static ssize_t iio_read_channel_label(struct device *dev,
731 struct device_attribute *attr,
734 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
735 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
737 if (indio_dev->info->read_label)
738 return indio_dev->info->read_label(indio_dev, this_attr->c, buf);
740 if (this_attr->c->extend_name)
741 return sysfs_emit(buf, "%s\n", this_attr->c->extend_name);
746 static ssize_t iio_read_channel_info(struct device *dev,
747 struct device_attribute *attr,
750 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
751 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
752 int vals[INDIO_MAX_RAW_ELEMENTS];
756 if (indio_dev->info->read_raw_multi)
757 ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
758 INDIO_MAX_RAW_ELEMENTS,
762 ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
763 &vals[0], &vals[1], this_attr->address);
768 return iio_format_value(buf, ret, val_len, vals);
771 static ssize_t iio_format_list(char *buf, const int *vals, int type, int length,
772 const char *prefix, const char *suffix)
787 len = sysfs_emit(buf, prefix);
789 for (i = 0; i <= length - stride; i += stride) {
791 len += sysfs_emit_at(buf, len, " ");
792 if (len >= PAGE_SIZE)
796 len += __iio_format_value(buf, len, type, stride, &vals[i]);
797 if (len >= PAGE_SIZE)
801 len += sysfs_emit_at(buf, len, "%s\n", suffix);
806 static ssize_t iio_format_avail_list(char *buf, const int *vals,
807 int type, int length)
810 return iio_format_list(buf, vals, type, length, "", "");
813 static ssize_t iio_format_avail_range(char *buf, const int *vals, int type)
818 * length refers to the array size , not the number of elements.
819 * The purpose is to print the range [min , step ,max] so length should
820 * be 3 in case of int, and 6 for other types.
831 return iio_format_list(buf, vals, type, length, "[", "]");
834 static ssize_t iio_read_channel_info_avail(struct device *dev,
835 struct device_attribute *attr,
838 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
839 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
845 ret = indio_dev->info->read_avail(indio_dev, this_attr->c,
846 &vals, &type, &length,
853 return iio_format_avail_list(buf, vals, type, length);
854 case IIO_AVAIL_RANGE:
855 return iio_format_avail_range(buf, vals, type);
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
867 * @scale_db: True if this should parse as dB
869 * Returns 0 on success, or a negative error code if the string could not be
872 static int __iio_str_to_fixpoint(const char *str, int fract_mult,
873 int *integer, int *fract, bool scale_db)
876 bool integer_part = true, negative = false;
878 if (fract_mult == 0) {
881 return kstrtoint(str, 0, integer);
887 } else if (str[0] == '+') {
892 if ('0' <= *str && *str <= '9') {
894 i = i * 10 + *str - '0';
896 f += fract_mult * (*str - '0');
899 } else if (*str == '\n') {
900 if (*(str + 1) == '\0')
903 } else if (!strncmp(str, " dB", sizeof(" dB") - 1) && scale_db) {
904 /* Ignore the dB suffix */
905 str += sizeof(" dB") - 1;
907 } else if (!strncmp(str, "dB", sizeof("dB") - 1) && scale_db) {
908 /* Ignore the dB suffix */
909 str += sizeof("dB") - 1;
911 } else if (*str == '.' && integer_part) {
912 integer_part = false;
933 * iio_str_to_fixpoint() - Parse a fixed-point number from a string
934 * @str: The string to parse
935 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
936 * @integer: The integer part of the number
937 * @fract: The fractional part of the number
939 * Returns 0 on success, or a negative error code if the string could not be
942 int iio_str_to_fixpoint(const char *str, int fract_mult,
943 int *integer, int *fract)
945 return __iio_str_to_fixpoint(str, fract_mult, integer, fract, false);
947 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
949 static ssize_t iio_write_channel_info(struct device *dev,
950 struct device_attribute *attr,
954 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
955 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
956 int ret, fract_mult = 100000;
957 int integer, fract = 0;
958 bool is_char = false;
959 bool scale_db = false;
961 /* Assumes decimal - precision based on number of digits */
962 if (!indio_dev->info->write_raw)
965 if (indio_dev->info->write_raw_get_fmt)
966 switch (indio_dev->info->write_raw_get_fmt(indio_dev,
967 this_attr->c, this_attr->address)) {
971 case IIO_VAL_INT_PLUS_MICRO_DB:
974 case IIO_VAL_INT_PLUS_MICRO:
977 case IIO_VAL_INT_PLUS_NANO:
978 fract_mult = 100000000;
990 if (sscanf(buf, "%c", &ch) != 1)
994 ret = __iio_str_to_fixpoint(buf, fract_mult, &integer, &fract,
1000 ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
1001 integer, fract, this_attr->address);
1009 int __iio_device_attr_init(struct device_attribute *dev_attr,
1010 const char *postfix,
1011 struct iio_chan_spec const *chan,
1012 ssize_t (*readfunc)(struct device *dev,
1013 struct device_attribute *attr,
1015 ssize_t (*writefunc)(struct device *dev,
1016 struct device_attribute *attr,
1019 enum iio_shared_by shared_by)
1024 sysfs_attr_init(&dev_attr->attr);
1026 /* Build up postfix of <extend_name>_<modifier>_postfix */
1027 if (chan->modified && (shared_by == IIO_SEPARATE)) {
1028 if (chan->extend_name)
1029 full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
1030 iio_modifier_names[chan
1035 full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
1036 iio_modifier_names[chan
1040 if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
1041 full_postfix = kstrdup(postfix, GFP_KERNEL);
1043 full_postfix = kasprintf(GFP_KERNEL,
1048 if (full_postfix == NULL)
1051 if (chan->differential) { /* Differential can not have modifier */
1052 switch (shared_by) {
1053 case IIO_SHARED_BY_ALL:
1054 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1056 case IIO_SHARED_BY_DIR:
1057 name = kasprintf(GFP_KERNEL, "%s_%s",
1058 iio_direction[chan->output],
1061 case IIO_SHARED_BY_TYPE:
1062 name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
1063 iio_direction[chan->output],
1064 iio_chan_type_name_spec[chan->type],
1065 iio_chan_type_name_spec[chan->type],
1069 if (!chan->indexed) {
1070 WARN(1, "Differential channels must be indexed\n");
1072 goto error_free_full_postfix;
1074 name = kasprintf(GFP_KERNEL,
1076 iio_direction[chan->output],
1077 iio_chan_type_name_spec[chan->type],
1079 iio_chan_type_name_spec[chan->type],
1084 } else { /* Single ended */
1085 switch (shared_by) {
1086 case IIO_SHARED_BY_ALL:
1087 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1089 case IIO_SHARED_BY_DIR:
1090 name = kasprintf(GFP_KERNEL, "%s_%s",
1091 iio_direction[chan->output],
1094 case IIO_SHARED_BY_TYPE:
1095 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1096 iio_direction[chan->output],
1097 iio_chan_type_name_spec[chan->type],
1103 name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
1104 iio_direction[chan->output],
1105 iio_chan_type_name_spec[chan->type],
1109 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1110 iio_direction[chan->output],
1111 iio_chan_type_name_spec[chan->type],
1118 goto error_free_full_postfix;
1120 dev_attr->attr.name = name;
1123 dev_attr->attr.mode |= 0444;
1124 dev_attr->show = readfunc;
1128 dev_attr->attr.mode |= 0200;
1129 dev_attr->store = writefunc;
1132 error_free_full_postfix:
1133 kfree(full_postfix);
1138 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
1140 kfree(dev_attr->attr.name);
1143 int __iio_add_chan_devattr(const char *postfix,
1144 struct iio_chan_spec const *chan,
1145 ssize_t (*readfunc)(struct device *dev,
1146 struct device_attribute *attr,
1148 ssize_t (*writefunc)(struct device *dev,
1149 struct device_attribute *attr,
1153 enum iio_shared_by shared_by,
1155 struct iio_buffer *buffer,
1156 struct list_head *attr_list)
1159 struct iio_dev_attr *iio_attr, *t;
1161 iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
1162 if (iio_attr == NULL)
1164 ret = __iio_device_attr_init(&iio_attr->dev_attr,
1166 readfunc, writefunc, shared_by);
1168 goto error_iio_dev_attr_free;
1170 iio_attr->address = mask;
1171 iio_attr->buffer = buffer;
1172 list_for_each_entry(t, attr_list, l)
1173 if (strcmp(t->dev_attr.attr.name,
1174 iio_attr->dev_attr.attr.name) == 0) {
1175 if (shared_by == IIO_SEPARATE)
1176 dev_err(dev, "tried to double register : %s\n",
1177 t->dev_attr.attr.name);
1179 goto error_device_attr_deinit;
1181 list_add(&iio_attr->l, attr_list);
1185 error_device_attr_deinit:
1186 __iio_device_attr_deinit(&iio_attr->dev_attr);
1187 error_iio_dev_attr_free:
1192 static int iio_device_add_channel_label(struct iio_dev *indio_dev,
1193 struct iio_chan_spec const *chan)
1195 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1198 if (!indio_dev->info->read_label && !chan->extend_name)
1201 ret = __iio_add_chan_devattr("label",
1203 &iio_read_channel_label,
1209 &iio_dev_opaque->channel_attr_list);
1216 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
1217 struct iio_chan_spec const *chan,
1218 enum iio_shared_by shared_by,
1219 const long *infomask)
1221 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1222 int i, ret, attrcount = 0;
1224 for_each_set_bit(i, infomask, sizeof(*infomask)*8) {
1225 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1227 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
1229 &iio_read_channel_info,
1230 &iio_write_channel_info,
1235 &iio_dev_opaque->channel_attr_list);
1236 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1246 static int iio_device_add_info_mask_type_avail(struct iio_dev *indio_dev,
1247 struct iio_chan_spec const *chan,
1248 enum iio_shared_by shared_by,
1249 const long *infomask)
1251 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1252 int i, ret, attrcount = 0;
1253 char *avail_postfix;
1255 for_each_set_bit(i, infomask, sizeof(*infomask) * 8) {
1256 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1258 avail_postfix = kasprintf(GFP_KERNEL,
1260 iio_chan_info_postfix[i]);
1264 ret = __iio_add_chan_devattr(avail_postfix,
1266 &iio_read_channel_info_avail,
1272 &iio_dev_opaque->channel_attr_list);
1273 kfree(avail_postfix);
1274 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1284 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
1285 struct iio_chan_spec const *chan)
1287 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1288 int ret, attrcount = 0;
1289 const struct iio_chan_spec_ext_info *ext_info;
1291 if (chan->channel < 0)
1293 ret = iio_device_add_info_mask_type(indio_dev, chan,
1295 &chan->info_mask_separate);
1300 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1303 info_mask_separate_available);
1308 ret = iio_device_add_info_mask_type(indio_dev, chan,
1310 &chan->info_mask_shared_by_type);
1315 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1318 info_mask_shared_by_type_available);
1323 ret = iio_device_add_info_mask_type(indio_dev, chan,
1325 &chan->info_mask_shared_by_dir);
1330 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1332 &chan->info_mask_shared_by_dir_available);
1337 ret = iio_device_add_info_mask_type(indio_dev, chan,
1339 &chan->info_mask_shared_by_all);
1344 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1346 &chan->info_mask_shared_by_all_available);
1351 ret = iio_device_add_channel_label(indio_dev, chan);
1356 if (chan->ext_info) {
1358 for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
1359 ret = __iio_add_chan_devattr(ext_info->name,
1362 &iio_read_channel_ext_info : NULL,
1364 &iio_write_channel_ext_info : NULL,
1369 &iio_dev_opaque->channel_attr_list);
1371 if (ret == -EBUSY && ext_info->shared)
1385 * iio_free_chan_devattr_list() - Free a list of IIO device attributes
1386 * @attr_list: List of IIO device attributes
1388 * This function frees the memory allocated for each of the IIO device
1389 * attributes in the list.
1391 void iio_free_chan_devattr_list(struct list_head *attr_list)
1393 struct iio_dev_attr *p, *n;
1395 list_for_each_entry_safe(p, n, attr_list, l) {
1396 kfree_const(p->dev_attr.attr.name);
1402 static ssize_t name_show(struct device *dev, struct device_attribute *attr,
1405 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1406 return sysfs_emit(buf, "%s\n", indio_dev->name);
1409 static DEVICE_ATTR_RO(name);
1411 static ssize_t label_show(struct device *dev, struct device_attribute *attr,
1414 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1415 return sysfs_emit(buf, "%s\n", indio_dev->label);
1418 static DEVICE_ATTR_RO(label);
1420 static ssize_t current_timestamp_clock_show(struct device *dev,
1421 struct device_attribute *attr,
1424 const struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1425 const clockid_t clk = iio_device_get_clock(indio_dev);
1430 case CLOCK_REALTIME:
1431 name = "realtime\n";
1432 sz = sizeof("realtime\n");
1434 case CLOCK_MONOTONIC:
1435 name = "monotonic\n";
1436 sz = sizeof("monotonic\n");
1438 case CLOCK_MONOTONIC_RAW:
1439 name = "monotonic_raw\n";
1440 sz = sizeof("monotonic_raw\n");
1442 case CLOCK_REALTIME_COARSE:
1443 name = "realtime_coarse\n";
1444 sz = sizeof("realtime_coarse\n");
1446 case CLOCK_MONOTONIC_COARSE:
1447 name = "monotonic_coarse\n";
1448 sz = sizeof("monotonic_coarse\n");
1450 case CLOCK_BOOTTIME:
1451 name = "boottime\n";
1452 sz = sizeof("boottime\n");
1456 sz = sizeof("tai\n");
1462 memcpy(buf, name, sz);
1466 static ssize_t current_timestamp_clock_store(struct device *dev,
1467 struct device_attribute *attr,
1468 const char *buf, size_t len)
1473 if (sysfs_streq(buf, "realtime"))
1474 clk = CLOCK_REALTIME;
1475 else if (sysfs_streq(buf, "monotonic"))
1476 clk = CLOCK_MONOTONIC;
1477 else if (sysfs_streq(buf, "monotonic_raw"))
1478 clk = CLOCK_MONOTONIC_RAW;
1479 else if (sysfs_streq(buf, "realtime_coarse"))
1480 clk = CLOCK_REALTIME_COARSE;
1481 else if (sysfs_streq(buf, "monotonic_coarse"))
1482 clk = CLOCK_MONOTONIC_COARSE;
1483 else if (sysfs_streq(buf, "boottime"))
1484 clk = CLOCK_BOOTTIME;
1485 else if (sysfs_streq(buf, "tai"))
1490 ret = iio_device_set_clock(dev_to_iio_dev(dev), clk);
1497 int iio_device_register_sysfs_group(struct iio_dev *indio_dev,
1498 const struct attribute_group *group)
1500 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1501 const struct attribute_group **new, **old = iio_dev_opaque->groups;
1502 unsigned int cnt = iio_dev_opaque->groupcounter;
1504 new = krealloc(old, sizeof(*new) * (cnt + 2), GFP_KERNEL);
1508 new[iio_dev_opaque->groupcounter++] = group;
1509 new[iio_dev_opaque->groupcounter] = NULL;
1511 iio_dev_opaque->groups = new;
1516 static DEVICE_ATTR_RW(current_timestamp_clock);
1518 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
1520 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1521 int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
1522 struct iio_dev_attr *p;
1523 struct attribute **attr, *clk = NULL;
1525 /* First count elements in any existing group */
1526 if (indio_dev->info->attrs) {
1527 attr = indio_dev->info->attrs->attrs;
1528 while (*attr++ != NULL)
1531 attrcount = attrcount_orig;
1533 * New channel registration method - relies on the fact a group does
1534 * not need to be initialized if its name is NULL.
1536 if (indio_dev->channels)
1537 for (i = 0; i < indio_dev->num_channels; i++) {
1538 const struct iio_chan_spec *chan =
1539 &indio_dev->channels[i];
1541 if (chan->type == IIO_TIMESTAMP)
1542 clk = &dev_attr_current_timestamp_clock.attr;
1544 ret = iio_device_add_channel_sysfs(indio_dev, chan);
1546 goto error_clear_attrs;
1550 if (iio_dev_opaque->event_interface)
1551 clk = &dev_attr_current_timestamp_clock.attr;
1553 if (indio_dev->name)
1555 if (indio_dev->label)
1560 iio_dev_opaque->chan_attr_group.attrs =
1561 kcalloc(attrcount + 1,
1562 sizeof(iio_dev_opaque->chan_attr_group.attrs[0]),
1564 if (iio_dev_opaque->chan_attr_group.attrs == NULL) {
1566 goto error_clear_attrs;
1568 /* Copy across original attributes */
1569 if (indio_dev->info->attrs) {
1570 memcpy(iio_dev_opaque->chan_attr_group.attrs,
1571 indio_dev->info->attrs->attrs,
1572 sizeof(iio_dev_opaque->chan_attr_group.attrs[0])
1574 iio_dev_opaque->chan_attr_group.is_visible =
1575 indio_dev->info->attrs->is_visible;
1577 attrn = attrcount_orig;
1578 /* Add all elements from the list. */
1579 list_for_each_entry(p, &iio_dev_opaque->channel_attr_list, l)
1580 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1581 if (indio_dev->name)
1582 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
1583 if (indio_dev->label)
1584 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_label.attr;
1586 iio_dev_opaque->chan_attr_group.attrs[attrn++] = clk;
1588 ret = iio_device_register_sysfs_group(indio_dev,
1589 &iio_dev_opaque->chan_attr_group);
1591 goto error_clear_attrs;
1596 iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1601 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
1603 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1605 iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1606 kfree(iio_dev_opaque->chan_attr_group.attrs);
1607 iio_dev_opaque->chan_attr_group.attrs = NULL;
1608 kfree(iio_dev_opaque->groups);
1609 iio_dev_opaque->groups = NULL;
1612 static void iio_dev_release(struct device *device)
1614 struct iio_dev *indio_dev = dev_to_iio_dev(device);
1615 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1617 if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1618 iio_device_unregister_trigger_consumer(indio_dev);
1619 iio_device_unregister_eventset(indio_dev);
1620 iio_device_unregister_sysfs(indio_dev);
1622 iio_device_detach_buffers(indio_dev);
1624 ida_free(&iio_ida, iio_dev_opaque->id);
1625 kfree(iio_dev_opaque);
1628 const struct device_type iio_device_type = {
1629 .name = "iio_device",
1630 .release = iio_dev_release,
1634 * iio_device_alloc() - allocate an iio_dev from a driver
1635 * @parent: Parent device.
1636 * @sizeof_priv: Space to allocate for private structure.
1638 struct iio_dev *iio_device_alloc(struct device *parent, int sizeof_priv)
1640 struct iio_dev_opaque *iio_dev_opaque;
1641 struct iio_dev *indio_dev;
1644 alloc_size = sizeof(struct iio_dev_opaque);
1646 alloc_size = ALIGN(alloc_size, IIO_DMA_MINALIGN);
1647 alloc_size += sizeof_priv;
1650 iio_dev_opaque = kzalloc(alloc_size, GFP_KERNEL);
1651 if (!iio_dev_opaque)
1654 indio_dev = &iio_dev_opaque->indio_dev;
1655 indio_dev->priv = (char *)iio_dev_opaque +
1656 ALIGN(sizeof(struct iio_dev_opaque), IIO_DMA_MINALIGN);
1658 indio_dev->dev.parent = parent;
1659 indio_dev->dev.type = &iio_device_type;
1660 indio_dev->dev.bus = &iio_bus_type;
1661 device_initialize(&indio_dev->dev);
1662 mutex_init(&indio_dev->mlock);
1663 mutex_init(&iio_dev_opaque->info_exist_lock);
1664 INIT_LIST_HEAD(&iio_dev_opaque->channel_attr_list);
1666 iio_dev_opaque->id = ida_alloc(&iio_ida, GFP_KERNEL);
1667 if (iio_dev_opaque->id < 0) {
1668 /* cannot use a dev_err as the name isn't available */
1669 pr_err("failed to get device id\n");
1670 kfree(iio_dev_opaque);
1674 if (dev_set_name(&indio_dev->dev, "iio:device%d", iio_dev_opaque->id)) {
1675 ida_free(&iio_ida, iio_dev_opaque->id);
1676 kfree(iio_dev_opaque);
1680 INIT_LIST_HEAD(&iio_dev_opaque->buffer_list);
1681 INIT_LIST_HEAD(&iio_dev_opaque->ioctl_handlers);
1685 EXPORT_SYMBOL(iio_device_alloc);
1688 * iio_device_free() - free an iio_dev from a driver
1689 * @dev: the iio_dev associated with the device
1691 void iio_device_free(struct iio_dev *dev)
1694 put_device(&dev->dev);
1696 EXPORT_SYMBOL(iio_device_free);
1698 static void devm_iio_device_release(void *iio_dev)
1700 iio_device_free(iio_dev);
1704 * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1705 * @parent: Device to allocate iio_dev for, and parent for this IIO device
1706 * @sizeof_priv: Space to allocate for private structure.
1708 * Managed iio_device_alloc. iio_dev allocated with this function is
1709 * automatically freed on driver detach.
1712 * Pointer to allocated iio_dev on success, NULL on failure.
1714 struct iio_dev *devm_iio_device_alloc(struct device *parent, int sizeof_priv)
1716 struct iio_dev *iio_dev;
1719 iio_dev = iio_device_alloc(parent, sizeof_priv);
1723 ret = devm_add_action_or_reset(parent, devm_iio_device_release,
1730 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1733 * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1734 * @inode: Inode structure for identifying the device in the file system
1735 * @filp: File structure for iio device used to keep and later access
1738 * Return: 0 on success or -EBUSY if the device is already opened
1740 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1742 struct iio_dev_opaque *iio_dev_opaque =
1743 container_of(inode->i_cdev, struct iio_dev_opaque, chrdev);
1744 struct iio_dev *indio_dev = &iio_dev_opaque->indio_dev;
1745 struct iio_dev_buffer_pair *ib;
1747 if (test_and_set_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags))
1750 iio_device_get(indio_dev);
1752 ib = kmalloc(sizeof(*ib), GFP_KERNEL);
1754 iio_device_put(indio_dev);
1755 clear_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags);
1759 ib->indio_dev = indio_dev;
1760 ib->buffer = indio_dev->buffer;
1762 filp->private_data = ib;
1768 * iio_chrdev_release() - chrdev file close buffer access and ioctls
1769 * @inode: Inode structure pointer for the char device
1770 * @filp: File structure pointer for the char device
1772 * Return: 0 for successful release
1774 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1776 struct iio_dev_buffer_pair *ib = filp->private_data;
1777 struct iio_dev_opaque *iio_dev_opaque =
1778 container_of(inode->i_cdev, struct iio_dev_opaque, chrdev);
1779 struct iio_dev *indio_dev = &iio_dev_opaque->indio_dev;
1781 clear_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags);
1782 iio_device_put(indio_dev);
1787 void iio_device_ioctl_handler_register(struct iio_dev *indio_dev,
1788 struct iio_ioctl_handler *h)
1790 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1792 list_add_tail(&h->entry, &iio_dev_opaque->ioctl_handlers);
1795 void iio_device_ioctl_handler_unregister(struct iio_ioctl_handler *h)
1797 list_del(&h->entry);
1800 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1802 struct iio_dev_buffer_pair *ib = filp->private_data;
1803 struct iio_dev *indio_dev = ib->indio_dev;
1804 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1805 struct iio_ioctl_handler *h;
1808 mutex_lock(&iio_dev_opaque->info_exist_lock);
1811 * The NULL check here is required to prevent crashing when a device
1812 * is being removed while userspace would still have open file handles
1813 * to try to access this device.
1815 if (!indio_dev->info)
1818 list_for_each_entry(h, &iio_dev_opaque->ioctl_handlers, entry) {
1819 ret = h->ioctl(indio_dev, filp, cmd, arg);
1820 if (ret != IIO_IOCTL_UNHANDLED)
1824 if (ret == IIO_IOCTL_UNHANDLED)
1828 mutex_unlock(&iio_dev_opaque->info_exist_lock);
1833 static const struct file_operations iio_buffer_fileops = {
1834 .owner = THIS_MODULE,
1835 .llseek = noop_llseek,
1836 .read = iio_buffer_read_outer_addr,
1837 .write = iio_buffer_write_outer_addr,
1838 .poll = iio_buffer_poll_addr,
1839 .unlocked_ioctl = iio_ioctl,
1840 .compat_ioctl = compat_ptr_ioctl,
1841 .open = iio_chrdev_open,
1842 .release = iio_chrdev_release,
1845 static const struct file_operations iio_event_fileops = {
1846 .owner = THIS_MODULE,
1847 .llseek = noop_llseek,
1848 .unlocked_ioctl = iio_ioctl,
1849 .compat_ioctl = compat_ptr_ioctl,
1850 .open = iio_chrdev_open,
1851 .release = iio_chrdev_release,
1854 static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1857 const struct iio_chan_spec *channels = indio_dev->channels;
1859 if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1862 for (i = 0; i < indio_dev->num_channels - 1; i++) {
1863 if (channels[i].scan_index < 0)
1865 for (j = i + 1; j < indio_dev->num_channels; j++)
1866 if (channels[i].scan_index == channels[j].scan_index) {
1867 dev_err(&indio_dev->dev,
1868 "Duplicate scan index %d\n",
1869 channels[i].scan_index);
1877 static int iio_check_extended_name(const struct iio_dev *indio_dev)
1881 if (!indio_dev->info->read_label)
1884 for (i = 0; i < indio_dev->num_channels; i++) {
1885 if (indio_dev->channels[i].extend_name) {
1886 dev_err(&indio_dev->dev,
1887 "Cannot use labels and extend_name at the same time\n");
1895 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1897 int __iio_device_register(struct iio_dev *indio_dev, struct module *this_mod)
1899 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1900 struct fwnode_handle *fwnode;
1903 if (!indio_dev->info)
1906 iio_dev_opaque->driver_module = this_mod;
1908 /* If the calling driver did not initialize firmware node, do it here */
1909 if (dev_fwnode(&indio_dev->dev))
1910 fwnode = dev_fwnode(&indio_dev->dev);
1912 fwnode = dev_fwnode(indio_dev->dev.parent);
1913 device_set_node(&indio_dev->dev, fwnode);
1915 fwnode_property_read_string(fwnode, "label", &indio_dev->label);
1917 ret = iio_check_unique_scan_index(indio_dev);
1921 ret = iio_check_extended_name(indio_dev);
1925 iio_device_register_debugfs(indio_dev);
1927 ret = iio_buffers_alloc_sysfs_and_mask(indio_dev);
1929 dev_err(indio_dev->dev.parent,
1930 "Failed to create buffer sysfs interfaces\n");
1931 goto error_unreg_debugfs;
1934 ret = iio_device_register_sysfs(indio_dev);
1936 dev_err(indio_dev->dev.parent,
1937 "Failed to register sysfs interfaces\n");
1938 goto error_buffer_free_sysfs;
1940 ret = iio_device_register_eventset(indio_dev);
1942 dev_err(indio_dev->dev.parent,
1943 "Failed to register event set\n");
1944 goto error_free_sysfs;
1946 if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1947 iio_device_register_trigger_consumer(indio_dev);
1949 if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1950 indio_dev->setup_ops == NULL)
1951 indio_dev->setup_ops = &noop_ring_setup_ops;
1953 if (iio_dev_opaque->attached_buffers_cnt)
1954 cdev_init(&iio_dev_opaque->chrdev, &iio_buffer_fileops);
1955 else if (iio_dev_opaque->event_interface)
1956 cdev_init(&iio_dev_opaque->chrdev, &iio_event_fileops);
1958 if (iio_dev_opaque->attached_buffers_cnt || iio_dev_opaque->event_interface) {
1959 indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), iio_dev_opaque->id);
1960 iio_dev_opaque->chrdev.owner = this_mod;
1963 /* assign device groups now; they should be all registered now */
1964 indio_dev->dev.groups = iio_dev_opaque->groups;
1966 ret = cdev_device_add(&iio_dev_opaque->chrdev, &indio_dev->dev);
1968 goto error_unreg_eventset;
1972 error_unreg_eventset:
1973 iio_device_unregister_eventset(indio_dev);
1975 iio_device_unregister_sysfs(indio_dev);
1976 error_buffer_free_sysfs:
1977 iio_buffers_free_sysfs_and_mask(indio_dev);
1978 error_unreg_debugfs:
1979 iio_device_unregister_debugfs(indio_dev);
1982 EXPORT_SYMBOL(__iio_device_register);
1985 * iio_device_unregister() - unregister a device from the IIO subsystem
1986 * @indio_dev: Device structure representing the device.
1988 void iio_device_unregister(struct iio_dev *indio_dev)
1990 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1992 cdev_device_del(&iio_dev_opaque->chrdev, &indio_dev->dev);
1994 mutex_lock(&iio_dev_opaque->info_exist_lock);
1996 iio_device_unregister_debugfs(indio_dev);
1998 iio_disable_all_buffers(indio_dev);
2000 indio_dev->info = NULL;
2002 iio_device_wakeup_eventset(indio_dev);
2003 iio_buffer_wakeup_poll(indio_dev);
2005 mutex_unlock(&iio_dev_opaque->info_exist_lock);
2007 iio_buffers_free_sysfs_and_mask(indio_dev);
2009 EXPORT_SYMBOL(iio_device_unregister);
2011 static void devm_iio_device_unreg(void *indio_dev)
2013 iio_device_unregister(indio_dev);
2016 int __devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev,
2017 struct module *this_mod)
2021 ret = __iio_device_register(indio_dev, this_mod);
2025 return devm_add_action_or_reset(dev, devm_iio_device_unreg, indio_dev);
2027 EXPORT_SYMBOL_GPL(__devm_iio_device_register);
2030 * iio_device_claim_direct_mode - Keep device in direct mode
2031 * @indio_dev: the iio_dev associated with the device
2033 * If the device is in direct mode it is guaranteed to stay
2034 * that way until iio_device_release_direct_mode() is called.
2036 * Use with iio_device_release_direct_mode()
2038 * Returns: 0 on success, -EBUSY on failure
2040 int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
2042 mutex_lock(&indio_dev->mlock);
2044 if (iio_buffer_enabled(indio_dev)) {
2045 mutex_unlock(&indio_dev->mlock);
2050 EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
2053 * iio_device_release_direct_mode - releases claim on direct mode
2054 * @indio_dev: the iio_dev associated with the device
2056 * Release the claim. Device is no longer guaranteed to stay
2059 * Use with iio_device_claim_direct_mode()
2061 void iio_device_release_direct_mode(struct iio_dev *indio_dev)
2063 mutex_unlock(&indio_dev->mlock);
2065 EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
2068 * iio_device_get_current_mode() - helper function providing read-only access to
2069 * the opaque @currentmode variable
2070 * @indio_dev: IIO device structure for device
2072 int iio_device_get_current_mode(struct iio_dev *indio_dev)
2074 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2076 return iio_dev_opaque->currentmode;
2078 EXPORT_SYMBOL_GPL(iio_device_get_current_mode);
2080 subsys_initcall(iio_init);
2081 module_exit(iio_exit);
2083 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
2084 MODULE_DESCRIPTION("Industrial I/O core");
2085 MODULE_LICENSE("GPL");