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