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