]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/staging/comedi/drivers/s626.c
Merge branch 'akpm' (incoming from Andrew)
[karo-tx-linux.git] / drivers / staging / comedi / drivers / s626.c
1 /*
2   comedi/drivers/s626.c
3   Sensoray s626 Comedi driver
4
5   COMEDI - Linux Control and Measurement Device Interface
6   Copyright (C) 2000 David A. Schleef <ds@schleef.org>
7
8   Based on Sensoray Model 626 Linux driver Version 0.2
9   Copyright (C) 2002-2004 Sensoray Co., Inc.
10
11   This program is free software; you can redistribute it and/or modify
12   it under the terms of the GNU General Public License as published by
13   the Free Software Foundation; either version 2 of the License, or
14   (at your option) any later version.
15
16   This program is distributed in the hope that it will be useful,
17   but WITHOUT ANY WARRANTY; without even the implied warranty of
18   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19   GNU General Public License for more details.
20
21   You should have received a copy of the GNU General Public License
22   along with this program; if not, write to the Free Software
23   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24
25 */
26
27 /*
28 Driver: s626
29 Description: Sensoray 626 driver
30 Devices: [Sensoray] 626 (s626)
31 Authors: Gianluca Palli <gpalli@deis.unibo.it>,
32 Updated: Fri, 15 Feb 2008 10:28:42 +0000
33 Status: experimental
34
35 Configuration options: not applicable, uses PCI auto config
36
37 INSN_CONFIG instructions:
38   analog input:
39    none
40
41   analog output:
42    none
43
44   digital channel:
45    s626 has 3 dio subdevices (2,3 and 4) each with 16 i/o channels
46    supported configuration options:
47    INSN_CONFIG_DIO_QUERY
48    COMEDI_INPUT
49    COMEDI_OUTPUT
50
51   encoder:
52    Every channel must be configured before reading.
53
54    Example code
55
56    insn.insn=INSN_CONFIG;   //configuration instruction
57    insn.n=1;                //number of operation (must be 1)
58    insn.data=&initialvalue; //initial value loaded into encoder
59                                 //during configuration
60    insn.subdev=5;           //encoder subdevice
61    insn.chanspec=CR_PACK(encoder_channel,0,AREF_OTHER); //encoder_channel
62                                                         //to configure
63
64    comedi_do_insn(cf,&insn); //executing configuration
65 */
66
67 #include <linux/pci.h>
68 #include <linux/interrupt.h>
69 #include <linux/kernel.h>
70 #include <linux/types.h>
71
72 #include "../comedidev.h"
73
74 #include "comedi_fc.h"
75 #include "s626.h"
76
77 #define PCI_VENDOR_ID_S626 0x1131
78 #define PCI_DEVICE_ID_S626 0x7146
79 #define PCI_SUBVENDOR_ID_S626 0x6000
80 #define PCI_SUBDEVICE_ID_S626 0x0272
81
82 struct s626_private {
83         void __iomem *base_addr;
84         uint8_t ai_cmd_running; /*  ai_cmd is running */
85         uint8_t ai_continous;   /*  continous acquisition */
86         int ai_sample_count;    /*  number of samples to acquire */
87         unsigned int ai_sample_timer;
88         /*  time between samples in  units of the timer */
89         int ai_convert_count;   /*  conversion counter */
90         unsigned int ai_convert_timer;
91         /*  time between conversion in  units of the timer */
92         uint16_t CounterIntEnabs;
93         /* Counter interrupt enable  mask for MISC2 register. */
94         uint8_t AdcItems;       /* Number of items in ADC poll  list. */
95         struct bufferDMA RPSBuf;        /* DMA buffer used to hold ADC (RPS1) program. */
96         struct bufferDMA ANABuf;
97         /* DMA buffer used to receive ADC data and hold DAC data. */
98         uint32_t *pDacWBuf;
99         /* Pointer to logical adrs of DMA buffer used to hold DAC  data. */
100         uint16_t Dacpol;        /* Image of DAC polarity register. */
101         uint8_t TrimSetpoint[12];       /* Images of TrimDAC setpoints */
102         /* Charge Enabled (0 or WRMISC2_CHARGE_ENABLE). */
103         uint32_t I2CAdrs;
104         /* I2C device address for onboard EEPROM (board rev dependent). */
105         /*   short         I2Cards; */
106         unsigned int ao_readback[S626_DAC_CHANNELS];
107 };
108
109 struct dio_private {
110         uint16_t RDDIn;
111         uint16_t WRDOut;
112         uint16_t RDEdgSel;
113         uint16_t WREdgSel;
114         uint16_t RDCapSel;
115         uint16_t WRCapSel;
116         uint16_t RDCapFlg;
117         uint16_t RDIntSel;
118         uint16_t WRIntSel;
119 };
120
121 static struct dio_private dio_private_A = {
122         .RDDIn = LP_RDDINA,
123         .WRDOut = LP_WRDOUTA,
124         .RDEdgSel = LP_RDEDGSELA,
125         .WREdgSel = LP_WREDGSELA,
126         .RDCapSel = LP_RDCAPSELA,
127         .WRCapSel = LP_WRCAPSELA,
128         .RDCapFlg = LP_RDCAPFLGA,
129         .RDIntSel = LP_RDINTSELA,
130         .WRIntSel = LP_WRINTSELA,
131 };
132
133 static struct dio_private dio_private_B = {
134         .RDDIn = LP_RDDINB,
135         .WRDOut = LP_WRDOUTB,
136         .RDEdgSel = LP_RDEDGSELB,
137         .WREdgSel = LP_WREDGSELB,
138         .RDCapSel = LP_RDCAPSELB,
139         .WRCapSel = LP_WRCAPSELB,
140         .RDCapFlg = LP_RDCAPFLGB,
141         .RDIntSel = LP_RDINTSELB,
142         .WRIntSel = LP_WRINTSELB,
143 };
144
145 static struct dio_private dio_private_C = {
146         .RDDIn = LP_RDDINC,
147         .WRDOut = LP_WRDOUTC,
148         .RDEdgSel = LP_RDEDGSELC,
149         .WREdgSel = LP_WREDGSELC,
150         .RDCapSel = LP_RDCAPSELC,
151         .WRCapSel = LP_WRCAPSELC,
152         .RDCapFlg = LP_RDCAPFLGC,
153         .RDIntSel = LP_RDINTSELC,
154         .WRIntSel = LP_WRINTSELC,
155 };
156
157 /* to group dio devices (48 bits mask and data are not allowed ???)
158 static struct dio_private *dio_private_word[]={
159   &dio_private_A,
160   &dio_private_B,
161   &dio_private_C,
162 };
163 */
164
165 #define diopriv ((struct dio_private *)s->private)
166
167 /*  COUNTER OBJECT ------------------------------------------------ */
168 struct enc_private {
169         /*  Pointers to functions that differ for A and B counters: */
170         uint16_t(*GetEnable) (struct comedi_device *dev, struct enc_private *); /* Return clock enable. */
171         uint16_t(*GetIntSrc) (struct comedi_device *dev, struct enc_private *); /* Return interrupt source. */
172         uint16_t(*GetLoadTrig) (struct comedi_device *dev, struct enc_private *);       /* Return preload trigger source. */
173         uint16_t(*GetMode) (struct comedi_device *dev, struct enc_private *);   /* Return standardized operating mode. */
174         void (*PulseIndex) (struct comedi_device *dev, struct enc_private *);   /* Generate soft index strobe. */
175         void (*SetEnable) (struct comedi_device *dev, struct enc_private *, uint16_t enab);     /* Program clock enable. */
176         void (*SetIntSrc) (struct comedi_device *dev, struct enc_private *, uint16_t IntSource);        /* Program interrupt source. */
177         void (*SetLoadTrig) (struct comedi_device *dev, struct enc_private *, uint16_t Trig);   /* Program preload trigger source. */
178         void (*SetMode) (struct comedi_device *dev, struct enc_private *, uint16_t Setup, uint16_t DisableIntSrc);      /* Program standardized operating mode. */
179         void (*ResetCapFlags) (struct comedi_device *dev, struct enc_private *);        /* Reset event capture flags. */
180
181         uint16_t MyCRA;         /*    Address of CRA register. */
182         uint16_t MyCRB;         /*    Address of CRB register. */
183         uint16_t MyLatchLsw;    /*    Address of Latch least-significant-word */
184         /*    register. */
185         uint16_t MyEventBits[4];        /*    Bit translations for IntSrc -->RDMISC2. */
186 };
187
188 #define encpriv ((struct enc_private *)(dev->subdevices+5)->private)
189
190 /*  Counter overflow/index event flag masks for RDMISC2. */
191 #define INDXMASK(C)             (1 << (((C) > 2) ? ((C) * 2 - 1) : ((C) * 2 +  4)))
192 #define OVERMASK(C)             (1 << (((C) > 2) ? ((C) * 2 + 5) : ((C) * 2 + 10)))
193 #define EVBITS(C)               { 0, OVERMASK(C), INDXMASK(C), OVERMASK(C) | INDXMASK(C) }
194
195 /*  Translation table to map IntSrc into equivalent RDMISC2 event flag  bits. */
196 /* static const uint16_t EventBits[][4] = { EVBITS(0), EVBITS(1), EVBITS(2), EVBITS(3), EVBITS(4), EVBITS(5) }; */
197
198 /*  enab/disable a function or test status bit(s) that are accessed */
199 /*  through Main Control Registers 1 or 2. */
200 #define MC_ENABLE(REGADRS, CTRLWORD)    writel(((uint32_t)(CTRLWORD) << 16) | (uint32_t)(CTRLWORD), devpriv->base_addr+(REGADRS))
201
202 #define MC_DISABLE(REGADRS, CTRLWORD)   writel((uint32_t)(CTRLWORD) << 16 , devpriv->base_addr+(REGADRS))
203
204 #define MC_TEST(REGADRS, CTRLWORD)      ((readl(devpriv->base_addr+(REGADRS)) & CTRLWORD) != 0)
205
206 /* #define WR7146(REGARDS,CTRLWORD)
207     writel(CTRLWORD,(uint32_t)(devpriv->base_addr+(REGARDS))) */
208 #define WR7146(REGARDS, CTRLWORD) writel(CTRLWORD, devpriv->base_addr+(REGARDS))
209
210 /* #define RR7146(REGARDS)
211     readl((uint32_t)(devpriv->base_addr+(REGARDS))) */
212 #define RR7146(REGARDS)         readl(devpriv->base_addr+(REGARDS))
213
214 #define BUGFIX_STREG(REGADRS)   (REGADRS - 4)
215
216 /*  Write a time slot control record to TSL2. */
217 #define VECTPORT(VECTNUM)               (P_TSL2 + ((VECTNUM) << 2))
218 #define SETVECT(VECTNUM, VECTVAL)       WR7146(VECTPORT(VECTNUM), (VECTVAL))
219
220 /*  Code macros used for constructing I2C command bytes. */
221 #define I2C_B2(ATTR, VAL)       (((ATTR) << 6) | ((VAL) << 24))
222 #define I2C_B1(ATTR, VAL)       (((ATTR) << 4) | ((VAL) << 16))
223 #define I2C_B0(ATTR, VAL)       (((ATTR) << 2) | ((VAL) <<  8))
224
225 static const struct comedi_lrange s626_range_table = { 2, {
226                                                            RANGE(-5, 5),
227                                                            RANGE(-10, 10),
228                                                            }
229 };
230
231 /*  Execute a DEBI transfer.  This must be called from within a */
232 /*  critical section. */
233 static void DEBItransfer(struct comedi_device *dev)
234 {
235         struct s626_private *devpriv = dev->private;
236
237         /*  Initiate upload of shadow RAM to DEBI control register. */
238         MC_ENABLE(P_MC2, MC2_UPLD_DEBI);
239
240         /*  Wait for completion of upload from shadow RAM to DEBI control */
241         /*  register. */
242         while (!MC_TEST(P_MC2, MC2_UPLD_DEBI))
243                 ;
244
245         /*  Wait until DEBI transfer is done. */
246         while (RR7146(P_PSR) & PSR_DEBI_S)
247                 ;
248 }
249
250 /*  Initialize the DEBI interface for all transfers. */
251
252 static uint16_t DEBIread(struct comedi_device *dev, uint16_t addr)
253 {
254         struct s626_private *devpriv = dev->private;
255         uint16_t retval;
256
257         /*  Set up DEBI control register value in shadow RAM. */
258         WR7146(P_DEBICMD, DEBI_CMD_RDWORD | addr);
259
260         /*  Execute the DEBI transfer. */
261         DEBItransfer(dev);
262
263         /*  Fetch target register value. */
264         retval = (uint16_t) RR7146(P_DEBIAD);
265
266         /*  Return register value. */
267         return retval;
268 }
269
270 /*  Write a value to a gate array register. */
271 static void DEBIwrite(struct comedi_device *dev, uint16_t addr, uint16_t wdata)
272 {
273         struct s626_private *devpriv = dev->private;
274
275         /*  Set up DEBI control register value in shadow RAM. */
276         WR7146(P_DEBICMD, DEBI_CMD_WRWORD | addr);
277         WR7146(P_DEBIAD, wdata);
278
279         /*  Execute the DEBI transfer. */
280         DEBItransfer(dev);
281 }
282
283 /* Replace the specified bits in a gate array register.  Imports: mask
284  * specifies bits that are to be preserved, wdata is new value to be
285  * or'd with the masked original.
286  */
287 static void DEBIreplace(struct comedi_device *dev, uint16_t addr, uint16_t mask,
288                         uint16_t wdata)
289 {
290         struct s626_private *devpriv = dev->private;
291
292         /*  Copy target gate array register into P_DEBIAD register. */
293         WR7146(P_DEBICMD, DEBI_CMD_RDWORD | addr);
294         /* Set up DEBI control reg value in shadow RAM. */
295         DEBItransfer(dev);      /*  Execute the DEBI Read transfer. */
296
297         /*  Write back the modified image. */
298         WR7146(P_DEBICMD, DEBI_CMD_WRWORD | addr);
299         /* Set up DEBI control reg value in shadow  RAM. */
300
301         WR7146(P_DEBIAD, wdata | ((uint16_t) RR7146(P_DEBIAD) & mask));
302         /* Modify the register image. */
303         DEBItransfer(dev);      /*  Execute the DEBI Write transfer. */
304 }
305
306 /* **************  EEPROM ACCESS FUNCTIONS  ************** */
307
308 static uint32_t I2Chandshake(struct comedi_device *dev, uint32_t val)
309 {
310         struct s626_private *devpriv = dev->private;
311
312         /*  Write I2C command to I2C Transfer Control shadow register. */
313         WR7146(P_I2CCTRL, val);
314
315         /*  Upload I2C shadow registers into working registers and wait for */
316         /*  upload confirmation. */
317
318         MC_ENABLE(P_MC2, MC2_UPLD_IIC);
319         while (!MC_TEST(P_MC2, MC2_UPLD_IIC))
320                 ;
321
322         /*  Wait until I2C bus transfer is finished or an error occurs. */
323         while ((RR7146(P_I2CCTRL) & (I2C_BUSY | I2C_ERR)) == I2C_BUSY)
324                 ;
325
326         /*  Return non-zero if I2C error occurred. */
327         return RR7146(P_I2CCTRL) & I2C_ERR;
328
329 }
330
331 /*  Read uint8_t from EEPROM. */
332 static uint8_t I2Cread(struct comedi_device *dev, uint8_t addr)
333 {
334         struct s626_private *devpriv = dev->private;
335         uint8_t rtnval;
336
337         /*  Send EEPROM target address. */
338         if (I2Chandshake(dev, I2C_B2(I2C_ATTRSTART, I2CW)
339                          /* Byte2 = I2C command: write to I2C EEPROM  device. */
340                          | I2C_B1(I2C_ATTRSTOP, addr)
341                          /* Byte1 = EEPROM internal target address. */
342                          | I2C_B0(I2C_ATTRNOP, 0))) {   /*  Byte0 = Not sent. */
343                 /*  Abort function and declare error if handshake failed. */
344                 return 0;
345         }
346         /*  Execute EEPROM read. */
347         if (I2Chandshake(dev, I2C_B2(I2C_ATTRSTART, I2CR)
348
349                          /*  Byte2 = I2C */
350                          /*  command: read */
351                          /*  from I2C EEPROM */
352                          /*  device. */
353                          |I2C_B1(I2C_ATTRSTOP, 0)
354
355                          /*  Byte1 receives */
356                          /*  uint8_t from */
357                          /*  EEPROM. */
358                          |I2C_B0(I2C_ATTRNOP, 0))) {    /*  Byte0 = Not  sent. */
359
360                 /*  Abort function and declare error if handshake failed. */
361                 return 0;
362         }
363         /*  Return copy of EEPROM value. */
364         rtnval = (uint8_t) (RR7146(P_I2CCTRL) >> 16);
365         return rtnval;
366 }
367
368 /* ***********  DAC FUNCTIONS *********** */
369
370 /*  Slot 0 base settings. */
371 #define VECT0   (XSD2 | RSD3 | SIB_A2)
372 /*  Slot 0 always shifts in  0xFF and store it to  FB_BUFFER2. */
373
374 /*  TrimDac LogicalChan-to-PhysicalChan mapping table. */
375 static uint8_t trimchan[] = { 10, 9, 8, 3, 2, 7, 6, 1, 0, 5, 4 };
376
377 /*  TrimDac LogicalChan-to-EepromAdrs mapping table. */
378 static uint8_t trimadrs[] = { 0x40, 0x41, 0x42, 0x50, 0x51, 0x52, 0x53, 0x60, 0x61, 0x62, 0x63 };
379
380 /* Private helper function: Transmit serial data to DAC via Audio
381  * channel 2.  Assumes: (1) TSL2 slot records initialized, and (2)
382  * Dacpol contains valid target image.
383  */
384 static void SendDAC(struct comedi_device *dev, uint32_t val)
385 {
386         struct s626_private *devpriv = dev->private;
387
388         /* START THE SERIAL CLOCK RUNNING ------------- */
389
390         /* Assert DAC polarity control and enable gating of DAC serial clock
391          * and audio bit stream signals.  At this point in time we must be
392          * assured of being in time slot 0.  If we are not in slot 0, the
393          * serial clock and audio stream signals will be disabled; this is
394          * because the following DEBIwrite statement (which enables signals
395          * to be passed through the gate array) would execute before the
396          * trailing edge of WS1/WS3 (which turns off the signals), thus
397          * causing the signals to be inactive during the DAC write.
398          */
399         DEBIwrite(dev, LP_DACPOL, devpriv->Dacpol);
400
401         /* TRANSFER OUTPUT DWORD VALUE INTO A2'S OUTPUT FIFO ---------------- */
402
403         /* Copy DAC setpoint value to DAC's output DMA buffer. */
404
405         /* WR7146( (uint32_t)devpriv->pDacWBuf, val ); */
406         *devpriv->pDacWBuf = val;
407
408         /* enab the output DMA transfer.  This will cause the DMAC to copy
409          * the DAC's data value to A2's output FIFO.  The DMA transfer will
410          * then immediately terminate because the protection address is
411          * reached upon transfer of the first DWORD value.
412          */
413         MC_ENABLE(P_MC1, MC1_A2OUT);
414
415         /*  While the DMA transfer is executing ... */
416
417         /* Reset Audio2 output FIFO's underflow flag (along with any other
418          * FIFO underflow/overflow flags).  When set, this flag will
419          * indicate that we have emerged from slot 0.
420          */
421         WR7146(P_ISR, ISR_AFOU);
422
423         /* Wait for the DMA transfer to finish so that there will be data
424          * available in the FIFO when time slot 1 tries to transfer a DWORD
425          * from the FIFO to the output buffer register.  We test for DMA
426          * Done by polling the DMAC enable flag; this flag is automatically
427          * cleared when the transfer has finished.
428          */
429         while ((RR7146(P_MC1) & MC1_A2OUT) != 0)
430                 ;
431
432         /* START THE OUTPUT STREAM TO THE TARGET DAC -------------------- */
433
434         /* FIFO data is now available, so we enable execution of time slots
435          * 1 and higher by clearing the EOS flag in slot 0.  Note that SD3
436          * will be shifted in and stored in FB_BUFFER2 for end-of-slot-list
437          * detection.
438          */
439         SETVECT(0, XSD2 | RSD3 | SIB_A2);
440
441         /* Wait for slot 1 to execute to ensure that the Packet will be
442          * transmitted.  This is detected by polling the Audio2 output FIFO
443          * underflow flag, which will be set when slot 1 execution has
444          * finished transferring the DAC's data DWORD from the output FIFO
445          * to the output buffer register.
446          */
447         while ((RR7146(P_SSR) & SSR_AF2_OUT) == 0)
448                 ;
449
450         /* Set up to trap execution at slot 0 when the TSL sequencer cycles
451          * back to slot 0 after executing the EOS in slot 5.  Also,
452          * simultaneously shift out and in the 0x00 that is ALWAYS the value
453          * stored in the last byte to be shifted out of the FIFO's DWORD
454          * buffer register.
455          */
456         SETVECT(0, XSD2 | XFIFO_2 | RSD2 | SIB_A2 | EOS);
457
458         /* WAIT FOR THE TRANSACTION TO FINISH ----------------------- */
459
460         /* Wait for the TSL to finish executing all time slots before
461          * exiting this function.  We must do this so that the next DAC
462          * write doesn't start, thereby enabling clock/chip select signals:
463          *
464          * 1. Before the TSL sequence cycles back to slot 0, which disables
465          *    the clock/cs signal gating and traps slot // list execution.
466          *    we have not yet finished slot 5 then the clock/cs signals are
467          *    still gated and we have not finished transmitting the stream.
468          *
469          * 2. While slots 2-5 are executing due to a late slot 0 trap.  In
470          *    this case, the slot sequence is currently repeating, but with
471          *    clock/cs signals disabled.  We must wait for slot 0 to trap
472          *    execution before setting up the next DAC setpoint DMA transfer
473          *    and enabling the clock/cs signals.  To detect the end of slot 5,
474          *    we test for the FB_BUFFER2 MSB contents to be equal to 0xFF.  If
475          *    the TSL has not yet finished executing slot 5 ...
476          */
477         if ((RR7146(P_FB_BUFFER2) & 0xFF000000) != 0) {
478                 /* The trap was set on time and we are still executing somewhere
479                  * in slots 2-5, so we now wait for slot 0 to execute and trap
480                  * TSL execution.  This is detected when FB_BUFFER2 MSB changes
481                  * from 0xFF to 0x00, which slot 0 causes to happen by shifting
482                  * out/in on SD2 the 0x00 that is always referenced by slot 5.
483                  */
484                 while ((RR7146(P_FB_BUFFER2) & 0xFF000000) != 0)
485                         ;
486         }
487         /* Either (1) we were too late setting the slot 0 trap; the TSL
488          * sequencer restarted slot 0 before we could set the EOS trap flag,
489          * or (2) we were not late and execution is now trapped at slot 0.
490          * In either case, we must now change slot 0 so that it will store
491          * value 0xFF (instead of 0x00) to FB_BUFFER2 next time it executes.
492          * In order to do this, we reprogram slot 0 so that it will shift in
493          * SD3, which is driven only by a pull-up resistor.
494          */
495         SETVECT(0, RSD3 | SIB_A2 | EOS);
496
497         /* Wait for slot 0 to execute, at which time the TSL is setup for
498          * the next DAC write.  This is detected when FB_BUFFER2 MSB changes
499          * from 0x00 to 0xFF.
500          */
501         while ((RR7146(P_FB_BUFFER2) & 0xFF000000) == 0)
502                 ;
503 }
504
505 /*  Private helper function: Write setpoint to an application DAC channel. */
506 static void SetDAC(struct comedi_device *dev, uint16_t chan, short dacdata)
507 {
508         struct s626_private *devpriv = dev->private;
509         register uint16_t signmask;
510         register uint32_t WSImage;
511
512         /*  Adjust DAC data polarity and set up Polarity Control Register */
513         /*  image. */
514         signmask = 1 << chan;
515         if (dacdata < 0) {
516                 dacdata = -dacdata;
517                 devpriv->Dacpol |= signmask;
518         } else
519                 devpriv->Dacpol &= ~signmask;
520
521         /*  Limit DAC setpoint value to valid range. */
522         if ((uint16_t) dacdata > 0x1FFF)
523                 dacdata = 0x1FFF;
524
525         /* Set up TSL2 records (aka "vectors") for DAC update.  Vectors V2
526          * and V3 transmit the setpoint to the target DAC.  V4 and V5 send
527          * data to a non-existent TrimDac channel just to keep the clock
528          * running after sending data to the target DAC.  This is necessary
529          * to eliminate the clock glitch that would otherwise occur at the
530          * end of the target DAC's serial data stream.  When the sequence
531          * restarts at V0 (after executing V5), the gate array automatically
532          * disables gating for the DAC clock and all DAC chip selects.
533          */
534
535         WSImage = (chan & 2) ? WS1 : WS2;
536         /* Choose DAC chip select to be asserted. */
537         SETVECT(2, XSD2 | XFIFO_1 | WSImage);
538         /* Slot 2: Transmit high data byte to target DAC. */
539         SETVECT(3, XSD2 | XFIFO_0 | WSImage);
540         /* Slot 3: Transmit low data byte to target DAC. */
541         SETVECT(4, XSD2 | XFIFO_3 | WS3);
542         /* Slot 4: Transmit to non-existent TrimDac channel to keep clock */
543         SETVECT(5, XSD2 | XFIFO_2 | WS3 | EOS);
544         /* Slot 5: running after writing target DAC's low data byte. */
545
546         /*  Construct and transmit target DAC's serial packet:
547          * ( A10D DDDD ),( DDDD DDDD ),( 0x0F ),( 0x00 ) where A is chan<0>,
548          * and D<12:0> is the DAC setpoint.  Append a WORD value (that writes
549          * to a  non-existent TrimDac channel) that serves to keep the clock
550          * running after the packet has been sent to the target DAC.
551          */
552         SendDAC(dev, 0x0F000000
553                 /* Continue clock after target DAC data (write to non-existent trimdac). */
554                 | 0x00004000
555                 /* Address the two main dual-DAC devices (TSL's chip select enables
556                  * target device). */
557                 | ((uint32_t) (chan & 1) << 15)
558                 /*  Address the DAC channel within the  device. */
559                 | (uint32_t) dacdata);  /*  Include DAC setpoint data. */
560
561 }
562
563 static void WriteTrimDAC(struct comedi_device *dev, uint8_t LogicalChan,
564                          uint8_t DacData)
565 {
566         struct s626_private *devpriv = dev->private;
567         uint32_t chan;
568
569         /*  Save the new setpoint in case the application needs to read it back later. */
570         devpriv->TrimSetpoint[LogicalChan] = (uint8_t) DacData;
571
572         /*  Map logical channel number to physical channel number. */
573         chan = (uint32_t) trimchan[LogicalChan];
574
575         /* Set up TSL2 records for TrimDac write operation.  All slots shift
576          * 0xFF in from pulled-up SD3 so that the end of the slot sequence
577          * can be detected.
578          */
579
580         SETVECT(2, XSD2 | XFIFO_1 | WS3);
581         /* Slot 2: Send high uint8_t to target TrimDac. */
582         SETVECT(3, XSD2 | XFIFO_0 | WS3);
583         /* Slot 3: Send low uint8_t to target TrimDac. */
584         SETVECT(4, XSD2 | XFIFO_3 | WS1);
585         /* Slot 4: Send NOP high uint8_t to DAC0 to keep clock running. */
586         SETVECT(5, XSD2 | XFIFO_2 | WS1 | EOS);
587         /* Slot 5: Send NOP low  uint8_t to DAC0. */
588
589         /* Construct and transmit target DAC's serial packet:
590          * ( 0000 AAAA ), ( DDDD DDDD ),( 0x00 ),( 0x00 ) where A<3:0> is the
591          * DAC channel's address, and D<7:0> is the DAC setpoint.  Append a
592          * WORD value (that writes a channel 0 NOP command to a non-existent
593          * main DAC channel) that serves to keep the clock running after the
594          * packet has been sent to the target DAC.
595          */
596
597         /*  Address the DAC channel within the trimdac device. */
598         SendDAC(dev, ((uint32_t) chan << 8)
599                 | (uint32_t) DacData);  /*  Include DAC setpoint data. */
600 }
601
602 static void LoadTrimDACs(struct comedi_device *dev)
603 {
604         register uint8_t i;
605
606         /*  Copy TrimDac setpoint values from EEPROM to TrimDacs. */
607         for (i = 0; i < ARRAY_SIZE(trimchan); i++)
608                 WriteTrimDAC(dev, i, I2Cread(dev, trimadrs[i]));
609 }
610
611 /* ******  COUNTER FUNCTIONS  ******* */
612 /* All counter functions address a specific counter by means of the
613  * "Counter" argument, which is a logical counter number.  The Counter
614  * argument may have any of the following legal values: 0=0A, 1=1A,
615  * 2=2A, 3=0B, 4=1B, 5=2B.
616  */
617
618 /*  Read a counter's output latch. */
619 static uint32_t ReadLatch(struct comedi_device *dev, struct enc_private *k)
620 {
621         register uint32_t value;
622
623         /*  Latch counts and fetch LSW of latched counts value. */
624         value = (uint32_t) DEBIread(dev, k->MyLatchLsw);
625
626         /*  Fetch MSW of latched counts and combine with LSW. */
627         value |= ((uint32_t) DEBIread(dev, k->MyLatchLsw + 2) << 16);
628
629         /*  Return latched counts. */
630         return value;
631 }
632
633 /* Return/set a counter pair's latch trigger source.  0: On read
634  * access, 1: A index latches A, 2: B index latches B, 3: A overflow
635  * latches B.
636  */
637 static void SetLatchSource(struct comedi_device *dev, struct enc_private *k,
638                            uint16_t value)
639 {
640         DEBIreplace(dev, k->MyCRB,
641                     (uint16_t) (~(CRBMSK_INTCTRL | CRBMSK_LATCHSRC)),
642                     (uint16_t) (value << CRBBIT_LATCHSRC));
643 }
644
645 /*  Write value into counter preload register. */
646 static void Preload(struct comedi_device *dev, struct enc_private *k,
647                     uint32_t value)
648 {
649         DEBIwrite(dev, (uint16_t) (k->MyLatchLsw), (uint16_t) value);
650         DEBIwrite(dev, (uint16_t) (k->MyLatchLsw + 2),
651                   (uint16_t) (value >> 16));
652 }
653
654 static unsigned int s626_ai_reg_to_uint(int data)
655 {
656         unsigned int tempdata;
657
658         tempdata = (data >> 18);
659         if (tempdata & 0x2000)
660                 tempdata &= 0x1fff;
661         else
662                 tempdata += (1 << 13);
663
664         return tempdata;
665 }
666
667 /* static unsigned int s626_uint_to_reg(struct comedi_subdevice *s, int data){ */
668 /*   return 0; */
669 /* } */
670
671 static int s626_dio_set_irq(struct comedi_device *dev, unsigned int chan)
672 {
673         unsigned int group;
674         unsigned int bitmask;
675         unsigned int status;
676
677         /* select dio bank */
678         group = chan / 16;
679         bitmask = 1 << (chan - (16 * group));
680
681         /* set channel to capture positive edge */
682         status = DEBIread(dev,
683                           ((struct dio_private *)(dev->subdevices + 2 +
684                                                   group)->private)->RDEdgSel);
685         DEBIwrite(dev,
686                   ((struct dio_private *)(dev->subdevices + 2 +
687                                           group)->private)->WREdgSel,
688                   bitmask | status);
689
690         /* enable interrupt on selected channel */
691         status = DEBIread(dev,
692                           ((struct dio_private *)(dev->subdevices + 2 +
693                                                   group)->private)->RDIntSel);
694         DEBIwrite(dev,
695                   ((struct dio_private *)(dev->subdevices + 2 +
696                                           group)->private)->WRIntSel,
697                   bitmask | status);
698
699         /* enable edge capture write command */
700         DEBIwrite(dev, LP_MISC1, MISC1_EDCAP);
701
702         /* enable edge capture on selected channel */
703         status = DEBIread(dev,
704                           ((struct dio_private *)(dev->subdevices + 2 +
705                                                   group)->private)->RDCapSel);
706         DEBIwrite(dev,
707                   ((struct dio_private *)(dev->subdevices + 2 +
708                                           group)->private)->WRCapSel,
709                   bitmask | status);
710
711         return 0;
712 }
713
714 static int s626_dio_reset_irq(struct comedi_device *dev, unsigned int group,
715                               unsigned int mask)
716 {
717         /* disable edge capture write command */
718         DEBIwrite(dev, LP_MISC1, MISC1_NOEDCAP);
719
720         /* enable edge capture on selected channel */
721         DEBIwrite(dev,
722                   ((struct dio_private *)(dev->subdevices + 2 +
723                                           group)->private)->WRCapSel, mask);
724
725         return 0;
726 }
727
728 static int s626_dio_clear_irq(struct comedi_device *dev)
729 {
730         unsigned int group;
731
732         /* disable edge capture write command */
733         DEBIwrite(dev, LP_MISC1, MISC1_NOEDCAP);
734
735         for (group = 0; group < S626_DIO_BANKS; group++) {
736                 /* clear pending events and interrupt */
737                 DEBIwrite(dev,
738                           ((struct dio_private *)(dev->subdevices + 2 +
739                                                   group)->private)->WRCapSel,
740                           0xffff);
741         }
742
743         return 0;
744 }
745
746 static irqreturn_t s626_irq_handler(int irq, void *d)
747 {
748         struct comedi_device *dev = d;
749         struct s626_private *devpriv = dev->private;
750         struct comedi_subdevice *s;
751         struct comedi_cmd *cmd;
752         struct enc_private *k;
753         unsigned long flags;
754         int32_t *readaddr;
755         uint32_t irqtype, irqstatus;
756         int i = 0;
757         short tempdata;
758         uint8_t group;
759         uint16_t irqbit;
760
761         if (dev->attached == 0)
762                 return IRQ_NONE;
763         /*  lock to avoid race with comedi_poll */
764         spin_lock_irqsave(&dev->spinlock, flags);
765
766         /* save interrupt enable register state */
767         irqstatus = readl(devpriv->base_addr + P_IER);
768
769         /* read interrupt type */
770         irqtype = readl(devpriv->base_addr + P_ISR);
771
772         /* disable master interrupt */
773         writel(0, devpriv->base_addr + P_IER);
774
775         /* clear interrupt */
776         writel(irqtype, devpriv->base_addr + P_ISR);
777
778         switch (irqtype) {
779         case IRQ_RPS1:          /*  end_of_scan occurs */
780                 /*  manage ai subdevice */
781                 s = dev->subdevices;
782                 cmd = &(s->async->cmd);
783
784                 /* Init ptr to DMA buffer that holds new ADC data.  We skip the
785                  * first uint16_t in the buffer because it contains junk data from
786                  * the final ADC of the previous poll list scan.
787                  */
788                 readaddr = (int32_t *) devpriv->ANABuf.LogicalBase + 1;
789
790                 /*  get the data and hand it over to comedi */
791                 for (i = 0; i < (s->async->cmd.chanlist_len); i++) {
792                         /*  Convert ADC data to 16-bit integer values and copy to application */
793                         /*  buffer. */
794                         tempdata = s626_ai_reg_to_uint((int)*readaddr);
795                         readaddr++;
796
797                         /* put data into read buffer */
798                         /*  comedi_buf_put(s->async, tempdata); */
799                         if (cfc_write_to_buffer(s, tempdata) == 0)
800                                 printk
801                                     ("s626_irq_handler: cfc_write_to_buffer error!\n");
802                 }
803
804                 /* end of scan occurs */
805                 s->async->events |= COMEDI_CB_EOS;
806
807                 if (!(devpriv->ai_continous))
808                         devpriv->ai_sample_count--;
809                 if (devpriv->ai_sample_count <= 0) {
810                         devpriv->ai_cmd_running = 0;
811
812                         /*  Stop RPS program. */
813                         MC_DISABLE(P_MC1, MC1_ERPS1);
814
815                         /* send end of acquisition */
816                         s->async->events |= COMEDI_CB_EOA;
817
818                         /* disable master interrupt */
819                         irqstatus = 0;
820                 }
821
822                 if (devpriv->ai_cmd_running && cmd->scan_begin_src == TRIG_EXT)
823                         s626_dio_set_irq(dev, cmd->scan_begin_arg);
824                 /*  tell comedi that data is there */
825                 comedi_event(dev, s);
826                 break;
827         case IRQ_GPIO3: /* check dio and conter interrupt */
828                 /*  manage ai subdevice */
829                 s = dev->subdevices;
830                 cmd = &(s->async->cmd);
831
832                 /* s626_dio_clear_irq(dev); */
833
834                 for (group = 0; group < S626_DIO_BANKS; group++) {
835                         irqbit = 0;
836                         /* read interrupt type */
837                         irqbit = DEBIread(dev,
838                                           ((struct dio_private *)(dev->
839                                                                   subdevices +
840                                                                   2 +
841                                                                   group)->
842                                            private)->RDCapFlg);
843
844                         /* check if interrupt is generated from dio channels */
845                         if (irqbit) {
846                                 s626_dio_reset_irq(dev, group, irqbit);
847                                 if (devpriv->ai_cmd_running) {
848                                         /* check if interrupt is an ai acquisition start trigger */
849                                         if ((irqbit >> (cmd->start_arg -
850                                                         (16 * group)))
851                                             == 1 && cmd->start_src == TRIG_EXT) {
852                                                 /*  Start executing the RPS program. */
853                                                 MC_ENABLE(P_MC1, MC1_ERPS1);
854
855                                                 if (cmd->scan_begin_src ==
856                                                     TRIG_EXT) {
857                                                         s626_dio_set_irq(dev,
858                                                                          cmd->scan_begin_arg);
859                                                 }
860                                         }
861                                         if ((irqbit >> (cmd->scan_begin_arg -
862                                                         (16 * group)))
863                                             == 1
864                                             && cmd->scan_begin_src ==
865                                             TRIG_EXT) {
866                                                 /*  Trigger ADC scan loop start by setting RPS Signal 0. */
867                                                 MC_ENABLE(P_MC2, MC2_ADC_RPS);
868
869                                                 if (cmd->convert_src ==
870                                                     TRIG_EXT) {
871                                                         devpriv->ai_convert_count
872                                                             = cmd->chanlist_len;
873
874                                                         s626_dio_set_irq(dev,
875                                                                          cmd->convert_arg);
876                                                 }
877
878                                                 if (cmd->convert_src ==
879                                                     TRIG_TIMER) {
880                                                         k = &encpriv[5];
881                                                         devpriv->ai_convert_count
882                                                             = cmd->chanlist_len;
883                                                         k->SetEnable(dev, k,
884                                                                      CLKENAB_ALWAYS);
885                                                 }
886                                         }
887                                         if ((irqbit >> (cmd->convert_arg -
888                                                         (16 * group)))
889                                             == 1
890                                             && cmd->convert_src == TRIG_EXT) {
891                                                 /*  Trigger ADC scan loop start by setting RPS Signal 0. */
892                                                 MC_ENABLE(P_MC2, MC2_ADC_RPS);
893
894                                                 devpriv->ai_convert_count--;
895
896                                                 if (devpriv->ai_convert_count >
897                                                     0) {
898                                                         s626_dio_set_irq(dev,
899                                                                          cmd->convert_arg);
900                                                 }
901                                         }
902                                 }
903                                 break;
904                         }
905                 }
906
907                 /* read interrupt type */
908                 irqbit = DEBIread(dev, LP_RDMISC2);
909
910                 /* check interrupt on counters */
911                 if (irqbit & IRQ_COINT1A) {
912                         k = &encpriv[0];
913
914                         /* clear interrupt capture flag */
915                         k->ResetCapFlags(dev, k);
916                 }
917                 if (irqbit & IRQ_COINT2A) {
918                         k = &encpriv[1];
919
920                         /* clear interrupt capture flag */
921                         k->ResetCapFlags(dev, k);
922                 }
923                 if (irqbit & IRQ_COINT3A) {
924                         k = &encpriv[2];
925
926                         /* clear interrupt capture flag */
927                         k->ResetCapFlags(dev, k);
928                 }
929                 if (irqbit & IRQ_COINT1B) {
930                         k = &encpriv[3];
931
932                         /* clear interrupt capture flag */
933                         k->ResetCapFlags(dev, k);
934                 }
935                 if (irqbit & IRQ_COINT2B) {
936                         k = &encpriv[4];
937
938                         /* clear interrupt capture flag */
939                         k->ResetCapFlags(dev, k);
940
941                         if (devpriv->ai_convert_count > 0) {
942                                 devpriv->ai_convert_count--;
943                                 if (devpriv->ai_convert_count == 0)
944                                         k->SetEnable(dev, k, CLKENAB_INDEX);
945
946                                 if (cmd->convert_src == TRIG_TIMER) {
947                                         /*  Trigger ADC scan loop start by setting RPS Signal 0. */
948                                         MC_ENABLE(P_MC2, MC2_ADC_RPS);
949                                 }
950                         }
951                 }
952                 if (irqbit & IRQ_COINT3B) {
953                         k = &encpriv[5];
954
955                         /* clear interrupt capture flag */
956                         k->ResetCapFlags(dev, k);
957
958                         if (cmd->scan_begin_src == TRIG_TIMER) {
959                                 /*  Trigger ADC scan loop start by setting RPS Signal 0. */
960                                 MC_ENABLE(P_MC2, MC2_ADC_RPS);
961                         }
962
963                         if (cmd->convert_src == TRIG_TIMER) {
964                                 k = &encpriv[4];
965                                 devpriv->ai_convert_count = cmd->chanlist_len;
966                                 k->SetEnable(dev, k, CLKENAB_ALWAYS);
967                         }
968                 }
969         }
970
971         /* enable interrupt */
972         writel(irqstatus, devpriv->base_addr + P_IER);
973
974         spin_unlock_irqrestore(&dev->spinlock, flags);
975         return IRQ_HANDLED;
976 }
977
978 /*
979  * this functions build the RPS program for hardware driven acquistion
980  */
981 static void ResetADC(struct comedi_device *dev, uint8_t *ppl)
982 {
983         struct s626_private *devpriv = dev->private;
984         register uint32_t *pRPS;
985         uint32_t JmpAdrs;
986         uint16_t i;
987         uint16_t n;
988         uint32_t LocalPPL;
989         struct comedi_cmd *cmd = &(dev->subdevices->async->cmd);
990
991         /*  Stop RPS program in case it is currently running. */
992         MC_DISABLE(P_MC1, MC1_ERPS1);
993
994         /*  Set starting logical address to write RPS commands. */
995         pRPS = (uint32_t *) devpriv->RPSBuf.LogicalBase;
996
997         /*  Initialize RPS instruction pointer. */
998         WR7146(P_RPSADDR1, (uint32_t) devpriv->RPSBuf.PhysicalBase);
999
1000         /*  Construct RPS program in RPSBuf DMA buffer */
1001
1002         if (cmd != NULL && cmd->scan_begin_src != TRIG_FOLLOW) {
1003                 /*  Wait for Start trigger. */
1004                 *pRPS++ = RPS_PAUSE | RPS_SIGADC;
1005                 *pRPS++ = RPS_CLRSIGNAL | RPS_SIGADC;
1006         }
1007
1008         /* SAA7146 BUG WORKAROUND Do a dummy DEBI Write.  This is necessary
1009          * because the first RPS DEBI Write following a non-RPS DEBI write
1010          * seems to always fail.  If we don't do this dummy write, the ADC
1011          * gain might not be set to the value required for the first slot in
1012          * the poll list; the ADC gain would instead remain unchanged from
1013          * the previously programmed value.
1014          */
1015         *pRPS++ = RPS_LDREG | (P_DEBICMD >> 2);
1016         /* Write DEBI Write command and address to shadow RAM. */
1017
1018         *pRPS++ = DEBI_CMD_WRWORD | LP_GSEL;
1019         *pRPS++ = RPS_LDREG | (P_DEBIAD >> 2);
1020         /*  Write DEBI immediate data  to shadow RAM: */
1021
1022         *pRPS++ = GSEL_BIPOLAR5V;
1023         /*  arbitrary immediate data  value. */
1024
1025         *pRPS++ = RPS_CLRSIGNAL | RPS_DEBI;
1026         /*  Reset "shadow RAM  uploaded" flag. */
1027         *pRPS++ = RPS_UPLOAD | RPS_DEBI;        /*  Invoke shadow RAM upload. */
1028         *pRPS++ = RPS_PAUSE | RPS_DEBI; /*  Wait for shadow upload to finish. */
1029
1030         /* Digitize all slots in the poll list. This is implemented as a
1031          * for loop to limit the slot count to 16 in case the application
1032          * forgot to set the EOPL flag in the final slot.
1033          */
1034         for (devpriv->AdcItems = 0; devpriv->AdcItems < 16; devpriv->AdcItems++) {
1035                 /* Convert application's poll list item to private board class
1036                  * format.  Each app poll list item is an uint8_t with form
1037                  * (EOPL,x,x,RANGE,CHAN<3:0>), where RANGE code indicates 0 =
1038                  * +-10V, 1 = +-5V, and EOPL = End of Poll List marker.
1039                  */
1040                 LocalPPL =
1041                     (*ppl << 8) | (*ppl & 0x10 ? GSEL_BIPOLAR5V :
1042                                    GSEL_BIPOLAR10V);
1043
1044                 /*  Switch ADC analog gain. */
1045                 *pRPS++ = RPS_LDREG | (P_DEBICMD >> 2); /*  Write DEBI command */
1046                 /*  and address to */
1047                 /*  shadow RAM. */
1048                 *pRPS++ = DEBI_CMD_WRWORD | LP_GSEL;
1049                 *pRPS++ = RPS_LDREG | (P_DEBIAD >> 2);  /*  Write DEBI */
1050                 /*  immediate data to */
1051                 /*  shadow RAM. */
1052                 *pRPS++ = LocalPPL;
1053                 *pRPS++ = RPS_CLRSIGNAL | RPS_DEBI;     /*  Reset "shadow RAM uploaded" */
1054                 /*  flag. */
1055                 *pRPS++ = RPS_UPLOAD | RPS_DEBI;        /*  Invoke shadow RAM upload. */
1056                 *pRPS++ = RPS_PAUSE | RPS_DEBI; /*  Wait for shadow upload to */
1057                 /*  finish. */
1058
1059                 /*  Select ADC analog input channel. */
1060                 *pRPS++ = RPS_LDREG | (P_DEBICMD >> 2);
1061                 /*  Write DEBI command and address to  shadow RAM. */
1062                 *pRPS++ = DEBI_CMD_WRWORD | LP_ISEL;
1063                 *pRPS++ = RPS_LDREG | (P_DEBIAD >> 2);
1064                 /*  Write DEBI immediate data to shadow RAM. */
1065                 *pRPS++ = LocalPPL;
1066                 *pRPS++ = RPS_CLRSIGNAL | RPS_DEBI;
1067                 /*  Reset "shadow RAM uploaded"  flag. */
1068
1069                 *pRPS++ = RPS_UPLOAD | RPS_DEBI;
1070                 /*  Invoke shadow RAM upload. */
1071
1072                 *pRPS++ = RPS_PAUSE | RPS_DEBI;
1073                 /*  Wait for shadow upload to finish. */
1074
1075                 /* Delay at least 10 microseconds for analog input settling.
1076                  * Instead of padding with NOPs, we use RPS_JUMP instructions
1077                  * here; this allows us to produce a longer delay than is
1078                  * possible with NOPs because each RPS_JUMP flushes the RPS'
1079                  * instruction prefetch pipeline.
1080                  */
1081                 JmpAdrs =
1082                     (uint32_t) devpriv->RPSBuf.PhysicalBase +
1083                     (uint32_t) ((unsigned long)pRPS -
1084                                 (unsigned long)devpriv->RPSBuf.LogicalBase);
1085                 for (i = 0; i < (10 * RPSCLK_PER_US / 2); i++) {
1086                         JmpAdrs += 8;   /*  Repeat to implement time delay: */
1087                         *pRPS++ = RPS_JUMP;     /*  Jump to next RPS instruction. */
1088                         *pRPS++ = JmpAdrs;
1089                 }
1090
1091                 if (cmd != NULL && cmd->convert_src != TRIG_NOW) {
1092                         /*  Wait for Start trigger. */
1093                         *pRPS++ = RPS_PAUSE | RPS_SIGADC;
1094                         *pRPS++ = RPS_CLRSIGNAL | RPS_SIGADC;
1095                 }
1096                 /*  Start ADC by pulsing GPIO1. */
1097                 *pRPS++ = RPS_LDREG | (P_GPIO >> 2);    /*  Begin ADC Start pulse. */
1098                 *pRPS++ = GPIO_BASE | GPIO1_LO;
1099                 *pRPS++ = RPS_NOP;
1100                 /*  VERSION 2.03 CHANGE: STRETCH OUT ADC START PULSE. */
1101                 *pRPS++ = RPS_LDREG | (P_GPIO >> 2);    /*  End ADC Start pulse. */
1102                 *pRPS++ = GPIO_BASE | GPIO1_HI;
1103
1104                 /* Wait for ADC to complete (GPIO2 is asserted high when ADC not
1105                  * busy) and for data from previous conversion to shift into FB
1106                  * BUFFER 1 register.
1107                  */
1108                 *pRPS++ = RPS_PAUSE | RPS_GPIO2;        /*  Wait for ADC done. */
1109
1110                 /*  Transfer ADC data from FB BUFFER 1 register to DMA buffer. */
1111                 *pRPS++ = RPS_STREG | (BUGFIX_STREG(P_FB_BUFFER1) >> 2);
1112                 *pRPS++ =
1113                     (uint32_t) devpriv->ANABuf.PhysicalBase +
1114                     (devpriv->AdcItems << 2);
1115
1116                 /*  If this slot's EndOfPollList flag is set, all channels have */
1117                 /*  now been processed. */
1118                 if (*ppl++ & EOPL) {
1119                         devpriv->AdcItems++;    /*  Adjust poll list item count. */
1120                         break;  /*  Exit poll list processing loop. */
1121                 }
1122         }
1123
1124         /* VERSION 2.01 CHANGE: DELAY CHANGED FROM 250NS to 2US.  Allow the
1125          * ADC to stabilize for 2 microseconds before starting the final
1126          * (dummy) conversion.  This delay is necessary to allow sufficient
1127          * time between last conversion finished and the start of the dummy
1128          * conversion.  Without this delay, the last conversion's data value
1129          * is sometimes set to the previous conversion's data value.
1130          */
1131         for (n = 0; n < (2 * RPSCLK_PER_US); n++)
1132                 *pRPS++ = RPS_NOP;
1133
1134         /* Start a dummy conversion to cause the data from the last
1135          * conversion of interest to be shifted in.
1136          */
1137         *pRPS++ = RPS_LDREG | (P_GPIO >> 2);    /*  Begin ADC Start pulse. */
1138         *pRPS++ = GPIO_BASE | GPIO1_LO;
1139         *pRPS++ = RPS_NOP;
1140         /* VERSION 2.03 CHANGE: STRETCH OUT ADC START PULSE. */
1141         *pRPS++ = RPS_LDREG | (P_GPIO >> 2);    /*  End ADC Start pulse. */
1142         *pRPS++ = GPIO_BASE | GPIO1_HI;
1143
1144         /* Wait for the data from the last conversion of interest to arrive
1145          * in FB BUFFER 1 register.
1146          */
1147         *pRPS++ = RPS_PAUSE | RPS_GPIO2;        /*  Wait for ADC done. */
1148
1149         /*  Transfer final ADC data from FB BUFFER 1 register to DMA buffer. */
1150         *pRPS++ = RPS_STREG | (BUGFIX_STREG(P_FB_BUFFER1) >> 2);        /*  */
1151         *pRPS++ =
1152             (uint32_t) devpriv->ANABuf.PhysicalBase + (devpriv->AdcItems << 2);
1153
1154         /*  Indicate ADC scan loop is finished. */
1155         /*  *pRPS++= RPS_CLRSIGNAL | RPS_SIGADC ;  // Signal ReadADC() that scan is done. */
1156
1157         /* invoke interrupt */
1158         if (devpriv->ai_cmd_running == 1) {
1159                 *pRPS++ = RPS_IRQ;
1160         }
1161         /*  Restart RPS program at its beginning. */
1162         *pRPS++ = RPS_JUMP;     /*  Branch to start of RPS program. */
1163         *pRPS++ = (uint32_t) devpriv->RPSBuf.PhysicalBase;
1164
1165         /*  End of RPS program build */
1166 }
1167
1168 /* TO COMPLETE, IF NECESSARY */
1169 static int s626_ai_insn_config(struct comedi_device *dev,
1170                                struct comedi_subdevice *s,
1171                                struct comedi_insn *insn, unsigned int *data)
1172 {
1173
1174         return -EINVAL;
1175 }
1176
1177 /* static int s626_ai_rinsn(struct comedi_device *dev,struct comedi_subdevice *s,struct comedi_insn *insn,unsigned int *data) */
1178 /* { */
1179 /*   struct s626_private *devpriv = dev->private; */
1180 /*   register uint8_t   i; */
1181 /*   register int32_t   *readaddr; */
1182
1183 /*   Trigger ADC scan loop start by setting RPS Signal 0. */
1184 /*   MC_ENABLE( P_MC2, MC2_ADC_RPS ); */
1185
1186 /*   Wait until ADC scan loop is finished (RPS Signal 0 reset). */
1187 /*   while ( MC_TEST( P_MC2, MC2_ADC_RPS ) ); */
1188
1189 /* Init ptr to DMA buffer that holds new ADC data.  We skip the
1190  * first uint16_t in the buffer because it contains junk data from
1191  * the final ADC of the previous poll list scan.
1192  */
1193 /*   readaddr = (uint32_t *)devpriv->ANABuf.LogicalBase + 1; */
1194
1195 /*  Convert ADC data to 16-bit integer values and copy to application buffer. */
1196 /*   for ( i = 0; i < devpriv->AdcItems; i++ ) { */
1197 /*     *data = s626_ai_reg_to_uint( *readaddr++ ); */
1198 /*     data++; */
1199 /*   } */
1200
1201 /*   return i; */
1202 /* } */
1203
1204 static int s626_ai_insn_read(struct comedi_device *dev,
1205                              struct comedi_subdevice *s,
1206                              struct comedi_insn *insn, unsigned int *data)
1207 {
1208         struct s626_private *devpriv = dev->private;
1209         uint16_t chan = CR_CHAN(insn->chanspec);
1210         uint16_t range = CR_RANGE(insn->chanspec);
1211         uint16_t AdcSpec = 0;
1212         uint32_t GpioImage;
1213         int n;
1214
1215         /* interrupt call test  */
1216 /*   writel(IRQ_GPIO3,devpriv->base_addr+P_PSR); */
1217         /* Writing a logical 1 into any of the RPS_PSR bits causes the
1218          * corresponding interrupt to be generated if enabled
1219          */
1220
1221         /* Convert application's ADC specification into form
1222          *  appropriate for register programming.
1223          */
1224         if (range == 0)
1225                 AdcSpec = (chan << 8) | (GSEL_BIPOLAR5V);
1226         else
1227                 AdcSpec = (chan << 8) | (GSEL_BIPOLAR10V);
1228
1229         /*  Switch ADC analog gain. */
1230         DEBIwrite(dev, LP_GSEL, AdcSpec);       /*  Set gain. */
1231
1232         /*  Select ADC analog input channel. */
1233         DEBIwrite(dev, LP_ISEL, AdcSpec);       /*  Select channel. */
1234
1235         for (n = 0; n < insn->n; n++) {
1236
1237                 /*  Delay 10 microseconds for analog input settling. */
1238                 udelay(10);
1239
1240                 /*  Start ADC by pulsing GPIO1 low. */
1241                 GpioImage = RR7146(P_GPIO);
1242                 /*  Assert ADC Start command */
1243                 WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
1244                 /*    and stretch it out. */
1245                 WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
1246                 WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
1247                 /*  Negate ADC Start command. */
1248                 WR7146(P_GPIO, GpioImage | GPIO1_HI);
1249
1250                 /*  Wait for ADC to complete (GPIO2 is asserted high when */
1251                 /*  ADC not busy) and for data from previous conversion to */
1252                 /*  shift into FB BUFFER 1 register. */
1253
1254                 /*  Wait for ADC done. */
1255                 while (!(RR7146(P_PSR) & PSR_GPIO2))
1256                         ;
1257
1258                 /*  Fetch ADC data. */
1259                 if (n != 0)
1260                         data[n - 1] = s626_ai_reg_to_uint(RR7146(P_FB_BUFFER1));
1261
1262                 /* Allow the ADC to stabilize for 4 microseconds before
1263                  * starting the next (final) conversion.  This delay is
1264                  * necessary to allow sufficient time between last
1265                  * conversion finished and the start of the next
1266                  * conversion.  Without this delay, the last conversion's
1267                  * data value is sometimes set to the previous
1268                  * conversion's data value.
1269                  */
1270                 udelay(4);
1271         }
1272
1273         /* Start a dummy conversion to cause the data from the
1274          * previous conversion to be shifted in. */
1275         GpioImage = RR7146(P_GPIO);
1276
1277         /* Assert ADC Start command */
1278         WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
1279         /*    and stretch it out. */
1280         WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
1281         WR7146(P_GPIO, GpioImage & ~GPIO1_HI);
1282         /*  Negate ADC Start command. */
1283         WR7146(P_GPIO, GpioImage | GPIO1_HI);
1284
1285         /*  Wait for the data to arrive in FB BUFFER 1 register. */
1286
1287         /*  Wait for ADC done. */
1288         while (!(RR7146(P_PSR) & PSR_GPIO2))
1289                 ;
1290
1291         /*  Fetch ADC data from audio interface's input shift register. */
1292
1293         /*  Fetch ADC data. */
1294         if (n != 0)
1295                 data[n - 1] = s626_ai_reg_to_uint(RR7146(P_FB_BUFFER1));
1296
1297         return n;
1298 }
1299
1300 static int s626_ai_load_polllist(uint8_t *ppl, struct comedi_cmd *cmd)
1301 {
1302
1303         int n;
1304
1305         for (n = 0; n < cmd->chanlist_len; n++) {
1306                 if (CR_RANGE((cmd->chanlist)[n]) == 0)
1307                         ppl[n] = (CR_CHAN((cmd->chanlist)[n])) | (RANGE_5V);
1308                 else
1309                         ppl[n] = (CR_CHAN((cmd->chanlist)[n])) | (RANGE_10V);
1310         }
1311         if (n != 0)
1312                 ppl[n - 1] |= EOPL;
1313
1314         return n;
1315 }
1316
1317 static int s626_ai_inttrig(struct comedi_device *dev,
1318                            struct comedi_subdevice *s, unsigned int trignum)
1319 {
1320         struct s626_private *devpriv = dev->private;
1321
1322         if (trignum != 0)
1323                 return -EINVAL;
1324
1325         /*  Start executing the RPS program. */
1326         MC_ENABLE(P_MC1, MC1_ERPS1);
1327
1328         s->async->inttrig = NULL;
1329
1330         return 1;
1331 }
1332
1333 /* This function doesn't require a particular form, this is just what
1334  * happens to be used in some of the drivers.  It should convert ns
1335  * nanoseconds to a counter value suitable for programming the device.
1336  * Also, it should adjust ns so that it cooresponds to the actual time
1337  * that the device will use. */
1338 static int s626_ns_to_timer(int *nanosec, int round_mode)
1339 {
1340         int divider, base;
1341
1342         base = 500;             /* 2MHz internal clock */
1343
1344         switch (round_mode) {
1345         case TRIG_ROUND_NEAREST:
1346         default:
1347                 divider = (*nanosec + base / 2) / base;
1348                 break;
1349         case TRIG_ROUND_DOWN:
1350                 divider = (*nanosec) / base;
1351                 break;
1352         case TRIG_ROUND_UP:
1353                 divider = (*nanosec + base - 1) / base;
1354                 break;
1355         }
1356
1357         *nanosec = base * divider;
1358         return divider - 1;
1359 }
1360
1361 static void s626_timer_load(struct comedi_device *dev, struct enc_private *k,
1362                             int tick)
1363 {
1364         uint16_t Setup = (LOADSRC_INDX << BF_LOADSRC) | /*  Preload upon */
1365             /*  index. */
1366             (INDXSRC_SOFT << BF_INDXSRC) |      /*  Disable hardware index. */
1367             (CLKSRC_TIMER << BF_CLKSRC) |       /*  Operating mode is Timer. */
1368             (CLKPOL_POS << BF_CLKPOL) | /*  Active high clock. */
1369             (CNTDIR_DOWN << BF_CLKPOL) |        /*  Count direction is Down. */
1370             (CLKMULT_1X << BF_CLKMULT) |        /*  Clock multiplier is 1x. */
1371             (CLKENAB_INDEX << BF_CLKENAB);
1372         uint16_t valueSrclatch = LATCHSRC_A_INDXA;
1373         /*   uint16_t enab=CLKENAB_ALWAYS; */
1374
1375         k->SetMode(dev, k, Setup, FALSE);
1376
1377         /*  Set the preload register */
1378         Preload(dev, k, tick);
1379
1380         /*  Software index pulse forces the preload register to load */
1381         /*  into the counter */
1382         k->SetLoadTrig(dev, k, 0);
1383         k->PulseIndex(dev, k);
1384
1385         /* set reload on counter overflow */
1386         k->SetLoadTrig(dev, k, 1);
1387
1388         /* set interrupt on overflow */
1389         k->SetIntSrc(dev, k, INTSRC_OVER);
1390
1391         SetLatchSource(dev, k, valueSrclatch);
1392         /*   k->SetEnable(dev,k,(uint16_t)(enab != 0)); */
1393 }
1394
1395 /*  TO COMPLETE  */
1396 static int s626_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
1397 {
1398         struct s626_private *devpriv = dev->private;
1399         uint8_t ppl[16];
1400         struct comedi_cmd *cmd = &s->async->cmd;
1401         struct enc_private *k;
1402         int tick;
1403
1404         if (devpriv->ai_cmd_running) {
1405                 printk(KERN_ERR "s626_ai_cmd: Another ai_cmd is running %d\n",
1406                        dev->minor);
1407                 return -EBUSY;
1408         }
1409         /* disable interrupt */
1410         writel(0, devpriv->base_addr + P_IER);
1411
1412         /* clear interrupt request */
1413         writel(IRQ_RPS1 | IRQ_GPIO3, devpriv->base_addr + P_ISR);
1414
1415         /* clear any pending interrupt */
1416         s626_dio_clear_irq(dev);
1417         /*   s626_enc_clear_irq(dev); */
1418
1419         /* reset ai_cmd_running flag */
1420         devpriv->ai_cmd_running = 0;
1421
1422         /*  test if cmd is valid */
1423         if (cmd == NULL)
1424                 return -EINVAL;
1425
1426         if (dev->irq == 0) {
1427                 comedi_error(dev,
1428                              "s626_ai_cmd: cannot run command without an irq");
1429                 return -EIO;
1430         }
1431
1432         s626_ai_load_polllist(ppl, cmd);
1433         devpriv->ai_cmd_running = 1;
1434         devpriv->ai_convert_count = 0;
1435
1436         switch (cmd->scan_begin_src) {
1437         case TRIG_FOLLOW:
1438                 break;
1439         case TRIG_TIMER:
1440                 /*  set a conter to generate adc trigger at scan_begin_arg interval */
1441                 k = &encpriv[5];
1442                 tick = s626_ns_to_timer((int *)&cmd->scan_begin_arg,
1443                                         cmd->flags & TRIG_ROUND_MASK);
1444
1445                 /* load timer value and enable interrupt */
1446                 s626_timer_load(dev, k, tick);
1447                 k->SetEnable(dev, k, CLKENAB_ALWAYS);
1448                 break;
1449         case TRIG_EXT:
1450                 /*  set the digital line and interrupt for scan trigger */
1451                 if (cmd->start_src != TRIG_EXT)
1452                         s626_dio_set_irq(dev, cmd->scan_begin_arg);
1453                 break;
1454         }
1455
1456         switch (cmd->convert_src) {
1457         case TRIG_NOW:
1458                 break;
1459         case TRIG_TIMER:
1460                 /*  set a conter to generate adc trigger at convert_arg interval */
1461                 k = &encpriv[4];
1462                 tick = s626_ns_to_timer((int *)&cmd->convert_arg,
1463                                         cmd->flags & TRIG_ROUND_MASK);
1464
1465                 /* load timer value and enable interrupt */
1466                 s626_timer_load(dev, k, tick);
1467                 k->SetEnable(dev, k, CLKENAB_INDEX);
1468                 break;
1469         case TRIG_EXT:
1470                 /*  set the digital line and interrupt for convert trigger */
1471                 if (cmd->scan_begin_src != TRIG_EXT
1472                     && cmd->start_src == TRIG_EXT)
1473                         s626_dio_set_irq(dev, cmd->convert_arg);
1474                 break;
1475         }
1476
1477         switch (cmd->stop_src) {
1478         case TRIG_COUNT:
1479                 /*  data arrives as one packet */
1480                 devpriv->ai_sample_count = cmd->stop_arg;
1481                 devpriv->ai_continous = 0;
1482                 break;
1483         case TRIG_NONE:
1484                 /*  continous acquisition */
1485                 devpriv->ai_continous = 1;
1486                 devpriv->ai_sample_count = 0;
1487                 break;
1488         }
1489
1490         ResetADC(dev, ppl);
1491
1492         switch (cmd->start_src) {
1493         case TRIG_NOW:
1494                 /*  Trigger ADC scan loop start by setting RPS Signal 0. */
1495                 /*  MC_ENABLE( P_MC2, MC2_ADC_RPS ); */
1496
1497                 /*  Start executing the RPS program. */
1498                 MC_ENABLE(P_MC1, MC1_ERPS1);
1499
1500                 s->async->inttrig = NULL;
1501                 break;
1502         case TRIG_EXT:
1503                 /* configure DIO channel for acquisition trigger */
1504                 s626_dio_set_irq(dev, cmd->start_arg);
1505
1506                 s->async->inttrig = NULL;
1507                 break;
1508         case TRIG_INT:
1509                 s->async->inttrig = s626_ai_inttrig;
1510                 break;
1511         }
1512
1513         /* enable interrupt */
1514         writel(IRQ_GPIO3 | IRQ_RPS1, devpriv->base_addr + P_IER);
1515
1516         return 0;
1517 }
1518
1519 static int s626_ai_cmdtest(struct comedi_device *dev,
1520                            struct comedi_subdevice *s, struct comedi_cmd *cmd)
1521 {
1522         int err = 0;
1523         int tmp;
1524
1525         /* Step 1 : check if triggers are trivially valid */
1526
1527         err |= cfc_check_trigger_src(&cmd->start_src,
1528                                         TRIG_NOW | TRIG_INT | TRIG_EXT);
1529         err |= cfc_check_trigger_src(&cmd->scan_begin_src,
1530                                         TRIG_TIMER | TRIG_EXT | TRIG_FOLLOW);
1531         err |= cfc_check_trigger_src(&cmd->convert_src,
1532                                         TRIG_TIMER | TRIG_EXT | TRIG_NOW);
1533         err |= cfc_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
1534         err |= cfc_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);
1535
1536         if (err)
1537                 return 1;
1538
1539         /* Step 2a : make sure trigger sources are unique */
1540
1541         err |= cfc_check_trigger_is_unique(cmd->start_src);
1542         err |= cfc_check_trigger_is_unique(cmd->scan_begin_src);
1543         err |= cfc_check_trigger_is_unique(cmd->convert_src);
1544         err |= cfc_check_trigger_is_unique(cmd->stop_src);
1545
1546         /* Step 2b : and mutually compatible */
1547
1548         if (err)
1549                 return 2;
1550
1551         /* step 3: make sure arguments are trivially compatible */
1552
1553         if (cmd->start_src != TRIG_EXT)
1554                 err |= cfc_check_trigger_arg_is(&cmd->start_arg, 0);
1555         if (cmd->start_src == TRIG_EXT)
1556                 err |= cfc_check_trigger_arg_max(&cmd->start_arg, 39);
1557
1558         if (cmd->scan_begin_src == TRIG_EXT)
1559                 err |= cfc_check_trigger_arg_max(&cmd->scan_begin_arg, 39);
1560
1561         if (cmd->convert_src == TRIG_EXT)
1562                 err |= cfc_check_trigger_arg_max(&cmd->convert_arg, 39);
1563
1564 #define MAX_SPEED       200000  /* in nanoseconds */
1565 #define MIN_SPEED       2000000000      /* in nanoseconds */
1566
1567         if (cmd->scan_begin_src == TRIG_TIMER) {
1568                 err |= cfc_check_trigger_arg_min(&cmd->scan_begin_arg,
1569                                                  MAX_SPEED);
1570                 err |= cfc_check_trigger_arg_max(&cmd->scan_begin_arg,
1571                                                  MIN_SPEED);
1572         } else {
1573                 /* external trigger */
1574                 /* should be level/edge, hi/lo specification here */
1575                 /* should specify multiple external triggers */
1576 /*              err |= cfc_check_trigger_arg_max(&cmd->scan_begin_arg, 9); */
1577         }
1578         if (cmd->convert_src == TRIG_TIMER) {
1579                 err |= cfc_check_trigger_arg_min(&cmd->convert_arg, MAX_SPEED);
1580                 err |= cfc_check_trigger_arg_max(&cmd->convert_arg, MIN_SPEED);
1581         } else {
1582                 /* external trigger */
1583                 /* see above */
1584 /*              err |= cfc_check_trigger_arg_max(&cmd->scan_begin_arg, 9); */
1585         }
1586
1587         err |= cfc_check_trigger_arg_is(&cmd->scan_end_arg, cmd->chanlist_len);
1588
1589         if (cmd->stop_src == TRIG_COUNT)
1590                 err |= cfc_check_trigger_arg_max(&cmd->stop_arg, 0x00ffffff);
1591         else    /* TRIG_NONE */
1592                 err |= cfc_check_trigger_arg_is(&cmd->stop_arg, 0);
1593
1594         if (err)
1595                 return 3;
1596
1597         /* step 4: fix up any arguments */
1598
1599         if (cmd->scan_begin_src == TRIG_TIMER) {
1600                 tmp = cmd->scan_begin_arg;
1601                 s626_ns_to_timer((int *)&cmd->scan_begin_arg,
1602                                  cmd->flags & TRIG_ROUND_MASK);
1603                 if (tmp != cmd->scan_begin_arg)
1604                         err++;
1605         }
1606         if (cmd->convert_src == TRIG_TIMER) {
1607                 tmp = cmd->convert_arg;
1608                 s626_ns_to_timer((int *)&cmd->convert_arg,
1609                                  cmd->flags & TRIG_ROUND_MASK);
1610                 if (tmp != cmd->convert_arg)
1611                         err++;
1612                 if (cmd->scan_begin_src == TRIG_TIMER &&
1613                     cmd->scan_begin_arg <
1614                     cmd->convert_arg * cmd->scan_end_arg) {
1615                         cmd->scan_begin_arg =
1616                             cmd->convert_arg * cmd->scan_end_arg;
1617                         err++;
1618                 }
1619         }
1620
1621         if (err)
1622                 return 4;
1623
1624         return 0;
1625 }
1626
1627 static int s626_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
1628 {
1629         struct s626_private *devpriv = dev->private;
1630
1631         /*  Stop RPS program in case it is currently running. */
1632         MC_DISABLE(P_MC1, MC1_ERPS1);
1633
1634         /* disable master interrupt */
1635         writel(0, devpriv->base_addr + P_IER);
1636
1637         devpriv->ai_cmd_running = 0;
1638
1639         return 0;
1640 }
1641
1642 static int s626_ao_winsn(struct comedi_device *dev, struct comedi_subdevice *s,
1643                          struct comedi_insn *insn, unsigned int *data)
1644 {
1645         struct s626_private *devpriv = dev->private;
1646         int i;
1647         uint16_t chan = CR_CHAN(insn->chanspec);
1648         int16_t dacdata;
1649
1650         for (i = 0; i < insn->n; i++) {
1651                 dacdata = (int16_t) data[i];
1652                 devpriv->ao_readback[CR_CHAN(insn->chanspec)] = data[i];
1653                 dacdata -= (0x1fff);
1654
1655                 SetDAC(dev, chan, dacdata);
1656         }
1657
1658         return i;
1659 }
1660
1661 static int s626_ao_rinsn(struct comedi_device *dev, struct comedi_subdevice *s,
1662                          struct comedi_insn *insn, unsigned int *data)
1663 {
1664         struct s626_private *devpriv = dev->private;
1665         int i;
1666
1667         for (i = 0; i < insn->n; i++)
1668                 data[i] = devpriv->ao_readback[CR_CHAN(insn->chanspec)];
1669
1670         return i;
1671 }
1672
1673 /* *************** DIGITAL I/O FUNCTIONS ***************
1674  * All DIO functions address a group of DIO channels by means of
1675  * "group" argument.  group may be 0, 1 or 2, which correspond to DIO
1676  * ports A, B and C, respectively.
1677  */
1678
1679 static void s626_dio_init(struct comedi_device *dev)
1680 {
1681         uint16_t group;
1682         struct comedi_subdevice *s;
1683
1684         /*  Prepare to treat writes to WRCapSel as capture disables. */
1685         DEBIwrite(dev, LP_MISC1, MISC1_NOEDCAP);
1686
1687         /*  For each group of sixteen channels ... */
1688         for (group = 0; group < S626_DIO_BANKS; group++) {
1689                 s = dev->subdevices + 2 + group;
1690                 DEBIwrite(dev, diopriv->WRIntSel, 0);   /*  Disable all interrupts. */
1691                 DEBIwrite(dev, diopriv->WRCapSel, 0xFFFF);      /*  Disable all event */
1692                 /*  captures. */
1693                 DEBIwrite(dev, diopriv->WREdgSel, 0);   /*  Init all DIOs to */
1694                 /*  default edge */
1695                 /*  polarity. */
1696                 DEBIwrite(dev, diopriv->WRDOut, 0);     /*  Program all outputs */
1697                 /*  to inactive state. */
1698         }
1699 }
1700
1701 /* DIO devices are slightly special.  Although it is possible to
1702  * implement the insn_read/insn_write interface, it is much more
1703  * useful to applications if you implement the insn_bits interface.
1704  * This allows packed reading/writing of the DIO channels.  The comedi
1705  * core can convert between insn_bits and insn_read/write */
1706
1707 static int s626_dio_insn_bits(struct comedi_device *dev,
1708                               struct comedi_subdevice *s,
1709                               struct comedi_insn *insn, unsigned int *data)
1710 {
1711         /*
1712          * The insn data consists of a mask in data[0] and the new data in
1713          * data[1]. The mask defines which bits we are concerning about.
1714          * The new data must be anded with the mask.  Each channel
1715          * corresponds to a bit.
1716          */
1717         if (data[0]) {
1718                 /* Check if requested ports are configured for output */
1719                 if ((s->io_bits & data[0]) != data[0])
1720                         return -EIO;
1721
1722                 s->state &= ~data[0];
1723                 s->state |= data[0] & data[1];
1724
1725                 /* Write out the new digital output lines */
1726
1727                 DEBIwrite(dev, diopriv->WRDOut, s->state);
1728         }
1729         data[1] = DEBIread(dev, diopriv->RDDIn);
1730
1731         return insn->n;
1732 }
1733
1734 static int s626_dio_insn_config(struct comedi_device *dev,
1735                                 struct comedi_subdevice *s,
1736                                 struct comedi_insn *insn, unsigned int *data)
1737 {
1738
1739         switch (data[0]) {
1740         case INSN_CONFIG_DIO_QUERY:
1741                 data[1] =
1742                     (s->
1743                      io_bits & (1 << CR_CHAN(insn->chanspec))) ? COMEDI_OUTPUT :
1744                     COMEDI_INPUT;
1745                 return insn->n;
1746                 break;
1747         case COMEDI_INPUT:
1748                 s->io_bits &= ~(1 << CR_CHAN(insn->chanspec));
1749                 break;
1750         case COMEDI_OUTPUT:
1751                 s->io_bits |= 1 << CR_CHAN(insn->chanspec);
1752                 break;
1753         default:
1754                 return -EINVAL;
1755                 break;
1756         }
1757         DEBIwrite(dev, diopriv->WRDOut, s->io_bits);
1758
1759         return 1;
1760 }
1761
1762 /* Now this function initializes the value of the counter (data[0])
1763    and set the subdevice. To complete with trigger and interrupt
1764    configuration */
1765 /* FIXME: data[0] is supposed to be an INSN_CONFIG_xxx constant indicating
1766  * what is being configured, but this function appears to be using data[0]
1767  * as a variable. */
1768 static int s626_enc_insn_config(struct comedi_device *dev,
1769                                 struct comedi_subdevice *s,
1770                                 struct comedi_insn *insn, unsigned int *data)
1771 {
1772         uint16_t Setup = (LOADSRC_INDX << BF_LOADSRC) | /*  Preload upon */
1773             /*  index. */
1774             (INDXSRC_SOFT << BF_INDXSRC) |      /*  Disable hardware index. */
1775             (CLKSRC_COUNTER << BF_CLKSRC) |     /*  Operating mode is Counter. */
1776             (CLKPOL_POS << BF_CLKPOL) | /*  Active high clock. */
1777             /* ( CNTDIR_UP << BF_CLKPOL ) |      // Count direction is Down. */
1778             (CLKMULT_1X << BF_CLKMULT) |        /*  Clock multiplier is 1x. */
1779             (CLKENAB_INDEX << BF_CLKENAB);
1780         /*   uint16_t DisableIntSrc=TRUE; */
1781         /*  uint32_t Preloadvalue;              //Counter initial value */
1782         uint16_t valueSrclatch = LATCHSRC_AB_READ;
1783         uint16_t enab = CLKENAB_ALWAYS;
1784         struct enc_private *k = &encpriv[CR_CHAN(insn->chanspec)];
1785
1786         /*   (data==NULL) ? (Preloadvalue=0) : (Preloadvalue=data[0]); */
1787
1788         k->SetMode(dev, k, Setup, TRUE);
1789         Preload(dev, k, data[0]);
1790         k->PulseIndex(dev, k);
1791         SetLatchSource(dev, k, valueSrclatch);
1792         k->SetEnable(dev, k, (uint16_t) (enab != 0));
1793
1794         return insn->n;
1795 }
1796
1797 static int s626_enc_insn_read(struct comedi_device *dev,
1798                               struct comedi_subdevice *s,
1799                               struct comedi_insn *insn, unsigned int *data)
1800 {
1801
1802         int n;
1803         struct enc_private *k = &encpriv[CR_CHAN(insn->chanspec)];
1804
1805         for (n = 0; n < insn->n; n++)
1806                 data[n] = ReadLatch(dev, k);
1807
1808         return n;
1809 }
1810
1811 static int s626_enc_insn_write(struct comedi_device *dev,
1812                                struct comedi_subdevice *s,
1813                                struct comedi_insn *insn, unsigned int *data)
1814 {
1815
1816         struct enc_private *k = &encpriv[CR_CHAN(insn->chanspec)];
1817
1818         /*  Set the preload register */
1819         Preload(dev, k, data[0]);
1820
1821         /*  Software index pulse forces the preload register to load */
1822         /*  into the counter */
1823         k->SetLoadTrig(dev, k, 0);
1824         k->PulseIndex(dev, k);
1825         k->SetLoadTrig(dev, k, 2);
1826
1827         return 1;
1828 }
1829
1830 static void WriteMISC2(struct comedi_device *dev, uint16_t NewImage)
1831 {
1832         DEBIwrite(dev, LP_MISC1, MISC1_WENABLE);        /*  enab writes to */
1833         /*  MISC2 register. */
1834         DEBIwrite(dev, LP_WRMISC2, NewImage);   /*  Write new image to MISC2. */
1835         DEBIwrite(dev, LP_MISC1, MISC1_WDISABLE);       /*  Disable writes to MISC2. */
1836 }
1837
1838 static void CloseDMAB(struct comedi_device *dev, struct bufferDMA *pdma,
1839                       size_t bsize)
1840 {
1841         struct pci_dev *pcidev = comedi_to_pci_dev(dev);
1842         void *vbptr;
1843         dma_addr_t vpptr;
1844
1845         if (pdma == NULL)
1846                 return;
1847         /* find the matching allocation from the board struct */
1848
1849         vbptr = pdma->LogicalBase;
1850         vpptr = pdma->PhysicalBase;
1851         if (vbptr) {
1852                 pci_free_consistent(pcidev, bsize, vbptr, vpptr);
1853                 pdma->LogicalBase = NULL;
1854                 pdma->PhysicalBase = 0;
1855         }
1856 }
1857
1858 /* ******  PRIVATE COUNTER FUNCTIONS ****** */
1859
1860 /*  Reset a counter's index and overflow event capture flags. */
1861
1862 static void ResetCapFlags_A(struct comedi_device *dev, struct enc_private *k)
1863 {
1864         DEBIreplace(dev, k->MyCRB, (uint16_t) (~CRBMSK_INTCTRL),
1865                     CRBMSK_INTRESETCMD | CRBMSK_INTRESET_A);
1866 }
1867
1868 static void ResetCapFlags_B(struct comedi_device *dev, struct enc_private *k)
1869 {
1870         DEBIreplace(dev, k->MyCRB, (uint16_t) (~CRBMSK_INTCTRL),
1871                     CRBMSK_INTRESETCMD | CRBMSK_INTRESET_B);
1872 }
1873
1874 /*  Return counter setup in a format (COUNTER_SETUP) that is consistent */
1875 /*  for both A and B counters. */
1876
1877 static uint16_t GetMode_A(struct comedi_device *dev, struct enc_private *k)
1878 {
1879         register uint16_t cra;
1880         register uint16_t crb;
1881         register uint16_t setup;
1882
1883         /*  Fetch CRA and CRB register images. */
1884         cra = DEBIread(dev, k->MyCRA);
1885         crb = DEBIread(dev, k->MyCRB);
1886
1887         /*  Populate the standardized counter setup bit fields.  Note: */
1888         /*  IndexSrc is restricted to ENC_X or IndxPol. */
1889         setup = ((cra & STDMSK_LOADSRC) /*  LoadSrc  = LoadSrcA. */
1890                  |((crb << (STDBIT_LATCHSRC - CRBBIT_LATCHSRC)) & STDMSK_LATCHSRC)      /*  LatchSrc = LatchSrcA. */
1891                  |((cra << (STDBIT_INTSRC - CRABIT_INTSRC_A)) & STDMSK_INTSRC)  /*  IntSrc   = IntSrcA. */
1892                  |((cra << (STDBIT_INDXSRC - (CRABIT_INDXSRC_A + 1))) & STDMSK_INDXSRC) /*  IndxSrc  = IndxSrcA<1>. */
1893                  |((cra >> (CRABIT_INDXPOL_A - STDBIT_INDXPOL)) & STDMSK_INDXPOL)       /*  IndxPol  = IndxPolA. */
1894                  |((crb >> (CRBBIT_CLKENAB_A - STDBIT_CLKENAB)) & STDMSK_CLKENAB));     /*  ClkEnab  = ClkEnabA. */
1895
1896         /*  Adjust mode-dependent parameters. */
1897         if (cra & (2 << CRABIT_CLKSRC_A))       /*  If Timer mode (ClkSrcA<1> == 1): */
1898                 setup |= ((CLKSRC_TIMER << STDBIT_CLKSRC)       /*    Indicate Timer mode. */
1899                           |((cra << (STDBIT_CLKPOL - CRABIT_CLKSRC_A)) & STDMSK_CLKPOL) /*    Set ClkPol to indicate count direction (ClkSrcA<0>). */
1900                           |(MULT_X1 << STDBIT_CLKMULT));        /*    ClkMult must be 1x in Timer mode. */
1901
1902         else                    /*  If Counter mode (ClkSrcA<1> == 0): */
1903                 setup |= ((CLKSRC_COUNTER << STDBIT_CLKSRC)     /*    Indicate Counter mode. */
1904                           |((cra >> (CRABIT_CLKPOL_A - STDBIT_CLKPOL)) & STDMSK_CLKPOL) /*    Pass through ClkPol. */
1905                           |(((cra & CRAMSK_CLKMULT_A) == (MULT_X0 << CRABIT_CLKMULT_A)) ?       /*    Force ClkMult to 1x if not legal, else pass through. */
1906                             (MULT_X1 << STDBIT_CLKMULT) :
1907                             ((cra >> (CRABIT_CLKMULT_A -
1908                                       STDBIT_CLKMULT)) & STDMSK_CLKMULT)));
1909
1910         /*  Return adjusted counter setup. */
1911         return setup;
1912 }
1913
1914 static uint16_t GetMode_B(struct comedi_device *dev, struct enc_private *k)
1915 {
1916         register uint16_t cra;
1917         register uint16_t crb;
1918         register uint16_t setup;
1919
1920         /*  Fetch CRA and CRB register images. */
1921         cra = DEBIread(dev, k->MyCRA);
1922         crb = DEBIread(dev, k->MyCRB);
1923
1924         /*  Populate the standardized counter setup bit fields.  Note: */
1925         /*  IndexSrc is restricted to ENC_X or IndxPol. */
1926         setup = (((crb << (STDBIT_INTSRC - CRBBIT_INTSRC_B)) & STDMSK_INTSRC)   /*  IntSrc   = IntSrcB. */
1927                  |((crb << (STDBIT_LATCHSRC - CRBBIT_LATCHSRC)) & STDMSK_LATCHSRC)      /*  LatchSrc = LatchSrcB. */
1928                  |((crb << (STDBIT_LOADSRC - CRBBIT_LOADSRC_B)) & STDMSK_LOADSRC)       /*  LoadSrc  = LoadSrcB. */
1929                  |((crb << (STDBIT_INDXPOL - CRBBIT_INDXPOL_B)) & STDMSK_INDXPOL)       /*  IndxPol  = IndxPolB. */
1930                  |((crb >> (CRBBIT_CLKENAB_B - STDBIT_CLKENAB)) & STDMSK_CLKENAB)       /*  ClkEnab  = ClkEnabB. */
1931                  |((cra >> ((CRABIT_INDXSRC_B + 1) - STDBIT_INDXSRC)) & STDMSK_INDXSRC));       /*  IndxSrc  = IndxSrcB<1>. */
1932
1933         /*  Adjust mode-dependent parameters. */
1934         if ((crb & CRBMSK_CLKMULT_B) == (MULT_X0 << CRBBIT_CLKMULT_B))  /*  If Extender mode (ClkMultB == MULT_X0): */
1935                 setup |= ((CLKSRC_EXTENDER << STDBIT_CLKSRC)    /*    Indicate Extender mode. */
1936                           |(MULT_X1 << STDBIT_CLKMULT)  /*    Indicate multiplier is 1x. */
1937                           |((cra >> (CRABIT_CLKSRC_B - STDBIT_CLKPOL)) & STDMSK_CLKPOL));       /*    Set ClkPol equal to Timer count direction (ClkSrcB<0>). */
1938
1939         else if (cra & (2 << CRABIT_CLKSRC_B))  /*  If Timer mode (ClkSrcB<1> == 1): */
1940                 setup |= ((CLKSRC_TIMER << STDBIT_CLKSRC)       /*    Indicate Timer mode. */
1941                           |(MULT_X1 << STDBIT_CLKMULT)  /*    Indicate multiplier is 1x. */
1942                           |((cra >> (CRABIT_CLKSRC_B - STDBIT_CLKPOL)) & STDMSK_CLKPOL));       /*    Set ClkPol equal to Timer count direction (ClkSrcB<0>). */
1943
1944         else                    /*  If Counter mode (ClkSrcB<1> == 0): */
1945                 setup |= ((CLKSRC_COUNTER << STDBIT_CLKSRC)     /*    Indicate Timer mode. */
1946                           |((crb >> (CRBBIT_CLKMULT_B - STDBIT_CLKMULT)) & STDMSK_CLKMULT)      /*    Clock multiplier is passed through. */
1947                           |((crb << (STDBIT_CLKPOL - CRBBIT_CLKPOL_B)) & STDMSK_CLKPOL));       /*    Clock polarity is passed through. */
1948
1949         /*  Return adjusted counter setup. */
1950         return setup;
1951 }
1952
1953 /*
1954  * Set the operating mode for the specified counter.  The setup
1955  * parameter is treated as a COUNTER_SETUP data type.  The following
1956  * parameters are programmable (all other parms are ignored): ClkMult,
1957  * ClkPol, ClkEnab, IndexSrc, IndexPol, LoadSrc.
1958  */
1959
1960 static void SetMode_A(struct comedi_device *dev, struct enc_private *k,
1961                       uint16_t Setup, uint16_t DisableIntSrc)
1962 {
1963         struct s626_private *devpriv = dev->private;
1964         register uint16_t cra;
1965         register uint16_t crb;
1966         register uint16_t setup = Setup;        /*  Cache the Standard Setup. */
1967
1968         /*  Initialize CRA and CRB images. */
1969         cra = ((setup & CRAMSK_LOADSRC_A)       /*  Preload trigger is passed through. */
1970                |((setup & STDMSK_INDXSRC) >> (STDBIT_INDXSRC - (CRABIT_INDXSRC_A + 1))));       /*  IndexSrc is restricted to ENC_X or IndxPol. */
1971
1972         crb = (CRBMSK_INTRESETCMD | CRBMSK_INTRESET_A   /*  Reset any pending CounterA event captures. */
1973                | ((setup & STDMSK_CLKENAB) << (CRBBIT_CLKENAB_A - STDBIT_CLKENAB)));    /*  Clock enable is passed through. */
1974
1975         /*  Force IntSrc to Disabled if DisableIntSrc is asserted. */
1976         if (!DisableIntSrc)
1977                 cra |= ((setup & STDMSK_INTSRC) >> (STDBIT_INTSRC -
1978                                                     CRABIT_INTSRC_A));
1979
1980         /*  Populate all mode-dependent attributes of CRA & CRB images. */
1981         switch ((setup & STDMSK_CLKSRC) >> STDBIT_CLKSRC) {
1982         case CLKSRC_EXTENDER:   /*  Extender Mode: Force to Timer mode */
1983                 /*  (Extender valid only for B counters). */
1984
1985         case CLKSRC_TIMER:      /*  Timer Mode: */
1986                 cra |= ((2 << CRABIT_CLKSRC_A)  /*    ClkSrcA<1> selects system clock */
1987                         |((setup & STDMSK_CLKPOL) >> (STDBIT_CLKPOL - CRABIT_CLKSRC_A)) /*      with count direction (ClkSrcA<0>) obtained from ClkPol. */
1988                         |(1 << CRABIT_CLKPOL_A) /*    ClkPolA behaves as always-on clock enable. */
1989                         |(MULT_X1 << CRABIT_CLKMULT_A));        /*    ClkMult must be 1x. */
1990                 break;
1991
1992         default:                /*  Counter Mode: */
1993                 cra |= (CLKSRC_COUNTER  /*    Select ENC_C and ENC_D as clock/direction inputs. */
1994                         | ((setup & STDMSK_CLKPOL) << (CRABIT_CLKPOL_A - STDBIT_CLKPOL))        /*    Clock polarity is passed through. */
1995                         |(((setup & STDMSK_CLKMULT) == (MULT_X0 << STDBIT_CLKMULT)) ?   /*    Force multiplier to x1 if not legal, otherwise pass through. */
1996                           (MULT_X1 << CRABIT_CLKMULT_A) :
1997                           ((setup & STDMSK_CLKMULT) << (CRABIT_CLKMULT_A -
1998                                                         STDBIT_CLKMULT))));
1999         }
2000
2001         /*  Force positive index polarity if IndxSrc is software-driven only, */
2002         /*  otherwise pass it through. */
2003         if (~setup & STDMSK_INDXSRC)
2004                 cra |= ((setup & STDMSK_INDXPOL) << (CRABIT_INDXPOL_A -
2005                                                      STDBIT_INDXPOL));
2006
2007         /*  If IntSrc has been forced to Disabled, update the MISC2 interrupt */
2008         /*  enable mask to indicate the counter interrupt is disabled. */
2009         if (DisableIntSrc)
2010                 devpriv->CounterIntEnabs &= ~k->MyEventBits[3];
2011
2012         /*  While retaining CounterB and LatchSrc configurations, program the */
2013         /*  new counter operating mode. */
2014         DEBIreplace(dev, k->MyCRA, CRAMSK_INDXSRC_B | CRAMSK_CLKSRC_B, cra);
2015         DEBIreplace(dev, k->MyCRB,
2016                     (uint16_t) (~(CRBMSK_INTCTRL | CRBMSK_CLKENAB_A)), crb);
2017 }
2018
2019 static void SetMode_B(struct comedi_device *dev, struct enc_private *k,
2020                       uint16_t Setup, uint16_t DisableIntSrc)
2021 {
2022         struct s626_private *devpriv = dev->private;
2023         register uint16_t cra;
2024         register uint16_t crb;
2025         register uint16_t setup = Setup;        /*  Cache the Standard Setup. */
2026
2027         /*  Initialize CRA and CRB images. */
2028         cra = ((setup & STDMSK_INDXSRC) << ((CRABIT_INDXSRC_B + 1) - STDBIT_INDXSRC));  /*  IndexSrc field is restricted to ENC_X or IndxPol. */
2029
2030         crb = (CRBMSK_INTRESETCMD | CRBMSK_INTRESET_B   /*  Reset event captures and disable interrupts. */
2031                | ((setup & STDMSK_CLKENAB) << (CRBBIT_CLKENAB_B - STDBIT_CLKENAB))      /*  Clock enable is passed through. */
2032                |((setup & STDMSK_LOADSRC) >> (STDBIT_LOADSRC - CRBBIT_LOADSRC_B)));     /*  Preload trigger source is passed through. */
2033
2034         /*  Force IntSrc to Disabled if DisableIntSrc is asserted. */
2035         if (!DisableIntSrc)
2036                 crb |= ((setup & STDMSK_INTSRC) >> (STDBIT_INTSRC -
2037                                                     CRBBIT_INTSRC_B));
2038
2039         /*  Populate all mode-dependent attributes of CRA & CRB images. */
2040         switch ((setup & STDMSK_CLKSRC) >> STDBIT_CLKSRC) {
2041         case CLKSRC_TIMER:      /*  Timer Mode: */
2042                 cra |= ((2 << CRABIT_CLKSRC_B)  /*    ClkSrcB<1> selects system clock */
2043                         |((setup & STDMSK_CLKPOL) << (CRABIT_CLKSRC_B - STDBIT_CLKPOL)));       /*      with direction (ClkSrcB<0>) obtained from ClkPol. */
2044                 crb |= ((1 << CRBBIT_CLKPOL_B)  /*    ClkPolB behaves as always-on clock enable. */
2045                         |(MULT_X1 << CRBBIT_CLKMULT_B));        /*    ClkMultB must be 1x. */
2046                 break;
2047
2048         case CLKSRC_EXTENDER:   /*  Extender Mode: */
2049                 cra |= ((2 << CRABIT_CLKSRC_B)  /*    ClkSrcB source is OverflowA (same as "timer") */
2050                         |((setup & STDMSK_CLKPOL) << (CRABIT_CLKSRC_B - STDBIT_CLKPOL)));       /*      with direction obtained from ClkPol. */
2051                 crb |= ((1 << CRBBIT_CLKPOL_B)  /*    ClkPolB controls IndexB -- always set to active. */
2052                         |(MULT_X0 << CRBBIT_CLKMULT_B));        /*    ClkMultB selects OverflowA as the clock source. */
2053                 break;
2054
2055         default:                /*  Counter Mode: */
2056                 cra |= (CLKSRC_COUNTER << CRABIT_CLKSRC_B);     /*    Select ENC_C and ENC_D as clock/direction inputs. */
2057                 crb |= (((setup & STDMSK_CLKPOL) >> (STDBIT_CLKPOL - CRBBIT_CLKPOL_B))  /*    ClkPol is passed through. */
2058                         |(((setup & STDMSK_CLKMULT) == (MULT_X0 << STDBIT_CLKMULT)) ?   /*    Force ClkMult to x1 if not legal, otherwise pass through. */
2059                           (MULT_X1 << CRBBIT_CLKMULT_B) :
2060                           ((setup & STDMSK_CLKMULT) << (CRBBIT_CLKMULT_B -
2061                                                         STDBIT_CLKMULT))));
2062         }
2063
2064         /*  Force positive index polarity if IndxSrc is software-driven only, */
2065         /*  otherwise pass it through. */
2066         if (~setup & STDMSK_INDXSRC)
2067                 crb |= ((setup & STDMSK_INDXPOL) >> (STDBIT_INDXPOL -
2068                                                      CRBBIT_INDXPOL_B));
2069
2070         /*  If IntSrc has been forced to Disabled, update the MISC2 interrupt */
2071         /*  enable mask to indicate the counter interrupt is disabled. */
2072         if (DisableIntSrc)
2073                 devpriv->CounterIntEnabs &= ~k->MyEventBits[3];
2074
2075         /*  While retaining CounterA and LatchSrc configurations, program the */
2076         /*  new counter operating mode. */
2077         DEBIreplace(dev, k->MyCRA,
2078                     (uint16_t) (~(CRAMSK_INDXSRC_B | CRAMSK_CLKSRC_B)), cra);
2079         DEBIreplace(dev, k->MyCRB, CRBMSK_CLKENAB_A | CRBMSK_LATCHSRC, crb);
2080 }
2081
2082 /*  Return/set a counter's enable.  enab: 0=always enabled, 1=enabled by index. */
2083
2084 static void SetEnable_A(struct comedi_device *dev, struct enc_private *k,
2085                         uint16_t enab)
2086 {
2087         DEBIreplace(dev, k->MyCRB,
2088                     (uint16_t) (~(CRBMSK_INTCTRL | CRBMSK_CLKENAB_A)),
2089                     (uint16_t) (enab << CRBBIT_CLKENAB_A));
2090 }
2091
2092 static void SetEnable_B(struct comedi_device *dev, struct enc_private *k,
2093                         uint16_t enab)
2094 {
2095         DEBIreplace(dev, k->MyCRB,
2096                     (uint16_t) (~(CRBMSK_INTCTRL | CRBMSK_CLKENAB_B)),
2097                     (uint16_t) (enab << CRBBIT_CLKENAB_B));
2098 }
2099
2100 static uint16_t GetEnable_A(struct comedi_device *dev, struct enc_private *k)
2101 {
2102         return (DEBIread(dev, k->MyCRB) >> CRBBIT_CLKENAB_A) & 1;
2103 }
2104
2105 static uint16_t GetEnable_B(struct comedi_device *dev, struct enc_private *k)
2106 {
2107         return (DEBIread(dev, k->MyCRB) >> CRBBIT_CLKENAB_B) & 1;
2108 }
2109
2110 /*
2111  * static uint16_t GetLatchSource(struct comedi_device *dev, struct enc_private *k )
2112  * {
2113  *      return ( DEBIread( dev, k->MyCRB) >> CRBBIT_LATCHSRC ) & 3;
2114  * }
2115  */
2116
2117 /*
2118  * Return/set the event that will trigger transfer of the preload
2119  * register into the counter.  0=ThisCntr_Index, 1=ThisCntr_Overflow,
2120  * 2=OverflowA (B counters only), 3=disabled.
2121  */
2122
2123 static void SetLoadTrig_A(struct comedi_device *dev, struct enc_private *k,
2124                           uint16_t Trig)
2125 {
2126         DEBIreplace(dev, k->MyCRA, (uint16_t) (~CRAMSK_LOADSRC_A),
2127                     (uint16_t) (Trig << CRABIT_LOADSRC_A));
2128 }
2129
2130 static void SetLoadTrig_B(struct comedi_device *dev, struct enc_private *k,
2131                           uint16_t Trig)
2132 {
2133         DEBIreplace(dev, k->MyCRB,
2134                     (uint16_t) (~(CRBMSK_LOADSRC_B | CRBMSK_INTCTRL)),
2135                     (uint16_t) (Trig << CRBBIT_LOADSRC_B));
2136 }
2137
2138 static uint16_t GetLoadTrig_A(struct comedi_device *dev, struct enc_private *k)
2139 {
2140         return (DEBIread(dev, k->MyCRA) >> CRABIT_LOADSRC_A) & 3;
2141 }
2142
2143 static uint16_t GetLoadTrig_B(struct comedi_device *dev, struct enc_private *k)
2144 {
2145         return (DEBIread(dev, k->MyCRB) >> CRBBIT_LOADSRC_B) & 3;
2146 }
2147
2148 /* Return/set counter interrupt source and clear any captured
2149  * index/overflow events.  IntSource: 0=Disabled, 1=OverflowOnly,
2150  * 2=IndexOnly, 3=IndexAndOverflow.
2151  */
2152
2153 static void SetIntSrc_A(struct comedi_device *dev, struct enc_private *k,
2154                         uint16_t IntSource)
2155 {
2156         struct s626_private *devpriv = dev->private;
2157
2158         /*  Reset any pending counter overflow or index captures. */
2159         DEBIreplace(dev, k->MyCRB, (uint16_t) (~CRBMSK_INTCTRL),
2160                     CRBMSK_INTRESETCMD | CRBMSK_INTRESET_A);
2161
2162         /*  Program counter interrupt source. */
2163         DEBIreplace(dev, k->MyCRA, ~CRAMSK_INTSRC_A,
2164                     (uint16_t) (IntSource << CRABIT_INTSRC_A));
2165
2166         /*  Update MISC2 interrupt enable mask. */
2167         devpriv->CounterIntEnabs =
2168             (devpriv->CounterIntEnabs & ~k->
2169              MyEventBits[3]) | k->MyEventBits[IntSource];
2170 }
2171
2172 static void SetIntSrc_B(struct comedi_device *dev, struct enc_private *k,
2173                         uint16_t IntSource)
2174 {
2175         struct s626_private *devpriv = dev->private;
2176         uint16_t crb;
2177
2178         /*  Cache writeable CRB register image. */
2179         crb = DEBIread(dev, k->MyCRB) & ~CRBMSK_INTCTRL;
2180
2181         /*  Reset any pending counter overflow or index captures. */
2182         DEBIwrite(dev, k->MyCRB,
2183                   (uint16_t) (crb | CRBMSK_INTRESETCMD | CRBMSK_INTRESET_B));
2184
2185         /*  Program counter interrupt source. */
2186         DEBIwrite(dev, k->MyCRB,
2187                   (uint16_t) ((crb & ~CRBMSK_INTSRC_B) | (IntSource <<
2188                                                           CRBBIT_INTSRC_B)));
2189
2190         /*  Update MISC2 interrupt enable mask. */
2191         devpriv->CounterIntEnabs =
2192             (devpriv->CounterIntEnabs & ~k->
2193              MyEventBits[3]) | k->MyEventBits[IntSource];
2194 }
2195
2196 static uint16_t GetIntSrc_A(struct comedi_device *dev, struct enc_private *k)
2197 {
2198         return (DEBIread(dev, k->MyCRA) >> CRABIT_INTSRC_A) & 3;
2199 }
2200
2201 static uint16_t GetIntSrc_B(struct comedi_device *dev, struct enc_private *k)
2202 {
2203         return (DEBIread(dev, k->MyCRB) >> CRBBIT_INTSRC_B) & 3;
2204 }
2205
2206 /*  Return/set the clock multiplier. */
2207
2208 /* static void SetClkMult(struct comedi_device *dev, struct enc_private *k, uint16_t value )  */
2209 /* { */
2210 /*   k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_CLKMULT ) | ( value << STDBIT_CLKMULT ) ), FALSE ); */
2211 /* } */
2212
2213 /* static uint16_t GetClkMult(struct comedi_device *dev, struct enc_private *k )  */
2214 /* { */
2215 /*   return ( k->GetMode(dev, k ) >> STDBIT_CLKMULT ) & 3; */
2216 /* } */
2217
2218 /* Return/set the clock polarity. */
2219
2220 /* static void SetClkPol( struct comedi_device *dev,struct enc_private *k, uint16_t value )  */
2221 /* { */
2222 /*   k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_CLKPOL ) | ( value << STDBIT_CLKPOL ) ), FALSE ); */
2223 /* } */
2224
2225 /* static uint16_t GetClkPol(struct comedi_device *dev, struct enc_private *k )  */
2226 /* { */
2227 /*   return ( k->GetMode(dev, k ) >> STDBIT_CLKPOL ) & 1; */
2228 /* } */
2229
2230 /* Return/set the clock source.  */
2231
2232 /* static void SetClkSrc( struct comedi_device *dev,struct enc_private *k, uint16_t value )  */
2233 /* { */
2234 /*   k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_CLKSRC ) | ( value << STDBIT_CLKSRC ) ), FALSE ); */
2235 /* } */
2236
2237 /* static uint16_t GetClkSrc( struct comedi_device *dev,struct enc_private *k )  */
2238 /* { */
2239 /*   return ( k->GetMode(dev, k ) >> STDBIT_CLKSRC ) & 3; */
2240 /* } */
2241
2242 /* Return/set the index polarity. */
2243
2244 /* static void SetIndexPol(struct comedi_device *dev, struct enc_private *k, uint16_t value )  */
2245 /* { */
2246 /*   k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_INDXPOL ) | ( (value != 0) << STDBIT_INDXPOL ) ), FALSE ); */
2247 /* } */
2248
2249 /* static uint16_t GetIndexPol(struct comedi_device *dev, struct enc_private *k )  */
2250 /* { */
2251 /*   return ( k->GetMode(dev, k ) >> STDBIT_INDXPOL ) & 1; */
2252 /* } */
2253
2254 /*  Return/set the index source. */
2255
2256 /* static void SetIndexSrc(struct comedi_device *dev, struct enc_private *k, uint16_t value )  */
2257 /* { */
2258 /*   k->SetMode(dev, k, (uint16_t)( ( k->GetMode(dev, k ) & ~STDMSK_INDXSRC ) | ( (value != 0) << STDBIT_INDXSRC ) ), FALSE ); */
2259 /* } */
2260
2261 /* static uint16_t GetIndexSrc(struct comedi_device *dev, struct enc_private *k )  */
2262 /* { */
2263 /*   return ( k->GetMode(dev, k ) >> STDBIT_INDXSRC ) & 1; */
2264 /* } */
2265
2266 /*  Generate an index pulse. */
2267
2268 static void PulseIndex_A(struct comedi_device *dev, struct enc_private *k)
2269 {
2270         register uint16_t cra;
2271
2272         cra = DEBIread(dev, k->MyCRA);  /*  Pulse index. */
2273         DEBIwrite(dev, k->MyCRA, (uint16_t) (cra ^ CRAMSK_INDXPOL_A));
2274         DEBIwrite(dev, k->MyCRA, cra);
2275 }
2276
2277 static void PulseIndex_B(struct comedi_device *dev, struct enc_private *k)
2278 {
2279         register uint16_t crb;
2280
2281         crb = DEBIread(dev, k->MyCRB) & ~CRBMSK_INTCTRL;        /*  Pulse index. */
2282         DEBIwrite(dev, k->MyCRB, (uint16_t) (crb ^ CRBMSK_INDXPOL_B));
2283         DEBIwrite(dev, k->MyCRB, crb);
2284 }
2285
2286 static struct enc_private enc_private_data[] = {
2287         {
2288                 .GetEnable      = GetEnable_A,
2289                 .GetIntSrc      = GetIntSrc_A,
2290                 .GetLoadTrig    = GetLoadTrig_A,
2291                 .GetMode        = GetMode_A,
2292                 .PulseIndex     = PulseIndex_A,
2293                 .SetEnable      = SetEnable_A,
2294                 .SetIntSrc      = SetIntSrc_A,
2295                 .SetLoadTrig    = SetLoadTrig_A,
2296                 .SetMode        = SetMode_A,
2297                 .ResetCapFlags  = ResetCapFlags_A,
2298                 .MyCRA          = LP_CR0A,
2299                 .MyCRB          = LP_CR0B,
2300                 .MyLatchLsw     = LP_CNTR0ALSW,
2301                 .MyEventBits    = EVBITS(0),
2302         }, {
2303                 .GetEnable      = GetEnable_A,
2304                 .GetIntSrc      = GetIntSrc_A,
2305                 .GetLoadTrig    = GetLoadTrig_A,
2306                 .GetMode        = GetMode_A,
2307                 .PulseIndex     = PulseIndex_A,
2308                 .SetEnable      = SetEnable_A,
2309                 .SetIntSrc      = SetIntSrc_A,
2310                 .SetLoadTrig    = SetLoadTrig_A,
2311                 .SetMode        = SetMode_A,
2312                 .ResetCapFlags  = ResetCapFlags_A,
2313                 .MyCRA          = LP_CR1A,
2314                 .MyCRB          = LP_CR1B,
2315                 .MyLatchLsw     = LP_CNTR1ALSW,
2316                 .MyEventBits    = EVBITS(1),
2317         }, {
2318                 .GetEnable      = GetEnable_A,
2319                 .GetIntSrc      = GetIntSrc_A,
2320                 .GetLoadTrig    = GetLoadTrig_A,
2321                 .GetMode        = GetMode_A,
2322                 .PulseIndex     = PulseIndex_A,
2323                 .SetEnable      = SetEnable_A,
2324                 .SetIntSrc      = SetIntSrc_A,
2325                 .SetLoadTrig    = SetLoadTrig_A,
2326                 .SetMode        = SetMode_A,
2327                 .ResetCapFlags  = ResetCapFlags_A,
2328                 .MyCRA          = LP_CR2A,
2329                 .MyCRB          = LP_CR2B,
2330                 .MyLatchLsw     = LP_CNTR2ALSW,
2331                 .MyEventBits    = EVBITS(2),
2332         }, {
2333                 .GetEnable      = GetEnable_B,
2334                 .GetIntSrc      = GetIntSrc_B,
2335                 .GetLoadTrig    = GetLoadTrig_B,
2336                 .GetMode        = GetMode_B,
2337                 .PulseIndex     = PulseIndex_B,
2338                 .SetEnable      = SetEnable_B,
2339                 .SetIntSrc      = SetIntSrc_B,
2340                 .SetLoadTrig    = SetLoadTrig_B,
2341                 .SetMode        = SetMode_B,
2342                 .ResetCapFlags  = ResetCapFlags_B,
2343                 .MyCRA          = LP_CR0A,
2344                 .MyCRB          = LP_CR0B,
2345                 .MyLatchLsw     = LP_CNTR0BLSW,
2346                 .MyEventBits    = EVBITS(3),
2347         }, {
2348                 .GetEnable      = GetEnable_B,
2349                 .GetIntSrc      = GetIntSrc_B,
2350                 .GetLoadTrig    = GetLoadTrig_B,
2351                 .GetMode        = GetMode_B,
2352                 .PulseIndex     = PulseIndex_B,
2353                 .SetEnable      = SetEnable_B,
2354                 .SetIntSrc      = SetIntSrc_B,
2355                 .SetLoadTrig    = SetLoadTrig_B,
2356                 .SetMode        = SetMode_B,
2357                 .ResetCapFlags  = ResetCapFlags_B,
2358                 .MyCRA          = LP_CR1A,
2359                 .MyCRB          = LP_CR1B,
2360                 .MyLatchLsw     = LP_CNTR1BLSW,
2361                 .MyEventBits    = EVBITS(4),
2362         }, {
2363                 .GetEnable      = GetEnable_B,
2364                 .GetIntSrc      = GetIntSrc_B,
2365                 .GetLoadTrig    = GetLoadTrig_B,
2366                 .GetMode        = GetMode_B,
2367                 .PulseIndex     = PulseIndex_B,
2368                 .SetEnable      = SetEnable_B,
2369                 .SetIntSrc      = SetIntSrc_B,
2370                 .SetLoadTrig    = SetLoadTrig_B,
2371                 .SetMode        = SetMode_B,
2372                 .ResetCapFlags  = ResetCapFlags_B,
2373                 .MyCRA          = LP_CR2A,
2374                 .MyCRB          = LP_CR2B,
2375                 .MyLatchLsw     = LP_CNTR2BLSW,
2376                 .MyEventBits    = EVBITS(5),
2377         },
2378 };
2379
2380 static void CountersInit(struct comedi_device *dev)
2381 {
2382         int chan;
2383         struct enc_private *k;
2384         uint16_t Setup = (LOADSRC_INDX << BF_LOADSRC) | /*  Preload upon */
2385             /*  index. */
2386             (INDXSRC_SOFT << BF_INDXSRC) |      /*  Disable hardware index. */
2387             (CLKSRC_COUNTER << BF_CLKSRC) |     /*  Operating mode is counter. */
2388             (CLKPOL_POS << BF_CLKPOL) | /*  Active high clock. */
2389             (CNTDIR_UP << BF_CLKPOL) |  /*  Count direction is up. */
2390             (CLKMULT_1X << BF_CLKMULT) |        /*  Clock multiplier is 1x. */
2391             (CLKENAB_INDEX << BF_CLKENAB);      /*  Enabled by index */
2392
2393         /*  Disable all counter interrupts and clear any captured counter events. */
2394         for (chan = 0; chan < S626_ENCODER_CHANNELS; chan++) {
2395                 k = &encpriv[chan];
2396                 k->SetMode(dev, k, Setup, TRUE);
2397                 k->SetIntSrc(dev, k, 0);
2398                 k->ResetCapFlags(dev, k);
2399                 k->SetEnable(dev, k, CLKENAB_ALWAYS);
2400         }
2401 }
2402
2403 static int s626_allocate_dma_buffers(struct comedi_device *dev)
2404 {
2405         struct pci_dev *pcidev = comedi_to_pci_dev(dev);
2406         struct s626_private *devpriv = dev->private;
2407         void *addr;
2408         dma_addr_t appdma;
2409
2410         addr = pci_alloc_consistent(pcidev, DMABUF_SIZE, &appdma);
2411         if (!addr)
2412                 return -ENOMEM;
2413         devpriv->ANABuf.LogicalBase = addr;
2414         devpriv->ANABuf.PhysicalBase = appdma;
2415
2416         addr = pci_alloc_consistent(pcidev, DMABUF_SIZE, &appdma);
2417         if (!addr)
2418                 return -ENOMEM;
2419         devpriv->RPSBuf.LogicalBase = addr;
2420         devpriv->RPSBuf.PhysicalBase = appdma;
2421
2422         return 0;
2423 }
2424
2425 static void s626_initialize(struct comedi_device *dev)
2426 {
2427         struct s626_private *devpriv = dev->private;
2428         dma_addr_t pPhysBuf;
2429         uint16_t chan;
2430         int i;
2431
2432         /* Enable DEBI and audio pins, enable I2C interface */
2433         MC_ENABLE(P_MC1, MC1_DEBI | MC1_AUDIO | MC1_I2C);
2434
2435         /*
2436          *  Configure DEBI operating mode
2437          *
2438          *   Local bus is 16 bits wide
2439          *   Declare DEBI transfer timeout interval
2440          *   Set up byte lane steering
2441          *   Intel-compatible local bus (DEBI never times out)
2442          */
2443         WR7146(P_DEBICFG, DEBI_CFG_SLAVE16 |
2444                           (DEBI_TOUT << DEBI_CFG_TOUT_BIT) |
2445                           DEBI_SWAP | DEBI_CFG_INTEL);
2446
2447         /* Disable MMU paging */
2448         WR7146(P_DEBIPAGE, DEBI_PAGE_DISABLE);
2449
2450         /* Init GPIO so that ADC Start* is negated */
2451         WR7146(P_GPIO, GPIO_BASE | GPIO1_HI);
2452
2453         /* I2C device address for onboard eeprom (revb) */
2454         devpriv->I2CAdrs = 0xA0;
2455
2456         /*
2457          * Issue an I2C ABORT command to halt any I2C
2458          * operation in progress and reset BUSY flag.
2459          */
2460         WR7146(P_I2CSTAT, I2C_CLKSEL | I2C_ABORT);
2461         MC_ENABLE(P_MC2, MC2_UPLD_IIC);
2462         while ((RR7146(P_MC2) & MC2_UPLD_IIC) == 0)
2463                 ;
2464
2465         /*
2466          * Per SAA7146 data sheet, write to STATUS
2467          * reg twice to reset all  I2C error flags.
2468          */
2469         for (i = 0; i < 2; i++) {
2470                 WR7146(P_I2CSTAT, I2C_CLKSEL);
2471                 MC_ENABLE(P_MC2, MC2_UPLD_IIC);
2472                 while (!MC_TEST(P_MC2, MC2_UPLD_IIC))
2473                         ;
2474         }
2475
2476         /*
2477          * Init audio interface functional attributes: set DAC/ADC
2478          * serial clock rates, invert DAC serial clock so that
2479          * DAC data setup times are satisfied, enable DAC serial
2480          * clock out.
2481          */
2482         WR7146(P_ACON2, ACON2_INIT);
2483
2484         /*
2485          * Set up TSL1 slot list, which is used to control the
2486          * accumulation of ADC data: RSD1 = shift data in on SD1.
2487          * SIB_A1  = store data uint8_t at next available location
2488          * in FB BUFFER1 register.
2489          */
2490         WR7146(P_TSL1, RSD1 | SIB_A1);
2491         WR7146(P_TSL1 + 4, RSD1 | SIB_A1 | EOS);
2492
2493         /* Enable TSL1 slot list so that it executes all the time */
2494         WR7146(P_ACON1, ACON1_ADCSTART);
2495
2496         /*
2497          * Initialize RPS registers used for ADC
2498          */
2499
2500         /* Physical start of RPS program */
2501         WR7146(P_RPSADDR1, (uint32_t)devpriv->RPSBuf.PhysicalBase);
2502         /* RPS program performs no explicit mem writes */
2503         WR7146(P_RPSPAGE1, 0);
2504         /* Disable RPS timeouts */
2505         WR7146(P_RPS1_TOUT, 0);
2506
2507 #if 0
2508         /*
2509          * SAA7146 BUG WORKAROUND
2510          *
2511          * Initialize SAA7146 ADC interface to a known state by
2512          * invoking ADCs until FB BUFFER 1 register shows that it
2513          * is correctly receiving ADC data. This is necessary
2514          * because the SAA7146 ADC interface does not start up in
2515          * a defined state after a PCI reset.
2516          */
2517
2518         {
2519         uint8_t PollList;
2520         uint16_t AdcData;
2521         uint16_t StartVal;
2522         uint16_t index;
2523         unsigned int data[16];
2524
2525         /* Create a simple polling list for analog input channel 0 */
2526         PollList = EOPL;
2527         ResetADC(dev, &PollList);
2528
2529         /* Get initial ADC value */
2530         s626_ai_rinsn(dev, dev->subdevices, NULL, data);
2531         StartVal = data[0];
2532
2533         /*
2534          * VERSION 2.01 CHANGE: TIMEOUT ADDED TO PREVENT HANGED EXECUTION.
2535          *
2536          * Invoke ADCs until the new ADC value differs from the initial
2537          * value or a timeout occurs.  The timeout protects against the
2538          * possibility that the driver is restarting and the ADC data is a
2539          * fixed value resulting from the applied ADC analog input being
2540          * unusually quiet or at the rail.
2541          */
2542         for (index = 0; index < 500; index++) {
2543                 s626_ai_rinsn(dev, dev->subdevices, NULL, data);
2544                 AdcData = data[0];
2545                 if (AdcData != StartVal)
2546                         break;
2547         }
2548
2549         }
2550 #endif  /* SAA7146 BUG WORKAROUND */
2551
2552         /*
2553          * Initialize the DAC interface
2554          */
2555
2556         /*
2557          * Init Audio2's output DMAC attributes:
2558          *   burst length = 1 DWORD
2559          *   threshold = 1 DWORD.
2560          */
2561         WR7146(P_PCI_BT_A, 0);
2562
2563         /*
2564          * Init Audio2's output DMA physical addresses.  The protection
2565          * address is set to 1 DWORD past the base address so that a
2566          * single DWORD will be transferred each time a DMA transfer is
2567          * enabled.
2568          */
2569         pPhysBuf = devpriv->ANABuf.PhysicalBase +
2570                    (DAC_WDMABUF_OS * sizeof(uint32_t));
2571         WR7146(P_BASEA2_OUT, (uint32_t) pPhysBuf);
2572         WR7146(P_PROTA2_OUT, (uint32_t) (pPhysBuf + sizeof(uint32_t)));
2573
2574         /*
2575          * Cache Audio2's output DMA buffer logical address.  This is
2576          * where DAC data is buffered for A2 output DMA transfers.
2577          */
2578         devpriv->pDacWBuf = (uint32_t *)devpriv->ANABuf.LogicalBase +
2579                             DAC_WDMABUF_OS;
2580
2581         /*
2582          * Audio2's output channels does not use paging.  The
2583          * protection violation handling bit is set so that the
2584          * DMAC will automatically halt and its PCI address pointer
2585          * will be reset when the protection address is reached.
2586          */
2587         WR7146(P_PAGEA2_OUT, 8);
2588
2589         /*
2590          * Initialize time slot list 2 (TSL2), which is used to control
2591          * the clock generation for and serialization of data to be sent
2592          * to the DAC devices.  Slot 0 is a NOP that is used to trap TSL
2593          * execution; this permits other slots to be safely modified
2594          * without first turning off the TSL sequencer (which is
2595          * apparently impossible to do).  Also, SD3 (which is driven by a
2596          * pull-up resistor) is shifted in and stored to the MSB of
2597          * FB_BUFFER2 to be used as evidence that the slot sequence has
2598          * not yet finished executing.
2599          */
2600
2601         /* Slot 0: Trap TSL execution, shift 0xFF into FB_BUFFER2 */
2602         SETVECT(0, XSD2 | RSD3 | SIB_A2 | EOS);
2603
2604         /*
2605          * Initialize slot 1, which is constant.  Slot 1 causes a
2606          * DWORD to be transferred from audio channel 2's output FIFO
2607          * to the FIFO's output buffer so that it can be serialized
2608          * and sent to the DAC during subsequent slots.  All remaining
2609          * slots are dynamically populated as required by the target
2610          * DAC device.
2611          */
2612
2613         /* Slot 1: Fetch DWORD from Audio2's output FIFO */
2614         SETVECT(1, LF_A2);
2615
2616         /* Start DAC's audio interface (TSL2) running */
2617         WR7146(P_ACON1, ACON1_DACSTART);
2618
2619         /*
2620          * Init Trim DACs to calibrated values.  Do it twice because the
2621          * SAA7146 audio channel does not always reset properly and
2622          * sometimes causes the first few TrimDAC writes to malfunction.
2623          */
2624         LoadTrimDACs(dev);
2625         LoadTrimDACs(dev);
2626
2627         /*
2628          * Manually init all gate array hardware in case this is a soft
2629          * reset (we have no way of determining whether this is a warm
2630          * or cold start).  This is necessary because the gate array will
2631          * reset only in response to a PCI hard reset; there is no soft
2632          * reset function.
2633          */
2634
2635         /*
2636          * Init all DAC outputs to 0V and init all DAC setpoint and
2637          * polarity images.
2638          */
2639         for (chan = 0; chan < S626_DAC_CHANNELS; chan++)
2640                 SetDAC(dev, chan, 0);
2641
2642         /* Init counters */
2643         CountersInit(dev);
2644
2645         /*
2646          * Without modifying the state of the Battery Backup enab, disable
2647          * the watchdog timer, set DIO channels 0-5 to operate in the
2648          * standard DIO (vs. counter overflow) mode, disable the battery
2649          * charger, and reset the watchdog interval selector to zero.
2650          */
2651         WriteMISC2(dev, (uint16_t)(DEBIread(dev, LP_RDMISC2) &
2652                                    MISC2_BATT_ENABLE));
2653
2654         /* Initialize the digital I/O subsystem */
2655         s626_dio_init(dev);
2656
2657         /* enable interrupt test */
2658         /* writel(IRQ_GPIO3 | IRQ_RPS1, devpriv->base_addr + P_IER); */
2659 }
2660
2661 static int s626_auto_attach(struct comedi_device *dev,
2662                                       unsigned long context_unused)
2663 {
2664         struct pci_dev *pcidev = comedi_to_pci_dev(dev);
2665         struct s626_private *devpriv;
2666         struct comedi_subdevice *s;
2667         int ret;
2668
2669         dev->board_name = dev->driver->driver_name;
2670
2671         devpriv = kzalloc(sizeof(*devpriv), GFP_KERNEL);
2672         if (!devpriv)
2673                 return -ENOMEM;
2674         dev->private = devpriv;
2675
2676         ret = comedi_pci_enable(pcidev, dev->board_name);
2677         if (ret)
2678                 return ret;
2679         dev->iobase = 1;        /* detach needs this */
2680
2681         devpriv->base_addr = ioremap(pci_resource_start(pcidev, 0),
2682                                      pci_resource_len(pcidev, 0));
2683         if (!devpriv->base_addr)
2684                 return -ENOMEM;
2685
2686         /* disable master interrupt */
2687         writel(0, devpriv->base_addr + P_IER);
2688
2689         /* soft reset */
2690         writel(MC1_SOFT_RESET, devpriv->base_addr + P_MC1);
2691
2692         /* DMA FIXME DMA// */
2693
2694         ret = s626_allocate_dma_buffers(dev);
2695         if (ret)
2696                 return ret;
2697
2698         if (pcidev->irq) {
2699                 ret = request_irq(pcidev->irq, s626_irq_handler, IRQF_SHARED,
2700                                   dev->board_name, dev);
2701
2702                 if (ret == 0)
2703                         dev->irq = pcidev->irq;
2704         }
2705
2706         ret = comedi_alloc_subdevices(dev, 6);
2707         if (ret)
2708                 return ret;
2709
2710         s = dev->subdevices + 0;
2711         /* analog input subdevice */
2712         dev->read_subdev = s;
2713         /* we support single-ended (ground) and differential */
2714         s->type = COMEDI_SUBD_AI;
2715         s->subdev_flags = SDF_READABLE | SDF_DIFF | SDF_CMD_READ;
2716         s->n_chan = S626_ADC_CHANNELS;
2717         s->maxdata = (0xffff >> 2);
2718         s->range_table = &s626_range_table;
2719         s->len_chanlist = S626_ADC_CHANNELS;
2720         s->insn_config = s626_ai_insn_config;
2721         s->insn_read = s626_ai_insn_read;
2722         s->do_cmd = s626_ai_cmd;
2723         s->do_cmdtest = s626_ai_cmdtest;
2724         s->cancel = s626_ai_cancel;
2725
2726         s = dev->subdevices + 1;
2727         /* analog output subdevice */
2728         s->type = COMEDI_SUBD_AO;
2729         s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
2730         s->n_chan = S626_DAC_CHANNELS;
2731         s->maxdata = (0x3fff);
2732         s->range_table = &range_bipolar10;
2733         s->insn_write = s626_ao_winsn;
2734         s->insn_read = s626_ao_rinsn;
2735
2736         s = dev->subdevices + 2;
2737         /* digital I/O subdevice */
2738         s->type = COMEDI_SUBD_DIO;
2739         s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
2740         s->n_chan = 16;
2741         s->maxdata = 1;
2742         s->io_bits = 0xffff;
2743         s->private = &dio_private_A;
2744         s->range_table = &range_digital;
2745         s->insn_config = s626_dio_insn_config;
2746         s->insn_bits = s626_dio_insn_bits;
2747
2748         s = dev->subdevices + 3;
2749         /* digital I/O subdevice */
2750         s->type = COMEDI_SUBD_DIO;
2751         s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
2752         s->n_chan = 16;
2753         s->maxdata = 1;
2754         s->io_bits = 0xffff;
2755         s->private = &dio_private_B;
2756         s->range_table = &range_digital;
2757         s->insn_config = s626_dio_insn_config;
2758         s->insn_bits = s626_dio_insn_bits;
2759
2760         s = dev->subdevices + 4;
2761         /* digital I/O subdevice */
2762         s->type = COMEDI_SUBD_DIO;
2763         s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
2764         s->n_chan = 16;
2765         s->maxdata = 1;
2766         s->io_bits = 0xffff;
2767         s->private = &dio_private_C;
2768         s->range_table = &range_digital;
2769         s->insn_config = s626_dio_insn_config;
2770         s->insn_bits = s626_dio_insn_bits;
2771
2772         s = dev->subdevices + 5;
2773         /* encoder (counter) subdevice */
2774         s->type = COMEDI_SUBD_COUNTER;
2775         s->subdev_flags = SDF_WRITABLE | SDF_READABLE | SDF_LSAMPL;
2776         s->n_chan = S626_ENCODER_CHANNELS;
2777         s->private = enc_private_data;
2778         s->insn_config = s626_enc_insn_config;
2779         s->insn_read = s626_enc_insn_read;
2780         s->insn_write = s626_enc_insn_write;
2781         s->maxdata = 0xffffff;
2782         s->range_table = &range_unknown;
2783
2784         s626_initialize(dev);
2785
2786         dev_info(dev->class_dev, "%s attached\n", dev->board_name);
2787
2788         return 0;
2789 }
2790
2791 static void s626_detach(struct comedi_device *dev)
2792 {
2793         struct pci_dev *pcidev = comedi_to_pci_dev(dev);
2794         struct s626_private *devpriv = dev->private;
2795
2796         if (devpriv) {
2797                 /* stop ai_command */
2798                 devpriv->ai_cmd_running = 0;
2799
2800                 if (devpriv->base_addr) {
2801                         /* interrupt mask */
2802                         WR7146(P_IER, 0);       /*  Disable master interrupt. */
2803                         WR7146(P_ISR, IRQ_GPIO3 | IRQ_RPS1);    /*  Clear board's IRQ status flag. */
2804
2805                         /*  Disable the watchdog timer and battery charger. */
2806                         WriteMISC2(dev, 0);
2807
2808                         /*  Close all interfaces on 7146 device. */
2809                         WR7146(P_MC1, MC1_SHUTDOWN);
2810                         WR7146(P_ACON1, ACON1_BASE);
2811
2812                         CloseDMAB(dev, &devpriv->RPSBuf, DMABUF_SIZE);
2813                         CloseDMAB(dev, &devpriv->ANABuf, DMABUF_SIZE);
2814                 }
2815
2816                 if (dev->irq)
2817                         free_irq(dev->irq, dev);
2818                 if (devpriv->base_addr)
2819                         iounmap(devpriv->base_addr);
2820         }
2821         if (pcidev) {
2822                 if (dev->iobase)
2823                         comedi_pci_disable(pcidev);
2824         }
2825 }
2826
2827 static struct comedi_driver s626_driver = {
2828         .driver_name    = "s626",
2829         .module         = THIS_MODULE,
2830         .auto_attach    = s626_auto_attach,
2831         .detach         = s626_detach,
2832 };
2833
2834 static int s626_pci_probe(struct pci_dev *dev,
2835                                     const struct pci_device_id *ent)
2836 {
2837         return comedi_pci_auto_config(dev, &s626_driver);
2838 }
2839
2840 /*
2841  * For devices with vendor:device id == 0x1131:0x7146 you must specify
2842  * also subvendor:subdevice ids, because otherwise it will conflict with
2843  * Philips SAA7146 media/dvb based cards.
2844  */
2845 static DEFINE_PCI_DEVICE_TABLE(s626_pci_table) = {
2846         { PCI_VENDOR_ID_S626, PCI_DEVICE_ID_S626,
2847                 PCI_SUBVENDOR_ID_S626, PCI_SUBDEVICE_ID_S626, 0, 0, 0 },
2848         { 0 }
2849 };
2850 MODULE_DEVICE_TABLE(pci, s626_pci_table);
2851
2852 static struct pci_driver s626_pci_driver = {
2853         .name           = "s626",
2854         .id_table       = s626_pci_table,
2855         .probe          = s626_pci_probe,
2856         .remove         = comedi_pci_auto_unconfig,
2857 };
2858 module_comedi_pci_driver(s626_driver, s626_pci_driver);
2859
2860 MODULE_AUTHOR("Gianluca Palli <gpalli@deis.unibo.it>");
2861 MODULE_DESCRIPTION("Sensoray 626 Comedi driver module");
2862 MODULE_LICENSE("GPL");