Merge branch 'v4l_for_linus' of git://git.kernel.org/pub/scm/linux/kernel/git/mchehab...
[firefly-linux-kernel-4.4.55.git] / drivers / staging / comedi / drivers / amplc_pci224.c
1 /*
2     comedi/drivers/amplc_pci224.c
3     Driver for Amplicon PCI224 and PCI234 AO boards.
4
5     Copyright (C) 2005 MEV Ltd. <http://www.mev.co.uk/>
6
7     COMEDI - Linux Control and Measurement Device Interface
8     Copyright (C) 1998,2000 David A. Schleef <ds@schleef.org>
9
10     This program is free software; you can redistribute it and/or modify
11     it under the terms of the GNU General Public License as published by
12     the Free Software Foundation; either version 2 of the License, or
13     (at your option) any later version.
14
15     This program is distributed in the hope that it will be useful,
16     but WITHOUT ANY WARRANTY; without even the implied warranty of
17     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18     GNU General Public License for more details.
19
20     You should have received a copy of the GNU General Public License
21     along with this program; if not, write to the Free Software
22     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23
24 */
25 /*
26 Driver: amplc_pci224
27 Description: Amplicon PCI224, PCI234
28 Author: Ian Abbott <abbotti@mev.co.uk>
29 Devices: [Amplicon] PCI224 (amplc_pci224 or pci224),
30   PCI234 (amplc_pci224 or pci234)
31 Updated: Wed, 22 Oct 2008 12:25:08 +0100
32 Status: works, but see caveats
33
34 Supports:
35
36   - ao_insn read/write
37   - ao_do_cmd mode with the following sources:
38
39     - start_src         TRIG_INT        TRIG_EXT
40     - scan_begin_src    TRIG_TIMER      TRIG_EXT
41     - convert_src       TRIG_NOW
42     - scan_end_src      TRIG_COUNT
43     - stop_src          TRIG_COUNT      TRIG_EXT        TRIG_NONE
44
45     The channel list must contain at least one channel with no repeated
46     channels.  The scan end count must equal the number of channels in
47     the channel list.
48
49     There is only one external trigger source so only one of start_src,
50     scan_begin_src or stop_src may use TRIG_EXT.
51
52 Configuration options - PCI224:
53   [0] - PCI bus of device (optional).
54   [1] - PCI slot of device (optional).
55           If bus/slot is not specified, the first available PCI device
56           will be used.
57   [2] - Select available ranges according to jumper LK1.  All channels
58         are set to the same range:
59         0=Jumper position 1-2 (factory default), 4 software-selectable
60           internal voltage references, giving 4 bipolar and 4 unipolar
61           ranges:
62             [-10V,+10V], [-5V,+5V], [-2.5V,+2.5V], [-1.25V,+1.25V],
63             [0,+10V], [0,+5V], [0,+2.5V], [0,1.25V].
64         1=Jumper position 2-3, 1 external voltage reference, giving
65           1 bipolar and 1 unipolar range:
66             [-Vext,+Vext], [0,+Vext].
67
68 Configuration options - PCI234:
69   [0] - PCI bus of device (optional).
70   [1] - PCI slot of device (optional).
71           If bus/slot is not specified, the first available PCI device
72           will be used.
73   [2] - Select internal or external voltage reference according to
74         jumper LK1.  This affects all channels:
75         0=Jumper position 1-2 (factory default), Vref=5V internal.
76         1=Jumper position 2-3, Vref=Vext external.
77   [3] - Select channel 0 range according to jumper LK2:
78         0=Jumper position 2-3 (factory default), range [-2*Vref,+2*Vref]
79           (10V bipolar when options[2]=0).
80         1=Jumper position 1-2, range [-Vref,+Vref]
81           (5V bipolar when options[2]=0).
82   [4] - Select channel 1 range according to jumper LK3: cf. options[3].
83   [5] - Select channel 2 range according to jumper LK4: cf. options[3].
84   [6] - Select channel 3 range according to jumper LK5: cf. options[3].
85
86 Passing a zero for an option is the same as leaving it unspecified.
87
88 Caveats:
89
90   1) All channels on the PCI224 share the same range.  Any change to the
91      range as a result of insn_write or a streaming command will affect
92      the output voltages of all channels, including those not specified
93      by the instruction or command.
94
95   2) For the analog output command,  the first scan may be triggered
96      falsely at the start of acquisition.  This occurs when the DAC scan
97      trigger source is switched from 'none' to 'timer' (scan_begin_src =
98      TRIG_TIMER) or 'external' (scan_begin_src == TRIG_EXT) at the start
99      of acquisition and the trigger source is at logic level 1 at the
100      time of the switch.  This is very likely for TRIG_TIMER.  For
101      TRIG_EXT, it depends on the state of the external line and whether
102      the CR_INVERT flag has been set.  The remaining scans are triggered
103      correctly.
104 */
105
106 #include <linux/pci.h>
107 #include <linux/interrupt.h>
108 #include <linux/slab.h>
109
110 #include "../comedidev.h"
111
112 #include "comedi_fc.h"
113 #include "8253.h"
114
115 #define DRIVER_NAME     "amplc_pci224"
116
117 /*
118  * PCI IDs.
119  */
120 #define PCI_DEVICE_ID_AMPLICON_PCI224 0x0007
121 #define PCI_DEVICE_ID_AMPLICON_PCI234 0x0008
122 #define PCI_DEVICE_ID_INVALID 0xffff
123
124 /*
125  * PCI224/234 i/o space 1 (PCIBAR2) registers.
126  */
127 #define PCI224_IO1_SIZE 0x20    /* Size of i/o space 1 (8-bit registers) */
128 #define PCI224_Z2_CT0   0x14    /* 82C54 counter/timer 0 */
129 #define PCI224_Z2_CT1   0x15    /* 82C54 counter/timer 1 */
130 #define PCI224_Z2_CT2   0x16    /* 82C54 counter/timer 2 */
131 #define PCI224_Z2_CTC   0x17    /* 82C54 counter/timer control word */
132 #define PCI224_ZCLK_SCE 0x1A    /* Group Z Clock Configuration Register */
133 #define PCI224_ZGAT_SCE 0x1D    /* Group Z Gate Configuration Register */
134 #define PCI224_INT_SCE  0x1E    /* ISR Interrupt source mask register */
135                                 /* /Interrupt status */
136
137 /*
138  * PCI224/234 i/o space 2 (PCIBAR3) 16-bit registers.
139  */
140 #define PCI224_IO2_SIZE 0x10    /* Size of i/o space 2 (16-bit registers). */
141 #define PCI224_DACDATA  0x00    /* (w-o) DAC FIFO data. */
142 #define PCI224_SOFTTRIG 0x00    /* (r-o) DAC software scan trigger. */
143 #define PCI224_DACCON   0x02    /* (r/w) DAC status/configuration. */
144 #define PCI224_FIFOSIZ  0x04    /* (w-o) FIFO size for wraparound mode. */
145 #define PCI224_DACCEN   0x06    /* (w-o) DAC channel enable register. */
146
147 /*
148  * DACCON values.
149  */
150 /* (r/w) Scan trigger. */
151 #define PCI224_DACCON_TRIG_MASK         (7 << 0)
152 #define PCI224_DACCON_TRIG_NONE         (0 << 0)        /* none */
153 #define PCI224_DACCON_TRIG_SW           (1 << 0)        /* software trig */
154 #define PCI224_DACCON_TRIG_EXTP         (2 << 0)        /* ext +ve edge */
155 #define PCI224_DACCON_TRIG_EXTN         (3 << 0)        /* ext -ve edge */
156 #define PCI224_DACCON_TRIG_Z2CT0        (4 << 0)        /* Z2 CT0 out */
157 #define PCI224_DACCON_TRIG_Z2CT1        (5 << 0)        /* Z2 CT1 out */
158 #define PCI224_DACCON_TRIG_Z2CT2        (6 << 0)        /* Z2 CT2 out */
159 /* (r/w) Polarity (PCI224 only, PCI234 always bipolar!). */
160 #define PCI224_DACCON_POLAR_MASK        (1 << 3)
161 #define PCI224_DACCON_POLAR_UNI         (0 << 3)        /* range [0,Vref] */
162 #define PCI224_DACCON_POLAR_BI          (1 << 3)        /* range [-Vref,Vref] */
163 /* (r/w) Internal Vref (PCI224 only, when LK1 in position 1-2). */
164 #define PCI224_DACCON_VREF_MASK         (3 << 4)
165 #define PCI224_DACCON_VREF_1_25         (0 << 4)        /* Vref = 1.25V */
166 #define PCI224_DACCON_VREF_2_5          (1 << 4)        /* Vref = 2.5V */
167 #define PCI224_DACCON_VREF_5            (2 << 4)        /* Vref = 5V */
168 #define PCI224_DACCON_VREF_10           (3 << 4)        /* Vref = 10V */
169 /* (r/w) Wraparound mode enable (to play back stored waveform). */
170 #define PCI224_DACCON_FIFOWRAP          (1 << 7)
171 /* (r/w) FIFO enable.  It MUST be set! */
172 #define PCI224_DACCON_FIFOENAB          (1 << 8)
173 /* (r/w) FIFO interrupt trigger level (most values are not very useful). */
174 #define PCI224_DACCON_FIFOINTR_MASK     (7 << 9)
175 #define PCI224_DACCON_FIFOINTR_EMPTY    (0 << 9)        /* when empty */
176 #define PCI224_DACCON_FIFOINTR_NEMPTY   (1 << 9)        /* when not empty */
177 #define PCI224_DACCON_FIFOINTR_NHALF    (2 << 9)        /* when not half full */
178 #define PCI224_DACCON_FIFOINTR_HALF     (3 << 9)        /* when half full */
179 #define PCI224_DACCON_FIFOINTR_NFULL    (4 << 9)        /* when not full */
180 #define PCI224_DACCON_FIFOINTR_FULL     (5 << 9)        /* when full */
181 /* (r-o) FIFO fill level. */
182 #define PCI224_DACCON_FIFOFL_MASK       (7 << 12)
183 #define PCI224_DACCON_FIFOFL_EMPTY      (1 << 12)       /* 0 */
184 #define PCI224_DACCON_FIFOFL_ONETOHALF  (0 << 12)       /* [1,2048] */
185 #define PCI224_DACCON_FIFOFL_HALFTOFULL (4 << 12)       /* [2049,4095] */
186 #define PCI224_DACCON_FIFOFL_FULL       (6 << 12)       /* 4096 */
187 /* (r-o) DAC busy flag. */
188 #define PCI224_DACCON_BUSY              (1 << 15)
189 /* (w-o) FIFO reset. */
190 #define PCI224_DACCON_FIFORESET         (1 << 12)
191 /* (w-o) Global reset (not sure what it does). */
192 #define PCI224_DACCON_GLOBALRESET       (1 << 13)
193
194 /*
195  * DAC FIFO size.
196  */
197 #define PCI224_FIFO_SIZE        4096
198
199 /*
200  * DAC FIFO guaranteed minimum room available, depending on reported fill level.
201  * The maximum room available depends on the reported fill level and how much
202  * has been written!
203  */
204 #define PCI224_FIFO_ROOM_EMPTY          PCI224_FIFO_SIZE
205 #define PCI224_FIFO_ROOM_ONETOHALF      (PCI224_FIFO_SIZE / 2)
206 #define PCI224_FIFO_ROOM_HALFTOFULL     1
207 #define PCI224_FIFO_ROOM_FULL           0
208
209 /*
210  * Counter/timer clock input configuration sources.
211  */
212 #define CLK_CLK         0       /* reserved (channel-specific clock) */
213 #define CLK_10MHZ       1       /* internal 10 MHz clock */
214 #define CLK_1MHZ        2       /* internal 1 MHz clock */
215 #define CLK_100KHZ      3       /* internal 100 kHz clock */
216 #define CLK_10KHZ       4       /* internal 10 kHz clock */
217 #define CLK_1KHZ        5       /* internal 1 kHz clock */
218 #define CLK_OUTNM1      6       /* output of channel-1 modulo total */
219 #define CLK_EXT         7       /* external clock */
220 /* Macro to construct clock input configuration register value. */
221 #define CLK_CONFIG(chan, src)   ((((chan) & 3) << 3) | ((src) & 7))
222 /* Timebases in ns. */
223 #define TIMEBASE_10MHZ          100
224 #define TIMEBASE_1MHZ           1000
225 #define TIMEBASE_100KHZ         10000
226 #define TIMEBASE_10KHZ          100000
227 #define TIMEBASE_1KHZ           1000000
228
229 /*
230  * Counter/timer gate input configuration sources.
231  */
232 #define GAT_VCC         0       /* VCC (i.e. enabled) */
233 #define GAT_GND         1       /* GND (i.e. disabled) */
234 #define GAT_EXT         2       /* reserved (external gate input) */
235 #define GAT_NOUTNM2     3       /* inverted output of channel-2 modulo total */
236 /* Macro to construct gate input configuration register value. */
237 #define GAT_CONFIG(chan, src)   ((((chan) & 3) << 3) | ((src) & 7))
238
239 /*
240  * Summary of CLK_OUTNM1 and GAT_NOUTNM2 connections for PCI224 and PCI234:
241  *
242  *              Channel's       Channel's
243  *              clock input     gate input
244  * Channel      CLK_OUTNM1      GAT_NOUTNM2
245  * -------      ----------      -----------
246  * Z2-CT0       Z2-CT2-OUT      /Z2-CT1-OUT
247  * Z2-CT1       Z2-CT0-OUT      /Z2-CT2-OUT
248  * Z2-CT2       Z2-CT1-OUT      /Z2-CT0-OUT
249  */
250
251 /*
252  * Interrupt enable/status bits
253  */
254 #define PCI224_INTR_EXT         0x01    /* rising edge on external input */
255 #define PCI224_INTR_DAC         0x04    /* DAC (FIFO) interrupt */
256 #define PCI224_INTR_Z2CT1       0x20    /* rising edge on Z2-CT1 output */
257
258 #define PCI224_INTR_EDGE_BITS   (PCI224_INTR_EXT | PCI224_INTR_Z2CT1)
259 #define PCI224_INTR_LEVEL_BITS  PCI224_INTR_DACFIFO
260
261 /*
262  * Handy macros.
263  */
264
265 /* Combine old and new bits. */
266 #define COMBINE(old, new, mask) (((old) & ~(mask)) | ((new) & (mask)))
267
268 /* Current CPU.  XXX should this be hard_smp_processor_id()? */
269 #define THISCPU         smp_processor_id()
270
271 /* State bits for use with atomic bit operations. */
272 #define AO_CMD_STARTED  0
273
274 /*
275  * Range tables.
276  */
277
278 /* The software selectable internal ranges for PCI224 (option[2] == 0). */
279 static const struct comedi_lrange range_pci224_internal = {
280         8,
281         {
282          BIP_RANGE(10),
283          BIP_RANGE(5),
284          BIP_RANGE(2.5),
285          BIP_RANGE(1.25),
286          UNI_RANGE(10),
287          UNI_RANGE(5),
288          UNI_RANGE(2.5),
289          UNI_RANGE(1.25),
290          }
291 };
292
293 static const unsigned short hwrange_pci224_internal[8] = {
294         PCI224_DACCON_POLAR_BI | PCI224_DACCON_VREF_10,
295         PCI224_DACCON_POLAR_BI | PCI224_DACCON_VREF_5,
296         PCI224_DACCON_POLAR_BI | PCI224_DACCON_VREF_2_5,
297         PCI224_DACCON_POLAR_BI | PCI224_DACCON_VREF_1_25,
298         PCI224_DACCON_POLAR_UNI | PCI224_DACCON_VREF_10,
299         PCI224_DACCON_POLAR_UNI | PCI224_DACCON_VREF_5,
300         PCI224_DACCON_POLAR_UNI | PCI224_DACCON_VREF_2_5,
301         PCI224_DACCON_POLAR_UNI | PCI224_DACCON_VREF_1_25,
302 };
303
304 /* The software selectable external ranges for PCI224 (option[2] == 1). */
305 static const struct comedi_lrange range_pci224_external = {
306         2,
307         {
308          RANGE_ext(-1, 1),      /* bipolar [-Vref,+Vref] */
309          RANGE_ext(0, 1),       /* unipolar [0,+Vref] */
310          }
311 };
312
313 static const unsigned short hwrange_pci224_external[2] = {
314         PCI224_DACCON_POLAR_BI,
315         PCI224_DACCON_POLAR_UNI,
316 };
317
318 /* The hardware selectable Vref*2 external range for PCI234
319  * (option[2] == 1, option[3+n] == 0). */
320 static const struct comedi_lrange range_pci234_ext2 = {
321         1,
322         {
323          RANGE_ext(-2, 2),
324          }
325 };
326
327 /* The hardware selectable Vref external range for PCI234
328  * (option[2] == 1, option[3+n] == 1). */
329 static const struct comedi_lrange range_pci234_ext = {
330         1,
331         {
332          RANGE_ext(-1, 1),
333          }
334 };
335
336 /* This serves for all the PCI234 ranges. */
337 static const unsigned short hwrange_pci234[1] = {
338         PCI224_DACCON_POLAR_BI, /* bipolar - hardware ignores it! */
339 };
340
341 /*
342  * Board descriptions.
343  */
344
345 enum pci224_model { any_model, pci224_model, pci234_model };
346
347 struct pci224_board {
348         const char *name;
349         unsigned short devid;
350         enum pci224_model model;
351         unsigned int ao_chans;
352         unsigned int ao_bits;
353 };
354
355 static const struct pci224_board pci224_boards[] = {
356         {
357          .name = "pci224",
358          .devid = PCI_DEVICE_ID_AMPLICON_PCI224,
359          .model = pci224_model,
360          .ao_chans = 16,
361          .ao_bits = 12,
362          },
363         {
364          .name = "pci234",
365          .devid = PCI_DEVICE_ID_AMPLICON_PCI234,
366          .model = pci234_model,
367          .ao_chans = 4,
368          .ao_bits = 16,
369          },
370         {
371          .name = DRIVER_NAME,
372          .devid = PCI_DEVICE_ID_INVALID,
373          .model = any_model,    /* wildcard */
374          },
375 };
376
377 /* this structure is for data unique to this hardware driver.  If
378    several hardware drivers keep similar information in this structure,
379    feel free to suggest moving the variable to the struct comedi_device struct.  */
380 struct pci224_private {
381         const unsigned short *hwrange;
382         unsigned long iobase1;
383         unsigned long state;
384         spinlock_t ao_spinlock;
385         unsigned int *ao_readback;
386         short *ao_scan_vals;
387         unsigned char *ao_scan_order;
388         int intr_cpuid;
389         short intr_running;
390         unsigned short daccon;
391         unsigned int cached_div1;
392         unsigned int cached_div2;
393         unsigned int ao_stop_count;
394         short ao_stop_continuous;
395         unsigned short ao_enab; /* max 16 channels so 'short' will do */
396         unsigned char intsce;
397 };
398
399 /*
400  * Called from the 'insn_write' function to perform a single write.
401  */
402 static void
403 pci224_ao_set_data(struct comedi_device *dev, int chan, int range,
404                    unsigned int data)
405 {
406         const struct pci224_board *thisboard = comedi_board(dev);
407         struct pci224_private *devpriv = dev->private;
408         unsigned short mangled;
409
410         /* Store unmangled data for readback. */
411         devpriv->ao_readback[chan] = data;
412         /* Enable the channel. */
413         outw(1 << chan, dev->iobase + PCI224_DACCEN);
414         /* Set range and reset FIFO. */
415         devpriv->daccon = COMBINE(devpriv->daccon, devpriv->hwrange[range],
416                                   (PCI224_DACCON_POLAR_MASK |
417                                    PCI224_DACCON_VREF_MASK));
418         outw(devpriv->daccon | PCI224_DACCON_FIFORESET,
419              dev->iobase + PCI224_DACCON);
420         /*
421          * Mangle the data.  The hardware expects:
422          * - bipolar: 16-bit 2's complement
423          * - unipolar: 16-bit unsigned
424          */
425         mangled = (unsigned short)data << (16 - thisboard->ao_bits);
426         if ((devpriv->daccon & PCI224_DACCON_POLAR_MASK) ==
427             PCI224_DACCON_POLAR_BI) {
428                 mangled ^= 0x8000;
429         }
430         /* Write mangled data to the FIFO. */
431         outw(mangled, dev->iobase + PCI224_DACDATA);
432         /* Trigger the conversion. */
433         inw(dev->iobase + PCI224_SOFTTRIG);
434 }
435
436 /*
437  * 'insn_write' function for AO subdevice.
438  */
439 static int
440 pci224_ao_insn_write(struct comedi_device *dev, struct comedi_subdevice *s,
441                      struct comedi_insn *insn, unsigned int *data)
442 {
443         int i;
444         int chan, range;
445
446         /* Unpack channel and range. */
447         chan = CR_CHAN(insn->chanspec);
448         range = CR_RANGE(insn->chanspec);
449
450         /* Writing a list of values to an AO channel is probably not
451          * very useful, but that's how the interface is defined. */
452         for (i = 0; i < insn->n; i++)
453                 pci224_ao_set_data(dev, chan, range, data[i]);
454
455         return i;
456 }
457
458 /*
459  * 'insn_read' function for AO subdevice.
460  *
461  * N.B. The value read will not be valid if the DAC channel has
462  * never been written successfully since the device was attached
463  * or since the channel has been used by an AO streaming write
464  * command.
465  */
466 static int
467 pci224_ao_insn_read(struct comedi_device *dev, struct comedi_subdevice *s,
468                     struct comedi_insn *insn, unsigned int *data)
469 {
470         struct pci224_private *devpriv = dev->private;
471         int i;
472         int chan;
473
474         chan = CR_CHAN(insn->chanspec);
475
476         for (i = 0; i < insn->n; i++)
477                 data[i] = devpriv->ao_readback[chan];
478
479
480         return i;
481 }
482
483 /*
484  * Just a wrapper for the inline function 'i8253_cascade_ns_to_timer'.
485  */
486 static void
487 pci224_cascade_ns_to_timer(int osc_base, unsigned int *d1, unsigned int *d2,
488                            unsigned int *nanosec, int round_mode)
489 {
490         i8253_cascade_ns_to_timer(osc_base, d1, d2, nanosec, round_mode);
491 }
492
493 /*
494  * Kills a command running on the AO subdevice.
495  */
496 static void pci224_ao_stop(struct comedi_device *dev,
497                            struct comedi_subdevice *s)
498 {
499         struct pci224_private *devpriv = dev->private;
500         unsigned long flags;
501
502         if (!test_and_clear_bit(AO_CMD_STARTED, &devpriv->state))
503                 return;
504
505
506         spin_lock_irqsave(&devpriv->ao_spinlock, flags);
507         /* Kill the interrupts. */
508         devpriv->intsce = 0;
509         outb(0, devpriv->iobase1 + PCI224_INT_SCE);
510         /*
511          * Interrupt routine may or may not be running.  We may or may not
512          * have been called from the interrupt routine (directly or
513          * indirectly via a comedi_events() callback routine).  It's highly
514          * unlikely that we've been called from some other interrupt routine
515          * but who knows what strange things coders get up to!
516          *
517          * If the interrupt routine is currently running, wait for it to
518          * finish, unless we appear to have been called via the interrupt
519          * routine.
520          */
521         while (devpriv->intr_running && devpriv->intr_cpuid != THISCPU) {
522                 spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
523                 spin_lock_irqsave(&devpriv->ao_spinlock, flags);
524         }
525         spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
526         /* Reconfigure DAC for insn_write usage. */
527         outw(0, dev->iobase + PCI224_DACCEN);   /* Disable channels. */
528         devpriv->daccon = COMBINE(devpriv->daccon,
529                                   PCI224_DACCON_TRIG_SW |
530                                   PCI224_DACCON_FIFOINTR_EMPTY,
531                                   PCI224_DACCON_TRIG_MASK |
532                                   PCI224_DACCON_FIFOINTR_MASK);
533         outw(devpriv->daccon | PCI224_DACCON_FIFORESET,
534              dev->iobase + PCI224_DACCON);
535 }
536
537 /*
538  * Handles start of acquisition for the AO subdevice.
539  */
540 static void pci224_ao_start(struct comedi_device *dev,
541                             struct comedi_subdevice *s)
542 {
543         struct pci224_private *devpriv = dev->private;
544         struct comedi_cmd *cmd = &s->async->cmd;
545         unsigned long flags;
546
547         set_bit(AO_CMD_STARTED, &devpriv->state);
548         if (!devpriv->ao_stop_continuous && devpriv->ao_stop_count == 0) {
549                 /* An empty acquisition! */
550                 pci224_ao_stop(dev, s);
551                 s->async->events |= COMEDI_CB_EOA;
552                 comedi_event(dev, s);
553         } else {
554                 /* Enable interrupts. */
555                 spin_lock_irqsave(&devpriv->ao_spinlock, flags);
556                 if (cmd->stop_src == TRIG_EXT)
557                         devpriv->intsce = PCI224_INTR_EXT | PCI224_INTR_DAC;
558                 else
559                         devpriv->intsce = PCI224_INTR_DAC;
560
561                 outb(devpriv->intsce, devpriv->iobase1 + PCI224_INT_SCE);
562                 spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
563         }
564 }
565
566 /*
567  * Handles interrupts from the DAC FIFO.
568  */
569 static void pci224_ao_handle_fifo(struct comedi_device *dev,
570                                   struct comedi_subdevice *s)
571 {
572         struct pci224_private *devpriv = dev->private;
573         struct comedi_cmd *cmd = &s->async->cmd;
574         unsigned int num_scans;
575         unsigned int room;
576         unsigned short dacstat;
577         unsigned int i, n;
578         unsigned int bytes_per_scan;
579
580         if (cmd->chanlist_len) {
581                 bytes_per_scan = cmd->chanlist_len * sizeof(short);
582         } else {
583                 /* Shouldn't get here! */
584                 bytes_per_scan = sizeof(short);
585         }
586         /* Determine number of scans available in buffer. */
587         num_scans = comedi_buf_read_n_available(s->async) / bytes_per_scan;
588         if (!devpriv->ao_stop_continuous) {
589                 /* Fixed number of scans. */
590                 if (num_scans > devpriv->ao_stop_count)
591                         num_scans = devpriv->ao_stop_count;
592
593         }
594
595         /* Determine how much room is in the FIFO (in samples). */
596         dacstat = inw(dev->iobase + PCI224_DACCON);
597         switch (dacstat & PCI224_DACCON_FIFOFL_MASK) {
598         case PCI224_DACCON_FIFOFL_EMPTY:
599                 room = PCI224_FIFO_ROOM_EMPTY;
600                 if (!devpriv->ao_stop_continuous && devpriv->ao_stop_count == 0) {
601                         /* FIFO empty at end of counted acquisition. */
602                         pci224_ao_stop(dev, s);
603                         s->async->events |= COMEDI_CB_EOA;
604                         comedi_event(dev, s);
605                         return;
606                 }
607                 break;
608         case PCI224_DACCON_FIFOFL_ONETOHALF:
609                 room = PCI224_FIFO_ROOM_ONETOHALF;
610                 break;
611         case PCI224_DACCON_FIFOFL_HALFTOFULL:
612                 room = PCI224_FIFO_ROOM_HALFTOFULL;
613                 break;
614         default:
615                 room = PCI224_FIFO_ROOM_FULL;
616                 break;
617         }
618         if (room >= PCI224_FIFO_ROOM_ONETOHALF) {
619                 /* FIFO is less than half-full. */
620                 if (num_scans == 0) {
621                         /* Nothing left to put in the FIFO. */
622                         pci224_ao_stop(dev, s);
623                         s->async->events |= COMEDI_CB_OVERFLOW;
624                         dev_err(dev->class_dev, "AO buffer underrun\n");
625                 }
626         }
627         /* Determine how many new scans can be put in the FIFO. */
628         if (cmd->chanlist_len)
629                 room /= cmd->chanlist_len;
630
631         /* Determine how many scans to process. */
632         if (num_scans > room)
633                 num_scans = room;
634
635         /* Process scans. */
636         for (n = 0; n < num_scans; n++) {
637                 cfc_read_array_from_buffer(s, &devpriv->ao_scan_vals[0],
638                                            bytes_per_scan);
639                 for (i = 0; i < cmd->chanlist_len; i++) {
640                         outw(devpriv->ao_scan_vals[devpriv->ao_scan_order[i]],
641                              dev->iobase + PCI224_DACDATA);
642                 }
643         }
644         if (!devpriv->ao_stop_continuous) {
645                 devpriv->ao_stop_count -= num_scans;
646                 if (devpriv->ao_stop_count == 0) {
647                         /*
648                          * Change FIFO interrupt trigger level to wait
649                          * until FIFO is empty.
650                          */
651                         devpriv->daccon = COMBINE(devpriv->daccon,
652                                                   PCI224_DACCON_FIFOINTR_EMPTY,
653                                                   PCI224_DACCON_FIFOINTR_MASK);
654                         outw(devpriv->daccon, dev->iobase + PCI224_DACCON);
655                 }
656         }
657         if ((devpriv->daccon & PCI224_DACCON_TRIG_MASK) ==
658             PCI224_DACCON_TRIG_NONE) {
659                 unsigned short trig;
660
661                 /*
662                  * This is the initial DAC FIFO interrupt at the
663                  * start of the acquisition.  The DAC's scan trigger
664                  * has been set to 'none' up until now.
665                  *
666                  * Now that data has been written to the FIFO, the
667                  * DAC's scan trigger source can be set to the
668                  * correct value.
669                  *
670                  * BUG: The first scan will be triggered immediately
671                  * if the scan trigger source is at logic level 1.
672                  */
673                 if (cmd->scan_begin_src == TRIG_TIMER) {
674                         trig = PCI224_DACCON_TRIG_Z2CT0;
675                 } else {
676                         /* cmd->scan_begin_src == TRIG_EXT */
677                         if (cmd->scan_begin_arg & CR_INVERT)
678                                 trig = PCI224_DACCON_TRIG_EXTN;
679                         else
680                                 trig = PCI224_DACCON_TRIG_EXTP;
681
682                 }
683                 devpriv->daccon = COMBINE(devpriv->daccon, trig,
684                                           PCI224_DACCON_TRIG_MASK);
685                 outw(devpriv->daccon, dev->iobase + PCI224_DACCON);
686         }
687         if (s->async->events)
688                 comedi_event(dev, s);
689
690 }
691
692 /*
693  * Internal trigger function to start acquisition on AO subdevice.
694  */
695 static int
696 pci224_ao_inttrig_start(struct comedi_device *dev, struct comedi_subdevice *s,
697                         unsigned int trignum)
698 {
699         if (trignum != 0)
700                 return -EINVAL;
701
702         s->async->inttrig = NULL;
703         pci224_ao_start(dev, s);
704
705         return 1;
706 }
707
708 #define MAX_SCAN_PERIOD         0xFFFFFFFFU
709 #define MIN_SCAN_PERIOD         2500
710 #define CONVERT_PERIOD          625
711
712 /*
713  * 'do_cmdtest' function for AO subdevice.
714  */
715 static int
716 pci224_ao_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
717                   struct comedi_cmd *cmd)
718 {
719         struct pci224_private *devpriv = dev->private;
720         int err = 0;
721         unsigned int tmp;
722
723         /* Step 1 : check if triggers are trivially valid */
724
725         err |= cfc_check_trigger_src(&cmd->start_src, TRIG_INT | TRIG_EXT);
726         err |= cfc_check_trigger_src(&cmd->scan_begin_src,
727                                         TRIG_EXT | TRIG_TIMER);
728         err |= cfc_check_trigger_src(&cmd->convert_src, TRIG_NOW);
729         err |= cfc_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
730         err |= cfc_check_trigger_src(&cmd->stop_src,
731                                         TRIG_COUNT | TRIG_EXT | TRIG_NONE);
732
733         if (err)
734                 return 1;
735
736         /* Step 2a : make sure trigger sources are unique */
737
738         err |= cfc_check_trigger_is_unique(cmd->start_src);
739         err |= cfc_check_trigger_is_unique(cmd->scan_begin_src);
740         err |= cfc_check_trigger_is_unique(cmd->stop_src);
741
742         /* Step 2b : and mutually compatible */
743
744         /*
745          * There's only one external trigger signal (which makes these
746          * tests easier).  Only one thing can use it.
747          */
748         tmp = 0;
749         if (cmd->start_src & TRIG_EXT)
750                 tmp++;
751         if (cmd->scan_begin_src & TRIG_EXT)
752                 tmp++;
753         if (cmd->stop_src & TRIG_EXT)
754                 tmp++;
755         if (tmp > 1)
756                 err |= -EINVAL;
757
758         if (err)
759                 return 2;
760
761         /* Step 3: check if arguments are trivially valid */
762
763         switch (cmd->start_src) {
764         case TRIG_INT:
765                 err |= cfc_check_trigger_arg_is(&cmd->start_arg, 0);
766                 break;
767         case TRIG_EXT:
768                 /* Force to external trigger 0. */
769                 if ((cmd->start_arg & ~CR_FLAGS_MASK) != 0) {
770                         cmd->start_arg = COMBINE(cmd->start_arg, 0,
771                                                  ~CR_FLAGS_MASK);
772                         err |= -EINVAL;
773                 }
774                 /* The only flag allowed is CR_EDGE, which is ignored. */
775                 if ((cmd->start_arg & CR_FLAGS_MASK & ~CR_EDGE) != 0) {
776                         cmd->start_arg = COMBINE(cmd->start_arg, 0,
777                                                  CR_FLAGS_MASK & ~CR_EDGE);
778                         err |= -EINVAL;
779                 }
780                 break;
781         }
782
783         switch (cmd->scan_begin_src) {
784         case TRIG_TIMER:
785                 err |= cfc_check_trigger_arg_max(&cmd->scan_begin_arg,
786                                                  MAX_SCAN_PERIOD);
787
788                 tmp = cmd->chanlist_len * CONVERT_PERIOD;
789                 if (tmp < MIN_SCAN_PERIOD)
790                         tmp = MIN_SCAN_PERIOD;
791                 err |= cfc_check_trigger_arg_min(&cmd->scan_begin_arg, tmp);
792                 break;
793         case TRIG_EXT:
794                 /* Force to external trigger 0. */
795                 if ((cmd->scan_begin_arg & ~CR_FLAGS_MASK) != 0) {
796                         cmd->scan_begin_arg = COMBINE(cmd->scan_begin_arg, 0,
797                                                       ~CR_FLAGS_MASK);
798                         err |= -EINVAL;
799                 }
800                 /* Only allow flags CR_EDGE and CR_INVERT.  Ignore CR_EDGE. */
801                 if ((cmd->scan_begin_arg & CR_FLAGS_MASK &
802                      ~(CR_EDGE | CR_INVERT)) != 0) {
803                         cmd->scan_begin_arg = COMBINE(cmd->scan_begin_arg, 0,
804                                                       CR_FLAGS_MASK &
805                                                       ~(CR_EDGE | CR_INVERT));
806                         err |= -EINVAL;
807                 }
808                 break;
809         }
810
811         err |= cfc_check_trigger_arg_is(&cmd->convert_arg, 0);
812         err |= cfc_check_trigger_arg_is(&cmd->scan_end_arg, cmd->chanlist_len);
813
814         switch (cmd->stop_src) {
815         case TRIG_COUNT:
816                 /* Any count allowed. */
817                 break;
818         case TRIG_EXT:
819                 /* Force to external trigger 0. */
820                 if ((cmd->stop_arg & ~CR_FLAGS_MASK) != 0) {
821                         cmd->stop_arg = COMBINE(cmd->stop_arg, 0,
822                                                 ~CR_FLAGS_MASK);
823                         err |= -EINVAL;
824                 }
825                 /* The only flag allowed is CR_EDGE, which is ignored. */
826                 if ((cmd->stop_arg & CR_FLAGS_MASK & ~CR_EDGE) != 0) {
827                         cmd->stop_arg = COMBINE(cmd->stop_arg, 0,
828                                                 CR_FLAGS_MASK & ~CR_EDGE);
829                 }
830                 break;
831         case TRIG_NONE:
832                 err |= cfc_check_trigger_arg_is(&cmd->stop_arg, 0);
833                 break;
834         }
835
836         if (err)
837                 return 3;
838
839         /* Step 4: fix up any arguments. */
840
841         if (cmd->scan_begin_src == TRIG_TIMER) {
842                 unsigned int div1, div2, round;
843                 int round_mode = cmd->flags & TRIG_ROUND_MASK;
844
845                 tmp = cmd->scan_begin_arg;
846                 /* Check whether to use a single timer. */
847                 switch (round_mode) {
848                 case TRIG_ROUND_NEAREST:
849                 default:
850                         round = TIMEBASE_10MHZ / 2;
851                         break;
852                 case TRIG_ROUND_DOWN:
853                         round = 0;
854                         break;
855                 case TRIG_ROUND_UP:
856                         round = TIMEBASE_10MHZ - 1;
857                         break;
858                 }
859                 /* Be careful to avoid overflow! */
860                 div2 = cmd->scan_begin_arg / TIMEBASE_10MHZ;
861                 div2 += (round + cmd->scan_begin_arg % TIMEBASE_10MHZ) /
862                     TIMEBASE_10MHZ;
863                 if (div2 <= 0x10000) {
864                         /* A single timer will suffice. */
865                         if (div2 < 2)
866                                 div2 = 2;
867                         cmd->scan_begin_arg = div2 * TIMEBASE_10MHZ;
868                         if (cmd->scan_begin_arg < div2 ||
869                             cmd->scan_begin_arg < TIMEBASE_10MHZ) {
870                                 /* Overflow! */
871                                 cmd->scan_begin_arg = MAX_SCAN_PERIOD;
872                         }
873                 } else {
874                         /* Use two timers. */
875                         div1 = devpriv->cached_div1;
876                         div2 = devpriv->cached_div2;
877                         pci224_cascade_ns_to_timer(TIMEBASE_10MHZ, &div1, &div2,
878                                                    &cmd->scan_begin_arg,
879                                                    round_mode);
880                         devpriv->cached_div1 = div1;
881                         devpriv->cached_div2 = div2;
882                 }
883                 if (tmp != cmd->scan_begin_arg)
884                         err++;
885
886         }
887
888         if (err)
889                 return 4;
890
891         /* Step 5: check channel list. */
892
893         if (cmd->chanlist && (cmd->chanlist_len > 0)) {
894                 unsigned int range;
895                 enum { range_err = 1, dupchan_err = 2, };
896                 unsigned errors;
897                 unsigned int n;
898                 unsigned int ch;
899
900                 /*
901                  * Check all channels have the same range index.  Don't care
902                  * about analogue reference, as we can't configure it.
903                  *
904                  * Check the list has no duplicate channels.
905                  */
906                 range = CR_RANGE(cmd->chanlist[0]);
907                 errors = 0;
908                 tmp = 0;
909                 for (n = 0; n < cmd->chanlist_len; n++) {
910                         ch = CR_CHAN(cmd->chanlist[n]);
911                         if (tmp & (1U << ch))
912                                 errors |= dupchan_err;
913
914                         tmp |= (1U << ch);
915                         if (CR_RANGE(cmd->chanlist[n]) != range)
916                                 errors |= range_err;
917
918                 }
919                 if (errors) {
920                         if (errors & dupchan_err) {
921                                 DPRINTK("comedi%d: " DRIVER_NAME
922                                         ": ao_cmdtest: "
923                                         "entries in chanlist must contain no "
924                                         "duplicate channels\n", dev->minor);
925                         }
926                         if (errors & range_err) {
927                                 DPRINTK("comedi%d: " DRIVER_NAME
928                                         ": ao_cmdtest: "
929                                         "entries in chanlist must all have "
930                                         "the same range index\n", dev->minor);
931                         }
932                         err++;
933                 }
934         }
935
936         if (err)
937                 return 5;
938
939         return 0;
940 }
941
942 /*
943  * 'do_cmd' function for AO subdevice.
944  */
945 static int pci224_ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
946 {
947         struct pci224_private *devpriv = dev->private;
948         struct comedi_cmd *cmd = &s->async->cmd;
949         int range;
950         unsigned int i, j;
951         unsigned int ch;
952         unsigned int rank;
953         unsigned long flags;
954
955         /* Cannot handle null/empty chanlist. */
956         if (cmd->chanlist == NULL || cmd->chanlist_len == 0)
957                 return -EINVAL;
958
959
960         /* Determine which channels are enabled and their load order.  */
961         devpriv->ao_enab = 0;
962
963         for (i = 0; i < cmd->chanlist_len; i++) {
964                 ch = CR_CHAN(cmd->chanlist[i]);
965                 devpriv->ao_enab |= 1U << ch;
966                 rank = 0;
967                 for (j = 0; j < cmd->chanlist_len; j++) {
968                         if (CR_CHAN(cmd->chanlist[j]) < ch)
969                                 rank++;
970
971                 }
972                 devpriv->ao_scan_order[rank] = i;
973         }
974
975         /* Set enabled channels. */
976         outw(devpriv->ao_enab, dev->iobase + PCI224_DACCEN);
977
978         /* Determine range and polarity.  All channels the same.  */
979         range = CR_RANGE(cmd->chanlist[0]);
980
981         /*
982          * Set DAC range and polarity.
983          * Set DAC scan trigger source to 'none'.
984          * Set DAC FIFO interrupt trigger level to 'not half full'.
985          * Reset DAC FIFO.
986          *
987          * N.B. DAC FIFO interrupts are currently disabled.
988          */
989         devpriv->daccon = COMBINE(devpriv->daccon,
990                                   (devpriv->
991                                    hwrange[range] | PCI224_DACCON_TRIG_NONE |
992                                    PCI224_DACCON_FIFOINTR_NHALF),
993                                   (PCI224_DACCON_POLAR_MASK |
994                                    PCI224_DACCON_VREF_MASK |
995                                    PCI224_DACCON_TRIG_MASK |
996                                    PCI224_DACCON_FIFOINTR_MASK));
997         outw(devpriv->daccon | PCI224_DACCON_FIFORESET,
998              dev->iobase + PCI224_DACCON);
999
1000         if (cmd->scan_begin_src == TRIG_TIMER) {
1001                 unsigned int div1, div2, round;
1002                 unsigned int ns = cmd->scan_begin_arg;
1003                 int round_mode = cmd->flags & TRIG_ROUND_MASK;
1004
1005                 /* Check whether to use a single timer. */
1006                 switch (round_mode) {
1007                 case TRIG_ROUND_NEAREST:
1008                 default:
1009                         round = TIMEBASE_10MHZ / 2;
1010                         break;
1011                 case TRIG_ROUND_DOWN:
1012                         round = 0;
1013                         break;
1014                 case TRIG_ROUND_UP:
1015                         round = TIMEBASE_10MHZ - 1;
1016                         break;
1017                 }
1018                 /* Be careful to avoid overflow! */
1019                 div2 = cmd->scan_begin_arg / TIMEBASE_10MHZ;
1020                 div2 += (round + cmd->scan_begin_arg % TIMEBASE_10MHZ) /
1021                     TIMEBASE_10MHZ;
1022                 if (div2 <= 0x10000) {
1023                         /* A single timer will suffice. */
1024                         if (div2 < 2)
1025                                 div2 = 2;
1026                         div2 &= 0xffff;
1027                         div1 = 1;       /* Flag that single timer to be used. */
1028                 } else {
1029                         /* Use two timers. */
1030                         div1 = devpriv->cached_div1;
1031                         div2 = devpriv->cached_div2;
1032                         pci224_cascade_ns_to_timer(TIMEBASE_10MHZ, &div1, &div2,
1033                                                    &ns, round_mode);
1034                 }
1035
1036                 /*
1037                  * The output of timer Z2-0 will be used as the scan trigger
1038                  * source.
1039                  */
1040                 /* Make sure Z2-0 is gated on.  */
1041                 outb(GAT_CONFIG(0, GAT_VCC),
1042                      devpriv->iobase1 + PCI224_ZGAT_SCE);
1043                 if (div1 == 1) {
1044                         /* Not cascading.  Z2-0 needs 10 MHz clock. */
1045                         outb(CLK_CONFIG(0, CLK_10MHZ),
1046                              devpriv->iobase1 + PCI224_ZCLK_SCE);
1047                 } else {
1048                         /* Cascading with Z2-2. */
1049                         /* Make sure Z2-2 is gated on.  */
1050                         outb(GAT_CONFIG(2, GAT_VCC),
1051                              devpriv->iobase1 + PCI224_ZGAT_SCE);
1052                         /* Z2-2 needs 10 MHz clock. */
1053                         outb(CLK_CONFIG(2, CLK_10MHZ),
1054                              devpriv->iobase1 + PCI224_ZCLK_SCE);
1055                         /* Load Z2-2 mode (2) and counter (div1). */
1056                         i8254_load(devpriv->iobase1 + PCI224_Z2_CT0, 0,
1057                                    2, div1, 2);
1058                         /* Z2-0 is clocked from Z2-2's output. */
1059                         outb(CLK_CONFIG(0, CLK_OUTNM1),
1060                              devpriv->iobase1 + PCI224_ZCLK_SCE);
1061                 }
1062                 /* Load Z2-0 mode (2) and counter (div2). */
1063                 i8254_load(devpriv->iobase1 + PCI224_Z2_CT0, 0, 0, div2, 2);
1064         }
1065
1066         /*
1067          * Sort out end of acquisition.
1068          */
1069         switch (cmd->stop_src) {
1070         case TRIG_COUNT:
1071                 /* Fixed number of scans.  */
1072                 devpriv->ao_stop_continuous = 0;
1073                 devpriv->ao_stop_count = cmd->stop_arg;
1074                 break;
1075         default:
1076                 /* Continuous scans. */
1077                 devpriv->ao_stop_continuous = 1;
1078                 devpriv->ao_stop_count = 0;
1079                 break;
1080         }
1081
1082         /*
1083          * Sort out start of acquisition.
1084          */
1085         switch (cmd->start_src) {
1086         case TRIG_INT:
1087                 spin_lock_irqsave(&devpriv->ao_spinlock, flags);
1088                 s->async->inttrig = &pci224_ao_inttrig_start;
1089                 spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
1090                 break;
1091         case TRIG_EXT:
1092                 /* Enable external interrupt trigger to start acquisition. */
1093                 spin_lock_irqsave(&devpriv->ao_spinlock, flags);
1094                 devpriv->intsce |= PCI224_INTR_EXT;
1095                 outb(devpriv->intsce, devpriv->iobase1 + PCI224_INT_SCE);
1096                 spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
1097                 break;
1098         }
1099
1100         return 0;
1101 }
1102
1103 /*
1104  * 'cancel' function for AO subdevice.
1105  */
1106 static int pci224_ao_cancel(struct comedi_device *dev,
1107                             struct comedi_subdevice *s)
1108 {
1109         pci224_ao_stop(dev, s);
1110         return 0;
1111 }
1112
1113 /*
1114  * 'munge' data for AO command.
1115  */
1116 static void
1117 pci224_ao_munge(struct comedi_device *dev, struct comedi_subdevice *s,
1118                 void *data, unsigned int num_bytes, unsigned int chan_index)
1119 {
1120         const struct pci224_board *thisboard = comedi_board(dev);
1121         struct pci224_private *devpriv = dev->private;
1122         struct comedi_async *async = s->async;
1123         short *array = data;
1124         unsigned int length = num_bytes / sizeof(*array);
1125         unsigned int offset;
1126         unsigned int shift;
1127         unsigned int i;
1128
1129         /* The hardware expects 16-bit numbers. */
1130         shift = 16 - thisboard->ao_bits;
1131         /* Channels will be all bipolar or all unipolar. */
1132         if ((devpriv->hwrange[CR_RANGE(async->cmd.chanlist[0])] &
1133              PCI224_DACCON_POLAR_MASK) == PCI224_DACCON_POLAR_UNI) {
1134                 /* Unipolar */
1135                 offset = 0;
1136         } else {
1137                 /* Bipolar */
1138                 offset = 32768;
1139         }
1140         /* Munge the data. */
1141         for (i = 0; i < length; i++)
1142                 array[i] = (array[i] << shift) - offset;
1143
1144 }
1145
1146 /*
1147  * Interrupt handler.
1148  */
1149 static irqreturn_t pci224_interrupt(int irq, void *d)
1150 {
1151         struct comedi_device *dev = d;
1152         struct pci224_private *devpriv = dev->private;
1153         struct comedi_subdevice *s = &dev->subdevices[0];
1154         struct comedi_cmd *cmd;
1155         unsigned char intstat, valid_intstat;
1156         unsigned char curenab;
1157         int retval = 0;
1158         unsigned long flags;
1159
1160         intstat = inb(devpriv->iobase1 + PCI224_INT_SCE) & 0x3F;
1161         if (intstat) {
1162                 retval = 1;
1163                 spin_lock_irqsave(&devpriv->ao_spinlock, flags);
1164                 valid_intstat = devpriv->intsce & intstat;
1165                 /* Temporarily disable interrupt sources. */
1166                 curenab = devpriv->intsce & ~intstat;
1167                 outb(curenab, devpriv->iobase1 + PCI224_INT_SCE);
1168                 devpriv->intr_running = 1;
1169                 devpriv->intr_cpuid = THISCPU;
1170                 spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
1171                 if (valid_intstat != 0) {
1172                         cmd = &s->async->cmd;
1173                         if (valid_intstat & PCI224_INTR_EXT) {
1174                                 devpriv->intsce &= ~PCI224_INTR_EXT;
1175                                 if (cmd->start_src == TRIG_EXT)
1176                                         pci224_ao_start(dev, s);
1177                                 else if (cmd->stop_src == TRIG_EXT)
1178                                         pci224_ao_stop(dev, s);
1179
1180                         }
1181                         if (valid_intstat & PCI224_INTR_DAC)
1182                                 pci224_ao_handle_fifo(dev, s);
1183
1184                 }
1185                 /* Reenable interrupt sources. */
1186                 spin_lock_irqsave(&devpriv->ao_spinlock, flags);
1187                 if (curenab != devpriv->intsce) {
1188                         outb(devpriv->intsce,
1189                              devpriv->iobase1 + PCI224_INT_SCE);
1190                 }
1191                 devpriv->intr_running = 0;
1192                 spin_unlock_irqrestore(&devpriv->ao_spinlock, flags);
1193         }
1194         return IRQ_RETVAL(retval);
1195 }
1196
1197 /*
1198  * This function looks for a board matching the supplied PCI device.
1199  */
1200 static const struct pci224_board
1201 *pci224_find_pci_board(struct pci_dev *pci_dev)
1202 {
1203         int i;
1204
1205         for (i = 0; i < ARRAY_SIZE(pci224_boards); i++)
1206                 if (pci_dev->device == pci224_boards[i].devid)
1207                         return &pci224_boards[i];
1208         return NULL;
1209 }
1210
1211 /*
1212  * This function looks for a PCI device matching the requested board name,
1213  * bus and slot.
1214  */
1215 static struct pci_dev *pci224_find_pci_dev(struct comedi_device *dev,
1216                                            struct comedi_devconfig *it)
1217 {
1218         const struct pci224_board *thisboard = comedi_board(dev);
1219         struct pci_dev *pci_dev = NULL;
1220         int bus = it->options[0];
1221         int slot = it->options[1];
1222
1223         for_each_pci_dev(pci_dev) {
1224                 if (bus || slot) {
1225                         if (bus != pci_dev->bus->number ||
1226                             slot != PCI_SLOT(pci_dev->devfn))
1227                                 continue;
1228                 }
1229                 if (pci_dev->vendor != PCI_VENDOR_ID_AMPLICON)
1230                         continue;
1231
1232                 if (thisboard->model == any_model) {
1233                         /* Match any supported model. */
1234                         const struct pci224_board *board_ptr;
1235
1236                         board_ptr = pci224_find_pci_board(pci_dev);
1237                         if (board_ptr == NULL)
1238                                 continue;
1239                         /* Change board_ptr to matched board. */
1240                         dev->board_ptr = board_ptr;
1241                 } else {
1242                         /* Match specific model name. */
1243                         if (thisboard->devid != pci_dev->device)
1244                                 continue;
1245                 }
1246                 return pci_dev;
1247         }
1248         dev_err(dev->class_dev,
1249                 "No supported board found! (req. bus %d, slot %d)\n",
1250                 bus, slot);
1251         return NULL;
1252 }
1253
1254 static void pci224_report_attach(struct comedi_device *dev, unsigned int irq)
1255 {
1256         struct pci_dev *pcidev = comedi_to_pci_dev(dev);
1257         char tmpbuf[30];
1258
1259         if (irq)
1260                 snprintf(tmpbuf, sizeof(tmpbuf), "irq %u%s", irq,
1261                          (dev->irq ? "" : " UNAVAILABLE"));
1262         else
1263                 snprintf(tmpbuf, sizeof(tmpbuf), "no irq");
1264         dev_info(dev->class_dev, "%s (pci %s) (%s) attached\n",
1265                  dev->board_name, pci_name(pcidev), tmpbuf);
1266 }
1267
1268 /*
1269  * Common part of attach and auto_attach.
1270  */
1271 static int pci224_attach_common(struct comedi_device *dev,
1272                                 struct pci_dev *pci_dev, int *options)
1273 {
1274         const struct pci224_board *thisboard = comedi_board(dev);
1275         struct pci224_private *devpriv = dev->private;
1276         struct comedi_subdevice *s;
1277         unsigned int irq;
1278         unsigned n;
1279         int ret;
1280
1281         comedi_set_hw_dev(dev, &pci_dev->dev);
1282
1283         ret = comedi_pci_enable(dev);
1284         if (ret)
1285                 return ret;
1286
1287         spin_lock_init(&devpriv->ao_spinlock);
1288
1289         devpriv->iobase1 = pci_resource_start(pci_dev, 2);
1290         dev->iobase = pci_resource_start(pci_dev, 3);
1291         irq = pci_dev->irq;
1292
1293         /* Allocate readback buffer for AO channels. */
1294         devpriv->ao_readback = kmalloc(sizeof(devpriv->ao_readback[0]) *
1295                                        thisboard->ao_chans, GFP_KERNEL);
1296         if (!devpriv->ao_readback)
1297                 return -ENOMEM;
1298
1299
1300         /* Allocate buffer to hold values for AO channel scan. */
1301         devpriv->ao_scan_vals = kmalloc(sizeof(devpriv->ao_scan_vals[0]) *
1302                                         thisboard->ao_chans, GFP_KERNEL);
1303         if (!devpriv->ao_scan_vals)
1304                 return -ENOMEM;
1305
1306
1307         /* Allocate buffer to hold AO channel scan order. */
1308         devpriv->ao_scan_order = kmalloc(sizeof(devpriv->ao_scan_order[0]) *
1309                                          thisboard->ao_chans, GFP_KERNEL);
1310         if (!devpriv->ao_scan_order)
1311                 return -ENOMEM;
1312
1313
1314         /* Disable interrupt sources. */
1315         devpriv->intsce = 0;
1316         outb(0, devpriv->iobase1 + PCI224_INT_SCE);
1317
1318         /* Initialize the DAC hardware. */
1319         outw(PCI224_DACCON_GLOBALRESET, dev->iobase + PCI224_DACCON);
1320         outw(0, dev->iobase + PCI224_DACCEN);
1321         outw(0, dev->iobase + PCI224_FIFOSIZ);
1322         devpriv->daccon = (PCI224_DACCON_TRIG_SW | PCI224_DACCON_POLAR_BI |
1323                            PCI224_DACCON_FIFOENAB |
1324                            PCI224_DACCON_FIFOINTR_EMPTY);
1325         outw(devpriv->daccon | PCI224_DACCON_FIFORESET,
1326              dev->iobase + PCI224_DACCON);
1327
1328         ret = comedi_alloc_subdevices(dev, 1);
1329         if (ret)
1330                 return ret;
1331
1332         s = &dev->subdevices[0];
1333         /* Analog output subdevice. */
1334         s->type = COMEDI_SUBD_AO;
1335         s->subdev_flags = SDF_WRITABLE | SDF_GROUND | SDF_CMD_WRITE;
1336         s->n_chan = thisboard->ao_chans;
1337         s->maxdata = (1 << thisboard->ao_bits) - 1;
1338         s->insn_write = &pci224_ao_insn_write;
1339         s->insn_read = &pci224_ao_insn_read;
1340         s->len_chanlist = s->n_chan;
1341
1342         dev->write_subdev = s;
1343         s->do_cmd = &pci224_ao_cmd;
1344         s->do_cmdtest = &pci224_ao_cmdtest;
1345         s->cancel = &pci224_ao_cancel;
1346         s->munge = &pci224_ao_munge;
1347
1348         /* Sort out channel range options. */
1349         if (thisboard->model == pci234_model) {
1350                 /* PCI234 range options. */
1351                 const struct comedi_lrange **range_table_list;
1352
1353                 s->range_table_list = range_table_list =
1354                     kmalloc(sizeof(struct comedi_lrange *) * s->n_chan,
1355                             GFP_KERNEL);
1356                 if (!s->range_table_list)
1357                         return -ENOMEM;
1358
1359                 if (options) {
1360                         for (n = 2; n < 3 + s->n_chan; n++) {
1361                                 if (options[n] < 0 || options[n] > 1) {
1362                                         dev_warn(dev->class_dev, DRIVER_NAME
1363                                                  ": warning! bad options[%u]=%d\n",
1364                                                  n, options[n]);
1365                                 }
1366                         }
1367                 }
1368                 for (n = 0; n < s->n_chan; n++) {
1369                         if (n < COMEDI_NDEVCONFOPTS - 3 && options &&
1370                             options[3 + n] == 1) {
1371                                 if (options[2] == 1)
1372                                         range_table_list[n] = &range_pci234_ext;
1373                                 else
1374                                         range_table_list[n] = &range_bipolar5;
1375
1376                         } else {
1377                                 if (options && options[2] == 1) {
1378                                         range_table_list[n] =
1379                                             &range_pci234_ext2;
1380                                 } else {
1381                                         range_table_list[n] = &range_bipolar10;
1382                                 }
1383                         }
1384                 }
1385                 devpriv->hwrange = hwrange_pci234;
1386         } else {
1387                 /* PCI224 range options. */
1388                 if (options && options[2] == 1) {
1389                         s->range_table = &range_pci224_external;
1390                         devpriv->hwrange = hwrange_pci224_external;
1391                 } else {
1392                         if (options && options[2] != 0) {
1393                                 dev_warn(dev->class_dev, DRIVER_NAME
1394                                          ": warning! bad options[2]=%d\n",
1395                                          options[2]);
1396                         }
1397                         s->range_table = &range_pci224_internal;
1398                         devpriv->hwrange = hwrange_pci224_internal;
1399                 }
1400         }
1401
1402         dev->board_name = thisboard->name;
1403
1404         if (irq) {
1405                 ret = request_irq(irq, pci224_interrupt, IRQF_SHARED,
1406                                   DRIVER_NAME, dev);
1407                 if (ret < 0) {
1408                         dev_err(dev->class_dev,
1409                                 "error! unable to allocate irq %u\n", irq);
1410                         return ret;
1411                 } else {
1412                         dev->irq = irq;
1413                 }
1414         }
1415
1416         pci224_report_attach(dev, irq);
1417         return 1;
1418 }
1419
1420 static int pci224_attach(struct comedi_device *dev, struct comedi_devconfig *it)
1421 {
1422         struct pci224_private *devpriv;
1423         struct pci_dev *pci_dev;
1424
1425         dev_info(dev->class_dev, DRIVER_NAME ": attach\n");
1426
1427         devpriv = kzalloc(sizeof(*devpriv), GFP_KERNEL);
1428         if (!devpriv)
1429                 return -ENOMEM;
1430         dev->private = devpriv;
1431
1432         pci_dev = pci224_find_pci_dev(dev, it);
1433         if (!pci_dev)
1434                 return -EIO;
1435
1436         return pci224_attach_common(dev, pci_dev, it->options);
1437 }
1438
1439 static int
1440 pci224_auto_attach(struct comedi_device *dev, unsigned long context_unused)
1441 {
1442         struct pci_dev *pci_dev = comedi_to_pci_dev(dev);
1443         struct pci224_private *devpriv;
1444
1445         dev_info(dev->class_dev, DRIVER_NAME ": attach pci %s\n",
1446                  pci_name(pci_dev));
1447
1448         devpriv = kzalloc(sizeof(*devpriv), GFP_KERNEL);
1449         if (!devpriv)
1450                 return -ENOMEM;
1451         dev->private = devpriv;
1452
1453         dev->board_ptr = pci224_find_pci_board(pci_dev);
1454         if (dev->board_ptr == NULL) {
1455                 dev_err(dev->class_dev,
1456                         DRIVER_NAME ": BUG! cannot determine board type!\n");
1457                 return -EINVAL;
1458         }
1459         /*
1460          * Need to 'get' the PCI device to match the 'put' in pci224_detach().
1461          * TODO: Remove the pci_dev_get() and matching pci_dev_put() once
1462          * support for manual attachment of PCI devices via pci224_attach()
1463          * has been removed.
1464          */
1465         pci_dev_get(pci_dev);
1466         return pci224_attach_common(dev, pci_dev, NULL);
1467 }
1468
1469 static void pci224_detach(struct comedi_device *dev)
1470 {
1471         struct pci224_private *devpriv = dev->private;
1472         struct pci_dev *pcidev = comedi_to_pci_dev(dev);
1473
1474         if (dev->irq)
1475                 free_irq(dev->irq, dev);
1476         if (dev->subdevices) {
1477                 struct comedi_subdevice *s;
1478
1479                 s = &dev->subdevices[0];
1480                 /* AO subdevice */
1481                 kfree(s->range_table_list);
1482         }
1483         if (devpriv) {
1484                 kfree(devpriv->ao_readback);
1485                 kfree(devpriv->ao_scan_vals);
1486                 kfree(devpriv->ao_scan_order);
1487         }
1488         comedi_pci_disable(dev);
1489         if (pcidev)
1490                 pci_dev_put(pcidev);
1491 }
1492
1493 static struct comedi_driver amplc_pci224_driver = {
1494         .driver_name    = "amplc_pci224",
1495         .module         = THIS_MODULE,
1496         .attach         = pci224_attach,
1497         .detach         = pci224_detach,
1498         .auto_attach    = pci224_auto_attach,
1499         .board_name     = &pci224_boards[0].name,
1500         .offset         = sizeof(struct pci224_board),
1501         .num_names      = ARRAY_SIZE(pci224_boards),
1502 };
1503
1504 static int amplc_pci224_pci_probe(struct pci_dev *dev,
1505                                   const struct pci_device_id *id)
1506 {
1507         return comedi_pci_auto_config(dev, &amplc_pci224_driver,
1508                                       id->driver_data);
1509 }
1510
1511 static DEFINE_PCI_DEVICE_TABLE(amplc_pci224_pci_table) = {
1512         { PCI_DEVICE(PCI_VENDOR_ID_AMPLICON, PCI_DEVICE_ID_AMPLICON_PCI224) },
1513         { PCI_DEVICE(PCI_VENDOR_ID_AMPLICON, PCI_DEVICE_ID_AMPLICON_PCI234) },
1514         { 0 }
1515 };
1516 MODULE_DEVICE_TABLE(pci, amplc_pci224_pci_table);
1517
1518 static struct pci_driver amplc_pci224_pci_driver = {
1519         .name           = "amplc_pci224",
1520         .id_table       = amplc_pci224_pci_table,
1521         .probe          = amplc_pci224_pci_probe,
1522         .remove         = comedi_pci_auto_unconfig,
1523 };
1524 module_comedi_pci_driver(amplc_pci224_driver, amplc_pci224_pci_driver);
1525
1526 MODULE_AUTHOR("Comedi http://www.comedi.org");
1527 MODULE_DESCRIPTION("Comedi low-level driver");
1528 MODULE_LICENSE("GPL");