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