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