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