1 /* The industrial I/O core
3 * Copyright (c) 2008 Jonathan Cameron
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License version 2 as published by
7 * the Free Software Foundation.
9 * Based on elements of hwmon and input subsystems.
12 #define pr_fmt(fmt) "iio-core: " fmt
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/idr.h>
17 #include <linux/kdev_t.h>
18 #include <linux/err.h>
19 #include <linux/device.h>
21 #include <linux/poll.h>
22 #include <linux/sched.h>
23 #include <linux/wait.h>
24 #include <linux/cdev.h>
25 #include <linux/slab.h>
26 #include <linux/anon_inodes.h>
27 #include <linux/debugfs.h>
28 #include <linux/mutex.h>
29 #include <linux/iio/iio.h>
31 #include "iio_core_trigger.h"
32 #include <linux/iio/sysfs.h>
33 #include <linux/iio/events.h>
34 #include <linux/iio/buffer.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",
86 static const char * const iio_modifier_names[] = {
90 [IIO_MOD_X_AND_Y] = "x&y",
91 [IIO_MOD_X_AND_Z] = "x&z",
92 [IIO_MOD_Y_AND_Z] = "y&z",
93 [IIO_MOD_X_AND_Y_AND_Z] = "x&y&z",
94 [IIO_MOD_X_OR_Y] = "x|y",
95 [IIO_MOD_X_OR_Z] = "x|z",
96 [IIO_MOD_Y_OR_Z] = "y|z",
97 [IIO_MOD_X_OR_Y_OR_Z] = "x|y|z",
98 [IIO_MOD_ROOT_SUM_SQUARED_X_Y] = "sqrt(x^2+y^2)",
99 [IIO_MOD_SUM_SQUARED_X_Y_Z] = "x^2+y^2+z^2",
100 [IIO_MOD_LIGHT_BOTH] = "both",
101 [IIO_MOD_LIGHT_IR] = "ir",
102 [IIO_MOD_LIGHT_CLEAR] = "clear",
103 [IIO_MOD_LIGHT_RED] = "red",
104 [IIO_MOD_LIGHT_GREEN] = "green",
105 [IIO_MOD_LIGHT_BLUE] = "blue",
106 [IIO_MOD_LIGHT_UV] = "uv",
107 [IIO_MOD_QUATERNION] = "quaternion",
108 [IIO_MOD_TEMP_AMBIENT] = "ambient",
109 [IIO_MOD_TEMP_OBJECT] = "object",
110 [IIO_MOD_NORTH_MAGN] = "from_north_magnetic",
111 [IIO_MOD_NORTH_TRUE] = "from_north_true",
112 [IIO_MOD_NORTH_MAGN_TILT_COMP] = "from_north_magnetic_tilt_comp",
113 [IIO_MOD_NORTH_TRUE_TILT_COMP] = "from_north_true_tilt_comp",
114 [IIO_MOD_RUNNING] = "running",
115 [IIO_MOD_JOGGING] = "jogging",
116 [IIO_MOD_WALKING] = "walking",
117 [IIO_MOD_STILL] = "still",
118 [IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z] = "sqrt(x^2+y^2+z^2)",
121 [IIO_MOD_CO2] = "co2",
122 [IIO_MOD_VOC] = "voc",
125 /* relies on pairs of these shared then separate */
126 static const char * const iio_chan_info_postfix[] = {
127 [IIO_CHAN_INFO_RAW] = "raw",
128 [IIO_CHAN_INFO_PROCESSED] = "input",
129 [IIO_CHAN_INFO_SCALE] = "scale",
130 [IIO_CHAN_INFO_OFFSET] = "offset",
131 [IIO_CHAN_INFO_CALIBSCALE] = "calibscale",
132 [IIO_CHAN_INFO_CALIBBIAS] = "calibbias",
133 [IIO_CHAN_INFO_PEAK] = "peak_raw",
134 [IIO_CHAN_INFO_PEAK_SCALE] = "peak_scale",
135 [IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW] = "quadrature_correction_raw",
136 [IIO_CHAN_INFO_AVERAGE_RAW] = "mean_raw",
137 [IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY]
138 = "filter_low_pass_3db_frequency",
139 [IIO_CHAN_INFO_HIGH_PASS_FILTER_3DB_FREQUENCY]
140 = "filter_high_pass_3db_frequency",
141 [IIO_CHAN_INFO_SAMP_FREQ] = "sampling_frequency",
142 [IIO_CHAN_INFO_FREQUENCY] = "frequency",
143 [IIO_CHAN_INFO_PHASE] = "phase",
144 [IIO_CHAN_INFO_HARDWAREGAIN] = "hardwaregain",
145 [IIO_CHAN_INFO_HYSTERESIS] = "hysteresis",
146 [IIO_CHAN_INFO_INT_TIME] = "integration_time",
147 [IIO_CHAN_INFO_ENABLE] = "en",
148 [IIO_CHAN_INFO_CALIBHEIGHT] = "calibheight",
149 [IIO_CHAN_INFO_CALIBWEIGHT] = "calibweight",
150 [IIO_CHAN_INFO_DEBOUNCE_COUNT] = "debounce_count",
151 [IIO_CHAN_INFO_DEBOUNCE_TIME] = "debounce_time",
152 [IIO_CHAN_INFO_CALIBEMISSIVITY] = "calibemissivity",
153 [IIO_CHAN_INFO_OVERSAMPLING_RATIO] = "oversampling_ratio",
157 * iio_find_channel_from_si() - get channel from its scan index
159 * @si: scan index to match
161 const struct iio_chan_spec
162 *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
166 for (i = 0; i < indio_dev->num_channels; i++)
167 if (indio_dev->channels[i].scan_index == si)
168 return &indio_dev->channels[i];
172 /* This turns up an awful lot */
173 ssize_t iio_read_const_attr(struct device *dev,
174 struct device_attribute *attr,
177 return sprintf(buf, "%s\n", to_iio_const_attr(attr)->string);
179 EXPORT_SYMBOL(iio_read_const_attr);
181 static int iio_device_set_clock(struct iio_dev *indio_dev, clockid_t clock_id)
184 const struct iio_event_interface *ev_int = indio_dev->event_interface;
186 ret = mutex_lock_interruptible(&indio_dev->mlock);
189 if ((ev_int && iio_event_enabled(ev_int)) ||
190 iio_buffer_enabled(indio_dev)) {
191 mutex_unlock(&indio_dev->mlock);
194 indio_dev->clock_id = clock_id;
195 mutex_unlock(&indio_dev->mlock);
201 * iio_get_time_ns() - utility function to get a time stamp for events etc
204 s64 iio_get_time_ns(const struct iio_dev *indio_dev)
208 switch (iio_device_get_clock(indio_dev)) {
210 ktime_get_real_ts(&tp);
212 case CLOCK_MONOTONIC:
215 case CLOCK_MONOTONIC_RAW:
216 getrawmonotonic(&tp);
218 case CLOCK_REALTIME_COARSE:
219 tp = current_kernel_time();
221 case CLOCK_MONOTONIC_COARSE:
222 tp = get_monotonic_coarse();
225 get_monotonic_boottime(&tp);
228 timekeeping_clocktai(&tp);
234 return timespec_to_ns(&tp);
236 EXPORT_SYMBOL(iio_get_time_ns);
239 * iio_get_time_res() - utility function to get time stamp clock resolution in
243 unsigned int iio_get_time_res(const struct iio_dev *indio_dev)
245 switch (iio_device_get_clock(indio_dev)) {
247 case CLOCK_MONOTONIC:
248 case CLOCK_MONOTONIC_RAW:
251 return hrtimer_resolution;
252 case CLOCK_REALTIME_COARSE:
253 case CLOCK_MONOTONIC_COARSE:
259 EXPORT_SYMBOL(iio_get_time_res);
261 static int __init iio_init(void)
265 /* Register sysfs bus */
266 ret = bus_register(&iio_bus_type);
268 pr_err("could not register bus type\n");
272 ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
274 pr_err("failed to allocate char dev region\n");
275 goto error_unregister_bus_type;
278 iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
282 error_unregister_bus_type:
283 bus_unregister(&iio_bus_type);
288 static void __exit iio_exit(void)
291 unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
292 bus_unregister(&iio_bus_type);
293 debugfs_remove(iio_debugfs_dentry);
296 #if defined(CONFIG_DEBUG_FS)
297 static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
298 size_t count, loff_t *ppos)
300 struct iio_dev *indio_dev = file->private_data;
306 ret = indio_dev->info->debugfs_reg_access(indio_dev,
307 indio_dev->cached_reg_addr,
310 dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
312 len = snprintf(buf, sizeof(buf), "0x%X\n", val);
314 return simple_read_from_buffer(userbuf, count, ppos, buf, len);
317 static ssize_t iio_debugfs_write_reg(struct file *file,
318 const char __user *userbuf, size_t count, loff_t *ppos)
320 struct iio_dev *indio_dev = file->private_data;
325 count = min_t(size_t, count, (sizeof(buf)-1));
326 if (copy_from_user(buf, userbuf, count))
331 ret = sscanf(buf, "%i %i", ®, &val);
335 indio_dev->cached_reg_addr = reg;
338 indio_dev->cached_reg_addr = reg;
339 ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
342 dev_err(indio_dev->dev.parent, "%s: write failed\n",
354 static const struct file_operations iio_debugfs_reg_fops = {
356 .read = iio_debugfs_read_reg,
357 .write = iio_debugfs_write_reg,
360 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
362 debugfs_remove_recursive(indio_dev->debugfs_dentry);
365 static int iio_device_register_debugfs(struct iio_dev *indio_dev)
369 if (indio_dev->info->debugfs_reg_access == NULL)
372 if (!iio_debugfs_dentry)
375 indio_dev->debugfs_dentry =
376 debugfs_create_dir(dev_name(&indio_dev->dev),
378 if (indio_dev->debugfs_dentry == NULL) {
379 dev_warn(indio_dev->dev.parent,
380 "Failed to create debugfs directory\n");
384 d = debugfs_create_file("direct_reg_access", 0644,
385 indio_dev->debugfs_dentry,
386 indio_dev, &iio_debugfs_reg_fops);
388 iio_device_unregister_debugfs(indio_dev);
395 static int iio_device_register_debugfs(struct iio_dev *indio_dev)
400 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
403 #endif /* CONFIG_DEBUG_FS */
405 static ssize_t iio_read_channel_ext_info(struct device *dev,
406 struct device_attribute *attr,
409 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
410 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
411 const struct iio_chan_spec_ext_info *ext_info;
413 ext_info = &this_attr->c->ext_info[this_attr->address];
415 return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
418 static ssize_t iio_write_channel_ext_info(struct device *dev,
419 struct device_attribute *attr,
423 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
424 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
425 const struct iio_chan_spec_ext_info *ext_info;
427 ext_info = &this_attr->c->ext_info[this_attr->address];
429 return ext_info->write(indio_dev, ext_info->private,
430 this_attr->c, buf, len);
433 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
434 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
436 const struct iio_enum *e = (const struct iio_enum *)priv;
443 for (i = 0; i < e->num_items; ++i)
444 len += scnprintf(buf + len, PAGE_SIZE - len, "%s ", e->items[i]);
446 /* replace last space with a newline */
451 EXPORT_SYMBOL_GPL(iio_enum_available_read);
453 ssize_t iio_enum_read(struct iio_dev *indio_dev,
454 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
456 const struct iio_enum *e = (const struct iio_enum *)priv;
462 i = e->get(indio_dev, chan);
465 else if (i >= e->num_items)
468 return snprintf(buf, PAGE_SIZE, "%s\n", e->items[i]);
470 EXPORT_SYMBOL_GPL(iio_enum_read);
472 ssize_t iio_enum_write(struct iio_dev *indio_dev,
473 uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
476 const struct iio_enum *e = (const struct iio_enum *)priv;
483 for (i = 0; i < e->num_items; i++) {
484 if (sysfs_streq(buf, e->items[i]))
488 if (i == e->num_items)
491 ret = e->set(indio_dev, chan, i);
492 return ret ? ret : len;
494 EXPORT_SYMBOL_GPL(iio_enum_write);
496 static const struct iio_mount_matrix iio_mount_idmatrix = {
504 static int iio_setup_mount_idmatrix(const struct device *dev,
505 struct iio_mount_matrix *matrix)
507 *matrix = iio_mount_idmatrix;
508 dev_info(dev, "mounting matrix not found: using identity...\n");
512 ssize_t iio_show_mount_matrix(struct iio_dev *indio_dev, uintptr_t priv,
513 const struct iio_chan_spec *chan, char *buf)
515 const struct iio_mount_matrix *mtx = ((iio_get_mount_matrix_t *)
516 priv)(indio_dev, chan);
522 mtx = &iio_mount_idmatrix;
524 return snprintf(buf, PAGE_SIZE, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
525 mtx->rotation[0], mtx->rotation[1], mtx->rotation[2],
526 mtx->rotation[3], mtx->rotation[4], mtx->rotation[5],
527 mtx->rotation[6], mtx->rotation[7], mtx->rotation[8]);
529 EXPORT_SYMBOL_GPL(iio_show_mount_matrix);
532 * of_iio_read_mount_matrix() - retrieve iio device mounting matrix from
533 * device-tree "mount-matrix" property
534 * @dev: device the mounting matrix property is assigned to
535 * @propname: device specific mounting matrix property name
536 * @matrix: where to store retrieved matrix
538 * If device is assigned no mounting matrix property, a default 3x3 identity
539 * matrix will be filled in.
541 * Return: 0 if success, or a negative error code on failure.
544 int of_iio_read_mount_matrix(const struct device *dev,
545 const char *propname,
546 struct iio_mount_matrix *matrix)
549 int err = of_property_read_string_array(dev->of_node,
550 propname, matrix->rotation,
551 ARRAY_SIZE(iio_mount_idmatrix.rotation));
553 if (err == ARRAY_SIZE(iio_mount_idmatrix.rotation))
557 /* Invalid number of matrix entries. */
561 /* Invalid matrix declaration format. */
565 /* Matrix was not declared at all: fallback to identity. */
566 return iio_setup_mount_idmatrix(dev, matrix);
569 int of_iio_read_mount_matrix(const struct device *dev,
570 const char *propname,
571 struct iio_mount_matrix *matrix)
573 return iio_setup_mount_idmatrix(dev, matrix);
576 EXPORT_SYMBOL(of_iio_read_mount_matrix);
579 * iio_format_value() - Formats a IIO value into its string representation
580 * @buf: The buffer to which the formatted value gets written
581 * @type: One of the IIO_VAL_... constants. This decides how the val
582 * and val2 parameters are formatted.
583 * @size: Number of IIO value entries contained in vals
584 * @vals: Pointer to the values, exact meaning depends on the
587 * Return: 0 by default, a negative number on failure or the
588 * total number of characters written for a type that belongs
589 * to the IIO_VAL_... constant.
591 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
593 unsigned long long tmp;
594 bool scale_db = false;
598 return sprintf(buf, "%d\n", vals[0]);
599 case IIO_VAL_INT_PLUS_MICRO_DB:
601 case IIO_VAL_INT_PLUS_MICRO:
603 return sprintf(buf, "-%d.%06u%s\n", abs(vals[0]),
604 -vals[1], scale_db ? " dB" : "");
606 return sprintf(buf, "%d.%06u%s\n", vals[0], vals[1],
607 scale_db ? " dB" : "");
608 case IIO_VAL_INT_PLUS_NANO:
610 return sprintf(buf, "-%d.%09u\n", abs(vals[0]),
613 return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
614 case IIO_VAL_FRACTIONAL:
615 tmp = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
616 vals[0] = (int)div_s64_rem(tmp, 1000000000, &vals[1]);
617 return sprintf(buf, "%d.%09u\n", vals[0], abs(vals[1]));
618 case IIO_VAL_FRACTIONAL_LOG2:
619 tmp = (s64)vals[0] * 1000000000LL >> vals[1];
620 vals[1] = do_div(tmp, 1000000000LL);
622 return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
623 case IIO_VAL_INT_MULTIPLE:
628 for (i = 0; i < size; ++i)
629 len += snprintf(&buf[len], PAGE_SIZE - len, "%d ",
631 len += snprintf(&buf[len], PAGE_SIZE - len, "\n");
638 EXPORT_SYMBOL_GPL(iio_format_value);
640 static ssize_t iio_read_channel_info(struct device *dev,
641 struct device_attribute *attr,
644 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
645 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
646 int vals[INDIO_MAX_RAW_ELEMENTS];
650 if (indio_dev->info->read_raw_multi)
651 ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
652 INDIO_MAX_RAW_ELEMENTS,
656 ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
657 &vals[0], &vals[1], this_attr->address);
662 return iio_format_value(buf, ret, val_len, vals);
666 * iio_str_to_fixpoint() - Parse a fixed-point number from a string
667 * @str: The string to parse
668 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
669 * @integer: The integer part of the number
670 * @fract: The fractional part of the number
672 * Returns 0 on success, or a negative error code if the string could not be
675 int iio_str_to_fixpoint(const char *str, int fract_mult,
676 int *integer, int *fract)
679 bool integer_part = true, negative = false;
681 if (fract_mult == 0) {
684 return kstrtoint(str, 0, integer);
690 } else if (str[0] == '+') {
695 if ('0' <= *str && *str <= '9') {
697 i = i * 10 + *str - '0';
699 f += fract_mult * (*str - '0');
702 } else if (*str == '\n') {
703 if (*(str + 1) == '\0')
707 } else if (*str == '.' && integer_part) {
708 integer_part = false;
727 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
729 static ssize_t iio_write_channel_info(struct device *dev,
730 struct device_attribute *attr,
734 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
735 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
736 int ret, fract_mult = 100000;
739 /* Assumes decimal - precision based on number of digits */
740 if (!indio_dev->info->write_raw)
743 if (indio_dev->info->write_raw_get_fmt)
744 switch (indio_dev->info->write_raw_get_fmt(indio_dev,
745 this_attr->c, this_attr->address)) {
749 case IIO_VAL_INT_PLUS_MICRO:
752 case IIO_VAL_INT_PLUS_NANO:
753 fract_mult = 100000000;
759 ret = iio_str_to_fixpoint(buf, fract_mult, &integer, &fract);
763 ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
764 integer, fract, this_attr->address);
772 int __iio_device_attr_init(struct device_attribute *dev_attr,
774 struct iio_chan_spec const *chan,
775 ssize_t (*readfunc)(struct device *dev,
776 struct device_attribute *attr,
778 ssize_t (*writefunc)(struct device *dev,
779 struct device_attribute *attr,
782 enum iio_shared_by shared_by)
787 sysfs_attr_init(&dev_attr->attr);
789 /* Build up postfix of <extend_name>_<modifier>_postfix */
790 if (chan->modified && (shared_by == IIO_SEPARATE)) {
791 if (chan->extend_name)
792 full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
793 iio_modifier_names[chan
798 full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
799 iio_modifier_names[chan
803 if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
804 full_postfix = kstrdup(postfix, GFP_KERNEL);
806 full_postfix = kasprintf(GFP_KERNEL,
811 if (full_postfix == NULL)
814 if (chan->differential) { /* Differential can not have modifier */
816 case IIO_SHARED_BY_ALL:
817 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
819 case IIO_SHARED_BY_DIR:
820 name = kasprintf(GFP_KERNEL, "%s_%s",
821 iio_direction[chan->output],
824 case IIO_SHARED_BY_TYPE:
825 name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
826 iio_direction[chan->output],
827 iio_chan_type_name_spec[chan->type],
828 iio_chan_type_name_spec[chan->type],
832 if (!chan->indexed) {
833 WARN(1, "Differential channels must be indexed\n");
835 goto error_free_full_postfix;
837 name = kasprintf(GFP_KERNEL,
839 iio_direction[chan->output],
840 iio_chan_type_name_spec[chan->type],
842 iio_chan_type_name_spec[chan->type],
847 } else { /* Single ended */
849 case IIO_SHARED_BY_ALL:
850 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
852 case IIO_SHARED_BY_DIR:
853 name = kasprintf(GFP_KERNEL, "%s_%s",
854 iio_direction[chan->output],
857 case IIO_SHARED_BY_TYPE:
858 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
859 iio_direction[chan->output],
860 iio_chan_type_name_spec[chan->type],
866 name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
867 iio_direction[chan->output],
868 iio_chan_type_name_spec[chan->type],
872 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
873 iio_direction[chan->output],
874 iio_chan_type_name_spec[chan->type],
881 goto error_free_full_postfix;
883 dev_attr->attr.name = name;
886 dev_attr->attr.mode |= S_IRUGO;
887 dev_attr->show = readfunc;
891 dev_attr->attr.mode |= S_IWUSR;
892 dev_attr->store = writefunc;
895 error_free_full_postfix:
901 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
903 kfree(dev_attr->attr.name);
906 int __iio_add_chan_devattr(const char *postfix,
907 struct iio_chan_spec const *chan,
908 ssize_t (*readfunc)(struct device *dev,
909 struct device_attribute *attr,
911 ssize_t (*writefunc)(struct device *dev,
912 struct device_attribute *attr,
916 enum iio_shared_by shared_by,
918 struct list_head *attr_list)
921 struct iio_dev_attr *iio_attr, *t;
923 iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
924 if (iio_attr == NULL)
926 ret = __iio_device_attr_init(&iio_attr->dev_attr,
928 readfunc, writefunc, shared_by);
930 goto error_iio_dev_attr_free;
932 iio_attr->address = mask;
933 list_for_each_entry(t, attr_list, l)
934 if (strcmp(t->dev_attr.attr.name,
935 iio_attr->dev_attr.attr.name) == 0) {
936 if (shared_by == IIO_SEPARATE)
937 dev_err(dev, "tried to double register : %s\n",
938 t->dev_attr.attr.name);
940 goto error_device_attr_deinit;
942 list_add(&iio_attr->l, attr_list);
946 error_device_attr_deinit:
947 __iio_device_attr_deinit(&iio_attr->dev_attr);
948 error_iio_dev_attr_free:
953 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
954 struct iio_chan_spec const *chan,
955 enum iio_shared_by shared_by,
956 const long *infomask)
958 int i, ret, attrcount = 0;
960 for_each_set_bit(i, infomask, sizeof(infomask)*8) {
961 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
963 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
965 &iio_read_channel_info,
966 &iio_write_channel_info,
970 &indio_dev->channel_attr_list);
971 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
981 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
982 struct iio_chan_spec const *chan)
984 int ret, attrcount = 0;
985 const struct iio_chan_spec_ext_info *ext_info;
987 if (chan->channel < 0)
989 ret = iio_device_add_info_mask_type(indio_dev, chan,
991 &chan->info_mask_separate);
996 ret = iio_device_add_info_mask_type(indio_dev, chan,
998 &chan->info_mask_shared_by_type);
1003 ret = iio_device_add_info_mask_type(indio_dev, chan,
1005 &chan->info_mask_shared_by_dir);
1010 ret = iio_device_add_info_mask_type(indio_dev, chan,
1012 &chan->info_mask_shared_by_all);
1017 if (chan->ext_info) {
1019 for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
1020 ret = __iio_add_chan_devattr(ext_info->name,
1023 &iio_read_channel_ext_info : NULL,
1025 &iio_write_channel_ext_info : NULL,
1029 &indio_dev->channel_attr_list);
1031 if (ret == -EBUSY && ext_info->shared)
1045 * iio_free_chan_devattr_list() - Free a list of IIO device attributes
1046 * @attr_list: List of IIO device attributes
1048 * This function frees the memory allocated for each of the IIO device
1049 * attributes in the list.
1051 void iio_free_chan_devattr_list(struct list_head *attr_list)
1053 struct iio_dev_attr *p, *n;
1055 list_for_each_entry_safe(p, n, attr_list, l) {
1056 kfree(p->dev_attr.attr.name);
1062 static ssize_t iio_show_dev_name(struct device *dev,
1063 struct device_attribute *attr,
1066 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1067 return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->name);
1070 static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
1072 static ssize_t iio_show_timestamp_clock(struct device *dev,
1073 struct device_attribute *attr,
1076 const struct iio_dev *indio_dev = dev_to_iio_dev(dev);
1077 const clockid_t clk = iio_device_get_clock(indio_dev);
1082 case CLOCK_REALTIME:
1083 name = "realtime\n";
1084 sz = sizeof("realtime\n");
1086 case CLOCK_MONOTONIC:
1087 name = "monotonic\n";
1088 sz = sizeof("monotonic\n");
1090 case CLOCK_MONOTONIC_RAW:
1091 name = "monotonic_raw\n";
1092 sz = sizeof("monotonic_raw\n");
1094 case CLOCK_REALTIME_COARSE:
1095 name = "realtime_coarse\n";
1096 sz = sizeof("realtime_coarse\n");
1098 case CLOCK_MONOTONIC_COARSE:
1099 name = "monotonic_coarse\n";
1100 sz = sizeof("monotonic_coarse\n");
1102 case CLOCK_BOOTTIME:
1103 name = "boottime\n";
1104 sz = sizeof("boottime\n");
1108 sz = sizeof("tai\n");
1114 memcpy(buf, name, sz);
1118 static ssize_t iio_store_timestamp_clock(struct device *dev,
1119 struct device_attribute *attr,
1120 const char *buf, size_t len)
1125 if (sysfs_streq(buf, "realtime"))
1126 clk = CLOCK_REALTIME;
1127 else if (sysfs_streq(buf, "monotonic"))
1128 clk = CLOCK_MONOTONIC;
1129 else if (sysfs_streq(buf, "monotonic_raw"))
1130 clk = CLOCK_MONOTONIC_RAW;
1131 else if (sysfs_streq(buf, "realtime_coarse"))
1132 clk = CLOCK_REALTIME_COARSE;
1133 else if (sysfs_streq(buf, "monotonic_coarse"))
1134 clk = CLOCK_MONOTONIC_COARSE;
1135 else if (sysfs_streq(buf, "boottime"))
1136 clk = CLOCK_BOOTTIME;
1137 else if (sysfs_streq(buf, "tai"))
1142 ret = iio_device_set_clock(dev_to_iio_dev(dev), clk);
1149 static DEVICE_ATTR(current_timestamp_clock, S_IRUGO | S_IWUSR,
1150 iio_show_timestamp_clock, iio_store_timestamp_clock);
1152 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
1154 int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
1155 struct iio_dev_attr *p;
1156 struct attribute **attr, *clk = NULL;
1158 /* First count elements in any existing group */
1159 if (indio_dev->info->attrs) {
1160 attr = indio_dev->info->attrs->attrs;
1161 while (*attr++ != NULL)
1164 attrcount = attrcount_orig;
1166 * New channel registration method - relies on the fact a group does
1167 * not need to be initialized if its name is NULL.
1169 if (indio_dev->channels)
1170 for (i = 0; i < indio_dev->num_channels; i++) {
1171 const struct iio_chan_spec *chan =
1172 &indio_dev->channels[i];
1174 if (chan->type == IIO_TIMESTAMP)
1175 clk = &dev_attr_current_timestamp_clock.attr;
1177 ret = iio_device_add_channel_sysfs(indio_dev, chan);
1179 goto error_clear_attrs;
1183 if (indio_dev->event_interface)
1184 clk = &dev_attr_current_timestamp_clock.attr;
1186 if (indio_dev->name)
1191 indio_dev->chan_attr_group.attrs = kcalloc(attrcount + 1,
1192 sizeof(indio_dev->chan_attr_group.attrs[0]),
1194 if (indio_dev->chan_attr_group.attrs == NULL) {
1196 goto error_clear_attrs;
1198 /* Copy across original attributes */
1199 if (indio_dev->info->attrs)
1200 memcpy(indio_dev->chan_attr_group.attrs,
1201 indio_dev->info->attrs->attrs,
1202 sizeof(indio_dev->chan_attr_group.attrs[0])
1204 attrn = attrcount_orig;
1205 /* Add all elements from the list. */
1206 list_for_each_entry(p, &indio_dev->channel_attr_list, l)
1207 indio_dev->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1208 if (indio_dev->name)
1209 indio_dev->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
1211 indio_dev->chan_attr_group.attrs[attrn++] = clk;
1213 indio_dev->groups[indio_dev->groupcounter++] =
1214 &indio_dev->chan_attr_group;
1219 iio_free_chan_devattr_list(&indio_dev->channel_attr_list);
1224 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
1227 iio_free_chan_devattr_list(&indio_dev->channel_attr_list);
1228 kfree(indio_dev->chan_attr_group.attrs);
1229 indio_dev->chan_attr_group.attrs = NULL;
1232 static void iio_dev_release(struct device *device)
1234 struct iio_dev *indio_dev = dev_to_iio_dev(device);
1235 if (indio_dev->modes & (INDIO_BUFFER_TRIGGERED | INDIO_EVENT_TRIGGERED))
1236 iio_device_unregister_trigger_consumer(indio_dev);
1237 iio_device_unregister_eventset(indio_dev);
1238 iio_device_unregister_sysfs(indio_dev);
1240 iio_buffer_put(indio_dev->buffer);
1242 ida_simple_remove(&iio_ida, indio_dev->id);
1246 struct device_type iio_device_type = {
1247 .name = "iio_device",
1248 .release = iio_dev_release,
1252 * iio_device_alloc() - allocate an iio_dev from a driver
1253 * @sizeof_priv: Space to allocate for private structure.
1255 struct iio_dev *iio_device_alloc(int sizeof_priv)
1257 struct iio_dev *dev;
1260 alloc_size = sizeof(struct iio_dev);
1262 alloc_size = ALIGN(alloc_size, IIO_ALIGN);
1263 alloc_size += sizeof_priv;
1265 /* ensure 32-byte alignment of whole construct ? */
1266 alloc_size += IIO_ALIGN - 1;
1268 dev = kzalloc(alloc_size, GFP_KERNEL);
1271 dev->dev.groups = dev->groups;
1272 dev->dev.type = &iio_device_type;
1273 dev->dev.bus = &iio_bus_type;
1274 device_initialize(&dev->dev);
1275 dev_set_drvdata(&dev->dev, (void *)dev);
1276 mutex_init(&dev->mlock);
1277 mutex_init(&dev->info_exist_lock);
1278 INIT_LIST_HEAD(&dev->channel_attr_list);
1280 dev->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
1282 /* cannot use a dev_err as the name isn't available */
1283 pr_err("failed to get device id\n");
1287 dev_set_name(&dev->dev, "iio:device%d", dev->id);
1288 INIT_LIST_HEAD(&dev->buffer_list);
1293 EXPORT_SYMBOL(iio_device_alloc);
1296 * iio_device_free() - free an iio_dev from a driver
1297 * @dev: the iio_dev associated with the device
1299 void iio_device_free(struct iio_dev *dev)
1302 put_device(&dev->dev);
1304 EXPORT_SYMBOL(iio_device_free);
1306 static void devm_iio_device_release(struct device *dev, void *res)
1308 iio_device_free(*(struct iio_dev **)res);
1311 static int devm_iio_device_match(struct device *dev, void *res, void *data)
1313 struct iio_dev **r = res;
1322 * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1323 * @dev: Device to allocate iio_dev for
1324 * @sizeof_priv: Space to allocate for private structure.
1326 * Managed iio_device_alloc. iio_dev allocated with this function is
1327 * automatically freed on driver detach.
1329 * If an iio_dev allocated with this function needs to be freed separately,
1330 * devm_iio_device_free() must be used.
1333 * Pointer to allocated iio_dev on success, NULL on failure.
1335 struct iio_dev *devm_iio_device_alloc(struct device *dev, int sizeof_priv)
1337 struct iio_dev **ptr, *iio_dev;
1339 ptr = devres_alloc(devm_iio_device_release, sizeof(*ptr),
1344 iio_dev = iio_device_alloc(sizeof_priv);
1347 devres_add(dev, ptr);
1354 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1357 * devm_iio_device_free - Resource-managed iio_device_free()
1358 * @dev: Device this iio_dev belongs to
1359 * @iio_dev: the iio_dev associated with the device
1361 * Free iio_dev allocated with devm_iio_device_alloc().
1363 void devm_iio_device_free(struct device *dev, struct iio_dev *iio_dev)
1367 rc = devres_release(dev, devm_iio_device_release,
1368 devm_iio_device_match, iio_dev);
1371 EXPORT_SYMBOL_GPL(devm_iio_device_free);
1374 * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1375 * @inode: Inode structure for identifying the device in the file system
1376 * @filp: File structure for iio device used to keep and later access
1379 * Return: 0 on success or -EBUSY if the device is already opened
1381 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1383 struct iio_dev *indio_dev = container_of(inode->i_cdev,
1384 struct iio_dev, chrdev);
1386 if (test_and_set_bit(IIO_BUSY_BIT_POS, &indio_dev->flags))
1389 iio_device_get(indio_dev);
1391 filp->private_data = indio_dev;
1397 * iio_chrdev_release() - chrdev file close buffer access and ioctls
1398 * @inode: Inode structure pointer for the char device
1399 * @filp: File structure pointer for the char device
1401 * Return: 0 for successful release
1403 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1405 struct iio_dev *indio_dev = container_of(inode->i_cdev,
1406 struct iio_dev, chrdev);
1407 clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
1408 iio_device_put(indio_dev);
1413 /* Somewhat of a cross file organization violation - ioctls here are actually
1415 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1417 struct iio_dev *indio_dev = filp->private_data;
1418 int __user *ip = (int __user *)arg;
1421 if (!indio_dev->info)
1424 if (cmd == IIO_GET_EVENT_FD_IOCTL) {
1425 fd = iio_event_getfd(indio_dev);
1428 if (copy_to_user(ip, &fd, sizeof(fd)))
1435 static const struct file_operations iio_buffer_fileops = {
1436 .read = iio_buffer_read_first_n_outer_addr,
1437 .release = iio_chrdev_release,
1438 .open = iio_chrdev_open,
1439 .poll = iio_buffer_poll_addr,
1440 .owner = THIS_MODULE,
1441 .llseek = noop_llseek,
1442 .unlocked_ioctl = iio_ioctl,
1443 .compat_ioctl = iio_ioctl,
1446 static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1449 const struct iio_chan_spec *channels = indio_dev->channels;
1451 if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1454 for (i = 0; i < indio_dev->num_channels - 1; i++) {
1455 if (channels[i].scan_index < 0)
1457 for (j = i + 1; j < indio_dev->num_channels; j++)
1458 if (channels[i].scan_index == channels[j].scan_index) {
1459 dev_err(&indio_dev->dev,
1460 "Duplicate scan index %d\n",
1461 channels[i].scan_index);
1469 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1472 * iio_device_register() - register a device with the IIO subsystem
1473 * @indio_dev: Device structure filled by the device driver
1475 int iio_device_register(struct iio_dev *indio_dev)
1479 /* If the calling driver did not initialize of_node, do it here */
1480 if (!indio_dev->dev.of_node && indio_dev->dev.parent)
1481 indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
1483 ret = iio_check_unique_scan_index(indio_dev);
1487 /* configure elements for the chrdev */
1488 indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), indio_dev->id);
1490 ret = iio_device_register_debugfs(indio_dev);
1492 dev_err(indio_dev->dev.parent,
1493 "Failed to register debugfs interfaces\n");
1497 ret = iio_buffer_alloc_sysfs_and_mask(indio_dev);
1499 dev_err(indio_dev->dev.parent,
1500 "Failed to create buffer sysfs interfaces\n");
1501 goto error_unreg_debugfs;
1504 ret = iio_device_register_sysfs(indio_dev);
1506 dev_err(indio_dev->dev.parent,
1507 "Failed to register sysfs interfaces\n");
1508 goto error_buffer_free_sysfs;
1510 ret = iio_device_register_eventset(indio_dev);
1512 dev_err(indio_dev->dev.parent,
1513 "Failed to register event set\n");
1514 goto error_free_sysfs;
1516 if (indio_dev->modes & (INDIO_BUFFER_TRIGGERED | INDIO_EVENT_TRIGGERED))
1517 iio_device_register_trigger_consumer(indio_dev);
1519 if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1520 indio_dev->setup_ops == NULL)
1521 indio_dev->setup_ops = &noop_ring_setup_ops;
1523 cdev_init(&indio_dev->chrdev, &iio_buffer_fileops);
1524 indio_dev->chrdev.owner = indio_dev->info->driver_module;
1525 indio_dev->chrdev.kobj.parent = &indio_dev->dev.kobj;
1526 ret = cdev_add(&indio_dev->chrdev, indio_dev->dev.devt, 1);
1528 goto error_unreg_eventset;
1530 ret = device_add(&indio_dev->dev);
1532 goto error_cdev_del;
1536 cdev_del(&indio_dev->chrdev);
1537 error_unreg_eventset:
1538 iio_device_unregister_eventset(indio_dev);
1540 iio_device_unregister_sysfs(indio_dev);
1541 error_buffer_free_sysfs:
1542 iio_buffer_free_sysfs_and_mask(indio_dev);
1543 error_unreg_debugfs:
1544 iio_device_unregister_debugfs(indio_dev);
1547 EXPORT_SYMBOL(iio_device_register);
1550 * iio_device_unregister() - unregister a device from the IIO subsystem
1551 * @indio_dev: Device structure representing the device.
1553 void iio_device_unregister(struct iio_dev *indio_dev)
1555 mutex_lock(&indio_dev->info_exist_lock);
1557 device_del(&indio_dev->dev);
1559 if (indio_dev->chrdev.dev)
1560 cdev_del(&indio_dev->chrdev);
1561 iio_device_unregister_debugfs(indio_dev);
1563 iio_disable_all_buffers(indio_dev);
1565 indio_dev->info = NULL;
1567 iio_device_wakeup_eventset(indio_dev);
1568 iio_buffer_wakeup_poll(indio_dev);
1570 mutex_unlock(&indio_dev->info_exist_lock);
1572 iio_buffer_free_sysfs_and_mask(indio_dev);
1574 EXPORT_SYMBOL(iio_device_unregister);
1576 static void devm_iio_device_unreg(struct device *dev, void *res)
1578 iio_device_unregister(*(struct iio_dev **)res);
1582 * devm_iio_device_register - Resource-managed iio_device_register()
1583 * @dev: Device to allocate iio_dev for
1584 * @indio_dev: Device structure filled by the device driver
1586 * Managed iio_device_register. The IIO device registered with this
1587 * function is automatically unregistered on driver detach. This function
1588 * calls iio_device_register() internally. Refer to that function for more
1591 * If an iio_dev registered with this function needs to be unregistered
1592 * separately, devm_iio_device_unregister() must be used.
1595 * 0 on success, negative error number on failure.
1597 int devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev)
1599 struct iio_dev **ptr;
1602 ptr = devres_alloc(devm_iio_device_unreg, sizeof(*ptr), GFP_KERNEL);
1607 ret = iio_device_register(indio_dev);
1609 devres_add(dev, ptr);
1615 EXPORT_SYMBOL_GPL(devm_iio_device_register);
1618 * devm_iio_device_unregister - Resource-managed iio_device_unregister()
1619 * @dev: Device this iio_dev belongs to
1620 * @indio_dev: the iio_dev associated with the device
1622 * Unregister iio_dev registered with devm_iio_device_register().
1624 void devm_iio_device_unregister(struct device *dev, struct iio_dev *indio_dev)
1628 rc = devres_release(dev, devm_iio_device_unreg,
1629 devm_iio_device_match, indio_dev);
1632 EXPORT_SYMBOL_GPL(devm_iio_device_unregister);
1635 * iio_device_claim_direct_mode - Keep device in direct mode
1636 * @indio_dev: the iio_dev associated with the device
1638 * If the device is in direct mode it is guaranteed to stay
1639 * that way until iio_device_release_direct_mode() is called.
1641 * Use with iio_device_release_direct_mode()
1643 * Returns: 0 on success, -EBUSY on failure
1645 int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
1647 mutex_lock(&indio_dev->mlock);
1649 if (iio_buffer_enabled(indio_dev)) {
1650 mutex_unlock(&indio_dev->mlock);
1655 EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
1658 * iio_device_release_direct_mode - releases claim on direct mode
1659 * @indio_dev: the iio_dev associated with the device
1661 * Release the claim. Device is no longer guaranteed to stay
1664 * Use with iio_device_claim_direct_mode()
1666 void iio_device_release_direct_mode(struct iio_dev *indio_dev)
1668 mutex_unlock(&indio_dev->mlock);
1670 EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
1672 subsys_initcall(iio_init);
1673 module_exit(iio_exit);
1675 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1676 MODULE_DESCRIPTION("Industrial I/O core");
1677 MODULE_LICENSE("GPL");