staging: iio: push the main buffer chrdev down to the top level.
[pandora-kernel.git] / drivers / staging / 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 "iio.h"
26 #include "iio_core.h"
27 #include "iio_core_trigger.h"
28 #include "chrdev.h"
29
30 #define IIO_ID_PREFIX "device"
31 #define IIO_ID_FORMAT IIO_ID_PREFIX "%d"
32
33 /* IDR to assign each registered device a unique id*/
34 static DEFINE_IDA(iio_ida);
35 /* IDR to allocate character device minor numbers */
36 static DEFINE_IDA(iio_chrdev_ida);
37 /* Lock used to protect both of the above */
38 static DEFINE_SPINLOCK(iio_ida_lock);
39
40 dev_t iio_devt;
41
42 #define IIO_DEV_MAX 256
43 struct bus_type iio_bus_type = {
44         .name = "iio",
45 };
46 EXPORT_SYMBOL(iio_bus_type);
47
48 static const char * const iio_chan_type_name_spec_shared[] = {
49         [IIO_IN] = "in",
50         [IIO_OUT] = "out",
51         [IIO_CURRENT] = "current",
52         [IIO_POWER] = "power",
53         [IIO_ACCEL] = "accel",
54         [IIO_IN_DIFF] = "in-in",
55         [IIO_GYRO] = "gyro",
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 };
66
67 static const char * const iio_chan_type_name_spec_complex[] = {
68         [IIO_IN_DIFF] = "in%d-in%d",
69 };
70
71 static const char * const iio_modifier_names_light[] = {
72         [IIO_MOD_LIGHT_BOTH] = "both",
73         [IIO_MOD_LIGHT_IR] = "ir",
74 };
75
76 static const char * const iio_modifier_names_axial[] = {
77         [IIO_MOD_X] = "x",
78         [IIO_MOD_Y] = "y",
79         [IIO_MOD_Z] = "z",
80 };
81
82 /* relies on pairs of these shared then separate */
83 static const char * const iio_chan_info_postfix[] = {
84         [IIO_CHAN_INFO_SCALE_SHARED/2] = "scale",
85         [IIO_CHAN_INFO_OFFSET_SHARED/2] = "offset",
86         [IIO_CHAN_INFO_CALIBSCALE_SHARED/2] = "calibscale",
87         [IIO_CHAN_INFO_CALIBBIAS_SHARED/2] = "calibbias",
88         [IIO_CHAN_INFO_PEAK_SHARED/2] = "peak_raw",
89         [IIO_CHAN_INFO_PEAK_SCALE_SHARED/2] = "peak_scale",
90         [IIO_CHAN_INFO_QUADRATURE_CORRECTION_RAW_SHARED/2]
91         = "quadrature_correction_raw",
92 };
93
94 /* Return a negative errno on failure */
95 static int iio_get_new_ida_val(struct ida *this_ida)
96 {
97         int ret;
98         int val;
99
100 ida_again:
101         if (unlikely(ida_pre_get(this_ida, GFP_KERNEL) == 0))
102                 return -ENOMEM;
103
104         spin_lock(&iio_ida_lock);
105         ret = ida_get_new(this_ida, &val);
106         spin_unlock(&iio_ida_lock);
107         if (unlikely(ret == -EAGAIN))
108                 goto ida_again;
109         else if (unlikely(ret))
110                 return ret;
111
112         return val;
113 }
114
115 static void iio_free_ida_val(struct ida *this_ida, int id)
116 {
117         spin_lock(&iio_ida_lock);
118         ida_remove(this_ida, id);
119         spin_unlock(&iio_ida_lock);
120 }
121
122 /**
123  * struct iio_detected_event_list - list element for events that have occurred
124  * @list:               linked list header
125  * @ev:                 the event itself
126  */
127 struct iio_detected_event_list {
128         struct list_head                list;
129         struct iio_event_data           ev;
130 };
131
132 /**
133  * struct iio_event_interface - chrdev interface for an event line
134  * @dev:                device assocated with event interface
135  * @wait:               wait queue to allow blocking reads of events
136  * @event_list_lock:    mutex to protect the list of detected events
137  * @det_events:         list of detected events
138  * @max_events:         maximum number of events before new ones are dropped
139  * @current_events:     number of events in detected list
140  * @flags:              file operations related flags including busy flag.
141  */
142 struct iio_event_interface {
143         wait_queue_head_t                       wait;
144         struct mutex                            event_list_lock;
145         struct list_head                        det_events;
146         int                                     max_events;
147         int                                     current_events;
148         struct list_head dev_attr_list;
149         unsigned long flags;
150 };
151
152 int iio_push_event(struct iio_dev *dev_info,
153                    int ev_line,
154                    int ev_code,
155                    s64 timestamp)
156 {
157         struct iio_event_interface *ev_int
158                 = &dev_info->event_interfaces[ev_line];
159         struct iio_detected_event_list *ev;
160         int ret = 0;
161
162         /* Does anyone care? */
163         mutex_lock(&ev_int->event_list_lock);
164         if (test_bit(IIO_BUSY_BIT_POS, &ev_int->flags)) {
165                 if (ev_int->current_events == ev_int->max_events) {
166                         mutex_unlock(&ev_int->event_list_lock);
167                         return 0;
168                 }
169                 ev = kmalloc(sizeof(*ev), GFP_KERNEL);
170                 if (ev == NULL) {
171                         ret = -ENOMEM;
172                         mutex_unlock(&ev_int->event_list_lock);
173                         goto error_ret;
174                 }
175                 ev->ev.id = ev_code;
176                 ev->ev.timestamp = timestamp;
177
178                 list_add_tail(&ev->list, &ev_int->det_events);
179                 ev_int->current_events++;
180                 mutex_unlock(&ev_int->event_list_lock);
181                 wake_up_interruptible(&ev_int->wait);
182         } else
183                 mutex_unlock(&ev_int->event_list_lock);
184
185 error_ret:
186         return ret;
187 }
188 EXPORT_SYMBOL(iio_push_event);
189
190
191 /* This turns up an awful lot */
192 ssize_t iio_read_const_attr(struct device *dev,
193                             struct device_attribute *attr,
194                             char *buf)
195 {
196         return sprintf(buf, "%s\n", to_iio_const_attr(attr)->string);
197 }
198 EXPORT_SYMBOL(iio_read_const_attr);
199
200
201 static ssize_t iio_event_chrdev_read(struct file *filep,
202                                      char __user *buf,
203                                      size_t count,
204                                      loff_t *f_ps)
205 {
206         struct iio_event_interface *ev_int = filep->private_data;
207         struct iio_detected_event_list *el;
208         int ret;
209         size_t len;
210
211         mutex_lock(&ev_int->event_list_lock);
212         if (list_empty(&ev_int->det_events)) {
213                 if (filep->f_flags & O_NONBLOCK) {
214                         ret = -EAGAIN;
215                         goto error_mutex_unlock;
216                 }
217                 mutex_unlock(&ev_int->event_list_lock);
218                 /* Blocking on device; waiting for something to be there */
219                 ret = wait_event_interruptible(ev_int->wait,
220                                                !list_empty(&ev_int
221                                                            ->det_events));
222                 if (ret)
223                         goto error_ret;
224                 /* Single access device so no one else can get the data */
225                 mutex_lock(&ev_int->event_list_lock);
226         }
227
228         el = list_first_entry(&ev_int->det_events,
229                               struct iio_detected_event_list,
230                               list);
231         len = sizeof el->ev;
232         if (copy_to_user(buf, &(el->ev), len)) {
233                 ret = -EFAULT;
234                 goto error_mutex_unlock;
235         }
236         list_del(&el->list);
237         ev_int->current_events--;
238         mutex_unlock(&ev_int->event_list_lock);
239         kfree(el);
240
241         return len;
242
243 error_mutex_unlock:
244         mutex_unlock(&ev_int->event_list_lock);
245 error_ret:
246
247         return ret;
248 }
249
250 static int iio_event_chrdev_release(struct inode *inode, struct file *filep)
251 {
252         struct iio_event_interface *ev_int = filep->private_data;
253         struct iio_detected_event_list *el, *t;
254
255         mutex_lock(&ev_int->event_list_lock);
256         clear_bit(IIO_BUSY_BIT_POS, &ev_int->flags);
257         /*
258          * In order to maintain a clean state for reopening,
259          * clear out any awaiting events. The mask will prevent
260          * any new __iio_push_event calls running.
261          */
262         list_for_each_entry_safe(el, t, &ev_int->det_events, list) {
263                 list_del(&el->list);
264                 kfree(el);
265         }
266         ev_int->current_events = 0;
267         mutex_unlock(&ev_int->event_list_lock);
268
269         return 0;
270 }
271
272 static const struct file_operations iio_event_chrdev_fileops = {
273         .read =  iio_event_chrdev_read,
274         .release = iio_event_chrdev_release,
275         .owner = THIS_MODULE,
276         .llseek = noop_llseek,
277 };
278
279 int iio_device_get_chrdev_minor(void)
280 {
281         int ret;
282
283         ret = iio_get_new_ida_val(&iio_chrdev_ida);
284         if (ret < IIO_DEV_MAX) /* both errors and valid */
285                 return ret;
286         else
287                 return -ENOMEM;
288 }
289
290 void iio_device_free_chrdev_minor(int val)
291 {
292         iio_free_ida_val(&iio_chrdev_ida, val);
293 }
294
295 static int iio_event_getfd(struct iio_dev *indio_dev)
296 {
297         if (indio_dev->event_interfaces == NULL)
298                 return -ENODEV;
299
300         mutex_lock(&indio_dev->event_interfaces->event_list_lock);
301         if (test_and_set_bit(IIO_BUSY_BIT_POS,
302                              &indio_dev->event_interfaces->flags)) {
303                 mutex_unlock(&indio_dev->event_interfaces->event_list_lock);
304                 return -EBUSY;
305         }
306         mutex_unlock(&indio_dev->event_interfaces->event_list_lock);
307         return anon_inode_getfd("iio:event",
308                                 &iio_event_chrdev_fileops,
309                                 &indio_dev->event_interfaces[0], O_RDONLY);
310 }
311
312 static void iio_setup_ev_int(struct iio_event_interface *ev_int)
313 {
314         mutex_init(&ev_int->event_list_lock);
315         /* discussion point - make this variable? */
316         ev_int->max_events = 10;
317         ev_int->current_events = 0;
318         INIT_LIST_HEAD(&ev_int->det_events);
319         init_waitqueue_head(&ev_int->wait);
320 }
321
322 static int __init iio_init(void)
323 {
324         int ret;
325
326         /* Register sysfs bus */
327         ret  = bus_register(&iio_bus_type);
328         if (ret < 0) {
329                 printk(KERN_ERR
330                        "%s could not register bus type\n",
331                         __FILE__);
332                 goto error_nothing;
333         }
334
335         ret = alloc_chrdev_region(&iio_devt, 0, IIO_DEV_MAX, "iio");
336         if (ret < 0) {
337                 printk(KERN_ERR "%s: failed to allocate char dev region\n",
338                        __FILE__);
339                 goto error_unregister_bus_type;
340         }
341
342         return 0;
343
344 error_unregister_bus_type:
345         bus_unregister(&iio_bus_type);
346 error_nothing:
347         return ret;
348 }
349
350 static void __exit iio_exit(void)
351 {
352         if (iio_devt)
353                 unregister_chrdev_region(iio_devt, IIO_DEV_MAX);
354         bus_unregister(&iio_bus_type);
355 }
356
357 static ssize_t iio_read_channel_info(struct device *dev,
358                                      struct device_attribute *attr,
359                                      char *buf)
360 {
361         struct iio_dev *indio_dev = dev_get_drvdata(dev);
362         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
363         int val, val2;
364         int ret = indio_dev->info->read_raw(indio_dev, this_attr->c,
365                                             &val, &val2, this_attr->address);
366
367         if (ret < 0)
368                 return ret;
369
370         if (ret == IIO_VAL_INT)
371                 return sprintf(buf, "%d\n", val);
372         else if (ret == IIO_VAL_INT_PLUS_MICRO) {
373                 if (val2 < 0)
374                         return sprintf(buf, "-%d.%06u\n", val, -val2);
375                 else
376                         return sprintf(buf, "%d.%06u\n", val, val2);
377         } else if (ret == IIO_VAL_INT_PLUS_NANO) {
378                 if (val2 < 0)
379                         return sprintf(buf, "-%d.%09u\n", val, -val2);
380                 else
381                         return sprintf(buf, "%d.%09u\n", val, val2);
382         } else
383                 return 0;
384 }
385
386 static ssize_t iio_write_channel_info(struct device *dev,
387                                       struct device_attribute *attr,
388                                       const char *buf,
389                                       size_t len)
390 {
391         struct iio_dev *indio_dev = dev_get_drvdata(dev);
392         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
393         int ret, integer = 0, fract = 0, fract_mult = 100000;
394         bool integer_part = true, negative = false;
395
396         /* Assumes decimal - precision based on number of digits */
397         if (!indio_dev->info->write_raw)
398                 return -EINVAL;
399
400         if (indio_dev->info->write_raw_get_fmt)
401                 switch (indio_dev->info->write_raw_get_fmt(indio_dev,
402                         this_attr->c, this_attr->address)) {
403                 case IIO_VAL_INT_PLUS_MICRO:
404                         fract_mult = 100000;
405                         break;
406                 case IIO_VAL_INT_PLUS_NANO:
407                         fract_mult = 100000000;
408                         break;
409                 default:
410                         return -EINVAL;
411                 }
412
413         if (buf[0] == '-') {
414                 negative = true;
415                 buf++;
416         }
417
418         while (*buf) {
419                 if ('0' <= *buf && *buf <= '9') {
420                         if (integer_part)
421                                 integer = integer*10 + *buf - '0';
422                         else {
423                                 fract += fract_mult*(*buf - '0');
424                                 if (fract_mult == 1)
425                                         break;
426                                 fract_mult /= 10;
427                         }
428                 } else if (*buf == '\n') {
429                         if (*(buf + 1) == '\0')
430                                 break;
431                         else
432                                 return -EINVAL;
433                 } else if (*buf == '.') {
434                         integer_part = false;
435                 } else {
436                         return -EINVAL;
437                 }
438                 buf++;
439         }
440         if (negative) {
441                 if (integer)
442                         integer = -integer;
443                 else
444                         fract = -fract;
445         }
446
447         ret = indio_dev->info->write_raw(indio_dev, this_attr->c,
448                                          integer, fract, this_attr->address);
449         if (ret)
450                 return ret;
451
452         return len;
453 }
454
455 static int __iio_build_postfix(struct iio_chan_spec const *chan,
456                                bool generic,
457                                const char *postfix,
458                                char **result)
459 {
460         char *all_post;
461         /* 3 options - generic, extend_name, modified - if generic, extend_name
462         * and modified cannot apply.*/
463
464         if (generic || (!chan->modified && !chan->extend_name)) {
465                 all_post = kasprintf(GFP_KERNEL, "%s", postfix);
466         } else if (chan->modified) {
467                 const char *intermediate;
468                 switch (chan->type) {
469                 case IIO_INTENSITY:
470                         intermediate
471                                 = iio_modifier_names_light[chan->channel2];
472                         break;
473                 case IIO_ACCEL:
474                 case IIO_GYRO:
475                 case IIO_MAGN:
476                 case IIO_INCLI:
477                 case IIO_ROT:
478                 case IIO_ANGL:
479                         intermediate
480                                 = iio_modifier_names_axial[chan->channel2];
481                         break;
482                 default:
483                         return -EINVAL;
484                 }
485                 if (chan->extend_name)
486                         all_post = kasprintf(GFP_KERNEL, "%s_%s_%s",
487                                              intermediate,
488                                              chan->extend_name,
489                                              postfix);
490                 else
491                         all_post = kasprintf(GFP_KERNEL, "%s_%s",
492                                              intermediate,
493                                              postfix);
494         } else
495                 all_post = kasprintf(GFP_KERNEL, "%s_%s", chan->extend_name,
496                                      postfix);
497         if (all_post == NULL)
498                 return -ENOMEM;
499         *result = all_post;
500         return 0;
501 }
502
503 static
504 int __iio_device_attr_init(struct device_attribute *dev_attr,
505                            const char *postfix,
506                            struct iio_chan_spec const *chan,
507                            ssize_t (*readfunc)(struct device *dev,
508                                                struct device_attribute *attr,
509                                                char *buf),
510                            ssize_t (*writefunc)(struct device *dev,
511                                                 struct device_attribute *attr,
512                                                 const char *buf,
513                                                 size_t len),
514                            bool generic)
515 {
516         int ret;
517         char *name_format, *full_postfix;
518         sysfs_attr_init(&dev_attr->attr);
519         ret = __iio_build_postfix(chan, generic, postfix, &full_postfix);
520         if (ret)
521                 goto error_ret;
522
523         /* Special case for types that uses both channel numbers in naming */
524         if (chan->type == IIO_IN_DIFF && !generic)
525                 name_format
526                         = kasprintf(GFP_KERNEL, "%s_%s",
527                                     iio_chan_type_name_spec_complex[chan->type],
528                                     full_postfix);
529         else if (generic || !chan->indexed)
530                 name_format
531                         = kasprintf(GFP_KERNEL, "%s_%s",
532                                     iio_chan_type_name_spec_shared[chan->type],
533                                     full_postfix);
534         else
535                 name_format
536                         = kasprintf(GFP_KERNEL, "%s%d_%s",
537                                     iio_chan_type_name_spec_shared[chan->type],
538                                     chan->channel,
539                                     full_postfix);
540
541         if (name_format == NULL) {
542                 ret = -ENOMEM;
543                 goto error_free_full_postfix;
544         }
545         dev_attr->attr.name = kasprintf(GFP_KERNEL,
546                                         name_format,
547                                         chan->channel,
548                                         chan->channel2);
549         if (dev_attr->attr.name == NULL) {
550                 ret = -ENOMEM;
551                 goto error_free_name_format;
552         }
553
554         if (readfunc) {
555                 dev_attr->attr.mode |= S_IRUGO;
556                 dev_attr->show = readfunc;
557         }
558
559         if (writefunc) {
560                 dev_attr->attr.mode |= S_IWUSR;
561                 dev_attr->store = writefunc;
562         }
563         kfree(name_format);
564         kfree(full_postfix);
565
566         return 0;
567
568 error_free_name_format:
569         kfree(name_format);
570 error_free_full_postfix:
571         kfree(full_postfix);
572 error_ret:
573         return ret;
574 }
575
576 static void __iio_device_attr_deinit(struct device_attribute *dev_attr)
577 {
578         kfree(dev_attr->attr.name);
579 }
580
581 int __iio_add_chan_devattr(const char *postfix,
582                            const char *group,
583                            struct iio_chan_spec const *chan,
584                            ssize_t (*readfunc)(struct device *dev,
585                                                struct device_attribute *attr,
586                                                char *buf),
587                            ssize_t (*writefunc)(struct device *dev,
588                                                 struct device_attribute *attr,
589                                                 const char *buf,
590                                                 size_t len),
591                            int mask,
592                            bool generic,
593                            struct device *dev,
594                            struct list_head *attr_list)
595 {
596         int ret;
597         struct iio_dev_attr *iio_attr, *t;
598
599         iio_attr = kzalloc(sizeof *iio_attr, GFP_KERNEL);
600         if (iio_attr == NULL) {
601                 ret = -ENOMEM;
602                 goto error_ret;
603         }
604         ret = __iio_device_attr_init(&iio_attr->dev_attr,
605                                      postfix, chan,
606                                      readfunc, writefunc, generic);
607         if (ret)
608                 goto error_iio_dev_attr_free;
609         iio_attr->c = chan;
610         iio_attr->address = mask;
611         list_for_each_entry(t, attr_list, l)
612                 if (strcmp(t->dev_attr.attr.name,
613                            iio_attr->dev_attr.attr.name) == 0) {
614                         if (!generic)
615                                 dev_err(dev, "tried to double register : %s\n",
616                                         t->dev_attr.attr.name);
617                         ret = -EBUSY;
618                         goto error_device_attr_deinit;
619                 }
620
621         ret = sysfs_add_file_to_group(&dev->kobj,
622                                       &iio_attr->dev_attr.attr, group);
623         if (ret < 0)
624                 goto error_device_attr_deinit;
625
626         list_add(&iio_attr->l, attr_list);
627
628         return 0;
629
630 error_device_attr_deinit:
631         __iio_device_attr_deinit(&iio_attr->dev_attr);
632 error_iio_dev_attr_free:
633         kfree(iio_attr);
634 error_ret:
635         return ret;
636 }
637
638 static int iio_device_add_channel_sysfs(struct iio_dev *dev_info,
639                                         struct iio_chan_spec const *chan)
640 {
641         int ret, i;
642
643
644         if (chan->channel < 0)
645                 return 0;
646         if (chan->processed_val)
647                 ret = __iio_add_chan_devattr("input", NULL, chan,
648                                              &iio_read_channel_info,
649                                              NULL,
650                                              0,
651                                              0,
652                                              &dev_info->dev,
653                                              &dev_info->channel_attr_list);
654         else
655                 ret = __iio_add_chan_devattr("raw", NULL, chan,
656                                              &iio_read_channel_info,
657                                              (chan->type == IIO_OUT ?
658                                              &iio_write_channel_info : NULL),
659                                              0,
660                                              0,
661                                              &dev_info->dev,
662                                              &dev_info->channel_attr_list);
663         if (ret)
664                 goto error_ret;
665
666         for_each_set_bit(i, &chan->info_mask, sizeof(long)*8) {
667                 ret = __iio_add_chan_devattr(iio_chan_info_postfix[i/2],
668                                              NULL, chan,
669                                              &iio_read_channel_info,
670                                              &iio_write_channel_info,
671                                              (1 << i),
672                                              !(i%2),
673                                              &dev_info->dev,
674                                              &dev_info->channel_attr_list);
675                 if (ret == -EBUSY && (i%2 == 0)) {
676                         ret = 0;
677                         continue;
678                 }
679                 if (ret < 0)
680                         goto error_ret;
681         }
682 error_ret:
683         return ret;
684 }
685
686 static void iio_device_remove_and_free_read_attr(struct iio_dev *dev_info,
687                                                  struct iio_dev_attr *p)
688 {
689         sysfs_remove_file_from_group(&dev_info->dev.kobj,
690                                      &p->dev_attr.attr, NULL);
691         kfree(p->dev_attr.attr.name);
692         kfree(p);
693 }
694
695 static ssize_t iio_show_dev_name(struct device *dev,
696                                  struct device_attribute *attr,
697                                  char *buf)
698 {
699         struct iio_dev *indio_dev = dev_get_drvdata(dev);
700         return sprintf(buf, "%s\n", indio_dev->name);
701 }
702
703 static DEVICE_ATTR(name, S_IRUGO, iio_show_dev_name, NULL);
704
705 static struct attribute *iio_base_dummy_attrs[] = {
706         NULL
707 };
708 static struct attribute_group iio_base_dummy_group = {
709         .attrs = iio_base_dummy_attrs,
710 };
711
712 static int iio_device_register_sysfs(struct iio_dev *dev_info)
713 {
714         int i, ret = 0;
715         struct iio_dev_attr *p, *n;
716
717         if (dev_info->info->attrs)
718                 ret = sysfs_create_group(&dev_info->dev.kobj,
719                                          dev_info->info->attrs);
720         else
721                 ret = sysfs_create_group(&dev_info->dev.kobj,
722                                          &iio_base_dummy_group);
723         
724         if (ret) {
725                 dev_err(dev_info->dev.parent,
726                         "Failed to register sysfs hooks\n");
727                 goto error_ret;
728         }
729
730         /*
731          * New channel registration method - relies on the fact a group does
732          *  not need to be initialized if it is name is NULL.
733          */
734         INIT_LIST_HEAD(&dev_info->channel_attr_list);
735         if (dev_info->channels)
736                 for (i = 0; i < dev_info->num_channels; i++) {
737                         ret = iio_device_add_channel_sysfs(dev_info,
738                                                            &dev_info
739                                                            ->channels[i]);
740                         if (ret < 0)
741                                 goto error_clear_attrs;
742                 }
743         if (dev_info->name) { 
744                 ret = sysfs_add_file_to_group(&dev_info->dev.kobj,
745                                               &dev_attr_name.attr,
746                                               NULL);
747                 if (ret)
748                         goto error_clear_attrs;
749         }
750         return 0;
751
752 error_clear_attrs:
753         list_for_each_entry_safe(p, n,
754                                  &dev_info->channel_attr_list, l) {
755                 list_del(&p->l);
756                 iio_device_remove_and_free_read_attr(dev_info, p);
757         }
758         if (dev_info->info->attrs)
759                 sysfs_remove_group(&dev_info->dev.kobj, dev_info->info->attrs);
760         else
761                 sysfs_remove_group(&dev_info->dev.kobj, &iio_base_dummy_group);
762 error_ret:
763         return ret;
764
765 }
766
767 static void iio_device_unregister_sysfs(struct iio_dev *dev_info)
768 {
769
770         struct iio_dev_attr *p, *n;
771         if (dev_info->name)
772                 sysfs_remove_file_from_group(&dev_info->dev.kobj,
773                                              &dev_attr_name.attr,
774                                              NULL);
775         list_for_each_entry_safe(p, n, &dev_info->channel_attr_list, l) {
776                 list_del(&p->l);
777                 iio_device_remove_and_free_read_attr(dev_info, p);
778         }
779
780         if (dev_info->info->attrs)
781                 sysfs_remove_group(&dev_info->dev.kobj, dev_info->info->attrs);
782         else
783                 sysfs_remove_group(&dev_info->dev.kobj, &iio_base_dummy_group);
784 }
785
786 static const char * const iio_ev_type_text[] = {
787         [IIO_EV_TYPE_THRESH] = "thresh",
788         [IIO_EV_TYPE_MAG] = "mag",
789         [IIO_EV_TYPE_ROC] = "roc"
790 };
791
792 static const char * const iio_ev_dir_text[] = {
793         [IIO_EV_DIR_EITHER] = "either",
794         [IIO_EV_DIR_RISING] = "rising",
795         [IIO_EV_DIR_FALLING] = "falling"
796 };
797
798 static ssize_t iio_ev_state_store(struct device *dev,
799                                   struct device_attribute *attr,
800                                   const char *buf,
801                                   size_t len)
802 {
803         struct iio_dev *indio_dev = dev_get_drvdata(dev);
804         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
805         int ret;
806         bool val;
807
808         ret = strtobool(buf, &val);
809         if (ret < 0)
810                 return ret;
811
812         ret = indio_dev->info->write_event_config(indio_dev,
813                                                   this_attr->address,
814                                                   val);
815         return (ret < 0) ? ret : len;
816 }
817
818 static ssize_t iio_ev_state_show(struct device *dev,
819                                  struct device_attribute *attr,
820                                  char *buf)
821 {
822         struct iio_dev *indio_dev = dev_get_drvdata(dev);
823         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
824         int val = indio_dev->info->read_event_config(indio_dev,
825                                                      this_attr->address);
826
827         if (val < 0)
828                 return val;
829         else
830                 return sprintf(buf, "%d\n", val);
831 }
832
833 static ssize_t iio_ev_value_show(struct device *dev,
834                                  struct device_attribute *attr,
835                                  char *buf)
836 {
837         struct iio_dev *indio_dev = dev_get_drvdata(dev);
838         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
839         int val, ret;
840
841         ret = indio_dev->info->read_event_value(indio_dev,
842                                                 this_attr->address, &val);
843         if (ret < 0)
844                 return ret;
845
846         return sprintf(buf, "%d\n", val);
847 }
848
849 static ssize_t iio_ev_value_store(struct device *dev,
850                                   struct device_attribute *attr,
851                                   const char *buf,
852                                   size_t len)
853 {
854         struct iio_dev *indio_dev = dev_get_drvdata(dev);
855         struct iio_dev_attr *this_attr = to_iio_dev_attr(attr);
856         unsigned long val;
857         int ret;
858
859         ret = strict_strtoul(buf, 10, &val);
860         if (ret)
861                 return ret;
862
863         ret = indio_dev->info->write_event_value(indio_dev, this_attr->address,
864                                                  val);
865         if (ret < 0)
866                 return ret;
867
868         return len;
869 }
870
871 static int iio_device_add_event_sysfs(struct iio_dev *dev_info,
872                                       struct iio_chan_spec const *chan)
873 {
874
875         int ret = 0, i, mask = 0;
876         char *postfix;
877         if (!chan->event_mask)
878                 return 0;
879
880         for_each_set_bit(i, &chan->event_mask, sizeof(chan->event_mask)*8) {
881                 postfix = kasprintf(GFP_KERNEL, "%s_%s_en",
882                                     iio_ev_type_text[i/IIO_EV_TYPE_MAX],
883                                     iio_ev_dir_text[i%IIO_EV_TYPE_MAX]);
884                 if (postfix == NULL) {
885                         ret = -ENOMEM;
886                         goto error_ret;
887                 }
888                 switch (chan->type) {
889                         /* Switch this to a table at some point */
890                 case IIO_IN:
891                         mask = IIO_UNMOD_EVENT_CODE(chan->type, chan->channel,
892                                                     i/IIO_EV_TYPE_MAX,
893                                                     i%IIO_EV_TYPE_MAX);
894                         break;
895                 case IIO_ACCEL:
896                         mask = IIO_MOD_EVENT_CODE(chan->type, 0, chan->channel,
897                                                   i/IIO_EV_TYPE_MAX,
898                                                   i%IIO_EV_TYPE_MAX);
899                         break;
900                 case IIO_IN_DIFF:
901                         mask = IIO_MOD_EVENT_CODE(chan->type, chan->channel,
902                                                   chan->channel2,
903                                                   i/IIO_EV_TYPE_MAX,
904                                                   i%IIO_EV_TYPE_MAX);
905                         break;
906                 default:
907                         printk(KERN_INFO "currently unhandled type of event\n");
908                         continue;
909                 }
910                 ret = __iio_add_chan_devattr(postfix,
911                                              "events",
912                                              chan,
913                                              &iio_ev_state_show,
914                                              iio_ev_state_store,
915                                              mask,
916                                              /*HACK. - limits us to one
917                                                event interface - fix by
918                                                extending the bitmask - but
919                                                how far*/
920                                              0,
921                                              &dev_info->dev,
922                                              &dev_info->event_interfaces[0].
923                                              dev_attr_list);
924                 kfree(postfix);
925                 if (ret)
926                         goto error_ret;
927
928                 postfix = kasprintf(GFP_KERNEL, "%s_%s_value",
929                                     iio_ev_type_text[i/IIO_EV_TYPE_MAX],
930                                     iio_ev_dir_text[i%IIO_EV_TYPE_MAX]);
931                 if (postfix == NULL) {
932                         ret = -ENOMEM;
933                         goto error_ret;
934                 }
935                 ret = __iio_add_chan_devattr(postfix, "events", chan,
936                                              iio_ev_value_show,
937                                              iio_ev_value_store,
938                                              mask,
939                                              0,
940                                              &dev_info->dev,
941                                              &dev_info->event_interfaces[0]
942                                              .dev_attr_list);
943                 kfree(postfix);
944                 if (ret)
945                         goto error_ret;
946
947         }
948
949 error_ret:
950         return ret;
951 }
952
953 static inline void __iio_remove_event_config_attrs(struct iio_dev *dev_info,
954                                                   int i)
955 {
956         struct iio_dev_attr *p, *n;
957         list_for_each_entry_safe(p, n,
958                                  &dev_info->event_interfaces[i].
959                                  dev_attr_list, l) {
960                 sysfs_remove_file_from_group(&dev_info->dev.kobj,
961                                              &p->dev_attr.attr,
962                                              NULL);
963                 kfree(p->dev_attr.attr.name);
964                 kfree(p);
965         }
966 }
967
968 static inline int __iio_add_event_config_attrs(struct iio_dev *dev_info, int i)
969 {
970         int j;
971         int ret;
972         INIT_LIST_HEAD(&dev_info->event_interfaces[i].dev_attr_list);
973         /* Dynically created from the channels array */
974         if (dev_info->channels) {
975                 for (j = 0; j < dev_info->num_channels; j++) {
976                         ret = iio_device_add_event_sysfs(dev_info,
977                                                          &dev_info
978                                                          ->channels[j]);
979                         if (ret)
980                                 goto error_clear_attrs;
981                 }
982         }
983         return 0;
984
985 error_clear_attrs:
986         __iio_remove_event_config_attrs(dev_info, i);
987
988         return ret;
989 }
990
991 static struct attribute *iio_events_dummy_attrs[] = {
992         NULL
993 };
994
995 static struct attribute_group iio_events_dummy_group = {
996         .name = "events",
997         .attrs = iio_events_dummy_attrs
998 };
999
1000 static int iio_device_register_eventset(struct iio_dev *dev_info)
1001 {
1002         int ret = 0, i, j;
1003
1004         if (dev_info->info->num_interrupt_lines == 0)
1005                 return 0;
1006
1007         dev_info->event_interfaces =
1008                 kzalloc(sizeof(struct iio_event_interface)
1009                         *dev_info->info->num_interrupt_lines,
1010                         GFP_KERNEL);
1011         if (dev_info->event_interfaces == NULL) {
1012                 ret = -ENOMEM;
1013                 goto error_ret;
1014         }
1015
1016         for (i = 0; i < dev_info->info->num_interrupt_lines; i++) {
1017                 iio_setup_ev_int(&dev_info->event_interfaces[i]);
1018                 if (dev_info->info->event_attrs != NULL)
1019                         ret = sysfs_create_group(&dev_info->dev.kobj,
1020                                                  &dev_info->info
1021                                                  ->event_attrs[i]);
1022                 else
1023                         ret = sysfs_create_group(&dev_info->dev.kobj,
1024                                                  &iio_events_dummy_group);
1025                 if (ret) {
1026                         dev_err(&dev_info->dev,
1027                                 "Failed to register sysfs for event attrs");
1028                         goto error_free_setup_event_lines;
1029                 }
1030                 ret = __iio_add_event_config_attrs(dev_info, i);
1031                 if (ret) {
1032                         if (dev_info->info->event_attrs != NULL)
1033                                 sysfs_remove_group(&dev_info->dev.kobj,
1034                                                    &dev_info->info
1035                                                    ->event_attrs[i]);
1036                         else
1037                                 sysfs_remove_group(&dev_info->dev.kobj,
1038                                                    &iio_events_dummy_group);
1039                         goto error_free_setup_event_lines;
1040                 }
1041         }
1042
1043         return 0;
1044
1045 error_free_setup_event_lines:
1046         for (j = 0; j < i; j++) {
1047                 __iio_remove_event_config_attrs(dev_info, j);
1048                 if (dev_info->info->event_attrs != NULL) {
1049                         sysfs_remove_group(&dev_info->dev.kobj,
1050                                            &dev_info->info->event_attrs[j]);
1051                         sysfs_remove_group(&dev_info->dev.kobj,
1052                                            &iio_events_dummy_group);
1053                 }
1054         }
1055         kfree(dev_info->event_interfaces);
1056 error_ret:
1057
1058         return ret;
1059 }
1060
1061 static void iio_device_unregister_eventset(struct iio_dev *dev_info)
1062 {
1063         int i;
1064
1065         if (dev_info->info->num_interrupt_lines == 0)
1066                 return;
1067         for (i = 0; i < dev_info->info->num_interrupt_lines; i++) {
1068                 __iio_remove_event_config_attrs(dev_info, i);
1069                 if (dev_info->info->event_attrs != NULL)
1070                         sysfs_remove_group(&dev_info->dev.kobj,
1071                                            &dev_info->info->event_attrs[i]);
1072                 else
1073                         sysfs_remove_group(&dev_info->dev.kobj,
1074                                            &iio_events_dummy_group);
1075         }
1076         kfree(dev_info->event_interfaces);
1077 }
1078
1079 static void iio_dev_release(struct device *device)
1080 {
1081         struct iio_dev *dev_info = container_of(device, struct iio_dev, dev);
1082         cdev_del(&dev_info->chrdev);
1083         iio_device_free_chrdev_minor(MINOR(device->devt));
1084         iio_put();
1085         kfree(dev_info);
1086 }
1087
1088 static struct device_type iio_dev_type = {
1089         .name = "iio_device",
1090         .release = iio_dev_release,
1091 };
1092
1093 struct iio_dev *iio_allocate_device(int sizeof_priv)
1094 {
1095         struct iio_dev *dev;
1096         size_t alloc_size;
1097
1098         alloc_size = sizeof(struct iio_dev);
1099         if (sizeof_priv) {
1100                 alloc_size = ALIGN(alloc_size, IIO_ALIGN);
1101                 alloc_size += sizeof_priv;
1102         }
1103         /* ensure 32-byte alignment of whole construct ? */
1104         alloc_size += IIO_ALIGN - 1;
1105
1106         dev = kzalloc(alloc_size, GFP_KERNEL);
1107
1108         if (dev) {
1109                 dev->dev.type = &iio_dev_type;
1110                 dev->dev.bus = &iio_bus_type;
1111                 device_initialize(&dev->dev);
1112                 dev_set_drvdata(&dev->dev, (void *)dev);
1113                 mutex_init(&dev->mlock);
1114                 iio_get();
1115         }
1116
1117         return dev;
1118 }
1119 EXPORT_SYMBOL(iio_allocate_device);
1120
1121 void iio_free_device(struct iio_dev *dev)
1122 {
1123         if (dev) {
1124                 iio_put();
1125                 kfree(dev);
1126         }
1127 }
1128 EXPORT_SYMBOL(iio_free_device);
1129
1130 /**
1131  * iio_chrdev_open() - chrdev file open for ring buffer access and ioctls
1132  **/
1133 static int iio_chrdev_open(struct inode *inode, struct file *filp)
1134 {
1135         struct iio_dev *dev_info = container_of(inode->i_cdev,
1136                                                 struct iio_dev, chrdev);
1137         filp->private_data = dev_info;
1138         iio_chrdev_ring_open(dev_info);
1139         return 0;
1140 }
1141
1142 /**
1143  * iio_chrdev_release() - chrdev file close ring buffer access and ioctls
1144  **/
1145 static int iio_chrdev_release(struct inode *inode, struct file *filp)
1146 {
1147         iio_chrdev_ring_release(container_of(inode->i_cdev,
1148                                              struct iio_dev, chrdev));
1149         return 0;
1150 }
1151
1152 /* Somewhat of a cross file organization violation - ioctls here are actually
1153  * event related */
1154 static long iio_ioctl(struct file *filp, unsigned int cmd, unsigned long arg)
1155 {
1156         struct iio_dev *indio_dev = filp->private_data;
1157         int __user *ip = (int __user *)arg;
1158         int fd;
1159
1160         if (cmd == IIO_GET_EVENT_FD_IOCTL) {
1161                 fd = iio_event_getfd(indio_dev);
1162                 if (copy_to_user(ip, &fd, sizeof(fd)))
1163                         return -EFAULT;
1164                 return 0;
1165         }
1166         return -EINVAL;
1167 }
1168
1169 static const struct file_operations iio_ring_fileops = {
1170         .read = iio_ring_read_first_n_outer_addr,
1171         .release = iio_chrdev_release,
1172         .open = iio_chrdev_open,
1173         .poll = iio_ring_poll_addr,
1174         .owner = THIS_MODULE,
1175         .llseek = noop_llseek,
1176         .unlocked_ioctl = iio_ioctl,
1177         .compat_ioctl = iio_ioctl,
1178 };
1179
1180 int iio_device_register(struct iio_dev *dev_info)
1181 {
1182         int ret;
1183
1184         dev_info->id = iio_get_new_ida_val(&iio_ida);
1185         if (dev_info->id < 0) {
1186                 ret = dev_info->id;
1187                 dev_err(&dev_info->dev, "Failed to get id\n");
1188                 goto error_ret;
1189         }
1190         dev_set_name(&dev_info->dev, "iio:device%d", dev_info->id);
1191         ret = iio_device_get_chrdev_minor();
1192         if (ret < 0)
1193                 goto error_free_ida;
1194
1195         /* configure elements for the chrdev */
1196         dev_info->dev.devt = MKDEV(MAJOR(iio_devt), ret);
1197
1198         ret = device_add(&dev_info->dev);
1199         if (ret)
1200                 goto error_free_ida;
1201         ret = iio_device_register_sysfs(dev_info);
1202         if (ret) {
1203                 dev_err(dev_info->dev.parent,
1204                         "Failed to register sysfs interfaces\n");
1205                 goto error_del_device;
1206         }
1207         ret = iio_device_register_eventset(dev_info);
1208         if (ret) {
1209                 dev_err(dev_info->dev.parent,
1210                         "Failed to register event set\n");
1211                 goto error_free_sysfs;
1212         }
1213         if (dev_info->modes & INDIO_RING_TRIGGERED)
1214                 iio_device_register_trigger_consumer(dev_info);
1215
1216         cdev_init(&dev_info->chrdev, &iio_ring_fileops);
1217         dev_info->chrdev.owner = dev_info->info->driver_module;
1218         ret = cdev_add(&dev_info->chrdev, dev_info->dev.devt, 1);
1219         return 0;
1220
1221 error_free_sysfs:
1222         iio_device_unregister_sysfs(dev_info);
1223 error_del_device:
1224         device_del(&dev_info->dev);
1225 error_free_ida:
1226         iio_free_ida_val(&iio_ida, dev_info->id);
1227 error_ret:
1228         return ret;
1229 }
1230 EXPORT_SYMBOL(iio_device_register);
1231
1232 void iio_device_unregister(struct iio_dev *dev_info)
1233 {
1234         if (dev_info->modes & INDIO_RING_TRIGGERED)
1235                 iio_device_unregister_trigger_consumer(dev_info);
1236         iio_device_unregister_eventset(dev_info);
1237         iio_device_unregister_sysfs(dev_info);
1238         iio_free_ida_val(&iio_ida, dev_info->id);
1239         device_unregister(&dev_info->dev);
1240 }
1241 EXPORT_SYMBOL(iio_device_unregister);
1242
1243 void iio_put(void)
1244 {
1245         module_put(THIS_MODULE);
1246 }
1247
1248 void iio_get(void)
1249 {
1250         __module_get(THIS_MODULE);
1251 }
1252
1253 subsys_initcall(iio_init);
1254 module_exit(iio_exit);
1255
1256 MODULE_AUTHOR("Jonathan Cameron <jic23@cam.ac.uk>");
1257 MODULE_DESCRIPTION("Industrial I/O core");
1258 MODULE_LICENSE("GPL");