GNU Linux-libre 4.9.326-gnu1
[releases.git] / drivers / staging / comedi / drivers.c
1 /*
2  *  module/drivers.c
3  *  functions for manipulating drivers
4  *
5  *  COMEDI - Linux Control and Measurement Device Interface
6  *  Copyright (C) 1997-2000 David A. Schleef <ds@schleef.org>
7  *  Copyright (C) 2002 Frank Mori Hess <fmhess@users.sourceforge.net>
8  *
9  *  This program is free software; you can redistribute it and/or modify
10  *  it under the terms of the GNU General Public License as published by
11  *  the Free Software Foundation; either version 2 of the License, or
12  *  (at your option) any later version.
13  *
14  *  This program is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  *  GNU General Public License for more details.
18  */
19
20 #include <linux/device.h>
21 #include <linux/module.h>
22 #include <linux/errno.h>
23 #include <linux/kernel.h>
24 #include <linux/ioport.h>
25 #include <linux/slab.h>
26 #include <linux/dma-direction.h>
27 #include <linux/interrupt.h>
28 #include <linux/firmware.h>
29
30 #include "comedidev.h"
31 #include "comedi_internal.h"
32
33 struct comedi_driver *comedi_drivers;
34 /* protects access to comedi_drivers */
35 DEFINE_MUTEX(comedi_drivers_list_lock);
36
37 /**
38  * comedi_set_hw_dev() - Set hardware device associated with COMEDI device
39  * @dev: COMEDI device.
40  * @hw_dev: Hardware device.
41  *
42  * For automatically configured COMEDI devices (resulting from a call to
43  * comedi_auto_config() or one of its wrappers from the low-level COMEDI
44  * driver), comedi_set_hw_dev() is called automatically by the COMEDI core
45  * to associate the COMEDI device with the hardware device.  It can also be
46  * called directly by "legacy" low-level COMEDI drivers that rely on the
47  * %COMEDI_DEVCONFIG ioctl to configure the hardware as long as the hardware
48  * has a &struct device.
49  *
50  * If @dev->hw_dev is NULL, it gets a reference to @hw_dev and sets
51  * @dev->hw_dev, otherwise, it does nothing.  Calling it multiple times
52  * with the same hardware device is not considered an error.  If it gets
53  * a reference to the hardware device, it will be automatically 'put' when
54  * the device is detached from COMEDI.
55  *
56  * Returns 0 if @dev->hw_dev was NULL or the same as @hw_dev, otherwise
57  * returns -EEXIST.
58  */
59 int comedi_set_hw_dev(struct comedi_device *dev, struct device *hw_dev)
60 {
61         if (hw_dev == dev->hw_dev)
62                 return 0;
63         if (dev->hw_dev)
64                 return -EEXIST;
65         dev->hw_dev = get_device(hw_dev);
66         return 0;
67 }
68 EXPORT_SYMBOL_GPL(comedi_set_hw_dev);
69
70 static void comedi_clear_hw_dev(struct comedi_device *dev)
71 {
72         put_device(dev->hw_dev);
73         dev->hw_dev = NULL;
74 }
75
76 /**
77  * comedi_alloc_devpriv() - Allocate memory for the device private data
78  * @dev: COMEDI device.
79  * @size: Size of the memory to allocate.
80  *
81  * The allocated memory is zero-filled.  @dev->private points to it on
82  * return.  The memory will be automatically freed when the COMEDI device is
83  * "detached".
84  *
85  * Returns a pointer to the allocated memory, or NULL on failure.
86  */
87 void *comedi_alloc_devpriv(struct comedi_device *dev, size_t size)
88 {
89         dev->private = kzalloc(size, GFP_KERNEL);
90         return dev->private;
91 }
92 EXPORT_SYMBOL_GPL(comedi_alloc_devpriv);
93
94 /**
95  * comedi_alloc_subdevices() - Allocate subdevices for COMEDI device
96  * @dev: COMEDI device.
97  * @num_subdevices: Number of subdevices to allocate.
98  *
99  * Allocates and initializes an array of &struct comedi_subdevice for the
100  * COMEDI device.  If successful, sets @dev->subdevices to point to the
101  * first one and @dev->n_subdevices to the number.
102  *
103  * Returns 0 on success, -EINVAL if @num_subdevices is < 1, or -ENOMEM if
104  * failed to allocate the memory.
105  */
106 int comedi_alloc_subdevices(struct comedi_device *dev, int num_subdevices)
107 {
108         struct comedi_subdevice *s;
109         int i;
110
111         if (num_subdevices < 1)
112                 return -EINVAL;
113
114         s = kcalloc(num_subdevices, sizeof(*s), GFP_KERNEL);
115         if (!s)
116                 return -ENOMEM;
117         dev->subdevices = s;
118         dev->n_subdevices = num_subdevices;
119
120         for (i = 0; i < num_subdevices; ++i) {
121                 s = &dev->subdevices[i];
122                 s->device = dev;
123                 s->index = i;
124                 s->async_dma_dir = DMA_NONE;
125                 spin_lock_init(&s->spin_lock);
126                 s->minor = -1;
127         }
128         return 0;
129 }
130 EXPORT_SYMBOL_GPL(comedi_alloc_subdevices);
131
132 /**
133  * comedi_alloc_subdev_readback() - Allocate memory for the subdevice readback
134  * @s: COMEDI subdevice.
135  *
136  * This is called by low-level COMEDI drivers to allocate an array to record
137  * the last values written to a subdevice's analog output channels (at least
138  * by the %INSN_WRITE instruction), to allow them to be read back by an
139  * %INSN_READ instruction.  It also provides a default handler for the
140  * %INSN_READ instruction unless one has already been set.
141  *
142  * On success, @s->readback points to the first element of the array, which
143  * is zero-filled.  The low-level driver is responsible for updating its
144  * contents.  @s->insn_read will be set to comedi_readback_insn_read()
145  * unless it is already non-NULL.
146  *
147  * Returns 0 on success, -EINVAL if the subdevice has no channels, or
148  * -ENOMEM on allocation failure.
149  */
150 int comedi_alloc_subdev_readback(struct comedi_subdevice *s)
151 {
152         if (!s->n_chan)
153                 return -EINVAL;
154
155         s->readback = kcalloc(s->n_chan, sizeof(*s->readback), GFP_KERNEL);
156         if (!s->readback)
157                 return -ENOMEM;
158
159         if (!s->insn_read)
160                 s->insn_read = comedi_readback_insn_read;
161
162         return 0;
163 }
164 EXPORT_SYMBOL_GPL(comedi_alloc_subdev_readback);
165
166 static void comedi_device_detach_cleanup(struct comedi_device *dev)
167 {
168         int i;
169         struct comedi_subdevice *s;
170
171         if (dev->subdevices) {
172                 for (i = 0; i < dev->n_subdevices; i++) {
173                         s = &dev->subdevices[i];
174                         if (comedi_can_auto_free_spriv(s))
175                                 kfree(s->private);
176                         comedi_free_subdevice_minor(s);
177                         if (s->async) {
178                                 comedi_buf_alloc(dev, s, 0);
179                                 kfree(s->async);
180                         }
181                         kfree(s->readback);
182                 }
183                 kfree(dev->subdevices);
184                 dev->subdevices = NULL;
185                 dev->n_subdevices = 0;
186         }
187         kfree(dev->private);
188         kfree(dev->pacer);
189         dev->private = NULL;
190         dev->pacer = NULL;
191         dev->driver = NULL;
192         dev->board_name = NULL;
193         dev->board_ptr = NULL;
194         dev->mmio = NULL;
195         dev->iobase = 0;
196         dev->iolen = 0;
197         dev->ioenabled = false;
198         dev->irq = 0;
199         dev->read_subdev = NULL;
200         dev->write_subdev = NULL;
201         dev->open = NULL;
202         dev->close = NULL;
203         comedi_clear_hw_dev(dev);
204 }
205
206 void comedi_device_detach(struct comedi_device *dev)
207 {
208         comedi_device_cancel_all(dev);
209         down_write(&dev->attach_lock);
210         dev->attached = false;
211         dev->detach_count++;
212         if (dev->driver)
213                 dev->driver->detach(dev);
214         comedi_device_detach_cleanup(dev);
215         up_write(&dev->attach_lock);
216 }
217
218 static int poll_invalid(struct comedi_device *dev, struct comedi_subdevice *s)
219 {
220         return -EINVAL;
221 }
222
223 int insn_inval(struct comedi_device *dev, struct comedi_subdevice *s,
224                struct comedi_insn *insn, unsigned int *data)
225 {
226         return -EINVAL;
227 }
228
229 /**
230  * comedi_readback_insn_read() - A generic (*insn_read) for subdevice readback.
231  * @dev: COMEDI device.
232  * @s: COMEDI subdevice.
233  * @insn: COMEDI instruction.
234  * @data: Pointer to return the readback data.
235  *
236  * Handles the %INSN_READ instruction for subdevices that use the readback
237  * array allocated by comedi_alloc_subdev_readback().  It may be used
238  * directly as the subdevice's handler (@s->insn_read) or called via a
239  * wrapper.
240  *
241  * @insn->n is normally 1, which will read a single value.  If higher, the
242  * same element of the readback array will be read multiple times.
243  *
244  * Returns @insn->n on success, or -EINVAL if @s->readback is NULL.
245  */
246 int comedi_readback_insn_read(struct comedi_device *dev,
247                               struct comedi_subdevice *s,
248                               struct comedi_insn *insn,
249                               unsigned int *data)
250 {
251         unsigned int chan = CR_CHAN(insn->chanspec);
252         int i;
253
254         if (!s->readback)
255                 return -EINVAL;
256
257         for (i = 0; i < insn->n; i++)
258                 data[i] = s->readback[chan];
259
260         return insn->n;
261 }
262 EXPORT_SYMBOL_GPL(comedi_readback_insn_read);
263
264 /**
265  * comedi_timeout() - Busy-wait for a driver condition to occur
266  * @dev: COMEDI device.
267  * @s: COMEDI subdevice.
268  * @insn: COMEDI instruction.
269  * @cb: Callback to check for the condition.
270  * @context: Private context from the driver.
271  *
272  * Busy-waits for up to a second (%COMEDI_TIMEOUT_MS) for the condition or
273  * some error (other than -EBUSY) to occur.  The parameters @dev, @s, @insn,
274  * and @context are passed to the callback function, which returns -EBUSY to
275  * continue waiting or some other value to stop waiting (generally 0 if the
276  * condition occurred, or some error value).
277  *
278  * Returns -ETIMEDOUT if timed out, otherwise the return value from the
279  * callback function.
280  */
281 int comedi_timeout(struct comedi_device *dev,
282                    struct comedi_subdevice *s,
283                    struct comedi_insn *insn,
284                    int (*cb)(struct comedi_device *dev,
285                              struct comedi_subdevice *s,
286                              struct comedi_insn *insn,
287                              unsigned long context),
288                    unsigned long context)
289 {
290         unsigned long timeout = jiffies + msecs_to_jiffies(COMEDI_TIMEOUT_MS);
291         int ret;
292
293         while (time_before(jiffies, timeout)) {
294                 ret = cb(dev, s, insn, context);
295                 if (ret != -EBUSY)
296                         return ret;     /* success (0) or non EBUSY errno */
297                 cpu_relax();
298         }
299         return -ETIMEDOUT;
300 }
301 EXPORT_SYMBOL_GPL(comedi_timeout);
302
303 /**
304  * comedi_dio_insn_config() - Boilerplate (*insn_config) for DIO subdevices
305  * @dev: COMEDI device.
306  * @s: COMEDI subdevice.
307  * @insn: COMEDI instruction.
308  * @data: Instruction parameters and return data.
309  * @mask: io_bits mask for grouped channels, or 0 for single channel.
310  *
311  * If @mask is 0, it is replaced with a single-bit mask corresponding to the
312  * channel number specified by @insn->chanspec.  Otherwise, @mask
313  * corresponds to a group of channels (which should include the specified
314  * channel) that are always configured together as inputs or outputs.
315  *
316  * Partially handles the %INSN_CONFIG_DIO_INPUT, %INSN_CONFIG_DIO_OUTPUTS,
317  * and %INSN_CONFIG_DIO_QUERY instructions.  The first two update
318  * @s->io_bits to record the directions of the masked channels.  The last
319  * one sets @data[1] to the current direction of the group of channels
320  * (%COMEDI_INPUT) or %COMEDI_OUTPUT) as recorded in @s->io_bits.
321  *
322  * The caller is responsible for updating the DIO direction in the hardware
323  * registers if this function returns 0.
324  *
325  * Returns 0 for a %INSN_CONFIG_DIO_INPUT or %INSN_CONFIG_DIO_OUTPUT
326  * instruction, @insn->n (> 0) for a %INSN_CONFIG_DIO_QUERY instruction, or
327  * -EINVAL for some other instruction.
328  */
329 int comedi_dio_insn_config(struct comedi_device *dev,
330                            struct comedi_subdevice *s,
331                            struct comedi_insn *insn,
332                            unsigned int *data,
333                            unsigned int mask)
334 {
335         unsigned int chan_mask = 1 << CR_CHAN(insn->chanspec);
336
337         if (!mask)
338                 mask = chan_mask;
339
340         switch (data[0]) {
341         case INSN_CONFIG_DIO_INPUT:
342                 s->io_bits &= ~mask;
343                 break;
344
345         case INSN_CONFIG_DIO_OUTPUT:
346                 s->io_bits |= mask;
347                 break;
348
349         case INSN_CONFIG_DIO_QUERY:
350                 data[1] = (s->io_bits & mask) ? COMEDI_OUTPUT : COMEDI_INPUT;
351                 return insn->n;
352
353         default:
354                 return -EINVAL;
355         }
356
357         return 0;
358 }
359 EXPORT_SYMBOL_GPL(comedi_dio_insn_config);
360
361 /**
362  * comedi_dio_update_state() - Update the internal state of DIO subdevices
363  * @s: COMEDI subdevice.
364  * @data: The channel mask and bits to update.
365  *
366  * Updates @s->state which holds the internal state of the outputs for DIO
367  * or DO subdevices (up to 32 channels).  @data[0] contains a bit-mask of
368  * the channels to be updated.  @data[1] contains a bit-mask of those
369  * channels to be set to '1'.  The caller is responsible for updating the
370  * outputs in hardware according to @s->state.  As a minimum, the channels
371  * in the returned bit-mask need to be updated.
372  *
373  * Returns @mask with non-existent channels removed.
374  */
375 unsigned int comedi_dio_update_state(struct comedi_subdevice *s,
376                                      unsigned int *data)
377 {
378         unsigned int chanmask = (s->n_chan < 32) ? ((1 << s->n_chan) - 1)
379                                                  : 0xffffffff;
380         unsigned int mask = data[0] & chanmask;
381         unsigned int bits = data[1];
382
383         if (mask) {
384                 s->state &= ~mask;
385                 s->state |= (bits & mask);
386         }
387
388         return mask;
389 }
390 EXPORT_SYMBOL_GPL(comedi_dio_update_state);
391
392 /**
393  * comedi_bytes_per_scan_cmd() - Get length of asynchronous command "scan" in
394  * bytes
395  * @s: COMEDI subdevice.
396  * @cmd: COMEDI command.
397  *
398  * Determines the overall scan length according to the subdevice type and the
399  * number of channels in the scan for the specified command.
400  *
401  * For digital input, output or input/output subdevices, samples for
402  * multiple channels are assumed to be packed into one or more unsigned
403  * short or unsigned int values according to the subdevice's %SDF_LSAMPL
404  * flag.  For other types of subdevice, samples are assumed to occupy a
405  * whole unsigned short or unsigned int according to the %SDF_LSAMPL flag.
406  *
407  * Returns the overall scan length in bytes.
408  */
409 unsigned int comedi_bytes_per_scan_cmd(struct comedi_subdevice *s,
410                                        struct comedi_cmd *cmd)
411 {
412         unsigned int num_samples;
413         unsigned int bits_per_sample;
414
415         switch (s->type) {
416         case COMEDI_SUBD_DI:
417         case COMEDI_SUBD_DO:
418         case COMEDI_SUBD_DIO:
419                 bits_per_sample = 8 * comedi_bytes_per_sample(s);
420                 num_samples = DIV_ROUND_UP(cmd->scan_end_arg, bits_per_sample);
421                 break;
422         default:
423                 num_samples = cmd->scan_end_arg;
424                 break;
425         }
426         return comedi_samples_to_bytes(s, num_samples);
427 }
428 EXPORT_SYMBOL_GPL(comedi_bytes_per_scan_cmd);
429
430 /**
431  * comedi_bytes_per_scan() - Get length of asynchronous command "scan" in bytes
432  * @s: COMEDI subdevice.
433  *
434  * Determines the overall scan length according to the subdevice type and the
435  * number of channels in the scan for the current command.
436  *
437  * For digital input, output or input/output subdevices, samples for
438  * multiple channels are assumed to be packed into one or more unsigned
439  * short or unsigned int values according to the subdevice's %SDF_LSAMPL
440  * flag.  For other types of subdevice, samples are assumed to occupy a
441  * whole unsigned short or unsigned int according to the %SDF_LSAMPL flag.
442  *
443  * Returns the overall scan length in bytes.
444  */
445 unsigned int comedi_bytes_per_scan(struct comedi_subdevice *s)
446 {
447         struct comedi_cmd *cmd = &s->async->cmd;
448
449         return comedi_bytes_per_scan_cmd(s, cmd);
450 }
451 EXPORT_SYMBOL_GPL(comedi_bytes_per_scan);
452
453 static unsigned int __comedi_nscans_left(struct comedi_subdevice *s,
454                                          unsigned int nscans)
455 {
456         struct comedi_async *async = s->async;
457         struct comedi_cmd *cmd = &async->cmd;
458
459         if (cmd->stop_src == TRIG_COUNT) {
460                 unsigned int scans_left = 0;
461
462                 if (async->scans_done < cmd->stop_arg)
463                         scans_left = cmd->stop_arg - async->scans_done;
464
465                 if (nscans > scans_left)
466                         nscans = scans_left;
467         }
468         return nscans;
469 }
470
471 /**
472  * comedi_nscans_left() - Return the number of scans left in the command
473  * @s: COMEDI subdevice.
474  * @nscans: The expected number of scans or 0 for all available scans.
475  *
476  * If @nscans is 0, it is set to the number of scans available in the
477  * async buffer.
478  *
479  * If the async command has a stop_src of %TRIG_COUNT, the @nscans will be
480  * checked against the number of scans remaining to complete the command.
481  *
482  * The return value will then be either the expected number of scans or the
483  * number of scans remaining to complete the command, whichever is fewer.
484  */
485 unsigned int comedi_nscans_left(struct comedi_subdevice *s,
486                                 unsigned int nscans)
487 {
488         if (nscans == 0) {
489                 unsigned int nbytes = comedi_buf_read_n_available(s);
490
491                 nscans = nbytes / comedi_bytes_per_scan(s);
492         }
493         return __comedi_nscans_left(s, nscans);
494 }
495 EXPORT_SYMBOL_GPL(comedi_nscans_left);
496
497 /**
498  * comedi_nsamples_left() - Return the number of samples left in the command
499  * @s: COMEDI subdevice.
500  * @nsamples: The expected number of samples.
501  *
502  * Returns the number of samples remaining to complete the command, or the
503  * specified expected number of samples (@nsamples), whichever is fewer.
504  */
505 unsigned int comedi_nsamples_left(struct comedi_subdevice *s,
506                                   unsigned int nsamples)
507 {
508         struct comedi_async *async = s->async;
509         struct comedi_cmd *cmd = &async->cmd;
510
511         if (cmd->stop_src == TRIG_COUNT) {
512                 unsigned int scans_left = __comedi_nscans_left(s, cmd->stop_arg);
513                 unsigned int scan_pos =
514                     comedi_bytes_to_samples(s, async->scan_progress);
515                 unsigned long long samples_left = 0;
516
517                 if (scans_left) {
518                         samples_left = ((unsigned long long)scans_left *
519                                         cmd->scan_end_arg) - scan_pos;
520                 }
521
522                 if (samples_left < nsamples)
523                         nsamples = samples_left;
524         }
525         return nsamples;
526 }
527 EXPORT_SYMBOL_GPL(comedi_nsamples_left);
528
529 /**
530  * comedi_inc_scan_progress() - Update scan progress in asynchronous command
531  * @s: COMEDI subdevice.
532  * @num_bytes: Amount of data in bytes to increment scan progress.
533  *
534  * Increments the scan progress by the number of bytes specified by @num_bytes.
535  * If the scan progress reaches or exceeds the scan length in bytes, reduce
536  * it modulo the scan length in bytes and set the "end of scan" asynchronous
537  * event flag (%COMEDI_CB_EOS) to be processed later.
538  */
539 void comedi_inc_scan_progress(struct comedi_subdevice *s,
540                               unsigned int num_bytes)
541 {
542         struct comedi_async *async = s->async;
543         struct comedi_cmd *cmd = &async->cmd;
544         unsigned int scan_length = comedi_bytes_per_scan(s);
545
546         /* track the 'cur_chan' for non-SDF_PACKED subdevices */
547         if (!(s->subdev_flags & SDF_PACKED)) {
548                 async->cur_chan += comedi_bytes_to_samples(s, num_bytes);
549                 async->cur_chan %= cmd->chanlist_len;
550         }
551
552         async->scan_progress += num_bytes;
553         if (async->scan_progress >= scan_length) {
554                 unsigned int nscans = async->scan_progress / scan_length;
555
556                 if (async->scans_done < (UINT_MAX - nscans))
557                         async->scans_done += nscans;
558                 else
559                         async->scans_done = UINT_MAX;
560
561                 async->scan_progress %= scan_length;
562                 async->events |= COMEDI_CB_EOS;
563         }
564 }
565 EXPORT_SYMBOL_GPL(comedi_inc_scan_progress);
566
567 /**
568  * comedi_handle_events() - Handle events and possibly stop acquisition
569  * @dev: COMEDI device.
570  * @s: COMEDI subdevice.
571  *
572  * Handles outstanding asynchronous acquisition event flags associated
573  * with the subdevice.  Call the subdevice's @s->cancel() handler if the
574  * "end of acquisition", "error" or "overflow" event flags are set in order
575  * to stop the acquisition at the driver level.
576  *
577  * Calls comedi_event() to further process the event flags, which may mark
578  * the asynchronous command as no longer running, possibly terminated with
579  * an error, and may wake up tasks.
580  *
581  * Return a bit-mask of the handled events.
582  */
583 unsigned int comedi_handle_events(struct comedi_device *dev,
584                                   struct comedi_subdevice *s)
585 {
586         unsigned int events = s->async->events;
587
588         if (events == 0)
589                 return events;
590
591         if ((events & COMEDI_CB_CANCEL_MASK) && s->cancel)
592                 s->cancel(dev, s);
593
594         comedi_event(dev, s);
595
596         return events;
597 }
598 EXPORT_SYMBOL_GPL(comedi_handle_events);
599
600 static int insn_rw_emulate_bits(struct comedi_device *dev,
601                                 struct comedi_subdevice *s,
602                                 struct comedi_insn *insn,
603                                 unsigned int *data)
604 {
605         struct comedi_insn _insn;
606         unsigned int chan = CR_CHAN(insn->chanspec);
607         unsigned int base_chan = (chan < 32) ? 0 : chan;
608         unsigned int _data[2];
609         int ret;
610
611         memset(_data, 0, sizeof(_data));
612         memset(&_insn, 0, sizeof(_insn));
613         _insn.insn = INSN_BITS;
614         _insn.chanspec = base_chan;
615         _insn.n = 2;
616         _insn.subdev = insn->subdev;
617
618         if (insn->insn == INSN_WRITE) {
619                 if (!(s->subdev_flags & SDF_WRITABLE))
620                         return -EINVAL;
621                 _data[0] = 1 << (chan - base_chan);                 /* mask */
622                 _data[1] = data[0] ? (1 << (chan - base_chan)) : 0; /* bits */
623         }
624
625         ret = s->insn_bits(dev, s, &_insn, _data);
626         if (ret < 0)
627                 return ret;
628
629         if (insn->insn == INSN_READ)
630                 data[0] = (_data[1] >> (chan - base_chan)) & 1;
631
632         return 1;
633 }
634
635 static int __comedi_device_postconfig_async(struct comedi_device *dev,
636                                             struct comedi_subdevice *s)
637 {
638         struct comedi_async *async;
639         unsigned int buf_size;
640         int ret;
641
642         if ((s->subdev_flags & (SDF_CMD_READ | SDF_CMD_WRITE)) == 0) {
643                 dev_warn(dev->class_dev,
644                          "async subdevices must support SDF_CMD_READ or SDF_CMD_WRITE\n");
645                 return -EINVAL;
646         }
647         if (!s->do_cmdtest) {
648                 dev_warn(dev->class_dev,
649                          "async subdevices must have a do_cmdtest() function\n");
650                 return -EINVAL;
651         }
652         if (!s->cancel)
653                 dev_warn(dev->class_dev,
654                          "async subdevices should have a cancel() function\n");
655
656         async = kzalloc(sizeof(*async), GFP_KERNEL);
657         if (!async)
658                 return -ENOMEM;
659
660         init_waitqueue_head(&async->wait_head);
661         s->async = async;
662
663         async->max_bufsize = comedi_default_buf_maxsize_kb * 1024;
664         buf_size = comedi_default_buf_size_kb * 1024;
665         if (buf_size > async->max_bufsize)
666                 buf_size = async->max_bufsize;
667
668         if (comedi_buf_alloc(dev, s, buf_size) < 0) {
669                 dev_warn(dev->class_dev, "Buffer allocation failed\n");
670                 return -ENOMEM;
671         }
672         if (s->buf_change) {
673                 ret = s->buf_change(dev, s);
674                 if (ret < 0)
675                         return ret;
676         }
677
678         comedi_alloc_subdevice_minor(s);
679
680         return 0;
681 }
682
683 static int __comedi_device_postconfig(struct comedi_device *dev)
684 {
685         struct comedi_subdevice *s;
686         int ret;
687         int i;
688
689         for (i = 0; i < dev->n_subdevices; i++) {
690                 s = &dev->subdevices[i];
691
692                 if (s->type == COMEDI_SUBD_UNUSED)
693                         continue;
694
695                 if (s->type == COMEDI_SUBD_DO) {
696                         if (s->n_chan < 32)
697                                 s->io_bits = (1 << s->n_chan) - 1;
698                         else
699                                 s->io_bits = 0xffffffff;
700                 }
701
702                 if (s->len_chanlist == 0)
703                         s->len_chanlist = 1;
704
705                 if (s->do_cmd) {
706                         ret = __comedi_device_postconfig_async(dev, s);
707                         if (ret)
708                                 return ret;
709                 }
710
711                 if (!s->range_table && !s->range_table_list)
712                         s->range_table = &range_unknown;
713
714                 if (!s->insn_read && s->insn_bits)
715                         s->insn_read = insn_rw_emulate_bits;
716                 if (!s->insn_write && s->insn_bits)
717                         s->insn_write = insn_rw_emulate_bits;
718
719                 if (!s->insn_read)
720                         s->insn_read = insn_inval;
721                 if (!s->insn_write)
722                         s->insn_write = insn_inval;
723                 if (!s->insn_bits)
724                         s->insn_bits = insn_inval;
725                 if (!s->insn_config)
726                         s->insn_config = insn_inval;
727
728                 if (!s->poll)
729                         s->poll = poll_invalid;
730         }
731
732         return 0;
733 }
734
735 /* do a little post-config cleanup */
736 static int comedi_device_postconfig(struct comedi_device *dev)
737 {
738         int ret;
739
740         ret = __comedi_device_postconfig(dev);
741         if (ret < 0)
742                 return ret;
743         down_write(&dev->attach_lock);
744         dev->attached = true;
745         up_write(&dev->attach_lock);
746         return 0;
747 }
748
749 /*
750  * Generic recognize function for drivers that register their supported
751  * board names.
752  *
753  * 'driv->board_name' points to a 'const char *' member within the
754  * zeroth element of an array of some private board information
755  * structure, say 'struct foo_board' containing a member 'const char
756  * *board_name' that is initialized to point to a board name string that
757  * is one of the candidates matched against this function's 'name'
758  * parameter.
759  *
760  * 'driv->offset' is the size of the private board information
761  * structure, say 'sizeof(struct foo_board)', and 'driv->num_names' is
762  * the length of the array of private board information structures.
763  *
764  * If one of the board names in the array of private board information
765  * structures matches the name supplied to this function, the function
766  * returns a pointer to the pointer to the board name, otherwise it
767  * returns NULL.  The return value ends up in the 'board_ptr' member of
768  * a 'struct comedi_device' that the low-level comedi driver's
769  * 'attach()' hook can convert to a point to a particular element of its
770  * array of private board information structures by subtracting the
771  * offset of the member that points to the board name.  (No subtraction
772  * is required if the board name pointer is the first member of the
773  * private board information structure, which is generally the case.)
774  */
775 static void *comedi_recognize(struct comedi_driver *driv, const char *name)
776 {
777         char **name_ptr = (char **)driv->board_name;
778         int i;
779
780         for (i = 0; i < driv->num_names; i++) {
781                 if (strcmp(*name_ptr, name) == 0)
782                         return name_ptr;
783                 name_ptr = (void *)name_ptr + driv->offset;
784         }
785
786         return NULL;
787 }
788
789 static void comedi_report_boards(struct comedi_driver *driv)
790 {
791         unsigned int i;
792         const char *const *name_ptr;
793
794         pr_info("comedi: valid board names for %s driver are:\n",
795                 driv->driver_name);
796
797         name_ptr = driv->board_name;
798         for (i = 0; i < driv->num_names; i++) {
799                 pr_info(" %s\n", *name_ptr);
800                 name_ptr = (const char **)((char *)name_ptr + driv->offset);
801         }
802
803         if (driv->num_names == 0)
804                 pr_info(" %s\n", driv->driver_name);
805 }
806
807 /**
808  * comedi_load_firmware() - Request and load firmware for a device
809  * @dev: COMEDI device.
810  * @device: Hardware device.
811  * @name: The name of the firmware image.
812  * @cb: Callback to the upload the firmware image.
813  * @context: Private context from the driver.
814  *
815  * Sends a firmware request for the hardware device and waits for it.  Calls
816  * the callback function to upload the firmware to the device, them releases
817  * the firmware.
818  *
819  * Returns 0 on success, -EINVAL if @cb is NULL, or a negative error number
820  * from the firmware request or the callback function.
821  */
822 int comedi_load_firmware(struct comedi_device *dev,
823                          struct device *device,
824                          const char *name,
825                          int (*cb)(struct comedi_device *dev,
826                                    const u8 *data, size_t size,
827                                    unsigned long context),
828                          unsigned long context)
829 {
830         const struct firmware *fw;
831         int ret;
832
833         if (!cb)
834                 return -EINVAL;
835
836         ret = maybe_reject_firmware(&fw, name, device);
837         if (ret == 0) {
838                 ret = cb(dev, fw->data, fw->size, context);
839                 release_firmware(fw);
840         }
841
842         return ret < 0 ? ret : 0;
843 }
844 EXPORT_SYMBOL_GPL(comedi_load_firmware);
845
846 /**
847  * __comedi_request_region() - Request an I/O region for a legacy driver
848  * @dev: COMEDI device.
849  * @start: Base address of the I/O region.
850  * @len: Length of the I/O region.
851  *
852  * Requests the specified I/O port region which must start at a non-zero
853  * address.
854  *
855  * Returns 0 on success, -EINVAL if @start is 0, or -EIO if the request
856  * fails.
857  */
858 int __comedi_request_region(struct comedi_device *dev,
859                             unsigned long start, unsigned long len)
860 {
861         if (!start) {
862                 dev_warn(dev->class_dev,
863                          "%s: a I/O base address must be specified\n",
864                          dev->board_name);
865                 return -EINVAL;
866         }
867
868         if (!request_region(start, len, dev->board_name)) {
869                 dev_warn(dev->class_dev, "%s: I/O port conflict (%#lx,%lu)\n",
870                          dev->board_name, start, len);
871                 return -EIO;
872         }
873
874         return 0;
875 }
876 EXPORT_SYMBOL_GPL(__comedi_request_region);
877
878 /**
879  * comedi_request_region() - Request an I/O region for a legacy driver
880  * @dev: COMEDI device.
881  * @start: Base address of the I/O region.
882  * @len: Length of the I/O region.
883  *
884  * Requests the specified I/O port region which must start at a non-zero
885  * address.
886  *
887  * On success, @dev->iobase is set to the base address of the region and
888  * @dev->iolen is set to its length.
889  *
890  * Returns 0 on success, -EINVAL if @start is 0, or -EIO if the request
891  * fails.
892  */
893 int comedi_request_region(struct comedi_device *dev,
894                           unsigned long start, unsigned long len)
895 {
896         int ret;
897
898         ret = __comedi_request_region(dev, start, len);
899         if (ret == 0) {
900                 dev->iobase = start;
901                 dev->iolen = len;
902         }
903
904         return ret;
905 }
906 EXPORT_SYMBOL_GPL(comedi_request_region);
907
908 /**
909  * comedi_legacy_detach() - A generic (*detach) function for legacy drivers
910  * @dev: COMEDI device.
911  *
912  * This is a simple, generic 'detach' handler for legacy COMEDI devices that
913  * just use a single I/O port region and possibly an IRQ and that don't need
914  * any special clean-up for their private device or subdevice storage.  It
915  * can also be called by a driver-specific 'detach' handler.
916  *
917  * If @dev->irq is non-zero, the IRQ will be freed.  If @dev->iobase and
918  * @dev->iolen are both non-zero, the I/O port region will be released.
919  */
920 void comedi_legacy_detach(struct comedi_device *dev)
921 {
922         if (dev->irq) {
923                 free_irq(dev->irq, dev);
924                 dev->irq = 0;
925         }
926         if (dev->iobase && dev->iolen) {
927                 release_region(dev->iobase, dev->iolen);
928                 dev->iobase = 0;
929                 dev->iolen = 0;
930         }
931 }
932 EXPORT_SYMBOL_GPL(comedi_legacy_detach);
933
934 int comedi_device_attach(struct comedi_device *dev, struct comedi_devconfig *it)
935 {
936         struct comedi_driver *driv;
937         int ret;
938
939         if (dev->attached)
940                 return -EBUSY;
941
942         mutex_lock(&comedi_drivers_list_lock);
943         for (driv = comedi_drivers; driv; driv = driv->next) {
944                 if (!try_module_get(driv->module))
945                         continue;
946                 if (driv->num_names) {
947                         dev->board_ptr = comedi_recognize(driv, it->board_name);
948                         if (dev->board_ptr)
949                                 break;
950                 } else if (strcmp(driv->driver_name, it->board_name) == 0) {
951                         break;
952                 }
953                 module_put(driv->module);
954         }
955         if (!driv) {
956                 /*  recognize has failed if we get here */
957                 /*  report valid board names before returning error */
958                 for (driv = comedi_drivers; driv; driv = driv->next) {
959                         if (!try_module_get(driv->module))
960                                 continue;
961                         comedi_report_boards(driv);
962                         module_put(driv->module);
963                 }
964                 ret = -EIO;
965                 goto out;
966         }
967         if (!driv->attach) {
968                 /* driver does not support manual configuration */
969                 dev_warn(dev->class_dev,
970                          "driver '%s' does not support attach using comedi_config\n",
971                          driv->driver_name);
972                 module_put(driv->module);
973                 ret = -EIO;
974                 goto out;
975         }
976         dev->driver = driv;
977         dev->board_name = dev->board_ptr ? *(const char **)dev->board_ptr
978                                          : dev->driver->driver_name;
979         ret = driv->attach(dev, it);
980         if (ret >= 0)
981                 ret = comedi_device_postconfig(dev);
982         if (ret < 0) {
983                 comedi_device_detach(dev);
984                 module_put(driv->module);
985         }
986         /* On success, the driver module count has been incremented. */
987 out:
988         mutex_unlock(&comedi_drivers_list_lock);
989         return ret;
990 }
991
992 /**
993  * comedi_auto_config() - Create a COMEDI device for a hardware device
994  * @hardware_device: Hardware device.
995  * @driver: COMEDI low-level driver for the hardware device.
996  * @context: Driver context for the auto_attach handler.
997  *
998  * Allocates a new COMEDI device for the hardware device and calls the
999  * low-level driver's 'auto_attach' handler to set-up the hardware and
1000  * allocate the COMEDI subdevices.  Additional "post-configuration" setting
1001  * up is performed on successful return from the 'auto_attach' handler.
1002  * If the 'auto_attach' handler fails, the low-level driver's 'detach'
1003  * handler will be called as part of the clean-up.
1004  *
1005  * This is usually called from a wrapper function in a bus-specific COMEDI
1006  * module, which in turn is usually called from a bus device 'probe'
1007  * function in the low-level driver.
1008  *
1009  * Returns 0 on success, -EINVAL if the parameters are invalid or the
1010  * post-configuration determines the driver has set the COMEDI device up
1011  * incorrectly, -ENOMEM if failed to allocate memory, -EBUSY if run out of
1012  * COMEDI minor device numbers, or some negative error number returned by
1013  * the driver's 'auto_attach' handler.
1014  */
1015 int comedi_auto_config(struct device *hardware_device,
1016                        struct comedi_driver *driver, unsigned long context)
1017 {
1018         struct comedi_device *dev;
1019         int ret;
1020
1021         if (!hardware_device) {
1022                 pr_warn("BUG! comedi_auto_config called with NULL hardware_device\n");
1023                 return -EINVAL;
1024         }
1025         if (!driver) {
1026                 dev_warn(hardware_device,
1027                          "BUG! comedi_auto_config called with NULL comedi driver\n");
1028                 return -EINVAL;
1029         }
1030
1031         if (!driver->auto_attach) {
1032                 dev_warn(hardware_device,
1033                          "BUG! comedi driver '%s' has no auto_attach handler\n",
1034                          driver->driver_name);
1035                 return -EINVAL;
1036         }
1037
1038         dev = comedi_alloc_board_minor(hardware_device);
1039         if (IS_ERR(dev)) {
1040                 dev_warn(hardware_device,
1041                          "driver '%s' could not create device.\n",
1042                          driver->driver_name);
1043                 return PTR_ERR(dev);
1044         }
1045         /* Note: comedi_alloc_board_minor() locked dev->mutex. */
1046
1047         dev->driver = driver;
1048         dev->board_name = dev->driver->driver_name;
1049         ret = driver->auto_attach(dev, context);
1050         if (ret >= 0)
1051                 ret = comedi_device_postconfig(dev);
1052         mutex_unlock(&dev->mutex);
1053
1054         if (ret < 0) {
1055                 dev_warn(hardware_device,
1056                          "driver '%s' failed to auto-configure device.\n",
1057                          driver->driver_name);
1058                 comedi_release_hardware_device(hardware_device);
1059         } else {
1060                 /*
1061                  * class_dev should be set properly here
1062                  *  after a successful auto config
1063                  */
1064                 dev_info(dev->class_dev,
1065                          "driver '%s' has successfully auto-configured '%s'.\n",
1066                          driver->driver_name, dev->board_name);
1067         }
1068         return ret;
1069 }
1070 EXPORT_SYMBOL_GPL(comedi_auto_config);
1071
1072 /**
1073  * comedi_auto_unconfig() - Unconfigure auto-allocated COMEDI device
1074  * @hardware_device: Hardware device previously passed to
1075  *                   comedi_auto_config().
1076  *
1077  * Cleans up and eventually destroys the COMEDI device allocated by
1078  * comedi_auto_config() for the same hardware device.  As part of this
1079  * clean-up, the low-level COMEDI driver's 'detach' handler will be called.
1080  * (The COMEDI device itself will persist in an unattached state if it is
1081  * still open, until it is released, and any mmapped buffers will persist
1082  * until they are munmapped.)
1083  *
1084  * This is usually called from a wrapper module in a bus-specific COMEDI
1085  * module, which in turn is usually set as the bus device 'remove' function
1086  * in the low-level COMEDI driver.
1087  */
1088 void comedi_auto_unconfig(struct device *hardware_device)
1089 {
1090         if (!hardware_device)
1091                 return;
1092         comedi_release_hardware_device(hardware_device);
1093 }
1094 EXPORT_SYMBOL_GPL(comedi_auto_unconfig);
1095
1096 /**
1097  * comedi_driver_register() - Register a low-level COMEDI driver
1098  * @driver: Low-level COMEDI driver.
1099  *
1100  * The low-level COMEDI driver is added to the list of registered COMEDI
1101  * drivers.  This is used by the handler for the "/proc/comedi" file and is
1102  * also used by the handler for the %COMEDI_DEVCONFIG ioctl to configure
1103  * "legacy" COMEDI devices (for those low-level drivers that support it).
1104  *
1105  * Returns 0.
1106  */
1107 int comedi_driver_register(struct comedi_driver *driver)
1108 {
1109         mutex_lock(&comedi_drivers_list_lock);
1110         driver->next = comedi_drivers;
1111         comedi_drivers = driver;
1112         mutex_unlock(&comedi_drivers_list_lock);
1113
1114         return 0;
1115 }
1116 EXPORT_SYMBOL_GPL(comedi_driver_register);
1117
1118 /**
1119  * comedi_driver_unregister() - Unregister a low-level COMEDI driver
1120  * @driver: Low-level COMEDI driver.
1121  *
1122  * The low-level COMEDI driver is removed from the list of registered COMEDI
1123  * drivers.  Detaches any COMEDI devices attached to the driver, which will
1124  * result in the low-level driver's 'detach' handler being called for those
1125  * devices before this function returns.
1126  */
1127 void comedi_driver_unregister(struct comedi_driver *driver)
1128 {
1129         struct comedi_driver *prev;
1130         int i;
1131
1132         /* unlink the driver */
1133         mutex_lock(&comedi_drivers_list_lock);
1134         if (comedi_drivers == driver) {
1135                 comedi_drivers = driver->next;
1136         } else {
1137                 for (prev = comedi_drivers; prev->next; prev = prev->next) {
1138                         if (prev->next == driver) {
1139                                 prev->next = driver->next;
1140                                 break;
1141                         }
1142                 }
1143         }
1144         mutex_unlock(&comedi_drivers_list_lock);
1145
1146         /* check for devices using this driver */
1147         for (i = 0; i < COMEDI_NUM_BOARD_MINORS; i++) {
1148                 struct comedi_device *dev = comedi_dev_get_from_minor(i);
1149
1150                 if (!dev)
1151                         continue;
1152
1153                 mutex_lock(&dev->mutex);
1154                 if (dev->attached && dev->driver == driver) {
1155                         if (dev->use_count)
1156                                 dev_warn(dev->class_dev,
1157                                          "BUG! detaching device with use_count=%d\n",
1158                                          dev->use_count);
1159                         comedi_device_detach(dev);
1160                 }
1161                 mutex_unlock(&dev->mutex);
1162                 comedi_dev_put(dev);
1163         }
1164 }
1165 EXPORT_SYMBOL_GPL(comedi_driver_unregister);