1 // SPDX-License-Identifier: GPL-2.0-only
3 * The industrial I/O core
5 * Copyright (c) 2008 Jonathan Cameron
7 * Based on elements of hwmon and input subsystems.
10 #define pr_fmt(fmt) "iio-core: " fmt
12 #include <linux/anon_inodes.h>
13 #include <linux/cdev.h>
14 #include <linux/debugfs.h>
15 #include <linux/device.h>
16 #include <linux/err.h>
18 #include <linux/idr.h>
19 #include <linux/kdev_t.h>
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/mutex.h>
23 #include <linux/poll.h>
24 #include <linux/property.h>
25 #include <linux/sched.h>
26 #include <linux/slab.h>
27 #include <linux/wait.h>
29 #include <linux/iio/buffer.h>
30 #include <linux/iio/buffer_impl.h>
31 #include <linux/iio/events.h>
32 #include <linux/iio/iio-opaque.h>
33 #include <linux/iio/iio.h>
34 #include <linux/iio/sysfs.h>
37 #include "iio_core_trigger.h"
39 /* IDA to assign each registered device a unique id */
40 static DEFINE_IDA(iio_ida);
42 static dev_t iio_devt;
44 #define IIO_DEV_MAX 256
45 struct bus_type iio_bus_type = {
48 EXPORT_SYMBOL(iio_bus_type);
50 static struct dentry *iio_debugfs_dentry;
52 static const char * const iio_direction[] = {
57 static const char * const iio_chan_type_name_spec[] = {
58 [IIO_VOLTAGE] = "voltage",
59 [IIO_CURRENT] = "current",
60 [IIO_POWER] = "power",
61 [IIO_ACCEL] = "accel",
62 [IIO_ANGL_VEL] = "anglvel",
64 [IIO_LIGHT] = "illuminance",
65 [IIO_INTENSITY] = "intensity",
66 [IIO_PROXIMITY] = "proximity",
68 [IIO_INCLI] = "incli",
71 [IIO_TIMESTAMP] = "timestamp",
72 [IIO_CAPACITANCE] = "capacitance",
73 [IIO_ALTVOLTAGE] = "altvoltage",
75 [IIO_PRESSURE] = "pressure",
76 [IIO_HUMIDITYRELATIVE] = "humidityrelative",
77 [IIO_ACTIVITY] = "activity",
78 [IIO_STEPS] = "steps",
79 [IIO_ENERGY] = "energy",
80 [IIO_DISTANCE] = "distance",
81 [IIO_VELOCITY] = "velocity",
82 [IIO_CONCENTRATION] = "concentration",
83 [IIO_RESISTANCE] = "resistance",
85 [IIO_UVINDEX] = "uvindex",
86 [IIO_ELECTRICALCONDUCTIVITY] = "electricalconductivity",
87 [IIO_COUNT] = "count",
88 [IIO_INDEX] = "index",
89 [IIO_GRAVITY] = "gravity",
90 [IIO_POSITIONRELATIVE] = "positionrelative",
91 [IIO_PHASE] = "phase",
92 [IIO_MASSCONCENTRATION] = "massconcentration",
93 [IIO_DELTA_ANGL] = "deltaangl",
94 [IIO_DELTA_VELOCITY] = "deltavelocity",
95 [IIO_COLORTEMP] = "colortemp",
96 [IIO_CHROMATICITY] = "chromaticity",
99 static const char * const iio_modifier_names[] = {
103 [IIO_MOD_X_AND_Y] = "x&y",
104 [IIO_MOD_X_AND_Z] = "x&z",
105 [IIO_MOD_Y_AND_Z] = "y&z",
106 [IIO_MOD_X_AND_Y_AND_Z] = "x&y&z",
107 [IIO_MOD_X_OR_Y] = "x|y",
108 [IIO_MOD_X_OR_Z] = "x|z",
109 [IIO_MOD_Y_OR_Z] = "y|z",
110 [IIO_MOD_X_OR_Y_OR_Z] = "x|y|z",
111 [IIO_MOD_ROOT_SUM_SQUARED_X_Y] = "sqrt(x^2+y^2)",
112 [IIO_MOD_SUM_SQUARED_X_Y_Z] = "x^2+y^2+z^2",
113 [IIO_MOD_LIGHT_BOTH] = "both",
114 [IIO_MOD_LIGHT_IR] = "ir",
115 [IIO_MOD_LIGHT_CLEAR] = "clear",
116 [IIO_MOD_LIGHT_RED] = "red",
117 [IIO_MOD_LIGHT_GREEN] = "green",
118 [IIO_MOD_LIGHT_BLUE] = "blue",
119 [IIO_MOD_LIGHT_UV] = "uv",
120 [IIO_MOD_LIGHT_DUV] = "duv",
121 [IIO_MOD_QUATERNION] = "quaternion",
122 [IIO_MOD_TEMP_AMBIENT] = "ambient",
123 [IIO_MOD_TEMP_OBJECT] = "object",
124 [IIO_MOD_NORTH_MAGN] = "from_north_magnetic",
125 [IIO_MOD_NORTH_TRUE] = "from_north_true",
126 [IIO_MOD_NORTH_MAGN_TILT_COMP] = "from_north_magnetic_tilt_comp",
127 [IIO_MOD_NORTH_TRUE_TILT_COMP] = "from_north_true_tilt_comp",
128 [IIO_MOD_RUNNING] = "running",
129 [IIO_MOD_JOGGING] = "jogging",
130 [IIO_MOD_WALKING] = "walking",
131 [IIO_MOD_STILL] = "still",
132 [IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z] = "sqrt(x^2+y^2+z^2)",
135 [IIO_MOD_CO2] = "co2",
136 [IIO_MOD_VOC] = "voc",
137 [IIO_MOD_PM1] = "pm1",
138 [IIO_MOD_PM2P5] = "pm2p5",
139 [IIO_MOD_PM4] = "pm4",
140 [IIO_MOD_PM10] = "pm10",
141 [IIO_MOD_ETHANOL] = "ethanol",
144 [IIO_MOD_LINEAR_X] = "linear_x",
145 [IIO_MOD_LINEAR_Y] = "linear_y",
146 [IIO_MOD_LINEAR_Z] = "linear_z",
147 [IIO_MOD_PITCH] = "pitch",
148 [IIO_MOD_YAW] = "yaw",
149 [IIO_MOD_ROLL] = "roll",
152 /* relies on pairs of these shared then separate */
153 static const char * const iio_chan_info_postfix[] = {
154 [IIO_CHAN_INFO_RAW] = "raw",
155 [IIO_CHAN_INFO_PROCESSED] = "input",
156 [IIO_CHAN_INFO_SCALE] = "scale",
157 [IIO_CHAN_INFO_OFFSET] = "offset",
158 [IIO_CHAN_INFO_CALIBSCALE] = "calibscale",
159 [IIO_CHAN_INFO_CALIBBIAS] = "calibbias",
160 [IIO_CHAN_INFO_PEAK] = "peak_raw",
161 [IIO_CHAN_INFO_PEAK_SCALE] = "peak_scale",
162 [IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW] = "quadrature_correction_raw",
163 [IIO_CHAN_INFO_AVERAGE_RAW] = "mean_raw",
164 [IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY]
165 = "filter_low_pass_3db_frequency",
166 [IIO_CHAN_INFO_HIGH_PASS_FILTER_3DB_FREQUENCY]
167 = "filter_high_pass_3db_frequency",
168 [IIO_CHAN_INFO_SAMP_FREQ] = "sampling_frequency",
169 [IIO_CHAN_INFO_FREQUENCY] = "frequency",
170 [IIO_CHAN_INFO_PHASE] = "phase",
171 [IIO_CHAN_INFO_HARDWAREGAIN] = "hardwaregain",
172 [IIO_CHAN_INFO_HYSTERESIS] = "hysteresis",
173 [IIO_CHAN_INFO_HYSTERESIS_RELATIVE] = "hysteresis_relative",
174 [IIO_CHAN_INFO_INT_TIME] = "integration_time",
175 [IIO_CHAN_INFO_ENABLE] = "en",
176 [IIO_CHAN_INFO_CALIBHEIGHT] = "calibheight",
177 [IIO_CHAN_INFO_CALIBWEIGHT] = "calibweight",
178 [IIO_CHAN_INFO_DEBOUNCE_COUNT] = "debounce_count",
179 [IIO_CHAN_INFO_DEBOUNCE_TIME] = "debounce_time",
180 [IIO_CHAN_INFO_CALIBEMISSIVITY] = "calibemissivity",
181 [IIO_CHAN_INFO_OVERSAMPLING_RATIO] = "oversampling_ratio",
182 [IIO_CHAN_INFO_THERMOCOUPLE_TYPE] = "thermocouple_type",
183 [IIO_CHAN_INFO_CALIBAMBIENT] = "calibambient",
184 [IIO_CHAN_INFO_ZEROPOINT] = "zeropoint",
187 * iio_device_id() - query the unique ID for the device
188 * @indio_dev: Device structure whose ID is being queried
190 * The IIO device ID is a unique index used for example for the naming
191 * of the character device /dev/iio\:device[ID].
193 * Returns: Unique ID for the device.
195 int iio_device_id(struct iio_dev *indio_dev)
197 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
199 return iio_dev_opaque->id;
201 EXPORT_SYMBOL_GPL(iio_device_id);
204 * iio_buffer_enabled() - helper function to test if the buffer is enabled
205 * @indio_dev: IIO device structure for device
207 * Returns: True, if the buffer is enabled.
209 bool iio_buffer_enabled(struct iio_dev *indio_dev)
211 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
213 return iio_dev_opaque->currentmode &
214 (INDIO_BUFFER_HARDWARE | INDIO_BUFFER_SOFTWARE |
215 INDIO_BUFFER_TRIGGERED);
217 EXPORT_SYMBOL_GPL(iio_buffer_enabled);
219 #if defined(CONFIG_DEBUG_FS)
221 * There's also a CONFIG_DEBUG_FS guard in include/linux/iio/iio.h for
222 * iio_get_debugfs_dentry() to make it inline if CONFIG_DEBUG_FS is undefined
224 struct dentry *iio_get_debugfs_dentry(struct iio_dev *indio_dev)
226 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
228 return iio_dev_opaque->debugfs_dentry;
230 EXPORT_SYMBOL_GPL(iio_get_debugfs_dentry);
234 * iio_find_channel_from_si() - get channel from its scan index
236 * @si: scan index to match
239 * Constant pointer to iio_chan_spec, if scan index matches, NULL on failure.
241 const struct iio_chan_spec
242 *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
246 for (i = 0; i < indio_dev->num_channels; i++)
247 if (indio_dev->channels[i].scan_index == si)
248 return &indio_dev->channels[i];
252 /* This turns up an awful lot */
253 ssize_t iio_read_const_attr(struct device *dev,
254 struct device_attribute *attr,
257 return sysfs_emit(buf, "%s\n", to_iio_const_attr(attr)->string);
259 EXPORT_SYMBOL(iio_read_const_attr);
262 * iio_device_set_clock() - Set current timestamping clock for the device
263 * @indio_dev: IIO device structure containing the device
264 * @clock_id: timestamping clock POSIX identifier to set.
266 * Returns: 0 on success, or a negative error code.
268 int iio_device_set_clock(struct iio_dev *indio_dev, clockid_t clock_id)
271 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
272 const struct iio_event_interface *ev_int = iio_dev_opaque->event_interface;
274 ret = mutex_lock_interruptible(&iio_dev_opaque->mlock);
277 if ((ev_int && iio_event_enabled(ev_int)) ||
278 iio_buffer_enabled(indio_dev)) {
279 mutex_unlock(&iio_dev_opaque->mlock);
282 iio_dev_opaque->clock_id = clock_id;
283 mutex_unlock(&iio_dev_opaque->mlock);
287 EXPORT_SYMBOL(iio_device_set_clock);
290 * iio_device_get_clock() - Retrieve current timestamping clock for the device
291 * @indio_dev: IIO device structure containing the device
293 * Returns: Clock ID of the current timestamping clock for the device.
295 clockid_t iio_device_get_clock(const struct iio_dev *indio_dev)
297 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
299 return iio_dev_opaque->clock_id;
301 EXPORT_SYMBOL(iio_device_get_clock);
304 * iio_get_time_ns() - utility function to get a time stamp for events etc
307 * Returns: Timestamp of the event in nanoseconds.
309 s64 iio_get_time_ns(const struct iio_dev *indio_dev)
311 struct timespec64 tp;
313 switch (iio_device_get_clock(indio_dev)) {
315 return ktime_get_real_ns();
316 case CLOCK_MONOTONIC:
317 return ktime_get_ns();
318 case CLOCK_MONOTONIC_RAW:
319 return ktime_get_raw_ns();
320 case CLOCK_REALTIME_COARSE:
321 return ktime_to_ns(ktime_get_coarse_real());
322 case CLOCK_MONOTONIC_COARSE:
323 ktime_get_coarse_ts64(&tp);
324 return timespec64_to_ns(&tp);
326 return ktime_get_boottime_ns();
328 return ktime_get_clocktai_ns();
333 EXPORT_SYMBOL(iio_get_time_ns);
335 static int __init iio_init(void)
339 /* Register sysfs bus */
340 ret = bus_register(&iio_bus_type);
342 pr_err("could not register bus type\n");
346 ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
348 pr_err("failed to allocate char dev region\n");
349 goto error_unregister_bus_type;
352 iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
356 error_unregister_bus_type:
357 bus_unregister(&iio_bus_type);
362 static void __exit iio_exit(void)
365 unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
366 bus_unregister(&iio_bus_type);
367 debugfs_remove(iio_debugfs_dentry);
370 #if defined(CONFIG_DEBUG_FS)
371 static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
372 size_t count, loff_t *ppos)
374 struct iio_dev *indio_dev = file->private_data;
375 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
376 unsigned int val = 0;
380 return simple_read_from_buffer(userbuf, count, ppos,
381 iio_dev_opaque->read_buf,
382 iio_dev_opaque->read_buf_len);
384 ret = indio_dev->info->debugfs_reg_access(indio_dev,
385 iio_dev_opaque->cached_reg_addr,
388 dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
392 iio_dev_opaque->read_buf_len = snprintf(iio_dev_opaque->read_buf,
393 sizeof(iio_dev_opaque->read_buf),
396 return simple_read_from_buffer(userbuf, count, ppos,
397 iio_dev_opaque->read_buf,
398 iio_dev_opaque->read_buf_len);
401 static ssize_t iio_debugfs_write_reg(struct file *file,
402 const char __user *userbuf, size_t count, loff_t *ppos)
404 struct iio_dev *indio_dev = file->private_data;
405 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
406 unsigned int reg, val;
410 count = min(count, sizeof(buf) - 1);
411 if (copy_from_user(buf, userbuf, count))
416 ret = sscanf(buf, "%i %i", ®, &val);
420 iio_dev_opaque->cached_reg_addr = reg;
423 iio_dev_opaque->cached_reg_addr = reg;
424 ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
427 dev_err(indio_dev->dev.parent, "%s: write failed\n",
439 static const struct file_operations iio_debugfs_reg_fops = {
441 .read = iio_debugfs_read_reg,
442 .write = iio_debugfs_write_reg,
445 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
447 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
449 debugfs_remove_recursive(iio_dev_opaque->debugfs_dentry);
452 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
454 struct iio_dev_opaque *iio_dev_opaque;
456 if (indio_dev->info->debugfs_reg_access == NULL)
459 if (!iio_debugfs_dentry)
462 iio_dev_opaque = to_iio_dev_opaque(indio_dev);
464 iio_dev_opaque->debugfs_dentry =
465 debugfs_create_dir(dev_name(&indio_dev->dev),
468 debugfs_create_file("direct_reg_access", 0644,
469 iio_dev_opaque->debugfs_dentry, indio_dev,
470 &iio_debugfs_reg_fops);
473 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
477 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
480 #endif /* CONFIG_DEBUG_FS */
482 static ssize_t iio_read_channel_ext_info(struct device *dev,
483 struct device_attribute *attr,
486 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
487 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
488 const struct iio_chan_spec_ext_info *ext_info;
490 ext_info = &this_attr->c->ext_info[this_attr->address];
492 return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
495 static ssize_t iio_write_channel_ext_info(struct device *dev,
496 struct device_attribute *attr,
497 const char *buf, size_t len)
499 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
500 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
501 const struct iio_chan_spec_ext_info *ext_info;
503 ext_info = &this_attr->c->ext_info[this_attr->address];
505 return ext_info->write(indio_dev, ext_info->private,
506 this_attr->c, buf, len);
509 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
510 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
512 const struct iio_enum *e = (const struct iio_enum *)priv;
519 for (i = 0; i < e->num_items; ++i) {
522 len += sysfs_emit_at(buf, len, "%s ", e->items[i]);
525 /* replace last space with a newline */
530 EXPORT_SYMBOL_GPL(iio_enum_available_read);
532 ssize_t iio_enum_read(struct iio_dev *indio_dev,
533 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
535 const struct iio_enum *e = (const struct iio_enum *)priv;
541 i = e->get(indio_dev, chan);
544 if (i >= e->num_items || !e->items[i])
547 return sysfs_emit(buf, "%s\n", e->items[i]);
549 EXPORT_SYMBOL_GPL(iio_enum_read);
551 ssize_t iio_enum_write(struct iio_dev *indio_dev,
552 uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
555 const struct iio_enum *e = (const struct iio_enum *)priv;
561 ret = __sysfs_match_string(e->items, e->num_items, buf);
565 ret = e->set(indio_dev, chan, ret);
566 return ret ? ret : len;
568 EXPORT_SYMBOL_GPL(iio_enum_write);
570 static const struct iio_mount_matrix iio_mount_idmatrix = {
578 static int iio_setup_mount_idmatrix(const struct device *dev,
579 struct iio_mount_matrix *matrix)
581 *matrix = iio_mount_idmatrix;
582 dev_info(dev, "mounting matrix not found: using identity...\n");
586 ssize_t iio_show_mount_matrix(struct iio_dev *indio_dev, uintptr_t priv,
587 const struct iio_chan_spec *chan, char *buf)
589 const struct iio_mount_matrix *mtx;
591 mtx = ((iio_get_mount_matrix_t *)priv)(indio_dev, chan);
596 mtx = &iio_mount_idmatrix;
598 return sysfs_emit(buf, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
599 mtx->rotation[0], mtx->rotation[1], mtx->rotation[2],
600 mtx->rotation[3], mtx->rotation[4], mtx->rotation[5],
601 mtx->rotation[6], mtx->rotation[7], mtx->rotation[8]);
603 EXPORT_SYMBOL_GPL(iio_show_mount_matrix);
606 * iio_read_mount_matrix() - retrieve iio device mounting matrix from
607 * device "mount-matrix" property
608 * @dev: device the mounting matrix property is assigned to
609 * @matrix: where to store retrieved matrix
611 * If device is assigned no mounting matrix property, a default 3x3 identity
612 * matrix will be filled in.
614 * Returns: 0 if success, or a negative error code on failure.
616 int iio_read_mount_matrix(struct device *dev, struct iio_mount_matrix *matrix)
618 size_t len = ARRAY_SIZE(iio_mount_idmatrix.rotation);
621 err = device_property_read_string_array(dev, "mount-matrix", matrix->rotation, len);
626 /* Invalid number of matrix entries. */
630 /* Invalid matrix declaration format. */
633 /* Matrix was not declared at all: fallback to identity. */
634 return iio_setup_mount_idmatrix(dev, matrix);
636 EXPORT_SYMBOL(iio_read_mount_matrix);
638 static ssize_t __iio_format_value(char *buf, size_t offset, unsigned int type,
639 int size, const int *vals)
643 bool scale_db = false;
647 return sysfs_emit_at(buf, offset, "%d", vals[0]);
648 case IIO_VAL_INT_PLUS_MICRO_DB:
651 case IIO_VAL_INT_PLUS_MICRO:
653 return sysfs_emit_at(buf, offset, "-%d.%06u%s",
654 abs(vals[0]), -vals[1],
655 scale_db ? " dB" : "");
657 return sysfs_emit_at(buf, offset, "%d.%06u%s", vals[0],
658 vals[1], scale_db ? " dB" : "");
659 case IIO_VAL_INT_PLUS_NANO:
661 return sysfs_emit_at(buf, offset, "-%d.%09u",
662 abs(vals[0]), -vals[1]);
664 return sysfs_emit_at(buf, offset, "%d.%09u", vals[0],
666 case IIO_VAL_FRACTIONAL:
667 tmp2 = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
669 tmp0 = (int)div_s64_rem(tmp2, 1000000000, &tmp1);
670 if ((tmp2 < 0) && (tmp0 == 0))
671 return sysfs_emit_at(buf, offset, "-0.%09u", abs(tmp1));
673 return sysfs_emit_at(buf, offset, "%d.%09u", tmp0,
675 case IIO_VAL_FRACTIONAL_LOG2:
676 tmp2 = shift_right((s64)vals[0] * 1000000000LL, vals[1]);
677 tmp0 = (int)div_s64_rem(tmp2, 1000000000LL, &tmp1);
678 if (tmp0 == 0 && tmp2 < 0)
679 return sysfs_emit_at(buf, offset, "-0.%09u", abs(tmp1));
681 return sysfs_emit_at(buf, offset, "%d.%09u", tmp0,
683 case IIO_VAL_INT_MULTIPLE:
688 for (i = 0; i < size; ++i)
689 l += sysfs_emit_at(buf, offset + l, "%d ", vals[i]);
693 return sysfs_emit_at(buf, offset, "%c", (char)vals[0]);
695 tmp2 = (s64)((((u64)vals[1]) << 32) | (u32)vals[0]);
696 return sysfs_emit_at(buf, offset, "%lld", tmp2);
703 * iio_format_value() - Formats a IIO value into its string representation
704 * @buf: The buffer to which the formatted value gets written
705 * which is assumed to be big enough (i.e. PAGE_SIZE).
706 * @type: One of the IIO_VAL_* constants. This decides how the val
707 * and val2 parameters are formatted.
708 * @size: Number of IIO value entries contained in vals
709 * @vals: Pointer to the values, exact meaning depends on the
713 * 0 by default, a negative number on failure or the total number of characters
714 * written for a type that belongs to the IIO_VAL_* constant.
716 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
720 len = __iio_format_value(buf, 0, type, size, vals);
721 if (len >= PAGE_SIZE - 1)
724 return len + sysfs_emit_at(buf, len, "\n");
726 EXPORT_SYMBOL_GPL(iio_format_value);
728 static ssize_t iio_read_channel_label(struct device *dev,
729 struct device_attribute *attr,
732 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
733 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
735 if (indio_dev->info->read_label)
736 return indio_dev->info->read_label(indio_dev, this_attr->c, buf);
738 if (this_attr->c->extend_name)
739 return sysfs_emit(buf, "%s\n", this_attr->c->extend_name);
744 static ssize_t iio_read_channel_info(struct device *dev,
745 struct device_attribute *attr,
748 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
749 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
750 int vals[INDIO_MAX_RAW_ELEMENTS];
754 if (indio_dev->info->read_raw_multi)
755 ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
756 INDIO_MAX_RAW_ELEMENTS,
760 ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
761 &vals[0], &vals[1], this_attr->address);
766 return iio_format_value(buf, ret, val_len, vals);
769 static ssize_t iio_format_list(char *buf, const int *vals, int type, int length,
770 const char *prefix, const char *suffix)
785 len = sysfs_emit(buf, prefix);
787 for (i = 0; i <= length - stride; i += stride) {
789 len += sysfs_emit_at(buf, len, " ");
790 if (len >= PAGE_SIZE)
794 len += __iio_format_value(buf, len, type, stride, &vals[i]);
795 if (len >= PAGE_SIZE)
799 len += sysfs_emit_at(buf, len, "%s\n", suffix);
804 static ssize_t iio_format_avail_list(char *buf, const int *vals,
805 int type, int length)
808 return iio_format_list(buf, vals, type, length, "", "");
811 static ssize_t iio_format_avail_range(char *buf, const int *vals, int type)
816 * length refers to the array size , not the number of elements.
817 * The purpose is to print the range [min , step ,max] so length should
818 * be 3 in case of int, and 6 for other types.
829 return iio_format_list(buf, vals, type, length, "[", "]");
832 static ssize_t iio_read_channel_info_avail(struct device *dev,
833 struct device_attribute *attr,
836 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
837 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
843 ret = indio_dev->info->read_avail(indio_dev, this_attr->c,
844 &vals, &type, &length,
851 return iio_format_avail_list(buf, vals, type, length);
852 case IIO_AVAIL_RANGE:
853 return iio_format_avail_range(buf, vals, type);
860 * __iio_str_to_fixpoint() - Parse a fixed-point number from a string
861 * @str: The string to parse
862 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
863 * @integer: The integer part of the number
864 * @fract: The fractional part of the number
865 * @scale_db: True if this should parse as dB
868 * 0 on success, or a negative error code if the string could not be parsed.
870 static int __iio_str_to_fixpoint(const char *str, int fract_mult,
871 int *integer, int *fract, bool scale_db)
874 bool integer_part = true, negative = false;
876 if (fract_mult == 0) {
879 return kstrtoint(str, 0, integer);
885 } else if (str[0] == '+') {
890 if ('0' <= *str && *str <= '9') {
892 i = i * 10 + *str - '0';
894 f += fract_mult * (*str - '0');
897 } else if (*str == '\n') {
898 if (*(str + 1) == '\0')
901 } else if (!strncmp(str, " dB", sizeof(" dB") - 1) && scale_db) {
902 /* Ignore the dB suffix */
903 str += sizeof(" dB") - 1;
905 } else if (!strncmp(str, "dB", sizeof("dB") - 1) && scale_db) {
906 /* Ignore the dB suffix */
907 str += sizeof("dB") - 1;
909 } else if (*str == '.' && integer_part) {
910 integer_part = false;
931 * iio_str_to_fixpoint() - Parse a fixed-point number from a string
932 * @str: The string to parse
933 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
934 * @integer: The integer part of the number
935 * @fract: The fractional part of the number
938 * 0 on success, or a negative error code if the string could not be parsed.
940 int iio_str_to_fixpoint(const char *str, int fract_mult,
941 int *integer, int *fract)
943 return __iio_str_to_fixpoint(str, fract_mult, integer, fract, false);
945 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
947 static ssize_t iio_write_channel_info(struct device *dev,
948 struct device_attribute *attr,
952 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
953 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
954 int ret, fract_mult = 100000;
955 int integer, fract = 0;
956 bool is_char = false;
957 bool scale_db = false;
959 /* Assumes decimal - precision based on number of digits */
960 if (!indio_dev->info->write_raw)
963 if (indio_dev->info->write_raw_get_fmt)
964 switch (indio_dev->info->write_raw_get_fmt(indio_dev,
965 this_attr->c, this_attr->address)) {
969 case IIO_VAL_INT_PLUS_MICRO_DB:
972 case IIO_VAL_INT_PLUS_MICRO:
975 case IIO_VAL_INT_PLUS_NANO:
976 fract_mult = 100000000;
988 if (sscanf(buf, "%c", &ch) != 1)
992 ret = __iio_str_to_fixpoint(buf, fract_mult, &integer, &fract,
998 ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
999 integer, fract, this_attr->address);
1007 int __iio_device_attr_init(struct device_attribute *dev_attr,
1008 const char *postfix,
1009 struct iio_chan_spec const *chan,
1010 ssize_t (*readfunc)(struct device *dev,
1011 struct device_attribute *attr,
1013 ssize_t (*writefunc)(struct device *dev,
1014 struct device_attribute *attr,
1017 enum iio_shared_by shared_by)
1023 sysfs_attr_init(&dev_attr->attr);
1025 /* Build up postfix of <extend_name>_<modifier>_postfix */
1026 if (chan->modified && (shared_by == IIO_SEPARATE)) {
1027 if (chan->extend_name)
1028 full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
1029 iio_modifier_names[chan->channel2],
1033 full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
1034 iio_modifier_names[chan->channel2],
1037 if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
1038 full_postfix = kstrdup(postfix, GFP_KERNEL);
1040 full_postfix = kasprintf(GFP_KERNEL,
1045 if (full_postfix == NULL)
1048 if (chan->differential) { /* Differential can not have modifier */
1049 switch (shared_by) {
1050 case IIO_SHARED_BY_ALL:
1051 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1053 case IIO_SHARED_BY_DIR:
1054 name = kasprintf(GFP_KERNEL, "%s_%s",
1055 iio_direction[chan->output],
1058 case IIO_SHARED_BY_TYPE:
1059 name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
1060 iio_direction[chan->output],
1061 iio_chan_type_name_spec[chan->type],
1062 iio_chan_type_name_spec[chan->type],
1066 if (!chan->indexed) {
1067 WARN(1, "Differential channels must be indexed\n");
1069 goto error_free_full_postfix;
1071 name = kasprintf(GFP_KERNEL,
1073 iio_direction[chan->output],
1074 iio_chan_type_name_spec[chan->type],
1076 iio_chan_type_name_spec[chan->type],
1081 } else { /* Single ended */
1082 switch (shared_by) {
1083 case IIO_SHARED_BY_ALL:
1084 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1086 case IIO_SHARED_BY_DIR:
1087 name = kasprintf(GFP_KERNEL, "%s_%s",
1088 iio_direction[chan->output],
1091 case IIO_SHARED_BY_TYPE:
1092 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1093 iio_direction[chan->output],
1094 iio_chan_type_name_spec[chan->type],
1100 name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
1101 iio_direction[chan->output],
1102 iio_chan_type_name_spec[chan->type],
1106 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1107 iio_direction[chan->output],
1108 iio_chan_type_name_spec[chan->type],
1115 goto error_free_full_postfix;
1117 dev_attr->attr.name = name;
1120 dev_attr->attr.mode |= 0444;
1121 dev_attr->show = readfunc;
1125 dev_attr->attr.mode |= 0200;
1126 dev_attr->store = writefunc;
1129 error_free_full_postfix:
1130 kfree(full_postfix);
1135 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
1137 kfree(dev_attr->attr.name);
1140 int __iio_add_chan_devattr(const char *postfix,
1141 struct iio_chan_spec const *chan,
1142 ssize_t (*readfunc)(struct device *dev,
1143 struct device_attribute *attr,
1145 ssize_t (*writefunc)(struct device *dev,
1146 struct device_attribute *attr,
1150 enum iio_shared_by shared_by,
1152 struct iio_buffer *buffer,
1153 struct list_head *attr_list)
1156 struct iio_dev_attr *iio_attr, *t;
1158 iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
1159 if (iio_attr == NULL)
1161 ret = __iio_device_attr_init(&iio_attr->dev_attr,
1163 readfunc, writefunc, shared_by);
1165 goto error_iio_dev_attr_free;
1167 iio_attr->address = mask;
1168 iio_attr->buffer = buffer;
1169 list_for_each_entry(t, attr_list, l)
1170 if (strcmp(t->dev_attr.attr.name,
1171 iio_attr->dev_attr.attr.name) == 0) {
1172 if (shared_by == IIO_SEPARATE)
1173 dev_err(dev, "tried to double register : %s\n",
1174 t->dev_attr.attr.name);
1176 goto error_device_attr_deinit;
1178 list_add(&iio_attr->l, attr_list);
1182 error_device_attr_deinit:
1183 __iio_device_attr_deinit(&iio_attr->dev_attr);
1184 error_iio_dev_attr_free:
1189 static int iio_device_add_channel_label(struct iio_dev *indio_dev,
1190 struct iio_chan_spec const *chan)
1192 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1195 if (!indio_dev->info->read_label && !chan->extend_name)
1198 ret = __iio_add_chan_devattr("label",
1200 &iio_read_channel_label,
1206 &iio_dev_opaque->channel_attr_list);
1213 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
1214 struct iio_chan_spec const *chan,
1215 enum iio_shared_by shared_by,
1216 const long *infomask)
1218 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1219 int i, ret, attrcount = 0;
1221 for_each_set_bit(i, infomask, sizeof(*infomask)*8) {
1222 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1224 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
1226 &iio_read_channel_info,
1227 &iio_write_channel_info,
1232 &iio_dev_opaque->channel_attr_list);
1233 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1243 static int iio_device_add_info_mask_type_avail(struct iio_dev *indio_dev,
1244 struct iio_chan_spec const *chan,
1245 enum iio_shared_by shared_by,
1246 const long *infomask)
1248 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1249 int i, ret, attrcount = 0;
1250 char *avail_postfix;
1252 for_each_set_bit(i, infomask, sizeof(*infomask) * 8) {
1253 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1255 avail_postfix = kasprintf(GFP_KERNEL,
1257 iio_chan_info_postfix[i]);
1261 ret = __iio_add_chan_devattr(avail_postfix,
1263 &iio_read_channel_info_avail,
1269 &iio_dev_opaque->channel_attr_list);
1270 kfree(avail_postfix);
1271 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1281 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
1282 struct iio_chan_spec const *chan)
1284 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1285 int ret, attrcount = 0;
1286 const struct iio_chan_spec_ext_info *ext_info;
1288 if (chan->channel < 0)
1290 ret = iio_device_add_info_mask_type(indio_dev, chan,
1292 &chan->info_mask_separate);
1297 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1299 &chan->info_mask_separate_available);
1304 ret = iio_device_add_info_mask_type(indio_dev, chan,
1306 &chan->info_mask_shared_by_type);
1311 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1313 &chan->info_mask_shared_by_type_available);
1318 ret = iio_device_add_info_mask_type(indio_dev, chan,
1320 &chan->info_mask_shared_by_dir);
1325 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1327 &chan->info_mask_shared_by_dir_available);
1332 ret = iio_device_add_info_mask_type(indio_dev, chan,
1334 &chan->info_mask_shared_by_all);
1339 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1341 &chan->info_mask_shared_by_all_available);
1346 ret = iio_device_add_channel_label(indio_dev, chan);
1351 if (chan->ext_info) {
1354 for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
1355 ret = __iio_add_chan_devattr(ext_info->name,
1358 &iio_read_channel_ext_info : NULL,
1360 &iio_write_channel_ext_info : NULL,
1365 &iio_dev_opaque->channel_attr_list);
1367 if (ret == -EBUSY && ext_info->shared)
1381 * iio_free_chan_devattr_list() - Free a list of IIO device attributes
1382 * @attr_list: List of IIO device attributes
1384 * This function frees the memory allocated for each of the IIO device
1385 * attributes in the list.
1387 void iio_free_chan_devattr_list(struct list_head *attr_list)
1389 struct iio_dev_attr *p, *n;
1391 list_for_each_entry_safe(p, n, attr_list, l) {
1392 kfree_const(p->dev_attr.attr.name);
1398 static ssize_t name_show(struct device *dev, struct device_attribute *attr,
1401 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1403 return sysfs_emit(buf, "%s\n", indio_dev->name);
1406 static DEVICE_ATTR_RO(name);
1408 static ssize_t label_show(struct device *dev, struct device_attribute *attr,
1411 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1413 return sysfs_emit(buf, "%s\n", indio_dev->label);
1416 static DEVICE_ATTR_RO(label);
1418 static const char * const clock_names[] = {
1419 [CLOCK_REALTIME] = "realtime",
1420 [CLOCK_MONOTONIC] = "monotonic",
1421 [CLOCK_PROCESS_CPUTIME_ID] = "process_cputime_id",
1422 [CLOCK_THREAD_CPUTIME_ID] = "thread_cputime_id",
1423 [CLOCK_MONOTONIC_RAW] = "monotonic_raw",
1424 [CLOCK_REALTIME_COARSE] = "realtime_coarse",
1425 [CLOCK_MONOTONIC_COARSE] = "monotonic_coarse",
1426 [CLOCK_BOOTTIME] = "boottime",
1427 [CLOCK_REALTIME_ALARM] = "realtime_alarm",
1428 [CLOCK_BOOTTIME_ALARM] = "boottime_alarm",
1429 [CLOCK_SGI_CYCLE] = "sgi_cycle",
1430 [CLOCK_TAI] = "tai",
1433 static ssize_t current_timestamp_clock_show(struct device *dev,
1434 struct device_attribute *attr,
1437 const struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1438 const clockid_t clk = iio_device_get_clock(indio_dev);
1441 case CLOCK_REALTIME:
1442 case CLOCK_MONOTONIC:
1443 case CLOCK_MONOTONIC_RAW:
1444 case CLOCK_REALTIME_COARSE:
1445 case CLOCK_MONOTONIC_COARSE:
1446 case CLOCK_BOOTTIME:
1453 return sysfs_emit(buf, "%s\n", clock_names[clk]);
1456 static ssize_t current_timestamp_clock_store(struct device *dev,
1457 struct device_attribute *attr,
1458 const char *buf, size_t len)
1463 ret = sysfs_match_string(clock_names, buf);
1469 case CLOCK_REALTIME:
1470 case CLOCK_MONOTONIC:
1471 case CLOCK_MONOTONIC_RAW:
1472 case CLOCK_REALTIME_COARSE:
1473 case CLOCK_MONOTONIC_COARSE:
1474 case CLOCK_BOOTTIME:
1481 ret = iio_device_set_clock(dev_to_iio_dev(dev), clk);
1488 int iio_device_register_sysfs_group(struct iio_dev *indio_dev,
1489 const struct attribute_group *group)
1491 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1492 const struct attribute_group **new, **old = iio_dev_opaque->groups;
1493 unsigned int cnt = iio_dev_opaque->groupcounter;
1495 new = krealloc_array(old, cnt + 2, sizeof(*new), GFP_KERNEL);
1499 new[iio_dev_opaque->groupcounter++] = group;
1500 new[iio_dev_opaque->groupcounter] = NULL;
1502 iio_dev_opaque->groups = new;
1507 static DEVICE_ATTR_RW(current_timestamp_clock);
1509 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
1511 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1512 int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
1513 struct iio_dev_attr *p;
1514 struct attribute **attr, *clk = NULL;
1516 /* First count elements in any existing group */
1517 if (indio_dev->info->attrs) {
1518 attr = indio_dev->info->attrs->attrs;
1519 while (*attr++ != NULL)
1522 attrcount = attrcount_orig;
1524 * New channel registration method - relies on the fact a group does
1525 * not need to be initialized if its name is NULL.
1527 if (indio_dev->channels)
1528 for (i = 0; i < indio_dev->num_channels; i++) {
1529 const struct iio_chan_spec *chan =
1530 &indio_dev->channels[i];
1532 if (chan->type == IIO_TIMESTAMP)
1533 clk = &dev_attr_current_timestamp_clock.attr;
1535 ret = iio_device_add_channel_sysfs(indio_dev, chan);
1537 goto error_clear_attrs;
1541 if (iio_dev_opaque->event_interface)
1542 clk = &dev_attr_current_timestamp_clock.attr;
1544 if (indio_dev->name)
1546 if (indio_dev->label)
1551 iio_dev_opaque->chan_attr_group.attrs =
1552 kcalloc(attrcount + 1,
1553 sizeof(iio_dev_opaque->chan_attr_group.attrs[0]),
1555 if (iio_dev_opaque->chan_attr_group.attrs == NULL) {
1557 goto error_clear_attrs;
1559 /* Copy across original attributes, and point to original binary attributes */
1560 if (indio_dev->info->attrs) {
1561 memcpy(iio_dev_opaque->chan_attr_group.attrs,
1562 indio_dev->info->attrs->attrs,
1563 sizeof(iio_dev_opaque->chan_attr_group.attrs[0])
1565 iio_dev_opaque->chan_attr_group.is_visible =
1566 indio_dev->info->attrs->is_visible;
1567 iio_dev_opaque->chan_attr_group.bin_attrs =
1568 indio_dev->info->attrs->bin_attrs;
1570 attrn = attrcount_orig;
1571 /* Add all elements from the list. */
1572 list_for_each_entry(p, &iio_dev_opaque->channel_attr_list, l)
1573 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1574 if (indio_dev->name)
1575 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
1576 if (indio_dev->label)
1577 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_label.attr;
1579 iio_dev_opaque->chan_attr_group.attrs[attrn++] = clk;
1581 ret = iio_device_register_sysfs_group(indio_dev,
1582 &iio_dev_opaque->chan_attr_group);
1584 goto error_clear_attrs;
1589 iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1594 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
1596 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1598 iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1599 kfree(iio_dev_opaque->chan_attr_group.attrs);
1600 iio_dev_opaque->chan_attr_group.attrs = NULL;
1601 kfree(iio_dev_opaque->groups);
1602 iio_dev_opaque->groups = NULL;
1605 static void iio_dev_release(struct device *device)
1607 struct iio_dev *indio_dev = dev_to_iio_dev(device);
1608 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1610 if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1611 iio_device_unregister_trigger_consumer(indio_dev);
1612 iio_device_unregister_eventset(indio_dev);
1613 iio_device_unregister_sysfs(indio_dev);
1615 iio_device_detach_buffers(indio_dev);
1617 lockdep_unregister_key(&iio_dev_opaque->mlock_key);
1619 ida_free(&iio_ida, iio_dev_opaque->id);
1620 kfree(iio_dev_opaque);
1623 const struct device_type iio_device_type = {
1624 .name = "iio_device",
1625 .release = iio_dev_release,
1629 * iio_device_alloc() - allocate an iio_dev from a driver
1630 * @parent: Parent device.
1631 * @sizeof_priv: Space to allocate for private structure.
1634 * Pointer to allocated iio_dev on success, NULL on failure.
1636 struct iio_dev *iio_device_alloc(struct device *parent, int sizeof_priv)
1638 struct iio_dev_opaque *iio_dev_opaque;
1639 struct iio_dev *indio_dev;
1642 alloc_size = sizeof(struct iio_dev_opaque);
1644 alloc_size = ALIGN(alloc_size, IIO_DMA_MINALIGN);
1645 alloc_size += sizeof_priv;
1648 iio_dev_opaque = kzalloc(alloc_size, GFP_KERNEL);
1649 if (!iio_dev_opaque)
1652 indio_dev = &iio_dev_opaque->indio_dev;
1653 indio_dev->priv = (char *)iio_dev_opaque +
1654 ALIGN(sizeof(struct iio_dev_opaque), IIO_DMA_MINALIGN);
1656 indio_dev->dev.parent = parent;
1657 indio_dev->dev.type = &iio_device_type;
1658 indio_dev->dev.bus = &iio_bus_type;
1659 device_initialize(&indio_dev->dev);
1660 mutex_init(&iio_dev_opaque->mlock);
1661 mutex_init(&iio_dev_opaque->info_exist_lock);
1662 INIT_LIST_HEAD(&iio_dev_opaque->channel_attr_list);
1664 iio_dev_opaque->id = ida_alloc(&iio_ida, GFP_KERNEL);
1665 if (iio_dev_opaque->id < 0) {
1666 /* cannot use a dev_err as the name isn't available */
1667 pr_err("failed to get device id\n");
1668 kfree(iio_dev_opaque);
1672 if (dev_set_name(&indio_dev->dev, "iio:device%d", iio_dev_opaque->id)) {
1673 ida_free(&iio_ida, iio_dev_opaque->id);
1674 kfree(iio_dev_opaque);
1678 INIT_LIST_HEAD(&iio_dev_opaque->buffer_list);
1679 INIT_LIST_HEAD(&iio_dev_opaque->ioctl_handlers);
1681 lockdep_register_key(&iio_dev_opaque->mlock_key);
1682 lockdep_set_class(&iio_dev_opaque->mlock, &iio_dev_opaque->mlock_key);
1686 EXPORT_SYMBOL(iio_device_alloc);
1689 * iio_device_free() - free an iio_dev from a driver
1690 * @dev: the iio_dev associated with the device
1692 void iio_device_free(struct iio_dev *dev)
1695 put_device(&dev->dev);
1697 EXPORT_SYMBOL(iio_device_free);
1699 static void devm_iio_device_release(void *iio_dev)
1701 iio_device_free(iio_dev);
1705 * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1706 * @parent: Device to allocate iio_dev for, and parent for this IIO device
1707 * @sizeof_priv: Space to allocate for private structure.
1709 * Managed iio_device_alloc. iio_dev allocated with this function is
1710 * automatically freed on driver detach.
1713 * Pointer to allocated iio_dev on success, NULL on failure.
1715 struct iio_dev *devm_iio_device_alloc(struct device *parent, int sizeof_priv)
1717 struct iio_dev *iio_dev;
1720 iio_dev = iio_device_alloc(parent, sizeof_priv);
1724 ret = devm_add_action_or_reset(parent, devm_iio_device_release,
1731 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1734 * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1735 * @inode: Inode structure for identifying the device in the file system
1736 * @filp: File structure for iio device used to keep and later access
1739 * Returns: 0 on success or -EBUSY if the device is already opened
1741 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1743 struct iio_dev_opaque *iio_dev_opaque =
1744 container_of(inode->i_cdev, struct iio_dev_opaque, chrdev);
1745 struct iio_dev *indio_dev = &iio_dev_opaque->indio_dev;
1746 struct iio_dev_buffer_pair *ib;
1748 if (test_and_set_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags))
1751 iio_device_get(indio_dev);
1753 ib = kmalloc(sizeof(*ib), GFP_KERNEL);
1755 iio_device_put(indio_dev);
1756 clear_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags);
1760 ib->indio_dev = indio_dev;
1761 ib->buffer = indio_dev->buffer;
1763 filp->private_data = ib;
1769 * iio_chrdev_release() - chrdev file close buffer access and ioctls
1770 * @inode: Inode structure pointer for the char device
1771 * @filp: File structure pointer for the char device
1773 * Returns: 0 for successful release.
1775 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1777 struct iio_dev_buffer_pair *ib = filp->private_data;
1778 struct iio_dev_opaque *iio_dev_opaque =
1779 container_of(inode->i_cdev, struct iio_dev_opaque, chrdev);
1780 struct iio_dev *indio_dev = &iio_dev_opaque->indio_dev;
1783 clear_bit(IIO_BUSY_BIT_POS, &iio_dev_opaque->flags);
1784 iio_device_put(indio_dev);
1789 void iio_device_ioctl_handler_register(struct iio_dev *indio_dev,
1790 struct iio_ioctl_handler *h)
1792 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1794 list_add_tail(&h->entry, &iio_dev_opaque->ioctl_handlers);
1797 void iio_device_ioctl_handler_unregister(struct iio_ioctl_handler *h)
1799 list_del(&h->entry);
1802 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1804 struct iio_dev_buffer_pair *ib = filp->private_data;
1805 struct iio_dev *indio_dev = ib->indio_dev;
1806 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1807 struct iio_ioctl_handler *h;
1810 mutex_lock(&iio_dev_opaque->info_exist_lock);
1813 * The NULL check here is required to prevent crashing when a device
1814 * is being removed while userspace would still have open file handles
1815 * to try to access this device.
1817 if (!indio_dev->info)
1820 list_for_each_entry(h, &iio_dev_opaque->ioctl_handlers, entry) {
1821 ret = h->ioctl(indio_dev, filp, cmd, arg);
1822 if (ret != IIO_IOCTL_UNHANDLED)
1826 if (ret == IIO_IOCTL_UNHANDLED)
1830 mutex_unlock(&iio_dev_opaque->info_exist_lock);
1835 static const struct file_operations iio_buffer_fileops = {
1836 .owner = THIS_MODULE,
1837 .llseek = noop_llseek,
1838 .read = iio_buffer_read_outer_addr,
1839 .write = iio_buffer_write_outer_addr,
1840 .poll = iio_buffer_poll_addr,
1841 .unlocked_ioctl = iio_ioctl,
1842 .compat_ioctl = compat_ptr_ioctl,
1843 .open = iio_chrdev_open,
1844 .release = iio_chrdev_release,
1847 static const struct file_operations iio_event_fileops = {
1848 .owner = THIS_MODULE,
1849 .llseek = noop_llseek,
1850 .unlocked_ioctl = iio_ioctl,
1851 .compat_ioctl = compat_ptr_ioctl,
1852 .open = iio_chrdev_open,
1853 .release = iio_chrdev_release,
1856 static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1859 const struct iio_chan_spec *channels = indio_dev->channels;
1861 if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1864 for (i = 0; i < indio_dev->num_channels - 1; i++) {
1865 if (channels[i].scan_index < 0)
1867 for (j = i + 1; j < indio_dev->num_channels; j++)
1868 if (channels[i].scan_index == channels[j].scan_index) {
1869 dev_err(&indio_dev->dev,
1870 "Duplicate scan index %d\n",
1871 channels[i].scan_index);
1879 static int iio_check_extended_name(const struct iio_dev *indio_dev)
1883 if (!indio_dev->info->read_label)
1886 for (i = 0; i < indio_dev->num_channels; i++) {
1887 if (indio_dev->channels[i].extend_name) {
1888 dev_err(&indio_dev->dev,
1889 "Cannot use labels and extend_name at the same time\n");
1897 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1899 int __iio_device_register(struct iio_dev *indio_dev, struct module *this_mod)
1901 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1902 struct fwnode_handle *fwnode = NULL;
1905 if (!indio_dev->info)
1908 iio_dev_opaque->driver_module = this_mod;
1910 /* If the calling driver did not initialize firmware node, do it here */
1911 if (dev_fwnode(&indio_dev->dev))
1912 fwnode = dev_fwnode(&indio_dev->dev);
1913 /* The default dummy IIO device has no parent */
1914 else if (indio_dev->dev.parent)
1915 fwnode = dev_fwnode(indio_dev->dev.parent);
1916 device_set_node(&indio_dev->dev, fwnode);
1918 fwnode_property_read_string(fwnode, "label", &indio_dev->label);
1920 ret = iio_check_unique_scan_index(indio_dev);
1924 ret = iio_check_extended_name(indio_dev);
1928 iio_device_register_debugfs(indio_dev);
1930 ret = iio_buffers_alloc_sysfs_and_mask(indio_dev);
1932 dev_err(indio_dev->dev.parent,
1933 "Failed to create buffer sysfs interfaces\n");
1934 goto error_unreg_debugfs;
1937 ret = iio_device_register_sysfs(indio_dev);
1939 dev_err(indio_dev->dev.parent,
1940 "Failed to register sysfs interfaces\n");
1941 goto error_buffer_free_sysfs;
1943 ret = iio_device_register_eventset(indio_dev);
1945 dev_err(indio_dev->dev.parent,
1946 "Failed to register event set\n");
1947 goto error_free_sysfs;
1949 if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1950 iio_device_register_trigger_consumer(indio_dev);
1952 if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1953 indio_dev->setup_ops == NULL)
1954 indio_dev->setup_ops = &noop_ring_setup_ops;
1956 if (iio_dev_opaque->attached_buffers_cnt)
1957 cdev_init(&iio_dev_opaque->chrdev, &iio_buffer_fileops);
1958 else if (iio_dev_opaque->event_interface)
1959 cdev_init(&iio_dev_opaque->chrdev, &iio_event_fileops);
1961 if (iio_dev_opaque->attached_buffers_cnt || iio_dev_opaque->event_interface) {
1962 indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), iio_dev_opaque->id);
1963 iio_dev_opaque->chrdev.owner = this_mod;
1966 /* assign device groups now; they should be all registered now */
1967 indio_dev->dev.groups = iio_dev_opaque->groups;
1969 ret = cdev_device_add(&iio_dev_opaque->chrdev, &indio_dev->dev);
1971 goto error_unreg_eventset;
1975 error_unreg_eventset:
1976 iio_device_unregister_eventset(indio_dev);
1978 iio_device_unregister_sysfs(indio_dev);
1979 error_buffer_free_sysfs:
1980 iio_buffers_free_sysfs_and_mask(indio_dev);
1981 error_unreg_debugfs:
1982 iio_device_unregister_debugfs(indio_dev);
1985 EXPORT_SYMBOL(__iio_device_register);
1988 * iio_device_unregister() - unregister a device from the IIO subsystem
1989 * @indio_dev: Device structure representing the device.
1991 void iio_device_unregister(struct iio_dev *indio_dev)
1993 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1995 cdev_device_del(&iio_dev_opaque->chrdev, &indio_dev->dev);
1997 mutex_lock(&iio_dev_opaque->info_exist_lock);
1999 iio_device_unregister_debugfs(indio_dev);
2001 iio_disable_all_buffers(indio_dev);
2003 indio_dev->info = NULL;
2005 iio_device_wakeup_eventset(indio_dev);
2006 iio_buffer_wakeup_poll(indio_dev);
2008 mutex_unlock(&iio_dev_opaque->info_exist_lock);
2010 iio_buffers_free_sysfs_and_mask(indio_dev);
2012 EXPORT_SYMBOL(iio_device_unregister);
2014 static void devm_iio_device_unreg(void *indio_dev)
2016 iio_device_unregister(indio_dev);
2019 int __devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev,
2020 struct module *this_mod)
2024 ret = __iio_device_register(indio_dev, this_mod);
2028 return devm_add_action_or_reset(dev, devm_iio_device_unreg, indio_dev);
2030 EXPORT_SYMBOL_GPL(__devm_iio_device_register);
2033 * iio_device_claim_direct_mode - Keep device in direct mode
2034 * @indio_dev: the iio_dev associated with the device
2036 * If the device is in direct mode it is guaranteed to stay
2037 * that way until iio_device_release_direct_mode() is called.
2039 * Use with iio_device_release_direct_mode()
2041 * Returns: 0 on success, -EBUSY on failure.
2043 int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
2045 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2047 mutex_lock(&iio_dev_opaque->mlock);
2049 if (iio_buffer_enabled(indio_dev)) {
2050 mutex_unlock(&iio_dev_opaque->mlock);
2055 EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
2058 * iio_device_release_direct_mode - releases claim on direct mode
2059 * @indio_dev: the iio_dev associated with the device
2061 * Release the claim. Device is no longer guaranteed to stay
2064 * Use with iio_device_claim_direct_mode()
2066 void iio_device_release_direct_mode(struct iio_dev *indio_dev)
2068 mutex_unlock(&to_iio_dev_opaque(indio_dev)->mlock);
2070 EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
2073 * iio_device_claim_buffer_mode - Keep device in buffer mode
2074 * @indio_dev: the iio_dev associated with the device
2076 * If the device is in buffer mode it is guaranteed to stay
2077 * that way until iio_device_release_buffer_mode() is called.
2079 * Use with iio_device_release_buffer_mode().
2081 * Returns: 0 on success, -EBUSY on failure.
2083 int iio_device_claim_buffer_mode(struct iio_dev *indio_dev)
2085 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2087 mutex_lock(&iio_dev_opaque->mlock);
2089 if (iio_buffer_enabled(indio_dev))
2092 mutex_unlock(&iio_dev_opaque->mlock);
2095 EXPORT_SYMBOL_GPL(iio_device_claim_buffer_mode);
2098 * iio_device_release_buffer_mode - releases claim on buffer mode
2099 * @indio_dev: the iio_dev associated with the device
2101 * Release the claim. Device is no longer guaranteed to stay
2104 * Use with iio_device_claim_buffer_mode().
2106 void iio_device_release_buffer_mode(struct iio_dev *indio_dev)
2108 mutex_unlock(&to_iio_dev_opaque(indio_dev)->mlock);
2110 EXPORT_SYMBOL_GPL(iio_device_release_buffer_mode);
2113 * iio_device_get_current_mode() - helper function providing read-only access to
2114 * the opaque @currentmode variable
2115 * @indio_dev: IIO device structure for device
2117 int iio_device_get_current_mode(struct iio_dev *indio_dev)
2119 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
2121 return iio_dev_opaque->currentmode;
2123 EXPORT_SYMBOL_GPL(iio_device_get_current_mode);
2125 subsys_initcall(iio_init);
2126 module_exit(iio_exit);
2129 MODULE_DESCRIPTION("Industrial I/O core");
2130 MODULE_LICENSE("GPL");