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