Linux-libre 3.10.70-gnu
[librecmc/linux-libre.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 /*
24  * Driver: rtd520
25  * Description: Real Time Devices PCI4520/DM7520
26  * Devices: (Real Time Devices) DM7520HR-1 [DM7520]
27  *          (Real Time Devices) DM7520HR-8 [DM7520]
28  *          (Real Time Devices) PCI4520 [PCI4520]
29  *          (Real Time Devices) PCI4520-8 [PCI4520]
30  * Author: Dan Christian
31  * Status: Works. Only tested on DM7520-8. Not SMP safe.
32  *
33  * Configuration options: not applicable, uses PCI auto config
34  */
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 cb_pcidas64.c
76  * 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  * driver status:
87  *
88  * Analog-In supports instruction and command mode.
89  *
90  * With DMA, you can sample at 1.15Mhz with 70% idle on a 400Mhz K6-2
91  * (single channel, 64K read buffer). I get random system lockups when
92  * using DMA with ALI-15xx based systems. I haven't been able to test
93  * any other chipsets. The lockups happen soon after the start of an
94  * acquistion, not in the middle of a long run.
95  *
96  * Without DMA, you can do 620Khz sampling with 20% idle on a 400Mhz K6-2
97  * (with a 256K read buffer).
98  *
99  * Digital-IO and Analog-Out only support instruction mode.
100  */
101
102 #include <linux/pci.h>
103 #include <linux/delay.h>
104 #include <linux/interrupt.h>
105
106 #include "../comedidev.h"
107
108 #include "comedi_fc.h"
109 #include "plx9080.h"
110
111 /*
112  * Local Address Space 0 Offsets
113  */
114 #define LAS0_USER_IO            0x0008  /* User I/O */
115 #define LAS0_ADC                0x0010  /* FIFO Status/Software A/D Start */
116 #define FS_DAC1_NOT_EMPTY       (1 << 0)        /* DAC1 FIFO not empty */
117 #define FS_DAC1_HEMPTY          (1 << 1)        /* DAC1 FIFO half empty */
118 #define FS_DAC1_NOT_FULL        (1 << 2)        /* DAC1 FIFO not full */
119 #define FS_DAC2_NOT_EMPTY       (1 << 4)        /* DAC2 FIFO not empty */
120 #define FS_DAC2_HEMPTY          (1 << 5)        /* DAC2 FIFO half empty */
121 #define FS_DAC2_NOT_FULL        (1 << 6)        /* DAC2 FIFO not full */
122 #define FS_ADC_NOT_EMPTY        (1 << 8)        /* ADC FIFO not empty */
123 #define FS_ADC_HEMPTY           (1 << 9)        /* ADC FIFO half empty */
124 #define FS_ADC_NOT_FULL         (1 << 10)       /* ADC FIFO not full */
125 #define FS_DIN_NOT_EMPTY        (1 << 12)       /* DIN FIFO not empty */
126 #define FS_DIN_HEMPTY           (1 << 13)       /* DIN FIFO half empty */
127 #define FS_DIN_NOT_FULL         (1 << 14)       /* DIN FIFO not full */
128 #define LAS0_DAC1               0x0014  /* Software D/A1 Update (w) */
129 #define LAS0_DAC2               0x0018  /* Software D/A2 Update (w) */
130 #define LAS0_DAC                0x0024  /* Software Simultaneous Update (w) */
131 #define LAS0_PACER              0x0028  /* Software Pacer Start/Stop */
132 #define LAS0_TIMER              0x002c  /* Timer Status/HDIN Software Trig. */
133 #define LAS0_IT                 0x0030  /* Interrupt Status/Enable */
134 #define IRQM_ADC_FIFO_WRITE     (1 << 0)        /* ADC FIFO Write */
135 #define IRQM_CGT_RESET          (1 << 1)        /* Reset CGT */
136 #define IRQM_CGT_PAUSE          (1 << 3)        /* Pause CGT */
137 #define IRQM_ADC_ABOUT_CNT      (1 << 4)        /* About Counter out */
138 #define IRQM_ADC_DELAY_CNT      (1 << 5)        /* Delay Counter out */
139 #define IRQM_ADC_SAMPLE_CNT     (1 << 6)        /* ADC Sample Counter */
140 #define IRQM_DAC1_UCNT          (1 << 7)        /* DAC1 Update Counter */
141 #define IRQM_DAC2_UCNT          (1 << 8)        /* DAC2 Update Counter */
142 #define IRQM_UTC1               (1 << 9)        /* User TC1 out */
143 #define IRQM_UTC1_INV           (1 << 10)       /* User TC1 out, inverted */
144 #define IRQM_UTC2               (1 << 11)       /* User TC2 out */
145 #define IRQM_DIGITAL_IT         (1 << 12)       /* Digital Interrupt */
146 #define IRQM_EXTERNAL_IT        (1 << 13)       /* External Interrupt */
147 #define IRQM_ETRIG_RISING       (1 << 14)       /* Ext Trigger rising-edge */
148 #define IRQM_ETRIG_FALLING      (1 << 15)       /* Ext Trigger falling-edge */
149 #define LAS0_CLEAR              0x0034  /* Clear/Set Interrupt Clear Mask */
150 #define LAS0_OVERRUN            0x0038  /* Pending interrupts/Clear Overrun */
151 #define LAS0_PCLK               0x0040  /* Pacer Clock (24bit) */
152 #define LAS0_BCLK               0x0044  /* Burst Clock (10bit) */
153 #define LAS0_ADC_SCNT           0x0048  /* A/D Sample counter (10bit) */
154 #define LAS0_DAC1_UCNT          0x004c  /* D/A1 Update counter (10 bit) */
155 #define LAS0_DAC2_UCNT          0x0050  /* D/A2 Update counter (10 bit) */
156 #define LAS0_DCNT               0x0054  /* Delay counter (16 bit) */
157 #define LAS0_ACNT               0x0058  /* About counter (16 bit) */
158 #define LAS0_DAC_CLK            0x005c  /* DAC clock (16bit) */
159 #define LAS0_UTC0               0x0060  /* 8254 TC Counter 0 */
160 #define LAS0_UTC1               0x0064  /* 8254 TC Counter 1 */
161 #define LAS0_UTC2               0x0068  /* 8254 TC Counter 2 */
162 #define LAS0_UTC_CTRL           0x006c  /* 8254 TC Control */
163 #define LAS0_DIO0               0x0070  /* Digital I/O Port 0 */
164 #define LAS0_DIO1               0x0074  /* Digital I/O Port 1 */
165 #define LAS0_DIO0_CTRL          0x0078  /* Digital I/O Control */
166 #define LAS0_DIO_STATUS         0x007c  /* Digital I/O Status */
167 #define LAS0_BOARD_RESET        0x0100  /* Board reset */
168 #define LAS0_DMA0_SRC           0x0104  /* DMA 0 Sources select */
169 #define LAS0_DMA1_SRC           0x0108  /* DMA 1 Sources select */
170 #define LAS0_ADC_CONVERSION     0x010c  /* A/D Conversion Signal select */
171 #define LAS0_BURST_START        0x0110  /* Burst Clock Start Trigger select */
172 #define LAS0_PACER_START        0x0114  /* Pacer Clock Start Trigger select */
173 #define LAS0_PACER_STOP         0x0118  /* Pacer Clock Stop Trigger select */
174 #define LAS0_ACNT_STOP_ENABLE   0x011c  /* About Counter Stop Enable */
175 #define LAS0_PACER_REPEAT       0x0120  /* Pacer Start Trigger Mode select */
176 #define LAS0_DIN_START          0x0124  /* HiSpd DI Sampling Signal select */
177 #define LAS0_DIN_FIFO_CLEAR     0x0128  /* Digital Input FIFO Clear */
178 #define LAS0_ADC_FIFO_CLEAR     0x012c  /* A/D FIFO Clear */
179 #define LAS0_CGT_WRITE          0x0130  /* Channel Gain Table Write */
180 #define LAS0_CGL_WRITE          0x0134  /* Channel Gain Latch Write */
181 #define LAS0_CG_DATA            0x0138  /* Digital Table Write */
182 #define LAS0_CGT_ENABLE         0x013c  /* Channel Gain Table Enable */
183 #define LAS0_CG_ENABLE          0x0140  /* Digital Table Enable */
184 #define LAS0_CGT_PAUSE          0x0144  /* Table Pause Enable */
185 #define LAS0_CGT_RESET          0x0148  /* Reset Channel Gain Table */
186 #define LAS0_CGT_CLEAR          0x014c  /* Clear Channel Gain Table */
187 #define LAS0_DAC1_CTRL          0x0150  /* D/A1 output type/range */
188 #define LAS0_DAC1_SRC           0x0154  /* D/A1 update source */
189 #define LAS0_DAC1_CYCLE         0x0158  /* D/A1 cycle mode */
190 #define LAS0_DAC1_RESET         0x015c  /* D/A1 FIFO reset */
191 #define LAS0_DAC1_FIFO_CLEAR    0x0160  /* D/A1 FIFO clear */
192 #define LAS0_DAC2_CTRL          0x0164  /* D/A2 output type/range */
193 #define LAS0_DAC2_SRC           0x0168  /* D/A2 update source */
194 #define LAS0_DAC2_CYCLE         0x016c  /* D/A2 cycle mode */
195 #define LAS0_DAC2_RESET         0x0170  /* D/A2 FIFO reset */
196 #define LAS0_DAC2_FIFO_CLEAR    0x0174  /* D/A2 FIFO clear */
197 #define LAS0_ADC_SCNT_SRC       0x0178  /* A/D Sample Counter Source select */
198 #define LAS0_PACER_SELECT       0x0180  /* Pacer Clock select */
199 #define LAS0_SBUS0_SRC          0x0184  /* SyncBus 0 Source select */
200 #define LAS0_SBUS0_ENABLE       0x0188  /* SyncBus 0 enable */
201 #define LAS0_SBUS1_SRC          0x018c  /* SyncBus 1 Source select */
202 #define LAS0_SBUS1_ENABLE       0x0190  /* SyncBus 1 enable */
203 #define LAS0_SBUS2_SRC          0x0198  /* SyncBus 2 Source select */
204 #define LAS0_SBUS2_ENABLE       0x019c  /* SyncBus 2 enable */
205 #define LAS0_ETRG_POLARITY      0x01a4  /* Ext. Trigger polarity select */
206 #define LAS0_EINT_POLARITY      0x01a8  /* Ext. Interrupt polarity select */
207 #define LAS0_UTC0_CLOCK         0x01ac  /* UTC0 Clock select */
208 #define LAS0_UTC0_GATE          0x01b0  /* UTC0 Gate select */
209 #define LAS0_UTC1_CLOCK         0x01b4  /* UTC1 Clock select */
210 #define LAS0_UTC1_GATE          0x01b8  /* UTC1 Gate select */
211 #define LAS0_UTC2_CLOCK         0x01bc  /* UTC2 Clock select */
212 #define LAS0_UTC2_GATE          0x01c0  /* UTC2 Gate select */
213 #define LAS0_UOUT0_SELECT       0x01c4  /* User Output 0 source select */
214 #define LAS0_UOUT1_SELECT       0x01c8  /* User Output 1 source select */
215 #define LAS0_DMA0_RESET         0x01cc  /* DMA0 Request state machine reset */
216 #define LAS0_DMA1_RESET         0x01d0  /* DMA1 Request state machine reset */
217
218 /*
219  * Local Address Space 1 Offsets
220  */
221 #define LAS1_ADC_FIFO           0x0000  /* A/D FIFO (16bit) */
222 #define LAS1_HDIO_FIFO          0x0004  /* HiSpd DI FIFO (16bit) */
223 #define LAS1_DAC1_FIFO          0x0008  /* D/A1 FIFO (16bit) */
224 #define LAS1_DAC2_FIFO          0x000c  /* D/A2 FIFO (16bit) */
225
226 /*======================================================================
227   Driver specific stuff (tunable)
228 ======================================================================*/
229
230 /* We really only need 2 buffers.  More than that means being much
231    smarter about knowing which ones are full. */
232 #define DMA_CHAIN_COUNT 2       /* max DMA segments/buffers in a ring (min 2) */
233
234 /* Target period for periodic transfers.  This sets the user read latency. */
235 /* Note: There are certain rates where we give this up and transfer 1/2 FIFO */
236 /* If this is too low, efficiency is poor */
237 #define TRANS_TARGET_PERIOD 10000000    /* 10 ms (in nanoseconds) */
238
239 /* Set a practical limit on how long a list to support (affects memory use) */
240 /* The board support a channel list up to the FIFO length (1K or 8K) */
241 #define RTD_MAX_CHANLIST        128     /* max channel list that we allow */
242
243 /* tuning for ai/ao instruction done polling */
244 #ifdef FAST_SPIN
245 #define WAIT_QUIETLY            /* as nothing, spin on done bit */
246 #define RTD_ADC_TIMEOUT 66000   /* 2 msec at 33mhz bus rate */
247 #define RTD_DAC_TIMEOUT 66000
248 #define RTD_DMA_TIMEOUT 33000   /* 1 msec */
249 #else
250 /* by delaying, power and electrical noise are reduced somewhat */
251 #define WAIT_QUIETLY    udelay(1)
252 #define RTD_ADC_TIMEOUT 2000    /* in usec */
253 #define RTD_DAC_TIMEOUT 2000    /* in usec */
254 #define RTD_DMA_TIMEOUT 1000    /* in usec */
255 #endif
256
257 /*======================================================================
258   Board specific stuff
259 ======================================================================*/
260
261 #define RTD_CLOCK_RATE  8000000 /* 8Mhz onboard clock */
262 #define RTD_CLOCK_BASE  125     /* clock period in ns */
263
264 /* Note: these speed are slower than the spec, but fit the counter resolution*/
265 #define RTD_MAX_SPEED   1625    /* when sampling, in nanoseconds */
266 /* max speed if we don't have to wait for settling */
267 #define RTD_MAX_SPEED_1 875     /* if single channel, in nanoseconds */
268
269 #define RTD_MIN_SPEED   2097151875      /* (24bit counter) in nanoseconds */
270 /* min speed when only 1 channel (no burst counter) */
271 #define RTD_MIN_SPEED_1 5000000 /* 200Hz, in nanoseconds */
272
273 /* Setup continuous ring of 1/2 FIFO transfers.  See RTD manual p91 */
274 #define DMA_MODE_BITS (\
275                        PLX_LOCAL_BUS_16_WIDE_BITS \
276                        | PLX_DMA_EN_READYIN_BIT \
277                        | PLX_DMA_LOCAL_BURST_EN_BIT \
278                        | PLX_EN_CHAIN_BIT \
279                        | PLX_DMA_INTR_PCI_BIT \
280                        | PLX_LOCAL_ADDR_CONST_BIT \
281                        | PLX_DEMAND_MODE_BIT)
282
283 #define DMA_TRANSFER_BITS (\
284 /* descriptors in PCI memory*/  PLX_DESC_IN_PCI_BIT \
285 /* interrupt at end of block */ | PLX_INTR_TERM_COUNT \
286 /* from board to PCI */         | PLX_XFER_LOCAL_TO_PCI)
287
288 /*======================================================================
289   Comedi specific stuff
290 ======================================================================*/
291
292 /*
293  * The board has 3 input modes and the gains of 1,2,4,...32 (, 64, 128)
294  */
295 static const struct comedi_lrange rtd_ai_7520_range = {
296         18, {
297                 /* +-5V input range gain steps */
298                 BIP_RANGE(5.0),
299                 BIP_RANGE(5.0 / 2),
300                 BIP_RANGE(5.0 / 4),
301                 BIP_RANGE(5.0 / 8),
302                 BIP_RANGE(5.0 / 16),
303                 BIP_RANGE(5.0 / 32),
304                 /* +-10V input range gain steps */
305                 BIP_RANGE(10.0),
306                 BIP_RANGE(10.0 / 2),
307                 BIP_RANGE(10.0 / 4),
308                 BIP_RANGE(10.0 / 8),
309                 BIP_RANGE(10.0 / 16),
310                 BIP_RANGE(10.0 / 32),
311                 /* +10V input range gain steps */
312                 UNI_RANGE(10.0),
313                 UNI_RANGE(10.0 / 2),
314                 UNI_RANGE(10.0 / 4),
315                 UNI_RANGE(10.0 / 8),
316                 UNI_RANGE(10.0 / 16),
317                 UNI_RANGE(10.0 / 32),
318         }
319 };
320
321 /* PCI4520 has two more gains (6 more entries) */
322 static const struct comedi_lrange rtd_ai_4520_range = {
323         24, {
324                 /* +-5V input range gain steps */
325                 BIP_RANGE(5.0),
326                 BIP_RANGE(5.0 / 2),
327                 BIP_RANGE(5.0 / 4),
328                 BIP_RANGE(5.0 / 8),
329                 BIP_RANGE(5.0 / 16),
330                 BIP_RANGE(5.0 / 32),
331                 BIP_RANGE(5.0 / 64),
332                 BIP_RANGE(5.0 / 128),
333                 /* +-10V input range gain steps */
334                 BIP_RANGE(10.0),
335                 BIP_RANGE(10.0 / 2),
336                 BIP_RANGE(10.0 / 4),
337                 BIP_RANGE(10.0 / 8),
338                 BIP_RANGE(10.0 / 16),
339                 BIP_RANGE(10.0 / 32),
340                 BIP_RANGE(10.0 / 64),
341                 BIP_RANGE(10.0 / 128),
342                 /* +10V input range gain steps */
343                 UNI_RANGE(10.0),
344                 UNI_RANGE(10.0 / 2),
345                 UNI_RANGE(10.0 / 4),
346                 UNI_RANGE(10.0 / 8),
347                 UNI_RANGE(10.0 / 16),
348                 UNI_RANGE(10.0 / 32),
349                 UNI_RANGE(10.0 / 64),
350                 UNI_RANGE(10.0 / 128),
351         }
352 };
353
354 /* Table order matches range values */
355 static const struct comedi_lrange rtd_ao_range = {
356         4, {
357                 UNI_RANGE(5),
358                 UNI_RANGE(10),
359                 BIP_RANGE(5),
360                 BIP_RANGE(10),
361         }
362 };
363
364 enum rtd_boardid {
365         BOARD_DM7520,
366         BOARD_PCI4520,
367 };
368
369 struct rtd_boardinfo {
370         const char *name;
371         int range_bip10;        /* start of +-10V range */
372         int range_uni10;        /* start of +10V range */
373         const struct comedi_lrange *ai_range;
374 };
375
376 static const struct rtd_boardinfo rtd520Boards[] = {
377         [BOARD_DM7520] = {
378                 .name           = "DM7520",
379                 .range_bip10    = 6,
380                 .range_uni10    = 12,
381                 .ai_range       = &rtd_ai_7520_range,
382         },
383         [BOARD_PCI4520] = {
384                 .name           = "PCI4520",
385                 .range_bip10    = 8,
386                 .range_uni10    = 16,
387                 .ai_range       = &rtd_ai_4520_range,
388         },
389 };
390
391 struct rtd_private {
392         /* memory mapped board structures */
393         void __iomem *las0;
394         void __iomem *las1;
395         void __iomem *lcfg;
396
397         long ai_count;          /* total transfer size (samples) */
398         int xfer_count;         /* # to transfer data. 0->1/2FIFO */
399         int flags;              /* flag event modes */
400
401         unsigned char chan_is_bipolar[RTD_MAX_CHANLIST / 8];    /* bit array */
402
403         unsigned int ao_readback[2];
404
405         unsigned fifosz;
406 };
407
408 /* bit defines for "flags" */
409 #define SEND_EOS        0x01    /* send End Of Scan events */
410 #define DMA0_ACTIVE     0x02    /* DMA0 is active */
411 #define DMA1_ACTIVE     0x04    /* DMA1 is active */
412
413 /* Macros for accessing channel list bit array */
414 #define CHAN_ARRAY_TEST(array, index) \
415         (((array)[(index)/8] >> ((index) & 0x7)) & 0x1)
416 #define CHAN_ARRAY_SET(array, index) \
417         (((array)[(index)/8] |= 1 << ((index) & 0x7)))
418 #define CHAN_ARRAY_CLEAR(array, index) \
419         (((array)[(index)/8] &= ~(1 << ((index) & 0x7))))
420
421 /*
422   Given a desired period and the clock period (both in ns),
423   return the proper counter value (divider-1).
424   Sets the original period to be the true value.
425   Note: you have to check if the value is larger than the counter range!
426 */
427 static int rtd_ns_to_timer_base(unsigned int *nanosec,
428                                 int round_mode, int base)
429 {
430         int divider;
431
432         switch (round_mode) {
433         case TRIG_ROUND_NEAREST:
434         default:
435                 divider = (*nanosec + base / 2) / base;
436                 break;
437         case TRIG_ROUND_DOWN:
438                 divider = (*nanosec) / base;
439                 break;
440         case TRIG_ROUND_UP:
441                 divider = (*nanosec + base - 1) / base;
442                 break;
443         }
444         if (divider < 2)
445                 divider = 2;    /* min is divide by 2 */
446
447         /* Note: we don't check for max, because different timers
448            have different ranges */
449
450         *nanosec = base * divider;
451         return divider - 1;     /* countdown is divisor+1 */
452 }
453
454 /*
455   Given a desired period (in ns),
456   return the proper counter value (divider-1) for the internal clock.
457   Sets the original period to be the true value.
458 */
459 static int rtd_ns_to_timer(unsigned int *ns, int round_mode)
460 {
461         return rtd_ns_to_timer_base(ns, round_mode, RTD_CLOCK_BASE);
462 }
463
464 /*
465   Convert a single comedi channel-gain entry to a RTD520 table entry
466 */
467 static unsigned short rtd_convert_chan_gain(struct comedi_device *dev,
468                                             unsigned int chanspec, int index)
469 {
470         const struct rtd_boardinfo *board = comedi_board(dev);
471         struct rtd_private *devpriv = dev->private;
472         unsigned int chan = CR_CHAN(chanspec);
473         unsigned int range = CR_RANGE(chanspec);
474         unsigned int aref = CR_AREF(chanspec);
475         unsigned short r = 0;
476
477         r |= chan & 0xf;
478
479         /* Note: we also setup the channel list bipolar flag array */
480         if (range < board->range_bip10) {
481                 /* +-5 range */
482                 r |= 0x000;
483                 r |= (range & 0x7) << 4;
484                 CHAN_ARRAY_SET(devpriv->chan_is_bipolar, index);
485         } else if (range < board->range_uni10) {
486                 /* +-10 range */
487                 r |= 0x100;
488                 r |= ((range - board->range_bip10) & 0x7) << 4;
489                 CHAN_ARRAY_SET(devpriv->chan_is_bipolar, index);
490         } else {
491                 /* +10 range */
492                 r |= 0x200;
493                 r |= ((range - board->range_uni10) & 0x7) << 4;
494                 CHAN_ARRAY_CLEAR(devpriv->chan_is_bipolar, index);
495         }
496
497         switch (aref) {
498         case AREF_GROUND:       /* on-board ground */
499                 break;
500
501         case AREF_COMMON:
502                 r |= 0x80;      /* ref external analog common */
503                 break;
504
505         case AREF_DIFF:
506                 r |= 0x400;     /* differential inputs */
507                 break;
508
509         case AREF_OTHER:        /* ??? */
510                 break;
511         }
512         /*printk ("chan=%d r=%d a=%d -> 0x%x\n",
513            chan, range, aref, r); */
514         return r;
515 }
516
517 /*
518   Setup the channel-gain table from a comedi list
519 */
520 static void rtd_load_channelgain_list(struct comedi_device *dev,
521                                       unsigned int n_chan, unsigned int *list)
522 {
523         struct rtd_private *devpriv = dev->private;
524
525         if (n_chan > 1) {       /* setup channel gain table */
526                 int ii;
527
528                 writel(0, devpriv->las0 + LAS0_CGT_CLEAR);
529                 writel(1, devpriv->las0 + LAS0_CGT_ENABLE);
530                 for (ii = 0; ii < n_chan; ii++) {
531                         writel(rtd_convert_chan_gain(dev, list[ii], ii),
532                                 devpriv->las0 + LAS0_CGT_WRITE);
533                 }
534         } else {                /* just use the channel gain latch */
535                 writel(0, devpriv->las0 + LAS0_CGT_ENABLE);
536                 writel(rtd_convert_chan_gain(dev, list[0], 0),
537                         devpriv->las0 + LAS0_CGL_WRITE);
538         }
539 }
540
541 /* determine fifo size by doing adc conversions until the fifo half
542 empty status flag clears */
543 static int rtd520_probe_fifo_depth(struct comedi_device *dev)
544 {
545         struct rtd_private *devpriv = dev->private;
546         unsigned int chanspec = CR_PACK(0, 0, AREF_GROUND);
547         unsigned i;
548         static const unsigned limit = 0x2000;
549         unsigned fifo_size = 0;
550
551         writel(0, devpriv->las0 + LAS0_ADC_FIFO_CLEAR);
552         rtd_load_channelgain_list(dev, 1, &chanspec);
553         /* ADC conversion trigger source: SOFTWARE */
554         writel(0, devpriv->las0 + LAS0_ADC_CONVERSION);
555         /* convert  samples */
556         for (i = 0; i < limit; ++i) {
557                 unsigned fifo_status;
558                 /* trigger conversion */
559                 writew(0, devpriv->las0 + LAS0_ADC);
560                 udelay(1);
561                 fifo_status = readl(devpriv->las0 + LAS0_ADC);
562                 if ((fifo_status & FS_ADC_HEMPTY) == 0) {
563                         fifo_size = 2 * i;
564                         break;
565                 }
566         }
567         if (i == limit) {
568                 dev_info(dev->class_dev, "failed to probe fifo size.\n");
569                 return -EIO;
570         }
571         writel(0, devpriv->las0 + LAS0_ADC_FIFO_CLEAR);
572         if (fifo_size != 0x400 && fifo_size != 0x2000) {
573                 dev_info(dev->class_dev,
574                          "unexpected fifo size of %i, expected 1024 or 8192.\n",
575                          fifo_size);
576                 return -EIO;
577         }
578         return fifo_size;
579 }
580
581 /*
582   "instructions" read/write data in "one-shot" or "software-triggered"
583   mode (simplest case).
584   This doesn't use interrupts.
585
586   Note, we don't do any settling delays.  Use a instruction list to
587   select, delay, then read.
588  */
589 static int rtd_ai_rinsn(struct comedi_device *dev,
590                         struct comedi_subdevice *s, struct comedi_insn *insn,
591                         unsigned int *data)
592 {
593         struct rtd_private *devpriv = dev->private;
594         int n, ii;
595         int stat;
596
597         /* clear any old fifo data */
598         writel(0, devpriv->las0 + LAS0_ADC_FIFO_CLEAR);
599
600         /* write channel to multiplexer and clear channel gain table */
601         rtd_load_channelgain_list(dev, 1, &insn->chanspec);
602
603         /* ADC conversion trigger source: SOFTWARE */
604         writel(0, devpriv->las0 + LAS0_ADC_CONVERSION);
605
606         /* convert n samples */
607         for (n = 0; n < insn->n; n++) {
608                 s16 d;
609                 /* trigger conversion */
610                 writew(0, devpriv->las0 + LAS0_ADC);
611
612                 for (ii = 0; ii < RTD_ADC_TIMEOUT; ++ii) {
613                         stat = readl(devpriv->las0 + LAS0_ADC);
614                         if (stat & FS_ADC_NOT_EMPTY)    /* 1 -> not empty */
615                                 break;
616                         WAIT_QUIETLY;
617                 }
618                 if (ii >= RTD_ADC_TIMEOUT)
619                         return -ETIMEDOUT;
620
621                 /* read data */
622                 d = readw(devpriv->las1 + LAS1_ADC_FIFO);
623                 /*printk ("rtd520: Got 0x%x after %d usec\n", d, ii+1); */
624                 d = d >> 3;     /* low 3 bits are marker lines */
625                 if (CHAN_ARRAY_TEST(devpriv->chan_is_bipolar, 0))
626                         /* convert to comedi unsigned data */
627                         data[n] = d + 2048;
628                 else
629                         data[n] = d;
630         }
631
632         /* return the number of samples read/written */
633         return n;
634 }
635
636 /*
637   Get what we know is there.... Fast!
638   This uses 1/2 the bus cycles of read_dregs (below).
639
640   The manual claims that we can do a lword read, but it doesn't work here.
641 */
642 static int ai_read_n(struct comedi_device *dev, struct comedi_subdevice *s,
643                      int count)
644 {
645         struct rtd_private *devpriv = dev->private;
646         int ii;
647
648         for (ii = 0; ii < count; ii++) {
649                 short sample;
650                 s16 d;
651
652                 if (0 == devpriv->ai_count) {   /* done */
653                         d = readw(devpriv->las1 + LAS1_ADC_FIFO);
654                         continue;
655                 }
656
657                 d = readw(devpriv->las1 + LAS1_ADC_FIFO);
658                 d = d >> 3;     /* low 3 bits are marker lines */
659                 if (CHAN_ARRAY_TEST(devpriv->chan_is_bipolar,
660                                     s->async->cur_chan)) {
661                         /* convert to comedi unsigned data */
662                         sample = d + 2048;
663                 } else
664                         sample = d;
665
666                 if (!comedi_buf_put(s->async, sample))
667                         return -1;
668
669                 if (devpriv->ai_count > 0)      /* < 0, means read forever */
670                         devpriv->ai_count--;
671         }
672         return 0;
673 }
674
675 /*
676   unknown amout of data is waiting in fifo.
677 */
678 static int ai_read_dregs(struct comedi_device *dev, struct comedi_subdevice *s)
679 {
680         struct rtd_private *devpriv = dev->private;
681
682         while (readl(devpriv->las0 + LAS0_ADC) & FS_ADC_NOT_EMPTY) {
683                 short sample;
684                 s16 d = readw(devpriv->las1 + LAS1_ADC_FIFO);
685
686                 if (0 == devpriv->ai_count) {   /* done */
687                         continue;       /* read rest */
688                 }
689
690                 d = d >> 3;     /* low 3 bits are marker lines */
691                 if (CHAN_ARRAY_TEST(devpriv->chan_is_bipolar,
692                                     s->async->cur_chan)) {
693                         /* convert to comedi unsigned data */
694                         sample = d + 2048;
695                 } else
696                         sample = d;
697
698                 if (!comedi_buf_put(s->async, sample))
699                         return -1;
700
701                 if (devpriv->ai_count > 0)      /* < 0, means read forever */
702                         devpriv->ai_count--;
703         }
704         return 0;
705 }
706
707 /*
708   Handle all rtd520 interrupts.
709   Runs atomically and is never re-entered.
710   This is a "slow handler";  other interrupts may be active.
711   The data conversion may someday happen in a "bottom half".
712 */
713 static irqreturn_t rtd_interrupt(int irq, void *d)
714 {
715         struct comedi_device *dev = d;
716         struct comedi_subdevice *s = &dev->subdevices[0];
717         struct rtd_private *devpriv = dev->private;
718         u32 overrun;
719         u16 status;
720         u16 fifo_status;
721
722         if (!dev->attached)
723                 return IRQ_NONE;
724
725         fifo_status = readl(devpriv->las0 + LAS0_ADC);
726         /* check for FIFO full, this automatically halts the ADC! */
727         if (!(fifo_status & FS_ADC_NOT_FULL))   /* 0 -> full */
728                 goto xfer_abort;
729
730         status = readw(devpriv->las0 + LAS0_IT);
731         /* if interrupt was not caused by our board, or handled above */
732         if (0 == status)
733                 return IRQ_HANDLED;
734
735         if (status & IRQM_ADC_ABOUT_CNT) {      /* sample count -> read FIFO */
736                 /*
737                  * since the priority interrupt controller may have queued
738                  * a sample counter interrupt, even though we have already
739                  * finished, we must handle the possibility that there is
740                  * no data here
741                  */
742                 if (!(fifo_status & FS_ADC_HEMPTY)) {
743                         /* FIFO half full */
744                         if (ai_read_n(dev, s, devpriv->fifosz / 2) < 0)
745                                 goto xfer_abort;
746
747                         if (0 == devpriv->ai_count)
748                                 goto xfer_done;
749
750                         comedi_event(dev, s);
751                 } else if (devpriv->xfer_count > 0) {
752                         if (fifo_status & FS_ADC_NOT_EMPTY) {
753                                 /* FIFO not empty */
754                                 if (ai_read_n(dev, s, devpriv->xfer_count) < 0)
755                                         goto xfer_abort;
756
757                                 if (0 == devpriv->ai_count)
758                                         goto xfer_done;
759
760                                 comedi_event(dev, s);
761                         }
762                 }
763         }
764
765         overrun = readl(devpriv->las0 + LAS0_OVERRUN) & 0xffff;
766         if (overrun)
767                 goto xfer_abort;
768
769         /* clear the interrupt */
770         writew(status, devpriv->las0 + LAS0_CLEAR);
771         readw(devpriv->las0 + LAS0_CLEAR);
772         return IRQ_HANDLED;
773
774 xfer_abort:
775         writel(0, devpriv->las0 + LAS0_ADC_FIFO_CLEAR);
776         s->async->events |= COMEDI_CB_ERROR;
777         devpriv->ai_count = 0;  /* stop and don't transfer any more */
778         /* fall into xfer_done */
779
780 xfer_done:
781         /* pacer stop source: SOFTWARE */
782         writel(0, devpriv->las0 + LAS0_PACER_STOP);
783         writel(0, devpriv->las0 + LAS0_PACER);  /* stop pacer */
784         writel(0, devpriv->las0 + LAS0_ADC_CONVERSION);
785         writew(0, devpriv->las0 + LAS0_IT);
786
787         if (devpriv->ai_count > 0) {    /* there shouldn't be anything left */
788                 fifo_status = readl(devpriv->las0 + LAS0_ADC);
789                 ai_read_dregs(dev, s);  /* read anything left in FIFO */
790         }
791
792         s->async->events |= COMEDI_CB_EOA;      /* signal end to comedi */
793         comedi_event(dev, s);
794
795         /* clear the interrupt */
796         status = readw(devpriv->las0 + LAS0_IT);
797         writew(status, devpriv->las0 + LAS0_CLEAR);
798         readw(devpriv->las0 + LAS0_CLEAR);
799
800         fifo_status = readl(devpriv->las0 + LAS0_ADC);
801         overrun = readl(devpriv->las0 + LAS0_OVERRUN) & 0xffff;
802
803         return IRQ_HANDLED;
804 }
805
806 /*
807   cmdtest tests a particular command to see if it is valid.
808   Using the cmdtest ioctl, a user can create a valid cmd
809   and then have it executed by the cmd ioctl (asynchronously).
810
811   cmdtest returns 1,2,3,4 or 0, depending on which tests
812   the command passes.
813 */
814
815 static int rtd_ai_cmdtest(struct comedi_device *dev,
816                           struct comedi_subdevice *s, struct comedi_cmd *cmd)
817 {
818         int err = 0;
819         int tmp;
820
821         /* Step 1 : check if triggers are trivially valid */
822
823         err |= cfc_check_trigger_src(&cmd->start_src, TRIG_NOW);
824         err |= cfc_check_trigger_src(&cmd->scan_begin_src,
825                                         TRIG_TIMER | TRIG_EXT);
826         err |= cfc_check_trigger_src(&cmd->convert_src, TRIG_TIMER | TRIG_EXT);
827         err |= cfc_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
828         err |= cfc_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);
829
830         if (err)
831                 return 1;
832
833         /* Step 2a : make sure trigger sources are unique */
834
835         err |= cfc_check_trigger_is_unique(cmd->scan_begin_src);
836         err |= cfc_check_trigger_is_unique(cmd->convert_src);
837         err |= cfc_check_trigger_is_unique(cmd->stop_src);
838
839         /* Step 2b : and mutually compatible */
840
841         if (err)
842                 return 2;
843
844         /* Step 3: check if arguments are trivially valid */
845
846         err |= cfc_check_trigger_arg_is(&cmd->start_arg, 0);
847
848         if (cmd->scan_begin_src == TRIG_TIMER) {
849                 /* Note: these are time periods, not actual rates */
850                 if (1 == cmd->chanlist_len) {   /* no scanning */
851                         if (cfc_check_trigger_arg_min(&cmd->scan_begin_arg,
852                                                       RTD_MAX_SPEED_1)) {
853                                 rtd_ns_to_timer(&cmd->scan_begin_arg,
854                                                 TRIG_ROUND_UP);
855                                 err |= -EINVAL;
856                         }
857                         if (cfc_check_trigger_arg_max(&cmd->scan_begin_arg,
858                                                       RTD_MIN_SPEED_1)) {
859                                 rtd_ns_to_timer(&cmd->scan_begin_arg,
860                                                 TRIG_ROUND_DOWN);
861                                 err |= -EINVAL;
862                         }
863                 } else {
864                         if (cfc_check_trigger_arg_min(&cmd->scan_begin_arg,
865                                                       RTD_MAX_SPEED)) {
866                                 rtd_ns_to_timer(&cmd->scan_begin_arg,
867                                                 TRIG_ROUND_UP);
868                                 err |= -EINVAL;
869                         }
870                         if (cfc_check_trigger_arg_max(&cmd->scan_begin_arg,
871                                                       RTD_MIN_SPEED)) {
872                                 rtd_ns_to_timer(&cmd->scan_begin_arg,
873                                                 TRIG_ROUND_DOWN);
874                                 err |= -EINVAL;
875                         }
876                 }
877         } else {
878                 /* external trigger */
879                 /* should be level/edge, hi/lo specification here */
880                 /* should specify multiple external triggers */
881                 err |= cfc_check_trigger_arg_max(&cmd->scan_begin_arg, 9);
882         }
883
884         if (cmd->convert_src == TRIG_TIMER) {
885                 if (1 == cmd->chanlist_len) {   /* no scanning */
886                         if (cfc_check_trigger_arg_min(&cmd->convert_arg,
887                                                       RTD_MAX_SPEED_1)) {
888                                 rtd_ns_to_timer(&cmd->convert_arg,
889                                                 TRIG_ROUND_UP);
890                                 err |= -EINVAL;
891                         }
892                         if (cfc_check_trigger_arg_max(&cmd->convert_arg,
893                                                       RTD_MIN_SPEED_1)) {
894                                 rtd_ns_to_timer(&cmd->convert_arg,
895                                                 TRIG_ROUND_DOWN);
896                                 err |= -EINVAL;
897                         }
898                 } else {
899                         if (cfc_check_trigger_arg_min(&cmd->convert_arg,
900                                                       RTD_MAX_SPEED)) {
901                                 rtd_ns_to_timer(&cmd->convert_arg,
902                                                 TRIG_ROUND_UP);
903                                 err |= -EINVAL;
904                         }
905                         if (cfc_check_trigger_arg_max(&cmd->convert_arg,
906                                                       RTD_MIN_SPEED)) {
907                                 rtd_ns_to_timer(&cmd->convert_arg,
908                                                 TRIG_ROUND_DOWN);
909                                 err |= -EINVAL;
910                         }
911                 }
912         } else {
913                 /* external trigger */
914                 /* see above */
915                 err |= cfc_check_trigger_arg_max(&cmd->convert_arg, 9);
916         }
917
918         if (cmd->stop_src == TRIG_COUNT) {
919                 /* TODO check for rounding error due to counter wrap */
920         } else {
921                 /* TRIG_NONE */
922                 err |= cfc_check_trigger_arg_is(&cmd->stop_arg, 0);
923         }
924
925         if (err)
926                 return 3;
927
928
929         /* step 4: fix up any arguments */
930
931         if (cmd->chanlist_len > RTD_MAX_CHANLIST) {
932                 cmd->chanlist_len = RTD_MAX_CHANLIST;
933                 err++;
934         }
935         if (cmd->scan_begin_src == TRIG_TIMER) {
936                 tmp = cmd->scan_begin_arg;
937                 rtd_ns_to_timer(&cmd->scan_begin_arg,
938                                 cmd->flags & TRIG_ROUND_MASK);
939                 if (tmp != cmd->scan_begin_arg)
940                         err++;
941
942         }
943         if (cmd->convert_src == TRIG_TIMER) {
944                 tmp = cmd->convert_arg;
945                 rtd_ns_to_timer(&cmd->convert_arg,
946                                 cmd->flags & TRIG_ROUND_MASK);
947                 if (tmp != cmd->convert_arg)
948                         err++;
949
950                 if (cmd->scan_begin_src == TRIG_TIMER
951                     && (cmd->scan_begin_arg
952                         < (cmd->convert_arg * cmd->scan_end_arg))) {
953                         cmd->scan_begin_arg =
954                             cmd->convert_arg * cmd->scan_end_arg;
955                         err++;
956                 }
957         }
958
959         if (err)
960                 return 4;
961
962         return 0;
963 }
964
965 /*
966   Execute a analog in command with many possible triggering options.
967   The data get stored in the async structure of the subdevice.
968   This is usually done by an interrupt handler.
969   Userland gets to the data using read calls.
970 */
971 static int rtd_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
972 {
973         struct rtd_private *devpriv = dev->private;
974         struct comedi_cmd *cmd = &s->async->cmd;
975         int timer;
976
977         /* stop anything currently running */
978         /* pacer stop source: SOFTWARE */
979         writel(0, devpriv->las0 + LAS0_PACER_STOP);
980         writel(0, devpriv->las0 + LAS0_PACER);  /* stop pacer */
981         writel(0, devpriv->las0 + LAS0_ADC_CONVERSION);
982         writew(0, devpriv->las0 + LAS0_IT);
983         writel(0, devpriv->las0 + LAS0_ADC_FIFO_CLEAR);
984         writel(0, devpriv->las0 + LAS0_OVERRUN);
985
986         /* start configuration */
987         /* load channel list and reset CGT */
988         rtd_load_channelgain_list(dev, cmd->chanlist_len, cmd->chanlist);
989
990         /* setup the common case and override if needed */
991         if (cmd->chanlist_len > 1) {
992                 /* pacer start source: SOFTWARE */
993                 writel(0, devpriv->las0 + LAS0_PACER_START);
994                 /* burst trigger source: PACER */
995                 writel(1, devpriv->las0 + LAS0_BURST_START);
996                 /* ADC conversion trigger source: BURST */
997                 writel(2, devpriv->las0 + LAS0_ADC_CONVERSION);
998         } else {                /* single channel */
999                 /* pacer start source: SOFTWARE */
1000                 writel(0, devpriv->las0 + LAS0_PACER_START);
1001                 /* ADC conversion trigger source: PACER */
1002                 writel(1, devpriv->las0 + LAS0_ADC_CONVERSION);
1003         }
1004         writel((devpriv->fifosz / 2 - 1) & 0xffff, devpriv->las0 + LAS0_ACNT);
1005
1006         if (TRIG_TIMER == cmd->scan_begin_src) {
1007                 /* scan_begin_arg is in nanoseconds */
1008                 /* find out how many samples to wait before transferring */
1009                 if (cmd->flags & TRIG_WAKE_EOS) {
1010                         /*
1011                          * this may generate un-sustainable interrupt rates
1012                          * the application is responsible for doing the
1013                          * right thing
1014                          */
1015                         devpriv->xfer_count = cmd->chanlist_len;
1016                         devpriv->flags |= SEND_EOS;
1017                 } else {
1018                         /* arrange to transfer data periodically */
1019                         devpriv->xfer_count =
1020                             (TRANS_TARGET_PERIOD * cmd->chanlist_len) /
1021                             cmd->scan_begin_arg;
1022                         if (devpriv->xfer_count < cmd->chanlist_len) {
1023                                 /* transfer after each scan (and avoid 0) */
1024                                 devpriv->xfer_count = cmd->chanlist_len;
1025                         } else {        /* make a multiple of scan length */
1026                                 devpriv->xfer_count =
1027                                     (devpriv->xfer_count +
1028                                      cmd->chanlist_len - 1)
1029                                     / cmd->chanlist_len;
1030                                 devpriv->xfer_count *= cmd->chanlist_len;
1031                         }
1032                         devpriv->flags |= SEND_EOS;
1033                 }
1034                 if (devpriv->xfer_count >= (devpriv->fifosz / 2)) {
1035                         /* out of counter range, use 1/2 fifo instead */
1036                         devpriv->xfer_count = 0;
1037                         devpriv->flags &= ~SEND_EOS;
1038                 } else {
1039                         /* interrupt for each transfer */
1040                         writel((devpriv->xfer_count - 1) & 0xffff,
1041                                 devpriv->las0 + LAS0_ACNT);
1042                 }
1043         } else {                /* unknown timing, just use 1/2 FIFO */
1044                 devpriv->xfer_count = 0;
1045                 devpriv->flags &= ~SEND_EOS;
1046         }
1047         /* pacer clock source: INTERNAL 8MHz */
1048         writel(1, devpriv->las0 + LAS0_PACER_SELECT);
1049         /* just interrupt, don't stop */
1050         writel(1, devpriv->las0 + LAS0_ACNT_STOP_ENABLE);
1051
1052         /* BUG??? these look like enumerated values, but they are bit fields */
1053
1054         /* First, setup when to stop */
1055         switch (cmd->stop_src) {
1056         case TRIG_COUNT:        /* stop after N scans */
1057                 devpriv->ai_count = cmd->stop_arg * cmd->chanlist_len;
1058                 if ((devpriv->xfer_count > 0)
1059                     && (devpriv->xfer_count > devpriv->ai_count)) {
1060                         devpriv->xfer_count = devpriv->ai_count;
1061                 }
1062                 break;
1063
1064         case TRIG_NONE: /* stop when cancel is called */
1065                 devpriv->ai_count = -1; /* read forever */
1066                 break;
1067         }
1068
1069         /* Scan timing */
1070         switch (cmd->scan_begin_src) {
1071         case TRIG_TIMER:        /* periodic scanning */
1072                 timer = rtd_ns_to_timer(&cmd->scan_begin_arg,
1073                                         TRIG_ROUND_NEAREST);
1074                 /* set PACER clock */
1075                 writel(timer & 0xffffff, devpriv->las0 + LAS0_PCLK);
1076
1077                 break;
1078
1079         case TRIG_EXT:
1080                 /* pacer start source: EXTERNAL */
1081                 writel(1, devpriv->las0 + LAS0_PACER_START);
1082                 break;
1083         }
1084
1085         /* Sample timing within a scan */
1086         switch (cmd->convert_src) {
1087         case TRIG_TIMER:        /* periodic */
1088                 if (cmd->chanlist_len > 1) {
1089                         /* only needed for multi-channel */
1090                         timer = rtd_ns_to_timer(&cmd->convert_arg,
1091                                                 TRIG_ROUND_NEAREST);
1092                         /* setup BURST clock */
1093                         writel(timer & 0x3ff, devpriv->las0 + LAS0_BCLK);
1094                 }
1095
1096                 break;
1097
1098         case TRIG_EXT:          /* external */
1099                 /* burst trigger source: EXTERNAL */
1100                 writel(2, devpriv->las0 + LAS0_BURST_START);
1101                 break;
1102         }
1103         /* end configuration */
1104
1105         /* This doesn't seem to work.  There is no way to clear an interrupt
1106            that the priority controller has queued! */
1107         writew(~0, devpriv->las0 + LAS0_CLEAR);
1108         readw(devpriv->las0 + LAS0_CLEAR);
1109
1110         /* TODO: allow multiple interrupt sources */
1111         if (devpriv->xfer_count > 0) {  /* transfer every N samples */
1112                 writew(IRQM_ADC_ABOUT_CNT, devpriv->las0 + LAS0_IT);
1113         } else {                /* 1/2 FIFO transfers */
1114                 writew(IRQM_ADC_ABOUT_CNT, devpriv->las0 + LAS0_IT);
1115         }
1116
1117         /* BUG: start_src is ASSUMED to be TRIG_NOW */
1118         /* BUG? it seems like things are running before the "start" */
1119         readl(devpriv->las0 + LAS0_PACER);      /* start pacer */
1120         return 0;
1121 }
1122
1123 /*
1124   Stop a running data acquisition.
1125 */
1126 static int rtd_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
1127 {
1128         struct rtd_private *devpriv = dev->private;
1129         u32 overrun;
1130         u16 status;
1131
1132         /* pacer stop source: SOFTWARE */
1133         writel(0, devpriv->las0 + LAS0_PACER_STOP);
1134         writel(0, devpriv->las0 + LAS0_PACER);  /* stop pacer */
1135         writel(0, devpriv->las0 + LAS0_ADC_CONVERSION);
1136         writew(0, devpriv->las0 + LAS0_IT);
1137         devpriv->ai_count = 0;  /* stop and don't transfer any more */
1138         status = readw(devpriv->las0 + LAS0_IT);
1139         overrun = readl(devpriv->las0 + LAS0_OVERRUN) & 0xffff;
1140         return 0;
1141 }
1142
1143 /*
1144   Output one (or more) analog values to a single port as fast as possible.
1145 */
1146 static int rtd_ao_winsn(struct comedi_device *dev,
1147                         struct comedi_subdevice *s, struct comedi_insn *insn,
1148                         unsigned int *data)
1149 {
1150         struct rtd_private *devpriv = dev->private;
1151         int i;
1152         int chan = CR_CHAN(insn->chanspec);
1153         int range = CR_RANGE(insn->chanspec);
1154
1155         /* Configure the output range (table index matches the range values) */
1156         writew(range & 7, devpriv->las0 +
1157                 ((chan == 0) ? LAS0_DAC1_CTRL : LAS0_DAC2_CTRL));
1158
1159         /* Writing a list of values to an AO channel is probably not
1160          * very useful, but that's how the interface is defined. */
1161         for (i = 0; i < insn->n; ++i) {
1162                 int val = data[i] << 3;
1163                 int stat = 0;   /* initialize to avoid bogus warning */
1164                 int ii;
1165
1166                 /* VERIFY: comedi range and offset conversions */
1167
1168                 if ((range > 1) /* bipolar */
1169                     && (data[i] < 2048)) {
1170                         /* offset and sign extend */
1171                         val = (((int)data[i]) - 2048) << 3;
1172                 } else {        /* unipolor */
1173                         val = data[i] << 3;
1174                 }
1175
1176                 /* a typical programming sequence */
1177                 writew(val, devpriv->las1 +
1178                         ((chan == 0) ? LAS1_DAC1_FIFO : LAS1_DAC2_FIFO));
1179                 writew(0, devpriv->las0 +
1180                         ((chan == 0) ? LAS0_DAC1 : LAS0_DAC2));
1181
1182                 devpriv->ao_readback[chan] = data[i];
1183
1184                 for (ii = 0; ii < RTD_DAC_TIMEOUT; ++ii) {
1185                         stat = readl(devpriv->las0 + LAS0_ADC);
1186                         /* 1 -> not empty */
1187                         if (stat & ((0 == chan) ? FS_DAC1_NOT_EMPTY :
1188                                     FS_DAC2_NOT_EMPTY))
1189                                 break;
1190                         WAIT_QUIETLY;
1191                 }
1192                 if (ii >= RTD_DAC_TIMEOUT)
1193                         return -ETIMEDOUT;
1194         }
1195
1196         /* return the number of samples read/written */
1197         return i;
1198 }
1199
1200 /* AO subdevices should have a read insn as well as a write insn.
1201  * Usually this means copying a value stored in devpriv. */
1202 static int rtd_ao_rinsn(struct comedi_device *dev,
1203                         struct comedi_subdevice *s, struct comedi_insn *insn,
1204                         unsigned int *data)
1205 {
1206         struct rtd_private *devpriv = dev->private;
1207         int i;
1208         int chan = CR_CHAN(insn->chanspec);
1209
1210         for (i = 0; i < insn->n; i++)
1211                 data[i] = devpriv->ao_readback[chan];
1212
1213
1214         return i;
1215 }
1216
1217 static int rtd_dio_insn_bits(struct comedi_device *dev,
1218                              struct comedi_subdevice *s,
1219                              struct comedi_insn *insn,
1220                              unsigned int *data)
1221 {
1222         struct rtd_private *devpriv = dev->private;
1223         unsigned int mask = data[0];
1224         unsigned int bits = data[1];
1225
1226         if (mask) {
1227                 s->state &= ~mask;
1228                 s->state |= (bits & mask);
1229
1230                 writew(s->state & 0xff, devpriv->las0 + LAS0_DIO0);
1231         }
1232
1233         data[1] = readw(devpriv->las0 + LAS0_DIO0) & 0xff;
1234
1235         return insn->n;
1236 }
1237
1238 static int rtd_dio_insn_config(struct comedi_device *dev,
1239                                struct comedi_subdevice *s,
1240                                struct comedi_insn *insn,
1241                                unsigned int *data)
1242 {
1243         struct rtd_private *devpriv = dev->private;
1244         unsigned int chan = CR_CHAN(insn->chanspec);
1245         unsigned int mask = 1 << chan;
1246
1247         switch (data[0]) {
1248         case INSN_CONFIG_DIO_OUTPUT:
1249                 s->io_bits |= mask;
1250                 break;
1251         case INSN_CONFIG_DIO_INPUT:
1252                 s->io_bits &= ~mask;
1253                 break;
1254         case INSN_CONFIG_DIO_QUERY:
1255                 data[1] = (s->io_bits & mask) ? COMEDI_OUTPUT : COMEDI_INPUT;
1256                 return insn->n;
1257                 break;
1258         default:
1259                 return -EINVAL;
1260         }
1261
1262         /* TODO support digital match interrupts and strobes */
1263
1264         /* set direction */
1265         writew(0x01, devpriv->las0 + LAS0_DIO_STATUS);
1266         writew(s->io_bits & 0xff, devpriv->las0 + LAS0_DIO0_CTRL);
1267
1268         /* clear interrupts */
1269         writew(0x00, devpriv->las0 + LAS0_DIO_STATUS);
1270
1271         /* port1 can only be all input or all output */
1272
1273         /* there are also 2 user input lines and 2 user output lines */
1274
1275         return insn->n;
1276 }
1277
1278 static void rtd_reset(struct comedi_device *dev)
1279 {
1280         struct rtd_private *devpriv = dev->private;
1281
1282         writel(0, devpriv->las0 + LAS0_BOARD_RESET);
1283         udelay(100);            /* needed? */
1284         writel(0, devpriv->lcfg + PLX_INTRCS_REG);
1285         writew(0, devpriv->las0 + LAS0_IT);
1286         writew(~0, devpriv->las0 + LAS0_CLEAR);
1287         readw(devpriv->las0 + LAS0_CLEAR);
1288 }
1289
1290 /*
1291  * initialize board, per RTD spec
1292  * also, initialize shadow registers
1293  */
1294 static void rtd_init_board(struct comedi_device *dev)
1295 {
1296         struct rtd_private *devpriv = dev->private;
1297
1298         rtd_reset(dev);
1299
1300         writel(0, devpriv->las0 + LAS0_OVERRUN);
1301         writel(0, devpriv->las0 + LAS0_CGT_CLEAR);
1302         writel(0, devpriv->las0 + LAS0_ADC_FIFO_CLEAR);
1303         writel(0, devpriv->las0 + LAS0_DAC1_RESET);
1304         writel(0, devpriv->las0 + LAS0_DAC2_RESET);
1305         /* clear digital IO fifo */
1306         writew(0, devpriv->las0 + LAS0_DIO_STATUS);
1307         writeb((0 << 6) | 0x30, devpriv->las0 + LAS0_UTC_CTRL);
1308         writeb((1 << 6) | 0x30, devpriv->las0 + LAS0_UTC_CTRL);
1309         writeb((2 << 6) | 0x30, devpriv->las0 + LAS0_UTC_CTRL);
1310         writeb((3 << 6) | 0x00, devpriv->las0 + LAS0_UTC_CTRL);
1311         /* TODO: set user out source ??? */
1312 }
1313
1314 /* The RTD driver does this */
1315 static void rtd_pci_latency_quirk(struct comedi_device *dev,
1316                                   struct pci_dev *pcidev)
1317 {
1318         unsigned char pci_latency;
1319
1320         pci_read_config_byte(pcidev, PCI_LATENCY_TIMER, &pci_latency);
1321         if (pci_latency < 32) {
1322                 dev_info(dev->class_dev,
1323                         "PCI latency changed from %d to %d\n",
1324                         pci_latency, 32);
1325                 pci_write_config_byte(pcidev, PCI_LATENCY_TIMER, 32);
1326         }
1327 }
1328
1329 static int rtd_auto_attach(struct comedi_device *dev,
1330                            unsigned long context)
1331 {
1332         struct pci_dev *pcidev = comedi_to_pci_dev(dev);
1333         const struct rtd_boardinfo *board = NULL;
1334         struct rtd_private *devpriv;
1335         struct comedi_subdevice *s;
1336         int ret;
1337
1338         if (context < ARRAY_SIZE(rtd520Boards))
1339                 board = &rtd520Boards[context];
1340         if (!board)
1341                 return -ENODEV;
1342         dev->board_ptr = board;
1343         dev->board_name = board->name;
1344
1345         devpriv = kzalloc(sizeof(*devpriv), GFP_KERNEL);
1346         if (!devpriv)
1347                 return -ENOMEM;
1348         dev->private = devpriv;
1349
1350         ret = comedi_pci_enable(dev);
1351         if (ret)
1352                 return ret;
1353
1354         devpriv->las0 = pci_ioremap_bar(pcidev, 2);
1355         devpriv->las1 = pci_ioremap_bar(pcidev, 3);
1356         devpriv->lcfg = pci_ioremap_bar(pcidev, 0);
1357         if (!devpriv->las0 || !devpriv->las1 || !devpriv->lcfg)
1358                 return -ENOMEM;
1359
1360         rtd_pci_latency_quirk(dev, pcidev);
1361
1362         if (pcidev->irq) {
1363                 ret = request_irq(pcidev->irq, rtd_interrupt, IRQF_SHARED,
1364                                   dev->board_name, dev);
1365                 if (ret == 0)
1366                         dev->irq = pcidev->irq;
1367         }
1368
1369         ret = comedi_alloc_subdevices(dev, 4);
1370         if (ret)
1371                 return ret;
1372
1373         s = &dev->subdevices[0];
1374         /* analog input subdevice */
1375         s->type         = COMEDI_SUBD_AI;
1376         s->subdev_flags = SDF_READABLE | SDF_GROUND | SDF_COMMON | SDF_DIFF;
1377         s->n_chan       = 16;
1378         s->maxdata      = 0x0fff;
1379         s->range_table  = board->ai_range;
1380         s->len_chanlist = RTD_MAX_CHANLIST;
1381         s->insn_read    = rtd_ai_rinsn;
1382         if (dev->irq) {
1383                 dev->read_subdev = s;
1384                 s->subdev_flags |= SDF_CMD_READ;
1385                 s->do_cmd       = rtd_ai_cmd;
1386                 s->do_cmdtest   = rtd_ai_cmdtest;
1387                 s->cancel       = rtd_ai_cancel;
1388         }
1389
1390         s = &dev->subdevices[1];
1391         /* analog output subdevice */
1392         s->type         = COMEDI_SUBD_AO;
1393         s->subdev_flags = SDF_WRITABLE;
1394         s->n_chan       = 2;
1395         s->maxdata      = 0x0fff;
1396         s->range_table  = &rtd_ao_range;
1397         s->insn_write   = rtd_ao_winsn;
1398         s->insn_read    = rtd_ao_rinsn;
1399
1400         s = &dev->subdevices[2];
1401         /* digital i/o subdevice */
1402         s->type         = COMEDI_SUBD_DIO;
1403         s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
1404         /* we only support port 0 right now.  Ignoring port 1 and user IO */
1405         s->n_chan       = 8;
1406         s->maxdata      = 1;
1407         s->range_table  = &range_digital;
1408         s->insn_bits    = rtd_dio_insn_bits;
1409         s->insn_config  = rtd_dio_insn_config;
1410
1411         /* timer/counter subdevices (not currently supported) */
1412         s = &dev->subdevices[3];
1413         s->type         = COMEDI_SUBD_COUNTER;
1414         s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
1415         s->n_chan       = 3;
1416         s->maxdata      = 0xffff;
1417
1418         rtd_init_board(dev);
1419
1420         ret = rtd520_probe_fifo_depth(dev);
1421         if (ret < 0)
1422                 return ret;
1423         devpriv->fifosz = ret;
1424
1425         if (dev->irq)
1426                 writel(ICS_PIE | ICS_PLIE, devpriv->lcfg + PLX_INTRCS_REG);
1427
1428         dev_info(dev->class_dev, "%s attached\n", dev->board_name);
1429
1430         return 0;
1431 }
1432
1433 static void rtd_detach(struct comedi_device *dev)
1434 {
1435         struct rtd_private *devpriv = dev->private;
1436
1437         if (devpriv) {
1438                 /* Shut down any board ops by resetting it */
1439                 if (devpriv->las0 && devpriv->lcfg)
1440                         rtd_reset(dev);
1441                 if (dev->irq) {
1442                         writel(readl(devpriv->lcfg + PLX_INTRCS_REG) &
1443                                 ~(ICS_PLIE | ICS_DMA0_E | ICS_DMA1_E),
1444                                 devpriv->lcfg + PLX_INTRCS_REG);
1445                         free_irq(dev->irq, dev);
1446                 }
1447                 if (devpriv->las0)
1448                         iounmap(devpriv->las0);
1449                 if (devpriv->las1)
1450                         iounmap(devpriv->las1);
1451                 if (devpriv->lcfg)
1452                         iounmap(devpriv->lcfg);
1453         }
1454         comedi_pci_disable(dev);
1455 }
1456
1457 static struct comedi_driver rtd520_driver = {
1458         .driver_name    = "rtd520",
1459         .module         = THIS_MODULE,
1460         .auto_attach    = rtd_auto_attach,
1461         .detach         = rtd_detach,
1462 };
1463
1464 static int rtd520_pci_probe(struct pci_dev *dev,
1465                             const struct pci_device_id *id)
1466 {
1467         return comedi_pci_auto_config(dev, &rtd520_driver, id->driver_data);
1468 }
1469
1470 static DEFINE_PCI_DEVICE_TABLE(rtd520_pci_table) = {
1471         { PCI_VDEVICE(RTD, 0x7520), BOARD_DM7520 },
1472         { PCI_VDEVICE(RTD, 0x4520), BOARD_PCI4520 },
1473         { 0 }
1474 };
1475 MODULE_DEVICE_TABLE(pci, rtd520_pci_table);
1476
1477 static struct pci_driver rtd520_pci_driver = {
1478         .name           = "rtd520",
1479         .id_table       = rtd520_pci_table,
1480         .probe          = rtd520_pci_probe,
1481         .remove         = comedi_pci_auto_unconfig,
1482 };
1483 module_comedi_pci_driver(rtd520_driver, rtd520_pci_driver);
1484
1485 MODULE_AUTHOR("Comedi http://www.comedi.org");
1486 MODULE_DESCRIPTION("Comedi low-level driver");
1487 MODULE_LICENSE("GPL");