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