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_sysfs_match_string_with_gaps - matches given string in an array with gaps
189 * @array: array of strings
190 * @n: number of strings in the array
191 * @str: string to match with
193 * Returns index of @str in the @array or -EINVAL, similar to match_string().
194 * Uses sysfs_streq instead of strcmp for matching.
196 * This routine will look for a string in an array of strings.
197 * The search will continue until the element is found or the n-th element
198 * is reached, regardless of any NULL elements in the array.
200 static int iio_sysfs_match_string_with_gaps(const char * const *array, size_t n,
206 for (index = 0; index < n; index++) {
210 if (sysfs_streq(item, str))
217 #if defined(CONFIG_DEBUG_FS)
219 * There's also a CONFIG_DEBUG_FS guard in include/linux/iio/iio.h for
220 * iio_get_debugfs_dentry() to make it inline if CONFIG_DEBUG_FS is undefined
222 struct dentry *iio_get_debugfs_dentry(struct iio_dev *indio_dev)
224 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
225 return iio_dev_opaque->debugfs_dentry;
227 EXPORT_SYMBOL_GPL(iio_get_debugfs_dentry);
231 * iio_find_channel_from_si() - get channel from its scan index
233 * @si: scan index to match
235 const struct iio_chan_spec
236 *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
240 for (i = 0; i < indio_dev->num_channels; i++)
241 if (indio_dev->channels[i].scan_index == si)
242 return &indio_dev->channels[i];
246 /* This turns up an awful lot */
247 ssize_t iio_read_const_attr(struct device *dev,
248 struct device_attribute *attr,
251 return sysfs_emit(buf, "%s\n", to_iio_const_attr(attr)->string);
253 EXPORT_SYMBOL(iio_read_const_attr);
256 * iio_device_set_clock() - Set current timestamping clock for the device
257 * @indio_dev: IIO device structure containing the device
258 * @clock_id: timestamping clock posix identifier to set.
260 int iio_device_set_clock(struct iio_dev *indio_dev, clockid_t clock_id)
263 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
264 const struct iio_event_interface *ev_int = iio_dev_opaque->event_interface;
266 ret = mutex_lock_interruptible(&indio_dev->mlock);
269 if ((ev_int && iio_event_enabled(ev_int)) ||
270 iio_buffer_enabled(indio_dev)) {
271 mutex_unlock(&indio_dev->mlock);
274 iio_dev_opaque->clock_id = clock_id;
275 mutex_unlock(&indio_dev->mlock);
279 EXPORT_SYMBOL(iio_device_set_clock);
282 * iio_device_get_clock() - Retrieve current timestamping clock for the device
283 * @indio_dev: IIO device structure containing the device
285 clockid_t iio_device_get_clock(const struct iio_dev *indio_dev)
287 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
289 return iio_dev_opaque->clock_id;
291 EXPORT_SYMBOL(iio_device_get_clock);
294 * iio_get_time_ns() - utility function to get a time stamp for events etc
297 s64 iio_get_time_ns(const struct iio_dev *indio_dev)
299 struct timespec64 tp;
301 switch (iio_device_get_clock(indio_dev)) {
303 return ktime_get_real_ns();
304 case CLOCK_MONOTONIC:
305 return ktime_get_ns();
306 case CLOCK_MONOTONIC_RAW:
307 return ktime_get_raw_ns();
308 case CLOCK_REALTIME_COARSE:
309 return ktime_to_ns(ktime_get_coarse_real());
310 case CLOCK_MONOTONIC_COARSE:
311 ktime_get_coarse_ts64(&tp);
312 return timespec64_to_ns(&tp);
314 return ktime_get_boottime_ns();
316 return ktime_get_clocktai_ns();
321 EXPORT_SYMBOL(iio_get_time_ns);
324 * iio_get_time_res() - utility function to get time stamp clock resolution in
328 unsigned int iio_get_time_res(const struct iio_dev *indio_dev)
330 switch (iio_device_get_clock(indio_dev)) {
332 case CLOCK_MONOTONIC:
333 case CLOCK_MONOTONIC_RAW:
336 return hrtimer_resolution;
337 case CLOCK_REALTIME_COARSE:
338 case CLOCK_MONOTONIC_COARSE:
344 EXPORT_SYMBOL(iio_get_time_res);
346 static int __init iio_init(void)
350 /* Register sysfs bus */
351 ret = bus_register(&iio_bus_type);
353 pr_err("could not register bus type\n");
357 ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
359 pr_err("failed to allocate char dev region\n");
360 goto error_unregister_bus_type;
363 iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
367 error_unregister_bus_type:
368 bus_unregister(&iio_bus_type);
373 static void __exit iio_exit(void)
376 unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
377 bus_unregister(&iio_bus_type);
378 debugfs_remove(iio_debugfs_dentry);
381 #if defined(CONFIG_DEBUG_FS)
382 static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
383 size_t count, loff_t *ppos)
385 struct iio_dev *indio_dev = file->private_data;
386 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
391 return simple_read_from_buffer(userbuf, count, ppos,
392 iio_dev_opaque->read_buf,
393 iio_dev_opaque->read_buf_len);
395 ret = indio_dev->info->debugfs_reg_access(indio_dev,
396 iio_dev_opaque->cached_reg_addr,
399 dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
403 iio_dev_opaque->read_buf_len = snprintf(iio_dev_opaque->read_buf,
404 sizeof(iio_dev_opaque->read_buf),
407 return simple_read_from_buffer(userbuf, count, ppos,
408 iio_dev_opaque->read_buf,
409 iio_dev_opaque->read_buf_len);
412 static ssize_t iio_debugfs_write_reg(struct file *file,
413 const char __user *userbuf, size_t count, loff_t *ppos)
415 struct iio_dev *indio_dev = file->private_data;
416 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
421 count = min_t(size_t, count, (sizeof(buf)-1));
422 if (copy_from_user(buf, userbuf, count))
427 ret = sscanf(buf, "%i %i", ®, &val);
431 iio_dev_opaque->cached_reg_addr = reg;
434 iio_dev_opaque->cached_reg_addr = reg;
435 ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
438 dev_err(indio_dev->dev.parent, "%s: write failed\n",
450 static const struct file_operations iio_debugfs_reg_fops = {
452 .read = iio_debugfs_read_reg,
453 .write = iio_debugfs_write_reg,
456 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
458 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
459 debugfs_remove_recursive(iio_dev_opaque->debugfs_dentry);
462 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
464 struct iio_dev_opaque *iio_dev_opaque;
466 if (indio_dev->info->debugfs_reg_access == NULL)
469 if (!iio_debugfs_dentry)
472 iio_dev_opaque = to_iio_dev_opaque(indio_dev);
474 iio_dev_opaque->debugfs_dentry =
475 debugfs_create_dir(dev_name(&indio_dev->dev),
478 debugfs_create_file("direct_reg_access", 0644,
479 iio_dev_opaque->debugfs_dentry, indio_dev,
480 &iio_debugfs_reg_fops);
483 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
487 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
490 #endif /* CONFIG_DEBUG_FS */
492 static ssize_t iio_read_channel_ext_info(struct device *dev,
493 struct device_attribute *attr,
496 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
497 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
498 const struct iio_chan_spec_ext_info *ext_info;
500 ext_info = &this_attr->c->ext_info[this_attr->address];
502 return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
505 static ssize_t iio_write_channel_ext_info(struct device *dev,
506 struct device_attribute *attr,
510 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
511 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
512 const struct iio_chan_spec_ext_info *ext_info;
514 ext_info = &this_attr->c->ext_info[this_attr->address];
516 return ext_info->write(indio_dev, ext_info->private,
517 this_attr->c, buf, len);
520 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
521 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
523 const struct iio_enum *e = (const struct iio_enum *)priv;
530 for (i = 0; i < e->num_items; ++i) {
533 len += sysfs_emit_at(buf, len, "%s ", e->items[i]);
536 /* replace last space with a newline */
541 EXPORT_SYMBOL_GPL(iio_enum_available_read);
543 ssize_t iio_enum_read(struct iio_dev *indio_dev,
544 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
546 const struct iio_enum *e = (const struct iio_enum *)priv;
552 i = e->get(indio_dev, chan);
555 else if (i >= e->num_items || !e->items[i])
558 return sysfs_emit(buf, "%s\n", e->items[i]);
560 EXPORT_SYMBOL_GPL(iio_enum_read);
562 ssize_t iio_enum_write(struct iio_dev *indio_dev,
563 uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
566 const struct iio_enum *e = (const struct iio_enum *)priv;
572 ret = iio_sysfs_match_string_with_gaps(e->items, e->num_items, buf);
576 ret = e->set(indio_dev, chan, ret);
577 return ret ? ret : len;
579 EXPORT_SYMBOL_GPL(iio_enum_write);
581 static const struct iio_mount_matrix iio_mount_idmatrix = {
589 static int iio_setup_mount_idmatrix(const struct device *dev,
590 struct iio_mount_matrix *matrix)
592 *matrix = iio_mount_idmatrix;
593 dev_info(dev, "mounting matrix not found: using identity...\n");
597 ssize_t iio_show_mount_matrix(struct iio_dev *indio_dev, uintptr_t priv,
598 const struct iio_chan_spec *chan, char *buf)
600 const struct iio_mount_matrix *mtx = ((iio_get_mount_matrix_t *)
601 priv)(indio_dev, chan);
607 mtx = &iio_mount_idmatrix;
609 return sysfs_emit(buf, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
610 mtx->rotation[0], mtx->rotation[1], mtx->rotation[2],
611 mtx->rotation[3], mtx->rotation[4], mtx->rotation[5],
612 mtx->rotation[6], mtx->rotation[7], mtx->rotation[8]);
614 EXPORT_SYMBOL_GPL(iio_show_mount_matrix);
617 * iio_read_mount_matrix() - retrieve iio device mounting matrix from
618 * device "mount-matrix" property
619 * @dev: device the mounting matrix property is assigned to
620 * @matrix: where to store retrieved matrix
622 * If device is assigned no mounting matrix property, a default 3x3 identity
623 * matrix will be filled in.
625 * Return: 0 if success, or a negative error code on failure.
627 int iio_read_mount_matrix(struct device *dev, struct iio_mount_matrix *matrix)
629 size_t len = ARRAY_SIZE(iio_mount_idmatrix.rotation);
632 err = device_property_read_string_array(dev, "mount-matrix", matrix->rotation, len);
637 /* Invalid number of matrix entries. */
641 /* Invalid matrix declaration format. */
644 /* Matrix was not declared at all: fallback to identity. */
645 return iio_setup_mount_idmatrix(dev, matrix);
647 EXPORT_SYMBOL(iio_read_mount_matrix);
649 static ssize_t __iio_format_value(char *buf, size_t offset, unsigned int type,
650 int size, const int *vals)
654 bool scale_db = false;
658 return sysfs_emit_at(buf, offset, "%d", vals[0]);
659 case IIO_VAL_INT_PLUS_MICRO_DB:
662 case IIO_VAL_INT_PLUS_MICRO:
664 return sysfs_emit_at(buf, offset, "-%d.%06u%s",
665 abs(vals[0]), -vals[1],
666 scale_db ? " dB" : "");
668 return sysfs_emit_at(buf, offset, "%d.%06u%s", vals[0],
669 vals[1], scale_db ? " dB" : "");
670 case IIO_VAL_INT_PLUS_NANO:
672 return sysfs_emit_at(buf, offset, "-%d.%09u",
673 abs(vals[0]), -vals[1]);
675 return sysfs_emit_at(buf, offset, "%d.%09u", vals[0],
677 case IIO_VAL_FRACTIONAL:
678 tmp2 = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
680 tmp0 = (int)div_s64_rem(tmp2, 1000000000, &tmp1);
681 if ((tmp2 < 0) && (tmp0 == 0))
682 return sysfs_emit_at(buf, offset, "-0.%09u", abs(tmp1));
684 return sysfs_emit_at(buf, offset, "%d.%09u", tmp0,
686 case IIO_VAL_FRACTIONAL_LOG2:
687 tmp2 = shift_right((s64)vals[0] * 1000000000LL, vals[1]);
688 tmp0 = (int)div_s64_rem(tmp2, 1000000000LL, &tmp1);
689 if (tmp0 == 0 && tmp2 < 0)
690 return sysfs_emit_at(buf, offset, "-0.%09u", abs(tmp1));
692 return sysfs_emit_at(buf, offset, "%d.%09u", tmp0,
694 case IIO_VAL_INT_MULTIPLE:
699 for (i = 0; i < size; ++i)
700 l += sysfs_emit_at(buf, offset + l, "%d ", vals[i]);
704 return sysfs_emit_at(buf, offset, "%c", (char)vals[0]);
706 tmp2 = (s64)((((u64)vals[1]) << 32) | (u32)vals[0]);
707 return sysfs_emit_at(buf, offset, "%lld", tmp2);
714 * iio_format_value() - Formats a IIO value into its string representation
715 * @buf: The buffer to which the formatted value gets written
716 * which is assumed to be big enough (i.e. PAGE_SIZE).
717 * @type: One of the IIO_VAL_* constants. This decides how the val
718 * and val2 parameters are formatted.
719 * @size: Number of IIO value entries contained in vals
720 * @vals: Pointer to the values, exact meaning depends on the
723 * Return: 0 by default, a negative number on failure or the
724 * total number of characters written for a type that belongs
725 * to the IIO_VAL_* constant.
727 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
731 len = __iio_format_value(buf, 0, type, size, vals);
732 if (len >= PAGE_SIZE - 1)
735 return len + sysfs_emit_at(buf, len, "\n");
737 EXPORT_SYMBOL_GPL(iio_format_value);
739 static ssize_t iio_read_channel_label(struct device *dev,
740 struct device_attribute *attr,
743 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
744 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
746 if (indio_dev->info->read_label)
747 return indio_dev->info->read_label(indio_dev, this_attr->c, buf);
749 if (this_attr->c->extend_name)
750 return sprintf(buf, "%s\n", this_attr->c->extend_name);
755 static ssize_t iio_read_channel_info(struct device *dev,
756 struct device_attribute *attr,
759 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
760 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
761 int vals[INDIO_MAX_RAW_ELEMENTS];
765 if (indio_dev->info->read_raw_multi)
766 ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
767 INDIO_MAX_RAW_ELEMENTS,
771 ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
772 &vals[0], &vals[1], this_attr->address);
777 return iio_format_value(buf, ret, val_len, vals);
780 static ssize_t iio_format_list(char *buf, const int *vals, int type, int length,
781 const char *prefix, const char *suffix)
796 len = sysfs_emit(buf, prefix);
798 for (i = 0; i <= length - stride; i += stride) {
800 len += sysfs_emit_at(buf, len, " ");
801 if (len >= PAGE_SIZE)
805 len += __iio_format_value(buf, len, type, stride, &vals[i]);
806 if (len >= PAGE_SIZE)
810 len += sysfs_emit_at(buf, len, "%s\n", suffix);
815 static ssize_t iio_format_avail_list(char *buf, const int *vals,
816 int type, int length)
819 return iio_format_list(buf, vals, type, length, "", "");
822 static ssize_t iio_format_avail_range(char *buf, const int *vals, int type)
824 return iio_format_list(buf, vals, type, 3, "[", "]");
827 static ssize_t iio_read_channel_info_avail(struct device *dev,
828 struct device_attribute *attr,
831 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
832 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
838 ret = indio_dev->info->read_avail(indio_dev, this_attr->c,
839 &vals, &type, &length,
846 return iio_format_avail_list(buf, vals, type, length);
847 case IIO_AVAIL_RANGE:
848 return iio_format_avail_range(buf, vals, type);
855 * __iio_str_to_fixpoint() - Parse a fixed-point number from a string
856 * @str: The string to parse
857 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
858 * @integer: The integer part of the number
859 * @fract: The fractional part of the number
860 * @scale_db: True if this should parse as dB
862 * Returns 0 on success, or a negative error code if the string could not be
865 static int __iio_str_to_fixpoint(const char *str, int fract_mult,
866 int *integer, int *fract, bool scale_db)
869 bool integer_part = true, negative = false;
871 if (fract_mult == 0) {
874 return kstrtoint(str, 0, integer);
880 } else if (str[0] == '+') {
885 if ('0' <= *str && *str <= '9') {
887 i = i * 10 + *str - '0';
889 f += fract_mult * (*str - '0');
892 } else if (*str == '\n') {
893 if (*(str + 1) == '\0')
897 } else if (!strncmp(str, " dB", sizeof(" dB") - 1) && scale_db) {
898 /* Ignore the dB suffix */
899 str += sizeof(" dB") - 1;
901 } else if (!strncmp(str, "dB", sizeof("dB") - 1) && scale_db) {
902 /* Ignore the dB suffix */
903 str += sizeof("dB") - 1;
905 } else if (*str == '.' && integer_part) {
906 integer_part = false;
927 * iio_str_to_fixpoint() - Parse a fixed-point number from a string
928 * @str: The string to parse
929 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
930 * @integer: The integer part of the number
931 * @fract: The fractional part of the number
933 * Returns 0 on success, or a negative error code if the string could not be
936 int iio_str_to_fixpoint(const char *str, int fract_mult,
937 int *integer, int *fract)
939 return __iio_str_to_fixpoint(str, fract_mult, integer, fract, false);
941 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
943 static ssize_t iio_write_channel_info(struct device *dev,
944 struct device_attribute *attr,
948 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
949 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
950 int ret, fract_mult = 100000;
951 int integer, fract = 0;
952 bool is_char = false;
953 bool scale_db = false;
955 /* Assumes decimal - precision based on number of digits */
956 if (!indio_dev->info->write_raw)
959 if (indio_dev->info->write_raw_get_fmt)
960 switch (indio_dev->info->write_raw_get_fmt(indio_dev,
961 this_attr->c, this_attr->address)) {
965 case IIO_VAL_INT_PLUS_MICRO_DB:
968 case IIO_VAL_INT_PLUS_MICRO:
971 case IIO_VAL_INT_PLUS_NANO:
972 fract_mult = 100000000;
984 if (sscanf(buf, "%c", &ch) != 1)
988 ret = __iio_str_to_fixpoint(buf, fract_mult, &integer, &fract,
994 ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
995 integer, fract, this_attr->address);
1003 int __iio_device_attr_init(struct device_attribute *dev_attr,
1004 const char *postfix,
1005 struct iio_chan_spec const *chan,
1006 ssize_t (*readfunc)(struct device *dev,
1007 struct device_attribute *attr,
1009 ssize_t (*writefunc)(struct device *dev,
1010 struct device_attribute *attr,
1013 enum iio_shared_by shared_by)
1018 sysfs_attr_init(&dev_attr->attr);
1020 /* Build up postfix of <extend_name>_<modifier>_postfix */
1021 if (chan->modified && (shared_by == IIO_SEPARATE)) {
1022 if (chan->extend_name)
1023 full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
1024 iio_modifier_names[chan
1029 full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
1030 iio_modifier_names[chan
1034 if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
1035 full_postfix = kstrdup(postfix, GFP_KERNEL);
1037 full_postfix = kasprintf(GFP_KERNEL,
1042 if (full_postfix == NULL)
1045 if (chan->differential) { /* Differential can not have modifier */
1046 switch (shared_by) {
1047 case IIO_SHARED_BY_ALL:
1048 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1050 case IIO_SHARED_BY_DIR:
1051 name = kasprintf(GFP_KERNEL, "%s_%s",
1052 iio_direction[chan->output],
1055 case IIO_SHARED_BY_TYPE:
1056 name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
1057 iio_direction[chan->output],
1058 iio_chan_type_name_spec[chan->type],
1059 iio_chan_type_name_spec[chan->type],
1063 if (!chan->indexed) {
1064 WARN(1, "Differential channels must be indexed\n");
1066 goto error_free_full_postfix;
1068 name = kasprintf(GFP_KERNEL,
1070 iio_direction[chan->output],
1071 iio_chan_type_name_spec[chan->type],
1073 iio_chan_type_name_spec[chan->type],
1078 } else { /* Single ended */
1079 switch (shared_by) {
1080 case IIO_SHARED_BY_ALL:
1081 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1083 case IIO_SHARED_BY_DIR:
1084 name = kasprintf(GFP_KERNEL, "%s_%s",
1085 iio_direction[chan->output],
1088 case IIO_SHARED_BY_TYPE:
1089 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1090 iio_direction[chan->output],
1091 iio_chan_type_name_spec[chan->type],
1097 name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
1098 iio_direction[chan->output],
1099 iio_chan_type_name_spec[chan->type],
1103 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1104 iio_direction[chan->output],
1105 iio_chan_type_name_spec[chan->type],
1112 goto error_free_full_postfix;
1114 dev_attr->attr.name = name;
1117 dev_attr->attr.mode |= S_IRUGO;
1118 dev_attr->show = readfunc;
1122 dev_attr->attr.mode |= S_IWUSR;
1123 dev_attr->store = writefunc;
1126 error_free_full_postfix:
1127 kfree(full_postfix);
1132 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
1134 kfree(dev_attr->attr.name);
1137 int __iio_add_chan_devattr(const char *postfix,
1138 struct iio_chan_spec const *chan,
1139 ssize_t (*readfunc)(struct device *dev,
1140 struct device_attribute *attr,
1142 ssize_t (*writefunc)(struct device *dev,
1143 struct device_attribute *attr,
1147 enum iio_shared_by shared_by,
1149 struct iio_buffer *buffer,
1150 struct list_head *attr_list)
1153 struct iio_dev_attr *iio_attr, *t;
1155 iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
1156 if (iio_attr == NULL)
1158 ret = __iio_device_attr_init(&iio_attr->dev_attr,
1160 readfunc, writefunc, shared_by);
1162 goto error_iio_dev_attr_free;
1164 iio_attr->address = mask;
1165 iio_attr->buffer = buffer;
1166 list_for_each_entry(t, attr_list, l)
1167 if (strcmp(t->dev_attr.attr.name,
1168 iio_attr->dev_attr.attr.name) == 0) {
1169 if (shared_by == IIO_SEPARATE)
1170 dev_err(dev, "tried to double register : %s\n",
1171 t->dev_attr.attr.name);
1173 goto error_device_attr_deinit;
1175 list_add(&iio_attr->l, attr_list);
1179 error_device_attr_deinit:
1180 __iio_device_attr_deinit(&iio_attr->dev_attr);
1181 error_iio_dev_attr_free:
1186 static int iio_device_add_channel_label(struct iio_dev *indio_dev,
1187 struct iio_chan_spec const *chan)
1189 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1192 if (!indio_dev->info->read_label && !chan->extend_name)
1195 ret = __iio_add_chan_devattr("label",
1197 &iio_read_channel_label,
1203 &iio_dev_opaque->channel_attr_list);
1210 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
1211 struct iio_chan_spec const *chan,
1212 enum iio_shared_by shared_by,
1213 const long *infomask)
1215 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1216 int i, ret, attrcount = 0;
1218 for_each_set_bit(i, infomask, sizeof(*infomask)*8) {
1219 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1221 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
1223 &iio_read_channel_info,
1224 &iio_write_channel_info,
1229 &iio_dev_opaque->channel_attr_list);
1230 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1240 static int iio_device_add_info_mask_type_avail(struct iio_dev *indio_dev,
1241 struct iio_chan_spec const *chan,
1242 enum iio_shared_by shared_by,
1243 const long *infomask)
1245 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1246 int i, ret, attrcount = 0;
1247 char *avail_postfix;
1249 for_each_set_bit(i, infomask, sizeof(*infomask) * 8) {
1250 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1252 avail_postfix = kasprintf(GFP_KERNEL,
1254 iio_chan_info_postfix[i]);
1258 ret = __iio_add_chan_devattr(avail_postfix,
1260 &iio_read_channel_info_avail,
1266 &iio_dev_opaque->channel_attr_list);
1267 kfree(avail_postfix);
1268 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1278 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
1279 struct iio_chan_spec const *chan)
1281 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1282 int ret, attrcount = 0;
1283 const struct iio_chan_spec_ext_info *ext_info;
1285 if (chan->channel < 0)
1287 ret = iio_device_add_info_mask_type(indio_dev, chan,
1289 &chan->info_mask_separate);
1294 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1297 info_mask_separate_available);
1302 ret = iio_device_add_info_mask_type(indio_dev, chan,
1304 &chan->info_mask_shared_by_type);
1309 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1312 info_mask_shared_by_type_available);
1317 ret = iio_device_add_info_mask_type(indio_dev, chan,
1319 &chan->info_mask_shared_by_dir);
1324 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1326 &chan->info_mask_shared_by_dir_available);
1331 ret = iio_device_add_info_mask_type(indio_dev, chan,
1333 &chan->info_mask_shared_by_all);
1338 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1340 &chan->info_mask_shared_by_all_available);
1345 ret = iio_device_add_channel_label(indio_dev, chan);
1350 if (chan->ext_info) {
1352 for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
1353 ret = __iio_add_chan_devattr(ext_info->name,
1356 &iio_read_channel_ext_info : NULL,
1358 &iio_write_channel_ext_info : NULL,
1363 &iio_dev_opaque->channel_attr_list);
1365 if (ret == -EBUSY && ext_info->shared)
1379 * iio_free_chan_devattr_list() - Free a list of IIO device attributes
1380 * @attr_list: List of IIO device attributes
1382 * This function frees the memory allocated for each of the IIO device
1383 * attributes in the list.
1385 void iio_free_chan_devattr_list(struct list_head *attr_list)
1387 struct iio_dev_attr *p, *n;
1389 list_for_each_entry_safe(p, n, attr_list, l) {
1390 kfree_const(p->dev_attr.attr.name);
1396 static ssize_t iio_show_dev_name(struct device *dev,
1397 struct device_attribute *attr,
1400 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1401 return sysfs_emit(buf, "%s\n", indio_dev->name);
1404 static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
1406 static ssize_t iio_show_dev_label(struct device *dev,
1407 struct device_attribute *attr,
1410 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1411 return sysfs_emit(buf, "%s\n", indio_dev->label);
1414 static DEVICE_ATTR(label, S_IRUGO, iio_show_dev_label, NULL);
1416 static ssize_t iio_show_timestamp_clock(struct device *dev,
1417 struct device_attribute *attr,
1420 const struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1421 const clockid_t clk = iio_device_get_clock(indio_dev);
1426 case CLOCK_REALTIME:
1427 name = "realtime\n";
1428 sz = sizeof("realtime\n");
1430 case CLOCK_MONOTONIC:
1431 name = "monotonic\n";
1432 sz = sizeof("monotonic\n");
1434 case CLOCK_MONOTONIC_RAW:
1435 name = "monotonic_raw\n";
1436 sz = sizeof("monotonic_raw\n");
1438 case CLOCK_REALTIME_COARSE:
1439 name = "realtime_coarse\n";
1440 sz = sizeof("realtime_coarse\n");
1442 case CLOCK_MONOTONIC_COARSE:
1443 name = "monotonic_coarse\n";
1444 sz = sizeof("monotonic_coarse\n");
1446 case CLOCK_BOOTTIME:
1447 name = "boottime\n";
1448 sz = sizeof("boottime\n");
1452 sz = sizeof("tai\n");
1458 memcpy(buf, name, sz);
1462 static ssize_t iio_store_timestamp_clock(struct device *dev,
1463 struct device_attribute *attr,
1464 const char *buf, size_t len)
1469 if (sysfs_streq(buf, "realtime"))
1470 clk = CLOCK_REALTIME;
1471 else if (sysfs_streq(buf, "monotonic"))
1472 clk = CLOCK_MONOTONIC;
1473 else if (sysfs_streq(buf, "monotonic_raw"))
1474 clk = CLOCK_MONOTONIC_RAW;
1475 else if (sysfs_streq(buf, "realtime_coarse"))
1476 clk = CLOCK_REALTIME_COARSE;
1477 else if (sysfs_streq(buf, "monotonic_coarse"))
1478 clk = CLOCK_MONOTONIC_COARSE;
1479 else if (sysfs_streq(buf, "boottime"))
1480 clk = CLOCK_BOOTTIME;
1481 else if (sysfs_streq(buf, "tai"))
1486 ret = iio_device_set_clock(dev_to_iio_dev(dev), clk);
1493 int iio_device_register_sysfs_group(struct iio_dev *indio_dev,
1494 const struct attribute_group *group)
1496 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1497 const struct attribute_group **new, **old = iio_dev_opaque->groups;
1498 unsigned int cnt = iio_dev_opaque->groupcounter;
1500 new = krealloc(old, sizeof(*new) * (cnt + 2), GFP_KERNEL);
1504 new[iio_dev_opaque->groupcounter++] = group;
1505 new[iio_dev_opaque->groupcounter] = NULL;
1507 iio_dev_opaque->groups = new;
1512 static DEVICE_ATTR(current_timestamp_clock, S_IRUGO | S_IWUSR,
1513 iio_show_timestamp_clock, iio_store_timestamp_clock);
1515 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
1517 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1518 int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
1519 struct iio_dev_attr *p;
1520 struct attribute **attr, *clk = NULL;
1522 /* First count elements in any existing group */
1523 if (indio_dev->info->attrs) {
1524 attr = indio_dev->info->attrs->attrs;
1525 while (*attr++ != NULL)
1528 attrcount = attrcount_orig;
1530 * New channel registration method - relies on the fact a group does
1531 * not need to be initialized if its name is NULL.
1533 if (indio_dev->channels)
1534 for (i = 0; i < indio_dev->num_channels; i++) {
1535 const struct iio_chan_spec *chan =
1536 &indio_dev->channels[i];
1538 if (chan->type == IIO_TIMESTAMP)
1539 clk = &dev_attr_current_timestamp_clock.attr;
1541 ret = iio_device_add_channel_sysfs(indio_dev, chan);
1543 goto error_clear_attrs;
1547 if (iio_dev_opaque->event_interface)
1548 clk = &dev_attr_current_timestamp_clock.attr;
1550 if (indio_dev->name)
1552 if (indio_dev->label)
1557 iio_dev_opaque->chan_attr_group.attrs =
1558 kcalloc(attrcount + 1,
1559 sizeof(iio_dev_opaque->chan_attr_group.attrs[0]),
1561 if (iio_dev_opaque->chan_attr_group.attrs == NULL) {
1563 goto error_clear_attrs;
1565 /* Copy across original attributes */
1566 if (indio_dev->info->attrs) {
1567 memcpy(iio_dev_opaque->chan_attr_group.attrs,
1568 indio_dev->info->attrs->attrs,
1569 sizeof(iio_dev_opaque->chan_attr_group.attrs[0])
1571 iio_dev_opaque->chan_attr_group.is_visible =
1572 indio_dev->info->attrs->is_visible;
1574 attrn = attrcount_orig;
1575 /* Add all elements from the list. */
1576 list_for_each_entry(p, &iio_dev_opaque->channel_attr_list, l)
1577 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1578 if (indio_dev->name)
1579 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
1580 if (indio_dev->label)
1581 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_label.attr;
1583 iio_dev_opaque->chan_attr_group.attrs[attrn++] = clk;
1585 ret = iio_device_register_sysfs_group(indio_dev,
1586 &iio_dev_opaque->chan_attr_group);
1588 goto error_clear_attrs;
1593 iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1598 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
1600 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1602 iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1603 kfree(iio_dev_opaque->chan_attr_group.attrs);
1604 iio_dev_opaque->chan_attr_group.attrs = NULL;
1605 kfree(iio_dev_opaque->groups);
1606 iio_dev_opaque->groups = NULL;
1609 static void iio_dev_release(struct device *device)
1611 struct iio_dev *indio_dev = dev_to_iio_dev(device);
1612 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1614 if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1615 iio_device_unregister_trigger_consumer(indio_dev);
1616 iio_device_unregister_eventset(indio_dev);
1617 iio_device_unregister_sysfs(indio_dev);
1619 iio_device_detach_buffers(indio_dev);
1621 ida_simple_remove(&iio_ida, iio_dev_opaque->id);
1622 kfree(iio_dev_opaque);
1625 const struct device_type iio_device_type = {
1626 .name = "iio_device",
1627 .release = iio_dev_release,
1631 * iio_device_alloc() - allocate an iio_dev from a driver
1632 * @parent: Parent device.
1633 * @sizeof_priv: Space to allocate for private structure.
1635 struct iio_dev *iio_device_alloc(struct device *parent, int sizeof_priv)
1637 struct iio_dev_opaque *iio_dev_opaque;
1638 struct iio_dev *indio_dev;
1641 alloc_size = sizeof(struct iio_dev_opaque);
1643 alloc_size = ALIGN(alloc_size, IIO_ALIGN);
1644 alloc_size += sizeof_priv;
1647 iio_dev_opaque = kzalloc(alloc_size, GFP_KERNEL);
1648 if (!iio_dev_opaque)
1651 indio_dev = &iio_dev_opaque->indio_dev;
1652 indio_dev->priv = (char *)iio_dev_opaque +
1653 ALIGN(sizeof(struct iio_dev_opaque), IIO_ALIGN);
1655 indio_dev->dev.parent = parent;
1656 indio_dev->dev.type = &iio_device_type;
1657 indio_dev->dev.bus = &iio_bus_type;
1658 device_initialize(&indio_dev->dev);
1659 mutex_init(&indio_dev->mlock);
1660 mutex_init(&iio_dev_opaque->info_exist_lock);
1661 INIT_LIST_HEAD(&iio_dev_opaque->channel_attr_list);
1663 iio_dev_opaque->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
1664 if (iio_dev_opaque->id < 0) {
1665 /* cannot use a dev_err as the name isn't available */
1666 pr_err("failed to get device id\n");
1667 kfree(iio_dev_opaque);
1671 if (dev_set_name(&indio_dev->dev, "iio:device%d", iio_dev_opaque->id)) {
1672 ida_simple_remove(&iio_ida, iio_dev_opaque->id);
1673 kfree(iio_dev_opaque);
1677 INIT_LIST_HEAD(&iio_dev_opaque->buffer_list);
1678 INIT_LIST_HEAD(&iio_dev_opaque->ioctl_handlers);
1682 EXPORT_SYMBOL(iio_device_alloc);
1685 * iio_device_free() - free an iio_dev from a driver
1686 * @dev: the iio_dev associated with the device
1688 void iio_device_free(struct iio_dev *dev)
1691 put_device(&dev->dev);
1693 EXPORT_SYMBOL(iio_device_free);
1695 static void devm_iio_device_release(void *iio_dev)
1697 iio_device_free(iio_dev);
1701 * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1702 * @parent: Device to allocate iio_dev for, and parent for this IIO device
1703 * @sizeof_priv: Space to allocate for private structure.
1705 * Managed iio_device_alloc. iio_dev allocated with this function is
1706 * automatically freed on driver detach.
1709 * Pointer to allocated iio_dev on success, NULL on failure.
1711 struct iio_dev *devm_iio_device_alloc(struct device *parent, int sizeof_priv)
1713 struct iio_dev *iio_dev;
1716 iio_dev = iio_device_alloc(parent, sizeof_priv);
1720 ret = devm_add_action_or_reset(parent, devm_iio_device_release,
1727 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1730 * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1731 * @inode: Inode structure for identifying the device in the file system
1732 * @filp: File structure for iio device used to keep and later access
1735 * Return: 0 on success or -EBUSY if the device is already opened
1737 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1739 struct iio_dev_opaque *iio_dev_opaque =
1740 container_of(inode->i_cdev, struct iio_dev_opaque, chrdev);
1741 struct iio_dev *indio_dev = &iio_dev_opaque->indio_dev;
1742 struct iio_dev_buffer_pair *ib;
1744 if (test_and_set_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags))
1747 iio_device_get(indio_dev);
1749 ib = kmalloc(sizeof(*ib), GFP_KERNEL);
1751 iio_device_put(indio_dev);
1752 clear_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags);
1756 ib->indio_dev = indio_dev;
1757 ib->buffer = indio_dev->buffer;
1759 filp->private_data = ib;
1765 * iio_chrdev_release() - chrdev file close buffer access and ioctls
1766 * @inode: Inode structure pointer for the char device
1767 * @filp: File structure pointer for the char device
1769 * Return: 0 for successful release
1771 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1773 struct iio_dev_buffer_pair *ib = filp->private_data;
1774 struct iio_dev_opaque *iio_dev_opaque =
1775 container_of(inode->i_cdev, struct iio_dev_opaque, chrdev);
1776 struct iio_dev *indio_dev = &iio_dev_opaque->indio_dev;
1778 clear_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags);
1779 iio_device_put(indio_dev);
1784 void iio_device_ioctl_handler_register(struct iio_dev *indio_dev,
1785 struct iio_ioctl_handler *h)
1787 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1789 list_add_tail(&h->entry, &iio_dev_opaque->ioctl_handlers);
1792 void iio_device_ioctl_handler_unregister(struct iio_ioctl_handler *h)
1794 list_del(&h->entry);
1797 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1799 struct iio_dev_buffer_pair *ib = filp->private_data;
1800 struct iio_dev *indio_dev = ib->indio_dev;
1801 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1802 struct iio_ioctl_handler *h;
1805 mutex_lock(&iio_dev_opaque->info_exist_lock);
1808 * The NULL check here is required to prevent crashing when a device
1809 * is being removed while userspace would still have open file handles
1810 * to try to access this device.
1812 if (!indio_dev->info)
1815 list_for_each_entry(h, &iio_dev_opaque->ioctl_handlers, entry) {
1816 ret = h->ioctl(indio_dev, filp, cmd, arg);
1817 if (ret != IIO_IOCTL_UNHANDLED)
1821 if (ret == IIO_IOCTL_UNHANDLED)
1825 mutex_unlock(&iio_dev_opaque->info_exist_lock);
1830 static const struct file_operations iio_buffer_fileops = {
1831 .owner = THIS_MODULE,
1832 .llseek = noop_llseek,
1833 .read = iio_buffer_read_outer_addr,
1834 .write = iio_buffer_write_outer_addr,
1835 .poll = iio_buffer_poll_addr,
1836 .unlocked_ioctl = iio_ioctl,
1837 .compat_ioctl = compat_ptr_ioctl,
1838 .open = iio_chrdev_open,
1839 .release = iio_chrdev_release,
1842 static const struct file_operations iio_event_fileops = {
1843 .owner = THIS_MODULE,
1844 .llseek = noop_llseek,
1845 .unlocked_ioctl = iio_ioctl,
1846 .compat_ioctl = compat_ptr_ioctl,
1847 .open = iio_chrdev_open,
1848 .release = iio_chrdev_release,
1851 static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1854 const struct iio_chan_spec *channels = indio_dev->channels;
1856 if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1859 for (i = 0; i < indio_dev->num_channels - 1; i++) {
1860 if (channels[i].scan_index < 0)
1862 for (j = i + 1; j < indio_dev->num_channels; j++)
1863 if (channels[i].scan_index == channels[j].scan_index) {
1864 dev_err(&indio_dev->dev,
1865 "Duplicate scan index %d\n",
1866 channels[i].scan_index);
1874 static int iio_check_extended_name(const struct iio_dev *indio_dev)
1878 if (!indio_dev->info->read_label)
1881 for (i = 0; i < indio_dev->num_channels; i++) {
1882 if (indio_dev->channels[i].extend_name) {
1883 dev_err(&indio_dev->dev,
1884 "Cannot use labels and extend_name at the same time\n");
1892 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1894 int __iio_device_register(struct iio_dev *indio_dev, struct module *this_mod)
1896 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1900 if (!indio_dev->info)
1903 iio_dev_opaque->driver_module = this_mod;
1904 /* If the calling driver did not initialize of_node, do it here */
1905 if (!indio_dev->dev.of_node && indio_dev->dev.parent)
1906 indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
1908 label = of_get_property(indio_dev->dev.of_node, "label", NULL);
1910 indio_dev->label = label;
1912 ret = iio_check_unique_scan_index(indio_dev);
1916 ret = iio_check_extended_name(indio_dev);
1920 iio_device_register_debugfs(indio_dev);
1922 ret = iio_buffers_alloc_sysfs_and_mask(indio_dev);
1924 dev_err(indio_dev->dev.parent,
1925 "Failed to create buffer sysfs interfaces\n");
1926 goto error_unreg_debugfs;
1929 ret = iio_device_register_sysfs(indio_dev);
1931 dev_err(indio_dev->dev.parent,
1932 "Failed to register sysfs interfaces\n");
1933 goto error_buffer_free_sysfs;
1935 ret = iio_device_register_eventset(indio_dev);
1937 dev_err(indio_dev->dev.parent,
1938 "Failed to register event set\n");
1939 goto error_free_sysfs;
1941 if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1942 iio_device_register_trigger_consumer(indio_dev);
1944 if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1945 indio_dev->setup_ops == NULL)
1946 indio_dev->setup_ops = &noop_ring_setup_ops;
1948 if (iio_dev_opaque->attached_buffers_cnt)
1949 cdev_init(&iio_dev_opaque->chrdev, &iio_buffer_fileops);
1950 else if (iio_dev_opaque->event_interface)
1951 cdev_init(&iio_dev_opaque->chrdev, &iio_event_fileops);
1953 if (iio_dev_opaque->attached_buffers_cnt || iio_dev_opaque->event_interface) {
1954 indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), iio_dev_opaque->id);
1955 iio_dev_opaque->chrdev.owner = this_mod;
1958 /* assign device groups now; they should be all registered now */
1959 indio_dev->dev.groups = iio_dev_opaque->groups;
1961 ret = cdev_device_add(&iio_dev_opaque->chrdev, &indio_dev->dev);
1963 goto error_unreg_eventset;
1967 error_unreg_eventset:
1968 iio_device_unregister_eventset(indio_dev);
1970 iio_device_unregister_sysfs(indio_dev);
1971 error_buffer_free_sysfs:
1972 iio_buffers_free_sysfs_and_mask(indio_dev);
1973 error_unreg_debugfs:
1974 iio_device_unregister_debugfs(indio_dev);
1977 EXPORT_SYMBOL(__iio_device_register);
1980 * iio_device_unregister() - unregister a device from the IIO subsystem
1981 * @indio_dev: Device structure representing the device.
1983 void iio_device_unregister(struct iio_dev *indio_dev)
1985 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1987 cdev_device_del(&iio_dev_opaque->chrdev, &indio_dev->dev);
1989 mutex_lock(&iio_dev_opaque->info_exist_lock);
1991 iio_device_unregister_debugfs(indio_dev);
1993 iio_disable_all_buffers(indio_dev);
1995 indio_dev->info = NULL;
1997 iio_device_wakeup_eventset(indio_dev);
1998 iio_buffer_wakeup_poll(indio_dev);
2000 mutex_unlock(&iio_dev_opaque->info_exist_lock);
2002 iio_buffers_free_sysfs_and_mask(indio_dev);
2004 EXPORT_SYMBOL(iio_device_unregister);
2006 static void devm_iio_device_unreg(void *indio_dev)
2008 iio_device_unregister(indio_dev);
2011 int __devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev,
2012 struct module *this_mod)
2016 ret = __iio_device_register(indio_dev, this_mod);
2020 return devm_add_action_or_reset(dev, devm_iio_device_unreg, indio_dev);
2022 EXPORT_SYMBOL_GPL(__devm_iio_device_register);
2025 * iio_device_claim_direct_mode - Keep device in direct mode
2026 * @indio_dev: the iio_dev associated with the device
2028 * If the device is in direct mode it is guaranteed to stay
2029 * that way until iio_device_release_direct_mode() is called.
2031 * Use with iio_device_release_direct_mode()
2033 * Returns: 0 on success, -EBUSY on failure
2035 int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
2037 mutex_lock(&indio_dev->mlock);
2039 if (iio_buffer_enabled(indio_dev)) {
2040 mutex_unlock(&indio_dev->mlock);
2045 EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
2048 * iio_device_release_direct_mode - releases claim on direct mode
2049 * @indio_dev: the iio_dev associated with the device
2051 * Release the claim. Device is no longer guaranteed to stay
2054 * Use with iio_device_claim_direct_mode()
2056 void iio_device_release_direct_mode(struct iio_dev *indio_dev)
2058 mutex_unlock(&indio_dev->mlock);
2060 EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
2062 subsys_initcall(iio_init);
2063 module_exit(iio_exit);
2065 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
2066 MODULE_DESCRIPTION("Industrial I/O core");
2067 MODULE_LICENSE("GPL");