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