Linux-libre 4.14.2-gnu
[librecmc/linux-libre.git] / drivers / staging / comedi / comedidev.h
1 /*
2  * comedidev.h
3  * header file for kernel-only structures, variables, and constants
4  *
5  * COMEDI - Linux Control and Measurement Device Interface
6  * Copyright (C) 1997-2000 David A. Schleef <ds@schleef.org>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  */
18
19 #ifndef _COMEDIDEV_H
20 #define _COMEDIDEV_H
21
22 #include <linux/dma-mapping.h>
23 #include <linux/mutex.h>
24 #include <linux/spinlock_types.h>
25 #include <linux/rwsem.h>
26 #include <linux/kref.h>
27
28 #include "comedi.h"
29
30 #define COMEDI_VERSION(a, b, c) (((a) << 16) + ((b) << 8) + (c))
31 #define COMEDI_VERSION_CODE COMEDI_VERSION(COMEDI_MAJORVERSION, \
32         COMEDI_MINORVERSION, COMEDI_MICROVERSION)
33 #define COMEDI_RELEASE VERSION
34
35 #define COMEDI_NUM_BOARD_MINORS 0x30
36
37 /**
38  * struct comedi_subdevice - Working data for a COMEDI subdevice
39  * @device: COMEDI device to which this subdevice belongs.  (Initialized by
40  *      comedi_alloc_subdevices().)
41  * @index: Index of this subdevice within device's array of subdevices.
42  *      (Initialized by comedi_alloc_subdevices().)
43  * @type: Type of subdevice from &enum comedi_subdevice_type.  (Initialized by
44  *      the low-level driver.)
45  * @n_chan: Number of channels the subdevice supports.  (Initialized by the
46  *      low-level driver.)
47  * @subdev_flags: Various "SDF" flags indicating aspects of the subdevice to
48  *      the COMEDI core and user application.  (Initialized by the low-level
49  *      driver.)
50  * @len_chanlist: Maximum length of a channel list if the subdevice supports
51  *      asynchronous acquisition commands.  (Optionally initialized by the
52  *      low-level driver, or changed from 0 to 1 during post-configuration.)
53  * @private: Private data pointer which is either set by the low-level driver
54  *      itself, or by a call to comedi_alloc_spriv() which allocates storage.
55  *      In the latter case, the storage is automatically freed after the
56  *      low-level driver's "detach" handler is called for the device.
57  *      (Initialized by the low-level driver.)
58  * @async: Pointer to &struct comedi_async id the subdevice supports
59  *      asynchronous acquisition commands.  (Allocated and initialized during
60  *      post-configuration if needed.)
61  * @lock: Pointer to a file object that performed a %COMEDI_LOCK ioctl on the
62  *      subdevice.  (Initially NULL.)
63  * @busy: Pointer to a file object that is performing an asynchronous
64  *      acquisition command on the subdevice.  (Initially NULL.)
65  * @runflags: Internal flags for use by COMEDI core, mostly indicating whether
66  *      an asynchronous acquisition command is running.
67  * @spin_lock: Generic spin-lock for use by the COMEDI core and the low-level
68  *      driver.  (Initialized by comedi_alloc_subdevices().)
69  * @io_bits: Bit-mask indicating the channel directions for a DIO subdevice
70  *      with no more than 32 channels.  A '1' at a bit position indicates the
71  *      corresponding channel is configured as an output.  (Initialized by the
72  *      low-level driver for a DIO subdevice.  Forced to all-outputs during
73  *      post-configuration for a digital output subdevice.)
74  * @maxdata: If non-zero, this is the maximum raw data value of each channel.
75  *      If zero, the maximum data value is channel-specific.  (Initialized by
76  *      the low-level driver.)
77  * @maxdata_list: If the maximum data value is channel-specific, this points
78  *      to an array of maximum data values indexed by channel index.
79  *      (Initialized by the low-level driver.)
80  * @range_table: If non-NULL, this points to a COMEDI range table for the
81  *      subdevice.  If NULL, the range table is channel-specific.  (Initialized
82  *      by the low-level driver, will be set to an "invalid" range table during
83  *      post-configuration if @range_table and @range_table_list are both
84  *      NULL.)
85  * @range_table_list: If the COMEDI range table is channel-specific, this
86  *      points to an array of pointers to COMEDI range tables indexed by
87  *      channel number.  (Initialized by the low-level driver.)
88  * @chanlist: Not used.
89  * @insn_read: Optional pointer to a handler for the %INSN_READ instruction.
90  *      (Initialized by the low-level driver, or set to a default handler
91  *      during post-configuration.)
92  * @insn_write: Optional pointer to a handler for the %INSN_WRITE instruction.
93  *      (Initialized by the low-level driver, or set to a default handler
94  *      during post-configuration.)
95  * @insn_bits: Optional pointer to a handler for the %INSN_BITS instruction
96  *      for a digital input, digital output or digital input/output subdevice.
97  *      (Initialized by the low-level driver, or set to a default handler
98  *      during post-configuration.)
99  * @insn_config: Optional pointer to a handler for the %INSN_CONFIG
100  *      instruction.  (Initialized by the low-level driver, or set to a default
101  *      handler during post-configuration.)
102  * @do_cmd: If the subdevice supports asynchronous acquisition commands, this
103  *      points to a handler to set it up in hardware.  (Initialized by the
104  *      low-level driver.)
105  * @do_cmdtest: If the subdevice supports asynchronous acquisition commands,
106  *      this points to a handler used to check and possibly tweak a prospective
107  *      acquisition command without setting it up in hardware.  (Initialized by
108  *      the low-level driver.)
109  * @poll: If the subdevice supports asynchronous acquisition commands, this
110  *      is an optional pointer to a handler for the %COMEDI_POLL ioctl which
111  *      instructs the low-level driver to synchronize buffers.  (Initialized by
112  *      the low-level driver if needed.)
113  * @cancel: If the subdevice supports asynchronous acquisition commands, this
114  *      points to a handler used to terminate a running command.  (Initialized
115  *      by the low-level driver.)
116  * @buf_change: If the subdevice supports asynchronous acquisition commands,
117  *      this is an optional pointer to a handler that is called when the data
118  *      buffer for handling asynchronous commands is allocated or reallocated.
119  *      (Initialized by the low-level driver if needed.)
120  * @munge: If the subdevice supports asynchronous acquisition commands and
121  *      uses DMA to transfer data from the hardware to the acquisition buffer,
122  *      this points to a function used to "munge" the data values from the
123  *      hardware into the format expected by COMEDI.  (Initialized by the
124  *      low-level driver if needed.)
125  * @async_dma_dir: If the subdevice supports asynchronous acquisition commands
126  *      and uses DMA to transfer data from the hardware to the acquisition
127  *      buffer, this sets the DMA direction for the buffer. (initialized to
128  *      %DMA_NONE by comedi_alloc_subdevices() and changed by the low-level
129  *      driver if necessary.)
130  * @state: Handy bit-mask indicating the output states for a DIO or digital
131  *      output subdevice with no more than 32 channels. (Initialized by the
132  *      low-level driver.)
133  * @class_dev: If the subdevice supports asynchronous acquisition commands,
134  *      this points to a sysfs comediX_subdY device where X is the minor device
135  *      number of the COMEDI device and Y is the subdevice number.  The minor
136  *      device number for the sysfs device is allocated dynamically in the
137  *      range 48 to 255.  This is used to allow the COMEDI device to be opened
138  *      with a different default read or write subdevice.  (Allocated during
139  *      post-configuration if needed.)
140  * @minor: If @class_dev is set, this is its dynamically allocated minor
141  *      device number.  (Set during post-configuration if necessary.)
142  * @readback: Optional pointer to memory allocated by
143  *      comedi_alloc_subdev_readback() used to hold the values written to
144  *      analog output channels so they can be read back.  The storage is
145  *      automatically freed after the low-level driver's "detach" handler is
146  *      called for the device.  (Initialized by the low-level driver.)
147  *
148  * This is the main control structure for a COMEDI subdevice.  If the subdevice
149  * supports asynchronous acquisition commands, additional information is stored
150  * in the &struct comedi_async pointed to by @async.
151  *
152  * Most of the subdevice is initialized by the low-level driver's "attach" or
153  * "auto_attach" handlers but parts of it are initialized by
154  * comedi_alloc_subdevices(), and other parts are initialized during
155  * post-configuration on return from that handler.
156  *
157  * A low-level driver that sets @insn_bits for a digital input, digital output,
158  * or DIO subdevice may leave @insn_read and @insn_write uninitialized, in
159  * which case they will be set to a default handler during post-configuration
160  * that uses @insn_bits to emulate the %INSN_READ and %INSN_WRITE instructions.
161  */
162 struct comedi_subdevice {
163         struct comedi_device *device;
164         int index;
165         int type;
166         int n_chan;
167         int subdev_flags;
168         int len_chanlist;       /* maximum length of channel/gain list */
169
170         void *private;
171
172         struct comedi_async *async;
173
174         void *lock;
175         void *busy;
176         unsigned int runflags;
177         spinlock_t spin_lock;   /* generic spin-lock for COMEDI and drivers */
178
179         unsigned int io_bits;
180
181         unsigned int maxdata;   /* if maxdata==0, use list */
182         const unsigned int *maxdata_list;       /* list is channel specific */
183
184         const struct comedi_lrange *range_table;
185         const struct comedi_lrange *const *range_table_list;
186
187         unsigned int *chanlist; /* driver-owned chanlist (not used) */
188
189         int (*insn_read)(struct comedi_device *, struct comedi_subdevice *,
190                          struct comedi_insn *, unsigned int *);
191         int (*insn_write)(struct comedi_device *, struct comedi_subdevice *,
192                           struct comedi_insn *, unsigned int *);
193         int (*insn_bits)(struct comedi_device *, struct comedi_subdevice *,
194                          struct comedi_insn *, unsigned int *);
195         int (*insn_config)(struct comedi_device *, struct comedi_subdevice *,
196                            struct comedi_insn *, unsigned int *);
197
198         int (*do_cmd)(struct comedi_device *, struct comedi_subdevice *);
199         int (*do_cmdtest)(struct comedi_device *, struct comedi_subdevice *,
200                           struct comedi_cmd *);
201         int (*poll)(struct comedi_device *, struct comedi_subdevice *);
202         int (*cancel)(struct comedi_device *, struct comedi_subdevice *);
203
204         /* called when the buffer changes */
205         int (*buf_change)(struct comedi_device *, struct comedi_subdevice *);
206
207         void (*munge)(struct comedi_device *dev, struct comedi_subdevice *s,
208                       void *data, unsigned int num_bytes,
209                       unsigned int start_chan_index);
210         enum dma_data_direction async_dma_dir;
211
212         unsigned int state;
213
214         struct device *class_dev;
215         int minor;
216
217         unsigned int *readback;
218 };
219
220 /**
221  * struct comedi_buf_page - Describe a page of a COMEDI buffer
222  * @virt_addr: Kernel address of page.
223  * @dma_addr: DMA address of page if in DMA coherent memory.
224  */
225 struct comedi_buf_page {
226         void *virt_addr;
227         dma_addr_t dma_addr;
228 };
229
230 /**
231  * struct comedi_buf_map - Describe pages in a COMEDI buffer
232  * @dma_hw_dev: Low-level hardware &struct device pointer copied from the
233  *      COMEDI device's hw_dev member.
234  * @page_list: Pointer to array of &struct comedi_buf_page, one for each
235  *      page in the buffer.
236  * @n_pages: Number of pages in the buffer.
237  * @dma_dir: DMA direction used to allocate pages of DMA coherent memory,
238  *      or %DMA_NONE if pages allocated from regular memory.
239  * @refcount: &struct kref reference counter used to free the buffer.
240  *
241  * A COMEDI data buffer is allocated as individual pages, either in
242  * conventional memory or DMA coherent memory, depending on the attached,
243  * low-level hardware device.  (The buffer pages also get mapped into the
244  * kernel's contiguous virtual address space pointed to by the 'prealloc_buf'
245  * member of &struct comedi_async.)
246  *
247  * The buffer is normally freed when the COMEDI device is detached from the
248  * low-level driver (which may happen due to device removal), but if it happens
249  * to be mmapped at the time, the pages cannot be freed until the buffer has
250  * been munmapped.  That is what the reference counter is for.  (The virtual
251  * address space pointed by 'prealloc_buf' is freed when the COMEDI device is
252  * detached.)
253  */
254 struct comedi_buf_map {
255         struct device *dma_hw_dev;
256         struct comedi_buf_page *page_list;
257         unsigned int n_pages;
258         enum dma_data_direction dma_dir;
259         struct kref refcount;
260 };
261
262 /**
263  * struct comedi_async - Control data for asynchronous COMEDI commands
264  * @prealloc_buf: Kernel virtual address of allocated acquisition buffer.
265  * @prealloc_bufsz: Buffer size (in bytes).
266  * @buf_map: Map of buffer pages.
267  * @max_bufsize: Maximum allowed buffer size (in bytes).
268  * @buf_write_count: "Write completed" count (in bytes, modulo 2**32).
269  * @buf_write_alloc_count: "Allocated for writing" count (in bytes,
270  *      modulo 2**32).
271  * @buf_read_count: "Read completed" count (in bytes, modulo 2**32).
272  * @buf_read_alloc_count: "Allocated for reading" count (in bytes,
273  *      modulo 2**32).
274  * @buf_write_ptr: Buffer position for writer.
275  * @buf_read_ptr: Buffer position for reader.
276  * @cur_chan: Current position in chanlist for scan (for those drivers that
277  *      use it).
278  * @scans_done: The number of scans completed.
279  * @scan_progress: Amount received or sent for current scan (in bytes).
280  * @munge_chan: Current position in chanlist for "munging".
281  * @munge_count: "Munge" count (in bytes, modulo 2**32).
282  * @munge_ptr: Buffer position for "munging".
283  * @events: Bit-vector of events that have occurred.
284  * @cmd: Details of comedi command in progress.
285  * @wait_head: Task wait queue for file reader or writer.
286  * @cb_mask: Bit-vector of events that should wake waiting tasks.
287  * @inttrig: Software trigger function for command, or NULL.
288  *
289  * Note about the ..._count and ..._ptr members:
290  *
291  * Think of the _Count values being integers of unlimited size, indexing
292  * into a buffer of infinite length (though only an advancing portion
293  * of the buffer of fixed length prealloc_bufsz is accessible at any
294  * time).  Then:
295  *
296  *   Buf_Read_Count <= Buf_Read_Alloc_Count <= Munge_Count <=
297  *   Buf_Write_Count <= Buf_Write_Alloc_Count <=
298  *   (Buf_Read_Count + prealloc_bufsz)
299  *
300  * (Those aren't the actual members, apart from prealloc_bufsz.) When the
301  * buffer is reset, those _Count values start at 0 and only increase in value,
302  * maintaining the above inequalities until the next time the buffer is
303  * reset.  The buffer is divided into the following regions by the inequalities:
304  *
305  *   [0, Buf_Read_Count):
306  *     old region no longer accessible
307  *
308  *   [Buf_Read_Count, Buf_Read_Alloc_Count):
309  *     filled and munged region allocated for reading but not yet read
310  *
311  *   [Buf_Read_Alloc_Count, Munge_Count):
312  *     filled and munged region not yet allocated for reading
313  *
314  *   [Munge_Count, Buf_Write_Count):
315  *     filled region not yet munged
316  *
317  *   [Buf_Write_Count, Buf_Write_Alloc_Count):
318  *     unfilled region allocated for writing but not yet written
319  *
320  *   [Buf_Write_Alloc_Count, Buf_Read_Count + prealloc_bufsz):
321  *     unfilled region not yet allocated for writing
322  *
323  *   [Buf_Read_Count + prealloc_bufsz, infinity):
324  *     unfilled region not yet accessible
325  *
326  * Data needs to be written into the buffer before it can be read out,
327  * and may need to be converted (or "munged") between the two
328  * operations.  Extra unfilled buffer space may need to allocated for
329  * writing (advancing Buf_Write_Alloc_Count) before new data is written.
330  * After writing new data, the newly filled space needs to be released
331  * (advancing Buf_Write_Count).  This also results in the new data being
332  * "munged" (advancing Munge_Count).  Before data is read out of the
333  * buffer, extra space may need to be allocated for reading (advancing
334  * Buf_Read_Alloc_Count).  After the data has been read out, the space
335  * needs to be released (advancing Buf_Read_Count).
336  *
337  * The actual members, buf_read_count, buf_read_alloc_count,
338  * munge_count, buf_write_count, and buf_write_alloc_count take the
339  * value of the corresponding capitalized _Count values modulo 2^32
340  * (UINT_MAX+1).  Subtracting a "higher" _count value from a "lower"
341  * _count value gives the same answer as subtracting a "higher" _Count
342  * value from a lower _Count value because prealloc_bufsz < UINT_MAX+1.
343  * The modulo operation is done implicitly.
344  *
345  * The buf_read_ptr, munge_ptr, and buf_write_ptr members take the value
346  * of the corresponding capitalized _Count values modulo prealloc_bufsz.
347  * These correspond to byte indices in the physical buffer.  The modulo
348  * operation is done by subtracting prealloc_bufsz when the value
349  * exceeds prealloc_bufsz (assuming prealloc_bufsz plus the increment is
350  * less than or equal to UINT_MAX).
351  */
352 struct comedi_async {
353         void *prealloc_buf;
354         unsigned int prealloc_bufsz;
355         struct comedi_buf_map *buf_map;
356         unsigned int max_bufsize;
357         unsigned int buf_write_count;
358         unsigned int buf_write_alloc_count;
359         unsigned int buf_read_count;
360         unsigned int buf_read_alloc_count;
361         unsigned int buf_write_ptr;
362         unsigned int buf_read_ptr;
363         unsigned int cur_chan;
364         unsigned int scans_done;
365         unsigned int scan_progress;
366         unsigned int munge_chan;
367         unsigned int munge_count;
368         unsigned int munge_ptr;
369         unsigned int events;
370         struct comedi_cmd cmd;
371         wait_queue_head_t wait_head;
372         unsigned int cb_mask;
373         int (*inttrig)(struct comedi_device *dev, struct comedi_subdevice *s,
374                        unsigned int x);
375 };
376
377 /**
378  * enum comedi_cb - &struct comedi_async callback "events"
379  * @COMEDI_CB_EOS:              end-of-scan
380  * @COMEDI_CB_EOA:              end-of-acquisition/output
381  * @COMEDI_CB_BLOCK:            data has arrived, wakes up read() / write()
382  * @COMEDI_CB_EOBUF:            DEPRECATED: end of buffer
383  * @COMEDI_CB_ERROR:            card error during acquisition
384  * @COMEDI_CB_OVERFLOW:         buffer overflow/underflow
385  * @COMEDI_CB_ERROR_MASK:       events that indicate an error has occurred
386  * @COMEDI_CB_CANCEL_MASK:      events that will cancel an async command
387  */
388 enum comedi_cb {
389         COMEDI_CB_EOS           = BIT(0),
390         COMEDI_CB_EOA           = BIT(1),
391         COMEDI_CB_BLOCK         = BIT(2),
392         COMEDI_CB_EOBUF         = BIT(3),
393         COMEDI_CB_ERROR         = BIT(4),
394         COMEDI_CB_OVERFLOW      = BIT(5),
395         /* masks */
396         COMEDI_CB_ERROR_MASK    = (COMEDI_CB_ERROR | COMEDI_CB_OVERFLOW),
397         COMEDI_CB_CANCEL_MASK   = (COMEDI_CB_EOA | COMEDI_CB_ERROR_MASK)
398 };
399
400 /**
401  * struct comedi_driver - COMEDI driver registration
402  * @driver_name: Name of driver.
403  * @module: Owning module.
404  * @attach: The optional "attach" handler for manually configured COMEDI
405  *      devices.
406  * @detach: The "detach" handler for deconfiguring COMEDI devices.
407  * @auto_attach: The optional "auto_attach" handler for automatically
408  *      configured COMEDI devices.
409  * @num_names: Optional number of "board names" supported.
410  * @board_name: Optional pointer to a pointer to a board name.  The pointer
411  *      to a board name is embedded in an element of a driver-defined array
412  *      of static, read-only board type information.
413  * @offset: Optional size of each element of the driver-defined array of
414  *      static, read-only board type information, i.e. the offset between each
415  *      pointer to a board name.
416  *
417  * This is used with comedi_driver_register() and comedi_driver_unregister() to
418  * register and unregister a low-level COMEDI driver with the COMEDI core.
419  *
420  * If @num_names is non-zero, @board_name should be non-NULL, and @offset
421  * should be at least sizeof(*board_name).  These are used by the handler for
422  * the %COMEDI_DEVCONFIG ioctl to match a hardware device and its driver by
423  * board name.  If @num_names is zero, the %COMEDI_DEVCONFIG ioctl matches a
424  * hardware device and its driver by driver name.  This is only useful if the
425  * @attach handler is set.  If @num_names is non-zero, the driver's @attach
426  * handler will be called with the COMEDI device structure's board_ptr member
427  * pointing to the matched pointer to a board name within the driver's private
428  * array of static, read-only board type information.
429  *
430  * The @detach handler has two roles.  If a COMEDI device was successfully
431  * configured by the @attach or @auto_attach handler, it is called when the
432  * device is being deconfigured (by the %COMEDI_DEVCONFIG ioctl, or due to
433  * unloading of the driver, or due to device removal).  It is also called when
434  * the @attach or @auto_attach handler returns an error.  Therefore, the
435  * @attach or @auto_attach handlers can defer clean-up on error until the
436  * @detach handler is called.  If the @attach or @auto_attach handlers free
437  * any resources themselves, they must prevent the @detach handler from
438  * freeing the same resources.  The @detach handler must not assume that all
439  * resources requested by the @attach or @auto_attach handler were
440  * successfully allocated.
441  */
442 struct comedi_driver {
443         /* private: */
444         struct comedi_driver *next;     /* Next in list of COMEDI drivers. */
445         /* public: */
446         const char *driver_name;
447         struct module *module;
448         int (*attach)(struct comedi_device *, struct comedi_devconfig *);
449         void (*detach)(struct comedi_device *);
450         int (*auto_attach)(struct comedi_device *, unsigned long);
451         unsigned int num_names;
452         const char *const *board_name;
453         int offset;
454 };
455
456 /**
457  * struct comedi_device - Working data for a COMEDI device
458  * @use_count: Number of open file objects.
459  * @driver: Low-level COMEDI driver attached to this COMEDI device.
460  * @pacer: Optional pointer to a dynamically allocated acquisition pacer
461  *      control.  It is freed automatically after the COMEDI device is
462  *      detached from the low-level driver.
463  * @private: Optional pointer to private data allocated by the low-level
464  *      driver.  It is freed automatically after the COMEDI device is
465  *      detached from the low-level driver.
466  * @class_dev: Sysfs comediX device.
467  * @minor: Minor device number of COMEDI char device (0-47).
468  * @detach_count: Counter incremented every time the COMEDI device is detached.
469  *      Used for checking a previous attachment is still valid.
470  * @hw_dev: Optional pointer to the low-level hardware &struct device.  It is
471  *      required for automatically configured COMEDI devices and optional for
472  *      COMEDI devices configured by the %COMEDI_DEVCONFIG ioctl, although
473  *      the bus-specific COMEDI functions only work if it is set correctly.
474  *      It is also passed to dma_alloc_coherent() for COMEDI subdevices that
475  *      have their 'async_dma_dir' member set to something other than
476  *      %DMA_NONE.
477  * @board_name: Pointer to a COMEDI board name or a COMEDI driver name.  When
478  *      the low-level driver's "attach" handler is called by the handler for
479  *      the %COMEDI_DEVCONFIG ioctl, it either points to a matched board name
480  *      string if the 'num_names' member of the &struct comedi_driver is
481  *      non-zero, otherwise it points to the low-level driver name string.
482  *      When the low-lever driver's "auto_attach" handler is called for an
483  *      automatically configured COMEDI device, it points to the low-level
484  *      driver name string.  The low-level driver is free to change it in its
485  *      "attach" or "auto_attach" handler if it wishes.
486  * @board_ptr: Optional pointer to private, read-only board type information in
487  *      the low-level driver.  If the 'num_names' member of the &struct
488  *      comedi_driver is non-zero, the handler for the %COMEDI_DEVCONFIG ioctl
489  *      will point it to a pointer to a matched board name string within the
490  *      driver's private array of static, read-only board type information when
491  *      calling the driver's "attach" handler.  The low-level driver is free to
492  *      change it.
493  * @attached: Flag indicating that the COMEDI device is attached to a low-level
494  *      driver.
495  * @ioenabled: Flag used to indicate that a PCI device has been enabled and
496  *      its regions requested.
497  * @spinlock: Generic spin-lock for use by the low-level driver.
498  * @mutex: Generic mutex for use by the COMEDI core module.
499  * @attach_lock: &struct rw_semaphore used to guard against the COMEDI device
500  *      being detached while an operation is in progress.  The down_write()
501  *      operation is only allowed while @mutex is held and is used when
502  *      changing @attached and @detach_count and calling the low-level driver's
503  *      "detach" handler.  The down_read() operation is generally used without
504  *      holding @mutex.
505  * @refcount: &struct kref reference counter for freeing COMEDI device.
506  * @n_subdevices: Number of COMEDI subdevices allocated by the low-level
507  *      driver for this device.
508  * @subdevices: Dynamically allocated array of COMEDI subdevices.
509  * @mmio: Optional pointer to a remapped MMIO region set by the low-level
510  *      driver.
511  * @iobase: Optional base of an I/O port region requested by the low-level
512  *      driver.
513  * @iolen: Length of I/O port region requested at @iobase.
514  * @irq: Optional IRQ number requested by the low-level driver.
515  * @read_subdev: Optional pointer to a default COMEDI subdevice operated on by
516  *      the read() file operation.  Set by the low-level driver.
517  * @write_subdev: Optional pointer to a default COMEDI subdevice operated on by
518  *      the write() file operation.  Set by the low-level driver.
519  * @async_queue: Storage for fasync_helper().
520  * @open: Optional pointer to a function set by the low-level driver to be
521  *      called when @use_count changes from 0 to 1.
522  * @close: Optional pointer to a function set by the low-level driver to be
523  *      called when @use_count changed from 1 to 0.
524  *
525  * This is the main control data structure for a COMEDI device (as far as the
526  * COMEDI core is concerned).  There are two groups of COMEDI devices -
527  * "legacy" devices that are configured by the handler for the
528  * %COMEDI_DEVCONFIG ioctl, and automatically configured devices resulting
529  * from a call to comedi_auto_config() as a result of a bus driver probe in
530  * a low-level COMEDI driver.  The "legacy" COMEDI devices are allocated
531  * during module initialization if the "comedi_num_legacy_minors" module
532  * parameter is non-zero and use minor device numbers from 0 to
533  * comedi_num_legacy_minors minus one.  The automatically configured COMEDI
534  * devices are allocated on demand and use minor device numbers from
535  * comedi_num_legacy_minors to 47.
536  */
537 struct comedi_device {
538         int use_count;
539         struct comedi_driver *driver;
540         struct comedi_8254 *pacer;
541         void *private;
542
543         struct device *class_dev;
544         int minor;
545         unsigned int detach_count;
546         struct device *hw_dev;
547
548         const char *board_name;
549         const void *board_ptr;
550         bool attached:1;
551         bool ioenabled:1;
552         spinlock_t spinlock;    /* generic spin-lock for low-level driver */
553         struct mutex mutex;     /* generic mutex for COMEDI core */
554         struct rw_semaphore attach_lock;
555         struct kref refcount;
556
557         int n_subdevices;
558         struct comedi_subdevice *subdevices;
559
560         /* dumb */
561         void __iomem *mmio;
562         unsigned long iobase;
563         unsigned long iolen;
564         unsigned int irq;
565
566         struct comedi_subdevice *read_subdev;
567         struct comedi_subdevice *write_subdev;
568
569         struct fasync_struct *async_queue;
570
571         int (*open)(struct comedi_device *dev);
572         void (*close)(struct comedi_device *dev);
573 };
574
575 /*
576  * function prototypes
577  */
578
579 void comedi_event(struct comedi_device *dev, struct comedi_subdevice *s);
580
581 struct comedi_device *comedi_dev_get_from_minor(unsigned int minor);
582 int comedi_dev_put(struct comedi_device *dev);
583
584 bool comedi_is_subdevice_running(struct comedi_subdevice *s);
585
586 void *comedi_alloc_spriv(struct comedi_subdevice *s, size_t size);
587 void comedi_set_spriv_auto_free(struct comedi_subdevice *s);
588
589 int comedi_check_chanlist(struct comedi_subdevice *s,
590                           int n,
591                           unsigned int *chanlist);
592
593 /* range stuff */
594
595 #define RANGE(a, b)             {(a) * 1e6, (b) * 1e6, 0}
596 #define RANGE_ext(a, b)         {(a) * 1e6, (b) * 1e6, RF_EXTERNAL}
597 #define RANGE_mA(a, b)          {(a) * 1e6, (b) * 1e6, UNIT_mA}
598 #define RANGE_unitless(a, b)    {(a) * 1e6, (b) * 1e6, 0}
599 #define BIP_RANGE(a)            {-(a) * 1e6, (a) * 1e6, 0}
600 #define UNI_RANGE(a)            {0, (a) * 1e6, 0}
601
602 extern const struct comedi_lrange range_bipolar10;
603 extern const struct comedi_lrange range_bipolar5;
604 extern const struct comedi_lrange range_bipolar2_5;
605 extern const struct comedi_lrange range_unipolar10;
606 extern const struct comedi_lrange range_unipolar5;
607 extern const struct comedi_lrange range_unipolar2_5;
608 extern const struct comedi_lrange range_0_20mA;
609 extern const struct comedi_lrange range_4_20mA;
610 extern const struct comedi_lrange range_0_32mA;
611 extern const struct comedi_lrange range_unknown;
612
613 #define range_digital           range_unipolar5
614
615 /**
616  * struct comedi_lrange - Describes a COMEDI range table
617  * @length: Number of entries in the range table.
618  * @range: Array of &struct comedi_krange, one for each range.
619  *
620  * Each element of @range[] describes the minimum and maximum physical range
621  * range and the type of units.  Typically, the type of unit is %UNIT_volt
622  * (i.e. volts) and the minimum and maximum are in millionths of a volt.
623  * There may also be a flag that indicates the minimum and maximum are merely
624  * scale factors for an unknown, external reference.
625  */
626 struct comedi_lrange {
627         int length;
628         struct comedi_krange range[];
629 };
630
631 /**
632  * comedi_range_is_bipolar() - Test if subdevice range is bipolar
633  * @s: COMEDI subdevice.
634  * @range: Index of range within a range table.
635  *
636  * Tests whether a range is bipolar by checking whether its minimum value
637  * is negative.
638  *
639  * Assumes @range is valid.  Does not work for subdevices using a
640  * channel-specific range table list.
641  *
642  * Return:
643  *      %true if the range is bipolar.
644  *      %false if the range is unipolar.
645  */
646 static inline bool comedi_range_is_bipolar(struct comedi_subdevice *s,
647                                            unsigned int range)
648 {
649         return s->range_table->range[range].min < 0;
650 }
651
652 /**
653  * comedi_range_is_unipolar() - Test if subdevice range is unipolar
654  * @s: COMEDI subdevice.
655  * @range: Index of range within a range table.
656  *
657  * Tests whether a range is unipolar by checking whether its minimum value
658  * is at least 0.
659  *
660  * Assumes @range is valid.  Does not work for subdevices using a
661  * channel-specific range table list.
662  *
663  * Return:
664  *      %true if the range is unipolar.
665  *      %false if the range is bipolar.
666  */
667 static inline bool comedi_range_is_unipolar(struct comedi_subdevice *s,
668                                             unsigned int range)
669 {
670         return s->range_table->range[range].min >= 0;
671 }
672
673 /**
674  * comedi_range_is_external() - Test if subdevice range is external
675  * @s: COMEDI subdevice.
676  * @range: Index of range within a range table.
677  *
678  * Tests whether a range is externally reference by checking whether its
679  * %RF_EXTERNAL flag is set.
680  *
681  * Assumes @range is valid.  Does not work for subdevices using a
682  * channel-specific range table list.
683  *
684  * Return:
685  *      %true if the range is external.
686  *      %false if the range is internal.
687  */
688 static inline bool comedi_range_is_external(struct comedi_subdevice *s,
689                                             unsigned int range)
690 {
691         return !!(s->range_table->range[range].flags & RF_EXTERNAL);
692 }
693
694 /**
695  * comedi_chan_range_is_bipolar() - Test if channel-specific range is bipolar
696  * @s: COMEDI subdevice.
697  * @chan: The channel number.
698  * @range: Index of range within a range table.
699  *
700  * Tests whether a range is bipolar by checking whether its minimum value
701  * is negative.
702  *
703  * Assumes @chan and @range are valid.  Only works for subdevices with a
704  * channel-specific range table list.
705  *
706  * Return:
707  *      %true if the range is bipolar.
708  *      %false if the range is unipolar.
709  */
710 static inline bool comedi_chan_range_is_bipolar(struct comedi_subdevice *s,
711                                                 unsigned int chan,
712                                                 unsigned int range)
713 {
714         return s->range_table_list[chan]->range[range].min < 0;
715 }
716
717 /**
718  * comedi_chan_range_is_unipolar() - Test if channel-specific range is unipolar
719  * @s: COMEDI subdevice.
720  * @chan: The channel number.
721  * @range: Index of range within a range table.
722  *
723  * Tests whether a range is unipolar by checking whether its minimum value
724  * is at least 0.
725  *
726  * Assumes @chan and @range are valid.  Only works for subdevices with a
727  * channel-specific range table list.
728  *
729  * Return:
730  *      %true if the range is unipolar.
731  *      %false if the range is bipolar.
732  */
733 static inline bool comedi_chan_range_is_unipolar(struct comedi_subdevice *s,
734                                                  unsigned int chan,
735                                                  unsigned int range)
736 {
737         return s->range_table_list[chan]->range[range].min >= 0;
738 }
739
740 /**
741  * comedi_chan_range_is_external() - Test if channel-specific range is external
742  * @s: COMEDI subdevice.
743  * @chan: The channel number.
744  * @range: Index of range within a range table.
745  *
746  * Tests whether a range is externally reference by checking whether its
747  * %RF_EXTERNAL flag is set.
748  *
749  * Assumes @chan and @range are valid.  Only works for subdevices with a
750  * channel-specific range table list.
751  *
752  * Return:
753  *      %true if the range is bipolar.
754  *      %false if the range is unipolar.
755  */
756 static inline bool comedi_chan_range_is_external(struct comedi_subdevice *s,
757                                                  unsigned int chan,
758                                                  unsigned int range)
759 {
760         return !!(s->range_table_list[chan]->range[range].flags & RF_EXTERNAL);
761 }
762
763 /**
764  * comedi_offset_munge() - Convert between offset binary and 2's complement
765  * @s: COMEDI subdevice.
766  * @val: Value to be converted.
767  *
768  * Toggles the highest bit of a sample value to toggle between offset binary
769  * and 2's complement.  Assumes that @s->maxdata is a power of 2 minus 1.
770  *
771  * Return: The converted value.
772  */
773 static inline unsigned int comedi_offset_munge(struct comedi_subdevice *s,
774                                                unsigned int val)
775 {
776         return val ^ s->maxdata ^ (s->maxdata >> 1);
777 }
778
779 /**
780  * comedi_bytes_per_sample() - Determine subdevice sample size
781  * @s: COMEDI subdevice.
782  *
783  * The sample size will be 4 (sizeof int) or 2 (sizeof short) depending on
784  * whether the %SDF_LSAMPL subdevice flag is set or not.
785  *
786  * Return: The subdevice sample size.
787  */
788 static inline unsigned int comedi_bytes_per_sample(struct comedi_subdevice *s)
789 {
790         return s->subdev_flags & SDF_LSAMPL ? sizeof(int) : sizeof(short);
791 }
792
793 /**
794  * comedi_sample_shift() - Determine log2 of subdevice sample size
795  * @s: COMEDI subdevice.
796  *
797  * The sample size will be 4 (sizeof int) or 2 (sizeof short) depending on
798  * whether the %SDF_LSAMPL subdevice flag is set or not.  The log2 of the
799  * sample size will be 2 or 1 and can be used as the right operand of a
800  * bit-shift operator to multiply or divide something by the sample size.
801  *
802  * Return: log2 of the subdevice sample size.
803  */
804 static inline unsigned int comedi_sample_shift(struct comedi_subdevice *s)
805 {
806         return s->subdev_flags & SDF_LSAMPL ? 2 : 1;
807 }
808
809 /**
810  * comedi_bytes_to_samples() - Convert a number of bytes to a number of samples
811  * @s: COMEDI subdevice.
812  * @nbytes: Number of bytes
813  *
814  * Return: The number of bytes divided by the subdevice sample size.
815  */
816 static inline unsigned int comedi_bytes_to_samples(struct comedi_subdevice *s,
817                                                    unsigned int nbytes)
818 {
819         return nbytes >> comedi_sample_shift(s);
820 }
821
822 /**
823  * comedi_samples_to_bytes() - Convert a number of samples to a number of bytes
824  * @s: COMEDI subdevice.
825  * @nsamples: Number of samples.
826  *
827  * Return: The number of samples multiplied by the subdevice sample size.
828  * (Does not check for arithmetic overflow.)
829  */
830 static inline unsigned int comedi_samples_to_bytes(struct comedi_subdevice *s,
831                                                    unsigned int nsamples)
832 {
833         return nsamples << comedi_sample_shift(s);
834 }
835
836 /**
837  * comedi_check_trigger_src() - Trivially validate a comedi_cmd trigger source
838  * @src: Pointer to the trigger source to validate.
839  * @flags: Bitmask of valid %TRIG_* for the trigger.
840  *
841  * This is used in "step 1" of the do_cmdtest functions of comedi drivers
842  * to validate the comedi_cmd triggers. The mask of the @src against the
843  * @flags allows the userspace comedilib to pass all the comedi_cmd
844  * triggers as %TRIG_ANY and get back a bitmask of the valid trigger sources.
845  *
846  * Return:
847  *      0 if trigger sources in *@src are all supported.
848  *      -EINVAL if any trigger source in *@src is unsupported.
849  */
850 static inline int comedi_check_trigger_src(unsigned int *src,
851                                            unsigned int flags)
852 {
853         unsigned int orig_src = *src;
854
855         *src = orig_src & flags;
856         if (*src == TRIG_INVALID || *src != orig_src)
857                 return -EINVAL;
858         return 0;
859 }
860
861 /**
862  * comedi_check_trigger_is_unique() - Make sure a trigger source is unique
863  * @src: The trigger source to check.
864  *
865  * Return:
866  *      0 if no more than one trigger source is set.
867  *      -EINVAL if more than one trigger source is set.
868  */
869 static inline int comedi_check_trigger_is_unique(unsigned int src)
870 {
871         /* this test is true if more than one _src bit is set */
872         if ((src & (src - 1)) != 0)
873                 return -EINVAL;
874         return 0;
875 }
876
877 /**
878  * comedi_check_trigger_arg_is() - Trivially validate a trigger argument
879  * @arg: Pointer to the trigger arg to validate.
880  * @val: The value the argument should be.
881  *
882  * Forces *@arg to be @val.
883  *
884  * Return:
885  *      0 if *@arg was already @val.
886  *      -EINVAL if *@arg differed from @val.
887  */
888 static inline int comedi_check_trigger_arg_is(unsigned int *arg,
889                                               unsigned int val)
890 {
891         if (*arg != val) {
892                 *arg = val;
893                 return -EINVAL;
894         }
895         return 0;
896 }
897
898 /**
899  * comedi_check_trigger_arg_min() - Trivially validate a trigger argument min
900  * @arg: Pointer to the trigger arg to validate.
901  * @val: The minimum value the argument should be.
902  *
903  * Forces *@arg to be at least @val, setting it to @val if necessary.
904  *
905  * Return:
906  *      0 if *@arg was already at least @val.
907  *      -EINVAL if *@arg was less than @val.
908  */
909 static inline int comedi_check_trigger_arg_min(unsigned int *arg,
910                                                unsigned int val)
911 {
912         if (*arg < val) {
913                 *arg = val;
914                 return -EINVAL;
915         }
916         return 0;
917 }
918
919 /**
920  * comedi_check_trigger_arg_max() - Trivially validate a trigger argument max
921  * @arg: Pointer to the trigger arg to validate.
922  * @val: The maximum value the argument should be.
923  *
924  * Forces *@arg to be no more than @val, setting it to @val if necessary.
925  *
926  * Return:
927  *      0 if*@arg was already no more than @val.
928  *      -EINVAL if *@arg was greater than @val.
929  */
930 static inline int comedi_check_trigger_arg_max(unsigned int *arg,
931                                                unsigned int val)
932 {
933         if (*arg > val) {
934                 *arg = val;
935                 return -EINVAL;
936         }
937         return 0;
938 }
939
940 /*
941  * Must set dev->hw_dev if you wish to dma directly into comedi's buffer.
942  * Also useful for retrieving a previously configured hardware device of
943  * known bus type.  Set automatically for auto-configured devices.
944  * Automatically set to NULL when detaching hardware device.
945  */
946 int comedi_set_hw_dev(struct comedi_device *dev, struct device *hw_dev);
947
948 /**
949  * comedi_buf_n_bytes_ready - Determine amount of unread data in buffer
950  * @s: COMEDI subdevice.
951  *
952  * Determines the number of bytes of unread data in the asynchronous
953  * acquisition data buffer for a subdevice.  The data in question might not
954  * have been fully "munged" yet.
955  *
956  * Returns: The amount of unread data in bytes.
957  */
958 static inline unsigned int comedi_buf_n_bytes_ready(struct comedi_subdevice *s)
959 {
960         return s->async->buf_write_count - s->async->buf_read_count;
961 }
962
963 unsigned int comedi_buf_write_alloc(struct comedi_subdevice *s, unsigned int n);
964 unsigned int comedi_buf_write_free(struct comedi_subdevice *s, unsigned int n);
965
966 unsigned int comedi_buf_read_n_available(struct comedi_subdevice *s);
967 unsigned int comedi_buf_read_alloc(struct comedi_subdevice *s, unsigned int n);
968 unsigned int comedi_buf_read_free(struct comedi_subdevice *s, unsigned int n);
969
970 unsigned int comedi_buf_write_samples(struct comedi_subdevice *s,
971                                       const void *data, unsigned int nsamples);
972 unsigned int comedi_buf_read_samples(struct comedi_subdevice *s,
973                                      void *data, unsigned int nsamples);
974
975 /* drivers.c - general comedi driver functions */
976
977 #define COMEDI_TIMEOUT_MS       1000
978
979 int comedi_timeout(struct comedi_device *dev, struct comedi_subdevice *s,
980                    struct comedi_insn *insn,
981                    int (*cb)(struct comedi_device *dev,
982                              struct comedi_subdevice *s,
983                              struct comedi_insn *insn, unsigned long context),
984                    unsigned long context);
985
986 unsigned int comedi_handle_events(struct comedi_device *dev,
987                                   struct comedi_subdevice *s);
988
989 int comedi_dio_insn_config(struct comedi_device *dev,
990                            struct comedi_subdevice *s,
991                            struct comedi_insn *insn, unsigned int *data,
992                            unsigned int mask);
993 unsigned int comedi_dio_update_state(struct comedi_subdevice *s,
994                                      unsigned int *data);
995 unsigned int comedi_bytes_per_scan(struct comedi_subdevice *s);
996 unsigned int comedi_nscans_left(struct comedi_subdevice *s,
997                                 unsigned int nscans);
998 unsigned int comedi_nsamples_left(struct comedi_subdevice *s,
999                                   unsigned int nsamples);
1000 void comedi_inc_scan_progress(struct comedi_subdevice *s,
1001                               unsigned int num_bytes);
1002
1003 void *comedi_alloc_devpriv(struct comedi_device *dev, size_t size);
1004 int comedi_alloc_subdevices(struct comedi_device *dev, int num_subdevices);
1005 int comedi_alloc_subdev_readback(struct comedi_subdevice *s);
1006
1007 int comedi_readback_insn_read(struct comedi_device *dev,
1008                               struct comedi_subdevice *s,
1009                               struct comedi_insn *insn, unsigned int *data);
1010
1011 int comedi_load_firmware(struct comedi_device *dev, struct device *hw_dev,
1012                          const char *name,
1013                          int (*cb)(struct comedi_device *dev,
1014                                    const u8 *data, size_t size,
1015                                    unsigned long context),
1016                          unsigned long context);
1017
1018 int __comedi_request_region(struct comedi_device *dev,
1019                             unsigned long start, unsigned long len);
1020 int comedi_request_region(struct comedi_device *dev,
1021                           unsigned long start, unsigned long len);
1022 void comedi_legacy_detach(struct comedi_device *dev);
1023
1024 int comedi_auto_config(struct device *hardware_device,
1025                        struct comedi_driver *driver, unsigned long context);
1026 void comedi_auto_unconfig(struct device *hardware_device);
1027
1028 int comedi_driver_register(struct comedi_driver *driver);
1029 void comedi_driver_unregister(struct comedi_driver *driver);
1030
1031 /**
1032  * module_comedi_driver() - Helper macro for registering a comedi driver
1033  * @__comedi_driver: comedi_driver struct
1034  *
1035  * Helper macro for comedi drivers which do not do anything special in module
1036  * init/exit. This eliminates a lot of boilerplate. Each module may only use
1037  * this macro once, and calling it replaces module_init() and module_exit().
1038  */
1039 #define module_comedi_driver(__comedi_driver) \
1040         module_driver(__comedi_driver, comedi_driver_register, \
1041                         comedi_driver_unregister)
1042
1043 #endif /* _COMEDIDEV_H */