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