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/iio/iio.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>
35 /* IDA to assign each registered device a unique id */
36 static DEFINE_IDA(iio_ida);
38 static dev_t iio_devt;
40 #define IIO_DEV_MAX 256
41 struct bus_type iio_bus_type = {
44 EXPORT_SYMBOL(iio_bus_type);
46 static struct dentry *iio_debugfs_dentry;
48 static const char * const iio_direction[] = {
53 static const char * const iio_chan_type_name_spec[] = {
54 [IIO_VOLTAGE] = "voltage",
55 [IIO_CURRENT] = "current",
56 [IIO_POWER] = "power",
57 [IIO_ACCEL] = "accel",
58 [IIO_ANGL_VEL] = "anglvel",
60 [IIO_LIGHT] = "illuminance",
61 [IIO_INTENSITY] = "intensity",
62 [IIO_PROXIMITY] = "proximity",
64 [IIO_INCLI] = "incli",
67 [IIO_TIMESTAMP] = "timestamp",
68 [IIO_CAPACITANCE] = "capacitance",
69 [IIO_ALTVOLTAGE] = "altvoltage",
71 [IIO_PRESSURE] = "pressure",
72 [IIO_HUMIDITYRELATIVE] = "humidityrelative",
73 [IIO_ACTIVITY] = "activity",
74 [IIO_STEPS] = "steps",
75 [IIO_ENERGY] = "energy",
76 [IIO_DISTANCE] = "distance",
77 [IIO_VELOCITY] = "velocity",
78 [IIO_CONCENTRATION] = "concentration",
79 [IIO_RESISTANCE] = "resistance",
82 static const char * const iio_modifier_names[] = {
86 [IIO_MOD_X_AND_Y] = "x&y",
87 [IIO_MOD_X_AND_Z] = "x&z",
88 [IIO_MOD_Y_AND_Z] = "y&z",
89 [IIO_MOD_X_AND_Y_AND_Z] = "x&y&z",
90 [IIO_MOD_X_OR_Y] = "x|y",
91 [IIO_MOD_X_OR_Z] = "x|z",
92 [IIO_MOD_Y_OR_Z] = "y|z",
93 [IIO_MOD_X_OR_Y_OR_Z] = "x|y|z",
94 [IIO_MOD_ROOT_SUM_SQUARED_X_Y] = "sqrt(x^2+y^2)",
95 [IIO_MOD_SUM_SQUARED_X_Y_Z] = "x^2+y^2+z^2",
96 [IIO_MOD_LIGHT_BOTH] = "both",
97 [IIO_MOD_LIGHT_IR] = "ir",
98 [IIO_MOD_LIGHT_CLEAR] = "clear",
99 [IIO_MOD_LIGHT_RED] = "red",
100 [IIO_MOD_LIGHT_GREEN] = "green",
101 [IIO_MOD_LIGHT_BLUE] = "blue",
102 [IIO_MOD_QUATERNION] = "quaternion",
103 [IIO_MOD_TEMP_AMBIENT] = "ambient",
104 [IIO_MOD_TEMP_OBJECT] = "object",
105 [IIO_MOD_NORTH_MAGN] = "from_north_magnetic",
106 [IIO_MOD_NORTH_TRUE] = "from_north_true",
107 [IIO_MOD_NORTH_MAGN_TILT_COMP] = "from_north_magnetic_tilt_comp",
108 [IIO_MOD_NORTH_TRUE_TILT_COMP] = "from_north_true_tilt_comp",
109 [IIO_MOD_RUNNING] = "running",
110 [IIO_MOD_JOGGING] = "jogging",
111 [IIO_MOD_WALKING] = "walking",
112 [IIO_MOD_STILL] = "still",
113 [IIO_MOD_ROOT_SUM_SQUARED_X_Y_Z] = "sqrt(x^2+y^2+z^2)",
116 [IIO_MOD_CO2] = "co2",
117 [IIO_MOD_VOC] = "voc",
120 /* relies on pairs of these shared then separate */
121 static const char * const iio_chan_info_postfix[] = {
122 [IIO_CHAN_INFO_RAW] = "raw",
123 [IIO_CHAN_INFO_PROCESSED] = "input",
124 [IIO_CHAN_INFO_SCALE] = "scale",
125 [IIO_CHAN_INFO_OFFSET] = "offset",
126 [IIO_CHAN_INFO_CALIBSCALE] = "calibscale",
127 [IIO_CHAN_INFO_CALIBBIAS] = "calibbias",
128 [IIO_CHAN_INFO_PEAK] = "peak_raw",
129 [IIO_CHAN_INFO_PEAK_SCALE] = "peak_scale",
130 [IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW] = "quadrature_correction_raw",
131 [IIO_CHAN_INFO_AVERAGE_RAW] = "mean_raw",
132 [IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY]
133 = "filter_low_pass_3db_frequency",
134 [IIO_CHAN_INFO_HIGH_PASS_FILTER_3DB_FREQUENCY]
135 = "filter_high_pass_3db_frequency",
136 [IIO_CHAN_INFO_SAMP_FREQ] = "sampling_frequency",
137 [IIO_CHAN_INFO_FREQUENCY] = "frequency",
138 [IIO_CHAN_INFO_PHASE] = "phase",
139 [IIO_CHAN_INFO_HARDWAREGAIN] = "hardwaregain",
140 [IIO_CHAN_INFO_HYSTERESIS] = "hysteresis",
141 [IIO_CHAN_INFO_INT_TIME] = "integration_time",
142 [IIO_CHAN_INFO_ENABLE] = "en",
143 [IIO_CHAN_INFO_CALIBHEIGHT] = "calibheight",
144 [IIO_CHAN_INFO_CALIBWEIGHT] = "calibweight",
145 [IIO_CHAN_INFO_DEBOUNCE_COUNT] = "debounce_count",
146 [IIO_CHAN_INFO_DEBOUNCE_TIME] = "debounce_time",
147 [IIO_CHAN_INFO_CALIBEMISSIVITY] = "calibemissivity",
148 [IIO_CHAN_INFO_OVERSAMPLING_RATIO] = "oversampling_ratio",
152 * iio_find_channel_from_si() - get channel from its scan index
154 * @si: scan index to match
156 const struct iio_chan_spec
157 *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
161 for (i = 0; i < indio_dev->num_channels; i++)
162 if (indio_dev->channels[i].scan_index == si)
163 return &indio_dev->channels[i];
167 /* This turns up an awful lot */
168 ssize_t iio_read_const_attr(struct device *dev,
169 struct device_attribute *attr,
172 return sprintf(buf, "%s\n", to_iio_const_attr(attr)->string);
174 EXPORT_SYMBOL(iio_read_const_attr);
176 static int __init iio_init(void)
180 /* Register sysfs bus */
181 ret = bus_register(&iio_bus_type);
183 pr_err("could not register bus type\n");
187 ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
189 pr_err("failed to allocate char dev region\n");
190 goto error_unregister_bus_type;
193 iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
197 error_unregister_bus_type:
198 bus_unregister(&iio_bus_type);
203 static void __exit iio_exit(void)
206 unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
207 bus_unregister(&iio_bus_type);
208 debugfs_remove(iio_debugfs_dentry);
211 #if defined(CONFIG_DEBUG_FS)
212 static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
213 size_t count, loff_t *ppos)
215 struct iio_dev *indio_dev = file->private_data;
221 ret = indio_dev->info->debugfs_reg_access(indio_dev,
222 indio_dev->cached_reg_addr,
225 dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
227 len = snprintf(buf, sizeof(buf), "0x%X\n", val);
229 return simple_read_from_buffer(userbuf, count, ppos, buf, len);
232 static ssize_t iio_debugfs_write_reg(struct file *file,
233 const char __user *userbuf, size_t count, loff_t *ppos)
235 struct iio_dev *indio_dev = file->private_data;
240 count = min_t(size_t, count, (sizeof(buf)-1));
241 if (copy_from_user(buf, userbuf, count))
246 ret = sscanf(buf, "%i %i", ®, &val);
250 indio_dev->cached_reg_addr = reg;
253 indio_dev->cached_reg_addr = reg;
254 ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
257 dev_err(indio_dev->dev.parent, "%s: write failed\n",
269 static const struct file_operations iio_debugfs_reg_fops = {
271 .read = iio_debugfs_read_reg,
272 .write = iio_debugfs_write_reg,
275 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
277 debugfs_remove_recursive(indio_dev->debugfs_dentry);
280 static int iio_device_register_debugfs(struct iio_dev *indio_dev)
284 if (indio_dev->info->debugfs_reg_access == NULL)
287 if (!iio_debugfs_dentry)
290 indio_dev->debugfs_dentry =
291 debugfs_create_dir(dev_name(&indio_dev->dev),
293 if (indio_dev->debugfs_dentry == NULL) {
294 dev_warn(indio_dev->dev.parent,
295 "Failed to create debugfs directory\n");
299 d = debugfs_create_file("direct_reg_access", 0644,
300 indio_dev->debugfs_dentry,
301 indio_dev, &iio_debugfs_reg_fops);
303 iio_device_unregister_debugfs(indio_dev);
310 static int iio_device_register_debugfs(struct iio_dev *indio_dev)
315 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
318 #endif /* CONFIG_DEBUG_FS */
320 static ssize_t iio_read_channel_ext_info(struct device *dev,
321 struct device_attribute *attr,
324 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
325 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
326 const struct iio_chan_spec_ext_info *ext_info;
328 ext_info = &this_attr->c->ext_info[this_attr->address];
330 return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
333 static ssize_t iio_write_channel_ext_info(struct device *dev,
334 struct device_attribute *attr,
338 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
339 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
340 const struct iio_chan_spec_ext_info *ext_info;
342 ext_info = &this_attr->c->ext_info[this_attr->address];
344 return ext_info->write(indio_dev, ext_info->private,
345 this_attr->c, buf, len);
348 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
349 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
351 const struct iio_enum *e = (const struct iio_enum *)priv;
358 for (i = 0; i < e->num_items; ++i)
359 len += scnprintf(buf + len, PAGE_SIZE - len, "%s ", e->items[i]);
361 /* replace last space with a newline */
366 EXPORT_SYMBOL_GPL(iio_enum_available_read);
368 ssize_t iio_enum_read(struct iio_dev *indio_dev,
369 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
371 const struct iio_enum *e = (const struct iio_enum *)priv;
377 i = e->get(indio_dev, chan);
380 else if (i >= e->num_items)
383 return snprintf(buf, PAGE_SIZE, "%s\n", e->items[i]);
385 EXPORT_SYMBOL_GPL(iio_enum_read);
387 ssize_t iio_enum_write(struct iio_dev *indio_dev,
388 uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
391 const struct iio_enum *e = (const struct iio_enum *)priv;
398 for (i = 0; i < e->num_items; i++) {
399 if (sysfs_streq(buf, e->items[i]))
403 if (i == e->num_items)
406 ret = e->set(indio_dev, chan, i);
407 return ret ? ret : len;
409 EXPORT_SYMBOL_GPL(iio_enum_write);
412 * iio_format_value() - Formats a IIO value into its string representation
413 * @buf: The buffer to which the formatted value gets written
414 * @type: One of the IIO_VAL_... constants. This decides how the val
415 * and val2 parameters are formatted.
416 * @size: Number of IIO value entries contained in vals
417 * @vals: Pointer to the values, exact meaning depends on the
420 * Return: 0 by default, a negative number on failure or the
421 * total number of characters written for a type that belongs
422 * to the IIO_VAL_... constant.
424 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
426 unsigned long long tmp;
427 bool scale_db = false;
431 return sprintf(buf, "%d\n", vals[0]);
432 case IIO_VAL_INT_PLUS_MICRO_DB:
434 case IIO_VAL_INT_PLUS_MICRO:
436 return sprintf(buf, "-%ld.%06u%s\n", abs(vals[0]),
438 scale_db ? " dB" : "");
440 return sprintf(buf, "%d.%06u%s\n", vals[0], vals[1],
441 scale_db ? " dB" : "");
442 case IIO_VAL_INT_PLUS_NANO:
444 return sprintf(buf, "-%ld.%09u\n", abs(vals[0]),
447 return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
448 case IIO_VAL_FRACTIONAL:
449 tmp = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
450 vals[1] = do_div(tmp, 1000000000LL);
452 return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
453 case IIO_VAL_FRACTIONAL_LOG2:
454 tmp = (s64)vals[0] * 1000000000LL >> vals[1];
455 vals[1] = do_div(tmp, 1000000000LL);
457 return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
458 case IIO_VAL_INT_MULTIPLE:
463 for (i = 0; i < size; ++i)
464 len += snprintf(&buf[len], PAGE_SIZE - len, "%d ",
466 len += snprintf(&buf[len], PAGE_SIZE - len, "\n");
474 static ssize_t iio_read_channel_info(struct device *dev,
475 struct device_attribute *attr,
478 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
479 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
480 int vals[INDIO_MAX_RAW_ELEMENTS];
484 if (indio_dev->info->read_raw_multi)
485 ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
486 INDIO_MAX_RAW_ELEMENTS,
490 ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
491 &vals[0], &vals[1], this_attr->address);
496 return iio_format_value(buf, ret, val_len, vals);
500 * iio_str_to_fixpoint() - Parse a fixed-point number from a string
501 * @str: The string to parse
502 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
503 * @integer: The integer part of the number
504 * @fract: The fractional part of the number
506 * Returns 0 on success, or a negative error code if the string could not be
509 int iio_str_to_fixpoint(const char *str, int fract_mult,
510 int *integer, int *fract)
513 bool integer_part = true, negative = false;
518 } else if (str[0] == '+') {
523 if ('0' <= *str && *str <= '9') {
525 i = i * 10 + *str - '0';
527 f += fract_mult * (*str - '0');
530 } else if (*str == '\n') {
531 if (*(str + 1) == '\0')
535 } else if (*str == '.' && integer_part) {
536 integer_part = false;
555 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
557 static ssize_t iio_write_channel_info(struct device *dev,
558 struct device_attribute *attr,
562 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
563 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
564 int ret, fract_mult = 100000;
567 /* Assumes decimal - precision based on number of digits */
568 if (!indio_dev->info->write_raw)
571 if (indio_dev->info->write_raw_get_fmt)
572 switch (indio_dev->info->write_raw_get_fmt(indio_dev,
573 this_attr->c, this_attr->address)) {
574 case IIO_VAL_INT_PLUS_MICRO:
577 case IIO_VAL_INT_PLUS_NANO:
578 fract_mult = 100000000;
584 ret = iio_str_to_fixpoint(buf, fract_mult, &integer, &fract);
588 ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
589 integer, fract, this_attr->address);
597 int __iio_device_attr_init(struct device_attribute *dev_attr,
599 struct iio_chan_spec const *chan,
600 ssize_t (*readfunc)(struct device *dev,
601 struct device_attribute *attr,
603 ssize_t (*writefunc)(struct device *dev,
604 struct device_attribute *attr,
607 enum iio_shared_by shared_by)
612 sysfs_attr_init(&dev_attr->attr);
614 /* Build up postfix of <extend_name>_<modifier>_postfix */
615 if (chan->modified && (shared_by == IIO_SEPARATE)) {
616 if (chan->extend_name)
617 full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
618 iio_modifier_names[chan
623 full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
624 iio_modifier_names[chan
628 if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
629 full_postfix = kstrdup(postfix, GFP_KERNEL);
631 full_postfix = kasprintf(GFP_KERNEL,
636 if (full_postfix == NULL)
639 if (chan->differential) { /* Differential can not have modifier */
641 case IIO_SHARED_BY_ALL:
642 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
644 case IIO_SHARED_BY_DIR:
645 name = kasprintf(GFP_KERNEL, "%s_%s",
646 iio_direction[chan->output],
649 case IIO_SHARED_BY_TYPE:
650 name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
651 iio_direction[chan->output],
652 iio_chan_type_name_spec[chan->type],
653 iio_chan_type_name_spec[chan->type],
657 if (!chan->indexed) {
658 WARN_ON("Differential channels must be indexed\n");
660 goto error_free_full_postfix;
662 name = kasprintf(GFP_KERNEL,
664 iio_direction[chan->output],
665 iio_chan_type_name_spec[chan->type],
667 iio_chan_type_name_spec[chan->type],
672 } else { /* Single ended */
674 case IIO_SHARED_BY_ALL:
675 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
677 case IIO_SHARED_BY_DIR:
678 name = kasprintf(GFP_KERNEL, "%s_%s",
679 iio_direction[chan->output],
682 case IIO_SHARED_BY_TYPE:
683 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
684 iio_direction[chan->output],
685 iio_chan_type_name_spec[chan->type],
691 name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
692 iio_direction[chan->output],
693 iio_chan_type_name_spec[chan->type],
697 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
698 iio_direction[chan->output],
699 iio_chan_type_name_spec[chan->type],
706 goto error_free_full_postfix;
708 dev_attr->attr.name = name;
711 dev_attr->attr.mode |= S_IRUGO;
712 dev_attr->show = readfunc;
716 dev_attr->attr.mode |= S_IWUSR;
717 dev_attr->store = writefunc;
720 error_free_full_postfix:
726 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
728 kfree(dev_attr->attr.name);
731 int __iio_add_chan_devattr(const char *postfix,
732 struct iio_chan_spec const *chan,
733 ssize_t (*readfunc)(struct device *dev,
734 struct device_attribute *attr,
736 ssize_t (*writefunc)(struct device *dev,
737 struct device_attribute *attr,
741 enum iio_shared_by shared_by,
743 struct list_head *attr_list)
746 struct iio_dev_attr *iio_attr, *t;
748 iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
749 if (iio_attr == NULL)
751 ret = __iio_device_attr_init(&iio_attr->dev_attr,
753 readfunc, writefunc, shared_by);
755 goto error_iio_dev_attr_free;
757 iio_attr->address = mask;
758 list_for_each_entry(t, attr_list, l)
759 if (strcmp(t->dev_attr.attr.name,
760 iio_attr->dev_attr.attr.name) == 0) {
761 if (shared_by == IIO_SEPARATE)
762 dev_err(dev, "tried to double register : %s\n",
763 t->dev_attr.attr.name);
765 goto error_device_attr_deinit;
767 list_add(&iio_attr->l, attr_list);
771 error_device_attr_deinit:
772 __iio_device_attr_deinit(&iio_attr->dev_attr);
773 error_iio_dev_attr_free:
778 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
779 struct iio_chan_spec const *chan,
780 enum iio_shared_by shared_by,
781 const long *infomask)
783 int i, ret, attrcount = 0;
785 for_each_set_bit(i, infomask, sizeof(infomask)*8) {
786 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
788 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
790 &iio_read_channel_info,
791 &iio_write_channel_info,
795 &indio_dev->channel_attr_list);
796 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
806 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
807 struct iio_chan_spec const *chan)
809 int ret, attrcount = 0;
810 const struct iio_chan_spec_ext_info *ext_info;
812 if (chan->channel < 0)
814 ret = iio_device_add_info_mask_type(indio_dev, chan,
816 &chan->info_mask_separate);
821 ret = iio_device_add_info_mask_type(indio_dev, chan,
823 &chan->info_mask_shared_by_type);
828 ret = iio_device_add_info_mask_type(indio_dev, chan,
830 &chan->info_mask_shared_by_dir);
835 ret = iio_device_add_info_mask_type(indio_dev, chan,
837 &chan->info_mask_shared_by_all);
842 if (chan->ext_info) {
844 for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
845 ret = __iio_add_chan_devattr(ext_info->name,
848 &iio_read_channel_ext_info : NULL,
850 &iio_write_channel_ext_info : NULL,
854 &indio_dev->channel_attr_list);
856 if (ret == -EBUSY && ext_info->shared)
870 * iio_free_chan_devattr_list() - Free a list of IIO device attributes
871 * @attr_list: List of IIO device attributes
873 * This function frees the memory allocated for each of the IIO device
874 * attributes in the list.
876 void iio_free_chan_devattr_list(struct list_head *attr_list)
878 struct iio_dev_attr *p, *n;
880 list_for_each_entry_safe(p, n, attr_list, l) {
881 kfree(p->dev_attr.attr.name);
887 static ssize_t iio_show_dev_name(struct device *dev,
888 struct device_attribute *attr,
891 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
892 return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->name);
895 static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
897 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
899 int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
900 struct iio_dev_attr *p;
901 struct attribute **attr;
903 /* First count elements in any existing group */
904 if (indio_dev->info->attrs) {
905 attr = indio_dev->info->attrs->attrs;
906 while (*attr++ != NULL)
909 attrcount = attrcount_orig;
911 * New channel registration method - relies on the fact a group does
912 * not need to be initialized if its name is NULL.
914 if (indio_dev->channels)
915 for (i = 0; i < indio_dev->num_channels; i++) {
916 ret = iio_device_add_channel_sysfs(indio_dev,
920 goto error_clear_attrs;
927 indio_dev->chan_attr_group.attrs = kcalloc(attrcount + 1,
928 sizeof(indio_dev->chan_attr_group.attrs[0]),
930 if (indio_dev->chan_attr_group.attrs == NULL) {
932 goto error_clear_attrs;
934 /* Copy across original attributes */
935 if (indio_dev->info->attrs)
936 memcpy(indio_dev->chan_attr_group.attrs,
937 indio_dev->info->attrs->attrs,
938 sizeof(indio_dev->chan_attr_group.attrs[0])
940 attrn = attrcount_orig;
941 /* Add all elements from the list. */
942 list_for_each_entry(p, &indio_dev->channel_attr_list, l)
943 indio_dev->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
945 indio_dev->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
947 indio_dev->groups[indio_dev->groupcounter++] =
948 &indio_dev->chan_attr_group;
953 iio_free_chan_devattr_list(&indio_dev->channel_attr_list);
958 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
961 iio_free_chan_devattr_list(&indio_dev->channel_attr_list);
962 kfree(indio_dev->chan_attr_group.attrs);
963 indio_dev->chan_attr_group.attrs = NULL;
966 static void iio_dev_release(struct device *device)
968 struct iio_dev *indio_dev = dev_to_iio_dev(device);
969 if (indio_dev->modes & (INDIO_BUFFER_TRIGGERED | INDIO_EVENT_TRIGGERED))
970 iio_device_unregister_trigger_consumer(indio_dev);
971 iio_device_unregister_eventset(indio_dev);
972 iio_device_unregister_sysfs(indio_dev);
974 iio_buffer_put(indio_dev->buffer);
976 ida_simple_remove(&iio_ida, indio_dev->id);
980 struct device_type iio_device_type = {
981 .name = "iio_device",
982 .release = iio_dev_release,
986 * iio_device_alloc() - allocate an iio_dev from a driver
987 * @sizeof_priv: Space to allocate for private structure.
989 struct iio_dev *iio_device_alloc(int sizeof_priv)
994 alloc_size = sizeof(struct iio_dev);
996 alloc_size = ALIGN(alloc_size, IIO_ALIGN);
997 alloc_size += sizeof_priv;
999 /* ensure 32-byte alignment of whole construct ? */
1000 alloc_size += IIO_ALIGN - 1;
1002 dev = kzalloc(alloc_size, GFP_KERNEL);
1005 dev->dev.groups = dev->groups;
1006 dev->dev.type = &iio_device_type;
1007 dev->dev.bus = &iio_bus_type;
1008 device_initialize(&dev->dev);
1009 dev_set_drvdata(&dev->dev, (void *)dev);
1010 mutex_init(&dev->mlock);
1011 mutex_init(&dev->info_exist_lock);
1012 INIT_LIST_HEAD(&dev->channel_attr_list);
1014 dev->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
1016 /* cannot use a dev_err as the name isn't available */
1017 pr_err("failed to get device id\n");
1021 dev_set_name(&dev->dev, "iio:device%d", dev->id);
1022 INIT_LIST_HEAD(&dev->buffer_list);
1027 EXPORT_SYMBOL(iio_device_alloc);
1030 * iio_device_free() - free an iio_dev from a driver
1031 * @dev: the iio_dev associated with the device
1033 void iio_device_free(struct iio_dev *dev)
1036 put_device(&dev->dev);
1038 EXPORT_SYMBOL(iio_device_free);
1040 static void devm_iio_device_release(struct device *dev, void *res)
1042 iio_device_free(*(struct iio_dev **)res);
1045 static int devm_iio_device_match(struct device *dev, void *res, void *data)
1047 struct iio_dev **r = res;
1056 * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1057 * @dev: Device to allocate iio_dev for
1058 * @sizeof_priv: Space to allocate for private structure.
1060 * Managed iio_device_alloc. iio_dev allocated with this function is
1061 * automatically freed on driver detach.
1063 * If an iio_dev allocated with this function needs to be freed separately,
1064 * devm_iio_device_free() must be used.
1067 * Pointer to allocated iio_dev on success, NULL on failure.
1069 struct iio_dev *devm_iio_device_alloc(struct device *dev, int sizeof_priv)
1071 struct iio_dev **ptr, *iio_dev;
1073 ptr = devres_alloc(devm_iio_device_release, sizeof(*ptr),
1078 iio_dev = iio_device_alloc(sizeof_priv);
1081 devres_add(dev, ptr);
1088 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1091 * devm_iio_device_free - Resource-managed iio_device_free()
1092 * @dev: Device this iio_dev belongs to
1093 * @iio_dev: the iio_dev associated with the device
1095 * Free iio_dev allocated with devm_iio_device_alloc().
1097 void devm_iio_device_free(struct device *dev, struct iio_dev *iio_dev)
1101 rc = devres_release(dev, devm_iio_device_release,
1102 devm_iio_device_match, iio_dev);
1105 EXPORT_SYMBOL_GPL(devm_iio_device_free);
1108 * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1109 * @inode: Inode structure for identifying the device in the file system
1110 * @filp: File structure for iio device used to keep and later access
1113 * Return: 0 on success or -EBUSY if the device is already opened
1115 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1117 struct iio_dev *indio_dev = container_of(inode->i_cdev,
1118 struct iio_dev, chrdev);
1120 if (test_and_set_bit(IIO_BUSY_BIT_POS, &indio_dev->flags))
1123 iio_device_get(indio_dev);
1125 filp->private_data = indio_dev;
1131 * iio_chrdev_release() - chrdev file close buffer access and ioctls
1132 * @inode: Inode structure pointer for the char device
1133 * @filp: File structure pointer for the char device
1135 * Return: 0 for successful release
1137 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1139 struct iio_dev *indio_dev = container_of(inode->i_cdev,
1140 struct iio_dev, chrdev);
1141 clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
1142 iio_device_put(indio_dev);
1147 /* Somewhat of a cross file organization violation - ioctls here are actually
1149 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1151 struct iio_dev *indio_dev = filp->private_data;
1152 int __user *ip = (int __user *)arg;
1155 if (!indio_dev->info)
1158 if (cmd == IIO_GET_EVENT_FD_IOCTL) {
1159 fd = iio_event_getfd(indio_dev);
1162 if (copy_to_user(ip, &fd, sizeof(fd)))
1169 static const struct file_operations iio_buffer_fileops = {
1170 .read = iio_buffer_read_first_n_outer_addr,
1171 .release = iio_chrdev_release,
1172 .open = iio_chrdev_open,
1173 .poll = iio_buffer_poll_addr,
1174 .owner = THIS_MODULE,
1175 .llseek = noop_llseek,
1176 .unlocked_ioctl = iio_ioctl,
1177 .compat_ioctl = iio_ioctl,
1180 static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1183 const struct iio_chan_spec *channels = indio_dev->channels;
1185 if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1188 for (i = 0; i < indio_dev->num_channels - 1; i++) {
1189 if (channels[i].scan_index < 0)
1191 for (j = i + 1; j < indio_dev->num_channels; j++)
1192 if (channels[i].scan_index == channels[j].scan_index) {
1193 dev_err(&indio_dev->dev,
1194 "Duplicate scan index %d\n",
1195 channels[i].scan_index);
1203 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1206 * iio_device_register() - register a device with the IIO subsystem
1207 * @indio_dev: Device structure filled by the device driver
1209 int iio_device_register(struct iio_dev *indio_dev)
1213 /* If the calling driver did not initialize of_node, do it here */
1214 if (!indio_dev->dev.of_node && indio_dev->dev.parent)
1215 indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
1217 ret = iio_check_unique_scan_index(indio_dev);
1221 /* configure elements for the chrdev */
1222 indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), indio_dev->id);
1224 ret = iio_device_register_debugfs(indio_dev);
1226 dev_err(indio_dev->dev.parent,
1227 "Failed to register debugfs interfaces\n");
1231 ret = iio_buffer_alloc_sysfs_and_mask(indio_dev);
1233 dev_err(indio_dev->dev.parent,
1234 "Failed to create buffer sysfs interfaces\n");
1235 goto error_unreg_debugfs;
1238 ret = iio_device_register_sysfs(indio_dev);
1240 dev_err(indio_dev->dev.parent,
1241 "Failed to register sysfs interfaces\n");
1242 goto error_buffer_free_sysfs;
1244 ret = iio_device_register_eventset(indio_dev);
1246 dev_err(indio_dev->dev.parent,
1247 "Failed to register event set\n");
1248 goto error_free_sysfs;
1250 if (indio_dev->modes & (INDIO_BUFFER_TRIGGERED | INDIO_EVENT_TRIGGERED))
1251 iio_device_register_trigger_consumer(indio_dev);
1253 if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1254 indio_dev->setup_ops == NULL)
1255 indio_dev->setup_ops = &noop_ring_setup_ops;
1257 cdev_init(&indio_dev->chrdev, &iio_buffer_fileops);
1258 indio_dev->chrdev.owner = indio_dev->info->driver_module;
1259 indio_dev->chrdev.kobj.parent = &indio_dev->dev.kobj;
1260 ret = cdev_add(&indio_dev->chrdev, indio_dev->dev.devt, 1);
1262 goto error_unreg_eventset;
1264 ret = device_add(&indio_dev->dev);
1266 goto error_cdev_del;
1270 cdev_del(&indio_dev->chrdev);
1271 error_unreg_eventset:
1272 iio_device_unregister_eventset(indio_dev);
1274 iio_device_unregister_sysfs(indio_dev);
1275 error_buffer_free_sysfs:
1276 iio_buffer_free_sysfs_and_mask(indio_dev);
1277 error_unreg_debugfs:
1278 iio_device_unregister_debugfs(indio_dev);
1281 EXPORT_SYMBOL(iio_device_register);
1284 * iio_device_unregister() - unregister a device from the IIO subsystem
1285 * @indio_dev: Device structure representing the device.
1287 void iio_device_unregister(struct iio_dev *indio_dev)
1289 mutex_lock(&indio_dev->info_exist_lock);
1291 device_del(&indio_dev->dev);
1293 if (indio_dev->chrdev.dev)
1294 cdev_del(&indio_dev->chrdev);
1295 iio_device_unregister_debugfs(indio_dev);
1297 iio_disable_all_buffers(indio_dev);
1299 indio_dev->info = NULL;
1301 iio_device_wakeup_eventset(indio_dev);
1302 iio_buffer_wakeup_poll(indio_dev);
1304 mutex_unlock(&indio_dev->info_exist_lock);
1306 iio_buffer_free_sysfs_and_mask(indio_dev);
1308 EXPORT_SYMBOL(iio_device_unregister);
1310 static void devm_iio_device_unreg(struct device *dev, void *res)
1312 iio_device_unregister(*(struct iio_dev **)res);
1316 * devm_iio_device_register - Resource-managed iio_device_register()
1317 * @dev: Device to allocate iio_dev for
1318 * @indio_dev: Device structure filled by the device driver
1320 * Managed iio_device_register. The IIO device registered with this
1321 * function is automatically unregistered on driver detach. This function
1322 * calls iio_device_register() internally. Refer to that function for more
1325 * If an iio_dev registered with this function needs to be unregistered
1326 * separately, devm_iio_device_unregister() must be used.
1329 * 0 on success, negative error number on failure.
1331 int devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev)
1333 struct iio_dev **ptr;
1336 ptr = devres_alloc(devm_iio_device_unreg, sizeof(*ptr), GFP_KERNEL);
1341 ret = iio_device_register(indio_dev);
1343 devres_add(dev, ptr);
1349 EXPORT_SYMBOL_GPL(devm_iio_device_register);
1352 * devm_iio_device_unregister - Resource-managed iio_device_unregister()
1353 * @dev: Device this iio_dev belongs to
1354 * @indio_dev: the iio_dev associated with the device
1356 * Unregister iio_dev registered with devm_iio_device_register().
1358 void devm_iio_device_unregister(struct device *dev, struct iio_dev *indio_dev)
1362 rc = devres_release(dev, devm_iio_device_unreg,
1363 devm_iio_device_match, indio_dev);
1366 EXPORT_SYMBOL_GPL(devm_iio_device_unregister);
1368 subsys_initcall(iio_init);
1369 module_exit(iio_exit);
1371 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1372 MODULE_DESCRIPTION("Industrial I/O core");
1373 MODULE_LICENSE("GPL");