Upgrade to 4.4.50-rt62
[kvmfornfv.git] / kernel / drivers / iio / industrialio-core.c
1 /* The industrial I/O core
2  *
3  * Copyright (c) 2008 Jonathan Cameron
4  *
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.
8  *
9  * Based on elements of hwmon and input subsystems.
10  */
11
12 #define pr_fmt(fmt) "iio-core: " fmt
13
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>
20 #include <linux/fs.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>
29 #include "iio_core.h"
30 #include "iio_core_trigger.h"
31 #include <linux/iio/sysfs.h>
32 #include <linux/iio/events.h>
33 #include <linux/iio/buffer.h>
34
35 /* IDA to assign each registered device a unique id */
36 static DEFINE_IDA(iio_ida);
37
38 static dev_t iio_devt;
39
40 #define IIO_DEV_MAX 256
41 struct bus_type iio_bus_type = {
42         .name = "iio",
43 };
44 EXPORT_SYMBOL(iio_bus_type);
45
46 static struct dentry *iio_debugfs_dentry;
47
48 static const char * const iio_direction[] = {
49         [0] = "in",
50         [1] = "out",
51 };
52
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",
59         [IIO_MAGN] = "magn",
60         [IIO_LIGHT] = "illuminance",
61         [IIO_INTENSITY] = "intensity",
62         [IIO_PROXIMITY] = "proximity",
63         [IIO_TEMP] = "temp",
64         [IIO_INCLI] = "incli",
65         [IIO_ROT] = "rot",
66         [IIO_ANGL] = "angl",
67         [IIO_TIMESTAMP] = "timestamp",
68         [IIO_CAPACITANCE] = "capacitance",
69         [IIO_ALTVOLTAGE] = "altvoltage",
70         [IIO_CCT] = "cct",
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",
80 };
81
82 static const char * const iio_modifier_names[] = {
83         [IIO_MOD_X] = "x",
84         [IIO_MOD_Y] = "y",
85         [IIO_MOD_Z] = "z",
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)",
114         [IIO_MOD_I] = "i",
115         [IIO_MOD_Q] = "q",
116         [IIO_MOD_CO2] = "co2",
117         [IIO_MOD_VOC] = "voc",
118 };
119
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",
149 };
150
151 /**
152  * iio_find_channel_from_si() - get channel from its scan index
153  * @indio_dev:          device
154  * @si:                 scan index to match
155  */
156 const struct iio_chan_spec
157 *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
158 {
159         int i;
160
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];
164         return NULL;
165 }
166
167 /* This turns up an awful lot */
168 ssize_t iio_read_const_attr(struct device *dev,
169                             struct device_attribute *attr,
170                             char *buf)
171 {
172         return sprintf(buf, "%s\n", to_iio_const_attr(attr)->string);
173 }
174 EXPORT_SYMBOL(iio_read_const_attr);
175
176 static int __init iio_init(void)
177 {
178         int ret;
179
180         /* Register sysfs bus */
181         ret  = bus_register(&iio_bus_type);
182         if (ret < 0) {
183                 pr_err("could not register bus type\n");
184                 goto error_nothing;
185         }
186
187         ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
188         if (ret < 0) {
189                 pr_err("failed to allocate char dev region\n");
190                 goto error_unregister_bus_type;
191         }
192
193         iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
194
195         return 0;
196
197 error_unregister_bus_type:
198         bus_unregister(&iio_bus_type);
199 error_nothing:
200         return ret;
201 }
202
203 static void __exit iio_exit(void)
204 {
205         if (iio_devt)
206                 unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
207         bus_unregister(&iio_bus_type);
208         debugfs_remove(iio_debugfs_dentry);
209 }
210
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)
214 {
215         struct iio_dev *indio_dev = file->private_data;
216         char buf[20];
217         unsigned val = 0;
218         ssize_t len;
219         int ret;
220
221         ret = indio_dev->info->debugfs_reg_access(indio_dev,
222                                                   indio_dev->cached_reg_addr,
223                                                   0, &val);
224         if (ret)
225                 dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
226
227         len = snprintf(buf, sizeof(buf), "0x%X\n", val);
228
229         return simple_read_from_buffer(userbuf, count, ppos, buf, len);
230 }
231
232 static ssize_t iio_debugfs_write_reg(struct file *file,
233                      const char __user *userbuf, size_t count, loff_t *ppos)
234 {
235         struct iio_dev *indio_dev = file->private_data;
236         unsigned reg, val;
237         char buf[80];
238         int ret;
239
240         count = min_t(size_t, count, (sizeof(buf)-1));
241         if (copy_from_user(buf, userbuf, count))
242                 return -EFAULT;
243
244         buf[count] = 0;
245
246         ret = sscanf(buf, "%i %i", &reg, &val);
247
248         switch (ret) {
249         case 1:
250                 indio_dev->cached_reg_addr = reg;
251                 break;
252         case 2:
253                 indio_dev->cached_reg_addr = reg;
254                 ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
255                                                           val, NULL);
256                 if (ret) {
257                         dev_err(indio_dev->dev.parent, "%s: write failed\n",
258                                 __func__);
259                         return ret;
260                 }
261                 break;
262         default:
263                 return -EINVAL;
264         }
265
266         return count;
267 }
268
269 static const struct file_operations iio_debugfs_reg_fops = {
270         .open = simple_open,
271         .read = iio_debugfs_read_reg,
272         .write = iio_debugfs_write_reg,
273 };
274
275 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
276 {
277         debugfs_remove_recursive(indio_dev->debugfs_dentry);
278 }
279
280 static int iio_device_register_debugfs(struct iio_dev *indio_dev)
281 {
282         struct dentry *d;
283
284         if (indio_dev->info->debugfs_reg_access == NULL)
285                 return 0;
286
287         if (!iio_debugfs_dentry)
288                 return 0;
289
290         indio_dev->debugfs_dentry =
291                 debugfs_create_dir(dev_name(&indio_dev->dev),
292                                    iio_debugfs_dentry);
293         if (indio_dev->debugfs_dentry == NULL) {
294                 dev_warn(indio_dev->dev.parent,
295                          "Failed to create debugfs directory\n");
296                 return -EFAULT;
297         }
298
299         d = debugfs_create_file("direct_reg_access", 0644,
300                                 indio_dev->debugfs_dentry,
301                                 indio_dev, &iio_debugfs_reg_fops);
302         if (!d) {
303                 iio_device_unregister_debugfs(indio_dev);
304                 return -ENOMEM;
305         }
306
307         return 0;
308 }
309 #else
310 static int iio_device_register_debugfs(struct iio_dev *indio_dev)
311 {
312         return 0;
313 }
314
315 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
316 {
317 }
318 #endif /* CONFIG_DEBUG_FS */
319
320 static ssize_t iio_read_channel_ext_info(struct device *dev,
321                                      struct device_attribute *attr,
322                                      char *buf)
323 {
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;
327
328         ext_info = &this_attr->c->ext_info[this_attr->address];
329
330         return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
331 }
332
333 static ssize_t iio_write_channel_ext_info(struct device *dev,
334                                      struct device_attribute *attr,
335                                      const char *buf,
336                                          size_t len)
337 {
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;
341
342         ext_info = &this_attr->c->ext_info[this_attr->address];
343
344         return ext_info->write(indio_dev, ext_info->private,
345                                this_attr->c, buf, len);
346 }
347
348 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
349         uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
350 {
351         const struct iio_enum *e = (const struct iio_enum *)priv;
352         unsigned int i;
353         size_t len = 0;
354
355         if (!e->num_items)
356                 return 0;
357
358         for (i = 0; i < e->num_items; ++i)
359                 len += scnprintf(buf + len, PAGE_SIZE - len, "%s ", e->items[i]);
360
361         /* replace last space with a newline */
362         buf[len - 1] = '\n';
363
364         return len;
365 }
366 EXPORT_SYMBOL_GPL(iio_enum_available_read);
367
368 ssize_t iio_enum_read(struct iio_dev *indio_dev,
369         uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
370 {
371         const struct iio_enum *e = (const struct iio_enum *)priv;
372         int i;
373
374         if (!e->get)
375                 return -EINVAL;
376
377         i = e->get(indio_dev, chan);
378         if (i < 0)
379                 return i;
380         else if (i >= e->num_items)
381                 return -EINVAL;
382
383         return snprintf(buf, PAGE_SIZE, "%s\n", e->items[i]);
384 }
385 EXPORT_SYMBOL_GPL(iio_enum_read);
386
387 ssize_t iio_enum_write(struct iio_dev *indio_dev,
388         uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
389         size_t len)
390 {
391         const struct iio_enum *e = (const struct iio_enum *)priv;
392         unsigned int i;
393         int ret;
394
395         if (!e->set)
396                 return -EINVAL;
397
398         for (i = 0; i < e->num_items; i++) {
399                 if (sysfs_streq(buf, e->items[i]))
400                         break;
401         }
402
403         if (i == e->num_items)
404                 return -EINVAL;
405
406         ret = e->set(indio_dev, chan, i);
407         return ret ? ret : len;
408 }
409 EXPORT_SYMBOL_GPL(iio_enum_write);
410
411 /**
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
418  *              type parameter.
419  *
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.
423  */
424 ssize_t iio_format_value(char *buf, unsigned int type, int size, int *vals)
425 {
426         unsigned long long tmp;
427         bool scale_db = false;
428
429         switch (type) {
430         case IIO_VAL_INT:
431                 return sprintf(buf, "%d\n", vals[0]);
432         case IIO_VAL_INT_PLUS_MICRO_DB:
433                 scale_db = true;
434         case IIO_VAL_INT_PLUS_MICRO:
435                 if (vals[1] < 0)
436                         return sprintf(buf, "-%d.%06u%s\n", abs(vals[0]),
437                                        -vals[1], scale_db ? " dB" : "");
438                 else
439                         return sprintf(buf, "%d.%06u%s\n", vals[0], vals[1],
440                                 scale_db ? " dB" : "");
441         case IIO_VAL_INT_PLUS_NANO:
442                 if (vals[1] < 0)
443                         return sprintf(buf, "-%d.%09u\n", abs(vals[0]),
444                                        -vals[1]);
445                 else
446                         return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
447         case IIO_VAL_FRACTIONAL:
448                 tmp = div_s64((s64)vals[0] * 1000000000LL, vals[1]);
449                 vals[0] = (int)div_s64_rem(tmp, 1000000000, &vals[1]);
450                 return sprintf(buf, "%d.%09u\n", vals[0], abs(vals[1]));
451         case IIO_VAL_FRACTIONAL_LOG2:
452                 tmp = (s64)vals[0] * 1000000000LL >> vals[1];
453                 vals[1] = do_div(tmp, 1000000000LL);
454                 vals[0] = tmp;
455                 return sprintf(buf, "%d.%09u\n", vals[0], vals[1]);
456         case IIO_VAL_INT_MULTIPLE:
457         {
458                 int i;
459                 int len = 0;
460
461                 for (i = 0; i < size; ++i)
462                         len += snprintf(&buf[len], PAGE_SIZE - len, "%d ",
463                                                                 vals[i]);
464                 len += snprintf(&buf[len], PAGE_SIZE - len, "\n");
465                 return len;
466         }
467         default:
468                 return 0;
469         }
470 }
471
472 static ssize_t iio_read_channel_info(struct device *dev,
473                                      struct device_attribute *attr,
474                                      char *buf)
475 {
476         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
477         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
478         int vals[INDIO_MAX_RAW_ELEMENTS];
479         int ret;
480         int val_len = 2;
481
482         if (indio_dev->info->read_raw_multi)
483                 ret = indio_dev->info->read_raw_multi(indio_dev, this_attr->c,
484                                                         INDIO_MAX_RAW_ELEMENTS,
485                                                         vals, &val_len,
486                                                         this_attr->address);
487         else
488                 ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
489                                     &vals[0], &vals[1], this_attr->address);
490
491         if (ret < 0)
492                 return ret;
493
494         return iio_format_value(buf, ret, val_len, vals);
495 }
496
497 /**
498  * iio_str_to_fixpoint() - Parse a fixed-point number from a string
499  * @str: The string to parse
500  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
501  * @integer: The integer part of the number
502  * @fract: The fractional part of the number
503  *
504  * Returns 0 on success, or a negative error code if the string could not be
505  * parsed.
506  */
507 int iio_str_to_fixpoint(const char *str, int fract_mult,
508         int *integer, int *fract)
509 {
510         int i = 0, f = 0;
511         bool integer_part = true, negative = false;
512
513         if (str[0] == '-') {
514                 negative = true;
515                 str++;
516         } else if (str[0] == '+') {
517                 str++;
518         }
519
520         while (*str) {
521                 if ('0' <= *str && *str <= '9') {
522                         if (integer_part) {
523                                 i = i * 10 + *str - '0';
524                         } else {
525                                 f += fract_mult * (*str - '0');
526                                 fract_mult /= 10;
527                         }
528                 } else if (*str == '\n') {
529                         if (*(str + 1) == '\0')
530                                 break;
531                         else
532                                 return -EINVAL;
533                 } else if (*str == '.' && integer_part) {
534                         integer_part = false;
535                 } else {
536                         return -EINVAL;
537                 }
538                 str++;
539         }
540
541         if (negative) {
542                 if (i)
543                         i = -i;
544                 else
545                         f = -f;
546         }
547
548         *integer = i;
549         *fract = f;
550
551         return 0;
552 }
553 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
554
555 static ssize_t iio_write_channel_info(struct device *dev,
556                                       struct device_attribute *attr,
557                                       const char *buf,
558                                       size_t len)
559 {
560         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
561         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
562         int ret, fract_mult = 100000;
563         int integer, fract;
564
565         /* Assumes decimal - precision based on number of digits */
566         if (!indio_dev->info->write_raw)
567                 return -EINVAL;
568
569         if (indio_dev->info->write_raw_get_fmt)
570                 switch (indio_dev->info->write_raw_get_fmt(indio_dev,
571                         this_attr->c, this_attr->address)) {
572                 case IIO_VAL_INT_PLUS_MICRO:
573                         fract_mult = 100000;
574                         break;
575                 case IIO_VAL_INT_PLUS_NANO:
576                         fract_mult = 100000000;
577                         break;
578                 default:
579                         return -EINVAL;
580                 }
581
582         ret = iio_str_to_fixpoint(buf, fract_mult, &integer, &fract);
583         if (ret)
584                 return ret;
585
586         ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
587                                          integer, fract, this_attr->address);
588         if (ret)
589                 return ret;
590
591         return len;
592 }
593
594 static
595 int __iio_device_attr_init(struct device_attribute *dev_attr,
596                            const char *postfix,
597                            struct iio_chan_spec const *chan,
598                            ssize_t (*readfunc)(struct device *dev,
599                                                struct device_attribute *attr,
600                                                char *buf),
601                            ssize_t (*writefunc)(struct device *dev,
602                                                 struct device_attribute *attr,
603                                                 const char *buf,
604                                                 size_t len),
605                            enum iio_shared_by shared_by)
606 {
607         int ret = 0;
608         char *name = NULL;
609         char *full_postfix;
610         sysfs_attr_init(&dev_attr->attr);
611
612         /* Build up postfix of <extend_name>_<modifier>_postfix */
613         if (chan->modified && (shared_by == IIO_SEPARATE)) {
614                 if (chan->extend_name)
615                         full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
616                                                  iio_modifier_names[chan
617                                                                     ->channel2],
618                                                  chan->extend_name,
619                                                  postfix);
620                 else
621                         full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
622                                                  iio_modifier_names[chan
623                                                                     ->channel2],
624                                                  postfix);
625         } else {
626                 if (chan->extend_name == NULL || shared_by != IIO_SEPARATE)
627                         full_postfix = kstrdup(postfix, GFP_KERNEL);
628                 else
629                         full_postfix = kasprintf(GFP_KERNEL,
630                                                  "%s_%s",
631                                                  chan->extend_name,
632                                                  postfix);
633         }
634         if (full_postfix == NULL)
635                 return -ENOMEM;
636
637         if (chan->differential) { /* Differential can not have modifier */
638                 switch (shared_by) {
639                 case IIO_SHARED_BY_ALL:
640                         name = kasprintf(GFP_KERNEL, "%s", full_postfix);
641                         break;
642                 case IIO_SHARED_BY_DIR:
643                         name = kasprintf(GFP_KERNEL, "%s_%s",
644                                                 iio_direction[chan->output],
645                                                 full_postfix);
646                         break;
647                 case IIO_SHARED_BY_TYPE:
648                         name = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
649                                             iio_direction[chan->output],
650                                             iio_chan_type_name_spec[chan->type],
651                                             iio_chan_type_name_spec[chan->type],
652                                             full_postfix);
653                         break;
654                 case IIO_SEPARATE:
655                         if (!chan->indexed) {
656                                 WARN(1, "Differential channels must be indexed\n");
657                                 ret = -EINVAL;
658                                 goto error_free_full_postfix;
659                         }
660                         name = kasprintf(GFP_KERNEL,
661                                             "%s_%s%d-%s%d_%s",
662                                             iio_direction[chan->output],
663                                             iio_chan_type_name_spec[chan->type],
664                                             chan->channel,
665                                             iio_chan_type_name_spec[chan->type],
666                                             chan->channel2,
667                                             full_postfix);
668                         break;
669                 }
670         } else { /* Single ended */
671                 switch (shared_by) {
672                 case IIO_SHARED_BY_ALL:
673                         name = kasprintf(GFP_KERNEL, "%s", full_postfix);
674                         break;
675                 case IIO_SHARED_BY_DIR:
676                         name = kasprintf(GFP_KERNEL, "%s_%s",
677                                                 iio_direction[chan->output],
678                                                 full_postfix);
679                         break;
680                 case IIO_SHARED_BY_TYPE:
681                         name = kasprintf(GFP_KERNEL, "%s_%s_%s",
682                                             iio_direction[chan->output],
683                                             iio_chan_type_name_spec[chan->type],
684                                             full_postfix);
685                         break;
686
687                 case IIO_SEPARATE:
688                         if (chan->indexed)
689                                 name = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
690                                                     iio_direction[chan->output],
691                                                     iio_chan_type_name_spec[chan->type],
692                                                     chan->channel,
693                                                     full_postfix);
694                         else
695                                 name = kasprintf(GFP_KERNEL, "%s_%s_%s",
696                                                     iio_direction[chan->output],
697                                                     iio_chan_type_name_spec[chan->type],
698                                                     full_postfix);
699                         break;
700                 }
701         }
702         if (name == NULL) {
703                 ret = -ENOMEM;
704                 goto error_free_full_postfix;
705         }
706         dev_attr->attr.name = name;
707
708         if (readfunc) {
709                 dev_attr->attr.mode |= S_IRUGO;
710                 dev_attr->show = readfunc;
711         }
712
713         if (writefunc) {
714                 dev_attr->attr.mode |= S_IWUSR;
715                 dev_attr->store = writefunc;
716         }
717
718 error_free_full_postfix:
719         kfree(full_postfix);
720
721         return ret;
722 }
723
724 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
725 {
726         kfree(dev_attr->attr.name);
727 }
728
729 int __iio_add_chan_devattr(const char *postfix,
730                            struct iio_chan_spec const *chan,
731                            ssize_t (*readfunc)(struct device *dev,
732                                                struct device_attribute *attr,
733                                                char *buf),
734                            ssize_t (*writefunc)(struct device *dev,
735                                                 struct device_attribute *attr,
736                                                 const char *buf,
737                                                 size_t len),
738                            u64 mask,
739                            enum iio_shared_by shared_by,
740                            struct device *dev,
741                            struct list_head *attr_list)
742 {
743         int ret;
744         struct iio_dev_attr *iio_attr, *t;
745
746         iio_attr = kzalloc(sizeof(*iio_attr), GFP_KERNEL);
747         if (iio_attr == NULL)
748                 return -ENOMEM;
749         ret = __iio_device_attr_init(&iio_attr->dev_attr,
750                                      postfix, chan,
751                                      readfunc, writefunc, shared_by);
752         if (ret)
753                 goto error_iio_dev_attr_free;
754         iio_attr->c = chan;
755         iio_attr->address = mask;
756         list_for_each_entry(t, attr_list, l)
757                 if (strcmp(t->dev_attr.attr.name,
758                            iio_attr->dev_attr.attr.name) == 0) {
759                         if (shared_by == IIO_SEPARATE)
760                                 dev_err(dev, "tried to double register : %s\n",
761                                         t->dev_attr.attr.name);
762                         ret = -EBUSY;
763                         goto error_device_attr_deinit;
764                 }
765         list_add(&iio_attr->l, attr_list);
766
767         return 0;
768
769 error_device_attr_deinit:
770         __iio_device_attr_deinit(&iio_attr->dev_attr);
771 error_iio_dev_attr_free:
772         kfree(iio_attr);
773         return ret;
774 }
775
776 static int iio_device_add_info_mask_type(struct iio_dev *indio_dev,
777                                          struct iio_chan_spec const *chan,
778                                          enum iio_shared_by shared_by,
779                                          const long *infomask)
780 {
781         int i, ret, attrcount = 0;
782
783         for_each_set_bit(i, infomask, sizeof(infomask)*8) {
784                 if (i >= ARRAY_SIZE(iio_chan_info_postfix))
785                         return -EINVAL;
786                 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
787                                              chan,
788                                              &iio_read_channel_info,
789                                              &iio_write_channel_info,
790                                              i,
791                                              shared_by,
792                                              &indio_dev->dev,
793                                              &indio_dev->channel_attr_list);
794                 if ((ret == -EBUSY) && (shared_by != IIO_SEPARATE))
795                         continue;
796                 else if (ret < 0)
797                         return ret;
798                 attrcount++;
799         }
800
801         return attrcount;
802 }
803
804 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
805                                         struct iio_chan_spec const *chan)
806 {
807         int ret, attrcount = 0;
808         const struct iio_chan_spec_ext_info *ext_info;
809
810         if (chan->channel < 0)
811                 return 0;
812         ret = iio_device_add_info_mask_type(indio_dev, chan,
813                                             IIO_SEPARATE,
814                                             &chan->info_mask_separate);
815         if (ret < 0)
816                 return ret;
817         attrcount += ret;
818
819         ret = iio_device_add_info_mask_type(indio_dev, chan,
820                                             IIO_SHARED_BY_TYPE,
821                                             &chan->info_mask_shared_by_type);
822         if (ret < 0)
823                 return ret;
824         attrcount += ret;
825
826         ret = iio_device_add_info_mask_type(indio_dev, chan,
827                                             IIO_SHARED_BY_DIR,
828                                             &chan->info_mask_shared_by_dir);
829         if (ret < 0)
830                 return ret;
831         attrcount += ret;
832
833         ret = iio_device_add_info_mask_type(indio_dev, chan,
834                                             IIO_SHARED_BY_ALL,
835                                             &chan->info_mask_shared_by_all);
836         if (ret < 0)
837                 return ret;
838         attrcount += ret;
839
840         if (chan->ext_info) {
841                 unsigned int i = 0;
842                 for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
843                         ret = __iio_add_chan_devattr(ext_info->name,
844                                         chan,
845                                         ext_info->read ?
846                                             &iio_read_channel_ext_info : NULL,
847                                         ext_info->write ?
848                                             &iio_write_channel_ext_info : NULL,
849                                         i,
850                                         ext_info->shared,
851                                         &indio_dev->dev,
852                                         &indio_dev->channel_attr_list);
853                         i++;
854                         if (ret == -EBUSY && ext_info->shared)
855                                 continue;
856
857                         if (ret)
858                                 return ret;
859
860                         attrcount++;
861                 }
862         }
863
864         return attrcount;
865 }
866
867 /**
868  * iio_free_chan_devattr_list() - Free a list of IIO device attributes
869  * @attr_list: List of IIO device attributes
870  *
871  * This function frees the memory allocated for each of the IIO device
872  * attributes in the list.
873  */
874 void iio_free_chan_devattr_list(struct list_head *attr_list)
875 {
876         struct iio_dev_attr *p, *n;
877
878         list_for_each_entry_safe(p, n, attr_list, l) {
879                 kfree(p->dev_attr.attr.name);
880                 list_del(&p->l);
881                 kfree(p);
882         }
883 }
884
885 static ssize_t iio_show_dev_name(struct device *dev,
886                                  struct device_attribute *attr,
887                                  char *buf)
888 {
889         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
890         return snprintf(buf, PAGE_SIZE, "%s\n", indio_dev->name);
891 }
892
893 static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
894
895 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
896 {
897         int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
898         struct iio_dev_attr *p;
899         struct attribute **attr;
900
901         /* First count elements in any existing group */
902         if (indio_dev->info->attrs) {
903                 attr = indio_dev->info->attrs->attrs;
904                 while (*attr++ != NULL)
905                         attrcount_orig++;
906         }
907         attrcount = attrcount_orig;
908         /*
909          * New channel registration method - relies on the fact a group does
910          * not need to be initialized if its name is NULL.
911          */
912         if (indio_dev->channels)
913                 for (i = 0; i < indio_dev->num_channels; i++) {
914                         ret = iio_device_add_channel_sysfs(indio_dev,
915                                                            &indio_dev
916                                                            ->channels[i]);
917                         if (ret < 0)
918                                 goto error_clear_attrs;
919                         attrcount += ret;
920                 }
921
922         if (indio_dev->name)
923                 attrcount++;
924
925         indio_dev->chan_attr_group.attrs = kcalloc(attrcount + 1,
926                                                    sizeof(indio_dev->chan_attr_group.attrs[0]),
927                                                    GFP_KERNEL);
928         if (indio_dev->chan_attr_group.attrs == NULL) {
929                 ret = -ENOMEM;
930                 goto error_clear_attrs;
931         }
932         /* Copy across original attributes */
933         if (indio_dev->info->attrs)
934                 memcpy(indio_dev->chan_attr_group.attrs,
935                        indio_dev->info->attrs->attrs,
936                        sizeof(indio_dev->chan_attr_group.attrs[0])
937                        *attrcount_orig);
938         attrn = attrcount_orig;
939         /* Add all elements from the list. */
940         list_for_each_entry(p, &indio_dev->channel_attr_list, l)
941                 indio_dev->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
942         if (indio_dev->name)
943                 indio_dev->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
944
945         indio_dev->groups[indio_dev->groupcounter++] =
946                 &indio_dev->chan_attr_group;
947
948         return 0;
949
950 error_clear_attrs:
951         iio_free_chan_devattr_list(&indio_dev->channel_attr_list);
952
953         return ret;
954 }
955
956 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
957 {
958
959         iio_free_chan_devattr_list(&indio_dev->channel_attr_list);
960         kfree(indio_dev->chan_attr_group.attrs);
961         indio_dev->chan_attr_group.attrs = NULL;
962 }
963
964 static void iio_dev_release(struct device *device)
965 {
966         struct iio_dev *indio_dev = dev_to_iio_dev(device);
967         if (indio_dev->modes & (INDIO_BUFFER_TRIGGERED | INDIO_EVENT_TRIGGERED))
968                 iio_device_unregister_trigger_consumer(indio_dev);
969         iio_device_unregister_eventset(indio_dev);
970         iio_device_unregister_sysfs(indio_dev);
971
972         iio_buffer_put(indio_dev->buffer);
973
974         ida_simple_remove(&iio_ida, indio_dev->id);
975         kfree(indio_dev);
976 }
977
978 struct device_type iio_device_type = {
979         .name = "iio_device",
980         .release = iio_dev_release,
981 };
982
983 /**
984  * iio_device_alloc() - allocate an iio_dev from a driver
985  * @sizeof_priv:        Space to allocate for private structure.
986  **/
987 struct iio_dev *iio_device_alloc(int sizeof_priv)
988 {
989         struct iio_dev *dev;
990         size_t alloc_size;
991
992         alloc_size = sizeof(struct iio_dev);
993         if (sizeof_priv) {
994                 alloc_size = ALIGN(alloc_size, IIO_ALIGN);
995                 alloc_size += sizeof_priv;
996         }
997         /* ensure 32-byte alignment of whole construct ? */
998         alloc_size += IIO_ALIGN - 1;
999
1000         dev = kzalloc(alloc_size, GFP_KERNEL);
1001
1002         if (dev) {
1003                 dev->dev.groups = dev->groups;
1004                 dev->dev.type = &iio_device_type;
1005                 dev->dev.bus = &iio_bus_type;
1006                 device_initialize(&dev->dev);
1007                 dev_set_drvdata(&dev->dev, (void *)dev);
1008                 mutex_init(&dev->mlock);
1009                 mutex_init(&dev->info_exist_lock);
1010                 INIT_LIST_HEAD(&dev->channel_attr_list);
1011
1012                 dev->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
1013                 if (dev->id < 0) {
1014                         /* cannot use a dev_err as the name isn't available */
1015                         pr_err("failed to get device id\n");
1016                         kfree(dev);
1017                         return NULL;
1018                 }
1019                 dev_set_name(&dev->dev, "iio:device%d", dev->id);
1020                 INIT_LIST_HEAD(&dev->buffer_list);
1021         }
1022
1023         return dev;
1024 }
1025 EXPORT_SYMBOL(iio_device_alloc);
1026
1027 /**
1028  * iio_device_free() - free an iio_dev from a driver
1029  * @dev:                the iio_dev associated with the device
1030  **/
1031 void iio_device_free(struct iio_dev *dev)
1032 {
1033         if (dev)
1034                 put_device(&dev->dev);
1035 }
1036 EXPORT_SYMBOL(iio_device_free);
1037
1038 static void devm_iio_device_release(struct device *dev, void *res)
1039 {
1040         iio_device_free(*(struct iio_dev **)res);
1041 }
1042
1043 static int devm_iio_device_match(struct device *dev, void *res, void *data)
1044 {
1045         struct iio_dev **r = res;
1046         if (!r || !*r) {
1047                 WARN_ON(!r || !*r);
1048                 return 0;
1049         }
1050         return *r == data;
1051 }
1052
1053 /**
1054  * devm_iio_device_alloc - Resource-managed iio_device_alloc()
1055  * @dev:                Device to allocate iio_dev for
1056  * @sizeof_priv:        Space to allocate for private structure.
1057  *
1058  * Managed iio_device_alloc. iio_dev allocated with this function is
1059  * automatically freed on driver detach.
1060  *
1061  * If an iio_dev allocated with this function needs to be freed separately,
1062  * devm_iio_device_free() must be used.
1063  *
1064  * RETURNS:
1065  * Pointer to allocated iio_dev on success, NULL on failure.
1066  */
1067 struct iio_dev *devm_iio_device_alloc(struct device *dev, int sizeof_priv)
1068 {
1069         struct iio_dev **ptr, *iio_dev;
1070
1071         ptr = devres_alloc(devm_iio_device_release, sizeof(*ptr),
1072                            GFP_KERNEL);
1073         if (!ptr)
1074                 return NULL;
1075
1076         iio_dev = iio_device_alloc(sizeof_priv);
1077         if (iio_dev) {
1078                 *ptr = iio_dev;
1079                 devres_add(dev, ptr);
1080         } else {
1081                 devres_free(ptr);
1082         }
1083
1084         return iio_dev;
1085 }
1086 EXPORT_SYMBOL_GPL(devm_iio_device_alloc);
1087
1088 /**
1089  * devm_iio_device_free - Resource-managed iio_device_free()
1090  * @dev:                Device this iio_dev belongs to
1091  * @iio_dev:            the iio_dev associated with the device
1092  *
1093  * Free iio_dev allocated with devm_iio_device_alloc().
1094  */
1095 void devm_iio_device_free(struct device *dev, struct iio_dev *iio_dev)
1096 {
1097         int rc;
1098
1099         rc = devres_release(dev, devm_iio_device_release,
1100                             devm_iio_device_match, iio_dev);
1101         WARN_ON(rc);
1102 }
1103 EXPORT_SYMBOL_GPL(devm_iio_device_free);
1104
1105 /**
1106  * iio_chrdev_open() - chrdev file open for buffer access and ioctls
1107  * @inode:      Inode structure for identifying the device in the file system
1108  * @filp:       File structure for iio device used to keep and later access
1109  *              private data
1110  *
1111  * Return: 0 on success or -EBUSY if the device is already opened
1112  **/
1113 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1114 {
1115         struct iio_dev *indio_dev = container_of(inode->i_cdev,
1116                                                 struct iio_dev, chrdev);
1117
1118         if (test_and_set_bit(IIO_BUSY_BIT_POS, &indio_dev->flags))
1119                 return -EBUSY;
1120
1121         iio_device_get(indio_dev);
1122
1123         filp->private_data = indio_dev;
1124
1125         return 0;
1126 }
1127
1128 /**
1129  * iio_chrdev_release() - chrdev file close buffer access and ioctls
1130  * @inode:      Inode structure pointer for the char device
1131  * @filp:       File structure pointer for the char device
1132  *
1133  * Return: 0 for successful release
1134  */
1135 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1136 {
1137         struct iio_dev *indio_dev = container_of(inode->i_cdev,
1138                                                 struct iio_dev, chrdev);
1139         clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
1140         iio_device_put(indio_dev);
1141
1142         return 0;
1143 }
1144
1145 /* Somewhat of a cross file organization violation - ioctls here are actually
1146  * event related */
1147 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1148 {
1149         struct iio_dev *indio_dev = filp->private_data;
1150         int __user *ip = (int __user *)arg;
1151         int fd;
1152
1153         if (!indio_dev->info)
1154                 return -ENODEV;
1155
1156         if (cmd == IIO_GET_EVENT_FD_IOCTL) {
1157                 fd = iio_event_getfd(indio_dev);
1158                 if (fd < 0)
1159                         return fd;
1160                 if (copy_to_user(ip, &fd, sizeof(fd)))
1161                         return -EFAULT;
1162                 return 0;
1163         }
1164         return -EINVAL;
1165 }
1166
1167 static const struct file_operations iio_buffer_fileops = {
1168         .read = iio_buffer_read_first_n_outer_addr,
1169         .release = iio_chrdev_release,
1170         .open = iio_chrdev_open,
1171         .poll = iio_buffer_poll_addr,
1172         .owner = THIS_MODULE,
1173         .llseek = noop_llseek,
1174         .unlocked_ioctl = iio_ioctl,
1175         .compat_ioctl = iio_ioctl,
1176 };
1177
1178 static int iio_check_unique_scan_index(struct iio_dev *indio_dev)
1179 {
1180         int i, j;
1181         const struct iio_chan_spec *channels = indio_dev->channels;
1182
1183         if (!(indio_dev->modes & INDIO_ALL_BUFFER_MODES))
1184                 return 0;
1185
1186         for (i = 0; i < indio_dev->num_channels - 1; i++) {
1187                 if (channels[i].scan_index < 0)
1188                         continue;
1189                 for (j = i + 1; j < indio_dev->num_channels; j++)
1190                         if (channels[i].scan_index == channels[j].scan_index) {
1191                                 dev_err(&indio_dev->dev,
1192                                         "Duplicate scan index %d\n",
1193                                         channels[i].scan_index);
1194                                 return -EINVAL;
1195                         }
1196         }
1197
1198         return 0;
1199 }
1200
1201 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
1202
1203 /**
1204  * iio_device_register() - register a device with the IIO subsystem
1205  * @indio_dev:          Device structure filled by the device driver
1206  **/
1207 int iio_device_register(struct iio_dev *indio_dev)
1208 {
1209         int ret;
1210
1211         /* If the calling driver did not initialize of_node, do it here */
1212         if (!indio_dev->dev.of_node && indio_dev->dev.parent)
1213                 indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
1214
1215         ret = iio_check_unique_scan_index(indio_dev);
1216         if (ret < 0)
1217                 return ret;
1218
1219         /* configure elements for the chrdev */
1220         indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), indio_dev->id);
1221
1222         ret = iio_device_register_debugfs(indio_dev);
1223         if (ret) {
1224                 dev_err(indio_dev->dev.parent,
1225                         "Failed to register debugfs interfaces\n");
1226                 return ret;
1227         }
1228
1229         ret = iio_buffer_alloc_sysfs_and_mask(indio_dev);
1230         if (ret) {
1231                 dev_err(indio_dev->dev.parent,
1232                         "Failed to create buffer sysfs interfaces\n");
1233                 goto error_unreg_debugfs;
1234         }
1235
1236         ret = iio_device_register_sysfs(indio_dev);
1237         if (ret) {
1238                 dev_err(indio_dev->dev.parent,
1239                         "Failed to register sysfs interfaces\n");
1240                 goto error_buffer_free_sysfs;
1241         }
1242         ret = iio_device_register_eventset(indio_dev);
1243         if (ret) {
1244                 dev_err(indio_dev->dev.parent,
1245                         "Failed to register event set\n");
1246                 goto error_free_sysfs;
1247         }
1248         if (indio_dev->modes & (INDIO_BUFFER_TRIGGERED | INDIO_EVENT_TRIGGERED))
1249                 iio_device_register_trigger_consumer(indio_dev);
1250
1251         if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1252                 indio_dev->setup_ops == NULL)
1253                 indio_dev->setup_ops = &noop_ring_setup_ops;
1254
1255         cdev_init(&indio_dev->chrdev, &iio_buffer_fileops);
1256         indio_dev->chrdev.owner = indio_dev->info->driver_module;
1257         indio_dev->chrdev.kobj.parent = &indio_dev->dev.kobj;
1258         ret = cdev_add(&indio_dev->chrdev, indio_dev->dev.devt, 1);
1259         if (ret < 0)
1260                 goto error_unreg_eventset;
1261
1262         ret = device_add(&indio_dev->dev);
1263         if (ret < 0)
1264                 goto error_cdev_del;
1265
1266         return 0;
1267 error_cdev_del:
1268         cdev_del(&indio_dev->chrdev);
1269 error_unreg_eventset:
1270         iio_device_unregister_eventset(indio_dev);
1271 error_free_sysfs:
1272         iio_device_unregister_sysfs(indio_dev);
1273 error_buffer_free_sysfs:
1274         iio_buffer_free_sysfs_and_mask(indio_dev);
1275 error_unreg_debugfs:
1276         iio_device_unregister_debugfs(indio_dev);
1277         return ret;
1278 }
1279 EXPORT_SYMBOL(iio_device_register);
1280
1281 /**
1282  * iio_device_unregister() - unregister a device from the IIO subsystem
1283  * @indio_dev:          Device structure representing the device.
1284  **/
1285 void iio_device_unregister(struct iio_dev *indio_dev)
1286 {
1287         mutex_lock(&indio_dev->info_exist_lock);
1288
1289         device_del(&indio_dev->dev);
1290
1291         if (indio_dev->chrdev.dev)
1292                 cdev_del(&indio_dev->chrdev);
1293         iio_device_unregister_debugfs(indio_dev);
1294
1295         iio_disable_all_buffers(indio_dev);
1296
1297         indio_dev->info = NULL;
1298
1299         iio_device_wakeup_eventset(indio_dev);
1300         iio_buffer_wakeup_poll(indio_dev);
1301
1302         mutex_unlock(&indio_dev->info_exist_lock);
1303
1304         iio_buffer_free_sysfs_and_mask(indio_dev);
1305 }
1306 EXPORT_SYMBOL(iio_device_unregister);
1307
1308 static void devm_iio_device_unreg(struct device *dev, void *res)
1309 {
1310         iio_device_unregister(*(struct iio_dev **)res);
1311 }
1312
1313 /**
1314  * devm_iio_device_register - Resource-managed iio_device_register()
1315  * @dev:        Device to allocate iio_dev for
1316  * @indio_dev:  Device structure filled by the device driver
1317  *
1318  * Managed iio_device_register.  The IIO device registered with this
1319  * function is automatically unregistered on driver detach. This function
1320  * calls iio_device_register() internally. Refer to that function for more
1321  * information.
1322  *
1323  * If an iio_dev registered with this function needs to be unregistered
1324  * separately, devm_iio_device_unregister() must be used.
1325  *
1326  * RETURNS:
1327  * 0 on success, negative error number on failure.
1328  */
1329 int devm_iio_device_register(struct device *dev, struct iio_dev *indio_dev)
1330 {
1331         struct iio_dev **ptr;
1332         int ret;
1333
1334         ptr = devres_alloc(devm_iio_device_unreg, sizeof(*ptr), GFP_KERNEL);
1335         if (!ptr)
1336                 return -ENOMEM;
1337
1338         *ptr = indio_dev;
1339         ret = iio_device_register(indio_dev);
1340         if (!ret)
1341                 devres_add(dev, ptr);
1342         else
1343                 devres_free(ptr);
1344
1345         return ret;
1346 }
1347 EXPORT_SYMBOL_GPL(devm_iio_device_register);
1348
1349 /**
1350  * devm_iio_device_unregister - Resource-managed iio_device_unregister()
1351  * @dev:        Device this iio_dev belongs to
1352  * @indio_dev:  the iio_dev associated with the device
1353  *
1354  * Unregister iio_dev registered with devm_iio_device_register().
1355  */
1356 void devm_iio_device_unregister(struct device *dev, struct iio_dev *indio_dev)
1357 {
1358         int rc;
1359
1360         rc = devres_release(dev, devm_iio_device_unreg,
1361                             devm_iio_device_match, indio_dev);
1362         WARN_ON(rc);
1363 }
1364 EXPORT_SYMBOL_GPL(devm_iio_device_unregister);
1365
1366 subsys_initcall(iio_init);
1367 module_exit(iio_exit);
1368
1369 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1370 MODULE_DESCRIPTION("Industrial I/O core");
1371 MODULE_LICENSE("GPL");