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