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