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