Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/mszeredi...
[firefly-linux-kernel-4.4.55.git] / drivers / staging / comedi / drivers / rtd520.c
1 /*
2     comedi/drivers/rtd520.c
3     Comedi driver for Real Time Devices (RTD) PCI4520/DM7520
4
5     COMEDI - Linux Control and Measurement Device Interface
6     Copyright (C) 2001 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     You should have received a copy of the GNU General Public License
19     along with this program; if not, write to the Free Software
20     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22 /*
23 Driver: rtd520
24 Description: Real Time Devices PCI4520/DM7520
25 Author: Dan Christian
26 Devices: [Real Time Devices] DM7520HR-1 (rtd520), DM7520HR-8,
27   PCI4520, PCI4520-8
28 Status: Works.  Only tested on DM7520-8.  Not SMP safe.
29
30 Configuration options:
31   [0] - PCI bus of device (optional)
32         If bus / slot is not specified, the first available PCI
33         device will be used.
34   [1] - PCI slot of device (optional)
35 */
36 /*
37     Created by Dan Christian, NASA Ames Research Center.
38
39     The PCI4520 is a PCI card.  The DM7520 is a PC/104-plus card.
40     Both have:
41     8/16 12 bit ADC with FIFO and channel gain table
42     8 bits high speed digital out (for external MUX) (or 8 in or 8 out)
43     8 bits high speed digital in with FIFO and interrupt on change (or 8 IO)
44     2 12 bit DACs with FIFOs
45     2 bits output
46     2 bits input
47     bus mastering DMA
48     timers: ADC sample, pacer, burst, about, delay, DA1, DA2
49     sample counter
50     3 user timer/counters (8254)
51     external interrupt
52
53     The DM7520 has slightly fewer features (fewer gain steps).
54
55     These boards can support external multiplexors and multi-board
56     synchronization, but this driver doesn't support that.
57
58     Board docs: http://www.rtdusa.com/PC104/DM/analog%20IO/dm7520.htm
59     Data sheet: http://www.rtdusa.com/pdf/dm7520.pdf
60     Example source: http://www.rtdusa.com/examples/dm/dm7520.zip
61     Call them and ask for the register level manual.
62     PCI chip: http://www.plxtech.com/products/io/pci9080
63
64     Notes:
65     This board is memory mapped.  There is some IO stuff, but it isn't needed.
66
67     I use a pretty loose naming style within the driver (rtd_blah).
68     All externally visible names should be rtd520_blah.
69     I use camelCase for structures (and inside them).
70     I may also use upper CamelCase for function names (old habit).
71
72     This board is somewhat related to the RTD PCI4400 board.
73
74     I borrowed heavily from the ni_mio_common, ni_atmio16d, mite, and
75     das1800, since they have the best documented code.  Driver
76     cb_pcidas64.c uses the same DMA controller.
77
78     As far as I can tell, the About interrupt doesn't work if Sample is
79     also enabled.  It turns out that About really isn't needed, since
80     we always count down samples read.
81
82     There was some timer/counter code, but it didn't follow the right API.
83
84 */
85
86 /*
87   driver status:
88
89   Analog-In supports instruction and command mode.
90
91   With DMA, you can sample at 1.15Mhz with 70% idle on a 400Mhz K6-2
92   (single channel, 64K read buffer).  I get random system lockups when
93   using DMA with ALI-15xx based systems.  I haven't been able to test
94   any other chipsets.  The lockups happen soon after the start of an
95   acquistion, not in the middle of a long run.
96
97   Without DMA, you can do 620Khz sampling with 20% idle on a 400Mhz K6-2
98   (with a 256K read buffer).
99
100   Digital-IO and Analog-Out only support instruction mode.
101
102 */
103
104 #include <linux/interrupt.h>
105 #include <linux/delay.h>
106
107 #include "../comedidev.h"
108
109 #define DRV_NAME "rtd520"
110
111 /*======================================================================
112   Driver specific stuff (tunable)
113 ======================================================================*/
114 /* Enable this to test the new DMA support. You may get hard lock ups */
115 /*#define USE_DMA*/
116
117 /* We really only need 2 buffers.  More than that means being much
118    smarter about knowing which ones are full. */
119 #define DMA_CHAIN_COUNT 2       /* max DMA segments/buffers in a ring (min 2) */
120
121 /* Target period for periodic transfers.  This sets the user read latency. */
122 /* Note: There are certain rates where we give this up and transfer 1/2 FIFO */
123 /* If this is too low, efficiency is poor */
124 #define TRANS_TARGET_PERIOD 10000000    /* 10 ms (in nanoseconds) */
125
126 /* Set a practical limit on how long a list to support (affects memory use) */
127 /* The board support a channel list up to the FIFO length (1K or 8K) */
128 #define RTD_MAX_CHANLIST        128     /* max channel list that we allow */
129
130 /* tuning for ai/ao instruction done polling */
131 #ifdef FAST_SPIN
132 #define WAIT_QUIETLY            /* as nothing, spin on done bit */
133 #define RTD_ADC_TIMEOUT 66000   /* 2 msec at 33mhz bus rate */
134 #define RTD_DAC_TIMEOUT 66000
135 #define RTD_DMA_TIMEOUT 33000   /* 1 msec */
136 #else
137 /* by delaying, power and electrical noise are reduced somewhat */
138 #define WAIT_QUIETLY    udelay(1)
139 #define RTD_ADC_TIMEOUT 2000    /* in usec */
140 #define RTD_DAC_TIMEOUT 2000    /* in usec */
141 #define RTD_DMA_TIMEOUT 1000    /* in usec */
142 #endif
143
144 /*======================================================================
145   Board specific stuff
146 ======================================================================*/
147
148 /* registers  */
149 #define PCI_VENDOR_ID_RTD       0x1435
150 /*
151   The board has three memory windows: las0, las1, and lcfg (the PCI chip)
152   Las1 has the data and can be burst DMAed 32bits at a time.
153 */
154 #define LCFG_PCIINDEX   0
155 /* PCI region 1 is a 256 byte IO space mapping.  Use??? */
156 #define LAS0_PCIINDEX   2       /* PCI memory resources */
157 #define LAS1_PCIINDEX   3
158 #define LCFG_PCISIZE    0x100
159 #define LAS0_PCISIZE    0x200
160 #define LAS1_PCISIZE    0x10
161
162 #define RTD_CLOCK_RATE  8000000 /* 8Mhz onboard clock */
163 #define RTD_CLOCK_BASE  125     /* clock period in ns */
164
165 /* Note: these speed are slower than the spec, but fit the counter resolution*/
166 #define RTD_MAX_SPEED   1625    /* when sampling, in nanoseconds */
167 /* max speed if we don't have to wait for settling */
168 #define RTD_MAX_SPEED_1 875     /* if single channel, in nanoseconds */
169
170 #define RTD_MIN_SPEED   2097151875      /* (24bit counter) in nanoseconds */
171 /* min speed when only 1 channel (no burst counter) */
172 #define RTD_MIN_SPEED_1 5000000 /* 200Hz, in nanoseconds */
173
174 #include "rtd520.h"
175 #include "plx9080.h"
176
177 /* Setup continuous ring of 1/2 FIFO transfers.  See RTD manual p91 */
178 #define DMA_MODE_BITS (\
179                        PLX_LOCAL_BUS_16_WIDE_BITS \
180                        | PLX_DMA_EN_READYIN_BIT \
181                        | PLX_DMA_LOCAL_BURST_EN_BIT \
182                        | PLX_EN_CHAIN_BIT \
183                        | PLX_DMA_INTR_PCI_BIT \
184                        | PLX_LOCAL_ADDR_CONST_BIT \
185                        | PLX_DEMAND_MODE_BIT)
186
187 #define DMA_TRANSFER_BITS (\
188 /* descriptors in PCI memory*/  PLX_DESC_IN_PCI_BIT \
189 /* interrupt at end of block */ | PLX_INTR_TERM_COUNT \
190 /* from board to PCI */         | PLX_XFER_LOCAL_TO_PCI)
191
192 /*======================================================================
193   Comedi specific stuff
194 ======================================================================*/
195
196 /*
197  * The board has 3 input modes and the gains of 1,2,4,...32 (, 64, 128)
198  */
199 static const struct comedi_lrange rtd_ai_7520_range = {
200         18, {
201                 /* +-5V input range gain steps */
202                 BIP_RANGE(5.0),
203                 BIP_RANGE(5.0 / 2),
204                 BIP_RANGE(5.0 / 4),
205                 BIP_RANGE(5.0 / 8),
206                 BIP_RANGE(5.0 / 16),
207                 BIP_RANGE(5.0 / 32),
208                 /* +-10V input range gain steps */
209                 BIP_RANGE(10.0),
210                 BIP_RANGE(10.0 / 2),
211                 BIP_RANGE(10.0 / 4),
212                 BIP_RANGE(10.0 / 8),
213                 BIP_RANGE(10.0 / 16),
214                 BIP_RANGE(10.0 / 32),
215                 /* +10V input range gain steps */
216                 UNI_RANGE(10.0),
217                 UNI_RANGE(10.0 / 2),
218                 UNI_RANGE(10.0 / 4),
219                 UNI_RANGE(10.0 / 8),
220                 UNI_RANGE(10.0 / 16),
221                 UNI_RANGE(10.0 / 32),
222         }
223 };
224
225 /* PCI4520 has two more gains (6 more entries) */
226 static const struct comedi_lrange rtd_ai_4520_range = {
227         24, {
228                 /* +-5V input range gain steps */
229                 BIP_RANGE(5.0),
230                 BIP_RANGE(5.0 / 2),
231                 BIP_RANGE(5.0 / 4),
232                 BIP_RANGE(5.0 / 8),
233                 BIP_RANGE(5.0 / 16),
234                 BIP_RANGE(5.0 / 32),
235                 BIP_RANGE(5.0 / 64),
236                 BIP_RANGE(5.0 / 128),
237                 /* +-10V input range gain steps */
238                 BIP_RANGE(10.0),
239                 BIP_RANGE(10.0 / 2),
240                 BIP_RANGE(10.0 / 4),
241                 BIP_RANGE(10.0 / 8),
242                 BIP_RANGE(10.0 / 16),
243                 BIP_RANGE(10.0 / 32),
244                 BIP_RANGE(10.0 / 64),
245                 BIP_RANGE(10.0 / 128),
246                 /* +10V input range gain steps */
247                 UNI_RANGE(10.0),
248                 UNI_RANGE(10.0 / 2),
249                 UNI_RANGE(10.0 / 4),
250                 UNI_RANGE(10.0 / 8),
251                 UNI_RANGE(10.0 / 16),
252                 UNI_RANGE(10.0 / 32),
253                 UNI_RANGE(10.0 / 64),
254                 UNI_RANGE(10.0 / 128),
255         }
256 };
257
258 /* Table order matches range values */
259 static const struct comedi_lrange rtd_ao_range = {
260         4, {
261                 UNI_RANGE(5),
262                 UNI_RANGE(10),
263                 BIP_RANGE(5),
264                 BIP_RANGE(10),
265         }
266 };
267
268 struct rtdBoard {
269         const char *name;
270         int device_id;
271         int aiChans;
272         int aiBits;
273         int aiMaxGain;
274         int range10Start;       /* start of +-10V range */
275         int rangeUniStart;      /* start of +10V range */
276 };
277
278 static const struct rtdBoard rtd520Boards[] = {
279         {
280                 .name           = "DM7520",
281                 .device_id      = 0x7520,
282                 .aiChans        = 16,
283                 .aiBits         = 12,
284                 .aiMaxGain      = 32,
285                 .range10Start   = 6,
286                 .rangeUniStart  = 12,
287         }, {
288                 .name           = "PCI4520",
289                 .device_id      = 0x4520,
290                 .aiChans        = 16,
291                 .aiBits         = 12,
292                 .aiMaxGain      = 128,
293                 .range10Start   = 8,
294                 .rangeUniStart  = 16,
295         },
296 };
297
298 /*
299    This structure is for data unique to this hardware driver.
300    This is also unique for each board in the system.
301 */
302 struct rtdPrivate {
303         /* memory mapped board structures */
304         void __iomem *las0;
305         void __iomem *las1;
306         void __iomem *lcfg;
307
308         unsigned long intCount; /* interrupt count */
309         long aiCount;           /* total transfer size (samples) */
310         int transCount;         /* # to transfer data. 0->1/2FIFO */
311         int flags;              /* flag event modes */
312
313         /* channel list info */
314         /* chanBipolar tracks whether a channel is bipolar (and needs +2048) */
315         unsigned char chanBipolar[RTD_MAX_CHANLIST / 8];        /* bit array */
316
317         /* read back data */
318         unsigned int aoValue[2];        /* Used for AO read back */
319
320         /* timer gate (when enabled) */
321         u8 utcGate[4];          /* 1 extra allows simple range check */
322
323         /* shadow registers affect other registers, but can't be read back */
324         /* The macros below update these on writes */
325         u16 intMask;            /* interrupt mask */
326         u16 intClearMask;       /* interrupt clear mask */
327         u8 utcCtrl[4];          /* crtl mode for 3 utc + read back */
328         u8 dioStatus;           /* could be read back (dio0Ctrl) */
329 #ifdef USE_DMA
330         /*
331          * Always DMA 1/2 FIFO.  Buffer (dmaBuff?) is (at least) twice that
332          * size.  After transferring, interrupt processes 1/2 FIFO and
333          * passes to comedi
334          */
335         s16 dma0Offset;         /* current processing offset (0, 1/2) */
336         uint16_t *dma0Buff[DMA_CHAIN_COUNT];    /* DMA buffers (for ADC) */
337         dma_addr_t dma0BuffPhysAddr[DMA_CHAIN_COUNT];   /* physical addresses */
338         struct plx_dma_desc *dma0Chain; /* DMA descriptor ring for dmaBuff */
339         dma_addr_t dma0ChainPhysAddr;   /* physical addresses */
340         /* shadow registers */
341         u8 dma0Control;
342         u8 dma1Control;
343 #endif                          /* USE_DMA */
344         unsigned fifoLen;
345 };
346
347 /* bit defines for "flags" */
348 #define SEND_EOS        0x01    /* send End Of Scan events */
349 #define DMA0_ACTIVE     0x02    /* DMA0 is active */
350 #define DMA1_ACTIVE     0x04    /* DMA1 is active */
351
352 /* Macros for accessing channel list bit array */
353 #define CHAN_ARRAY_TEST(array, index) \
354         (((array)[(index)/8] >> ((index) & 0x7)) & 0x1)
355 #define CHAN_ARRAY_SET(array, index) \
356         (((array)[(index)/8] |= 1 << ((index) & 0x7)))
357 #define CHAN_ARRAY_CLEAR(array, index) \
358         (((array)[(index)/8] &= ~(1 << ((index) & 0x7))))
359
360 /*
361   Given a desired period and the clock period (both in ns),
362   return the proper counter value (divider-1).
363   Sets the original period to be the true value.
364   Note: you have to check if the value is larger than the counter range!
365 */
366 static int rtd_ns_to_timer_base(unsigned int *nanosec,  /* desired period (in ns) */
367                                 int round_mode, int base)
368 {                               /* clock period (in ns) */
369         int divider;
370
371         switch (round_mode) {
372         case TRIG_ROUND_NEAREST:
373         default:
374                 divider = (*nanosec + base / 2) / base;
375                 break;
376         case TRIG_ROUND_DOWN:
377                 divider = (*nanosec) / base;
378                 break;
379         case TRIG_ROUND_UP:
380                 divider = (*nanosec + base - 1) / base;
381                 break;
382         }
383         if (divider < 2)
384                 divider = 2;    /* min is divide by 2 */
385
386         /* Note: we don't check for max, because different timers
387            have different ranges */
388
389         *nanosec = base * divider;
390         return divider - 1;     /* countdown is divisor+1 */
391 }
392
393 /*
394   Given a desired period (in ns),
395   return the proper counter value (divider-1) for the internal clock.
396   Sets the original period to be the true value.
397 */
398 static int rtd_ns_to_timer(unsigned int *ns, int round_mode)
399 {
400         return rtd_ns_to_timer_base(ns, round_mode, RTD_CLOCK_BASE);
401 }
402
403 /*
404   Convert a single comedi channel-gain entry to a RTD520 table entry
405 */
406 static unsigned short rtdConvertChanGain(struct comedi_device *dev,
407                                          unsigned int comediChan, int chanIndex)
408 {                               /* index in channel list */
409         const struct rtdBoard *thisboard = comedi_board(dev);
410         struct rtdPrivate *devpriv = dev->private;
411         unsigned int chan, range, aref;
412         unsigned short r = 0;
413
414         chan = CR_CHAN(comediChan);
415         range = CR_RANGE(comediChan);
416         aref = CR_AREF(comediChan);
417
418         r |= chan & 0xf;
419
420         /* Note: we also setup the channel list bipolar flag array */
421         if (range < thisboard->range10Start) {  /* first batch are +-5 */
422                 r |= 0x000;     /* +-5 range */
423                 r |= (range & 0x7) << 4;        /* gain */
424                 CHAN_ARRAY_SET(devpriv->chanBipolar, chanIndex);
425         } else if (range < thisboard->rangeUniStart) {  /* second batch are +-10 */
426                 r |= 0x100;     /* +-10 range */
427                 /* gain */
428                 r |= ((range - thisboard->range10Start) & 0x7) << 4;
429                 CHAN_ARRAY_SET(devpriv->chanBipolar, chanIndex);
430         } else {                /* last batch is +10 */
431                 r |= 0x200;     /* +10 range */
432                 /* gain */
433                 r |= ((range - thisboard->rangeUniStart) & 0x7) << 4;
434                 CHAN_ARRAY_CLEAR(devpriv->chanBipolar, chanIndex);
435         }
436
437         switch (aref) {
438         case AREF_GROUND:       /* on-board ground */
439                 break;
440
441         case AREF_COMMON:
442                 r |= 0x80;      /* ref external analog common */
443                 break;
444
445         case AREF_DIFF:
446                 r |= 0x400;     /* differential inputs */
447                 break;
448
449         case AREF_OTHER:        /* ??? */
450                 break;
451         }
452         /*printk ("chan=%d r=%d a=%d -> 0x%x\n",
453            chan, range, aref, r); */
454         return r;
455 }
456
457 /*
458   Setup the channel-gain table from a comedi list
459 */
460 static void rtd_load_channelgain_list(struct comedi_device *dev,
461                                       unsigned int n_chan, unsigned int *list)
462 {
463         struct rtdPrivate *devpriv = dev->private;
464
465         if (n_chan > 1) {       /* setup channel gain table */
466                 int ii;
467
468                 writel(0, devpriv->las0 + LAS0_CGT_CLEAR);
469                 writel(1, devpriv->las0 + LAS0_CGT_ENABLE);
470                 for (ii = 0; ii < n_chan; ii++) {
471                         writel(rtdConvertChanGain(dev, list[ii], ii),
472                                 devpriv->las0 + LAS0_CGT_WRITE);
473                 }
474         } else {                /* just use the channel gain latch */
475                 writel(0, devpriv->las0 + LAS0_CGT_ENABLE);
476                 writel(rtdConvertChanGain(dev, list[0], 0),
477                         devpriv->las0 + LAS0_CGL_WRITE);
478         }
479 }
480
481 /* determine fifo size by doing adc conversions until the fifo half
482 empty status flag clears */
483 static int rtd520_probe_fifo_depth(struct comedi_device *dev)
484 {
485         struct rtdPrivate *devpriv = dev->private;
486         unsigned int chanspec = CR_PACK(0, 0, AREF_GROUND);
487         unsigned i;
488         static const unsigned limit = 0x2000;
489         unsigned fifo_size = 0;
490
491         writel(0, devpriv->las0 + LAS0_ADC_FIFO_CLEAR);
492         rtd_load_channelgain_list(dev, 1, &chanspec);
493         /* ADC conversion trigger source: SOFTWARE */
494         writel(0, devpriv->las0 + LAS0_ADC_CONVERSION);
495         /* convert  samples */
496         for (i = 0; i < limit; ++i) {
497                 unsigned fifo_status;
498                 /* trigger conversion */
499                 writew(0, devpriv->las0 + LAS0_ADC);
500                 udelay(1);
501                 fifo_status = readl(devpriv->las0 + LAS0_ADC);
502                 if ((fifo_status & FS_ADC_HEMPTY) == 0) {
503                         fifo_size = 2 * i;
504                         break;
505                 }
506         }
507         if (i == limit) {
508                 printk(KERN_INFO "\ncomedi: %s: failed to probe fifo size.\n",
509                        DRV_NAME);
510                 return -EIO;
511         }
512         writel(0, devpriv->las0 + LAS0_ADC_FIFO_CLEAR);
513         if (fifo_size != 0x400 && fifo_size != 0x2000) {
514                 printk
515                     (KERN_INFO "\ncomedi: %s: unexpected fifo size of %i, expected 1024 or 8192.\n",
516                      DRV_NAME, fifo_size);
517                 return -EIO;
518         }
519         return fifo_size;
520 }
521
522 /*
523   "instructions" read/write data in "one-shot" or "software-triggered"
524   mode (simplest case).
525   This doesn't use interrupts.
526
527   Note, we don't do any settling delays.  Use a instruction list to
528   select, delay, then read.
529  */
530 static int rtd_ai_rinsn(struct comedi_device *dev,
531                         struct comedi_subdevice *s, struct comedi_insn *insn,
532                         unsigned int *data)
533 {
534         struct rtdPrivate *devpriv = dev->private;
535         int n, ii;
536         int stat;
537
538         /* clear any old fifo data */
539         writel(0, devpriv->las0 + LAS0_ADC_FIFO_CLEAR);
540
541         /* write channel to multiplexer and clear channel gain table */
542         rtd_load_channelgain_list(dev, 1, &insn->chanspec);
543
544         /* ADC conversion trigger source: SOFTWARE */
545         writel(0, devpriv->las0 + LAS0_ADC_CONVERSION);
546
547         /* convert n samples */
548         for (n = 0; n < insn->n; n++) {
549                 s16 d;
550                 /* trigger conversion */
551                 writew(0, devpriv->las0 + LAS0_ADC);
552
553                 for (ii = 0; ii < RTD_ADC_TIMEOUT; ++ii) {
554                         stat = readl(devpriv->las0 + LAS0_ADC);
555                         if (stat & FS_ADC_NOT_EMPTY)    /* 1 -> not empty */
556                                 break;
557                         WAIT_QUIETLY;
558                 }
559                 if (ii >= RTD_ADC_TIMEOUT) {
560                         DPRINTK
561                             ("rtd520: Error: ADC never finished! FifoStatus=0x%x\n",
562                              stat ^ 0x6666);
563                         return -ETIMEDOUT;
564                 }
565
566                 /* read data */
567                 d = readw(devpriv->las1 + LAS1_ADC_FIFO);
568                 /*printk ("rtd520: Got 0x%x after %d usec\n", d, ii+1); */
569                 d = d >> 3;     /* low 3 bits are marker lines */
570                 if (CHAN_ARRAY_TEST(devpriv->chanBipolar, 0))
571                         /* convert to comedi unsigned data */
572                         data[n] = d + 2048;
573                 else
574                         data[n] = d;
575         }
576
577         /* return the number of samples read/written */
578         return n;
579 }
580
581 /*
582   Get what we know is there.... Fast!
583   This uses 1/2 the bus cycles of read_dregs (below).
584
585   The manual claims that we can do a lword read, but it doesn't work here.
586 */
587 static int ai_read_n(struct comedi_device *dev, struct comedi_subdevice *s,
588                      int count)
589 {
590         struct rtdPrivate *devpriv = dev->private;
591         int ii;
592
593         for (ii = 0; ii < count; ii++) {
594                 short sample;
595                 s16 d;
596
597                 if (0 == devpriv->aiCount) {    /* done */
598                         d = readw(devpriv->las1 + LAS1_ADC_FIFO);
599                         continue;
600                 }
601 #if 0
602                 if (!(readl(devpriv->las0 + LAS0_ADC) & FS_ADC_NOT_EMPTY)) {
603                         DPRINTK("comedi: READ OOPS on %d of %d\n", ii + 1,
604                                 count);
605                         break;
606                 }
607 #endif
608                 d = readw(devpriv->las1 + LAS1_ADC_FIFO);
609
610                 d = d >> 3;     /* low 3 bits are marker lines */
611                 if (CHAN_ARRAY_TEST(devpriv->chanBipolar, s->async->cur_chan)) {
612                         /* convert to comedi unsigned data */
613                         sample = d + 2048;
614                 } else
615                         sample = d;
616
617                 if (!comedi_buf_put(s->async, sample))
618                         return -1;
619
620                 if (devpriv->aiCount > 0)       /* < 0, means read forever */
621                         devpriv->aiCount--;
622         }
623         return 0;
624 }
625
626 /*
627   unknown amout of data is waiting in fifo.
628 */
629 static int ai_read_dregs(struct comedi_device *dev, struct comedi_subdevice *s)
630 {
631         struct rtdPrivate *devpriv = dev->private;
632
633         while (readl(devpriv->las0 + LAS0_ADC) & FS_ADC_NOT_EMPTY) {
634                 short sample;
635                 s16 d = readw(devpriv->las1 + LAS1_ADC_FIFO);
636
637                 if (0 == devpriv->aiCount) {    /* done */
638                         continue;       /* read rest */
639                 }
640
641                 d = d >> 3;     /* low 3 bits are marker lines */
642                 if (CHAN_ARRAY_TEST(devpriv->chanBipolar, s->async->cur_chan)) {
643                         /* convert to comedi unsigned data */
644                         sample = d + 2048;
645                 } else
646                         sample = d;
647
648                 if (!comedi_buf_put(s->async, sample))
649                         return -1;
650
651                 if (devpriv->aiCount > 0)       /* < 0, means read forever */
652                         devpriv->aiCount--;
653         }
654         return 0;
655 }
656
657 #ifdef USE_DMA
658 /*
659   Terminate a DMA transfer and wait for everything to quiet down
660 */
661 void abort_dma(struct comedi_device *dev, unsigned int channel)
662 {                               /* DMA channel 0, 1 */
663         struct rtdPrivate *devpriv = dev->private;
664         unsigned long dma_cs_addr;      /* the control/status register */
665         uint8_t status;
666         unsigned int ii;
667         /* unsigned long flags; */
668
669         dma_cs_addr = (unsigned long)devpriv->lcfg
670             + ((channel == 0) ? LCFG_DMACSR0 : LCFG_DMACSR1);
671
672         /*  spinlock for plx dma control/status reg */
673         /* spin_lock_irqsave( &dev->spinlock, flags ); */
674
675         /*  abort dma transfer if necessary */
676         status = readb(dma_cs_addr);
677         if ((status & PLX_DMA_EN_BIT) == 0) {   /* not enabled (Error?) */
678                 DPRINTK("rtd520: AbortDma on non-active channel %d (0x%x)\n",
679                         channel, status);
680                 goto abortDmaExit;
681         }
682
683         /* wait to make sure done bit is zero (needed?) */
684         for (ii = 0; (status & PLX_DMA_DONE_BIT) && ii < RTD_DMA_TIMEOUT; ii++) {
685                 WAIT_QUIETLY;
686                 status = readb(dma_cs_addr);
687         }
688         if (status & PLX_DMA_DONE_BIT) {
689                 printk("rtd520: Timeout waiting for dma %i done clear\n",
690                        channel);
691                 goto abortDmaExit;
692         }
693
694         /* disable channel (required) */
695         writeb(0, dma_cs_addr);
696         udelay(1);              /* needed?? */
697         /* set abort bit for channel */
698         writeb(PLX_DMA_ABORT_BIT, dma_cs_addr);
699
700         /*  wait for dma done bit to be set */
701         status = readb(dma_cs_addr);
702         for (ii = 0;
703              (status & PLX_DMA_DONE_BIT) == 0 && ii < RTD_DMA_TIMEOUT; ii++) {
704                 status = readb(dma_cs_addr);
705                 WAIT_QUIETLY;
706         }
707         if ((status & PLX_DMA_DONE_BIT) == 0) {
708                 printk("rtd520: Timeout waiting for dma %i done set\n",
709                        channel);
710         }
711
712 abortDmaExit:
713         /* spin_unlock_irqrestore( &dev->spinlock, flags ); */
714 }
715
716 /*
717   Process what is in the DMA transfer buffer and pass to comedi
718   Note: this is not re-entrant
719 */
720 static int ai_process_dma(struct comedi_device *dev, struct comedi_subdevice *s)
721 {
722         struct rtdPrivate *devpriv = dev->private;
723         int ii, n;
724         s16 *dp;
725
726         if (devpriv->aiCount == 0)      /* transfer already complete */
727                 return 0;
728
729         dp = devpriv->dma0Buff[devpriv->dma0Offset];
730         for (ii = 0; ii < devpriv->fifoLen / 2;) {      /* convert samples */
731                 short sample;
732
733                 if (CHAN_ARRAY_TEST(devpriv->chanBipolar, s->async->cur_chan)) {
734                         sample = (*dp >> 3) + 2048;     /* convert to comedi unsigned data */
735                 else
736                         sample = *dp >> 3;      /* low 3 bits are marker lines */
737
738                 *dp++ = sample; /* put processed value back */
739
740                 if (++s->async->cur_chan >= s->async->cmd.chanlist_len)
741                         s->async->cur_chan = 0;
742
743                 ++ii;           /* number ready to transfer */
744                 if (devpriv->aiCount > 0) {     /* < 0, means read forever */
745                         if (--devpriv->aiCount == 0) {  /* done */
746                                 /*DPRINTK ("rtd520: Final %d samples\n", ii); */
747                                 break;
748                         }
749                 }
750         }
751
752         /* now pass the whole array to the comedi buffer */
753         dp = devpriv->dma0Buff[devpriv->dma0Offset];
754         n = comedi_buf_write_alloc(s->async, ii * sizeof(s16));
755         if (n < (ii * sizeof(s16))) {   /* any residual is an error */
756                 DPRINTK("rtd520:ai_process_dma buffer overflow %d samples!\n",
757                         ii - (n / sizeof(s16)));
758                 s->async->events |= COMEDI_CB_ERROR;
759                 return -1;
760         }
761         comedi_buf_memcpy_to(s->async, 0, dp, n);
762         comedi_buf_write_free(s->async, n);
763
764         /*
765          * always at least 1 scan -- 1/2 FIFO is larger than our max scan list
766          */
767         s->async->events |= COMEDI_CB_BLOCK | COMEDI_CB_EOS;
768
769         if (++devpriv->dma0Offset >= DMA_CHAIN_COUNT) { /* next buffer */
770                 devpriv->dma0Offset = 0;
771         }
772         return 0;
773 }
774 #endif /* USE_DMA */
775
776 /*
777   Handle all rtd520 interrupts.
778   Runs atomically and is never re-entered.
779   This is a "slow handler";  other interrupts may be active.
780   The data conversion may someday happen in a "bottom half".
781 */
782 static irqreturn_t rtd_interrupt(int irq,       /* interrupt number (ignored) */
783                                  void *d)
784 {                               /* our data *//* cpu context (ignored) */
785         struct comedi_device *dev = d;
786         struct comedi_subdevice *s = dev->subdevices + 0;       /* analog in subdevice */
787         struct rtdPrivate *devpriv = dev->private;
788         u32 overrun;
789         u16 status;
790         u16 fifoStatus;
791
792         if (!dev->attached)
793                 return IRQ_NONE;
794
795         devpriv->intCount++;    /* DEBUG statistics */
796
797         fifoStatus = readl(devpriv->las0 + LAS0_ADC);
798         /* check for FIFO full, this automatically halts the ADC! */
799         if (!(fifoStatus & FS_ADC_NOT_FULL)) {  /* 0 -> full */
800                 DPRINTK("rtd520: FIFO full! fifo_status=0x%x\n", (fifoStatus ^ 0x6666) & 0x7777);       /* should be all 0s */
801                 goto abortTransfer;
802         }
803 #ifdef USE_DMA
804         if (devpriv->flags & DMA0_ACTIVE) {     /* Check DMA */
805                 u32 istatus = readl(devpriv->lcfg + LCFG_ITCSR);
806
807                 if (istatus & ICS_DMA0_A) {
808                         if (ai_process_dma(dev, s) < 0) {
809                                 DPRINTK
810                                     ("rtd520: comedi read buffer overflow (DMA) with %ld to go!\n",
811                                      devpriv->aiCount);
812                                 devpriv->dma0Control &= ~PLX_DMA_START_BIT;
813                                 devpriv->dma0Control |= PLX_CLEAR_DMA_INTR_BIT;
814                                 writeb(devpriv->dma0Control,
815                                         devpriv->lcfg + LCFG_DMACSR0);
816                                 goto abortTransfer;
817                         }
818
819                         /*DPRINTK ("rtd520: DMA transfer: %ld to go, istatus %x\n",
820                            devpriv->aiCount, istatus); */
821                         devpriv->dma0Control &= ~PLX_DMA_START_BIT;
822                         devpriv->dma0Control |= PLX_CLEAR_DMA_INTR_BIT;
823                         writeb(devpriv->dma0Control,
824                                 devpriv->lcfg + LCFG_DMACSR0);
825                         if (0 == devpriv->aiCount) {    /* counted down */
826                                 DPRINTK("rtd520: Samples Done (DMA).\n");
827                                 goto transferDone;
828                         }
829                         comedi_event(dev, s);
830                 } else {
831                         /*DPRINTK ("rtd520: No DMA ready: istatus %x\n", istatus); */
832                 }
833         }
834         /* Fall through and check for other interrupt sources */
835 #endif /* USE_DMA */
836
837         status = readw(devpriv->las0 + LAS0_IT);
838         /* if interrupt was not caused by our board, or handled above */
839         if (0 == status)
840                 return IRQ_HANDLED;
841
842         if (status & IRQM_ADC_ABOUT_CNT) {      /* sample count -> read FIFO */
843                 /* since the priority interrupt controller may have queued a sample
844                    counter interrupt, even though we have already finished,
845                    we must handle the possibility that there is no data here */
846                 if (!(fifoStatus & FS_ADC_HEMPTY)) {    /* 0 -> 1/2 full */
847                         /*DPRINTK("rtd520: Sample int, reading 1/2FIFO.  fifo_status 0x%x\n",
848                            (fifoStatus ^ 0x6666) & 0x7777); */
849                         if (ai_read_n(dev, s, devpriv->fifoLen / 2) < 0) {
850                                 DPRINTK
851                                     ("rtd520: comedi read buffer overflow (1/2FIFO) with %ld to go!\n",
852                                      devpriv->aiCount);
853                                 goto abortTransfer;
854                         }
855                         if (0 == devpriv->aiCount) {    /* counted down */
856                                 DPRINTK("rtd520: Samples Done (1/2). fifo_status was 0x%x\n", (fifoStatus ^ 0x6666) & 0x7777);  /* should be all 0s */
857                                 goto transferDone;
858                         }
859                         comedi_event(dev, s);
860                 } else if (devpriv->transCount > 0) {   /* read often */
861                         /*DPRINTK("rtd520: Sample int, reading %d  fifo_status 0x%x\n",
862                            devpriv->transCount, (fifoStatus ^ 0x6666) & 0x7777); */
863                         if (fifoStatus & FS_ADC_NOT_EMPTY) {    /* 1 -> not empty */
864                                 if (ai_read_n(dev, s, devpriv->transCount) < 0) {
865                                         DPRINTK
866                                             ("rtd520: comedi read buffer overflow (N) with %ld to go!\n",
867                                              devpriv->aiCount);
868                                         goto abortTransfer;
869                                 }
870                                 if (0 == devpriv->aiCount) {    /* counted down */
871                                         DPRINTK
872                                             ("rtd520: Samples Done (N). fifo_status was 0x%x\n",
873                                              (fifoStatus ^ 0x6666) & 0x7777);
874                                         goto transferDone;
875                                 }
876                                 comedi_event(dev, s);
877                         }
878                 } else {        /* wait for 1/2 FIFO (old) */
879                         DPRINTK
880                             ("rtd520: Sample int.  Wait for 1/2. fifo_status 0x%x\n",
881                              (fifoStatus ^ 0x6666) & 0x7777);
882                 }
883         } else {
884                 DPRINTK("rtd520: unknown interrupt source!\n");
885         }
886
887         overrun = readl(devpriv->las0 + LAS0_OVERRUN) & 0xffff;
888         if (overrun) {
889                 DPRINTK
890                     ("rtd520: Interrupt overrun with %ld to go! over_status=0x%x\n",
891                      devpriv->aiCount, overrun);
892                 goto abortTransfer;
893         }
894
895         /* clear the interrupt */
896         devpriv->intClearMask = status;
897         writew(devpriv->intClearMask, devpriv->las0 + LAS0_CLEAR);
898         readw(devpriv->las0 + LAS0_CLEAR);
899         return IRQ_HANDLED;
900
901 abortTransfer:
902         writel(0, devpriv->las0 + LAS0_ADC_FIFO_CLEAR);
903         s->async->events |= COMEDI_CB_ERROR;
904         devpriv->aiCount = 0;   /* stop and don't transfer any more */
905         /* fall into transferDone */
906
907 transferDone:
908         /* pacer stop source: SOFTWARE */
909         writel(0, devpriv->las0 + LAS0_PACER_STOP);
910         writel(0, devpriv->las0 + LAS0_PACER);  /* stop pacer */
911         writel(0, devpriv->las0 + LAS0_ADC_CONVERSION);
912         devpriv->intMask = 0;
913         writew(devpriv->intMask, devpriv->las0 + LAS0_IT);
914 #ifdef USE_DMA
915         if (devpriv->flags & DMA0_ACTIVE) {
916                 writel(readl(devpriv->lcfg + LCFG_ITCSR) & ~ICS_DMA0_E,
917                         devpriv->lcfg + LCFG_ITCSR);
918                 abort_dma(dev, 0);
919                 devpriv->flags &= ~DMA0_ACTIVE;
920                 /* if Using DMA, then we should have read everything by now */
921                 if (devpriv->aiCount > 0) {
922                         DPRINTK("rtd520: Lost DMA data! %ld remain\n",
923                                 devpriv->aiCount);
924                 }
925         }
926 #endif /* USE_DMA */
927
928         if (devpriv->aiCount > 0) {     /* there shouldn't be anything left */
929                 fifoStatus = readl(devpriv->las0 + LAS0_ADC);
930                 DPRINTK("rtd520: Finishing up. %ld remain, fifoStat=%x\n", devpriv->aiCount, (fifoStatus ^ 0x6666) & 0x7777);   /* should read all 0s */
931                 ai_read_dregs(dev, s);  /* read anything left in FIFO */
932         }
933
934         s->async->events |= COMEDI_CB_EOA;      /* signal end to comedi */
935         comedi_event(dev, s);
936
937         /* clear the interrupt */
938         status = readw(devpriv->las0 + LAS0_IT);
939         devpriv->intClearMask = status;
940         writew(devpriv->intClearMask, devpriv->las0 + LAS0_CLEAR);
941         readw(devpriv->las0 + LAS0_CLEAR);
942
943         fifoStatus = readl(devpriv->las0 + LAS0_ADC);
944         overrun = readl(devpriv->las0 + LAS0_OVERRUN) & 0xffff;
945         DPRINTK
946             ("rtd520: Acquisition complete. %ld ints, intStat=%x, overStat=%x\n",
947              devpriv->intCount, status, overrun);
948
949         return IRQ_HANDLED;
950 }
951
952 #if 0
953 /*
954   return the number of samples available
955 */
956 static int rtd_ai_poll(struct comedi_device *dev, struct comedi_subdevice *s)
957 {
958         /* TODO: This needs to mask interrupts, read_dregs, and then re-enable */
959         /* Not sure what to do if DMA is active */
960         return s->async->buf_write_count - s->async->buf_read_count;
961 }
962 #endif
963
964 /*
965   cmdtest tests a particular command to see if it is valid.
966   Using the cmdtest ioctl, a user can create a valid cmd
967   and then have it executed by the cmd ioctl (asyncronously).
968
969   cmdtest returns 1,2,3,4 or 0, depending on which tests
970   the command passes.
971 */
972
973 static int rtd_ai_cmdtest(struct comedi_device *dev,
974                           struct comedi_subdevice *s, struct comedi_cmd *cmd)
975 {
976         int err = 0;
977         int tmp;
978
979         /* step 1: make sure trigger sources are trivially valid */
980
981         tmp = cmd->start_src;
982         cmd->start_src &= TRIG_NOW;
983         if (!cmd->start_src || tmp != cmd->start_src)
984                 err++;
985
986         tmp = cmd->scan_begin_src;
987         cmd->scan_begin_src &= TRIG_TIMER | TRIG_EXT;
988         if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
989                 err++;
990
991
992         tmp = cmd->convert_src;
993         cmd->convert_src &= TRIG_TIMER | TRIG_EXT;
994         if (!cmd->convert_src || tmp != cmd->convert_src)
995                 err++;
996
997
998         tmp = cmd->scan_end_src;
999         cmd->scan_end_src &= TRIG_COUNT;
1000         if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
1001                 err++;
1002
1003
1004         tmp = cmd->stop_src;
1005         cmd->stop_src &= TRIG_COUNT | TRIG_NONE;
1006         if (!cmd->stop_src || tmp != cmd->stop_src)
1007                 err++;
1008
1009
1010         if (err)
1011                 return 1;
1012
1013         /* step 2: make sure trigger sources are unique
1014            and mutually compatible */
1015         /* note that mutual compatibility is not an issue here */
1016         if (cmd->scan_begin_src != TRIG_TIMER &&
1017             cmd->scan_begin_src != TRIG_EXT) {
1018                 err++;
1019         }
1020         if (cmd->convert_src != TRIG_TIMER && cmd->convert_src != TRIG_EXT)
1021                 err++;
1022
1023         if (cmd->stop_src != TRIG_COUNT && cmd->stop_src != TRIG_NONE)
1024                 err++;
1025
1026         if (err)
1027                 return 2;
1028
1029         /* step 3: make sure arguments are trivially compatible */
1030
1031         if (cmd->start_arg != 0) {
1032                 cmd->start_arg = 0;
1033                 err++;
1034         }
1035
1036         if (cmd->scan_begin_src == TRIG_TIMER) {
1037                 /* Note: these are time periods, not actual rates */
1038                 if (1 == cmd->chanlist_len) {   /* no scanning */
1039                         if (cmd->scan_begin_arg < RTD_MAX_SPEED_1) {
1040                                 cmd->scan_begin_arg = RTD_MAX_SPEED_1;
1041                                 rtd_ns_to_timer(&cmd->scan_begin_arg,
1042                                                 TRIG_ROUND_UP);
1043                                 err++;
1044                         }
1045                         if (cmd->scan_begin_arg > RTD_MIN_SPEED_1) {
1046                                 cmd->scan_begin_arg = RTD_MIN_SPEED_1;
1047                                 rtd_ns_to_timer(&cmd->scan_begin_arg,
1048                                                 TRIG_ROUND_DOWN);
1049                                 err++;
1050                         }
1051                 } else {
1052                         if (cmd->scan_begin_arg < RTD_MAX_SPEED) {
1053                                 cmd->scan_begin_arg = RTD_MAX_SPEED;
1054                                 rtd_ns_to_timer(&cmd->scan_begin_arg,
1055                                                 TRIG_ROUND_UP);
1056                                 err++;
1057                         }
1058                         if (cmd->scan_begin_arg > RTD_MIN_SPEED) {
1059                                 cmd->scan_begin_arg = RTD_MIN_SPEED;
1060                                 rtd_ns_to_timer(&cmd->scan_begin_arg,
1061                                                 TRIG_ROUND_DOWN);
1062                                 err++;
1063                         }
1064                 }
1065         } else {
1066                 /* external trigger */
1067                 /* should be level/edge, hi/lo specification here */
1068                 /* should specify multiple external triggers */
1069                 if (cmd->scan_begin_arg > 9) {
1070                         cmd->scan_begin_arg = 9;
1071                         err++;
1072                 }
1073         }
1074         if (cmd->convert_src == TRIG_TIMER) {
1075                 if (1 == cmd->chanlist_len) {   /* no scanning */
1076                         if (cmd->convert_arg < RTD_MAX_SPEED_1) {
1077                                 cmd->convert_arg = RTD_MAX_SPEED_1;
1078                                 rtd_ns_to_timer(&cmd->convert_arg,
1079                                                 TRIG_ROUND_UP);
1080                                 err++;
1081                         }
1082                         if (cmd->convert_arg > RTD_MIN_SPEED_1) {
1083                                 cmd->convert_arg = RTD_MIN_SPEED_1;
1084                                 rtd_ns_to_timer(&cmd->convert_arg,
1085                                                 TRIG_ROUND_DOWN);
1086                                 err++;
1087                         }
1088                 } else {
1089                         if (cmd->convert_arg < RTD_MAX_SPEED) {
1090                                 cmd->convert_arg = RTD_MAX_SPEED;
1091                                 rtd_ns_to_timer(&cmd->convert_arg,
1092                                                 TRIG_ROUND_UP);
1093                                 err++;
1094                         }
1095                         if (cmd->convert_arg > RTD_MIN_SPEED) {
1096                                 cmd->convert_arg = RTD_MIN_SPEED;
1097                                 rtd_ns_to_timer(&cmd->convert_arg,
1098                                                 TRIG_ROUND_DOWN);
1099                                 err++;
1100                         }
1101                 }
1102         } else {
1103                 /* external trigger */
1104                 /* see above */
1105                 if (cmd->convert_arg > 9) {
1106                         cmd->convert_arg = 9;
1107                         err++;
1108                 }
1109         }
1110
1111 #if 0
1112         if (cmd->scan_end_arg != cmd->chanlist_len) {
1113                 cmd->scan_end_arg = cmd->chanlist_len;
1114                 err++;
1115         }
1116 #endif
1117         if (cmd->stop_src == TRIG_COUNT) {
1118                 /* TODO check for rounding error due to counter wrap */
1119
1120         } else {
1121                 /* TRIG_NONE */
1122                 if (cmd->stop_arg != 0) {
1123                         cmd->stop_arg = 0;
1124                         err++;
1125                 }
1126         }
1127
1128         if (err)
1129                 return 3;
1130
1131
1132         /* step 4: fix up any arguments */
1133
1134         if (cmd->chanlist_len > RTD_MAX_CHANLIST) {
1135                 cmd->chanlist_len = RTD_MAX_CHANLIST;
1136                 err++;
1137         }
1138         if (cmd->scan_begin_src == TRIG_TIMER) {
1139                 tmp = cmd->scan_begin_arg;
1140                 rtd_ns_to_timer(&cmd->scan_begin_arg,
1141                                 cmd->flags & TRIG_ROUND_MASK);
1142                 if (tmp != cmd->scan_begin_arg)
1143                         err++;
1144
1145         }
1146         if (cmd->convert_src == TRIG_TIMER) {
1147                 tmp = cmd->convert_arg;
1148                 rtd_ns_to_timer(&cmd->convert_arg,
1149                                 cmd->flags & TRIG_ROUND_MASK);
1150                 if (tmp != cmd->convert_arg)
1151                         err++;
1152
1153                 if (cmd->scan_begin_src == TRIG_TIMER
1154                     && (cmd->scan_begin_arg
1155                         < (cmd->convert_arg * cmd->scan_end_arg))) {
1156                         cmd->scan_begin_arg =
1157                             cmd->convert_arg * cmd->scan_end_arg;
1158                         err++;
1159                 }
1160         }
1161
1162         if (err)
1163                 return 4;
1164
1165         return 0;
1166 }
1167
1168 /*
1169   Execute a analog in command with many possible triggering options.
1170   The data get stored in the async structure of the subdevice.
1171   This is usually done by an interrupt handler.
1172   Userland gets to the data using read calls.
1173 */
1174 static int rtd_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
1175 {
1176         struct rtdPrivate *devpriv = dev->private;
1177         struct comedi_cmd *cmd = &s->async->cmd;
1178         int timer;
1179
1180         /* stop anything currently running */
1181         /* pacer stop source: SOFTWARE */
1182         writel(0, devpriv->las0 + LAS0_PACER_STOP);
1183         writel(0, devpriv->las0 + LAS0_PACER);  /* stop pacer */
1184         writel(0, devpriv->las0 + LAS0_ADC_CONVERSION);
1185         devpriv->intMask = 0;
1186         writew(devpriv->intMask, devpriv->las0 + LAS0_IT);
1187 #ifdef USE_DMA
1188         if (devpriv->flags & DMA0_ACTIVE) {     /* cancel anything running */
1189                 writel(readl(devpriv->lcfg + LCFG_ITCSR) & ~ICS_DMA0_E,
1190                         devpriv->lcfg + LCFG_ITCSR);
1191                 abort_dma(dev, 0);
1192                 devpriv->flags &= ~DMA0_ACTIVE;
1193                 if (readl(devpriv->lcfg + LCFG_ITCSR) & ICS_DMA0_A) {
1194                         devpriv->dma0Control = PLX_CLEAR_DMA_INTR_BIT;
1195                         writeb(devpriv->dma0Control,
1196                                 devpriv->lcfg + LCFG_DMACSR0);
1197                 }
1198         }
1199         writel(0, devpriv->las0 + LAS0_DMA0_RESET);
1200 #endif /* USE_DMA */
1201         writel(0, devpriv->las0 + LAS0_ADC_FIFO_CLEAR);
1202         writel(0, devpriv->las0 + LAS0_OVERRUN);
1203         devpriv->intCount = 0;
1204
1205         if (!dev->irq) {        /* we need interrupts for this */
1206                 DPRINTK("rtd520: ERROR! No interrupt available!\n");
1207                 return -ENXIO;
1208         }
1209
1210         /* start configuration */
1211         /* load channel list and reset CGT */
1212         rtd_load_channelgain_list(dev, cmd->chanlist_len, cmd->chanlist);
1213
1214         /* setup the common case and override if needed */
1215         if (cmd->chanlist_len > 1) {
1216                 /*DPRINTK ("rtd520: Multi channel setup\n"); */
1217                 /* pacer start source: SOFTWARE */
1218                 writel(0, devpriv->las0 + LAS0_PACER_START);
1219                 /* burst trigger source: PACER */
1220                 writel(1, devpriv->las0 + LAS0_BURST_START);
1221                 /* ADC conversion trigger source: BURST */
1222                 writel(2, devpriv->las0 + LAS0_ADC_CONVERSION);
1223         } else {                /* single channel */
1224                 /*DPRINTK ("rtd520: single channel setup\n"); */
1225                 /* pacer start source: SOFTWARE */
1226                 writel(0, devpriv->las0 + LAS0_PACER_START);
1227                 /* ADC conversion trigger source: PACER */
1228                 writel(1, devpriv->las0 + LAS0_ADC_CONVERSION);
1229         }
1230         writel((devpriv->fifoLen / 2 - 1) & 0xffff, devpriv->las0 + LAS0_ACNT);
1231
1232         if (TRIG_TIMER == cmd->scan_begin_src) {
1233                 /* scan_begin_arg is in nanoseconds */
1234                 /* find out how many samples to wait before transferring */
1235                 if (cmd->flags & TRIG_WAKE_EOS) {
1236                         /* this may generate un-sustainable interrupt rates */
1237                         /* the application is responsible for doing the right thing */
1238                         devpriv->transCount = cmd->chanlist_len;
1239                         devpriv->flags |= SEND_EOS;
1240                 } else {
1241                         /* arrange to transfer data periodically */
1242                         devpriv->transCount
1243                             =
1244                             (TRANS_TARGET_PERIOD * cmd->chanlist_len) /
1245                             cmd->scan_begin_arg;
1246                         if (devpriv->transCount < cmd->chanlist_len) {
1247                                 /* transfer after each scan (and avoid 0) */
1248                                 devpriv->transCount = cmd->chanlist_len;
1249                         } else {        /* make a multiple of scan length */
1250                                 devpriv->transCount =
1251                                     (devpriv->transCount +
1252                                      cmd->chanlist_len - 1)
1253                                     / cmd->chanlist_len;
1254                                 devpriv->transCount *= cmd->chanlist_len;
1255                         }
1256                         devpriv->flags |= SEND_EOS;
1257                 }
1258                 if (devpriv->transCount >= (devpriv->fifoLen / 2)) {
1259                         /* out of counter range, use 1/2 fifo instead */
1260                         devpriv->transCount = 0;
1261                         devpriv->flags &= ~SEND_EOS;
1262                 } else {
1263                         /* interrupt for each transfer */
1264                         writel((devpriv->transCount - 1) & 0xffff,
1265                                 devpriv->las0 + LAS0_ACNT);
1266                 }
1267
1268                 DPRINTK
1269                     ("rtd520: scanLen=%d transferCount=%d fifoLen=%d\n  scanTime(ns)=%d flags=0x%x\n",
1270                      cmd->chanlist_len, devpriv->transCount, devpriv->fifoLen,
1271                      cmd->scan_begin_arg, devpriv->flags);
1272         } else {                /* unknown timing, just use 1/2 FIFO */
1273                 devpriv->transCount = 0;
1274                 devpriv->flags &= ~SEND_EOS;
1275         }
1276         /* pacer clock source: INTERNAL 8MHz */
1277         writel(1, devpriv->las0 + LAS0_PACER_SELECT);
1278         /* just interrupt, don't stop */
1279         writel(1, devpriv->las0 + LAS0_ACNT_STOP_ENABLE);
1280
1281         /* BUG??? these look like enumerated values, but they are bit fields */
1282
1283         /* First, setup when to stop */
1284         switch (cmd->stop_src) {
1285         case TRIG_COUNT:        /* stop after N scans */
1286                 devpriv->aiCount = cmd->stop_arg * cmd->chanlist_len;
1287                 if ((devpriv->transCount > 0)
1288                     && (devpriv->transCount > devpriv->aiCount)) {
1289                         devpriv->transCount = devpriv->aiCount;
1290                 }
1291                 break;
1292
1293         case TRIG_NONE: /* stop when cancel is called */
1294                 devpriv->aiCount = -1;  /* read forever */
1295                 break;
1296
1297         default:
1298                 DPRINTK("rtd520: Warning! ignoring stop_src mode %d\n",
1299                         cmd->stop_src);
1300         }
1301
1302         /* Scan timing */
1303         switch (cmd->scan_begin_src) {
1304         case TRIG_TIMER:        /* periodic scanning */
1305                 timer = rtd_ns_to_timer(&cmd->scan_begin_arg,
1306                                         TRIG_ROUND_NEAREST);
1307                 /* set PACER clock */
1308                 /*DPRINTK ("rtd520: loading %d into pacer\n", timer); */
1309                 writel(timer & 0xffffff, devpriv->las0 + LAS0_PCLK);
1310
1311                 break;
1312
1313         case TRIG_EXT:
1314                 /* pacer start source: EXTERNAL */
1315                 writel(1, devpriv->las0 + LAS0_PACER_START);
1316                 break;
1317
1318         default:
1319                 DPRINTK("rtd520: Warning! ignoring scan_begin_src mode %d\n",
1320                         cmd->scan_begin_src);
1321         }
1322
1323         /* Sample timing within a scan */
1324         switch (cmd->convert_src) {
1325         case TRIG_TIMER:        /* periodic */
1326                 if (cmd->chanlist_len > 1) {    /* only needed for multi-channel */
1327                         timer = rtd_ns_to_timer(&cmd->convert_arg,
1328                                                 TRIG_ROUND_NEAREST);
1329                         /* setup BURST clock */
1330                         /*DPRINTK ("rtd520: loading %d into burst\n", timer); */
1331                         writel(timer & 0x3ff, devpriv->las0 + LAS0_BCLK);
1332                 }
1333
1334                 break;
1335
1336         case TRIG_EXT:          /* external */
1337                 /* burst trigger source: EXTERNAL */
1338                 writel(2, devpriv->las0 + LAS0_BURST_START);
1339                 break;
1340
1341         default:
1342                 DPRINTK("rtd520: Warning! ignoring convert_src mode %d\n",
1343                         cmd->convert_src);
1344         }
1345         /* end configuration */
1346
1347         /* This doesn't seem to work.  There is no way to clear an interrupt
1348            that the priority controller has queued! */
1349         devpriv->intClearMask = ~0;
1350         writew(devpriv->intClearMask, devpriv->las0 + LAS0_CLEAR);
1351         readw(devpriv->las0 + LAS0_CLEAR);
1352
1353         /* TODO: allow multiple interrupt sources */
1354         if (devpriv->transCount > 0) {  /* transfer every N samples */
1355                 devpriv->intMask = IRQM_ADC_ABOUT_CNT;
1356                 writew(devpriv->intMask, devpriv->las0 + LAS0_IT);
1357                 DPRINTK("rtd520: Transferring every %d\n", devpriv->transCount);
1358         } else {                /* 1/2 FIFO transfers */
1359 #ifdef USE_DMA
1360                 devpriv->flags |= DMA0_ACTIVE;
1361
1362                 /* point to first transfer in ring */
1363                 devpriv->dma0Offset = 0;
1364                 writel(DMA_MODE_BITS, devpriv->lcfg + LCFG_DMAMODE0);
1365                 /* point to first block */
1366                 writel(devpriv->dma0Chain[DMA_CHAIN_COUNT - 1].next,
1367                         devpriv->lcfg + LCFG_DMADPR0);
1368                 writel(DMAS_ADFIFO_HALF_FULL, devpriv->las0 + LAS0_DMA0_SRC);
1369                 writel(readl(devpriv->lcfg + LCFG_ITCSR) | ICS_DMA0_E,
1370                         devpriv->lcfg + LCFG_ITCSR);
1371                 /* Must be 2 steps.  See PLX app note about "Starting a DMA transfer" */
1372                 devpriv->dma0Control = PLX_DMA_EN_BIT;
1373                 writeb(devpriv->dma0Control,
1374                         devpriv->lcfg + LCFG_DMACSR0);
1375                 devpriv->dma0Control |= PLX_DMA_START_BIT;
1376                 writeb(devpriv->dma0Control,
1377                         devpriv->lcfg + LCFG_DMACSR0);
1378                 DPRINTK("rtd520: Using DMA0 transfers. plxInt %x RtdInt %x\n",
1379                         readl(devpriv->lcfg + LCFG_ITCSR), devpriv->intMask);
1380 #else /* USE_DMA */
1381                 devpriv->intMask = IRQM_ADC_ABOUT_CNT;
1382                 writew(devpriv->intMask, devpriv->las0 + LAS0_IT);
1383                 DPRINTK("rtd520: Transferring every 1/2 FIFO\n");
1384 #endif /* USE_DMA */
1385         }
1386
1387         /* BUG: start_src is ASSUMED to be TRIG_NOW */
1388         /* BUG? it seems like things are running before the "start" */
1389         readl(devpriv->las0 + LAS0_PACER);      /* start pacer */
1390         return 0;
1391 }
1392
1393 /*
1394   Stop a running data acquisition.
1395 */
1396 static int rtd_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
1397 {
1398         struct rtdPrivate *devpriv = dev->private;
1399         u32 overrun;
1400         u16 status;
1401
1402         /* pacer stop source: SOFTWARE */
1403         writel(0, devpriv->las0 + LAS0_PACER_STOP);
1404         writel(0, devpriv->las0 + LAS0_PACER);  /* stop pacer */
1405         writel(0, devpriv->las0 + LAS0_ADC_CONVERSION);
1406         devpriv->intMask = 0;
1407         writew(devpriv->intMask, devpriv->las0 + LAS0_IT);
1408         devpriv->aiCount = 0;   /* stop and don't transfer any more */
1409 #ifdef USE_DMA
1410         if (devpriv->flags & DMA0_ACTIVE) {
1411                 writel(readl(devpriv->lcfg + LCFG_ITCSR) & ~ICS_DMA0_E,
1412                         devpriv->lcfg + LCFG_ITCSR);
1413                 abort_dma(dev, 0);
1414                 devpriv->flags &= ~DMA0_ACTIVE;
1415         }
1416 #endif /* USE_DMA */
1417         status = readw(devpriv->las0 + LAS0_IT);
1418         overrun = readl(devpriv->las0 + LAS0_OVERRUN) & 0xffff;
1419         DPRINTK
1420             ("rtd520: Acquisition canceled. %ld ints, intStat=%x, overStat=%x\n",
1421              devpriv->intCount, status, overrun);
1422         return 0;
1423 }
1424
1425 /*
1426   Output one (or more) analog values to a single port as fast as possible.
1427 */
1428 static int rtd_ao_winsn(struct comedi_device *dev,
1429                         struct comedi_subdevice *s, struct comedi_insn *insn,
1430                         unsigned int *data)
1431 {
1432         struct rtdPrivate *devpriv = dev->private;
1433         int i;
1434         int chan = CR_CHAN(insn->chanspec);
1435         int range = CR_RANGE(insn->chanspec);
1436
1437         /* Configure the output range (table index matches the range values) */
1438         writew(range & 7, devpriv->las0 +
1439                 ((chan == 0) ? LAS0_DAC1_CTRL : LAS0_DAC2_CTRL));
1440
1441         /* Writing a list of values to an AO channel is probably not
1442          * very useful, but that's how the interface is defined. */
1443         for (i = 0; i < insn->n; ++i) {
1444                 int val = data[i] << 3;
1445                 int stat = 0;   /* initialize to avoid bogus warning */
1446                 int ii;
1447
1448                 /* VERIFY: comedi range and offset conversions */
1449
1450                 if ((range > 1) /* bipolar */
1451                     && (data[i] < 2048)) {
1452                         /* offset and sign extend */
1453                         val = (((int)data[i]) - 2048) << 3;
1454                 } else {        /* unipolor */
1455                         val = data[i] << 3;
1456                 }
1457
1458                 DPRINTK
1459                     ("comedi: rtd520 DAC chan=%d range=%d writing %d as 0x%x\n",
1460                      chan, range, data[i], val);
1461
1462                 /* a typical programming sequence */
1463                 writew(val, devpriv->las1 +
1464                         ((chan == 0) ? LAS1_DAC1_FIFO : LAS1_DAC2_FIFO));
1465                 writew(0, devpriv->las0 + ((chan == 0) ? LAS0_DAC1 : LAS0_DAC2));
1466
1467                 devpriv->aoValue[chan] = data[i];       /* save for read back */
1468
1469                 for (ii = 0; ii < RTD_DAC_TIMEOUT; ++ii) {
1470                         stat = readl(devpriv->las0 + LAS0_ADC);
1471                         /* 1 -> not empty */
1472                         if (stat & ((0 == chan) ? FS_DAC1_NOT_EMPTY :
1473                                     FS_DAC2_NOT_EMPTY))
1474                                 break;
1475                         WAIT_QUIETLY;
1476                 }
1477                 if (ii >= RTD_DAC_TIMEOUT) {
1478                         DPRINTK
1479                             ("rtd520: Error: DAC never finished! FifoStatus=0x%x\n",
1480                              stat ^ 0x6666);
1481                         return -ETIMEDOUT;
1482                 }
1483         }
1484
1485         /* return the number of samples read/written */
1486         return i;
1487 }
1488
1489 /* AO subdevices should have a read insn as well as a write insn.
1490  * Usually this means copying a value stored in devpriv. */
1491 static int rtd_ao_rinsn(struct comedi_device *dev,
1492                         struct comedi_subdevice *s, struct comedi_insn *insn,
1493                         unsigned int *data)
1494 {
1495         struct rtdPrivate *devpriv = dev->private;
1496         int i;
1497         int chan = CR_CHAN(insn->chanspec);
1498
1499         for (i = 0; i < insn->n; i++)
1500                 data[i] = devpriv->aoValue[chan];
1501
1502
1503         return i;
1504 }
1505
1506 /*
1507    Write a masked set of bits and the read back the port.
1508    We track what the bits should be (i.e. we don't read the port first).
1509
1510    DIO devices are slightly special.  Although it is possible to
1511  * implement the insn_read/insn_write interface, it is much more
1512  * useful to applications if you implement the insn_bits interface.
1513  * This allows packed reading/writing of the DIO channels.  The
1514  * comedi core can convert between insn_bits and insn_read/write
1515  */
1516 static int rtd_dio_insn_bits(struct comedi_device *dev,
1517                              struct comedi_subdevice *s,
1518                              struct comedi_insn *insn, unsigned int *data)
1519 {
1520         struct rtdPrivate *devpriv = dev->private;
1521
1522         /* The insn data is a mask in data[0] and the new data
1523          * in data[1], each channel cooresponding to a bit. */
1524         if (data[0]) {
1525                 s->state &= ~data[0];
1526                 s->state |= data[0] & data[1];
1527
1528                 /* Write out the new digital output lines */
1529                 writew(s->state & 0xff, devpriv->las0 + LAS0_DIO0);
1530         }
1531         /* on return, data[1] contains the value of the digital
1532          * input lines. */
1533         data[1] = readw(devpriv->las0 + LAS0_DIO0) & 0xff;
1534
1535         /*DPRINTK("rtd520:port_0 wrote: 0x%x read: 0x%x\n", s->state, data[1]); */
1536
1537         return insn->n;
1538 }
1539
1540 /*
1541   Configure one bit on a IO port as Input or Output (hence the name :-).
1542 */
1543 static int rtd_dio_insn_config(struct comedi_device *dev,
1544                                struct comedi_subdevice *s,
1545                                struct comedi_insn *insn, unsigned int *data)
1546 {
1547         struct rtdPrivate *devpriv = dev->private;
1548         int chan = CR_CHAN(insn->chanspec);
1549
1550         /* The input or output configuration of each digital line is
1551          * configured by a special insn_config instruction.  chanspec
1552          * contains the channel to be changed, and data[0] contains the
1553          * value COMEDI_INPUT or COMEDI_OUTPUT. */
1554         switch (data[0]) {
1555         case INSN_CONFIG_DIO_OUTPUT:
1556                 s->io_bits |= 1 << chan;        /* 1 means Out */
1557                 break;
1558         case INSN_CONFIG_DIO_INPUT:
1559                 s->io_bits &= ~(1 << chan);
1560                 break;
1561         case INSN_CONFIG_DIO_QUERY:
1562                 data[1] =
1563                     (s->io_bits & (1 << chan)) ? COMEDI_OUTPUT : COMEDI_INPUT;
1564                 return insn->n;
1565                 break;
1566         default:
1567                 return -EINVAL;
1568         }
1569
1570         DPRINTK("rtd520: port_0_direction=0x%x (1 means out)\n", s->io_bits);
1571         /* TODO support digital match interrupts and strobes */
1572         devpriv->dioStatus = 0x01;      /* set direction */
1573         writew(devpriv->dioStatus, devpriv->las0 + LAS0_DIO_STATUS);
1574         writew(s->io_bits & 0xff, devpriv->las0 + LAS0_DIO0_CTRL);
1575         devpriv->dioStatus = 0x00;      /* clear interrupts */
1576         writew(devpriv->dioStatus, devpriv->las0 + LAS0_DIO_STATUS);
1577
1578         /* port1 can only be all input or all output */
1579
1580         /* there are also 2 user input lines and 2 user output lines */
1581
1582         return 1;
1583 }
1584
1585 static struct pci_dev *rtd_find_pci(struct comedi_device *dev,
1586                                     struct comedi_devconfig *it)
1587 {
1588         const struct rtdBoard *thisboard;
1589         struct pci_dev *pcidev = NULL;
1590         int bus = it->options[0];
1591         int slot = it->options[1];
1592         int i;
1593
1594         for_each_pci_dev(pcidev) {
1595                 if (pcidev->vendor != PCI_VENDOR_ID_RTD)
1596                         continue;
1597                 if (bus || slot) {
1598                         if (pcidev->bus->number != bus ||
1599                             PCI_SLOT(pcidev->devfn) != slot)
1600                                 continue;
1601                 }
1602                 for (i = 0; i < ARRAY_SIZE(rtd520Boards); i++) {
1603                         thisboard = &rtd520Boards[i];
1604                         if (pcidev->device == thisboard->device_id) {
1605                                 dev->board_ptr = thisboard;
1606                                 return pcidev;
1607                         }
1608                 }
1609         }
1610         dev_warn(dev->class_dev,
1611                 "no supported board found! (req. bus/slot: %d/%d)\n",
1612                 bus, slot);
1613         return NULL;
1614 }
1615
1616 static int rtd_attach(struct comedi_device *dev, struct comedi_devconfig *it)
1617 {                               /* board name and options flags */
1618         const struct rtdBoard *thisboard;
1619         struct rtdPrivate *devpriv;
1620         struct pci_dev *pcidev;
1621         struct comedi_subdevice *s;
1622         int ret;
1623         resource_size_t physLas1;       /* data area */
1624         resource_size_t physLcfg;       /* PLX9080 */
1625 #ifdef USE_DMA
1626         int index;
1627 #endif
1628
1629         printk(KERN_INFO "comedi%d: rtd520 attaching.\n", dev->minor);
1630
1631 #if defined(CONFIG_COMEDI_DEBUG) && defined(USE_DMA)
1632         /* You can set this a load time: modprobe comedi comedi_debug=1 */
1633         if (0 == comedi_debug)  /* force DMA debug printks */
1634                 comedi_debug = 1;
1635 #endif
1636
1637         /*
1638          * Allocate the private structure area.  alloc_private() is a
1639          * convenient macro defined in comedidev.h.
1640          */
1641         if (alloc_private(dev, sizeof(struct rtdPrivate)) < 0)
1642                 return -ENOMEM;
1643         devpriv = dev->private;
1644
1645         pcidev = rtd_find_pci(dev, it);
1646         if (!pcidev)
1647                 return -EIO;
1648         comedi_set_hw_dev(dev, &pcidev->dev);
1649         thisboard = comedi_board(dev);
1650
1651         dev->board_name = thisboard->name;
1652
1653         ret = comedi_pci_enable(pcidev, DRV_NAME);
1654         if (ret < 0) {
1655                 printk(KERN_INFO "Failed to enable PCI device and request regions.\n");
1656                 return ret;
1657         }
1658
1659         /*
1660          * Initialize base addresses
1661          */
1662         /* Get the physical address from PCI config */
1663         dev->iobase = pci_resource_start(pcidev, LAS0_PCIINDEX);
1664         physLas1 = pci_resource_start(pcidev, LAS1_PCIINDEX);
1665         physLcfg = pci_resource_start(pcidev, LCFG_PCIINDEX);
1666         /* Now have the kernel map this into memory */
1667         /* ASSUME page aligned */
1668         devpriv->las0 = ioremap_nocache(dev->iobase, LAS0_PCISIZE);
1669         devpriv->las1 = ioremap_nocache(physLas1, LAS1_PCISIZE);
1670         devpriv->lcfg = ioremap_nocache(physLcfg, LCFG_PCISIZE);
1671
1672         if (!devpriv->las0 || !devpriv->las1 || !devpriv->lcfg)
1673                 return -ENOMEM;
1674
1675         {                       /* The RTD driver does this */
1676                 unsigned char pci_latency;
1677                 u16 revision;
1678                 /*uint32_t epld_version; */
1679
1680                 pci_read_config_word(pcidev, PCI_REVISION_ID,
1681                                      &revision);
1682                 DPRINTK("%s: PCI revision %d.\n", dev->board_name, revision);
1683
1684                 pci_read_config_byte(pcidev,
1685                                      PCI_LATENCY_TIMER, &pci_latency);
1686                 if (pci_latency < 32) {
1687                         printk(KERN_INFO "%s: PCI latency changed from %d to %d\n",
1688                                dev->board_name, pci_latency, 32);
1689                         pci_write_config_byte(pcidev,
1690                                               PCI_LATENCY_TIMER, 32);
1691                 } else {
1692                         DPRINTK("rtd520: PCI latency = %d\n", pci_latency);
1693                 }
1694
1695                 /*
1696                  * Undocumented EPLD version (doesn't match RTD driver results)
1697                  */
1698                 /*DPRINTK ("rtd520: Reading epld from %p\n",
1699                    devpriv->las0+0);
1700                    epld_version = readl (devpriv->las0+0);
1701                    if ((epld_version & 0xF0) >> 4 == 0x0F) {
1702                    DPRINTK("rtd520: pre-v8 EPLD. (%x)\n", epld_version);
1703                    } else {
1704                    DPRINTK("rtd520: EPLD version %x.\n", epld_version >> 4);
1705                    } */
1706         }
1707
1708         /* Show board configuration */
1709         printk(KERN_INFO "%s:", dev->board_name);
1710
1711         ret = comedi_alloc_subdevices(dev, 4);
1712         if (ret)
1713                 return ret;
1714
1715         s = dev->subdevices + 0;
1716         dev->read_subdev = s;
1717         /* analog input subdevice */
1718         s->type = COMEDI_SUBD_AI;
1719         s->subdev_flags =
1720             SDF_READABLE | SDF_GROUND | SDF_COMMON | SDF_DIFF | SDF_CMD_READ;
1721         s->n_chan = thisboard->aiChans;
1722         s->maxdata = (1 << thisboard->aiBits) - 1;
1723         if (thisboard->aiMaxGain <= 32)
1724                 s->range_table = &rtd_ai_7520_range;
1725         else
1726                 s->range_table = &rtd_ai_4520_range;
1727
1728         s->len_chanlist = RTD_MAX_CHANLIST;     /* devpriv->fifoLen */
1729         s->insn_read = rtd_ai_rinsn;
1730         s->do_cmd = rtd_ai_cmd;
1731         s->do_cmdtest = rtd_ai_cmdtest;
1732         s->cancel = rtd_ai_cancel;
1733         /* s->poll = rtd_ai_poll; *//* not ready yet */
1734
1735         s = dev->subdevices + 1;
1736         /* analog output subdevice */
1737         s->type = COMEDI_SUBD_AO;
1738         s->subdev_flags = SDF_WRITABLE;
1739         s->n_chan = 2;
1740         s->maxdata = (1 << thisboard->aiBits) - 1;
1741         s->range_table = &rtd_ao_range;
1742         s->insn_write = rtd_ao_winsn;
1743         s->insn_read = rtd_ao_rinsn;
1744
1745         s = dev->subdevices + 2;
1746         /* digital i/o subdevice */
1747         s->type = COMEDI_SUBD_DIO;
1748         s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
1749         /* we only support port 0 right now.  Ignoring port 1 and user IO */
1750         s->n_chan = 8;
1751         s->maxdata = 1;
1752         s->range_table = &range_digital;
1753         s->insn_bits = rtd_dio_insn_bits;
1754         s->insn_config = rtd_dio_insn_config;
1755
1756         /* timer/counter subdevices (not currently supported) */
1757         s = dev->subdevices + 3;
1758         s->type = COMEDI_SUBD_COUNTER;
1759         s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
1760         s->n_chan = 3;
1761         s->maxdata = 0xffff;
1762
1763         /* initialize board, per RTD spec */
1764         /* also, initialize shadow registers */
1765         writel(0, devpriv->las0 + LAS0_BOARD_RESET);
1766         udelay(100);            /* needed? */
1767         writel(0, devpriv->lcfg + LCFG_ITCSR);
1768         devpriv->intMask = 0;
1769         writew(devpriv->intMask, devpriv->las0 + LAS0_IT);
1770         devpriv->intClearMask = ~0;
1771         writew(devpriv->intClearMask, devpriv->las0 + LAS0_CLEAR);
1772         readw(devpriv->las0 + LAS0_CLEAR);
1773         writel(0, devpriv->las0 + LAS0_OVERRUN);
1774         writel(0, devpriv->las0 + LAS0_CGT_CLEAR);
1775         writel(0, devpriv->las0 + LAS0_ADC_FIFO_CLEAR);
1776         writel(0, devpriv->las0 + LAS0_DAC1_RESET);
1777         writel(0, devpriv->las0 + LAS0_DAC2_RESET);
1778         /* clear digital IO fifo */
1779         devpriv->dioStatus = 0;
1780         writew(devpriv->dioStatus, devpriv->las0 + LAS0_DIO_STATUS);
1781         devpriv->utcCtrl[0] = (0 << 6) | 0x30;
1782         devpriv->utcCtrl[1] = (1 << 6) | 0x30;
1783         devpriv->utcCtrl[2] = (2 << 6) | 0x30;
1784         devpriv->utcCtrl[3] = (3 << 6) | 0x00;
1785         writeb(devpriv->utcCtrl[0], devpriv->las0 + LAS0_UTC_CTRL);
1786         writeb(devpriv->utcCtrl[1], devpriv->las0 + LAS0_UTC_CTRL);
1787         writeb(devpriv->utcCtrl[2], devpriv->las0 + LAS0_UTC_CTRL);
1788         writeb(devpriv->utcCtrl[3], devpriv->las0 + LAS0_UTC_CTRL);
1789         /* TODO: set user out source ??? */
1790
1791         /* check if our interrupt is available and get it */
1792         ret = request_irq(pcidev->irq, rtd_interrupt,
1793                           IRQF_SHARED, DRV_NAME, dev);
1794
1795         if (ret < 0) {
1796                 printk("Could not get interrupt! (%u)\n",
1797                        pcidev->irq);
1798                 return ret;
1799         }
1800         dev->irq = pcidev->irq;
1801         printk(KERN_INFO "( irq=%u )", dev->irq);
1802
1803         ret = rtd520_probe_fifo_depth(dev);
1804         if (ret < 0)
1805                 return ret;
1806
1807         devpriv->fifoLen = ret;
1808         printk("( fifoLen=%d )", devpriv->fifoLen);
1809
1810 #ifdef USE_DMA
1811         if (dev->irq > 0) {
1812                 printk("( DMA buff=%d )\n", DMA_CHAIN_COUNT);
1813                 /*
1814                  * The PLX9080 has 2 DMA controllers, but there could be
1815                  * 4 sources: ADC, digital, DAC1, and DAC2.  Since only the
1816                  * ADC supports cmd mode right now, this isn't an issue (yet)
1817                  */
1818                 devpriv->dma0Offset = 0;
1819
1820                 for (index = 0; index < DMA_CHAIN_COUNT; index++) {
1821                         devpriv->dma0Buff[index] =
1822                             pci_alloc_consistent(pcidev,
1823                                                  sizeof(u16) *
1824                                                  devpriv->fifoLen / 2,
1825                                                  &devpriv->
1826                                                  dma0BuffPhysAddr[index]);
1827                         if (devpriv->dma0Buff[index] == NULL) {
1828                                 ret = -ENOMEM;
1829                                 goto rtd_attach_die_error;
1830                         }
1831                         /*DPRINTK ("buff[%d] @ %p virtual, %x PCI\n",
1832                            index,
1833                            devpriv->dma0Buff[index],
1834                            devpriv->dma0BuffPhysAddr[index]); */
1835                 }
1836
1837                 /*
1838                  * setup DMA descriptor ring (use cpu_to_le32 for byte
1839                  * ordering?)
1840                  */
1841                 devpriv->dma0Chain =
1842                     pci_alloc_consistent(pcidev,
1843                                          sizeof(struct plx_dma_desc) *
1844                                          DMA_CHAIN_COUNT,
1845                                          &devpriv->dma0ChainPhysAddr);
1846                 for (index = 0; index < DMA_CHAIN_COUNT; index++) {
1847                         devpriv->dma0Chain[index].pci_start_addr =
1848                             devpriv->dma0BuffPhysAddr[index];
1849                         devpriv->dma0Chain[index].local_start_addr =
1850                             DMALADDR_ADC;
1851                         devpriv->dma0Chain[index].transfer_size =
1852                             sizeof(u16) * devpriv->fifoLen / 2;
1853                         devpriv->dma0Chain[index].next =
1854                             (devpriv->dma0ChainPhysAddr + ((index +
1855                                                             1) %
1856                                                            (DMA_CHAIN_COUNT))
1857                              * sizeof(devpriv->dma0Chain[0]))
1858                             | DMA_TRANSFER_BITS;
1859                         /*DPRINTK ("ring[%d] @%lx PCI: %x, local: %x, N: 0x%x, next: %x\n",
1860                            index,
1861                            ((long)devpriv->dma0ChainPhysAddr
1862                            + (index * sizeof(devpriv->dma0Chain[0]))),
1863                            devpriv->dma0Chain[index].pci_start_addr,
1864                            devpriv->dma0Chain[index].local_start_addr,
1865                            devpriv->dma0Chain[index].transfer_size,
1866                            devpriv->dma0Chain[index].next); */
1867                 }
1868
1869                 if (devpriv->dma0Chain == NULL) {
1870                         ret = -ENOMEM;
1871                         goto rtd_attach_die_error;
1872                 }
1873
1874                 writel(DMA_MODE_BITS, devpriv->lcfg + LCFG_DMAMODE0);
1875                 /* set DMA trigger source */
1876                 writel(DMAS_ADFIFO_HALF_FULL, devpriv->las0 + LAS0_DMA0_SRC);
1877         } else {
1878                 printk(KERN_INFO "( no IRQ->no DMA )");
1879         }
1880 #endif /* USE_DMA */
1881
1882         if (dev->irq)
1883                 writel(ICS_PIE | ICS_PLIE, devpriv->lcfg + LCFG_ITCSR);
1884
1885         printk("\ncomedi%d: rtd520 driver attached.\n", dev->minor);
1886
1887         return 1;
1888 }
1889
1890 static void rtd_detach(struct comedi_device *dev)
1891 {
1892         struct rtdPrivate *devpriv = dev->private;
1893         struct pci_dev *pcidev = comedi_to_pci_dev(dev);
1894 #ifdef USE_DMA
1895         int index;
1896 #endif
1897
1898         if (devpriv) {
1899                 /* Shut down any board ops by resetting it */
1900 #ifdef USE_DMA
1901                 if (devpriv->lcfg) {
1902                         devpriv->dma0Control = 0;
1903                         devpriv->dma1Control = 0;
1904                         writeb(devpriv->dma0Control,
1905                                 devpriv->lcfg + LCFG_DMACSR0);
1906                         writeb(devpriv->dma1Control,
1907                                 devpriv->lcfg + LCFG_DMACSR1);
1908                         writel(ICS_PIE | ICS_PLIE, devpriv->lcfg + LCFG_ITCSR);
1909                 }
1910 #endif /* USE_DMA */
1911                 if (devpriv->las0) {
1912                         writel(0, devpriv->las0 + LAS0_BOARD_RESET);
1913                         devpriv->intMask = 0;
1914                         writew(devpriv->intMask, devpriv->las0 + LAS0_IT);
1915                         devpriv->intClearMask = ~0;
1916                         writew(devpriv->intClearMask,
1917                                 devpriv->las0 + LAS0_CLEAR);
1918                         readw(devpriv->las0 + LAS0_CLEAR);
1919                 }
1920 #ifdef USE_DMA
1921                 /* release DMA */
1922                 for (index = 0; index < DMA_CHAIN_COUNT; index++) {
1923                         if (NULL != devpriv->dma0Buff[index]) {
1924                                 pci_free_consistent(pcidev,
1925                                                     sizeof(u16) *
1926                                                     devpriv->fifoLen / 2,
1927                                                     devpriv->dma0Buff[index],
1928                                                     devpriv->
1929                                                     dma0BuffPhysAddr[index]);
1930                                 devpriv->dma0Buff[index] = NULL;
1931                         }
1932                 }
1933                 if (NULL != devpriv->dma0Chain) {
1934                         pci_free_consistent(pcidev,
1935                                             sizeof(struct plx_dma_desc) *
1936                                             DMA_CHAIN_COUNT, devpriv->dma0Chain,
1937                                             devpriv->dma0ChainPhysAddr);
1938                         devpriv->dma0Chain = NULL;
1939                 }
1940 #endif /* USE_DMA */
1941                 if (dev->irq) {
1942                         writel(readl(devpriv->lcfg + LCFG_ITCSR) &
1943                                 ~(ICS_PLIE | ICS_DMA0_E | ICS_DMA1_E),
1944                                 devpriv->lcfg + LCFG_ITCSR);
1945                         free_irq(dev->irq, dev);
1946                 }
1947                 if (devpriv->las0)
1948                         iounmap(devpriv->las0);
1949                 if (devpriv->las1)
1950                         iounmap(devpriv->las1);
1951                 if (devpriv->lcfg)
1952                         iounmap(devpriv->lcfg);
1953         }
1954         if (pcidev) {
1955                 if (dev->iobase)
1956                         comedi_pci_disable(pcidev);
1957                 pci_dev_put(pcidev);
1958         }
1959 }
1960
1961 static struct comedi_driver rtd520_driver = {
1962         .driver_name    = "rtd520",
1963         .module         = THIS_MODULE,
1964         .attach         = rtd_attach,
1965         .detach         = rtd_detach,
1966 };
1967
1968 static int __devinit rtd520_pci_probe(struct pci_dev *dev,
1969                                       const struct pci_device_id *ent)
1970 {
1971         return comedi_pci_auto_config(dev, &rtd520_driver);
1972 }
1973
1974 static void __devexit rtd520_pci_remove(struct pci_dev *dev)
1975 {
1976         comedi_pci_auto_unconfig(dev);
1977 }
1978
1979 static DEFINE_PCI_DEVICE_TABLE(rtd520_pci_table) = {
1980         { PCI_DEVICE(PCI_VENDOR_ID_RTD, 0x7520) },
1981         { PCI_DEVICE(PCI_VENDOR_ID_RTD, 0x4520) },
1982         { 0 }
1983 };
1984 MODULE_DEVICE_TABLE(pci, rtd520_pci_table);
1985
1986 static struct pci_driver rtd520_pci_driver = {
1987         .name           = "rtd520",
1988         .id_table       = rtd520_pci_table,
1989         .probe          = rtd520_pci_probe,
1990         .remove         = __devexit_p(rtd520_pci_remove),
1991 };
1992 module_comedi_pci_driver(rtd520_driver, rtd520_pci_driver);
1993
1994 MODULE_AUTHOR("Comedi http://www.comedi.org");
1995 MODULE_DESCRIPTION("Comedi low-level driver");
1996 MODULE_LICENSE("GPL");