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 __init iio_init(void)
185 /* Register sysfs bus */
186 ret = bus_register(&iio_bus_type);
188 pr_err("could not register bus type\n");
192 ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
194 pr_err("failed to allocate char dev region\n");
195 goto error_unregister_bus_type;
198 iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
202 error_unregister_bus_type:
203 bus_unregister(&iio_bus_type);
208 static void __exit iio_exit(void)
211 unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
212 bus_unregister(&iio_bus_type);
213 debugfs_remove(iio_debugfs_dentry);
216 #if defined(CONFIG_DEBUG_FS)
217 static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
218 size_t count, loff_t *ppos)
220 struct iio_dev *indio_dev = file->private_data;
226 ret = indio_dev->info->debugfs_reg_access(indio_dev,
227 indio_dev->cached_reg_addr,
230 dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
232 len = snprintf(buf, sizeof(buf), "0x%X\n", val);
234 return simple_read_from_buffer(userbuf, count, ppos, buf, len);
237 static ssize_t iio_debugfs_write_reg(struct file *file,
238 const char __user *userbuf, size_t count, loff_t *ppos)
240 struct iio_dev *indio_dev = file->private_data;
245 count = min_t(size_t, count, (sizeof(buf)-1));
246 if (copy_from_user(buf, userbuf, count))
251 ret = sscanf(buf, "%i %i", ®, &val);
255 indio_dev->cached_reg_addr = reg;
258 indio_dev->cached_reg_addr = reg;
259 ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
262 dev_err(indio_dev->dev.parent, "%s: write failed\n",
274 static const struct file_operations iio_debugfs_reg_fops = {
276 .read = iio_debugfs_read_reg,
277 .write = iio_debugfs_write_reg,
280 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
282 debugfs_remove_recursive(indio_dev->debugfs_dentry);
285 static int iio_device_register_debugfs(struct iio_dev *indio_dev)
289 if (indio_dev->info->debugfs_reg_access == NULL)
292 if (!iio_debugfs_dentry)
295 indio_dev->debugfs_dentry =
296 debugfs_create_dir(dev_name(&indio_dev->dev),
298 if (indio_dev->debugfs_dentry == NULL) {
299 dev_warn(indio_dev->dev.parent,
300 "Failed to create debugfs directory\n");
304 d = debugfs_create_file("direct_reg_access", 0644,
305 indio_dev->debugfs_dentry,
306 indio_dev, &iio_debugfs_reg_fops);
308 iio_device_unregister_debugfs(indio_dev);
315 static int iio_device_register_debugfs(struct iio_dev *indio_dev)
320 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
323 #endif /* CONFIG_DEBUG_FS */
325 static ssize_t iio_read_channel_ext_info(struct device *dev,
326 struct device_attribute *attr,
329 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
330 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
331 const struct iio_chan_spec_ext_info *ext_info;
333 ext_info = &this_attr->c->ext_info[this_attr->address];
335 return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
338 static ssize_t iio_write_channel_ext_info(struct device *dev,
339 struct device_attribute *attr,
343 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
344 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
345 const struct iio_chan_spec_ext_info *ext_info;
347 ext_info = &this_attr->c->ext_info[this_attr->address];
349 return ext_info->write(indio_dev, ext_info->private,
350 this_attr->c, buf, len);
353 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
354 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
356 const struct iio_enum *e = (const struct iio_enum *)priv;
363 for (i = 0; i < e->num_items; ++i)
364 len += scnprintf(buf + len, PAGE_SIZE - len, "%s ", e->items[i]);
366 /* replace last space with a newline */
371 EXPORT_SYMBOL_GPL(iio_enum_available_read);
373 ssize_t iio_enum_read(struct iio_dev *indio_dev,
374 uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
376 const struct iio_enum *e = (const struct iio_enum *)priv;
382 i = e->get(indio_dev, chan);
385 else if (i >= e->num_items)
388 return snprintf(buf, PAGE_SIZE, "%s\n", e->items[i]);
390 EXPORT_SYMBOL_GPL(iio_enum_read);
392 ssize_t iio_enum_write(struct iio_dev *indio_dev,
393 uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
396 const struct iio_enum *e = (const struct iio_enum *)priv;
403 for (i = 0; i < e->num_items; i++) {
404 if (sysfs_streq(buf, e->items[i]))
408 if (i == e->num_items)
411 ret = e->set(indio_dev, chan, i);
412 return ret ? ret : len;
414 EXPORT_SYMBOL_GPL(iio_enum_write);
416 static const struct iio_mount_matrix iio_mount_idmatrix = {
424 static int iio_setup_mount_idmatrix(const struct device *dev,
425 struct iio_mount_matrix *matrix)
427 *matrix = iio_mount_idmatrix;
428 dev_info(dev, "mounting matrix not found: using identity...\n");
432 ssize_t iio_show_mount_matrix(struct iio_dev *indio_dev, uintptr_t priv,
433 const struct iio_chan_spec *chan, char *buf)
435 const struct iio_mount_matrix *mtx = ((iio_get_mount_matrix_t *)
436 priv)(indio_dev, chan);
442 mtx = &iio_mount_idmatrix;
444 return snprintf(buf, PAGE_SIZE, "%s, %s, %s; %s, %s, %s; %s, %s, %s\n",
445 mtx->rotation[0], mtx->rotation[1], mtx->rotation[2],
446 mtx->rotation[3], mtx->rotation[4], mtx->rotation[5],
447 mtx->rotation[6], mtx->rotation[7], mtx->rotation[8]);
449 EXPORT_SYMBOL_GPL(iio_show_mount_matrix);
452 * of_iio_read_mount_matrix() - retrieve iio device mounting matrix from
453 * device-tree "mount-matrix" property
454 * @dev: device the mounting matrix property is assigned to
455 * @propname: device specific mounting matrix property name
456 * @matrix: where to store retrieved matrix
458 * If device is assigned no mounting matrix property, a default 3x3 identity
459 * matrix will be filled in.
461 * Return: 0 if success, or a negative error code on failure.
464 int of_iio_read_mount_matrix(const struct device *dev,
465 const char *propname,
466 struct iio_mount_matrix *matrix)
469 int err = of_property_read_string_array(dev->of_node,
470 propname, matrix->rotation,
471 ARRAY_SIZE(iio_mount_idmatrix.rotation));
473 if (err == ARRAY_SIZE(iio_mount_idmatrix.rotation))
477 /* Invalid number of matrix entries. */
481 /* Invalid matrix declaration format. */
485 /* Matrix was not declared at all: fallback to identity. */
486 return iio_setup_mount_idmatrix(dev, matrix);
489 int of_iio_read_mount_matrix(const struct device *dev,
490 const char *propname,
491 struct iio_mount_matrix *matrix)
493 return iio_setup_mount_idmatrix(dev, matrix);
496 EXPORT_SYMBOL(of_iio_read_mount_matrix);
499 * iio_format_value() - Formats a IIO value into its string representation
500 * @buf: The buffer to which the formatted value gets written
501 * @type: One of the IIO_VAL_... constants. This decides how the val
502 * and val2 parameters are formatted.
503 * @size: Number of IIO value entries contained in vals
504 * @vals: Pointer to the values, exact meaning depends on the
507 * Return: 0 by default, a negative number on failure or the
508 * total number of characters written for a type that belongs
509 * to the IIO_VAL_... constant.
511 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
513 unsigned long long tmp;
514 bool scale_db = false;
518 return sprintf(buf, "%d\n", vals[0]);
519 case IIO_VAL_INT_PLUS_MICRO_DB:
521 case IIO_VAL_INT_PLUS_MICRO:
523 return sprintf(buf, "-%d.%06u%s\n", abs(vals[0]),
524 -vals[1], scale_db ? " dB" : "");
526 return sprintf(buf, "%d.%06u%s\n", vals[0], vals[1],
527 scale_db ? " dB" : "");
528 case IIO_VAL_INT_PLUS_NANO:
530 return sprintf(buf, "-%d.%09u\n", abs(vals[0]),
533 return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
534 case IIO_VAL_FRACTIONAL:
535 tmp = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
536 vals[1] = do_div(tmp, 1000000000LL);
538 return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
539 case IIO_VAL_FRACTIONAL_LOG2:
540 tmp = (s64)vals[0] * 1000000000LL >> vals[1];
541 vals[1] = do_div(tmp, 1000000000LL);
543 return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
544 case IIO_VAL_INT_MULTIPLE:
549 for (i = 0; i < size; ++i)
550 len += snprintf(&buf[len], PAGE_SIZE - len, "%d ",
552 len += snprintf(&buf[len], PAGE_SIZE - len, "\n");
559 EXPORT_SYMBOL_GPL(iio_format_value);
561 static ssize_t iio_read_channel_info(struct device *dev,
562 struct device_attribute *attr,
565 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
566 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
567 int vals[INDIO_MAX_RAW_ELEMENTS];
571 if (indio_dev->info->read_raw_multi)
572 ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
573 INDIO_MAX_RAW_ELEMENTS,
577 ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
578 &vals[0], &vals[1], this_attr->address);
583 return iio_format_value(buf, ret, val_len, vals);
587 * iio_str_to_fixpoint() - Parse a fixed-point number from a string
588 * @str: The string to parse
589 * @fract_mult: Multiplier for the first decimal place, should be a power of 10
590 * @integer: The integer part of the number
591 * @fract: The fractional part of the number
593 * Returns 0 on success, or a negative error code if the string could not be
596 int iio_str_to_fixpoint(const char *str, int fract_mult,
597 int *integer, int *fract)
600 bool integer_part = true, negative = false;
602 if (fract_mult == 0) {
605 return kstrtoint(str, 0, integer);
611 } else if (str[0] == '+') {
616 if ('0' <= *str && *str <= '9') {
618 i = i * 10 + *str - '0';
620 f += fract_mult * (*str - '0');
623 } else if (*str == '\n') {
624 if (*(str + 1) == '\0')
628 } else if (*str == '.' && integer_part) {
629 integer_part = false;
648 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
650 static ssize_t iio_write_channel_info(struct device *dev,
651 struct device_attribute *attr,
655 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
656 struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
657 int ret, fract_mult = 100000;
660 /* Assumes decimal - precision based on number of digits */
661 if (!indio_dev->info->write_raw)
664 if (indio_dev->info->write_raw_get_fmt)
665 switch (indio_dev->info->write_raw_get_fmt(indio_dev,
666 this_attr->c, this_attr->address)) {
670 case IIO_VAL_INT_PLUS_MICRO:
673 case IIO_VAL_INT_PLUS_NANO:
674 fract_mult = 100000000;
680 ret = iio_str_to_fixpoint(buf, fract_mult, &integer, &fract);
684 ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
685 integer, fract, this_attr->address);
693 int __iio_device_attr_init(struct device_attribute *dev_attr,
695 struct iio_chan_spec const *chan,
696 ssize_t (*readfunc)(struct device *dev,
697 struct device_attribute *attr,
699 ssize_t (*writefunc)(struct device *dev,
700 struct device_attribute *attr,
703 enum iio_shared_by shared_by)
708 sysfs_attr_init(&dev_attr->attr);
710 /* Build up postfix of <extend_name>_<modifier>_postfix */
711 if (chan->modified && (shared_by == IIO_SEPARATE)) {
712 if (chan->extend_name)
713 full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
714 iio_modifier_names[chan
719 full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
720 iio_modifier_names[chan
724 if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
725 full_postfix = kstrdup(postfix, GFP_KERNEL);
727 full_postfix = kasprintf(GFP_KERNEL,
732 if (full_postfix == NULL)
735 if (chan->differential) { /* Differential can not have modifier */
737 case IIO_SHARED_BY_ALL:
738 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
740 case IIO_SHARED_BY_DIR:
741 name = kasprintf(GFP_KERNEL, "%s_%s",
742 iio_direction[chan->output],
745 case IIO_SHARED_BY_TYPE:
746 name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
747 iio_direction[chan->output],
748 iio_chan_type_name_spec[chan->type],
749 iio_chan_type_name_spec[chan->type],
753 if (!chan->indexed) {
754 WARN(1, "Differential channels must be indexed\n");
756 goto error_free_full_postfix;
758 name = kasprintf(GFP_KERNEL,
760 iio_direction[chan->output],
761 iio_chan_type_name_spec[chan->type],
763 iio_chan_type_name_spec[chan->type],
768 } else { /* Single ended */
770 case IIO_SHARED_BY_ALL:
771 name = kasprintf(GFP_KERNEL, "%s", full_postfix);
773 case IIO_SHARED_BY_DIR:
774 name = kasprintf(GFP_KERNEL, "%s_%s",
775 iio_direction[chan->output],
778 case IIO_SHARED_BY_TYPE:
779 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
780 iio_direction[chan->output],
781 iio_chan_type_name_spec[chan->type],
787 name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
788 iio_direction[chan->output],
789 iio_chan_type_name_spec[chan->type],
793 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
794 iio_direction[chan->output],
795 iio_chan_type_name_spec[chan->type],
802 goto error_free_full_postfix;
804 dev_attr->attr.name = name;
807 dev_attr->attr.mode |= S_IRUGO;
808 dev_attr->show = readfunc;
812 dev_attr->attr.mode |= S_IWUSR;
813 dev_attr->store = writefunc;
816 error_free_full_postfix:
822 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
824 kfree(dev_attr->attr.name);
827 int __iio_add_chan_devattr(const char *postfix,
828 struct iio_chan_spec const *chan,
829 ssize_t (*readfunc)(struct device *dev,
830 struct device_attribute *attr,
832 ssize_t (*writefunc)(struct device *dev,
833 struct device_attribute *attr,
837 enum iio_shared_by shared_by,
839 struct list_head *attr_list)
842 struct iio_dev_attr *iio_attr, *t;
844 iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
845 if (iio_attr == NULL)
847 ret = __iio_device_attr_init(&iio_attr->dev_attr,
849 readfunc, writefunc, shared_by);
851 goto error_iio_dev_attr_free;
853 iio_attr->address = mask;
854 list_for_each_entry(t, attr_list, l)
855 if (strcmp(t->dev_attr.attr.name,
856 iio_attr->dev_attr.attr.name) == 0) {
857 if (shared_by == IIO_SEPARATE)
858 dev_err(dev, "tried to double register : %s\n",
859 t->dev_attr.attr.name);
861 goto error_device_attr_deinit;
863 list_add(&iio_attr->l, attr_list);
867 error_device_attr_deinit:
868 __iio_device_attr_deinit(&iio_attr->dev_attr);
869 error_iio_dev_attr_free:
874 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
875 struct iio_chan_spec const *chan,
876 enum iio_shared_by shared_by,
877 const long *infomask)
879 int i, ret, attrcount = 0;
881 for_each_set_bit(i, infomask, sizeof(infomask)*8) {
882 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
884 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
886 &iio_read_channel_info,
887 &iio_write_channel_info,
891 &indio_dev->channel_attr_list);
892 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
902 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
903 struct iio_chan_spec const *chan)
905 int ret, attrcount = 0;
906 const struct iio_chan_spec_ext_info *ext_info;
908 if (chan->channel < 0)
910 ret = iio_device_add_info_mask_type(indio_dev, chan,
912 &chan->info_mask_separate);
917 ret = iio_device_add_info_mask_type(indio_dev, chan,
919 &chan->info_mask_shared_by_type);
924 ret = iio_device_add_info_mask_type(indio_dev, chan,
926 &chan->info_mask_shared_by_dir);
931 ret = iio_device_add_info_mask_type(indio_dev, chan,
933 &chan->info_mask_shared_by_all);
938 if (chan->ext_info) {
940 for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
941 ret = __iio_add_chan_devattr(ext_info->name,
944 &iio_read_channel_ext_info : NULL,
946 &iio_write_channel_ext_info : NULL,
950 &indio_dev->channel_attr_list);
952 if (ret == -EBUSY && ext_info->shared)
966 * iio_free_chan_devattr_list() - Free a list of IIO device attributes
967 * @attr_list: List of IIO device attributes
969 * This function frees the memory allocated for each of the IIO device
970 * attributes in the list.
972 void iio_free_chan_devattr_list(struct list_head *attr_list)
974 struct iio_dev_attr *p, *n;
976 list_for_each_entry_safe(p, n, attr_list, l) {
977 kfree(p->dev_attr.attr.name);
983 static ssize_t iio_show_dev_name(struct device *dev,
984 struct device_attribute *attr,
987 struct iio_dev *indio_dev = dev_to_iio_dev(dev);
988 return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->name);
991 static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
993 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
995 int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
996 struct iio_dev_attr *p;
997 struct attribute **attr;
999 /* First count elements in any existing group */
1000 if (indio_dev->info->attrs) {
1001 attr = indio_dev->info->attrs->attrs;
1002 while (*attr++ != NULL)
1005 attrcount = attrcount_orig;
1007 * New channel registration method - relies on the fact a group does
1008 * not need to be initialized if its name is NULL.
1010 if (indio_dev->channels)
1011 for (i = 0; i < indio_dev->num_channels; i++) {
1012 ret = iio_device_add_channel_sysfs(indio_dev,
1016 goto error_clear_attrs;
1020 if (indio_dev->name)
1023 indio_dev->chan_attr_group.attrs = kcalloc(attrcount + 1,
1024 sizeof(indio_dev->chan_attr_group.attrs[0]),
1026 if (indio_dev->chan_attr_group.attrs == NULL) {
1028 goto error_clear_attrs;
1030 /* Copy across original attributes */
1031 if (indio_dev->info->attrs)
1032 memcpy(indio_dev->chan_attr_group.attrs,
1033 indio_dev->info->attrs->attrs,
1034 sizeof(indio_dev->chan_attr_group.attrs[0])
1036 attrn = attrcount_orig;
1037 /* Add all elements from the list. */
1038 list_for_each_entry(p, &indio_dev->channel_attr_list, l)
1039 indio_dev->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
1040 if (indio_dev->name)
1041 indio_dev->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
1043 indio_dev->groups[indio_dev->groupcounter++] =
1044 &indio_dev->chan_attr_group;
1049 iio_free_chan_devattr_list(&indio_dev->channel_attr_list);
1054 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
1057 iio_free_chan_devattr_list(&indio_dev->channel_attr_list);
1058 kfree(indio_dev->chan_attr_group.attrs);
1059 indio_dev->chan_attr_group.attrs = NULL;
1062 static void iio_dev_release(struct device *device)
1064 struct iio_dev *indio_dev = dev_to_iio_dev(device);
1065 if (indio_dev->modes & (INDIO_BUFFER_TRIGGERED | INDIO_EVENT_TRIGGERED))
1066 iio_device_unregister_trigger_consumer(indio_dev);
1067 iio_device_unregister_eventset(indio_dev);
1068 iio_device_unregister_sysfs(indio_dev);
1070 iio_buffer_put(indio_dev->buffer);
1072 ida_simple_remove(&iio_ida, indio_dev->id);
1076 struct device_type iio_device_type = {
1077 .name = "iio_device",
1078 .release = iio_dev_release,
1082 * iio_device_alloc() - allocate an iio_dev from a driver
1083 * @sizeof_priv: Space to allocate for private structure.
1085 struct iio_dev *iio_device_alloc(int sizeof_priv)
1087 struct iio_dev *dev;
1090 alloc_size = sizeof(struct iio_dev);
1092 alloc_size = ALIGN(alloc_size, IIO_ALIGN);
1093 alloc_size += sizeof_priv;
1095 /* ensure 32-byte alignment of whole construct ? */
1096 alloc_size += IIO_ALIGN - 1;
1098 dev = kzalloc(alloc_size, GFP_KERNEL);
1101 dev->dev.groups = dev->groups;
1102 dev->dev.type = &iio_device_type;
1103 dev->dev.bus = &iio_bus_type;
1104 device_initialize(&dev->dev);
1105 dev_set_drvdata(&dev->dev, (void *)dev);
1106 mutex_init(&dev->mlock);
1107 mutex_init(&dev->info_exist_lock);
1108 INIT_LIST_HEAD(&dev->channel_attr_list);
1110 dev->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
1112 /* cannot use a dev_err as the name isn't available */
1113 pr_err("failed to get device id\n");
1117 dev_set_name(&dev->dev, "iio:device%d", dev->id);
1118 INIT_LIST_HEAD(&dev->buffer_list);
1123 EXPORT_SYMBOL(iio_device_alloc);
1126 * iio_device_free() - free an iio_dev from a driver
1127 * @dev: the iio_dev associated with the device
1129 void iio_device_free(struct iio_dev *dev)
1132 put_device(&dev->dev);
1134 EXPORT_SYMBOL(iio_device_free);
1136 static void devm_iio_device_release(struct device *dev, void *res)
1138 iio_device_free(*(struct iio_dev **)res);
1141 static int devm_iio_device_match(struct device *dev, void *res, void *data)
1143 struct iio_dev **r = res;
1152 * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1153 * @dev: Device to allocate iio_dev for
1154 * @sizeof_priv: Space to allocate for private structure.
1156 * Managed iio_device_alloc. iio_dev allocated with this function is
1157 * automatically freed on driver detach.
1159 * If an iio_dev allocated with this function needs to be freed separately,
1160 * devm_iio_device_free() must be used.
1163 * Pointer to allocated iio_dev on success, NULL on failure.
1165 struct iio_dev *devm_iio_device_alloc(struct device *dev, int sizeof_priv)
1167 struct iio_dev **ptr, *iio_dev;
1169 ptr = devres_alloc(devm_iio_device_release, sizeof(*ptr),
1174 iio_dev = iio_device_alloc(sizeof_priv);
1177 devres_add(dev, ptr);
1184 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1187 * devm_iio_device_free - Resource-managed iio_device_free()
1188 * @dev: Device this iio_dev belongs to
1189 * @iio_dev: the iio_dev associated with the device
1191 * Free iio_dev allocated with devm_iio_device_alloc().
1193 void devm_iio_device_free(struct device *dev, struct iio_dev *iio_dev)
1197 rc = devres_release(dev, devm_iio_device_release,
1198 devm_iio_device_match, iio_dev);
1201 EXPORT_SYMBOL_GPL(devm_iio_device_free);
1204 * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1205 * @inode: Inode structure for identifying the device in the file system
1206 * @filp: File structure for iio device used to keep and later access
1209 * Return: 0 on success or -EBUSY if the device is already opened
1211 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1213 struct iio_dev *indio_dev = container_of(inode->i_cdev,
1214 struct iio_dev, chrdev);
1216 if (test_and_set_bit(IIO_BUSY_BIT_POS, &indio_dev->flags))
1219 iio_device_get(indio_dev);
1221 filp->private_data = indio_dev;
1227 * iio_chrdev_release() - chrdev file close buffer access and ioctls
1228 * @inode: Inode structure pointer for the char device
1229 * @filp: File structure pointer for the char device
1231 * Return: 0 for successful release
1233 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1235 struct iio_dev *indio_dev = container_of(inode->i_cdev,
1236 struct iio_dev, chrdev);
1237 clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
1238 iio_device_put(indio_dev);
1243 /* Somewhat of a cross file organization violation - ioctls here are actually
1245 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1247 struct iio_dev *indio_dev = filp->private_data;
1248 int __user *ip = (int __user *)arg;
1251 if (!indio_dev->info)
1254 if (cmd == IIO_GET_EVENT_FD_IOCTL) {
1255 fd = iio_event_getfd(indio_dev);
1258 if (copy_to_user(ip, &fd, sizeof(fd)))
1265 static const struct file_operations iio_buffer_fileops = {
1266 .read = iio_buffer_read_first_n_outer_addr,
1267 .release = iio_chrdev_release,
1268 .open = iio_chrdev_open,
1269 .poll = iio_buffer_poll_addr,
1270 .owner = THIS_MODULE,
1271 .llseek = noop_llseek,
1272 .unlocked_ioctl = iio_ioctl,
1273 .compat_ioctl = iio_ioctl,
1276 static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1279 const struct iio_chan_spec *channels = indio_dev->channels;
1281 if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1284 for (i = 0; i < indio_dev->num_channels - 1; i++) {
1285 if (channels[i].scan_index < 0)
1287 for (j = i + 1; j < indio_dev->num_channels; j++)
1288 if (channels[i].scan_index == channels[j].scan_index) {
1289 dev_err(&indio_dev->dev,
1290 "Duplicate scan index %d\n",
1291 channels[i].scan_index);
1299 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1302 * iio_device_register() - register a device with the IIO subsystem
1303 * @indio_dev: Device structure filled by the device driver
1305 int iio_device_register(struct iio_dev *indio_dev)
1309 /* If the calling driver did not initialize of_node, do it here */
1310 if (!indio_dev->dev.of_node && indio_dev->dev.parent)
1311 indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
1313 ret = iio_check_unique_scan_index(indio_dev);
1317 /* configure elements for the chrdev */
1318 indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), indio_dev->id);
1320 ret = iio_device_register_debugfs(indio_dev);
1322 dev_err(indio_dev->dev.parent,
1323 "Failed to register debugfs interfaces\n");
1327 ret = iio_buffer_alloc_sysfs_and_mask(indio_dev);
1329 dev_err(indio_dev->dev.parent,
1330 "Failed to create buffer sysfs interfaces\n");
1331 goto error_unreg_debugfs;
1334 ret = iio_device_register_sysfs(indio_dev);
1336 dev_err(indio_dev->dev.parent,
1337 "Failed to register sysfs interfaces\n");
1338 goto error_buffer_free_sysfs;
1340 ret = iio_device_register_eventset(indio_dev);
1342 dev_err(indio_dev->dev.parent,
1343 "Failed to register event set\n");
1344 goto error_free_sysfs;
1346 if (indio_dev->modes & (INDIO_BUFFER_TRIGGERED | INDIO_EVENT_TRIGGERED))
1347 iio_device_register_trigger_consumer(indio_dev);
1349 if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1350 indio_dev->setup_ops == NULL)
1351 indio_dev->setup_ops = &noop_ring_setup_ops;
1353 cdev_init(&indio_dev->chrdev, &iio_buffer_fileops);
1354 indio_dev->chrdev.owner = indio_dev->info->driver_module;
1355 indio_dev->chrdev.kobj.parent = &indio_dev->dev.kobj;
1356 ret = cdev_add(&indio_dev->chrdev, indio_dev->dev.devt, 1);
1358 goto error_unreg_eventset;
1360 ret = device_add(&indio_dev->dev);
1362 goto error_cdev_del;
1366 cdev_del(&indio_dev->chrdev);
1367 error_unreg_eventset:
1368 iio_device_unregister_eventset(indio_dev);
1370 iio_device_unregister_sysfs(indio_dev);
1371 error_buffer_free_sysfs:
1372 iio_buffer_free_sysfs_and_mask(indio_dev);
1373 error_unreg_debugfs:
1374 iio_device_unregister_debugfs(indio_dev);
1377 EXPORT_SYMBOL(iio_device_register);
1380 * iio_device_unregister() - unregister a device from the IIO subsystem
1381 * @indio_dev: Device structure representing the device.
1383 void iio_device_unregister(struct iio_dev *indio_dev)
1385 mutex_lock(&indio_dev->info_exist_lock);
1387 device_del(&indio_dev->dev);
1389 if (indio_dev->chrdev.dev)
1390 cdev_del(&indio_dev->chrdev);
1391 iio_device_unregister_debugfs(indio_dev);
1393 iio_disable_all_buffers(indio_dev);
1395 indio_dev->info = NULL;
1397 iio_device_wakeup_eventset(indio_dev);
1398 iio_buffer_wakeup_poll(indio_dev);
1400 mutex_unlock(&indio_dev->info_exist_lock);
1402 iio_buffer_free_sysfs_and_mask(indio_dev);
1404 EXPORT_SYMBOL(iio_device_unregister);
1406 static void devm_iio_device_unreg(struct device *dev, void *res)
1408 iio_device_unregister(*(struct iio_dev **)res);
1412 * devm_iio_device_register - Resource-managed iio_device_register()
1413 * @dev: Device to allocate iio_dev for
1414 * @indio_dev: Device structure filled by the device driver
1416 * Managed iio_device_register. The IIO device registered with this
1417 * function is automatically unregistered on driver detach. This function
1418 * calls iio_device_register() internally. Refer to that function for more
1421 * If an iio_dev registered with this function needs to be unregistered
1422 * separately, devm_iio_device_unregister() must be used.
1425 * 0 on success, negative error number on failure.
1427 int devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev)
1429 struct iio_dev **ptr;
1432 ptr = devres_alloc(devm_iio_device_unreg, sizeof(*ptr), GFP_KERNEL);
1437 ret = iio_device_register(indio_dev);
1439 devres_add(dev, ptr);
1445 EXPORT_SYMBOL_GPL(devm_iio_device_register);
1448 * devm_iio_device_unregister - Resource-managed iio_device_unregister()
1449 * @dev: Device this iio_dev belongs to
1450 * @indio_dev: the iio_dev associated with the device
1452 * Unregister iio_dev registered with devm_iio_device_register().
1454 void devm_iio_device_unregister(struct device *dev, struct iio_dev *indio_dev)
1458 rc = devres_release(dev, devm_iio_device_unreg,
1459 devm_iio_device_match, indio_dev);
1462 EXPORT_SYMBOL_GPL(devm_iio_device_unregister);
1465 * iio_device_claim_direct_mode - Keep device in direct mode
1466 * @indio_dev: the iio_dev associated with the device
1468 * If the device is in direct mode it is guaranteed to stay
1469 * that way until iio_device_release_direct_mode() is called.
1471 * Use with iio_device_release_direct_mode()
1473 * Returns: 0 on success, -EBUSY on failure
1475 int iio_device_claim_direct_mode(struct iio_dev *indio_dev)
1477 mutex_lock(&indio_dev->mlock);
1479 if (iio_buffer_enabled(indio_dev)) {
1480 mutex_unlock(&indio_dev->mlock);
1485 EXPORT_SYMBOL_GPL(iio_device_claim_direct_mode);
1488 * iio_device_release_direct_mode - releases claim on direct mode
1489 * @indio_dev: the iio_dev associated with the device
1491 * Release the claim. Device is no longer guaranteed to stay
1494 * Use with iio_device_claim_direct_mode()
1496 void iio_device_release_direct_mode(struct iio_dev *indio_dev)
1498 mutex_unlock(&indio_dev->mlock);
1500 EXPORT_SYMBOL_GPL(iio_device_release_direct_mode);
1502 subsys_initcall(iio_init);
1503 module_exit(iio_exit);
1505 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1506 MODULE_DESCRIPTION("Industrial I/O core");
1507 MODULE_LICENSE("GPL");