37400e85c41709b8642f8c919d36e67e766cd78b
[firefly-linux-kernel-4.4.55.git] / drivers / staging / comedi / comedi_fops.c
1 /*
2     comedi/comedi_fops.c
3     comedi kernel module
4
5     COMEDI - Linux Control and Measurement Device Interface
6     Copyright (C) 1997-2000 David A. Schleef <ds@schleef.org>
7
8     This program is free software; you can redistribute it and/or modify
9     it under the terms of the GNU General Public License as published by
10     the Free Software Foundation; either version 2 of the License, or
11     (at your option) any later version.
12
13     This program is distributed in the hope that it will be useful,
14     but WITHOUT ANY WARRANTY; without even the implied warranty of
15     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16     GNU General Public License for more details.
17 */
18
19 #undef DEBUG
20
21 #include "comedi_compat32.h"
22
23 #include <linux/module.h>
24 #include <linux/errno.h>
25 #include <linux/kernel.h>
26 #include <linux/sched.h>
27 #include <linux/fcntl.h>
28 #include <linux/delay.h>
29 #include <linux/mm.h>
30 #include <linux/slab.h>
31 #include <linux/kmod.h>
32 #include <linux/poll.h>
33 #include <linux/init.h>
34 #include <linux/device.h>
35 #include <linux/vmalloc.h>
36 #include <linux/fs.h>
37 #include "comedidev.h"
38 #include <linux/cdev.h>
39 #include <linux/stat.h>
40
41 #include <linux/io.h>
42 #include <linux/uaccess.h>
43
44 #include "comedi_internal.h"
45
46 #define COMEDI_NUM_MINORS 0x100
47 #define COMEDI_NUM_SUBDEVICE_MINORS     \
48         (COMEDI_NUM_MINORS - COMEDI_NUM_BOARD_MINORS)
49
50 #ifdef CONFIG_COMEDI_DEBUG
51 int comedi_debug;
52 EXPORT_SYMBOL_GPL(comedi_debug);
53 module_param(comedi_debug, int, S_IRUGO | S_IWUSR);
54 MODULE_PARM_DESC(comedi_debug,
55                  "enable comedi core and driver debugging if non-zero (default 0)"
56                 );
57 #endif
58
59 static int comedi_num_legacy_minors;
60 module_param(comedi_num_legacy_minors, int, S_IRUGO);
61 MODULE_PARM_DESC(comedi_num_legacy_minors,
62                  "number of comedi minor devices to reserve for non-auto-configured devices (default 0)"
63                 );
64
65 unsigned int comedi_default_buf_size_kb = CONFIG_COMEDI_DEFAULT_BUF_SIZE_KB;
66 module_param(comedi_default_buf_size_kb, uint, S_IRUGO | S_IWUSR);
67 MODULE_PARM_DESC(comedi_default_buf_size_kb,
68                  "default asynchronous buffer size in KiB (default "
69                  __MODULE_STRING(CONFIG_COMEDI_DEFAULT_BUF_SIZE_KB) ")");
70
71 unsigned int comedi_default_buf_maxsize_kb
72         = CONFIG_COMEDI_DEFAULT_BUF_MAXSIZE_KB;
73 module_param(comedi_default_buf_maxsize_kb, uint, S_IRUGO | S_IWUSR);
74 MODULE_PARM_DESC(comedi_default_buf_maxsize_kb,
75                  "default maximum size of asynchronous buffer in KiB (default "
76                  __MODULE_STRING(CONFIG_COMEDI_DEFAULT_BUF_MAXSIZE_KB) ")");
77
78 static DEFINE_MUTEX(comedi_board_minor_table_lock);
79 static struct comedi_device
80 *comedi_board_minor_table[COMEDI_NUM_BOARD_MINORS];
81
82 static DEFINE_MUTEX(comedi_subdevice_minor_table_lock);
83 /* Note: indexed by minor - COMEDI_NUM_BOARD_MINORS. */
84 static struct comedi_subdevice
85 *comedi_subdevice_minor_table[COMEDI_NUM_SUBDEVICE_MINORS];
86
87 static struct class *comedi_class;
88 static struct cdev comedi_cdev;
89
90 static void comedi_device_init(struct comedi_device *dev)
91 {
92         kref_init(&dev->refcount);
93         spin_lock_init(&dev->spinlock);
94         mutex_init(&dev->mutex);
95         init_rwsem(&dev->attach_lock);
96         dev->minor = -1;
97 }
98
99 static void comedi_dev_kref_release(struct kref *kref)
100 {
101         struct comedi_device *dev =
102                 container_of(kref, struct comedi_device, refcount);
103
104         mutex_destroy(&dev->mutex);
105         kfree(dev);
106 }
107
108 int comedi_dev_put(struct comedi_device *dev)
109 {
110         if (dev)
111                 return kref_put(&dev->refcount, comedi_dev_kref_release);
112         return 1;
113 }
114 EXPORT_SYMBOL_GPL(comedi_dev_put);
115
116 static struct comedi_device *comedi_dev_get(struct comedi_device *dev)
117 {
118         if (dev)
119                 kref_get(&dev->refcount);
120         return dev;
121 }
122
123 static void comedi_device_cleanup(struct comedi_device *dev)
124 {
125         struct module *driver_module = NULL;
126
127         if (dev == NULL)
128                 return;
129         mutex_lock(&dev->mutex);
130         if (dev->attached)
131                 driver_module = dev->driver->module;
132         comedi_device_detach(dev);
133         while (dev->use_count > 0) {
134                 if (driver_module)
135                         module_put(driver_module);
136                 module_put(THIS_MODULE);
137                 dev->use_count--;
138         }
139         mutex_unlock(&dev->mutex);
140 }
141
142 static bool comedi_clear_board_dev(struct comedi_device *dev)
143 {
144         unsigned int i = dev->minor;
145         bool cleared = false;
146
147         mutex_lock(&comedi_board_minor_table_lock);
148         if (dev == comedi_board_minor_table[i]) {
149                 comedi_board_minor_table[i] = NULL;
150                 cleared = true;
151         }
152         mutex_unlock(&comedi_board_minor_table_lock);
153         return cleared;
154 }
155
156 static struct comedi_device *comedi_clear_board_minor(unsigned minor)
157 {
158         struct comedi_device *dev;
159
160         mutex_lock(&comedi_board_minor_table_lock);
161         dev = comedi_board_minor_table[minor];
162         comedi_board_minor_table[minor] = NULL;
163         mutex_unlock(&comedi_board_minor_table_lock);
164         return dev;
165 }
166
167 static void comedi_free_board_dev(struct comedi_device *dev)
168 {
169         if (dev) {
170                 if (dev->class_dev) {
171                         device_destroy(comedi_class,
172                                        MKDEV(COMEDI_MAJOR, dev->minor));
173                 }
174                 comedi_device_cleanup(dev);
175                 comedi_dev_put(dev);
176         }
177 }
178
179 static struct comedi_subdevice
180 *comedi_subdevice_from_minor(unsigned minor)
181 {
182         struct comedi_subdevice *s;
183         unsigned int i = minor - COMEDI_NUM_BOARD_MINORS;
184
185         BUG_ON(i >= COMEDI_NUM_SUBDEVICE_MINORS);
186         mutex_lock(&comedi_subdevice_minor_table_lock);
187         s = comedi_subdevice_minor_table[i];
188         mutex_unlock(&comedi_subdevice_minor_table_lock);
189         return s;
190 }
191
192 static struct comedi_device *comedi_dev_from_board_minor(unsigned minor)
193 {
194         struct comedi_device *dev;
195
196         BUG_ON(minor >= COMEDI_NUM_BOARD_MINORS);
197         mutex_lock(&comedi_board_minor_table_lock);
198         dev = comedi_board_minor_table[minor];
199         mutex_unlock(&comedi_board_minor_table_lock);
200         return dev;
201 }
202
203 static struct comedi_device *comedi_dev_from_subdevice_minor(unsigned minor)
204 {
205         struct comedi_subdevice *s;
206
207         s = comedi_subdevice_from_minor(minor);
208         return s ? s->device : NULL;
209 }
210
211 struct comedi_device *comedi_dev_from_minor(unsigned minor)
212 {
213         if (minor < COMEDI_NUM_BOARD_MINORS)
214                 return comedi_dev_from_board_minor(minor);
215         else
216                 return comedi_dev_from_subdevice_minor(minor);
217 }
218 EXPORT_SYMBOL_GPL(comedi_dev_from_minor);
219
220 static struct comedi_device *comedi_dev_get_from_board_minor(unsigned minor)
221 {
222         struct comedi_device *dev;
223
224         BUG_ON(minor >= COMEDI_NUM_BOARD_MINORS);
225         mutex_lock(&comedi_board_minor_table_lock);
226         dev = comedi_dev_get(comedi_board_minor_table[minor]);
227         mutex_unlock(&comedi_board_minor_table_lock);
228         return dev;
229 }
230
231 static struct comedi_device *comedi_dev_get_from_subdevice_minor(unsigned minor)
232 {
233         struct comedi_device *dev;
234         struct comedi_subdevice *s;
235         unsigned int i = minor - COMEDI_NUM_BOARD_MINORS;
236
237         BUG_ON(i >= COMEDI_NUM_SUBDEVICE_MINORS);
238         mutex_lock(&comedi_subdevice_minor_table_lock);
239         s = comedi_subdevice_minor_table[i];
240         dev = comedi_dev_get(s ? s->device : NULL);
241         mutex_unlock(&comedi_subdevice_minor_table_lock);
242         return dev;
243 }
244
245 struct comedi_device *comedi_dev_get_from_minor(unsigned minor)
246 {
247         if (minor < COMEDI_NUM_BOARD_MINORS)
248                 return comedi_dev_get_from_board_minor(minor);
249         else
250                 return comedi_dev_get_from_subdevice_minor(minor);
251 }
252 EXPORT_SYMBOL_GPL(comedi_dev_get_from_minor);
253
254 static struct comedi_subdevice *
255 comedi_read_subdevice(const struct comedi_device *dev, unsigned int minor)
256 {
257         struct comedi_subdevice *s;
258
259         if (minor >= COMEDI_NUM_BOARD_MINORS) {
260                 s = comedi_subdevice_from_minor(minor);
261                 if (!s || s->device != dev)
262                         return NULL;
263                 if (s->subdev_flags & SDF_CMD_READ)
264                         return s;
265         }
266         return dev->read_subdev;
267 }
268
269 static struct comedi_subdevice *
270 comedi_write_subdevice(const struct comedi_device *dev, unsigned int minor)
271 {
272         struct comedi_subdevice *s;
273
274         if (minor >= COMEDI_NUM_BOARD_MINORS) {
275                 s = comedi_subdevice_from_minor(minor);
276                 if (!s || s->device != dev)
277                         return NULL;
278                 if (s->subdev_flags & SDF_CMD_WRITE)
279                         return s;
280         }
281         return dev->write_subdev;
282 }
283
284 static int resize_async_buffer(struct comedi_device *dev,
285                                struct comedi_subdevice *s,
286                                struct comedi_async *async, unsigned new_size)
287 {
288         int retval;
289
290         if (new_size > async->max_bufsize)
291                 return -EPERM;
292
293         if (s->busy) {
294                 DPRINTK("subdevice is busy, cannot resize buffer\n");
295                 return -EBUSY;
296         }
297         if (async->mmap_count) {
298                 DPRINTK("subdevice is mmapped, cannot resize buffer\n");
299                 return -EBUSY;
300         }
301
302         /* make sure buffer is an integral number of pages
303          * (we round up) */
304         new_size = (new_size + PAGE_SIZE - 1) & PAGE_MASK;
305
306         retval = comedi_buf_alloc(dev, s, new_size);
307         if (retval < 0)
308                 return retval;
309
310         if (s->buf_change) {
311                 retval = s->buf_change(dev, s, new_size);
312                 if (retval < 0)
313                         return retval;
314         }
315
316         DPRINTK("comedi%i subd %d buffer resized to %i bytes\n",
317                 dev->minor, s->index, async->prealloc_bufsz);
318         return 0;
319 }
320
321 /* sysfs attribute files */
322
323 static ssize_t max_read_buffer_kb_show(struct device *csdev,
324                                        struct device_attribute *attr, char *buf)
325 {
326         unsigned int minor = MINOR(csdev->devt);
327         struct comedi_device *dev;
328         struct comedi_subdevice *s;
329         unsigned int size = 0;
330
331         dev = comedi_dev_get_from_minor(minor);
332         if (!dev)
333                 return -ENODEV;
334
335         mutex_lock(&dev->mutex);
336         s = comedi_read_subdevice(dev, minor);
337         if (s && (s->subdev_flags & SDF_CMD_READ) && s->async)
338                 size = s->async->max_bufsize / 1024;
339         mutex_unlock(&dev->mutex);
340
341         comedi_dev_put(dev);
342         return snprintf(buf, PAGE_SIZE, "%i\n", size);
343 }
344
345 static ssize_t max_read_buffer_kb_store(struct device *csdev,
346                                         struct device_attribute *attr,
347                                         const char *buf, size_t count)
348 {
349         unsigned int minor = MINOR(csdev->devt);
350         struct comedi_device *dev;
351         struct comedi_subdevice *s;
352         unsigned int size;
353         int err;
354
355         err = kstrtouint(buf, 10, &size);
356         if (err)
357                 return err;
358         if (size > (UINT_MAX / 1024))
359                 return -EINVAL;
360         size *= 1024;
361
362         dev = comedi_dev_get_from_minor(minor);
363         if (!dev)
364                 return -ENODEV;
365
366         mutex_lock(&dev->mutex);
367         s = comedi_read_subdevice(dev, minor);
368         if (s && (s->subdev_flags & SDF_CMD_READ) && s->async)
369                 s->async->max_bufsize = size;
370         else
371                 err = -EINVAL;
372         mutex_unlock(&dev->mutex);
373
374         comedi_dev_put(dev);
375         return err ? err : count;
376 }
377 static DEVICE_ATTR_RW(max_read_buffer_kb);
378
379 static ssize_t read_buffer_kb_show(struct device *csdev,
380                                    struct device_attribute *attr, char *buf)
381 {
382         unsigned int minor = MINOR(csdev->devt);
383         struct comedi_device *dev;
384         struct comedi_subdevice *s;
385         unsigned int size = 0;
386
387         dev = comedi_dev_get_from_minor(minor);
388         if (!dev)
389                 return -ENODEV;
390
391         mutex_lock(&dev->mutex);
392         s = comedi_read_subdevice(dev, minor);
393         if (s && (s->subdev_flags & SDF_CMD_READ) && s->async)
394                 size = s->async->prealloc_bufsz / 1024;
395         mutex_unlock(&dev->mutex);
396
397         comedi_dev_put(dev);
398         return snprintf(buf, PAGE_SIZE, "%i\n", size);
399 }
400
401 static ssize_t read_buffer_kb_store(struct device *csdev,
402                                     struct device_attribute *attr,
403                                     const char *buf, size_t count)
404 {
405         unsigned int minor = MINOR(csdev->devt);
406         struct comedi_device *dev;
407         struct comedi_subdevice *s;
408         unsigned int size;
409         int err;
410
411         err = kstrtouint(buf, 10, &size);
412         if (err)
413                 return err;
414         if (size > (UINT_MAX / 1024))
415                 return -EINVAL;
416         size *= 1024;
417
418         dev = comedi_dev_get_from_minor(minor);
419         if (!dev)
420                 return -ENODEV;
421
422         mutex_lock(&dev->mutex);
423         s = comedi_read_subdevice(dev, minor);
424         if (s && (s->subdev_flags & SDF_CMD_READ) && s->async)
425                 err = resize_async_buffer(dev, s, s->async, size);
426         else
427                 err = -EINVAL;
428         mutex_unlock(&dev->mutex);
429
430         comedi_dev_put(dev);
431         return err ? err : count;
432 }
433 static DEVICE_ATTR_RW(read_buffer_kb);
434
435 static ssize_t max_write_buffer_kb_show(struct device *csdev,
436                                         struct device_attribute *attr,
437                                         char *buf)
438 {
439         unsigned int minor = MINOR(csdev->devt);
440         struct comedi_device *dev;
441         struct comedi_subdevice *s;
442         unsigned int size = 0;
443
444         dev = comedi_dev_get_from_minor(minor);
445         if (!dev)
446                 return -ENODEV;
447
448         mutex_lock(&dev->mutex);
449         s = comedi_write_subdevice(dev, minor);
450         if (s && (s->subdev_flags & SDF_CMD_WRITE) && s->async)
451                 size = s->async->max_bufsize / 1024;
452         mutex_unlock(&dev->mutex);
453
454         comedi_dev_put(dev);
455         return snprintf(buf, PAGE_SIZE, "%i\n", size);
456 }
457
458 static ssize_t max_write_buffer_kb_store(struct device *csdev,
459                                          struct device_attribute *attr,
460                                          const char *buf, size_t count)
461 {
462         unsigned int minor = MINOR(csdev->devt);
463         struct comedi_device *dev;
464         struct comedi_subdevice *s;
465         unsigned int size;
466         int err;
467
468         err = kstrtouint(buf, 10, &size);
469         if (err)
470                 return err;
471         if (size > (UINT_MAX / 1024))
472                 return -EINVAL;
473         size *= 1024;
474
475         dev = comedi_dev_get_from_minor(minor);
476         if (!dev)
477                 return -ENODEV;
478
479         mutex_lock(&dev->mutex);
480         s = comedi_write_subdevice(dev, minor);
481         if (s && (s->subdev_flags & SDF_CMD_WRITE) && s->async)
482                 s->async->max_bufsize = size;
483         else
484                 err = -EINVAL;
485         mutex_unlock(&dev->mutex);
486
487         comedi_dev_put(dev);
488         return err ? err : count;
489 }
490 static DEVICE_ATTR_RW(max_write_buffer_kb);
491
492 static ssize_t write_buffer_kb_show(struct device *csdev,
493                                     struct device_attribute *attr, char *buf)
494 {
495         unsigned int minor = MINOR(csdev->devt);
496         struct comedi_device *dev;
497         struct comedi_subdevice *s;
498         unsigned int size = 0;
499
500         dev = comedi_dev_get_from_minor(minor);
501         if (!dev)
502                 return -ENODEV;
503
504         mutex_lock(&dev->mutex);
505         s = comedi_write_subdevice(dev, minor);
506         if (s && (s->subdev_flags & SDF_CMD_WRITE) && s->async)
507                 size = s->async->prealloc_bufsz / 1024;
508         mutex_unlock(&dev->mutex);
509
510         comedi_dev_put(dev);
511         return snprintf(buf, PAGE_SIZE, "%i\n", size);
512 }
513
514 static ssize_t write_buffer_kb_store(struct device *csdev,
515                                      struct device_attribute *attr,
516                                      const char *buf, size_t count)
517 {
518         unsigned int minor = MINOR(csdev->devt);
519         struct comedi_device *dev;
520         struct comedi_subdevice *s;
521         unsigned int size;
522         int err;
523
524         err = kstrtouint(buf, 10, &size);
525         if (err)
526                 return err;
527         if (size > (UINT_MAX / 1024))
528                 return -EINVAL;
529         size *= 1024;
530
531         dev = comedi_dev_get_from_minor(minor);
532         if (!dev)
533                 return -ENODEV;
534
535         mutex_lock(&dev->mutex);
536         s = comedi_write_subdevice(dev, minor);
537         if (s && (s->subdev_flags & SDF_CMD_WRITE) && s->async)
538                 err = resize_async_buffer(dev, s, s->async, size);
539         else
540                 err = -EINVAL;
541         mutex_unlock(&dev->mutex);
542
543         comedi_dev_put(dev);
544         return err ? err : count;
545 }
546 static DEVICE_ATTR_RW(write_buffer_kb);
547
548 static struct attribute *comedi_dev_attrs[] = {
549         &dev_attr_max_read_buffer_kb.attr,
550         &dev_attr_read_buffer_kb.attr,
551         &dev_attr_max_write_buffer_kb.attr,
552         &dev_attr_write_buffer_kb.attr,
553         NULL,
554 };
555 ATTRIBUTE_GROUPS(comedi_dev);
556
557 static void comedi_set_subdevice_runflags(struct comedi_subdevice *s,
558                                           unsigned mask, unsigned bits)
559 {
560         unsigned long flags;
561
562         spin_lock_irqsave(&s->spin_lock, flags);
563         s->runflags &= ~mask;
564         s->runflags |= (bits & mask);
565         spin_unlock_irqrestore(&s->spin_lock, flags);
566 }
567
568 static unsigned comedi_get_subdevice_runflags(struct comedi_subdevice *s)
569 {
570         unsigned long flags;
571         unsigned runflags;
572
573         spin_lock_irqsave(&s->spin_lock, flags);
574         runflags = s->runflags;
575         spin_unlock_irqrestore(&s->spin_lock, flags);
576         return runflags;
577 }
578
579 bool comedi_is_subdevice_running(struct comedi_subdevice *s)
580 {
581         unsigned runflags = comedi_get_subdevice_runflags(s);
582
583         return (runflags & SRF_RUNNING) ? true : false;
584 }
585 EXPORT_SYMBOL_GPL(comedi_is_subdevice_running);
586
587 static bool comedi_is_subdevice_in_error(struct comedi_subdevice *s)
588 {
589         unsigned runflags = comedi_get_subdevice_runflags(s);
590
591         return (runflags & SRF_ERROR) ? true : false;
592 }
593
594 static bool comedi_is_subdevice_idle(struct comedi_subdevice *s)
595 {
596         unsigned runflags = comedi_get_subdevice_runflags(s);
597
598         return (runflags & (SRF_ERROR | SRF_RUNNING)) ? false : true;
599 }
600
601 /**
602  * comedi_alloc_spriv() - Allocate memory for the subdevice private data.
603  * @s: comedi_subdevice struct
604  * @size: size of the memory to allocate
605  *
606  * This also sets the subdevice runflags to allow the core to automatically
607  * free the private data during the detach.
608  */
609 void *comedi_alloc_spriv(struct comedi_subdevice *s, size_t size)
610 {
611         s->private = kzalloc(size, GFP_KERNEL);
612         if (s->private)
613                 s->runflags |= SRF_FREE_SPRIV;
614         return s->private;
615 }
616 EXPORT_SYMBOL_GPL(comedi_alloc_spriv);
617
618 /*
619    This function restores a subdevice to an idle state.
620  */
621 static void do_become_nonbusy(struct comedi_device *dev,
622                               struct comedi_subdevice *s)
623 {
624         struct comedi_async *async = s->async;
625
626         comedi_set_subdevice_runflags(s, SRF_RUNNING, 0);
627         if (async) {
628                 comedi_buf_reset(async);
629                 async->inttrig = NULL;
630                 kfree(async->cmd.chanlist);
631                 async->cmd.chanlist = NULL;
632                 s->busy = NULL;
633                 wake_up_interruptible_all(&s->async->wait_head);
634         } else {
635                 dev_err(dev->class_dev,
636                         "BUG: (?) do_become_nonbusy called with async=NULL\n");
637                 s->busy = NULL;
638         }
639 }
640
641 static int do_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
642 {
643         int ret = 0;
644
645         if (comedi_is_subdevice_running(s) && s->cancel)
646                 ret = s->cancel(dev, s);
647
648         do_become_nonbusy(dev, s);
649
650         return ret;
651 }
652
653 void comedi_device_cancel_all(struct comedi_device *dev)
654 {
655         struct comedi_subdevice *s;
656         int i;
657
658         if (!dev->attached)
659                 return;
660
661         for (i = 0; i < dev->n_subdevices; i++) {
662                 s = &dev->subdevices[i];
663                 if (s->async)
664                         do_cancel(dev, s);
665         }
666 }
667
668 static int is_device_busy(struct comedi_device *dev)
669 {
670         struct comedi_subdevice *s;
671         int i;
672
673         if (!dev->attached)
674                 return 0;
675
676         for (i = 0; i < dev->n_subdevices; i++) {
677                 s = &dev->subdevices[i];
678                 if (s->busy)
679                         return 1;
680                 if (s->async && s->async->mmap_count)
681                         return 1;
682         }
683
684         return 0;
685 }
686
687 /*
688         COMEDI_DEVCONFIG
689         device config ioctl
690
691         arg:
692                 pointer to devconfig structure
693
694         reads:
695                 devconfig structure at arg
696
697         writes:
698                 none
699 */
700 static int do_devconfig_ioctl(struct comedi_device *dev,
701                               struct comedi_devconfig __user *arg)
702 {
703         struct comedi_devconfig it;
704
705         if (!capable(CAP_SYS_ADMIN))
706                 return -EPERM;
707
708         if (arg == NULL) {
709                 if (is_device_busy(dev))
710                         return -EBUSY;
711                 if (dev->attached) {
712                         struct module *driver_module = dev->driver->module;
713                         comedi_device_detach(dev);
714                         module_put(driver_module);
715                 }
716                 return 0;
717         }
718
719         if (copy_from_user(&it, arg, sizeof(it)))
720                 return -EFAULT;
721
722         it.board_name[COMEDI_NAMELEN - 1] = 0;
723
724         if (it.options[COMEDI_DEVCONF_AUX_DATA_LENGTH]) {
725                 dev_warn(dev->class_dev,
726                          "comedi_config --init_data is deprecated\n");
727                 return -EINVAL;
728         }
729
730         if (dev->minor >= comedi_num_legacy_minors)
731                 /* don't re-use dynamically allocated comedi devices */
732                 return -EBUSY;
733
734         /* This increments the driver module count on success. */
735         return comedi_device_attach(dev, &it);
736 }
737
738 /*
739         COMEDI_BUFCONFIG
740         buffer configuration ioctl
741
742         arg:
743                 pointer to bufconfig structure
744
745         reads:
746                 bufconfig at arg
747
748         writes:
749                 modified bufconfig at arg
750
751 */
752 static int do_bufconfig_ioctl(struct comedi_device *dev,
753                               struct comedi_bufconfig __user *arg)
754 {
755         struct comedi_bufconfig bc;
756         struct comedi_async *async;
757         struct comedi_subdevice *s;
758         int retval = 0;
759
760         if (copy_from_user(&bc, arg, sizeof(bc)))
761                 return -EFAULT;
762
763         if (bc.subdevice >= dev->n_subdevices)
764                 return -EINVAL;
765
766         s = &dev->subdevices[bc.subdevice];
767         async = s->async;
768
769         if (!async) {
770                 DPRINTK("subdevice does not have async capability\n");
771                 bc.size = 0;
772                 bc.maximum_size = 0;
773                 goto copyback;
774         }
775
776         if (bc.maximum_size) {
777                 if (!capable(CAP_SYS_ADMIN))
778                         return -EPERM;
779
780                 async->max_bufsize = bc.maximum_size;
781         }
782
783         if (bc.size) {
784                 retval = resize_async_buffer(dev, s, async, bc.size);
785                 if (retval < 0)
786                         return retval;
787         }
788
789         bc.size = async->prealloc_bufsz;
790         bc.maximum_size = async->max_bufsize;
791
792 copyback:
793         if (copy_to_user(arg, &bc, sizeof(bc)))
794                 return -EFAULT;
795
796         return 0;
797 }
798
799 /*
800         COMEDI_DEVINFO
801         device info ioctl
802
803         arg:
804                 pointer to devinfo structure
805
806         reads:
807                 none
808
809         writes:
810                 devinfo structure
811
812 */
813 static int do_devinfo_ioctl(struct comedi_device *dev,
814                             struct comedi_devinfo __user *arg,
815                             struct file *file)
816 {
817         const unsigned minor = iminor(file_inode(file));
818         struct comedi_subdevice *s;
819         struct comedi_devinfo devinfo;
820
821         memset(&devinfo, 0, sizeof(devinfo));
822
823         /* fill devinfo structure */
824         devinfo.version_code = COMEDI_VERSION_CODE;
825         devinfo.n_subdevs = dev->n_subdevices;
826         strlcpy(devinfo.driver_name, dev->driver->driver_name, COMEDI_NAMELEN);
827         strlcpy(devinfo.board_name, dev->board_name, COMEDI_NAMELEN);
828
829         s = comedi_read_subdevice(dev, minor);
830         if (s)
831                 devinfo.read_subdevice = s->index;
832         else
833                 devinfo.read_subdevice = -1;
834
835         s = comedi_write_subdevice(dev, minor);
836         if (s)
837                 devinfo.write_subdevice = s->index;
838         else
839                 devinfo.write_subdevice = -1;
840
841         if (copy_to_user(arg, &devinfo, sizeof(devinfo)))
842                 return -EFAULT;
843
844         return 0;
845 }
846
847 /*
848         COMEDI_SUBDINFO
849         subdevice info ioctl
850
851         arg:
852                 pointer to array of subdevice info structures
853
854         reads:
855                 none
856
857         writes:
858                 array of subdevice info structures at arg
859
860 */
861 static int do_subdinfo_ioctl(struct comedi_device *dev,
862                              struct comedi_subdinfo __user *arg, void *file)
863 {
864         int ret, i;
865         struct comedi_subdinfo *tmp, *us;
866         struct comedi_subdevice *s;
867
868         tmp = kcalloc(dev->n_subdevices, sizeof(*tmp), GFP_KERNEL);
869         if (!tmp)
870                 return -ENOMEM;
871
872         /* fill subdinfo structs */
873         for (i = 0; i < dev->n_subdevices; i++) {
874                 s = &dev->subdevices[i];
875                 us = tmp + i;
876
877                 us->type = s->type;
878                 us->n_chan = s->n_chan;
879                 us->subd_flags = s->subdev_flags;
880                 if (comedi_is_subdevice_running(s))
881                         us->subd_flags |= SDF_RUNNING;
882 #define TIMER_nanosec 5         /* backwards compatibility */
883                 us->timer_type = TIMER_nanosec;
884                 us->len_chanlist = s->len_chanlist;
885                 us->maxdata = s->maxdata;
886                 if (s->range_table) {
887                         us->range_type =
888                             (i << 24) | (0 << 16) | (s->range_table->length);
889                 } else {
890                         us->range_type = 0;     /* XXX */
891                 }
892
893                 if (s->busy)
894                         us->subd_flags |= SDF_BUSY;
895                 if (s->busy == file)
896                         us->subd_flags |= SDF_BUSY_OWNER;
897                 if (s->lock)
898                         us->subd_flags |= SDF_LOCKED;
899                 if (s->lock == file)
900                         us->subd_flags |= SDF_LOCK_OWNER;
901                 if (!s->maxdata && s->maxdata_list)
902                         us->subd_flags |= SDF_MAXDATA;
903                 if (s->range_table_list)
904                         us->subd_flags |= SDF_RANGETYPE;
905                 if (s->do_cmd)
906                         us->subd_flags |= SDF_CMD;
907
908                 if (s->insn_bits != &insn_inval)
909                         us->insn_bits_support = COMEDI_SUPPORTED;
910                 else
911                         us->insn_bits_support = COMEDI_UNSUPPORTED;
912         }
913
914         ret = copy_to_user(arg, tmp, dev->n_subdevices * sizeof(*tmp));
915
916         kfree(tmp);
917
918         return ret ? -EFAULT : 0;
919 }
920
921 /*
922         COMEDI_CHANINFO
923         subdevice info ioctl
924
925         arg:
926                 pointer to chaninfo structure
927
928         reads:
929                 chaninfo structure at arg
930
931         writes:
932                 arrays at elements of chaninfo structure
933
934 */
935 static int do_chaninfo_ioctl(struct comedi_device *dev,
936                              struct comedi_chaninfo __user *arg)
937 {
938         struct comedi_subdevice *s;
939         struct comedi_chaninfo it;
940
941         if (copy_from_user(&it, arg, sizeof(it)))
942                 return -EFAULT;
943
944         if (it.subdev >= dev->n_subdevices)
945                 return -EINVAL;
946         s = &dev->subdevices[it.subdev];
947
948         if (it.maxdata_list) {
949                 if (s->maxdata || !s->maxdata_list)
950                         return -EINVAL;
951                 if (copy_to_user(it.maxdata_list, s->maxdata_list,
952                                  s->n_chan * sizeof(unsigned int)))
953                         return -EFAULT;
954         }
955
956         if (it.flaglist)
957                 return -EINVAL; /* flaglist not supported */
958
959         if (it.rangelist) {
960                 int i;
961
962                 if (!s->range_table_list)
963                         return -EINVAL;
964                 for (i = 0; i < s->n_chan; i++) {
965                         int x;
966
967                         x = (dev->minor << 28) | (it.subdev << 24) | (i << 16) |
968                             (s->range_table_list[i]->length);
969                         if (put_user(x, it.rangelist + i))
970                                 return -EFAULT;
971                 }
972 #if 0
973                 if (copy_to_user(it.rangelist, s->range_type_list,
974                                  s->n_chan * sizeof(unsigned int)))
975                         return -EFAULT;
976 #endif
977         }
978
979         return 0;
980 }
981
982  /*
983     COMEDI_BUFINFO
984     buffer information ioctl
985
986     arg:
987     pointer to bufinfo structure
988
989     reads:
990     bufinfo at arg
991
992     writes:
993     modified bufinfo at arg
994
995   */
996 static int do_bufinfo_ioctl(struct comedi_device *dev,
997                             struct comedi_bufinfo __user *arg, void *file)
998 {
999         struct comedi_bufinfo bi;
1000         struct comedi_subdevice *s;
1001         struct comedi_async *async;
1002
1003         if (copy_from_user(&bi, arg, sizeof(bi)))
1004                 return -EFAULT;
1005
1006         if (bi.subdevice >= dev->n_subdevices)
1007                 return -EINVAL;
1008
1009         s = &dev->subdevices[bi.subdevice];
1010
1011         if (s->lock && s->lock != file)
1012                 return -EACCES;
1013
1014         async = s->async;
1015
1016         if (!async) {
1017                 DPRINTK("subdevice does not have async capability\n");
1018                 bi.buf_write_ptr = 0;
1019                 bi.buf_read_ptr = 0;
1020                 bi.buf_write_count = 0;
1021                 bi.buf_read_count = 0;
1022                 bi.bytes_read = 0;
1023                 bi.bytes_written = 0;
1024                 goto copyback;
1025         }
1026         if (!s->busy) {
1027                 bi.bytes_read = 0;
1028                 bi.bytes_written = 0;
1029                 goto copyback_position;
1030         }
1031         if (s->busy != file)
1032                 return -EACCES;
1033
1034         if (bi.bytes_read && (s->subdev_flags & SDF_CMD_READ)) {
1035                 bi.bytes_read = comedi_buf_read_alloc(async, bi.bytes_read);
1036                 comedi_buf_read_free(async, bi.bytes_read);
1037
1038                 if (comedi_is_subdevice_idle(s) &&
1039                     async->buf_write_count == async->buf_read_count) {
1040                         do_become_nonbusy(dev, s);
1041                 }
1042         }
1043
1044         if (bi.bytes_written && (s->subdev_flags & SDF_CMD_WRITE)) {
1045                 bi.bytes_written =
1046                     comedi_buf_write_alloc(async, bi.bytes_written);
1047                 comedi_buf_write_free(async, bi.bytes_written);
1048         }
1049
1050 copyback_position:
1051         bi.buf_write_count = async->buf_write_count;
1052         bi.buf_write_ptr = async->buf_write_ptr;
1053         bi.buf_read_count = async->buf_read_count;
1054         bi.buf_read_ptr = async->buf_read_ptr;
1055
1056 copyback:
1057         if (copy_to_user(arg, &bi, sizeof(bi)))
1058                 return -EFAULT;
1059
1060         return 0;
1061 }
1062
1063 static int check_insn_config_length(struct comedi_insn *insn,
1064                                     unsigned int *data)
1065 {
1066         if (insn->n < 1)
1067                 return -EINVAL;
1068
1069         switch (data[0]) {
1070         case INSN_CONFIG_DIO_OUTPUT:
1071         case INSN_CONFIG_DIO_INPUT:
1072         case INSN_CONFIG_DISARM:
1073         case INSN_CONFIG_RESET:
1074                 if (insn->n == 1)
1075                         return 0;
1076                 break;
1077         case INSN_CONFIG_ARM:
1078         case INSN_CONFIG_DIO_QUERY:
1079         case INSN_CONFIG_BLOCK_SIZE:
1080         case INSN_CONFIG_FILTER:
1081         case INSN_CONFIG_SERIAL_CLOCK:
1082         case INSN_CONFIG_BIDIRECTIONAL_DATA:
1083         case INSN_CONFIG_ALT_SOURCE:
1084         case INSN_CONFIG_SET_COUNTER_MODE:
1085         case INSN_CONFIG_8254_READ_STATUS:
1086         case INSN_CONFIG_SET_ROUTING:
1087         case INSN_CONFIG_GET_ROUTING:
1088         case INSN_CONFIG_GET_PWM_STATUS:
1089         case INSN_CONFIG_PWM_SET_PERIOD:
1090         case INSN_CONFIG_PWM_GET_PERIOD:
1091                 if (insn->n == 2)
1092                         return 0;
1093                 break;
1094         case INSN_CONFIG_SET_GATE_SRC:
1095         case INSN_CONFIG_GET_GATE_SRC:
1096         case INSN_CONFIG_SET_CLOCK_SRC:
1097         case INSN_CONFIG_GET_CLOCK_SRC:
1098         case INSN_CONFIG_SET_OTHER_SRC:
1099         case INSN_CONFIG_GET_COUNTER_STATUS:
1100         case INSN_CONFIG_PWM_SET_H_BRIDGE:
1101         case INSN_CONFIG_PWM_GET_H_BRIDGE:
1102         case INSN_CONFIG_GET_HARDWARE_BUFFER_SIZE:
1103                 if (insn->n == 3)
1104                         return 0;
1105                 break;
1106         case INSN_CONFIG_PWM_OUTPUT:
1107         case INSN_CONFIG_ANALOG_TRIG:
1108                 if (insn->n == 5)
1109                         return 0;
1110                 break;
1111         case INSN_CONFIG_DIGITAL_TRIG:
1112                 if (insn->n == 6)
1113                         return 0;
1114                 break;
1115                 /* by default we allow the insn since we don't have checks for
1116                  * all possible cases yet */
1117         default:
1118                 pr_warn("comedi: No check for data length of config insn id %i is implemented.\n",
1119                         data[0]);
1120                 pr_warn("comedi: Add a check to %s in %s.\n",
1121                         __func__, __FILE__);
1122                 pr_warn("comedi: Assuming n=%i is correct.\n", insn->n);
1123                 return 0;
1124         }
1125         return -EINVAL;
1126 }
1127
1128 static int parse_insn(struct comedi_device *dev, struct comedi_insn *insn,
1129                       unsigned int *data, void *file)
1130 {
1131         struct comedi_subdevice *s;
1132         int ret = 0;
1133         int i;
1134
1135         if (insn->insn & INSN_MASK_SPECIAL) {
1136                 /* a non-subdevice instruction */
1137
1138                 switch (insn->insn) {
1139                 case INSN_GTOD:
1140                         {
1141                                 struct timeval tv;
1142
1143                                 if (insn->n != 2) {
1144                                         ret = -EINVAL;
1145                                         break;
1146                                 }
1147
1148                                 do_gettimeofday(&tv);
1149                                 data[0] = tv.tv_sec;
1150                                 data[1] = tv.tv_usec;
1151                                 ret = 2;
1152
1153                                 break;
1154                         }
1155                 case INSN_WAIT:
1156                         if (insn->n != 1 || data[0] >= 100000) {
1157                                 ret = -EINVAL;
1158                                 break;
1159                         }
1160                         udelay(data[0] / 1000);
1161                         ret = 1;
1162                         break;
1163                 case INSN_INTTRIG:
1164                         if (insn->n != 1) {
1165                                 ret = -EINVAL;
1166                                 break;
1167                         }
1168                         if (insn->subdev >= dev->n_subdevices) {
1169                                 DPRINTK("%d not usable subdevice\n",
1170                                         insn->subdev);
1171                                 ret = -EINVAL;
1172                                 break;
1173                         }
1174                         s = &dev->subdevices[insn->subdev];
1175                         if (!s->async) {
1176                                 DPRINTK("no async\n");
1177                                 ret = -EINVAL;
1178                                 break;
1179                         }
1180                         if (!s->async->inttrig) {
1181                                 DPRINTK("no inttrig\n");
1182                                 ret = -EAGAIN;
1183                                 break;
1184                         }
1185                         ret = s->async->inttrig(dev, s, data[0]);
1186                         if (ret >= 0)
1187                                 ret = 1;
1188                         break;
1189                 default:
1190                         DPRINTK("invalid insn\n");
1191                         ret = -EINVAL;
1192                         break;
1193                 }
1194         } else {
1195                 /* a subdevice instruction */
1196                 unsigned int maxdata;
1197
1198                 if (insn->subdev >= dev->n_subdevices) {
1199                         DPRINTK("subdevice %d out of range\n", insn->subdev);
1200                         ret = -EINVAL;
1201                         goto out;
1202                 }
1203                 s = &dev->subdevices[insn->subdev];
1204
1205                 if (s->type == COMEDI_SUBD_UNUSED) {
1206                         DPRINTK("%d not usable subdevice\n", insn->subdev);
1207                         ret = -EIO;
1208                         goto out;
1209                 }
1210
1211                 /* are we locked? (ioctl lock) */
1212                 if (s->lock && s->lock != file) {
1213                         DPRINTK("device locked\n");
1214                         ret = -EACCES;
1215                         goto out;
1216                 }
1217
1218                 ret = comedi_check_chanlist(s, 1, &insn->chanspec);
1219                 if (ret < 0) {
1220                         ret = -EINVAL;
1221                         DPRINTK("bad chanspec\n");
1222                         goto out;
1223                 }
1224
1225                 if (s->busy) {
1226                         ret = -EBUSY;
1227                         goto out;
1228                 }
1229                 /* This looks arbitrary.  It is. */
1230                 s->busy = &parse_insn;
1231                 switch (insn->insn) {
1232                 case INSN_READ:
1233                         ret = s->insn_read(dev, s, insn, data);
1234                         break;
1235                 case INSN_WRITE:
1236                         maxdata = s->maxdata_list
1237                             ? s->maxdata_list[CR_CHAN(insn->chanspec)]
1238                             : s->maxdata;
1239                         for (i = 0; i < insn->n; ++i) {
1240                                 if (data[i] > maxdata) {
1241                                         ret = -EINVAL;
1242                                         DPRINTK("bad data value(s)\n");
1243                                         break;
1244                                 }
1245                         }
1246                         if (ret == 0)
1247                                 ret = s->insn_write(dev, s, insn, data);
1248                         break;
1249                 case INSN_BITS:
1250                         if (insn->n != 2) {
1251                                 ret = -EINVAL;
1252                         } else {
1253                                 /* Most drivers ignore the base channel in
1254                                  * insn->chanspec.  Fix this here if
1255                                  * the subdevice has <= 32 channels.  */
1256                                 unsigned int shift;
1257                                 unsigned int orig_mask;
1258
1259                                 orig_mask = data[0];
1260                                 if (s->n_chan <= 32) {
1261                                         shift = CR_CHAN(insn->chanspec);
1262                                         if (shift > 0) {
1263                                                 insn->chanspec = 0;
1264                                                 data[0] <<= shift;
1265                                                 data[1] <<= shift;
1266                                         }
1267                                 } else
1268                                         shift = 0;
1269                                 ret = s->insn_bits(dev, s, insn, data);
1270                                 data[0] = orig_mask;
1271                                 if (shift > 0)
1272                                         data[1] >>= shift;
1273                         }
1274                         break;
1275                 case INSN_CONFIG:
1276                         ret = check_insn_config_length(insn, data);
1277                         if (ret)
1278                                 break;
1279                         ret = s->insn_config(dev, s, insn, data);
1280                         break;
1281                 default:
1282                         ret = -EINVAL;
1283                         break;
1284                 }
1285
1286                 s->busy = NULL;
1287         }
1288
1289 out:
1290         return ret;
1291 }
1292
1293 /*
1294  *      COMEDI_INSNLIST
1295  *      synchronous instructions
1296  *
1297  *      arg:
1298  *              pointer to sync cmd structure
1299  *
1300  *      reads:
1301  *              sync cmd struct at arg
1302  *              instruction list
1303  *              data (for writes)
1304  *
1305  *      writes:
1306  *              data (for reads)
1307  */
1308 /* arbitrary limits */
1309 #define MAX_SAMPLES 256
1310 static int do_insnlist_ioctl(struct comedi_device *dev,
1311                              struct comedi_insnlist __user *arg, void *file)
1312 {
1313         struct comedi_insnlist insnlist;
1314         struct comedi_insn *insns = NULL;
1315         unsigned int *data = NULL;
1316         int i = 0;
1317         int ret = 0;
1318
1319         if (copy_from_user(&insnlist, arg, sizeof(insnlist)))
1320                 return -EFAULT;
1321
1322         data = kmalloc(sizeof(unsigned int) * MAX_SAMPLES, GFP_KERNEL);
1323         if (!data) {
1324                 DPRINTK("kmalloc failed\n");
1325                 ret = -ENOMEM;
1326                 goto error;
1327         }
1328
1329         insns = kcalloc(insnlist.n_insns, sizeof(*insns), GFP_KERNEL);
1330         if (!insns) {
1331                 DPRINTK("kmalloc failed\n");
1332                 ret = -ENOMEM;
1333                 goto error;
1334         }
1335
1336         if (copy_from_user(insns, insnlist.insns,
1337                            sizeof(*insns) * insnlist.n_insns)) {
1338                 DPRINTK("copy_from_user failed\n");
1339                 ret = -EFAULT;
1340                 goto error;
1341         }
1342
1343         for (i = 0; i < insnlist.n_insns; i++) {
1344                 if (insns[i].n > MAX_SAMPLES) {
1345                         DPRINTK("number of samples too large\n");
1346                         ret = -EINVAL;
1347                         goto error;
1348                 }
1349                 if (insns[i].insn & INSN_MASK_WRITE) {
1350                         if (copy_from_user(data, insns[i].data,
1351                                            insns[i].n * sizeof(unsigned int))) {
1352                                 DPRINTK("copy_from_user failed\n");
1353                                 ret = -EFAULT;
1354                                 goto error;
1355                         }
1356                 }
1357                 ret = parse_insn(dev, insns + i, data, file);
1358                 if (ret < 0)
1359                         goto error;
1360                 if (insns[i].insn & INSN_MASK_READ) {
1361                         if (copy_to_user(insns[i].data, data,
1362                                          insns[i].n * sizeof(unsigned int))) {
1363                                 DPRINTK("copy_to_user failed\n");
1364                                 ret = -EFAULT;
1365                                 goto error;
1366                         }
1367                 }
1368                 if (need_resched())
1369                         schedule();
1370         }
1371
1372 error:
1373         kfree(insns);
1374         kfree(data);
1375
1376         if (ret < 0)
1377                 return ret;
1378         return i;
1379 }
1380
1381 /*
1382  *      COMEDI_INSN
1383  *      synchronous instructions
1384  *
1385  *      arg:
1386  *              pointer to insn
1387  *
1388  *      reads:
1389  *              struct comedi_insn struct at arg
1390  *              data (for writes)
1391  *
1392  *      writes:
1393  *              data (for reads)
1394  */
1395 static int do_insn_ioctl(struct comedi_device *dev,
1396                          struct comedi_insn __user *arg, void *file)
1397 {
1398         struct comedi_insn insn;
1399         unsigned int *data = NULL;
1400         int ret = 0;
1401
1402         data = kmalloc(sizeof(unsigned int) * MAX_SAMPLES, GFP_KERNEL);
1403         if (!data) {
1404                 ret = -ENOMEM;
1405                 goto error;
1406         }
1407
1408         if (copy_from_user(&insn, arg, sizeof(insn))) {
1409                 ret = -EFAULT;
1410                 goto error;
1411         }
1412
1413         /* This is where the behavior of insn and insnlist deviate. */
1414         if (insn.n > MAX_SAMPLES)
1415                 insn.n = MAX_SAMPLES;
1416         if (insn.insn & INSN_MASK_WRITE) {
1417                 if (copy_from_user(data,
1418                                    insn.data,
1419                                    insn.n * sizeof(unsigned int))) {
1420                         ret = -EFAULT;
1421                         goto error;
1422                 }
1423         }
1424         ret = parse_insn(dev, &insn, data, file);
1425         if (ret < 0)
1426                 goto error;
1427         if (insn.insn & INSN_MASK_READ) {
1428                 if (copy_to_user(insn.data,
1429                                  data,
1430                                  insn.n * sizeof(unsigned int))) {
1431                         ret = -EFAULT;
1432                         goto error;
1433                 }
1434         }
1435         ret = insn.n;
1436
1437 error:
1438         kfree(data);
1439
1440         return ret;
1441 }
1442
1443 static int do_cmd_ioctl(struct comedi_device *dev,
1444                         struct comedi_cmd __user *arg, void *file)
1445 {
1446         struct comedi_cmd cmd;
1447         struct comedi_subdevice *s;
1448         struct comedi_async *async;
1449         int ret = 0;
1450         unsigned int __user *user_chanlist;
1451
1452         if (copy_from_user(&cmd, arg, sizeof(cmd))) {
1453                 DPRINTK("bad cmd address\n");
1454                 return -EFAULT;
1455         }
1456         /* save user's chanlist pointer so it can be restored later */
1457         user_chanlist = (unsigned int __user *)cmd.chanlist;
1458
1459         if (cmd.subdev >= dev->n_subdevices) {
1460                 DPRINTK("%d no such subdevice\n", cmd.subdev);
1461                 return -ENODEV;
1462         }
1463
1464         s = &dev->subdevices[cmd.subdev];
1465         async = s->async;
1466
1467         if (s->type == COMEDI_SUBD_UNUSED) {
1468                 DPRINTK("%d not valid subdevice\n", cmd.subdev);
1469                 return -EIO;
1470         }
1471
1472         if (!s->do_cmd || !s->do_cmdtest || !s->async) {
1473                 DPRINTK("subdevice %i does not support commands\n",
1474                         cmd.subdev);
1475                 return -EIO;
1476         }
1477
1478         /* are we locked? (ioctl lock) */
1479         if (s->lock && s->lock != file) {
1480                 DPRINTK("subdevice locked\n");
1481                 return -EACCES;
1482         }
1483
1484         /* are we busy? */
1485         if (s->busy) {
1486                 DPRINTK("subdevice busy\n");
1487                 return -EBUSY;
1488         }
1489
1490         /* make sure channel/gain list isn't too long */
1491         if (cmd.chanlist_len > s->len_chanlist) {
1492                 DPRINTK("channel/gain list too long %u > %d\n",
1493                         cmd.chanlist_len, s->len_chanlist);
1494                 return -EINVAL;
1495         }
1496
1497         /* make sure channel/gain list isn't too short */
1498         if (cmd.chanlist_len < 1) {
1499                 DPRINTK("channel/gain list too short %u < 1\n",
1500                         cmd.chanlist_len);
1501                 return -EINVAL;
1502         }
1503
1504         async->cmd = cmd;
1505         async->cmd.data = NULL;
1506         /* load channel/gain list */
1507         async->cmd.chanlist = memdup_user(user_chanlist,
1508                                           async->cmd.chanlist_len * sizeof(int));
1509         if (IS_ERR(async->cmd.chanlist)) {
1510                 ret = PTR_ERR(async->cmd.chanlist);
1511                 DPRINTK("memdup_user failed with code %d\n", ret);
1512                 goto cleanup;
1513         }
1514
1515         /* make sure each element in channel/gain list is valid */
1516         ret = comedi_check_chanlist(s,
1517                                     async->cmd.chanlist_len,
1518                                     async->cmd.chanlist);
1519         if (ret < 0) {
1520                 DPRINTK("bad chanlist\n");
1521                 goto cleanup;
1522         }
1523
1524         ret = s->do_cmdtest(dev, s, &async->cmd);
1525
1526         if (async->cmd.flags & TRIG_BOGUS || ret) {
1527                 DPRINTK("test returned %d\n", ret);
1528                 cmd = async->cmd;
1529                 /* restore chanlist pointer before copying back */
1530                 cmd.chanlist = (unsigned int __force *)user_chanlist;
1531                 cmd.data = NULL;
1532                 if (copy_to_user(arg, &cmd, sizeof(cmd))) {
1533                         DPRINTK("fault writing cmd\n");
1534                         ret = -EFAULT;
1535                         goto cleanup;
1536                 }
1537                 ret = -EAGAIN;
1538                 goto cleanup;
1539         }
1540
1541         if (!async->prealloc_bufsz) {
1542                 ret = -ENOMEM;
1543                 DPRINTK("no buffer (?)\n");
1544                 goto cleanup;
1545         }
1546
1547         comedi_buf_reset(async);
1548
1549         async->cb_mask =
1550             COMEDI_CB_EOA | COMEDI_CB_BLOCK | COMEDI_CB_ERROR |
1551             COMEDI_CB_OVERFLOW;
1552         if (async->cmd.flags & TRIG_WAKE_EOS)
1553                 async->cb_mask |= COMEDI_CB_EOS;
1554
1555         comedi_set_subdevice_runflags(s, SRF_ERROR | SRF_RUNNING, SRF_RUNNING);
1556
1557         /* set s->busy _after_ setting SRF_RUNNING flag to avoid race with
1558          * comedi_read() or comedi_write() */
1559         s->busy = file;
1560         ret = s->do_cmd(dev, s);
1561         if (ret == 0)
1562                 return 0;
1563
1564 cleanup:
1565         do_become_nonbusy(dev, s);
1566
1567         return ret;
1568 }
1569
1570 /*
1571         COMEDI_CMDTEST
1572         command testing ioctl
1573
1574         arg:
1575                 pointer to cmd structure
1576
1577         reads:
1578                 cmd structure at arg
1579                 channel/range list
1580
1581         writes:
1582                 modified cmd structure at arg
1583
1584 */
1585 static int do_cmdtest_ioctl(struct comedi_device *dev,
1586                             struct comedi_cmd __user *arg, void *file)
1587 {
1588         struct comedi_cmd cmd;
1589         struct comedi_subdevice *s;
1590         int ret = 0;
1591         unsigned int *chanlist = NULL;
1592         unsigned int __user *user_chanlist;
1593
1594         if (copy_from_user(&cmd, arg, sizeof(cmd))) {
1595                 DPRINTK("bad cmd address\n");
1596                 return -EFAULT;
1597         }
1598         /* save user's chanlist pointer so it can be restored later */
1599         user_chanlist = (unsigned int __user *)cmd.chanlist;
1600
1601         if (cmd.subdev >= dev->n_subdevices) {
1602                 DPRINTK("%d no such subdevice\n", cmd.subdev);
1603                 return -ENODEV;
1604         }
1605
1606         s = &dev->subdevices[cmd.subdev];
1607         if (s->type == COMEDI_SUBD_UNUSED) {
1608                 DPRINTK("%d not valid subdevice\n", cmd.subdev);
1609                 return -EIO;
1610         }
1611
1612         if (!s->do_cmd || !s->do_cmdtest) {
1613                 DPRINTK("subdevice %i does not support commands\n",
1614                         cmd.subdev);
1615                 return -EIO;
1616         }
1617
1618         /* make sure channel/gain list isn't too long */
1619         if (cmd.chanlist_len > s->len_chanlist) {
1620                 DPRINTK("channel/gain list too long %d > %d\n",
1621                         cmd.chanlist_len, s->len_chanlist);
1622                 ret = -EINVAL;
1623                 goto cleanup;
1624         }
1625
1626         /* load channel/gain list */
1627         if (cmd.chanlist) {
1628                 chanlist = memdup_user(user_chanlist,
1629                                        cmd.chanlist_len * sizeof(int));
1630                 if (IS_ERR(chanlist)) {
1631                         ret = PTR_ERR(chanlist);
1632                         DPRINTK("memdup_user exited with code %d", ret);
1633                         goto cleanup;
1634                 }
1635
1636                 /* make sure each element in channel/gain list is valid */
1637                 ret = comedi_check_chanlist(s, cmd.chanlist_len, chanlist);
1638                 if (ret < 0) {
1639                         DPRINTK("bad chanlist\n");
1640                         goto cleanup;
1641                 }
1642
1643                 cmd.chanlist = chanlist;
1644         }
1645
1646         ret = s->do_cmdtest(dev, s, &cmd);
1647
1648         /* restore chanlist pointer before copying back */
1649         cmd.chanlist = (unsigned int __force *)user_chanlist;
1650
1651         if (copy_to_user(arg, &cmd, sizeof(cmd))) {
1652                 DPRINTK("bad cmd address\n");
1653                 ret = -EFAULT;
1654                 goto cleanup;
1655         }
1656 cleanup:
1657         kfree(chanlist);
1658
1659         return ret;
1660 }
1661
1662 /*
1663         COMEDI_LOCK
1664         lock subdevice
1665
1666         arg:
1667                 subdevice number
1668
1669         reads:
1670                 none
1671
1672         writes:
1673                 none
1674
1675 */
1676
1677 static int do_lock_ioctl(struct comedi_device *dev, unsigned int arg,
1678                          void *file)
1679 {
1680         int ret = 0;
1681         unsigned long flags;
1682         struct comedi_subdevice *s;
1683
1684         if (arg >= dev->n_subdevices)
1685                 return -EINVAL;
1686         s = &dev->subdevices[arg];
1687
1688         spin_lock_irqsave(&s->spin_lock, flags);
1689         if (s->busy || s->lock)
1690                 ret = -EBUSY;
1691         else
1692                 s->lock = file;
1693         spin_unlock_irqrestore(&s->spin_lock, flags);
1694
1695 #if 0
1696         if (ret < 0)
1697                 return ret;
1698
1699         if (s->lock_f)
1700                 ret = s->lock_f(dev, s);
1701 #endif
1702
1703         return ret;
1704 }
1705
1706 /*
1707         COMEDI_UNLOCK
1708         unlock subdevice
1709
1710         arg:
1711                 subdevice number
1712
1713         reads:
1714                 none
1715
1716         writes:
1717                 none
1718
1719         This function isn't protected by the semaphore, since
1720         we already own the lock.
1721 */
1722 static int do_unlock_ioctl(struct comedi_device *dev, unsigned int arg,
1723                            void *file)
1724 {
1725         struct comedi_subdevice *s;
1726
1727         if (arg >= dev->n_subdevices)
1728                 return -EINVAL;
1729         s = &dev->subdevices[arg];
1730
1731         if (s->busy)
1732                 return -EBUSY;
1733
1734         if (s->lock && s->lock != file)
1735                 return -EACCES;
1736
1737         if (s->lock == file) {
1738 #if 0
1739                 if (s->unlock)
1740                         s->unlock(dev, s);
1741 #endif
1742
1743                 s->lock = NULL;
1744         }
1745
1746         return 0;
1747 }
1748
1749 /*
1750         COMEDI_CANCEL
1751         cancel acquisition ioctl
1752
1753         arg:
1754                 subdevice number
1755
1756         reads:
1757                 nothing
1758
1759         writes:
1760                 nothing
1761
1762 */
1763 static int do_cancel_ioctl(struct comedi_device *dev, unsigned int arg,
1764                            void *file)
1765 {
1766         struct comedi_subdevice *s;
1767         int ret;
1768
1769         if (arg >= dev->n_subdevices)
1770                 return -EINVAL;
1771         s = &dev->subdevices[arg];
1772         if (s->async == NULL)
1773                 return -EINVAL;
1774
1775         if (s->lock && s->lock != file)
1776                 return -EACCES;
1777
1778         if (!s->busy)
1779                 return 0;
1780
1781         if (s->busy != file)
1782                 return -EBUSY;
1783
1784         ret = do_cancel(dev, s);
1785
1786         return ret;
1787 }
1788
1789 /*
1790         COMEDI_POLL ioctl
1791         instructs driver to synchronize buffers
1792
1793         arg:
1794                 subdevice number
1795
1796         reads:
1797                 nothing
1798
1799         writes:
1800                 nothing
1801
1802 */
1803 static int do_poll_ioctl(struct comedi_device *dev, unsigned int arg,
1804                          void *file)
1805 {
1806         struct comedi_subdevice *s;
1807
1808         if (arg >= dev->n_subdevices)
1809                 return -EINVAL;
1810         s = &dev->subdevices[arg];
1811
1812         if (s->lock && s->lock != file)
1813                 return -EACCES;
1814
1815         if (!s->busy)
1816                 return 0;
1817
1818         if (s->busy != file)
1819                 return -EBUSY;
1820
1821         if (s->poll)
1822                 return s->poll(dev, s);
1823
1824         return -EINVAL;
1825 }
1826
1827 static long comedi_unlocked_ioctl(struct file *file, unsigned int cmd,
1828                                   unsigned long arg)
1829 {
1830         const unsigned minor = iminor(file_inode(file));
1831         struct comedi_device *dev = comedi_dev_from_minor(minor);
1832         int rc;
1833
1834         if (!dev)
1835                 return -ENODEV;
1836
1837         mutex_lock(&dev->mutex);
1838
1839         /* Device config is special, because it must work on
1840          * an unconfigured device. */
1841         if (cmd == COMEDI_DEVCONFIG) {
1842                 if (minor >= COMEDI_NUM_BOARD_MINORS) {
1843                         /* Device config not appropriate on non-board minors. */
1844                         rc = -ENOTTY;
1845                         goto done;
1846                 }
1847                 rc = do_devconfig_ioctl(dev,
1848                                         (struct comedi_devconfig __user *)arg);
1849                 if (rc == 0) {
1850                         if (arg == 0 &&
1851                             dev->minor >= comedi_num_legacy_minors) {
1852                                 /* Successfully unconfigured a dynamically
1853                                  * allocated device.  Try and remove it. */
1854                                 if (comedi_clear_board_dev(dev)) {
1855                                         mutex_unlock(&dev->mutex);
1856                                         comedi_free_board_dev(dev);
1857                                         return rc;
1858                                 }
1859                         }
1860                 }
1861                 goto done;
1862         }
1863
1864         if (!dev->attached) {
1865                 DPRINTK("no driver configured on /dev/comedi%i\n", dev->minor);
1866                 rc = -ENODEV;
1867                 goto done;
1868         }
1869
1870         switch (cmd) {
1871         case COMEDI_BUFCONFIG:
1872                 rc = do_bufconfig_ioctl(dev,
1873                                         (struct comedi_bufconfig __user *)arg);
1874                 break;
1875         case COMEDI_DEVINFO:
1876                 rc = do_devinfo_ioctl(dev, (struct comedi_devinfo __user *)arg,
1877                                       file);
1878                 break;
1879         case COMEDI_SUBDINFO:
1880                 rc = do_subdinfo_ioctl(dev,
1881                                        (struct comedi_subdinfo __user *)arg,
1882                                        file);
1883                 break;
1884         case COMEDI_CHANINFO:
1885                 rc = do_chaninfo_ioctl(dev, (void __user *)arg);
1886                 break;
1887         case COMEDI_RANGEINFO:
1888                 rc = do_rangeinfo_ioctl(dev, (void __user *)arg);
1889                 break;
1890         case COMEDI_BUFINFO:
1891                 rc = do_bufinfo_ioctl(dev,
1892                                       (struct comedi_bufinfo __user *)arg,
1893                                       file);
1894                 break;
1895         case COMEDI_LOCK:
1896                 rc = do_lock_ioctl(dev, arg, file);
1897                 break;
1898         case COMEDI_UNLOCK:
1899                 rc = do_unlock_ioctl(dev, arg, file);
1900                 break;
1901         case COMEDI_CANCEL:
1902                 rc = do_cancel_ioctl(dev, arg, file);
1903                 break;
1904         case COMEDI_CMD:
1905                 rc = do_cmd_ioctl(dev, (struct comedi_cmd __user *)arg, file);
1906                 break;
1907         case COMEDI_CMDTEST:
1908                 rc = do_cmdtest_ioctl(dev, (struct comedi_cmd __user *)arg,
1909                                       file);
1910                 break;
1911         case COMEDI_INSNLIST:
1912                 rc = do_insnlist_ioctl(dev,
1913                                        (struct comedi_insnlist __user *)arg,
1914                                        file);
1915                 break;
1916         case COMEDI_INSN:
1917                 rc = do_insn_ioctl(dev, (struct comedi_insn __user *)arg,
1918                                    file);
1919                 break;
1920         case COMEDI_POLL:
1921                 rc = do_poll_ioctl(dev, arg, file);
1922                 break;
1923         default:
1924                 rc = -ENOTTY;
1925                 break;
1926         }
1927
1928 done:
1929         mutex_unlock(&dev->mutex);
1930         return rc;
1931 }
1932
1933 static void comedi_vm_open(struct vm_area_struct *area)
1934 {
1935         struct comedi_async *async;
1936         struct comedi_device *dev;
1937
1938         async = area->vm_private_data;
1939         dev = async->subdevice->device;
1940
1941         mutex_lock(&dev->mutex);
1942         async->mmap_count++;
1943         mutex_unlock(&dev->mutex);
1944 }
1945
1946 static void comedi_vm_close(struct vm_area_struct *area)
1947 {
1948         struct comedi_async *async;
1949         struct comedi_device *dev;
1950
1951         async = area->vm_private_data;
1952         dev = async->subdevice->device;
1953
1954         mutex_lock(&dev->mutex);
1955         async->mmap_count--;
1956         mutex_unlock(&dev->mutex);
1957 }
1958
1959 static struct vm_operations_struct comedi_vm_ops = {
1960         .open = comedi_vm_open,
1961         .close = comedi_vm_close,
1962 };
1963
1964 static int comedi_mmap(struct file *file, struct vm_area_struct *vma)
1965 {
1966         const unsigned minor = iminor(file_inode(file));
1967         struct comedi_device *dev = comedi_dev_from_minor(minor);
1968         struct comedi_subdevice *s;
1969         struct comedi_async *async;
1970         unsigned long start = vma->vm_start;
1971         unsigned long size;
1972         int n_pages;
1973         int i;
1974         int retval;
1975
1976         if (!dev)
1977                 return -ENODEV;
1978
1979         mutex_lock(&dev->mutex);
1980
1981         if (!dev->attached) {
1982                 DPRINTK("no driver configured on comedi%i\n", dev->minor);
1983                 retval = -ENODEV;
1984                 goto done;
1985         }
1986
1987         if (vma->vm_flags & VM_WRITE)
1988                 s = comedi_write_subdevice(dev, minor);
1989         else
1990                 s = comedi_read_subdevice(dev, minor);
1991         if (!s) {
1992                 retval = -EINVAL;
1993                 goto done;
1994         }
1995
1996         async = s->async;
1997         if (!async) {
1998                 retval = -EINVAL;
1999                 goto done;
2000         }
2001
2002         if (vma->vm_pgoff != 0) {
2003                 DPRINTK("comedi: mmap() offset must be 0.\n");
2004                 retval = -EINVAL;
2005                 goto done;
2006         }
2007
2008         size = vma->vm_end - vma->vm_start;
2009         if (size > async->prealloc_bufsz) {
2010                 retval = -EFAULT;
2011                 goto done;
2012         }
2013         if (size & (~PAGE_MASK)) {
2014                 retval = -EFAULT;
2015                 goto done;
2016         }
2017
2018         n_pages = size >> PAGE_SHIFT;
2019         for (i = 0; i < n_pages; ++i) {
2020                 struct comedi_buf_page *buf = &async->buf_page_list[i];
2021
2022                 if (remap_pfn_range(vma, start,
2023                                     page_to_pfn(virt_to_page(buf->virt_addr)),
2024                                     PAGE_SIZE, PAGE_SHARED)) {
2025                         retval = -EAGAIN;
2026                         goto done;
2027                 }
2028                 start += PAGE_SIZE;
2029         }
2030
2031         vma->vm_ops = &comedi_vm_ops;
2032         vma->vm_private_data = async;
2033
2034         async->mmap_count++;
2035
2036         retval = 0;
2037 done:
2038         mutex_unlock(&dev->mutex);
2039         return retval;
2040 }
2041
2042 static unsigned int comedi_poll(struct file *file, poll_table *wait)
2043 {
2044         unsigned int mask = 0;
2045         const unsigned minor = iminor(file_inode(file));
2046         struct comedi_device *dev = comedi_dev_from_minor(minor);
2047         struct comedi_subdevice *s;
2048
2049         if (!dev)
2050                 return -ENODEV;
2051
2052         mutex_lock(&dev->mutex);
2053
2054         if (!dev->attached) {
2055                 DPRINTK("no driver configured on comedi%i\n", dev->minor);
2056                 goto done;
2057         }
2058
2059         s = comedi_read_subdevice(dev, minor);
2060         if (s && s->async) {
2061                 poll_wait(file, &s->async->wait_head, wait);
2062                 if (!s->busy || !comedi_is_subdevice_running(s) ||
2063                     comedi_buf_read_n_available(s->async) > 0)
2064                         mask |= POLLIN | POLLRDNORM;
2065         }
2066
2067         s = comedi_write_subdevice(dev, minor);
2068         if (s && s->async) {
2069                 unsigned int bps = bytes_per_sample(s->async->subdevice);
2070
2071                 poll_wait(file, &s->async->wait_head, wait);
2072                 comedi_buf_write_alloc(s->async, s->async->prealloc_bufsz);
2073                 if (!s->busy || !comedi_is_subdevice_running(s) ||
2074                     comedi_buf_write_n_allocated(s->async) >= bps)
2075                         mask |= POLLOUT | POLLWRNORM;
2076         }
2077
2078 done:
2079         mutex_unlock(&dev->mutex);
2080         return mask;
2081 }
2082
2083 static ssize_t comedi_write(struct file *file, const char __user *buf,
2084                             size_t nbytes, loff_t *offset)
2085 {
2086         struct comedi_subdevice *s;
2087         struct comedi_async *async;
2088         int n, m, count = 0, retval = 0;
2089         DECLARE_WAITQUEUE(wait, current);
2090         const unsigned minor = iminor(file_inode(file));
2091         struct comedi_device *dev = comedi_dev_from_minor(minor);
2092         bool on_wait_queue = false;
2093         bool attach_locked;
2094         unsigned int old_detach_count;
2095
2096         if (!dev)
2097                 return -ENODEV;
2098
2099         /* Protect against device detachment during operation. */
2100         down_read(&dev->attach_lock);
2101         attach_locked = true;
2102         old_detach_count = dev->detach_count;
2103
2104         if (!dev->attached) {
2105                 DPRINTK("no driver configured on comedi%i\n", dev->minor);
2106                 retval = -ENODEV;
2107                 goto out;
2108         }
2109
2110         s = comedi_write_subdevice(dev, minor);
2111         if (!s || !s->async) {
2112                 retval = -EIO;
2113                 goto out;
2114         }
2115
2116         async = s->async;
2117
2118         if (!s->busy || !nbytes)
2119                 goto out;
2120         if (s->busy != file) {
2121                 retval = -EACCES;
2122                 goto out;
2123         }
2124
2125         add_wait_queue(&async->wait_head, &wait);
2126         on_wait_queue = true;
2127         while (nbytes > 0 && !retval) {
2128                 set_current_state(TASK_INTERRUPTIBLE);
2129
2130                 if (!comedi_is_subdevice_running(s)) {
2131                         if (count == 0) {
2132                                 struct comedi_subdevice *new_s;
2133
2134                                 if (comedi_is_subdevice_in_error(s))
2135                                         retval = -EPIPE;
2136                                 else
2137                                         retval = 0;
2138                                 /*
2139                                  * To avoid deadlock, cannot acquire dev->mutex
2140                                  * while dev->attach_lock is held.  Need to
2141                                  * remove task from the async wait queue before
2142                                  * releasing dev->attach_lock, as it might not
2143                                  * be valid afterwards.
2144                                  */
2145                                 remove_wait_queue(&async->wait_head, &wait);
2146                                 on_wait_queue = false;
2147                                 up_read(&dev->attach_lock);
2148                                 attach_locked = false;
2149                                 mutex_lock(&dev->mutex);
2150                                 /*
2151                                  * Become non-busy unless things have changed
2152                                  * behind our back.  Checking dev->detach_count
2153                                  * is unchanged ought to be sufficient (unless
2154                                  * there have been 2**32 detaches in the
2155                                  * meantime!), but check the subdevice pointer
2156                                  * as well just in case.
2157                                  */
2158                                 new_s = comedi_write_subdevice(dev, minor);
2159                                 if (dev->attached &&
2160                                     old_detach_count == dev->detach_count &&
2161                                     s == new_s && new_s->async == async)
2162                                         do_become_nonbusy(dev, s);
2163                                 mutex_unlock(&dev->mutex);
2164                         }
2165                         break;
2166                 }
2167
2168                 n = nbytes;
2169
2170                 m = n;
2171                 if (async->buf_write_ptr + m > async->prealloc_bufsz)
2172                         m = async->prealloc_bufsz - async->buf_write_ptr;
2173                 comedi_buf_write_alloc(async, async->prealloc_bufsz);
2174                 if (m > comedi_buf_write_n_allocated(async))
2175                         m = comedi_buf_write_n_allocated(async);
2176                 if (m < n)
2177                         n = m;
2178
2179                 if (n == 0) {
2180                         if (file->f_flags & O_NONBLOCK) {
2181                                 retval = -EAGAIN;
2182                                 break;
2183                         }
2184                         schedule();
2185                         if (signal_pending(current)) {
2186                                 retval = -ERESTARTSYS;
2187                                 break;
2188                         }
2189                         if (!s->busy)
2190                                 break;
2191                         if (s->busy != file) {
2192                                 retval = -EACCES;
2193                                 break;
2194                         }
2195                         continue;
2196                 }
2197
2198                 m = copy_from_user(async->prealloc_buf + async->buf_write_ptr,
2199                                    buf, n);
2200                 if (m) {
2201                         n -= m;
2202                         retval = -EFAULT;
2203                 }
2204                 comedi_buf_write_free(async, n);
2205
2206                 count += n;
2207                 nbytes -= n;
2208
2209                 buf += n;
2210                 break;          /* makes device work like a pipe */
2211         }
2212 out:
2213         if (on_wait_queue)
2214                 remove_wait_queue(&async->wait_head, &wait);
2215         set_current_state(TASK_RUNNING);
2216         if (attach_locked)
2217                 up_read(&dev->attach_lock);
2218
2219         return count ? count : retval;
2220 }
2221
2222 static ssize_t comedi_read(struct file *file, char __user *buf, size_t nbytes,
2223                                 loff_t *offset)
2224 {
2225         struct comedi_subdevice *s;
2226         struct comedi_async *async;
2227         int n, m, count = 0, retval = 0;
2228         DECLARE_WAITQUEUE(wait, current);
2229         const unsigned minor = iminor(file_inode(file));
2230         struct comedi_device *dev = comedi_dev_from_minor(minor);
2231         unsigned int old_detach_count;
2232         bool become_nonbusy = false;
2233         bool attach_locked;
2234
2235         if (!dev)
2236                 return -ENODEV;
2237
2238         /* Protect against device detachment during operation. */
2239         down_read(&dev->attach_lock);
2240         attach_locked = true;
2241         old_detach_count = dev->detach_count;
2242
2243         if (!dev->attached) {
2244                 DPRINTK("no driver configured on comedi%i\n", dev->minor);
2245                 retval = -ENODEV;
2246                 goto out;
2247         }
2248
2249         s = comedi_read_subdevice(dev, minor);
2250         if (!s || !s->async) {
2251                 retval = -EIO;
2252                 goto out;
2253         }
2254
2255         async = s->async;
2256         if (!s->busy || !nbytes)
2257                 goto out;
2258         if (s->busy != file) {
2259                 retval = -EACCES;
2260                 goto out;
2261         }
2262
2263         add_wait_queue(&async->wait_head, &wait);
2264         while (nbytes > 0 && !retval) {
2265                 set_current_state(TASK_INTERRUPTIBLE);
2266
2267                 n = nbytes;
2268
2269                 m = comedi_buf_read_n_available(async);
2270                 /* printk("%d available\n",m); */
2271                 if (async->buf_read_ptr + m > async->prealloc_bufsz)
2272                         m = async->prealloc_bufsz - async->buf_read_ptr;
2273                 /* printk("%d contiguous\n",m); */
2274                 if (m < n)
2275                         n = m;
2276
2277                 if (n == 0) {
2278                         if (!comedi_is_subdevice_running(s)) {
2279                                 if (comedi_is_subdevice_in_error(s))
2280                                         retval = -EPIPE;
2281                                 else
2282                                         retval = 0;
2283                                 become_nonbusy = true;
2284                                 break;
2285                         }
2286                         if (file->f_flags & O_NONBLOCK) {
2287                                 retval = -EAGAIN;
2288                                 break;
2289                         }
2290                         schedule();
2291                         if (signal_pending(current)) {
2292                                 retval = -ERESTARTSYS;
2293                                 break;
2294                         }
2295                         if (!s->busy) {
2296                                 retval = 0;
2297                                 break;
2298                         }
2299                         if (s->busy != file) {
2300                                 retval = -EACCES;
2301                                 break;
2302                         }
2303                         continue;
2304                 }
2305                 m = copy_to_user(buf, async->prealloc_buf +
2306                                  async->buf_read_ptr, n);
2307                 if (m) {
2308                         n -= m;
2309                         retval = -EFAULT;
2310                 }
2311
2312                 comedi_buf_read_alloc(async, n);
2313                 comedi_buf_read_free(async, n);
2314
2315                 count += n;
2316                 nbytes -= n;
2317
2318                 buf += n;
2319                 break;          /* makes device work like a pipe */
2320         }
2321         remove_wait_queue(&async->wait_head, &wait);
2322         set_current_state(TASK_RUNNING);
2323         if (become_nonbusy || comedi_is_subdevice_idle(s)) {
2324                 struct comedi_subdevice *new_s;
2325
2326                 /*
2327                  * To avoid deadlock, cannot acquire dev->mutex
2328                  * while dev->attach_lock is held.
2329                  */
2330                 up_read(&dev->attach_lock);
2331                 attach_locked = false;
2332                 mutex_lock(&dev->mutex);
2333                 /*
2334                  * Check device hasn't become detached behind our back.
2335                  * Checking dev->detach_count is unchanged ought to be
2336                  * sufficient (unless there have been 2**32 detaches in the
2337                  * meantime!), but check the subdevice pointer as well just in
2338                  * case.
2339                  */
2340                 new_s = comedi_read_subdevice(dev, minor);
2341                 if (dev->attached && old_detach_count == dev->detach_count &&
2342                     s == new_s && new_s->async == async) {
2343                         if (become_nonbusy ||
2344                             async->buf_read_count - async->buf_write_count == 0)
2345                                 do_become_nonbusy(dev, s);
2346                 }
2347                 mutex_unlock(&dev->mutex);
2348         }
2349 out:
2350         if (attach_locked)
2351                 up_read(&dev->attach_lock);
2352
2353         return count ? count : retval;
2354 }
2355
2356 static int comedi_open(struct inode *inode, struct file *file)
2357 {
2358         const unsigned minor = iminor(inode);
2359         struct comedi_device *dev = comedi_dev_get_from_minor(minor);
2360         int rc;
2361
2362         if (!dev) {
2363                 DPRINTK("invalid minor number\n");
2364                 return -ENODEV;
2365         }
2366
2367         /* This is slightly hacky, but we want module autoloading
2368          * to work for root.
2369          * case: user opens device, attached -> ok
2370          * case: user opens device, unattached, !in_request_module -> autoload
2371          * case: user opens device, unattached, in_request_module -> fail
2372          * case: root opens device, attached -> ok
2373          * case: root opens device, unattached, in_request_module -> ok
2374          *   (typically called from modprobe)
2375          * case: root opens device, unattached, !in_request_module -> autoload
2376          *
2377          * The last could be changed to "-> ok", which would deny root
2378          * autoloading.
2379          */
2380         mutex_lock(&dev->mutex);
2381         if (dev->attached)
2382                 goto ok;
2383         if (!capable(CAP_NET_ADMIN) && dev->in_request_module) {
2384                 DPRINTK("in request module\n");
2385                 rc = -ENODEV;
2386                 goto out;
2387         }
2388         if (capable(CAP_NET_ADMIN) && dev->in_request_module)
2389                 goto ok;
2390
2391         dev->in_request_module = true;
2392
2393 #ifdef CONFIG_KMOD
2394         mutex_unlock(&dev->mutex);
2395         request_module("char-major-%i-%i", COMEDI_MAJOR, dev->minor);
2396         mutex_lock(&dev->mutex);
2397 #endif
2398
2399         dev->in_request_module = false;
2400
2401         if (!dev->attached && !capable(CAP_NET_ADMIN)) {
2402                 DPRINTK("not attached and not CAP_NET_ADMIN\n");
2403                 rc = -ENODEV;
2404                 goto out;
2405         }
2406 ok:
2407         __module_get(THIS_MODULE);
2408
2409         if (dev->attached) {
2410                 if (!try_module_get(dev->driver->module)) {
2411                         module_put(THIS_MODULE);
2412                         rc = -ENOSYS;
2413                         goto out;
2414                 }
2415         }
2416
2417         if (dev->attached && dev->use_count == 0 && dev->open) {
2418                 rc = dev->open(dev);
2419                 if (rc < 0) {
2420                         module_put(dev->driver->module);
2421                         module_put(THIS_MODULE);
2422                         goto out;
2423                 }
2424         }
2425
2426         dev->use_count++;
2427         rc = 0;
2428
2429 out:
2430         mutex_unlock(&dev->mutex);
2431         if (rc)
2432                 comedi_dev_put(dev);
2433         return rc;
2434 }
2435
2436 static int comedi_fasync(int fd, struct file *file, int on)
2437 {
2438         const unsigned minor = iminor(file_inode(file));
2439         struct comedi_device *dev = comedi_dev_from_minor(minor);
2440
2441         if (!dev)
2442                 return -ENODEV;
2443
2444         return fasync_helper(fd, file, on, &dev->async_queue);
2445 }
2446
2447 static int comedi_close(struct inode *inode, struct file *file)
2448 {
2449         const unsigned minor = iminor(inode);
2450         struct comedi_device *dev = comedi_dev_from_minor(minor);
2451         struct comedi_subdevice *s = NULL;
2452         int i;
2453
2454         if (!dev)
2455                 return -ENODEV;
2456
2457         mutex_lock(&dev->mutex);
2458
2459         if (dev->subdevices) {
2460                 for (i = 0; i < dev->n_subdevices; i++) {
2461                         s = &dev->subdevices[i];
2462
2463                         if (s->busy == file)
2464                                 do_cancel(dev, s);
2465                         if (s->lock == file)
2466                                 s->lock = NULL;
2467                 }
2468         }
2469         if (dev->attached && dev->use_count == 1 && dev->close)
2470                 dev->close(dev);
2471
2472         module_put(THIS_MODULE);
2473         if (dev->attached)
2474                 module_put(dev->driver->module);
2475
2476         dev->use_count--;
2477
2478         mutex_unlock(&dev->mutex);
2479         comedi_dev_put(dev);
2480
2481         return 0;
2482 }
2483
2484 static const struct file_operations comedi_fops = {
2485         .owner = THIS_MODULE,
2486         .unlocked_ioctl = comedi_unlocked_ioctl,
2487         .compat_ioctl = comedi_compat_ioctl,
2488         .open = comedi_open,
2489         .release = comedi_close,
2490         .read = comedi_read,
2491         .write = comedi_write,
2492         .mmap = comedi_mmap,
2493         .poll = comedi_poll,
2494         .fasync = comedi_fasync,
2495         .llseek = noop_llseek,
2496 };
2497
2498 void comedi_error(const struct comedi_device *dev, const char *s)
2499 {
2500         dev_err(dev->class_dev, "%s: %s\n", dev->driver->driver_name, s);
2501 }
2502 EXPORT_SYMBOL_GPL(comedi_error);
2503
2504 void comedi_event(struct comedi_device *dev, struct comedi_subdevice *s)
2505 {
2506         struct comedi_async *async = s->async;
2507         unsigned runflags = 0;
2508         unsigned runflags_mask = 0;
2509
2510         /* DPRINTK("comedi_event 0x%x\n",mask); */
2511
2512         if (!comedi_is_subdevice_running(s))
2513                 return;
2514
2515         if (s->
2516             async->events & (COMEDI_CB_EOA | COMEDI_CB_ERROR |
2517                              COMEDI_CB_OVERFLOW)) {
2518                 runflags_mask |= SRF_RUNNING;
2519         }
2520         /* remember if an error event has occurred, so an error
2521          * can be returned the next time the user does a read() */
2522         if (s->async->events & (COMEDI_CB_ERROR | COMEDI_CB_OVERFLOW)) {
2523                 runflags_mask |= SRF_ERROR;
2524                 runflags |= SRF_ERROR;
2525         }
2526         if (runflags_mask) {
2527                 /*sets SRF_ERROR and SRF_RUNNING together atomically */
2528                 comedi_set_subdevice_runflags(s, runflags_mask, runflags);
2529         }
2530
2531         if (async->cb_mask & s->async->events) {
2532                 wake_up_interruptible(&async->wait_head);
2533                 if (s->subdev_flags & SDF_CMD_READ)
2534                         kill_fasync(&dev->async_queue, SIGIO, POLL_IN);
2535                 if (s->subdev_flags & SDF_CMD_WRITE)
2536                         kill_fasync(&dev->async_queue, SIGIO, POLL_OUT);
2537         }
2538         s->async->events = 0;
2539 }
2540 EXPORT_SYMBOL_GPL(comedi_event);
2541
2542 /* Note: the ->mutex is pre-locked on successful return */
2543 struct comedi_device *comedi_alloc_board_minor(struct device *hardware_device)
2544 {
2545         struct comedi_device *dev;
2546         struct device *csdev;
2547         unsigned i;
2548
2549         dev = kzalloc(sizeof(struct comedi_device), GFP_KERNEL);
2550         if (dev == NULL)
2551                 return ERR_PTR(-ENOMEM);
2552         comedi_device_init(dev);
2553         comedi_set_hw_dev(dev, hardware_device);
2554         mutex_lock(&dev->mutex);
2555         mutex_lock(&comedi_board_minor_table_lock);
2556         for (i = hardware_device ? comedi_num_legacy_minors : 0;
2557              i < COMEDI_NUM_BOARD_MINORS; ++i) {
2558                 if (comedi_board_minor_table[i] == NULL) {
2559                         comedi_board_minor_table[i] = dev;
2560                         break;
2561                 }
2562         }
2563         mutex_unlock(&comedi_board_minor_table_lock);
2564         if (i == COMEDI_NUM_BOARD_MINORS) {
2565                 mutex_unlock(&dev->mutex);
2566                 comedi_device_cleanup(dev);
2567                 comedi_dev_put(dev);
2568                 pr_err("comedi: error: ran out of minor numbers for board device files.\n");
2569                 return ERR_PTR(-EBUSY);
2570         }
2571         dev->minor = i;
2572         csdev = device_create(comedi_class, hardware_device,
2573                               MKDEV(COMEDI_MAJOR, i), NULL, "comedi%i", i);
2574         if (!IS_ERR(csdev))
2575                 dev->class_dev = csdev;
2576
2577         /* Note: dev->mutex needs to be unlocked by the caller. */
2578         return dev;
2579 }
2580
2581 static void comedi_free_board_minor(unsigned minor)
2582 {
2583         BUG_ON(minor >= COMEDI_NUM_BOARD_MINORS);
2584         comedi_free_board_dev(comedi_clear_board_minor(minor));
2585 }
2586
2587 void comedi_release_hardware_device(struct device *hardware_device)
2588 {
2589         int minor;
2590         struct comedi_device *dev;
2591
2592         for (minor = comedi_num_legacy_minors; minor < COMEDI_NUM_BOARD_MINORS;
2593              minor++) {
2594                 mutex_lock(&comedi_board_minor_table_lock);
2595                 dev = comedi_board_minor_table[minor];
2596                 if (dev && dev->hw_dev == hardware_device) {
2597                         comedi_board_minor_table[minor] = NULL;
2598                         mutex_unlock(&comedi_board_minor_table_lock);
2599                         comedi_free_board_dev(dev);
2600                         break;
2601                 }
2602                 mutex_unlock(&comedi_board_minor_table_lock);
2603         }
2604 }
2605
2606 int comedi_alloc_subdevice_minor(struct comedi_subdevice *s)
2607 {
2608         struct comedi_device *dev = s->device;
2609         struct device *csdev;
2610         unsigned i;
2611
2612         mutex_lock(&comedi_subdevice_minor_table_lock);
2613         for (i = 0; i < COMEDI_NUM_SUBDEVICE_MINORS; ++i) {
2614                 if (comedi_subdevice_minor_table[i] == NULL) {
2615                         comedi_subdevice_minor_table[i] = s;
2616                         break;
2617                 }
2618         }
2619         mutex_unlock(&comedi_subdevice_minor_table_lock);
2620         if (i == COMEDI_NUM_SUBDEVICE_MINORS) {
2621                 pr_err("comedi: error: ran out of minor numbers for subdevice files.\n");
2622                 return -EBUSY;
2623         }
2624         i += COMEDI_NUM_BOARD_MINORS;
2625         s->minor = i;
2626         csdev = device_create(comedi_class, dev->class_dev,
2627                               MKDEV(COMEDI_MAJOR, i), NULL, "comedi%i_subd%i",
2628                               dev->minor, s->index);
2629         if (!IS_ERR(csdev))
2630                 s->class_dev = csdev;
2631
2632         return 0;
2633 }
2634
2635 void comedi_free_subdevice_minor(struct comedi_subdevice *s)
2636 {
2637         unsigned int i;
2638
2639         if (s == NULL)
2640                 return;
2641         if (s->minor < 0)
2642                 return;
2643
2644         BUG_ON(s->minor >= COMEDI_NUM_MINORS);
2645         BUG_ON(s->minor < COMEDI_NUM_BOARD_MINORS);
2646
2647         i = s->minor - COMEDI_NUM_BOARD_MINORS;
2648         mutex_lock(&comedi_subdevice_minor_table_lock);
2649         if (s == comedi_subdevice_minor_table[i])
2650                 comedi_subdevice_minor_table[i] = NULL;
2651         mutex_unlock(&comedi_subdevice_minor_table_lock);
2652         if (s->class_dev) {
2653                 device_destroy(comedi_class, MKDEV(COMEDI_MAJOR, s->minor));
2654                 s->class_dev = NULL;
2655         }
2656 }
2657
2658 static void comedi_cleanup_board_minors(void)
2659 {
2660         unsigned i;
2661
2662         for (i = 0; i < COMEDI_NUM_BOARD_MINORS; i++)
2663                 comedi_free_board_minor(i);
2664 }
2665
2666 static int __init comedi_init(void)
2667 {
2668         int i;
2669         int retval;
2670
2671         pr_info("comedi: version " COMEDI_RELEASE " - http://www.comedi.org\n");
2672
2673         if (comedi_num_legacy_minors < 0 ||
2674             comedi_num_legacy_minors > COMEDI_NUM_BOARD_MINORS) {
2675                 pr_err("comedi: error: invalid value for module parameter \"comedi_num_legacy_minors\".  Valid values are 0 through %i.\n",
2676                        COMEDI_NUM_BOARD_MINORS);
2677                 return -EINVAL;
2678         }
2679
2680         retval = register_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
2681                                         COMEDI_NUM_MINORS, "comedi");
2682         if (retval)
2683                 return -EIO;
2684         cdev_init(&comedi_cdev, &comedi_fops);
2685         comedi_cdev.owner = THIS_MODULE;
2686         kobject_set_name(&comedi_cdev.kobj, "comedi");
2687         if (cdev_add(&comedi_cdev, MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS)) {
2688                 unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
2689                                          COMEDI_NUM_MINORS);
2690                 return -EIO;
2691         }
2692         comedi_class = class_create(THIS_MODULE, "comedi");
2693         if (IS_ERR(comedi_class)) {
2694                 pr_err("comedi: failed to create class\n");
2695                 cdev_del(&comedi_cdev);
2696                 unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
2697                                          COMEDI_NUM_MINORS);
2698                 return PTR_ERR(comedi_class);
2699         }
2700
2701         comedi_class->dev_groups = comedi_dev_groups;
2702
2703         /* XXX requires /proc interface */
2704         comedi_proc_init();
2705
2706         /* create devices files for legacy/manual use */
2707         for (i = 0; i < comedi_num_legacy_minors; i++) {
2708                 struct comedi_device *dev;
2709                 dev = comedi_alloc_board_minor(NULL);
2710                 if (IS_ERR(dev)) {
2711                         comedi_cleanup_board_minors();
2712                         cdev_del(&comedi_cdev);
2713                         unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0),
2714                                                  COMEDI_NUM_MINORS);
2715                         return PTR_ERR(dev);
2716                 } else {
2717                         /* comedi_alloc_board_minor() locked the mutex */
2718                         mutex_unlock(&dev->mutex);
2719                 }
2720         }
2721
2722         return 0;
2723 }
2724 module_init(comedi_init);
2725
2726 static void __exit comedi_cleanup(void)
2727 {
2728         int i;
2729
2730         comedi_cleanup_board_minors();
2731         for (i = 0; i < COMEDI_NUM_BOARD_MINORS; ++i)
2732                 BUG_ON(comedi_board_minor_table[i]);
2733         for (i = 0; i < COMEDI_NUM_SUBDEVICE_MINORS; ++i)
2734                 BUG_ON(comedi_subdevice_minor_table[i]);
2735
2736         class_destroy(comedi_class);
2737         cdev_del(&comedi_cdev);
2738         unregister_chrdev_region(MKDEV(COMEDI_MAJOR, 0), COMEDI_NUM_MINORS);
2739
2740         comedi_proc_cleanup();
2741 }
2742 module_exit(comedi_cleanup);
2743
2744 MODULE_AUTHOR("http://www.comedi.org");
2745 MODULE_DESCRIPTION("Comedi core module");
2746 MODULE_LICENSE("GPL");