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