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",
174 * iio_sysfs_match_string_with_gaps - matches given string in an array with gaps
175 * @array: array of strings
176 * @n: number of strings in the array
177 * @str: string to match with
179 * Returns index of @str in the @array or -EINVAL, similar to match_string().
180 * Uses sysfs_streq instead of strcmp for matching.
182 * This routine will look for a string in an array of strings.
183 * The search will continue until the element is found or the n-th element
184 * is reached, regardless of any NULL elements in the array.
186 static int iio_sysfs_match_string_with_gaps(const char * const *array, size_t n,
192 for (index = 0; index < n; index++) {
196 if (sysfs_streq(item, str))
203 #if defined(CONFIG_DEBUG_FS)
205 * There's also a CONFIG_DEBUG_FS guard in include/linux/iio/iio.h for
206 * iio_get_debugfs_dentry() to make it inline if CONFIG_DEBUG_FS is undefined
208 struct dentry *iio_get_debugfs_dentry(struct iio_dev *indio_dev)
210 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
211 return iio_dev_opaque->debugfs_dentry;
213 EXPORT_SYMBOL_GPL(iio_get_debugfs_dentry);
217 * iio_find_channel_from_si() - get channel from its scan index
219 * @si: scan index to match
221 const struct iio_chan_spec
222 *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
226 for (i = 0; i < indio_dev->num_channels; i++)
227 if (indio_dev->channels[i].scan_index == si)
228 return &indio_dev->channels[i];
232 /* This turns up an awful lot */
233 ssize_t iio_read_const_attr(struct device *dev,
234 struct device_attribute *attr,
237 return sysfs_emit(buf, "%s\n", to_iio_const_attr(attr)->string);
239 EXPORT_SYMBOL(iio_read_const_attr);
242 * iio_device_set_clock() - Set current timestamping clock for the device
243 * @indio_dev: IIO device structure containing the device
244 * @clock_id: timestamping clock posix identifier to set.
246 int iio_device_set_clock(struct iio_dev *indio_dev, clockid_t clock_id)
249 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
250 const struct iio_event_interface *ev_int = iio_dev_opaque->event_interface;
252 ret = mutex_lock_interruptible(&indio_dev->mlock);
255 if ((ev_int && iio_event_enabled(ev_int)) ||
256 iio_buffer_enabled(indio_dev)) {
257 mutex_unlock(&indio_dev->mlock);
260 indio_dev->clock_id = clock_id;
261 mutex_unlock(&indio_dev->mlock);
265 EXPORT_SYMBOL(iio_device_set_clock);
268 * iio_get_time_ns() - utility function to get a time stamp for events etc
271 s64 iio_get_time_ns(const struct iio_dev *indio_dev)
273 struct timespec64 tp;
275 switch (iio_device_get_clock(indio_dev)) {
277 return ktime_get_real_ns();
278 case CLOCK_MONOTONIC:
279 return ktime_get_ns();
280 case CLOCK_MONOTONIC_RAW:
281 return ktime_get_raw_ns();
282 case CLOCK_REALTIME_COARSE:
283 return ktime_to_ns(ktime_get_coarse_real());
284 case CLOCK_MONOTONIC_COARSE:
285 ktime_get_coarse_ts64(&tp);
286 return timespec64_to_ns(&tp);
288 return ktime_get_boottime_ns();
290 return ktime_get_clocktai_ns();
295 EXPORT_SYMBOL(iio_get_time_ns);
298 * iio_get_time_res() - utility function to get time stamp clock resolution in
302 unsigned int iio_get_time_res(const struct iio_dev *indio_dev)
304 switch (iio_device_get_clock(indio_dev)) {
306 case CLOCK_MONOTONIC:
307 case CLOCK_MONOTONIC_RAW:
310 return hrtimer_resolution;
311 case CLOCK_REALTIME_COARSE:
312 case CLOCK_MONOTONIC_COARSE:
318 EXPORT_SYMBOL(iio_get_time_res);
320 static int __init iio_init(void)
324 /* Register sysfs bus */
325 ret = bus_register(&iio_bus_type);
327 pr_err("could not register bus type\n");
331 ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
333 pr_err("failed to allocate char dev region\n");
334 goto error_unregister_bus_type;
337 iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
341 error_unregister_bus_type:
342 bus_unregister(&iio_bus_type);
347 static void __exit iio_exit(void)
350 unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
351 bus_unregister(&iio_bus_type);
352 debugfs_remove(iio_debugfs_dentry);
355 #if defined(CONFIG_DEBUG_FS)
356 static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
357 size_t count, loff_t *ppos)
359 struct iio_dev *indio_dev = file->private_data;
360 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
365 return simple_read_from_buffer(userbuf, count, ppos,
366 iio_dev_opaque->read_buf,
367 iio_dev_opaque->read_buf_len);
369 ret = indio_dev->info->debugfs_reg_access(indio_dev,
370 iio_dev_opaque->cached_reg_addr,
373 dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
377 iio_dev_opaque->read_buf_len = snprintf(iio_dev_opaque->read_buf,
378 sizeof(iio_dev_opaque->read_buf),
381 return simple_read_from_buffer(userbuf, count, ppos,
382 iio_dev_opaque->read_buf,
383 iio_dev_opaque->read_buf_len);
386 static ssize_t iio_debugfs_write_reg(struct file *file,
387 const char __user *userbuf, size_t count, loff_t *ppos)
389 struct iio_dev *indio_dev = file->private_data;
390 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
395 count = min_t(size_t, count, (sizeof(buf)-1));
396 if (copy_from_user(buf, userbuf, count))
401 ret = sscanf(buf, "%i %i", ®, &val);
405 iio_dev_opaque->cached_reg_addr = reg;
408 iio_dev_opaque->cached_reg_addr = reg;
409 ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
412 dev_err(indio_dev->dev.parent, "%s: write failed\n",
424 static const struct file_operations iio_debugfs_reg_fops = {
426 .read = iio_debugfs_read_reg,
427 .write = iio_debugfs_write_reg,
430 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
432 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
433 debugfs_remove_recursive(iio_dev_opaque->debugfs_dentry);
436 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
438 struct iio_dev_opaque *iio_dev_opaque;
440 if (indio_dev->info->debugfs_reg_access == NULL)
443 if (!iio_debugfs_dentry)
446 iio_dev_opaque = to_iio_dev_opaque(indio_dev);
448 iio_dev_opaque->debugfs_dentry =
449 debugfs_create_dir(dev_name(&indio_dev->dev),
452 debugfs_create_file("direct_reg_access", 0644,
453 iio_dev_opaque->debugfs_dentry, indio_dev,
454 &iio_debugfs_reg_fops);
457 static void iio_device_register_debugfs(struct iio_dev *indio_dev)
461 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
464 #endif /* CONFIG_DEBUG_FS */
466 static ssize_t iio_read_channel_ext_info(struct device *dev,
467 struct device_attribute *attr,
470 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
471 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
472 const struct iio_chan_spec_ext_info *ext_info;
474 ext_info = &this_attr->c->ext_info[this_attr->address];
476 return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
479 static ssize_t iio_write_channel_ext_info(struct device *dev,
480 struct device_attribute *attr,
484 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
485 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
486 const struct iio_chan_spec_ext_info *ext_info;
488 ext_info = &this_attr->c->ext_info[this_attr->address];
490 return ext_info->write(indio_dev, ext_info->private,
491 this_attr->c, buf, len);
494 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
495 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
497 const struct iio_enum *e = (const struct iio_enum *)priv;
504 for (i = 0; i < e->num_items; ++i) {
507 len += sysfs_emit_at(buf, len, "%s ", e->items[i]);
510 /* replace last space with a newline */
515 EXPORT_SYMBOL_GPL(iio_enum_available_read);
517 ssize_t iio_enum_read(struct iio_dev *indio_dev,
518 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
520 const struct iio_enum *e = (const struct iio_enum *)priv;
526 i = e->get(indio_dev, chan);
529 else if (i >= e->num_items || !e->items[i])
532 return sysfs_emit(buf, "%s\n", e->items[i]);
534 EXPORT_SYMBOL_GPL(iio_enum_read);
536 ssize_t iio_enum_write(struct iio_dev *indio_dev,
537 uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
540 const struct iio_enum *e = (const struct iio_enum *)priv;
546 ret = iio_sysfs_match_string_with_gaps(e->items, e->num_items, buf);
550 ret = e->set(indio_dev, chan, ret);
551 return ret ? ret : len;
553 EXPORT_SYMBOL_GPL(iio_enum_write);
555 static const struct iio_mount_matrix iio_mount_idmatrix = {
563 static int iio_setup_mount_idmatrix(const struct device *dev,
564 struct iio_mount_matrix *matrix)
566 *matrix = iio_mount_idmatrix;
567 dev_info(dev, "mounting matrix not found: using identity...\n");
571 ssize_t iio_show_mount_matrix(struct iio_dev *indio_dev, uintptr_t priv,
572 const struct iio_chan_spec *chan, char *buf)
574 const struct iio_mount_matrix *mtx = ((iio_get_mount_matrix_t *)
575 priv)(indio_dev, chan);
581 mtx = &iio_mount_idmatrix;
583 return sysfs_emit(buf, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
584 mtx->rotation[0], mtx->rotation[1], mtx->rotation[2],
585 mtx->rotation[3], mtx->rotation[4], mtx->rotation[5],
586 mtx->rotation[6], mtx->rotation[7], mtx->rotation[8]);
588 EXPORT_SYMBOL_GPL(iio_show_mount_matrix);
591 * iio_read_mount_matrix() - retrieve iio device mounting matrix from
592 * device "mount-matrix" property
593 * @dev: device the mounting matrix property is assigned to
594 * @propname: device specific mounting matrix property name
595 * @matrix: where to store retrieved matrix
597 * If device is assigned no mounting matrix property, a default 3x3 identity
598 * matrix will be filled in.
600 * Return: 0 if success, or a negative error code on failure.
602 int iio_read_mount_matrix(struct device *dev, const char *propname,
603 struct iio_mount_matrix *matrix)
605 size_t len = ARRAY_SIZE(iio_mount_idmatrix.rotation);
608 err = device_property_read_string_array(dev, propname,
609 matrix->rotation, len);
614 /* Invalid number of matrix entries. */
618 /* Invalid matrix declaration format. */
621 /* Matrix was not declared at all: fallback to identity. */
622 return iio_setup_mount_idmatrix(dev, matrix);
624 EXPORT_SYMBOL(iio_read_mount_matrix);
626 static ssize_t __iio_format_value(char *buf, size_t offset, unsigned int type,
627 int size, const int *vals)
631 bool scale_db = false;
635 return sysfs_emit_at(buf, offset, "%d", vals[0]);
636 case IIO_VAL_INT_PLUS_MICRO_DB:
639 case IIO_VAL_INT_PLUS_MICRO:
641 return sysfs_emit_at(buf, offset, "-%d.%06u%s",
642 abs(vals[0]), -vals[1],
643 scale_db ? " dB" : "");
645 return sysfs_emit_at(buf, offset, "%d.%06u%s", vals[0],
646 vals[1], scale_db ? " dB" : "");
647 case IIO_VAL_INT_PLUS_NANO:
649 return sysfs_emit_at(buf, offset, "-%d.%09u",
650 abs(vals[0]), -vals[1]);
652 return sysfs_emit_at(buf, offset, "%d.%09u", vals[0],
654 case IIO_VAL_FRACTIONAL:
655 tmp2 = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
657 tmp0 = (int)div_s64_rem(tmp2, 1000000000, &tmp1);
658 if ((tmp2 < 0) && (tmp0 == 0))
659 return sysfs_emit_at(buf, offset, "-0.%09u", abs(tmp1));
661 return sysfs_emit_at(buf, offset, "%d.%09u", tmp0,
663 case IIO_VAL_FRACTIONAL_LOG2:
664 tmp2 = shift_right((s64)vals[0] * 1000000000LL, vals[1]);
665 tmp0 = (int)div_s64_rem(tmp2, 1000000000LL, &tmp1);
666 if (tmp0 == 0 && tmp2 < 0)
667 return sysfs_emit_at(buf, offset, "-0.%09u", abs(tmp1));
669 return sysfs_emit_at(buf, offset, "%d.%09u", tmp0,
671 case IIO_VAL_INT_MULTIPLE:
676 for (i = 0; i < size; ++i)
677 l += sysfs_emit_at(buf, offset + l, "%d ", vals[i]);
681 return sysfs_emit_at(buf, offset, "%c", (char)vals[0]);
688 * iio_format_value() - Formats a IIO value into its string representation
689 * @buf: The buffer to which the formatted value gets written
690 * which is assumed to be big enough (i.e. PAGE_SIZE).
691 * @type: One of the IIO_VAL_* constants. This decides how the val
692 * and val2 parameters are formatted.
693 * @size: Number of IIO value entries contained in vals
694 * @vals: Pointer to the values, exact meaning depends on the
697 * Return: 0 by default, a negative number on failure or the
698 * total number of characters written for a type that belongs
699 * to the IIO_VAL_* constant.
701 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
705 len = __iio_format_value(buf, 0, type, size, vals);
706 if (len >= PAGE_SIZE - 1)
709 return len + sysfs_emit_at(buf, len, "\n");
711 EXPORT_SYMBOL_GPL(iio_format_value);
713 static ssize_t iio_read_channel_label(struct device *dev,
714 struct device_attribute *attr,
717 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
718 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
720 if (!indio_dev->info->read_label)
723 return indio_dev->info->read_label(indio_dev, this_attr->c, buf);
726 static ssize_t iio_read_channel_info(struct device *dev,
727 struct device_attribute *attr,
730 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
731 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
732 int vals[INDIO_MAX_RAW_ELEMENTS];
736 if (indio_dev->info->read_raw_multi)
737 ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
738 INDIO_MAX_RAW_ELEMENTS,
742 ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
743 &vals[0], &vals[1], this_attr->address);
748 return iio_format_value(buf, ret, val_len, vals);
751 static ssize_t iio_format_list(char *buf, const int *vals, int type, int length,
752 const char *prefix, const char *suffix)
767 len = sysfs_emit(buf, prefix);
769 for (i = 0; i <= length - stride; i += stride) {
771 len += sysfs_emit_at(buf, len, " ");
772 if (len >= PAGE_SIZE)
776 len += __iio_format_value(buf, len, type, stride, &vals[i]);
777 if (len >= PAGE_SIZE)
781 len += sysfs_emit_at(buf, len, "%s\n", suffix);
786 static ssize_t iio_format_avail_list(char *buf, const int *vals,
787 int type, int length)
790 return iio_format_list(buf, vals, type, length, "", "");
793 static ssize_t iio_format_avail_range(char *buf, const int *vals, int type)
795 return iio_format_list(buf, vals, type, 3, "[", "]");
798 static ssize_t iio_read_channel_info_avail(struct device *dev,
799 struct device_attribute *attr,
802 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
803 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
809 ret = indio_dev->info->read_avail(indio_dev, this_attr->c,
810 &vals, &type, &length,
817 return iio_format_avail_list(buf, vals, type, length);
818 case IIO_AVAIL_RANGE:
819 return iio_format_avail_range(buf, vals, type);
826 * __iio_str_to_fixpoint() - Parse a fixed-point number from a string
827 * @str: The string to parse
828 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
829 * @integer: The integer part of the number
830 * @fract: The fractional part of the number
831 * @scale_db: True if this should parse as dB
833 * Returns 0 on success, or a negative error code if the string could not be
836 static int __iio_str_to_fixpoint(const char *str, int fract_mult,
837 int *integer, int *fract, bool scale_db)
840 bool integer_part = true, negative = false;
842 if (fract_mult == 0) {
845 return kstrtoint(str, 0, integer);
851 } else if (str[0] == '+') {
856 if ('0' <= *str && *str <= '9') {
858 i = i * 10 + *str - '0';
860 f += fract_mult * (*str - '0');
863 } else if (*str == '\n') {
864 if (*(str + 1) == '\0')
868 } else if (!strncmp(str, " dB", sizeof(" dB") - 1) && scale_db) {
869 /* Ignore the dB suffix */
870 str += sizeof(" dB") - 1;
872 } else if (!strncmp(str, "dB", sizeof("dB") - 1) && scale_db) {
873 /* Ignore the dB suffix */
874 str += sizeof("dB") - 1;
876 } else if (*str == '.' && integer_part) {
877 integer_part = false;
898 * iio_str_to_fixpoint() - Parse a fixed-point number from a string
899 * @str: The string to parse
900 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
901 * @integer: The integer part of the number
902 * @fract: The fractional part of the number
904 * Returns 0 on success, or a negative error code if the string could not be
907 int iio_str_to_fixpoint(const char *str, int fract_mult,
908 int *integer, int *fract)
910 return __iio_str_to_fixpoint(str, fract_mult, integer, fract, false);
912 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
914 static ssize_t iio_write_channel_info(struct device *dev,
915 struct device_attribute *attr,
919 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
920 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
921 int ret, fract_mult = 100000;
922 int integer, fract = 0;
923 bool is_char = false;
924 bool scale_db = false;
926 /* Assumes decimal - precision based on number of digits */
927 if (!indio_dev->info->write_raw)
930 if (indio_dev->info->write_raw_get_fmt)
931 switch (indio_dev->info->write_raw_get_fmt(indio_dev,
932 this_attr->c, this_attr->address)) {
936 case IIO_VAL_INT_PLUS_MICRO_DB:
939 case IIO_VAL_INT_PLUS_MICRO:
942 case IIO_VAL_INT_PLUS_NANO:
943 fract_mult = 100000000;
955 if (sscanf(buf, "%c", &ch) != 1)
959 ret = __iio_str_to_fixpoint(buf, fract_mult, &integer, &fract,
965 ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
966 integer, fract, this_attr->address);
974 int __iio_device_attr_init(struct device_attribute *dev_attr,
976 struct iio_chan_spec const *chan,
977 ssize_t (*readfunc)(struct device *dev,
978 struct device_attribute *attr,
980 ssize_t (*writefunc)(struct device *dev,
981 struct device_attribute *attr,
984 enum iio_shared_by shared_by)
989 sysfs_attr_init(&dev_attr->attr);
991 /* Build up postfix of <extend_name>_<modifier>_postfix */
992 if (chan->modified && (shared_by == IIO_SEPARATE)) {
993 if (chan->extend_name)
994 full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
995 iio_modifier_names[chan
1000 full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
1001 iio_modifier_names[chan
1005 if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
1006 full_postfix = kstrdup(postfix, GFP_KERNEL);
1008 full_postfix = kasprintf(GFP_KERNEL,
1013 if (full_postfix == NULL)
1016 if (chan->differential) { /* Differential can not have modifier */
1017 switch (shared_by) {
1018 case IIO_SHARED_BY_ALL:
1019 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1021 case IIO_SHARED_BY_DIR:
1022 name = kasprintf(GFP_KERNEL, "%s_%s",
1023 iio_direction[chan->output],
1026 case IIO_SHARED_BY_TYPE:
1027 name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
1028 iio_direction[chan->output],
1029 iio_chan_type_name_spec[chan->type],
1030 iio_chan_type_name_spec[chan->type],
1034 if (!chan->indexed) {
1035 WARN(1, "Differential channels must be indexed\n");
1037 goto error_free_full_postfix;
1039 name = kasprintf(GFP_KERNEL,
1041 iio_direction[chan->output],
1042 iio_chan_type_name_spec[chan->type],
1044 iio_chan_type_name_spec[chan->type],
1049 } else { /* Single ended */
1050 switch (shared_by) {
1051 case IIO_SHARED_BY_ALL:
1052 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
1054 case IIO_SHARED_BY_DIR:
1055 name = kasprintf(GFP_KERNEL, "%s_%s",
1056 iio_direction[chan->output],
1059 case IIO_SHARED_BY_TYPE:
1060 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1061 iio_direction[chan->output],
1062 iio_chan_type_name_spec[chan->type],
1068 name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
1069 iio_direction[chan->output],
1070 iio_chan_type_name_spec[chan->type],
1074 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
1075 iio_direction[chan->output],
1076 iio_chan_type_name_spec[chan->type],
1083 goto error_free_full_postfix;
1085 dev_attr->attr.name = name;
1088 dev_attr->attr.mode |= S_IRUGO;
1089 dev_attr->show = readfunc;
1093 dev_attr->attr.mode |= S_IWUSR;
1094 dev_attr->store = writefunc;
1097 error_free_full_postfix:
1098 kfree(full_postfix);
1103 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
1105 kfree(dev_attr->attr.name);
1108 int __iio_add_chan_devattr(const char *postfix,
1109 struct iio_chan_spec const *chan,
1110 ssize_t (*readfunc)(struct device *dev,
1111 struct device_attribute *attr,
1113 ssize_t (*writefunc)(struct device *dev,
1114 struct device_attribute *attr,
1118 enum iio_shared_by shared_by,
1120 struct iio_buffer *buffer,
1121 struct list_head *attr_list)
1124 struct iio_dev_attr *iio_attr, *t;
1126 iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
1127 if (iio_attr == NULL)
1129 ret = __iio_device_attr_init(&iio_attr->dev_attr,
1131 readfunc, writefunc, shared_by);
1133 goto error_iio_dev_attr_free;
1135 iio_attr->address = mask;
1136 iio_attr->buffer = buffer;
1137 list_for_each_entry(t, attr_list, l)
1138 if (strcmp(t->dev_attr.attr.name,
1139 iio_attr->dev_attr.attr.name) == 0) {
1140 if (shared_by == IIO_SEPARATE)
1141 dev_err(dev, "tried to double register : %s\n",
1142 t->dev_attr.attr.name);
1144 goto error_device_attr_deinit;
1146 list_add(&iio_attr->l, attr_list);
1150 error_device_attr_deinit:
1151 __iio_device_attr_deinit(&iio_attr->dev_attr);
1152 error_iio_dev_attr_free:
1157 static int iio_device_add_channel_label(struct iio_dev *indio_dev,
1158 struct iio_chan_spec const *chan)
1160 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1163 if (!indio_dev->info->read_label)
1166 ret = __iio_add_chan_devattr("label",
1168 &iio_read_channel_label,
1174 &iio_dev_opaque->channel_attr_list);
1181 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
1182 struct iio_chan_spec const *chan,
1183 enum iio_shared_by shared_by,
1184 const long *infomask)
1186 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1187 int i, ret, attrcount = 0;
1189 for_each_set_bit(i, infomask, sizeof(*infomask)*8) {
1190 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1192 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
1194 &iio_read_channel_info,
1195 &iio_write_channel_info,
1200 &iio_dev_opaque->channel_attr_list);
1201 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1211 static int iio_device_add_info_mask_type_avail(struct iio_dev *indio_dev,
1212 struct iio_chan_spec const *chan,
1213 enum iio_shared_by shared_by,
1214 const long *infomask)
1216 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1217 int i, ret, attrcount = 0;
1218 char *avail_postfix;
1220 for_each_set_bit(i, infomask, sizeof(*infomask) * 8) {
1221 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
1223 avail_postfix = kasprintf(GFP_KERNEL,
1225 iio_chan_info_postfix[i]);
1229 ret = __iio_add_chan_devattr(avail_postfix,
1231 &iio_read_channel_info_avail,
1237 &iio_dev_opaque->channel_attr_list);
1238 kfree(avail_postfix);
1239 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
1249 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
1250 struct iio_chan_spec const *chan)
1252 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1253 int ret, attrcount = 0;
1254 const struct iio_chan_spec_ext_info *ext_info;
1256 if (chan->channel < 0)
1258 ret = iio_device_add_info_mask_type(indio_dev, chan,
1260 &chan->info_mask_separate);
1265 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1268 info_mask_separate_available);
1273 ret = iio_device_add_info_mask_type(indio_dev, chan,
1275 &chan->info_mask_shared_by_type);
1280 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1283 info_mask_shared_by_type_available);
1288 ret = iio_device_add_info_mask_type(indio_dev, chan,
1290 &chan->info_mask_shared_by_dir);
1295 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1297 &chan->info_mask_shared_by_dir_available);
1302 ret = iio_device_add_info_mask_type(indio_dev, chan,
1304 &chan->info_mask_shared_by_all);
1309 ret = iio_device_add_info_mask_type_avail(indio_dev, chan,
1311 &chan->info_mask_shared_by_all_available);
1316 ret = iio_device_add_channel_label(indio_dev, chan);
1321 if (chan->ext_info) {
1323 for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
1324 ret = __iio_add_chan_devattr(ext_info->name,
1327 &iio_read_channel_ext_info : NULL,
1329 &iio_write_channel_ext_info : NULL,
1334 &iio_dev_opaque->channel_attr_list);
1336 if (ret == -EBUSY && ext_info->shared)
1350 * iio_free_chan_devattr_list() - Free a list of IIO device attributes
1351 * @attr_list: List of IIO device attributes
1353 * This function frees the memory allocated for each of the IIO device
1354 * attributes in the list.
1356 void iio_free_chan_devattr_list(struct list_head *attr_list)
1358 struct iio_dev_attr *p, *n;
1360 list_for_each_entry_safe(p, n, attr_list, l) {
1361 kfree_const(p->dev_attr.attr.name);
1367 static ssize_t iio_show_dev_name(struct device *dev,
1368 struct device_attribute *attr,
1371 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1372 return sysfs_emit(buf, "%s\n", indio_dev->name);
1375 static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
1377 static ssize_t iio_show_dev_label(struct device *dev,
1378 struct device_attribute *attr,
1381 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1382 return sysfs_emit(buf, "%s\n", indio_dev->label);
1385 static DEVICE_ATTR(label, S_IRUGO, iio_show_dev_label, NULL);
1387 static ssize_t iio_show_timestamp_clock(struct device *dev,
1388 struct device_attribute *attr,
1391 const struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1392 const clockid_t clk = iio_device_get_clock(indio_dev);
1397 case CLOCK_REALTIME:
1398 name = "realtime\n";
1399 sz = sizeof("realtime\n");
1401 case CLOCK_MONOTONIC:
1402 name = "monotonic\n";
1403 sz = sizeof("monotonic\n");
1405 case CLOCK_MONOTONIC_RAW:
1406 name = "monotonic_raw\n";
1407 sz = sizeof("monotonic_raw\n");
1409 case CLOCK_REALTIME_COARSE:
1410 name = "realtime_coarse\n";
1411 sz = sizeof("realtime_coarse\n");
1413 case CLOCK_MONOTONIC_COARSE:
1414 name = "monotonic_coarse\n";
1415 sz = sizeof("monotonic_coarse\n");
1417 case CLOCK_BOOTTIME:
1418 name = "boottime\n";
1419 sz = sizeof("boottime\n");
1423 sz = sizeof("tai\n");
1429 memcpy(buf, name, sz);
1433 static ssize_t iio_store_timestamp_clock(struct device *dev,
1434 struct device_attribute *attr,
1435 const char *buf, size_t len)
1440 if (sysfs_streq(buf, "realtime"))
1441 clk = CLOCK_REALTIME;
1442 else if (sysfs_streq(buf, "monotonic"))
1443 clk = CLOCK_MONOTONIC;
1444 else if (sysfs_streq(buf, "monotonic_raw"))
1445 clk = CLOCK_MONOTONIC_RAW;
1446 else if (sysfs_streq(buf, "realtime_coarse"))
1447 clk = CLOCK_REALTIME_COARSE;
1448 else if (sysfs_streq(buf, "monotonic_coarse"))
1449 clk = CLOCK_MONOTONIC_COARSE;
1450 else if (sysfs_streq(buf, "boottime"))
1451 clk = CLOCK_BOOTTIME;
1452 else if (sysfs_streq(buf, "tai"))
1457 ret = iio_device_set_clock(dev_to_iio_dev(dev), clk);
1464 int iio_device_register_sysfs_group(struct iio_dev *indio_dev,
1465 const struct attribute_group *group)
1467 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1468 const struct attribute_group **new, **old = iio_dev_opaque->groups;
1469 unsigned int cnt = iio_dev_opaque->groupcounter;
1471 new = krealloc(old, sizeof(*new) * (cnt + 2), GFP_KERNEL);
1475 new[iio_dev_opaque->groupcounter++] = group;
1476 new[iio_dev_opaque->groupcounter] = NULL;
1478 iio_dev_opaque->groups = new;
1483 static DEVICE_ATTR(current_timestamp_clock, S_IRUGO | S_IWUSR,
1484 iio_show_timestamp_clock, iio_store_timestamp_clock);
1486 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
1488 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1489 int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
1490 struct iio_dev_attr *p;
1491 struct attribute **attr, *clk = NULL;
1493 /* First count elements in any existing group */
1494 if (indio_dev->info->attrs) {
1495 attr = indio_dev->info->attrs->attrs;
1496 while (*attr++ != NULL)
1499 attrcount = attrcount_orig;
1501 * New channel registration method - relies on the fact a group does
1502 * not need to be initialized if its name is NULL.
1504 if (indio_dev->channels)
1505 for (i = 0; i < indio_dev->num_channels; i++) {
1506 const struct iio_chan_spec *chan =
1507 &indio_dev->channels[i];
1509 if (chan->type == IIO_TIMESTAMP)
1510 clk = &dev_attr_current_timestamp_clock.attr;
1512 ret = iio_device_add_channel_sysfs(indio_dev, chan);
1514 goto error_clear_attrs;
1518 if (iio_dev_opaque->event_interface)
1519 clk = &dev_attr_current_timestamp_clock.attr;
1521 if (indio_dev->name)
1523 if (indio_dev->label)
1528 iio_dev_opaque->chan_attr_group.attrs =
1529 kcalloc(attrcount + 1,
1530 sizeof(iio_dev_opaque->chan_attr_group.attrs[0]),
1532 if (iio_dev_opaque->chan_attr_group.attrs == NULL) {
1534 goto error_clear_attrs;
1536 /* Copy across original attributes */
1537 if (indio_dev->info->attrs) {
1538 memcpy(iio_dev_opaque->chan_attr_group.attrs,
1539 indio_dev->info->attrs->attrs,
1540 sizeof(iio_dev_opaque->chan_attr_group.attrs[0])
1542 iio_dev_opaque->chan_attr_group.is_visible =
1543 indio_dev->info->attrs->is_visible;
1545 attrn = attrcount_orig;
1546 /* Add all elements from the list. */
1547 list_for_each_entry(p, &iio_dev_opaque->channel_attr_list, l)
1548 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1549 if (indio_dev->name)
1550 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
1551 if (indio_dev->label)
1552 iio_dev_opaque->chan_attr_group.attrs[attrn++] = &dev_attr_label.attr;
1554 iio_dev_opaque->chan_attr_group.attrs[attrn++] = clk;
1556 ret = iio_device_register_sysfs_group(indio_dev,
1557 &iio_dev_opaque->chan_attr_group);
1559 goto error_clear_attrs;
1564 iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1569 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
1571 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1573 iio_free_chan_devattr_list(&iio_dev_opaque->channel_attr_list);
1574 kfree(iio_dev_opaque->chan_attr_group.attrs);
1575 iio_dev_opaque->chan_attr_group.attrs = NULL;
1576 kfree(iio_dev_opaque->groups);
1579 static void iio_dev_release(struct device *device)
1581 struct iio_dev *indio_dev = dev_to_iio_dev(device);
1582 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1584 if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1585 iio_device_unregister_trigger_consumer(indio_dev);
1586 iio_device_unregister_eventset(indio_dev);
1587 iio_device_unregister_sysfs(indio_dev);
1589 iio_device_detach_buffers(indio_dev);
1591 ida_simple_remove(&iio_ida, indio_dev->id);
1592 kfree(iio_dev_opaque);
1595 struct device_type iio_device_type = {
1596 .name = "iio_device",
1597 .release = iio_dev_release,
1601 * iio_device_alloc() - allocate an iio_dev from a driver
1602 * @parent: Parent device.
1603 * @sizeof_priv: Space to allocate for private structure.
1605 struct iio_dev *iio_device_alloc(struct device *parent, int sizeof_priv)
1607 struct iio_dev_opaque *iio_dev_opaque;
1608 struct iio_dev *indio_dev;
1611 alloc_size = sizeof(struct iio_dev_opaque);
1613 alloc_size = ALIGN(alloc_size, IIO_ALIGN);
1614 alloc_size += sizeof_priv;
1617 iio_dev_opaque = kzalloc(alloc_size, GFP_KERNEL);
1618 if (!iio_dev_opaque)
1621 indio_dev = &iio_dev_opaque->indio_dev;
1622 indio_dev->priv = (char *)iio_dev_opaque +
1623 ALIGN(sizeof(struct iio_dev_opaque), IIO_ALIGN);
1625 indio_dev->dev.parent = parent;
1626 indio_dev->dev.type = &iio_device_type;
1627 indio_dev->dev.bus = &iio_bus_type;
1628 device_initialize(&indio_dev->dev);
1629 iio_device_set_drvdata(indio_dev, (void *)indio_dev);
1630 mutex_init(&indio_dev->mlock);
1631 mutex_init(&indio_dev->info_exist_lock);
1632 INIT_LIST_HEAD(&iio_dev_opaque->channel_attr_list);
1634 indio_dev->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
1635 if (indio_dev->id < 0) {
1636 /* cannot use a dev_err as the name isn't available */
1637 pr_err("failed to get device id\n");
1638 kfree(iio_dev_opaque);
1641 dev_set_name(&indio_dev->dev, "iio:device%d", indio_dev->id);
1642 INIT_LIST_HEAD(&iio_dev_opaque->buffer_list);
1643 INIT_LIST_HEAD(&iio_dev_opaque->ioctl_handlers);
1647 EXPORT_SYMBOL(iio_device_alloc);
1650 * iio_device_free() - free an iio_dev from a driver
1651 * @dev: the iio_dev associated with the device
1653 void iio_device_free(struct iio_dev *dev)
1656 put_device(&dev->dev);
1658 EXPORT_SYMBOL(iio_device_free);
1660 static void devm_iio_device_release(struct device *dev, void *res)
1662 iio_device_free(*(struct iio_dev **)res);
1666 * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1667 * @parent: Device to allocate iio_dev for, and parent for this IIO device
1668 * @sizeof_priv: Space to allocate for private structure.
1670 * Managed iio_device_alloc. iio_dev allocated with this function is
1671 * automatically freed on driver detach.
1674 * Pointer to allocated iio_dev on success, NULL on failure.
1676 struct iio_dev *devm_iio_device_alloc(struct device *parent, int sizeof_priv)
1678 struct iio_dev **ptr, *iio_dev;
1680 ptr = devres_alloc(devm_iio_device_release, sizeof(*ptr),
1685 iio_dev = iio_device_alloc(parent, sizeof_priv);
1688 devres_add(parent, ptr);
1695 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1698 * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1699 * @inode: Inode structure for identifying the device in the file system
1700 * @filp: File structure for iio device used to keep and later access
1703 * Return: 0 on success or -EBUSY if the device is already opened
1705 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1707 struct iio_dev *indio_dev = container_of(inode->i_cdev,
1708 struct iio_dev, chrdev);
1709 struct iio_dev_buffer_pair *ib;
1711 if (test_and_set_bit(IIO_BUSY_BIT_POS, &indio_dev->flags))
1714 iio_device_get(indio_dev);
1716 ib = kmalloc(sizeof(*ib), GFP_KERNEL);
1718 iio_device_put(indio_dev);
1719 clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
1723 ib->indio_dev = indio_dev;
1724 ib->buffer = indio_dev->buffer;
1726 filp->private_data = ib;
1732 * iio_chrdev_release() - chrdev file close buffer access and ioctls
1733 * @inode: Inode structure pointer for the char device
1734 * @filp: File structure pointer for the char device
1736 * Return: 0 for successful release
1738 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1740 struct iio_dev_buffer_pair *ib = filp->private_data;
1741 struct iio_dev *indio_dev = container_of(inode->i_cdev,
1742 struct iio_dev, chrdev);
1744 clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
1745 iio_device_put(indio_dev);
1750 void iio_device_ioctl_handler_register(struct iio_dev *indio_dev,
1751 struct iio_ioctl_handler *h)
1753 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1755 list_add_tail(&h->entry, &iio_dev_opaque->ioctl_handlers);
1758 void iio_device_ioctl_handler_unregister(struct iio_ioctl_handler *h)
1760 list_del(&h->entry);
1763 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1765 struct iio_dev_buffer_pair *ib = filp->private_data;
1766 struct iio_dev *indio_dev = ib->indio_dev;
1767 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1768 struct iio_ioctl_handler *h;
1771 mutex_lock(&indio_dev->info_exist_lock);
1774 * The NULL check here is required to prevent crashing when a device
1775 * is being removed while userspace would still have open file handles
1776 * to try to access this device.
1778 if (!indio_dev->info)
1781 list_for_each_entry(h, &iio_dev_opaque->ioctl_handlers, entry) {
1782 ret = h->ioctl(indio_dev, filp, cmd, arg);
1783 if (ret != IIO_IOCTL_UNHANDLED)
1787 if (ret == IIO_IOCTL_UNHANDLED)
1791 mutex_unlock(&indio_dev->info_exist_lock);
1796 static const struct file_operations iio_buffer_fileops = {
1797 .owner = THIS_MODULE,
1798 .llseek = noop_llseek,
1799 .read = iio_buffer_read_outer_addr,
1800 .poll = iio_buffer_poll_addr,
1801 .unlocked_ioctl = iio_ioctl,
1802 .compat_ioctl = compat_ptr_ioctl,
1803 .open = iio_chrdev_open,
1804 .release = iio_chrdev_release,
1807 static const struct file_operations iio_event_fileops = {
1808 .owner = THIS_MODULE,
1809 .llseek = noop_llseek,
1810 .unlocked_ioctl = iio_ioctl,
1811 .compat_ioctl = compat_ptr_ioctl,
1812 .open = iio_chrdev_open,
1813 .release = iio_chrdev_release,
1816 static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1819 const struct iio_chan_spec *channels = indio_dev->channels;
1821 if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1824 for (i = 0; i < indio_dev->num_channels - 1; i++) {
1825 if (channels[i].scan_index < 0)
1827 for (j = i + 1; j < indio_dev->num_channels; j++)
1828 if (channels[i].scan_index == channels[j].scan_index) {
1829 dev_err(&indio_dev->dev,
1830 "Duplicate scan index %d\n",
1831 channels[i].scan_index);
1839 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1841 int __iio_device_register(struct iio_dev *indio_dev, struct module *this_mod)
1843 struct iio_dev_opaque *iio_dev_opaque = to_iio_dev_opaque(indio_dev);
1847 if (!indio_dev->info)
1850 indio_dev->driver_module = this_mod;
1851 /* If the calling driver did not initialize of_node, do it here */
1852 if (!indio_dev->dev.of_node && indio_dev->dev.parent)
1853 indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
1855 label = of_get_property(indio_dev->dev.of_node, "label", NULL);
1857 indio_dev->label = label;
1859 ret = iio_check_unique_scan_index(indio_dev);
1863 iio_device_register_debugfs(indio_dev);
1865 ret = iio_buffers_alloc_sysfs_and_mask(indio_dev);
1867 dev_err(indio_dev->dev.parent,
1868 "Failed to create buffer sysfs interfaces\n");
1869 goto error_unreg_debugfs;
1872 ret = iio_device_register_sysfs(indio_dev);
1874 dev_err(indio_dev->dev.parent,
1875 "Failed to register sysfs interfaces\n");
1876 goto error_buffer_free_sysfs;
1878 ret = iio_device_register_eventset(indio_dev);
1880 dev_err(indio_dev->dev.parent,
1881 "Failed to register event set\n");
1882 goto error_free_sysfs;
1884 if (indio_dev->modes & INDIO_ALL_TRIGGERED_MODES)
1885 iio_device_register_trigger_consumer(indio_dev);
1887 if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1888 indio_dev->setup_ops == NULL)
1889 indio_dev->setup_ops = &noop_ring_setup_ops;
1891 if (iio_dev_opaque->attached_buffers_cnt)
1892 cdev_init(&indio_dev->chrdev, &iio_buffer_fileops);
1893 else if (iio_dev_opaque->event_interface)
1894 cdev_init(&indio_dev->chrdev, &iio_event_fileops);
1896 if (iio_dev_opaque->attached_buffers_cnt || iio_dev_opaque->event_interface) {
1897 indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), indio_dev->id);
1898 indio_dev->chrdev.owner = this_mod;
1901 /* assign device groups now; they should be all registered now */
1902 indio_dev->dev.groups = iio_dev_opaque->groups;
1904 ret = cdev_device_add(&indio_dev->chrdev, &indio_dev->dev);
1906 goto error_unreg_eventset;
1910 error_unreg_eventset:
1911 iio_device_unregister_eventset(indio_dev);
1913 iio_device_unregister_sysfs(indio_dev);
1914 error_buffer_free_sysfs:
1915 iio_buffers_free_sysfs_and_mask(indio_dev);
1916 error_unreg_debugfs:
1917 iio_device_unregister_debugfs(indio_dev);
1920 EXPORT_SYMBOL(__iio_device_register);
1923 * iio_device_unregister() - unregister a device from the IIO subsystem
1924 * @indio_dev: Device structure representing the device.
1926 void iio_device_unregister(struct iio_dev *indio_dev)
1928 cdev_device_del(&indio_dev->chrdev, &indio_dev->dev);
1930 mutex_lock(&indio_dev->info_exist_lock);
1932 iio_device_unregister_debugfs(indio_dev);
1934 iio_disable_all_buffers(indio_dev);
1936 indio_dev->info = NULL;
1938 iio_device_wakeup_eventset(indio_dev);
1939 iio_buffer_wakeup_poll(indio_dev);
1941 mutex_unlock(&indio_dev->info_exist_lock);
1943 iio_buffers_free_sysfs_and_mask(indio_dev);
1945 EXPORT_SYMBOL(iio_device_unregister);
1947 static void devm_iio_device_unreg(struct device *dev, void *res)
1949 iio_device_unregister(*(struct iio_dev **)res);
1952 int __devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev,
1953 struct module *this_mod)
1955 struct iio_dev **ptr;
1958 ptr = devres_alloc(devm_iio_device_unreg, sizeof(*ptr), GFP_KERNEL);
1963 ret = __iio_device_register(indio_dev, this_mod);
1965 devres_add(dev, ptr);
1971 EXPORT_SYMBOL_GPL(__devm_iio_device_register);
1974 * iio_device_claim_direct_mode - Keep device in direct mode
1975 * @indio_dev: the iio_dev associated with the device
1977 * If the device is in direct mode it is guaranteed to stay
1978 * that way until iio_device_release_direct_mode() is called.
1980 * Use with iio_device_release_direct_mode()
1982 * Returns: 0 on success, -EBUSY on failure
1984 int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
1986 mutex_lock(&indio_dev->mlock);
1988 if (iio_buffer_enabled(indio_dev)) {
1989 mutex_unlock(&indio_dev->mlock);
1994 EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
1997 * iio_device_release_direct_mode - releases claim on direct mode
1998 * @indio_dev: the iio_dev associated with the device
2000 * Release the claim. Device is no longer guaranteed to stay
2003 * Use with iio_device_claim_direct_mode()
2005 void iio_device_release_direct_mode(struct iio_dev *indio_dev)
2007 mutex_unlock(&indio_dev->mlock);
2009 EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
2011 subsys_initcall(iio_init);
2012 module_exit(iio_exit);
2014 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
2015 MODULE_DESCRIPTION("Industrial I/O core");
2016 MODULE_LICENSE("GPL");