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