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