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