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