ARM: mali400: fix building out of tree
[profile/mobile/platform/kernel/linux-3.10-sc7730.git] / 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 #include <linux/kernel.h>
13 #include <linux/module.h>
14 #include <linux/idr.h>
15 #include <linux/kdev_t.h>
16 #include <linux/err.h>
17 #include <linux/device.h>
18 #include <linux/fs.h>
19 #include <linux/poll.h>
20 #include <linux/sched.h>
21 #include <linux/wait.h>
22 #include <linux/cdev.h>
23 #include <linux/slab.h>
24 #include <linux/anon_inodes.h>
25 #include <linux/debugfs.h>
26 #include <linux/iio/iio.h>
27 #include "iio_core.h"
28 #include "iio_core_trigger.h"
29 #include <linux/iio/sysfs.h>
30 #include <linux/iio/events.h>
31
32 /* IDA to assign each registered device a unique id */
33 static DEFINE_IDA(iio_ida);
34
35 static dev_t iio_devt;
36
37 #define IIO_DEV_MAX 256
38 struct bus_type iio_bus_type = {
39         .name = "iio",
40 };
41 EXPORT_SYMBOL(iio_bus_type);
42
43 static struct dentry *iio_debugfs_dentry;
44
45 static const char * const iio_direction[] = {
46         [0] = "in",
47         [1] = "out",
48 };
49
50 static const char * const iio_chan_type_name_spec[] = {
51         [IIO_VOLTAGE] = "voltage",
52         [IIO_CURRENT] = "current",
53         [IIO_POWER] = "power",
54         [IIO_ACCEL] = "accel",
55         [IIO_ANGL_VEL] = "anglvel",
56         [IIO_MAGN] = "magn",
57         [IIO_LIGHT] = "illuminance",
58         [IIO_INTENSITY] = "intensity",
59         [IIO_PROXIMITY] = "proximity",
60         [IIO_TEMP] = "temp",
61         [IIO_INCLI] = "incli",
62         [IIO_ROT] = "rot",
63         [IIO_ANGL] = "angl",
64         [IIO_TIMESTAMP] = "timestamp",
65         [IIO_CAPACITANCE] = "capacitance",
66         [IIO_ALTVOLTAGE] = "altvoltage",
67         [IIO_CCT] = "cct",
68         [IIO_PRESSURE] = "pressure",
69         [IIO_QUATERNION] = "quaternion",
70 };
71
72 static const char * const iio_modifier_names[] = {
73         [IIO_MOD_X] = "x",
74         [IIO_MOD_Y] = "y",
75         [IIO_MOD_Z] = "z",
76         [IIO_MOD_ROOT_SUM_SQUARED_X_Y] = "sqrt(x^2+y^2)",
77         [IIO_MOD_SUM_SQUARED_X_Y_Z] = "x^2+y^2+z^2",
78         [IIO_MOD_LIGHT_BOTH] = "both",
79         [IIO_MOD_LIGHT_IR] = "ir",
80         [IIO_MOD_LIGHT_CLEAR] = "clear",
81         [IIO_MOD_LIGHT_RED] = "red",
82         [IIO_MOD_LIGHT_GREEN] = "green",
83         [IIO_MOD_LIGHT_BLUE] = "blue",
84         [IIO_MOD_R]  = "r",
85 };
86
87 /* relies on pairs of these shared then separate */
88 static const char * const iio_chan_info_postfix[] = {
89         [IIO_CHAN_INFO_RAW] = "raw",
90         [IIO_CHAN_INFO_PROCESSED] = "input",
91         [IIO_CHAN_INFO_SCALE] = "scale",
92         [IIO_CHAN_INFO_OFFSET] = "offset",
93         [IIO_CHAN_INFO_CALIBSCALE] = "calibscale",
94         [IIO_CHAN_INFO_CALIBBIAS] = "calibbias",
95         [IIO_CHAN_INFO_PEAK] = "peak_raw",
96         [IIO_CHAN_INFO_PEAK_SCALE] = "peak_scale",
97         [IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW] = "quadrature_correction_raw",
98         [IIO_CHAN_INFO_AVERAGE_RAW] = "mean_raw",
99         [IIO_CHAN_INFO_LOW_PASS_FILTER_3DB_FREQUENCY]
100         = "filter_low_pass_3db_frequency",
101         [IIO_CHAN_INFO_SAMP_FREQ] = "sampling_frequency",
102         [IIO_CHAN_INFO_FREQUENCY] = "frequency",
103         [IIO_CHAN_INFO_PHASE] = "phase",
104         [IIO_CHAN_INFO_HARDWAREGAIN] = "hardwaregain",
105         [IIO_CHAN_INFO_HYSTERESIS] = "hysteresis",
106 };
107
108 const struct iio_chan_spec
109 *iio_find_channel_from_si(struct iio_dev *indio_dev, int si)
110 {
111         int i;
112
113         for (i = 0; i < indio_dev->num_channels; i++)
114                 if (indio_dev->channels[i].scan_index == si)
115                         return &indio_dev->channels[i];
116         return NULL;
117 }
118
119 /* This turns up an awful lot */
120 ssize_t iio_read_const_attr(struct device *dev,
121                             struct device_attribute *attr,
122                             char *buf)
123 {
124         return sprintf(buf, "%s\n", to_iio_const_attr(attr)->string);
125 }
126 EXPORT_SYMBOL(iio_read_const_attr);
127
128 static int __init iio_init(void)
129 {
130         int ret;
131
132         /* Register sysfs bus */
133         ret  = bus_register(&iio_bus_type);
134         if (ret < 0) {
135                 printk(KERN_ERR
136                        "%s could not register bus type\n",
137                         __FILE__);
138                 goto error_nothing;
139         }
140
141         ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
142         if (ret < 0) {
143                 printk(KERN_ERR "%s: failed to allocate char dev region\n",
144                        __FILE__);
145                 goto error_unregister_bus_type;
146         }
147
148         iio_debugfs_dentry = debugfs_create_dir("iio", NULL);
149
150         return 0;
151
152 error_unregister_bus_type:
153         bus_unregister(&iio_bus_type);
154 error_nothing:
155         return ret;
156 }
157
158 static void __exit iio_exit(void)
159 {
160         if (iio_devt)
161                 unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
162         bus_unregister(&iio_bus_type);
163         debugfs_remove(iio_debugfs_dentry);
164 }
165
166 #if defined(CONFIG_DEBUG_FS)
167 static ssize_t iio_debugfs_read_reg(struct file *file, char __user *userbuf,
168                               size_t count, loff_t *ppos)
169 {
170         struct iio_dev *indio_dev = file->private_data;
171         char buf[20];
172         unsigned val = 0;
173         ssize_t len;
174         int ret;
175
176         ret = indio_dev->info->debugfs_reg_access(indio_dev,
177                                                   indio_dev->cached_reg_addr,
178                                                   0, &val);
179         if (ret)
180                 dev_err(indio_dev->dev.parent, "%s: read failed\n", __func__);
181
182         len = snprintf(buf, sizeof(buf), "0x%X\n", val);
183
184         return simple_read_from_buffer(userbuf, count, ppos, buf, len);
185 }
186
187 static ssize_t iio_debugfs_write_reg(struct file *file,
188                      const char __user *userbuf, size_t count, loff_t *ppos)
189 {
190         struct iio_dev *indio_dev = file->private_data;
191         unsigned reg, val;
192         char buf[80];
193         int ret;
194
195         count = min_t(size_t, count, (sizeof(buf)-1));
196         if (copy_from_user(buf, userbuf, count))
197                 return -EFAULT;
198
199         buf[count] = 0;
200
201         ret = sscanf(buf, "%i %i", &reg, &val);
202
203         switch (ret) {
204         case 1:
205                 indio_dev->cached_reg_addr = reg;
206                 break;
207         case 2:
208                 indio_dev->cached_reg_addr = reg;
209                 ret = indio_dev->info->debugfs_reg_access(indio_dev, reg,
210                                                           val, NULL);
211                 if (ret) {
212                         dev_err(indio_dev->dev.parent, "%s: write failed\n",
213                                 __func__);
214                         return ret;
215                 }
216                 break;
217         default:
218                 return -EINVAL;
219         }
220
221         return count;
222 }
223
224 static const struct file_operations iio_debugfs_reg_fops = {
225         .open = simple_open,
226         .read = iio_debugfs_read_reg,
227         .write = iio_debugfs_write_reg,
228 };
229
230 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
231 {
232         debugfs_remove_recursive(indio_dev->debugfs_dentry);
233 }
234
235 static int iio_device_register_debugfs(struct iio_dev *indio_dev)
236 {
237         struct dentry *d;
238
239         if (indio_dev->info->debugfs_reg_access == NULL)
240                 return 0;
241
242         if (!iio_debugfs_dentry)
243                 return 0;
244
245         indio_dev->debugfs_dentry =
246                 debugfs_create_dir(dev_name(&indio_dev->dev),
247                                    iio_debugfs_dentry);
248         if (indio_dev->debugfs_dentry == NULL) {
249                 dev_warn(indio_dev->dev.parent,
250                          "Failed to create debugfs directory\n");
251                 return -EFAULT;
252         }
253
254         d = debugfs_create_file("direct_reg_access", 0644,
255                                 indio_dev->debugfs_dentry,
256                                 indio_dev, &iio_debugfs_reg_fops);
257         if (!d) {
258                 iio_device_unregister_debugfs(indio_dev);
259                 return -ENOMEM;
260         }
261
262         return 0;
263 }
264 #else
265 static int iio_device_register_debugfs(struct iio_dev *indio_dev)
266 {
267         return 0;
268 }
269
270 static void iio_device_unregister_debugfs(struct iio_dev *indio_dev)
271 {
272 }
273 #endif /* CONFIG_DEBUG_FS */
274
275 static ssize_t iio_read_channel_ext_info(struct device *dev,
276                                      struct device_attribute *attr,
277                                      char *buf)
278 {
279         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
280         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
281         const struct iio_chan_spec_ext_info *ext_info;
282
283         ext_info = &this_attr->c->ext_info[this_attr->address];
284
285         return ext_info->read(indio_dev, ext_info->private, this_attr->c, buf);
286 }
287
288 static ssize_t iio_write_channel_ext_info(struct device *dev,
289                                      struct device_attribute *attr,
290                                      const char *buf,
291                                          size_t len)
292 {
293         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
294         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
295         const struct iio_chan_spec_ext_info *ext_info;
296
297         ext_info = &this_attr->c->ext_info[this_attr->address];
298
299         return ext_info->write(indio_dev, ext_info->private,
300                                this_attr->c, buf, len);
301 }
302
303 ssize_t iio_enum_available_read(struct iio_dev *indio_dev,
304         uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
305 {
306         const struct iio_enum *e = (const struct iio_enum *)priv;
307         unsigned int i;
308         size_t len = 0;
309
310         if (!e->num_items)
311                 return 0;
312
313         for (i = 0; i < e->num_items; ++i)
314                 len += scnprintf(buf + len, PAGE_SIZE - len, "%s ", e->items[i]);
315
316         /* replace last space with a newline */
317         buf[len - 1] = '\n';
318
319         return len;
320 }
321 EXPORT_SYMBOL_GPL(iio_enum_available_read);
322
323 ssize_t iio_enum_read(struct iio_dev *indio_dev,
324         uintptr_t priv, const struct iio_chan_spec *chan, char *buf)
325 {
326         const struct iio_enum *e = (const struct iio_enum *)priv;
327         int i;
328
329         if (!e->get)
330                 return -EINVAL;
331
332         i = e->get(indio_dev, chan);
333         if (i < 0)
334                 return i;
335         else if (i >= e->num_items)
336                 return -EINVAL;
337
338         return sprintf(buf, "%s\n", e->items[i]);
339 }
340 EXPORT_SYMBOL_GPL(iio_enum_read);
341
342 ssize_t iio_enum_write(struct iio_dev *indio_dev,
343         uintptr_t priv, const struct iio_chan_spec *chan, const char *buf,
344         size_t len)
345 {
346         const struct iio_enum *e = (const struct iio_enum *)priv;
347         unsigned int i;
348         int ret;
349
350         if (!e->set)
351                 return -EINVAL;
352
353         for (i = 0; i < e->num_items; i++) {
354                 if (sysfs_streq(buf, e->items[i]))
355                         break;
356         }
357
358         if (i == e->num_items)
359                 return -EINVAL;
360
361         ret = e->set(indio_dev, chan, i);
362         return ret ? ret : len;
363 }
364 EXPORT_SYMBOL_GPL(iio_enum_write);
365
366 static ssize_t iio_read_channel_info(struct device *dev,
367                                      struct device_attribute *attr,
368                                      char *buf)
369 {
370         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
371         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
372         unsigned long long tmp;
373         int val, val2;
374         bool scale_db = false;
375         int ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
376                                             &val, &val2, this_attr->address);
377
378         if (ret < 0)
379                 return ret;
380
381         switch (ret) {
382         case IIO_VAL_INT:
383                 return sprintf(buf, "%d\n", val);
384         case IIO_VAL_INT_PLUS_MICRO_DB:
385                 scale_db = true;
386         case IIO_VAL_INT_PLUS_MICRO:
387                 if (val2 < 0)
388                         return sprintf(buf, "-%d.%06u%s\n", val, -val2,
389                                 scale_db ? " dB" : "");
390                 else
391                         return sprintf(buf, "%d.%06u%s\n", val, val2,
392                                 scale_db ? " dB" : "");
393         case IIO_VAL_INT_PLUS_NANO:
394                 if (val2 < 0)
395                         return sprintf(buf, "-%d.%09u\n", val, -val2);
396                 else
397                         return sprintf(buf, "%d.%09u\n", val, val2);
398         case IIO_VAL_FRACTIONAL:
399                 tmp = div_s64((s64)val * 1000000000LL, val2);
400                 val2 = do_div(tmp, 1000000000LL);
401                 val = tmp;
402                 return sprintf(buf, "%d.%09u\n", val, val2);
403         case IIO_VAL_FRACTIONAL_LOG2:
404                 tmp = (s64)val * 1000000000LL >> val2;
405                 val2 = do_div(tmp, 1000000000LL);
406                 val = tmp;
407                 return sprintf(buf, "%d.%09u\n", val, val2);
408         default:
409                 return 0;
410         }
411 }
412
413 /**
414  * iio_str_to_fixpoint() - Parse a fixed-point number from a string
415  * @str: The string to parse
416  * @fract_mult: Multiplier for the first decimal place, should be a power of 10
417  * @integer: The integer part of the number
418  * @fract: The fractional part of the number
419  *
420  * Returns 0 on success, or a negative error code if the string could not be
421  * parsed.
422  */
423 int iio_str_to_fixpoint(const char *str, int fract_mult,
424         int *integer, int *fract)
425 {
426         int i = 0, f = 0;
427         bool integer_part = true, negative = false;
428
429         if (str[0] == '-') {
430                 negative = true;
431                 str++;
432         } else if (str[0] == '+') {
433                 str++;
434         }
435
436         while (*str) {
437                 if ('0' <= *str && *str <= '9') {
438                         if (integer_part) {
439                                 i = i * 10 + *str - '0';
440                         } else {
441                                 f += fract_mult * (*str - '0');
442                                 fract_mult /= 10;
443                         }
444                 } else if (*str == '\n') {
445                         if (*(str + 1) == '\0')
446                                 break;
447                         else
448                                 return -EINVAL;
449                 } else if (*str == '.' && integer_part) {
450                         integer_part = false;
451                 } else {
452                         return -EINVAL;
453                 }
454                 str++;
455         }
456
457         if (negative) {
458                 if (i)
459                         i = -i;
460                 else
461                         f = -f;
462         }
463
464         *integer = i;
465         *fract = f;
466
467         return 0;
468 }
469 EXPORT_SYMBOL_GPL(iio_str_to_fixpoint);
470
471 static ssize_t iio_write_channel_info(struct device *dev,
472                                       struct device_attribute *attr,
473                                       const char *buf,
474                                       size_t len)
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 ret, fract_mult = 100000;
479         int integer, fract;
480
481         /* Assumes decimal - precision based on number of digits */
482         if (!indio_dev->info->write_raw)
483                 return -EINVAL;
484
485         if (indio_dev->info->write_raw_get_fmt)
486                 switch (indio_dev->info->write_raw_get_fmt(indio_dev,
487                         this_attr->c, this_attr->address)) {
488                 case IIO_VAL_INT_PLUS_MICRO:
489                         fract_mult = 100000;
490                         break;
491                 case IIO_VAL_INT_PLUS_NANO:
492                         fract_mult = 100000000;
493                         break;
494                 default:
495                         return -EINVAL;
496                 }
497
498         ret = iio_str_to_fixpoint(buf, fract_mult, &integer, &fract);
499         if (ret)
500                 return ret;
501
502         ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
503                                          integer, fract, this_attr->address);
504         if (ret)
505                 return ret;
506
507         return len;
508 }
509
510 static
511 int __iio_device_attr_init(struct device_attribute *dev_attr,
512                            const char *postfix,
513                            struct iio_chan_spec const *chan,
514                            ssize_t (*readfunc)(struct device *dev,
515                                                struct device_attribute *attr,
516                                                char *buf),
517                            ssize_t (*writefunc)(struct device *dev,
518                                                 struct device_attribute *attr,
519                                                 const char *buf,
520                                                 size_t len),
521                            bool generic)
522 {
523         int ret;
524         char *name_format, *full_postfix;
525         sysfs_attr_init(&dev_attr->attr);
526
527         /* Build up postfix of <extend_name>_<modifier>_postfix */
528         if (chan->modified && !generic) {
529                 if (chan->extend_name)
530                         full_postfix = kasprintf(GFP_KERNEL, "%s_%s_%s",
531                                                  iio_modifier_names[chan
532                                                                     ->channel2],
533                                                  chan->extend_name,
534                                                  postfix);
535                 else
536                         full_postfix = kasprintf(GFP_KERNEL, "%s_%s",
537                                                  iio_modifier_names[chan
538                                                                     ->channel2],
539                                                  postfix);
540         } else {
541                 if (chan->extend_name == NULL)
542                         full_postfix = kstrdup(postfix, GFP_KERNEL);
543                 else
544                         full_postfix = kasprintf(GFP_KERNEL,
545                                                  "%s_%s",
546                                                  chan->extend_name,
547                                                  postfix);
548         }
549         if (full_postfix == NULL) {
550                 ret = -ENOMEM;
551                 goto error_ret;
552         }
553
554         if (chan->differential) { /* Differential can not have modifier */
555                 if (generic)
556                         name_format
557                                 = kasprintf(GFP_KERNEL, "%s_%s-%s_%s",
558                                             iio_direction[chan->output],
559                                             iio_chan_type_name_spec[chan->type],
560                                             iio_chan_type_name_spec[chan->type],
561                                             full_postfix);
562                 else if (chan->indexed)
563                         name_format
564                                 = kasprintf(GFP_KERNEL, "%s_%s%d-%s%d_%s",
565                                             iio_direction[chan->output],
566                                             iio_chan_type_name_spec[chan->type],
567                                             chan->channel,
568                                             iio_chan_type_name_spec[chan->type],
569                                             chan->channel2,
570                                             full_postfix);
571                 else {
572                         WARN_ON("Differential channels must be indexed\n");
573                         ret = -EINVAL;
574                         goto error_free_full_postfix;
575                 }
576         } else { /* Single ended */
577                 if (generic)
578                         name_format
579                                 = kasprintf(GFP_KERNEL, "%s_%s_%s",
580                                             iio_direction[chan->output],
581                                             iio_chan_type_name_spec[chan->type],
582                                             full_postfix);
583                 else if (chan->indexed)
584                         name_format
585                                 = kasprintf(GFP_KERNEL, "%s_%s%d_%s",
586                                             iio_direction[chan->output],
587                                             iio_chan_type_name_spec[chan->type],
588                                             chan->channel,
589                                             full_postfix);
590                 else
591                         name_format
592                                 = kasprintf(GFP_KERNEL, "%s_%s_%s",
593                                             iio_direction[chan->output],
594                                             iio_chan_type_name_spec[chan->type],
595                                             full_postfix);
596         }
597         if (name_format == NULL) {
598                 ret = -ENOMEM;
599                 goto error_free_full_postfix;
600         }
601         dev_attr->attr.name = kasprintf(GFP_KERNEL,
602                                         name_format,
603                                         chan->channel,
604                                         chan->channel2);
605         if (dev_attr->attr.name == NULL) {
606                 ret = -ENOMEM;
607                 goto error_free_name_format;
608         }
609
610         if (readfunc) {
611                 dev_attr->attr.mode |= S_IRUGO;
612                 dev_attr->show = readfunc;
613         }
614
615         if (writefunc) {
616                 dev_attr->attr.mode |= S_IWUSR;
617                 dev_attr->store = writefunc;
618         }
619         kfree(name_format);
620         kfree(full_postfix);
621
622         return 0;
623
624 error_free_name_format:
625         kfree(name_format);
626 error_free_full_postfix:
627         kfree(full_postfix);
628 error_ret:
629         return ret;
630 }
631
632 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
633 {
634         kfree(dev_attr->attr.name);
635 }
636
637 int __iio_add_chan_devattr(const char *postfix,
638                            struct iio_chan_spec const *chan,
639                            ssize_t (*readfunc)(struct device *dev,
640                                                struct device_attribute *attr,
641                                                char *buf),
642                            ssize_t (*writefunc)(struct device *dev,
643                                                 struct device_attribute *attr,
644                                                 const char *buf,
645                                                 size_t len),
646                            u64 mask,
647                            bool generic,
648                            struct device *dev,
649                            struct list_head *attr_list)
650 {
651         int ret;
652         struct iio_dev_attr *iio_attr, *t;
653
654         iio_attr = kzalloc(sizeof *iio_attr, GFP_KERNEL);
655         if (iio_attr == NULL) {
656                 ret = -ENOMEM;
657                 goto error_ret;
658         }
659         ret = __iio_device_attr_init(&iio_attr->dev_attr,
660                                      postfix, chan,
661                                      readfunc, writefunc, generic);
662         if (ret)
663                 goto error_iio_dev_attr_free;
664         iio_attr->c = chan;
665         iio_attr->address = mask;
666         list_for_each_entry(t, attr_list, l)
667                 if (strcmp(t->dev_attr.attr.name,
668                            iio_attr->dev_attr.attr.name) == 0) {
669                         if (!generic)
670                                 dev_err(dev, "tried to double register : %s\n",
671                                         t->dev_attr.attr.name);
672                         ret = -EBUSY;
673                         goto error_device_attr_deinit;
674                 }
675         list_add(&iio_attr->l, attr_list);
676
677         return 0;
678
679 error_device_attr_deinit:
680         __iio_device_attr_deinit(&iio_attr->dev_attr);
681 error_iio_dev_attr_free:
682         kfree(iio_attr);
683 error_ret:
684         return ret;
685 }
686
687 static int iio_device_add_channel_sysfs(struct iio_dev *indio_dev,
688                                         struct iio_chan_spec const *chan)
689 {
690         int ret, attrcount = 0;
691         int i;
692         const struct iio_chan_spec_ext_info *ext_info;
693
694         if (chan->channel < 0)
695                 return 0;
696         for_each_set_bit(i, &chan->info_mask_separate, sizeof(long)*8) {
697                 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
698                                              chan,
699                                              &iio_read_channel_info,
700                                              &iio_write_channel_info,
701                                              i,
702                                              0,
703                                              &indio_dev->dev,
704                                              &indio_dev->channel_attr_list);
705                 if (ret < 0)
706                         goto error_ret;
707                 attrcount++;
708         }
709         for_each_set_bit(i, &chan->info_mask_shared_by_type, sizeof(long)*8) {
710                 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i],
711                                              chan,
712                                              &iio_read_channel_info,
713                                              &iio_write_channel_info,
714                                              i,
715                                              1,
716                                              &indio_dev->dev,
717                                              &indio_dev->channel_attr_list);
718                 if (ret == -EBUSY) {
719                         ret = 0;
720                         continue;
721                 } else if (ret < 0) {
722                         goto error_ret;
723                 }
724                 attrcount++;
725         }
726
727         if (chan->ext_info) {
728                 unsigned int i = 0;
729                 for (ext_info = chan->ext_info; ext_info->name; ext_info++) {
730                         ret = __iio_add_chan_devattr(ext_info->name,
731                                         chan,
732                                         ext_info->read ?
733                                             &iio_read_channel_ext_info : NULL,
734                                         ext_info->write ?
735                                             &iio_write_channel_ext_info : NULL,
736                                         i,
737                                         ext_info->shared,
738                                         &indio_dev->dev,
739                                         &indio_dev->channel_attr_list);
740                         i++;
741                         if (ret == -EBUSY && ext_info->shared)
742                                 continue;
743
744                         if (ret)
745                                 goto error_ret;
746
747                         attrcount++;
748                 }
749         }
750
751         ret = attrcount;
752 error_ret:
753         return ret;
754 }
755
756 static void iio_device_remove_and_free_read_attr(struct iio_dev *indio_dev,
757                                                  struct iio_dev_attr *p)
758 {
759         kfree(p->dev_attr.attr.name);
760         kfree(p);
761 }
762
763 static ssize_t iio_show_dev_name(struct device *dev,
764                                  struct device_attribute *attr,
765                                  char *buf)
766 {
767         struct iio_dev *indio_dev = dev_to_iio_dev(dev);
768         return sprintf(buf, "%s\n", indio_dev->name);
769 }
770
771 static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
772
773 static int iio_device_register_sysfs(struct iio_dev *indio_dev)
774 {
775         int i, ret = 0, attrcount, attrn, attrcount_orig = 0;
776         struct iio_dev_attr *p, *n;
777         struct attribute **attr;
778
779         /* First count elements in any existing group */
780         if (indio_dev->info->attrs) {
781                 attr = indio_dev->info->attrs->attrs;
782                 while (*attr++ != NULL)
783                         attrcount_orig++;
784         }
785         attrcount = attrcount_orig;
786         /*
787          * New channel registration method - relies on the fact a group does
788          * not need to be initialized if its name is NULL.
789          */
790         if (indio_dev->channels)
791                 for (i = 0; i < indio_dev->num_channels; i++) {
792                         ret = iio_device_add_channel_sysfs(indio_dev,
793                                                            &indio_dev
794                                                            ->channels[i]);
795                         if (ret < 0)
796                                 goto error_clear_attrs;
797                         attrcount += ret;
798                 }
799
800         if (indio_dev->name)
801                 attrcount++;
802
803         indio_dev->chan_attr_group.attrs = kcalloc(attrcount + 1,
804                                                    sizeof(indio_dev->chan_attr_group.attrs[0]),
805                                                    GFP_KERNEL);
806         if (indio_dev->chan_attr_group.attrs == NULL) {
807                 ret = -ENOMEM;
808                 goto error_clear_attrs;
809         }
810         /* Copy across original attributes */
811         if (indio_dev->info->attrs)
812                 memcpy(indio_dev->chan_attr_group.attrs,
813                        indio_dev->info->attrs->attrs,
814                        sizeof(indio_dev->chan_attr_group.attrs[0])
815                        *attrcount_orig);
816         attrn = attrcount_orig;
817         /* Add all elements from the list. */
818         list_for_each_entry(p, &indio_dev->channel_attr_list, l)
819                 indio_dev->chan_attr_group.attrs[attrn++] = &p->dev_attr.attr;
820         if (indio_dev->name)
821                 indio_dev->chan_attr_group.attrs[attrn++] = &dev_attr_name.attr;
822
823         indio_dev->groups[indio_dev->groupcounter++] =
824                 &indio_dev->chan_attr_group;
825
826         return 0;
827
828 error_clear_attrs:
829         list_for_each_entry_safe(p, n,
830                                  &indio_dev->channel_attr_list, l) {
831                 list_del(&p->l);
832                 iio_device_remove_and_free_read_attr(indio_dev, p);
833         }
834
835         return ret;
836 }
837
838 static void iio_device_unregister_sysfs(struct iio_dev *indio_dev)
839 {
840
841         struct iio_dev_attr *p, *n;
842
843         list_for_each_entry_safe(p, n, &indio_dev->channel_attr_list, l) {
844                 list_del(&p->l);
845                 iio_device_remove_and_free_read_attr(indio_dev, p);
846         }
847         kfree(indio_dev->chan_attr_group.attrs);
848 }
849
850 static void iio_dev_release(struct device *device)
851 {
852         struct iio_dev *indio_dev = dev_to_iio_dev(device);
853         if (indio_dev->chrdev.dev)
854                 cdev_del(&indio_dev->chrdev);
855         if (indio_dev->modes & INDIO_BUFFER_TRIGGERED)
856                 iio_device_unregister_trigger_consumer(indio_dev);
857         iio_device_unregister_eventset(indio_dev);
858         iio_device_unregister_sysfs(indio_dev);
859         iio_device_unregister_debugfs(indio_dev);
860
861         ida_simple_remove(&iio_ida, indio_dev->id);
862         kfree(indio_dev);
863 }
864
865 struct device_type iio_device_type = {
866         .name = "iio_device",
867         .release = iio_dev_release,
868 };
869
870 struct iio_dev *iio_device_alloc(int sizeof_priv)
871 {
872         struct iio_dev *dev;
873         size_t alloc_size;
874
875         alloc_size = sizeof(struct iio_dev);
876         if (sizeof_priv) {
877                 alloc_size = ALIGN(alloc_size, IIO_ALIGN);
878                 alloc_size += sizeof_priv;
879         }
880         /* ensure 32-byte alignment of whole construct ? */
881         alloc_size += IIO_ALIGN - 1;
882
883         dev = kzalloc(alloc_size, GFP_KERNEL);
884
885         if (dev) {
886                 dev->dev.groups = dev->groups;
887                 dev->dev.type = &iio_device_type;
888                 dev->dev.bus = &iio_bus_type;
889                 device_initialize(&dev->dev);
890                 dev_set_drvdata(&dev->dev, (void *)dev);
891                 mutex_init(&dev->mlock);
892                 mutex_init(&dev->info_exist_lock);
893                 INIT_LIST_HEAD(&dev->channel_attr_list);
894
895                 dev->id = ida_simple_get(&iio_ida, 0, 0, GFP_KERNEL);
896                 if (dev->id < 0) {
897                         /* cannot use a dev_err as the name isn't available */
898                         printk(KERN_ERR "Failed to get id\n");
899                         kfree(dev);
900                         return NULL;
901                 }
902                 dev_set_name(&dev->dev, "iio:device%d", dev->id);
903                 INIT_LIST_HEAD(&dev->buffer_list);
904         }
905
906         return dev;
907 }
908 EXPORT_SYMBOL(iio_device_alloc);
909
910 void iio_device_free(struct iio_dev *dev)
911 {
912         if (dev)
913                 put_device(&dev->dev);
914 }
915 EXPORT_SYMBOL(iio_device_free);
916
917 /**
918  * iio_chrdev_open() - chrdev file open for buffer access and ioctls
919  **/
920 static int iio_chrdev_open(struct inode *inode, struct file *filp)
921 {
922         struct iio_dev *indio_dev = container_of(inode->i_cdev,
923                                                 struct iio_dev, chrdev);
924
925         if (test_and_set_bit(IIO_BUSY_BIT_POS, &indio_dev->flags))
926                 return -EBUSY;
927
928         filp->private_data = indio_dev;
929
930         return 0;
931 }
932
933 /**
934  * iio_chrdev_release() - chrdev file close buffer access and ioctls
935  **/
936 static int iio_chrdev_release(struct inode *inode, struct file *filp)
937 {
938         struct iio_dev *indio_dev = container_of(inode->i_cdev,
939                                                 struct iio_dev, chrdev);
940         clear_bit(IIO_BUSY_BIT_POS, &indio_dev->flags);
941         return 0;
942 }
943
944 /* Somewhat of a cross file organization violation - ioctls here are actually
945  * event related */
946 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
947 {
948         struct iio_dev *indio_dev = filp->private_data;
949         int __user *ip = (int __user *)arg;
950         int fd;
951
952         if (cmd == IIO_GET_EVENT_FD_IOCTL) {
953                 fd = iio_event_getfd(indio_dev);
954                 if (copy_to_user(ip, &fd, sizeof(fd)))
955                         return -EFAULT;
956                 return 0;
957         }
958         return -EINVAL;
959 }
960
961 static const struct file_operations iio_buffer_fileops = {
962         .read = iio_buffer_read_first_n_outer_addr,
963         .release = iio_chrdev_release,
964         .open = iio_chrdev_open,
965         .poll = iio_buffer_poll_addr,
966         .owner = THIS_MODULE,
967         .llseek = noop_llseek,
968         .unlocked_ioctl = iio_ioctl,
969         .compat_ioctl = iio_ioctl,
970 };
971
972 static const struct iio_buffer_setup_ops noop_ring_setup_ops;
973
974 int iio_device_register(struct iio_dev *indio_dev)
975 {
976         int ret;
977
978         /* If the calling driver did not initialize of_node, do it here */
979         if (!indio_dev->dev.of_node && indio_dev->dev.parent)
980                 indio_dev->dev.of_node = indio_dev->dev.parent->of_node;
981
982         /* configure elements for the chrdev */
983         indio_dev->dev.devt = MKDEV(MAJOR(iio_devt), indio_dev->id);
984
985         ret = iio_device_register_debugfs(indio_dev);
986         if (ret) {
987                 dev_err(indio_dev->dev.parent,
988                         "Failed to register debugfs interfaces\n");
989                 goto error_ret;
990         }
991         ret = iio_device_register_sysfs(indio_dev);
992         if (ret) {
993                 dev_err(indio_dev->dev.parent,
994                         "Failed to register sysfs interfaces\n");
995                 goto error_unreg_debugfs;
996         }
997         ret = iio_device_register_eventset(indio_dev);
998         if (ret) {
999                 dev_err(indio_dev->dev.parent,
1000                         "Failed to register event set\n");
1001                 goto error_free_sysfs;
1002         }
1003         if (indio_dev->modes & INDIO_BUFFER_TRIGGERED)
1004                 iio_device_register_trigger_consumer(indio_dev);
1005
1006         if ((indio_dev->modes & INDIO_ALL_BUFFER_MODES) &&
1007                 indio_dev->setup_ops == NULL)
1008                 indio_dev->setup_ops = &noop_ring_setup_ops;
1009
1010         ret = device_add(&indio_dev->dev);
1011         if (ret < 0)
1012                 goto error_unreg_eventset;
1013         cdev_init(&indio_dev->chrdev, &iio_buffer_fileops);
1014         indio_dev->chrdev.owner = indio_dev->info->driver_module;
1015         ret = cdev_add(&indio_dev->chrdev, indio_dev->dev.devt, 1);
1016         if (ret < 0)
1017                 goto error_del_device;
1018         return 0;
1019
1020 error_del_device:
1021         device_del(&indio_dev->dev);
1022 error_unreg_eventset:
1023         iio_device_unregister_eventset(indio_dev);
1024 error_free_sysfs:
1025         iio_device_unregister_sysfs(indio_dev);
1026 error_unreg_debugfs:
1027         iio_device_unregister_debugfs(indio_dev);
1028 error_ret:
1029         return ret;
1030 }
1031 EXPORT_SYMBOL(iio_device_register);
1032
1033 void iio_device_unregister(struct iio_dev *indio_dev)
1034 {
1035         mutex_lock(&indio_dev->info_exist_lock);
1036         indio_dev->info = NULL;
1037         mutex_unlock(&indio_dev->info_exist_lock);
1038         device_del(&indio_dev->dev);
1039 }
1040 EXPORT_SYMBOL(iio_device_unregister);
1041 subsys_initcall(iio_init);
1042 module_exit(iio_exit);
1043
1044 MODULE_AUTHOR("Jonathan Cameron <jic23@kernel.org>");
1045 MODULE_DESCRIPTION("Industrial I/O core");
1046 MODULE_LICENSE("GPL");