generate overflow events when ai fifo overflows with pio transfers
[comedi.git] / comedi / drivers / ni_mio_common.c
1 /*
2     comedi/drivers/ni_mio_common.c
3     Hardware driver for DAQ-STC based boards
4
5     COMEDI - Linux Control and Measurement Device Interface
6     Copyright (C) 1997-2001 David A. Schleef <ds@schleef.org>
7     Copyright (C) 2002, 2003 Frank Mori Hess <fmhess@users.sourceforge.net
8
9     This program is free software; you can redistribute it and/or modify
10     it under the terms of the GNU General Public License as published by
11     the Free Software Foundation; either version 2 of the License, or
12     (at your option) any later version.
13
14     This program is distributed in the hope that it will be useful,
15     but WITHOUT ANY WARRANTY; without even the implied warranty of
16     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17     GNU General Public License for more details.
18
19     You should have received a copy of the GNU General Public License
20     along with this program; if not, write to the Free Software
21     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22
23 */
24
25 /*
26         This file is meant to be included by another file, e.g.,
27         ni_atmio.c or ni_pcimio.c.
28
29         Interrupt support originally added by Truxton Fulton
30         <trux@truxton.com>
31
32         References (from ftp://ftp.natinst.com/support/manuals):
33
34            340747b.pdf  AT-MIO E series Register Level Programmer Manual
35            341079b.pdf  PCI E Series RLPM
36            340934b.pdf  DAQ-STC reference manual
37         67xx and 611x registers (from http://www.ni.com/pdf/daq/us)
38         release_ni611x.pdf
39         release_ni67xx.pdf
40         Other possibly relevant info:
41
42            320517c.pdf  User manual (obsolete)
43            320517f.pdf  User manual (new)
44            320889a.pdf  delete
45            320906c.pdf  maximum signal ratings
46            321066a.pdf  about 16x
47            321791a.pdf  discontinuation of at-mio-16e-10 rev. c
48            321808a.pdf  about at-mio-16e-10 rev P
49            321837a.pdf  discontinuation of at-mio-16de-10 rev d
50            321838a.pdf  about at-mio-16de-10 rev N
51
52         ISSUES:
53
54          - the interrupt routine needs to be cleaned up
55          - many printk's need to be changed to rt_printk()
56 */
57
58 //#define DEBUG_INTERRUPT
59 //#define DEBUG_STATUS_A
60 //#define DEBUG_STATUS_B
61
62 #include "8255.h"
63 #include "mite.h"
64 #include "comedi_fc.h"
65
66 #ifndef MDPRINTK
67 #define MDPRINTK(format,args...)
68 #endif
69
70 /* A timeout count */
71
72 #define NI_TIMEOUT 1000
73
74 /* Note: this table must match the ai_gain_* definitions */
75 static short ni_gainlkup[][16]={
76         /* ai_gain_16 */
77         { 0, 1, 2, 3, 4, 5, 6, 7, 0x100, 0x101, 0x102, 0x103, 0x104, 0x105,
78                 0x106, 0x107 },
79         /* ai_gain_8 */
80         { 1, 2, 4, 7, 0x101, 0x102, 0x104, 0x107 },
81         /* ai_gain_14 */
82         { 1, 2, 3, 4, 5, 6, 7, 0x101, 0x102, 0x103, 0x104, 0x105, 0x106,
83                 0x107 },
84         /* ai_gain_4 */
85         { 0, 1, 4, 7 },
86         /* ai_gain_611x */
87         { 0x00a, 0x00b, 0x001, 0x002, 0x003, 0x004, 0x005, 0x006 }
88 };
89
90 static comedi_lrange range_ni_E_ai={    16, {
91         RANGE( -10,     10      ),
92         RANGE( -5,      5       ),
93         RANGE( -2.5,    2.5     ),
94         RANGE( -1,      1       ),
95         RANGE( -0.5,    0.5     ),
96         RANGE( -0.25,   0.25    ),
97         RANGE( -0.1,    0.1     ),
98         RANGE( -0.05,   0.05    ),
99         RANGE( 0,       20      ),
100         RANGE( 0,       10      ),
101         RANGE( 0,       5       ),
102         RANGE( 0,       2       ),
103         RANGE( 0,       1       ),
104         RANGE( 0,       0.5     ),
105         RANGE( 0,       0.2     ),
106         RANGE( 0,       0.1     ),
107 }};
108 static comedi_lrange range_ni_E_ai_limited={    8, {
109         RANGE( -10,     10      ),
110         RANGE( -5,      5       ),
111         RANGE( -1,      1       ),
112         RANGE( -0.1,    0.1     ),
113         RANGE( 0,       10      ),
114         RANGE( 0,       5       ),
115         RANGE( 0,       1       ),
116         RANGE( 0,       0.1     ),
117 }};
118 static comedi_lrange range_ni_E_ai_limited14={  14, {
119         RANGE( -10,     10      ),
120         RANGE( -5,      5       ),
121         RANGE( -2,      2       ),
122         RANGE( -1,      1       ),
123         RANGE( -0.5,    0.5     ),
124         RANGE( -0.2,    0.2     ),
125         RANGE( -0.1,    0.1     ),
126         RANGE( 0,       10      ),
127         RANGE( 0,       5       ),
128         RANGE( 0,       2       ),
129         RANGE( 0,       1       ),
130         RANGE( 0,       0.5     ),
131         RANGE( 0,       0.2     ),
132         RANGE( 0,       0.1     ),
133 }};
134 static comedi_lrange range_ni_E_ai_bipolar4={ 4, {
135         RANGE( -10,     10      ),
136         RANGE( -5,      5       ),
137         RANGE( -0.5,    0.5     ),
138         RANGE( -0.05,   0.05    ),
139 }};
140 static comedi_lrange range_ni_E_ai_611x={ 8, {
141         RANGE( -50,     50      ),
142         RANGE( -20,     20      ),
143         RANGE( -10,     10      ),
144         RANGE( -5,      5       ),
145         RANGE( -2,      2       ),
146         RANGE( -1,      1       ),
147         RANGE( -0.5,    0.5     ),
148         RANGE( -0.2,    0.2     ),
149 }};
150 static comedi_lrange range_ni_E_ao_ext = { 4, {
151         RANGE( -10,     10      ),
152         RANGE( 0,       10      ),
153         RANGE_ext( -1,  1       ),
154         RANGE_ext( 0,   1       ),
155 }};
156
157 static comedi_lrange *ni_range_lkup[]={
158         &range_ni_E_ai,
159         &range_ni_E_ai_limited,
160         &range_ni_E_ai_limited14,
161         &range_ni_E_ai_bipolar4,
162         &range_ni_E_ai_611x,
163 };
164
165
166
167 static int ni_dio_insn_config(comedi_device *dev,comedi_subdevice *s,
168         comedi_insn *insn,lsampl_t *data);
169 static int ni_dio_insn_bits(comedi_device *dev,comedi_subdevice *s,
170         comedi_insn *insn,lsampl_t *data);
171
172 static int ni_serial_insn_config(comedi_device *dev,comedi_subdevice *s,
173         comedi_insn *insn,lsampl_t *data);
174 static int ni_serial_hw_readwrite8(comedi_device *dev,comedi_subdevice *s,
175         unsigned char data_out, unsigned char *data_in);
176 static int ni_serial_sw_readwrite8(comedi_device *dev,comedi_subdevice *s,
177         unsigned char data_out, unsigned char *data_in);
178
179 static int ni_calib_insn_read(comedi_device *dev,comedi_subdevice *s,
180         comedi_insn *insn,lsampl_t *data);
181 static int ni_calib_insn_write(comedi_device *dev,comedi_subdevice *s,
182         comedi_insn *insn,lsampl_t *data);
183
184 static int ni_eeprom_insn_read(comedi_device *dev,comedi_subdevice *s,
185         comedi_insn *insn,lsampl_t *data);
186
187 static int ni_pfi_insn_bits(comedi_device *dev,comedi_subdevice *s,
188         comedi_insn *insn,lsampl_t *data);
189 static int ni_pfi_insn_config(comedi_device *dev,comedi_subdevice *s,
190         comedi_insn *insn,lsampl_t *data);
191
192 static void caldac_setup(comedi_device *dev,comedi_subdevice *s);
193 static int ni_read_eeprom(comedi_device *dev,int addr);
194
195 #ifdef DEBUG_STATUS_A
196 static void ni_mio_print_status_a(int status);
197 #else
198 #define ni_mio_print_status_a(a)
199 #endif
200 #ifdef DEBUG_STATUS_B
201 static void ni_mio_print_status_b(int status);
202 #else
203 #define ni_mio_print_status_b(a)
204 #endif
205
206 static int ni_ai_reset(comedi_device *dev,comedi_subdevice *s);
207 #ifndef PCIDMA
208 static void ni_handle_fifo_half_full(comedi_device *dev);
209 static int ni_ao_fifo_half_empty(comedi_device *dev,comedi_subdevice *s);
210 #endif
211 static void ni_handle_fifo_dregs(comedi_device *dev);
212 static int ni_ai_inttrig(comedi_device *dev,comedi_subdevice *s,
213         unsigned int trignum);
214 static void ni_load_channelgain_list(comedi_device *dev,unsigned int n_chan,
215         unsigned int *list);
216 static void shutdown_ai_command( comedi_device *dev );
217
218 static int ni_ao_inttrig(comedi_device *dev,comedi_subdevice *s,
219         unsigned int trignum);
220
221 static int ni_ao_reset(comedi_device *dev,comedi_subdevice *s);
222
223 static int ni_8255_callback(int dir,int port,int data,unsigned long arg);
224
225 static int ni_ns_to_timer(int *nanosec,int round_mode);
226
227
228 /*GPCT function def's*/
229 static int GPCT_G_Watch(comedi_device *dev, int chan);
230
231 static void GPCT_Reset(comedi_device *dev, int chan);
232 static void GPCT_Gen_Cont_Pulse(comedi_device *dev, int chan, unsigned int length);
233 static void GPCT_Gen_Single_Pulse(comedi_device *dev, int chan, unsigned int length);
234 static void GPCT_Period_Meas(comedi_device *dev, int chan);
235 static void GPCT_Pulse_Width_Meas(comedi_device *dev, int chan);
236 static void GPCT_Event_Counting(comedi_device *dev,int chan);
237 static int GPCT_Set_Direction(comedi_device *dev,int chan,int direction);
238 static int GPCT_Set_Gate(comedi_device *dev,int chan ,int gate);
239 static int GPCT_Set_Source(comedi_device *dev,int chan ,int source);
240
241 static int ni_gpct_insn_write(comedi_device *dev,comedi_subdevice *s,
242         comedi_insn *insn,lsampl_t *data);
243 static int ni_gpct_insn_read(comedi_device *dev,comedi_subdevice *s,
244         comedi_insn *insn,lsampl_t *data);
245 static int ni_gpct_insn_config(comedi_device *dev,comedi_subdevice *s,
246         comedi_insn *insn,lsampl_t *data);
247
248 static int init_cs5529(comedi_device *dev);
249 static int cs5529_do_conversion(comedi_device *dev, unsigned short *data);
250 static int cs5529_ai_insn_read(comedi_device *dev,comedi_subdevice *s,comedi_insn *insn,lsampl_t *data);
251 static unsigned int cs5529_config_read(comedi_device *dev, unsigned int reg_select_bits);
252 static void cs5529_config_write(comedi_device *dev, unsigned int value, unsigned int reg_select_bits);
253
254 enum aimodes
255 {
256         AIMODE_NONE = 0,
257         AIMODE_HALF_FULL = 1,
258         AIMODE_SCAN = 2,
259         AIMODE_SAMPLE = 3,
260 };
261
262 #define SERIAL_DISABLED         0
263 #define SERIAL_600NS            600
264 #define SERIAL_1_2US            1200
265 #define SERIAL_10US                     10000
266
267 static const int num_adc_stages_611x = 3;
268
269 static void handle_a_interrupt(comedi_device *dev,unsigned short status,
270         unsigned int m_status);
271 static void handle_b_interrupt(comedi_device *dev,unsigned short status,
272         unsigned int m_status);
273 static void get_last_sample_611x( comedi_device *dev );
274 #ifdef PCIDMA
275 //static void mite_handle_interrupt(comedi_device *dev,unsigned int status);
276 static int ni_ai_drain_dma(comedi_device *dev );
277 #endif
278
279 #define win_out2(data,addr) do{ \
280         win_out((data)>>16, (addr)); \
281         win_out((data)&0xffff, (addr)+1); \
282 }while(0)
283
284
285 #define ao_win_out(data,addr) ni_ao_win_outw(dev,data,addr)
286 static inline void ni_ao_win_outw( comedi_device *dev, uint16_t data, int addr )
287 {
288         unsigned long flags;
289
290         comedi_spin_lock_irqsave(&devpriv->window_lock,flags);
291         ni_writew(addr,AO_Window_Address_611x);
292         ni_writew(data,AO_Window_Data_611x);
293         comedi_spin_unlock_irqrestore(&devpriv->window_lock,flags);
294 }
295
296 static inline void ni_ao_win_outl(comedi_device *dev, uint32_t data, int addr)
297 {
298         unsigned long flags;
299
300         comedi_spin_lock_irqsave(&devpriv->window_lock,flags);
301         ni_writew(addr,AO_Window_Address_611x);
302         ni_writel(data,AO_Window_Data_611x);
303         comedi_spin_unlock_irqrestore(&devpriv->window_lock,flags);
304 }
305
306 static inline unsigned short ni_ao_win_inw( comedi_device *dev, int addr )
307 {
308         unsigned long flags;
309         unsigned short data;
310
311         comedi_spin_lock_irqsave(&devpriv->window_lock,flags);
312         ni_writew(addr, AO_Window_Address_611x);
313         data = ni_readw(AO_Window_Data_611x);
314         comedi_spin_unlock_irqrestore(&devpriv->window_lock,flags);
315         return data;
316 }
317
318 /* ni_set_bits( ) allows different parts of the ni_mio_common driver to
319 * share registers (such as Interrupt_A_Register) without interfering with
320 * each other.
321 *
322 * NOTE: the switch/case statements are optimized out for a constant argument
323 * so this is actually quite fast---  If you must wrap another function around this
324 * make it inline to avoid a large speed penalty.
325 *
326 * value should only be 1 or 0.
327 */
328 static inline void ni_set_bits(comedi_device *dev, int reg, int bits, int value)
329 {
330         unsigned long flags;
331
332         comedi_spin_lock_irqsave( &devpriv->window_lock, flags );
333         switch (reg){
334                 case Interrupt_A_Enable_Register:
335                         if(value)
336                                 devpriv->int_a_enable_reg |= bits;
337                         else
338                                 devpriv->int_a_enable_reg &= ~bits;
339                         comedi_spin_unlock_irqrestore( &devpriv->window_lock, flags );
340                         win_out(devpriv->int_a_enable_reg,Interrupt_A_Enable_Register);
341                         break;
342                 case Interrupt_B_Enable_Register:
343                         if(value)
344                                 devpriv->int_b_enable_reg |= bits;
345                         else
346                                 devpriv->int_b_enable_reg &= ~bits;
347                         comedi_spin_unlock_irqrestore( &devpriv->window_lock, flags );
348                         win_out(devpriv->int_b_enable_reg,Interrupt_B_Enable_Register);
349                         break;
350                 case IO_Bidirection_Pin_Register:
351                         if(value)
352                                 devpriv->io_bidirection_pin_reg |= bits;
353                         else
354                                 devpriv->io_bidirection_pin_reg &= ~bits;
355                         comedi_spin_unlock_irqrestore( &devpriv->window_lock, flags );
356                         win_out(devpriv->io_bidirection_pin_reg,IO_Bidirection_Pin_Register);
357                         break;
358                 default:
359                         printk("Warning ni_set_bits() called with invalid arguments\n");
360                         printk("reg is %d\n",reg);
361                         comedi_spin_unlock_irqrestore( &devpriv->window_lock, flags );
362                         break;
363         }
364 }
365
366
367 static irqreturn_t ni_E_interrupt(int irq,void *d,struct pt_regs * regs)
368 {
369         comedi_device *dev=d;
370         unsigned short a_status;
371         unsigned short b_status;
372         unsigned int m0_status;
373         unsigned int m1_status;
374         unsigned long flags;
375 #ifdef PCIDMA
376         struct mite_struct *mite = devpriv->mite;
377 #endif
378
379         if(dev->attached == 0) return IRQ_NONE;
380         // lock to avoid race with comedi_poll
381         comedi_spin_lock_irqsave(&dev->spinlock, flags);
382         a_status=win_in(AI_Status_1_Register);
383         b_status=win_in(AO_Status_1_Register);
384 #ifdef PCIDMA
385         m0_status=readl(mite->mite_io_addr + MITE_CHSR(AI_DMA_CHAN));
386         m1_status=readl(mite->mite_io_addr + MITE_CHSR(AO_DMA_CHAN));
387 #else
388         m0_status = 0;
389         m1_status = 0;
390 #endif
391
392         if(a_status&Interrupt_A_St || m0_status & CHSR_INT )
393                 handle_a_interrupt(dev, a_status, m0_status);
394         if(b_status&Interrupt_B_St || m1_status & CHSR_INT )
395                 handle_b_interrupt(dev, b_status, m1_status);
396         comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
397         return IRQ_HANDLED;
398 }
399
400 #ifdef PCIDMA
401 static void ni_sync_ai_dma(struct mite_struct *mite, comedi_device *dev)
402 {
403         int count;
404         comedi_subdevice *s = dev->subdevices + 0;
405         comedi_async *async = s->async;
406         unsigned int nbytes, old_alloc_count;
407         unsigned int bytes_per_scan = 2 * async->cmd.chanlist_len;
408
409         old_alloc_count = async->buf_write_alloc_count;
410         // write alloc as much as we can
411         comedi_buf_write_alloc(s->async, s->async->prealloc_bufsz);
412
413         nbytes = mite_bytes_transferred(mite, AI_DMA_CHAN);
414         rmb();
415         /* We use mite_bytes_read() for the overrun check
416          * because it returns an upper bound, and mite_bytes_transferred
417          * returns a lower bound on the number of bytes actually
418          * transferred */
419         if( (int)(mite_bytes_read(mite, AI_DMA_CHAN) - old_alloc_count) > 0 ){
420                 printk("ni_mio_common: DMA overwrite of free area\n");
421                 ni_ai_reset(dev,s);
422                 async->events |= COMEDI_CB_OVERFLOW;
423                 return;
424         }
425
426         count = nbytes - async->buf_write_count;
427         if( count <= 0 ){
428                 /* it's possible count will be negative due to
429                  * conservative value returned by mite_bytes_transferred */
430                 return;
431         }
432         comedi_buf_write_free(async, count);
433
434         async->scan_progress += count;
435         if( async->scan_progress >= bytes_per_scan )
436         {
437                 async->scan_progress %= bytes_per_scan;
438                 async->events |= COMEDI_CB_EOS;
439         }
440         async->events |= COMEDI_CB_BLOCK;
441 }
442
443 static void mite_handle_b_linkc(struct mite_struct *mite, comedi_device *dev)
444 {
445         int count;
446         comedi_subdevice *s = dev->subdevices + 1;
447         comedi_async *async = s->async;
448         unsigned int nbytes, new_write_count;
449
450         writel(CHOR_CLRLC, mite->mite_io_addr + MITE_CHOR(AO_DMA_CHAN));
451
452         new_write_count = async->buf_write_count;
453
454         nbytes = mite_bytes_read(mite, AO_DMA_CHAN);
455         if( async->cmd.stop_src == TRIG_COUNT &&
456                 (int) (nbytes - async->cmd.stop_arg * sizeof( sampl_t ) ) > 0 )
457                 nbytes = async->cmd.stop_arg * sizeof( sampl_t );
458         if( (int)(nbytes - devpriv->last_buf_write_count) > 0 ){
459                 rt_printk("ni_mio_common: DMA underrun\n");
460                 ni_ao_reset(dev,s);
461                 async->events |= COMEDI_CB_OVERFLOW;
462                 return;
463         }
464
465         devpriv->last_buf_write_count = new_write_count;
466
467         count = nbytes - async->buf_read_count;
468         if( count < 0 ){
469                 rt_printk("ni_mio_common: BUG: negative ao count\n");
470                 count = 0;
471         }
472         comedi_buf_read_free(async, count);
473
474         async->events |= COMEDI_CB_BLOCK;
475 }
476
477 static int ni_ao_wait_for_dma_load( comedi_device *dev )
478 {
479         static const int timeout = 10000;
480         int i;
481
482         for(i = 0; i < timeout; i++)
483         {
484                 unsigned short b_status;
485
486                 b_status = win_in( AO_Status_1_Register );
487                 if( b_status & AO_FIFO_Half_Full_St )
488                         break;
489                 /* if we poll too often, the pci bus activity seems
490                  to slow the dma transfer down */
491                 comedi_udelay(10);
492         }
493         if( i == timeout )
494         {
495                 comedi_error(dev, "timed out waiting for dma load");
496                 return -EPIPE;
497         }
498         return 0;
499 }
500
501 #endif //PCIDMA
502 static void ni_handle_eos(comedi_device *dev, comedi_subdevice *s)
503 {
504         if(devpriv->aimode == AIMODE_SCAN)
505         {
506 #ifdef PCIDMA
507                 static const int timeout = 10;
508                 int i;
509
510                 for(i = 0; i < timeout; i++)
511                 {
512                         ni_sync_ai_dma(devpriv->mite, dev);
513                         if((s->async->events & COMEDI_CB_EOS)) break;
514                         comedi_udelay(1);
515                 }
516 #else
517                 ni_handle_fifo_dregs(dev);
518                 s->async->events |= COMEDI_CB_EOS;
519 #endif
520         }
521         /* handle special case of single scan using AI_End_On_End_Of_Scan */
522         if((devpriv->ai_cmd2 & AI_End_On_End_Of_Scan)){
523                 shutdown_ai_command( dev );
524                 ni_ai_reset(dev, s);
525         }
526 }
527
528 static void shutdown_ai_command( comedi_device *dev )
529 {
530         comedi_subdevice *s = dev->subdevices + 0;
531
532 #ifdef PCIDMA
533         ni_ai_drain_dma( dev );
534         mite_dma_disarm(devpriv->mite, AI_DMA_CHAN);
535 #endif
536         ni_handle_fifo_dregs(dev);
537         get_last_sample_611x(dev);
538
539         ni_set_bits(dev, Interrupt_A_Enable_Register,
540                 AI_SC_TC_Interrupt_Enable | AI_START1_Interrupt_Enable|
541                 AI_START2_Interrupt_Enable| AI_START_Interrupt_Enable|
542                 AI_STOP_Interrupt_Enable| AI_Error_Interrupt_Enable|
543                 AI_FIFO_Interrupt_Enable,0);
544
545         s->async->events |= COMEDI_CB_EOA;
546 }
547
548 static void handle_a_interrupt(comedi_device *dev,unsigned short status,
549         unsigned int m_status)
550 {
551         comedi_subdevice *s=dev->subdevices+0;
552         unsigned short ack=0;
553
554         s->async->events = 0;
555
556 #ifdef DEBUG_INTERRUPT
557         rt_printk("ni_mio_common: interrupt: a_status=%04x m0_status=%08x\n",
558                 status, m_status);
559         ni_mio_print_status_a(status);
560 #endif
561
562
563 #ifdef PCIDMA
564         /* Currently, mite.c requires us to handle LINKC and DONE */
565         if(m_status & CHSR_LINKC){
566                 writel(CHOR_CLRLC, devpriv->mite->mite_io_addr + MITE_CHOR(AI_DMA_CHAN));
567                 ni_sync_ai_dma(devpriv->mite, dev);
568         }
569
570         if(m_status & CHSR_DONE){
571                 writel(CHOR_CLRDONE, devpriv->mite->mite_io_addr + MITE_CHOR(AI_DMA_CHAN));
572         }
573
574         if(m_status & ~(CHSR_INT | CHSR_LINKC | CHSR_DONE | CHSR_MRDY | CHSR_DRDY | CHSR_DRQ1 | CHSR_DRQ0 | CHSR_ERROR | CHSR_SABORT | CHSR_XFERR | CHSR_LxERR_mask)){
575                 printk("unknown mite interrupt, ack! (m_status=%08x)\n", m_status);
576                 //mite_print_chsr(m_status);
577                 mite_dma_disarm(devpriv->mite, AI_DMA_CHAN );
578                 writel(CHOR_DMARESET, devpriv->mite->mite_io_addr + MITE_CHOR(AI_DMA_CHAN));
579                 //disable_irq(dev->irq);
580         }
581 #endif
582
583         /* test for all uncommon interrupt events at the same time */
584         if(status&(AI_Overrun_St|AI_Overflow_St|AI_SC_TC_Error_St|AI_SC_TC_St|AI_START1_St)){
585                 if(status==0xffff){
586                         rt_printk("ni_mio_common: a_status=0xffff.  Card removed?\n");
587                         /* we probably aren't even running a command now,
588                          * so it's a good idea to be careful. */
589                         if(s->subdev_flags&SDF_RUNNING){
590                                 s->async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
591                                 //comedi_event(dev,s,s->async->events);
592                         }
593                         return;
594                 }
595                 if(status&(AI_Overrun_St|AI_Overflow_St|AI_SC_TC_Error_St)){
596                         rt_printk("ni_mio_common: ai error a_status=%04x\n",
597                                 status);
598                         ni_mio_print_status_a(status);
599
600                         ni_ai_reset(dev,dev->subdevices);
601
602
603                         shutdown_ai_command( dev );
604
605                         s->async->events |= COMEDI_CB_ERROR;
606                         if(status & (AI_Overrun_St | AI_Overflow_St))
607                                 s->async->events |= COMEDI_CB_OVERFLOW;
608                         
609                         comedi_event(dev,s,s->async->events);
610
611                         return;
612                 }
613                 if(status&AI_SC_TC_St){
614 #ifdef DEBUG_INTERRUPT
615                         rt_printk("ni_mio_common: SC_TC interrupt\n");
616 #endif
617                         if(!devpriv->ai_continuous){
618                                 shutdown_ai_command( dev );
619                         }
620                         ack|=AI_SC_TC_Interrupt_Ack;
621                 }
622                 if(status&AI_START1_St){
623                         ack|=AI_START1_Interrupt_Ack;
624                 }
625         }
626 #ifndef PCIDMA
627         if(status&AI_FIFO_Half_Full_St){
628                 int i;
629                 static const int timeout = 10;
630                 /* pcmcia cards (at least 6036) seem to stop producing interrupts if we 
631                  *fail to get the fifo less than half full, so loop to be sure.*/
632                 for(i = 0; i < timeout; ++i)
633                 {
634                         ni_handle_fifo_half_full(dev);
635                         if((win_in(AI_Status_1_Register) & AI_FIFO_Half_Full_St) == 0)
636                                 break;
637                 }
638         }
639 #endif // !PCIDMA
640
641         if( (status & AI_STOP_St) ){
642                 ni_handle_eos(dev, s);
643                 /* we need to ack the START, also */
644                 ack |= AI_STOP_Interrupt_Ack|AI_START_Interrupt_Ack;
645         }
646 #if 0
647         if(devpriv->aimode==AIMODE_SAMPLE){
648                 ni_handle_fifo_dregs(dev);
649
650                 //s->async->events |= COMEDI_CB_SAMPLE;
651         }
652 #endif
653         if(ack) win_out(ack,Interrupt_A_Ack_Register);
654
655         comedi_event(dev,s,s->async->events);
656
657 #ifdef DEBUG_INTERRUPT
658         status=win_in(AI_Status_1_Register);
659         if(status&Interrupt_A_St){
660                 printk("handle_a_interrupt: didn't clear interrupt? status=0x%x\n", status);
661         }
662 #endif
663 }
664
665 static void handle_b_interrupt(comedi_device *dev,unsigned short b_status, unsigned int m_status)
666 {
667         comedi_subdevice *s=dev->subdevices+1;
668         //unsigned short ack=0;
669 #ifdef DEBUG_INTERRUPT
670         rt_printk("ni_mio_common: interrupt: b_status=%04x m1_status=%08x\n",
671                 b_status,m_status);
672         ni_mio_print_status_b(b_status);
673 #endif
674
675
676 #ifdef PCIDMA
677         /* Currently, mite.c requires us to handle LINKC and DONE */
678         if(m_status & CHSR_LINKC){
679                 mite_handle_b_linkc(devpriv->mite, dev);
680         }
681
682         if(m_status & CHSR_DONE){
683                 writel(CHOR_CLRDONE, devpriv->mite->mite_io_addr + MITE_CHOR(AO_DMA_CHAN));
684         }
685
686         if(m_status & ~(CHSR_INT | CHSR_LINKC | CHSR_DONE | CHSR_MRDY | CHSR_DRDY | CHSR_DRQ1 | CHSR_DRQ0 | CHSR_ERROR | CHSR_SABORT | CHSR_XFERR | CHSR_LxERR_mask)){
687                 printk("unknown mite interrupt, ack! (m_status=%08x)\n", m_status);
688                 //mite_print_chsr(m_status);
689                 mite_dma_disarm(devpriv->mite, AO_DMA_CHAN );
690                 writel(CHOR_DMARESET, devpriv->mite->mite_io_addr + MITE_CHOR(AO_DMA_CHAN));
691        }
692 #endif
693
694         if(b_status==0xffff)return;
695         if(b_status&AO_Overrun_St){
696                 rt_printk("ni_mio_common: AO FIFO underrun status=0x%04x status2=0x%04x\n",b_status,win_in(AO_Status_2_Register));
697                 ni_ao_reset(dev,s);
698                 s->async->events |= COMEDI_CB_OVERFLOW;
699         }
700
701         if(b_status&AO_BC_TC_St){
702                 MDPRINTK("ni_mio_common: AO BC_TC status=0x%04x status2=0x%04x\n",b_status,win_in(AO_Status_2_Register));
703                 ni_ao_reset(dev,s);
704                 s->async->events |= COMEDI_CB_EOA;
705         }
706
707 #ifndef PCIDMA
708         if(b_status&AO_FIFO_Request_St){
709                 int ret;
710
711                 ret = ni_ao_fifo_half_empty(dev,s);
712                 if(!ret){
713                         rt_printk("ni_mio_common: AO buffer underrun\n");
714                         ni_set_bits(dev, Interrupt_B_Enable_Register,
715                                 AO_FIFO_Interrupt_Enable|AO_Error_Interrupt_Enable, 0);
716                         s->async->events |= COMEDI_CB_OVERFLOW;
717                 }
718         }
719 #endif
720
721         b_status=win_in(AO_Status_1_Register);
722         if(b_status&Interrupt_B_St){
723                 if(b_status&AO_FIFO_Request_St){
724                         rt_printk("ni_mio_common: AO buffer underrun\n");
725                 }
726                 rt_printk("Ack! didn't clear AO interrupt. b_status=0x%04x\n",b_status);
727                 ni_set_bits(dev,Interrupt_B_Enable_Register,~0,0);
728                 ni_ao_reset(dev,s);
729                 s->async->events |= COMEDI_CB_OVERFLOW;
730         }
731
732         comedi_event(dev,s,s->async->events);
733 }
734
735 #ifdef DEBUG_STATUS_A
736 static char *status_a_strings[]={
737         "passthru0","fifo","G0_gate","G0_TC",
738         "stop","start","sc_tc","start1",
739         "start2","sc_tc_error","overflow","overrun",
740         "fifo_empty","fifo_half_full","fifo_full","interrupt_a"
741 };
742
743 static void ni_mio_print_status_a(int status)
744 {
745         int i;
746
747         rt_printk("A status:");
748         for(i=15;i>=0;i--){
749                 if(status&(1<<i)){
750                         rt_printk(" %s",status_a_strings[i]);
751                 }
752         }
753         rt_printk("\n");
754 }
755 #endif
756
757 #ifdef DEBUG_STATUS_B
758 static char *status_b_strings[]={
759         "passthru1","fifo","G1_gate","G1_TC",
760         "UI2_TC","UPDATE","UC_TC","BC_TC",
761         "start1","overrun","start","bc_tc_error",
762         "fifo_empty","fifo_half_full","fifo_full","interrupt_b"
763 };
764
765 static void ni_mio_print_status_b(int status)
766 {
767         int i;
768
769         rt_printk("B status:");
770         for(i=15;i>=0;i--){
771                 if(status&(1<<i)){
772                         rt_printk(" %s",status_b_strings[i]);
773                 }
774         }
775         rt_printk("\n");
776 }
777 #endif
778
779 #ifndef PCIDMA
780
781 static void ni_ao_fifo_load(comedi_device *dev,comedi_subdevice *s, int n)
782 {
783         comedi_async *async = s->async;
784         comedi_cmd *cmd = &async->cmd;
785         int chan;
786         int i;
787         sampl_t d;
788         u32 packed_data;
789         int range;
790         int err = 1;
791
792         chan = async->cur_chan;
793         for(i=0;i<n;i++){
794                 err &= comedi_buf_get(async, &d);
795                 if(err == 0) break;
796
797                 range = CR_RANGE(cmd->chanlist[chan]);
798
799                 if(boardtype.reg_type & ni_reg_6xxx_mask)
800                 {
801                         packed_data = d & 0xffff;
802                         /* 6711 only has 16 bit wide ao fifo */
803                         if(boardtype.reg_type != ni_reg_6711)
804                         {
805                                 err &= comedi_buf_get(async, &d);
806                                 if(err == 0) break;
807                                 chan++;
808                                 i++;
809                                 packed_data |= ( d << 16 ) & 0xffff0000;
810                         }
811                         ni_writel( packed_data, DAC_FIFO_Data_611x );
812                 }else{
813                         ni_writew(d, DAC_FIFO_Data);
814                 }
815                 chan++;
816                 chan %= cmd->chanlist_len;
817         }
818         async->cur_chan = chan;
819         if(err==0){
820                 async->events |= COMEDI_CB_OVERFLOW;
821         }
822 }
823
824 /*
825  *  There's a small problem if the FIFO gets really low and we
826  *  don't have the data to fill it.  Basically, if after we fill
827  *  the FIFO with all the data available, the FIFO is _still_
828  *  less than half full, we never clear the interrupt.  If the
829  *  IRQ is in edge mode, we never get another interrupt, because
830  *  this one wasn't cleared.  If in level mode, we get flooded
831  *  with interrupts that we can't fulfill, because nothing ever
832  *  gets put into the buffer.
833  *
834  *  This kind of situation is recoverable, but it is easier to
835  *  just pretend we had a FIFO underrun, since there is a good
836  *  chance it will happen anyway.  This is _not_ the case for
837  *  RT code, as RT code might purposely be running close to the
838  *  metal.  Needs to be fixed eventually.
839  */
840 static int ni_ao_fifo_half_empty(comedi_device *dev,comedi_subdevice *s)
841 {
842         int n;
843
844         n = comedi_buf_read_n_available(s);
845         if(n==0){
846                 s->async->events |= COMEDI_CB_OVERFLOW;
847                 return 0;
848         }
849
850         n /= sizeof(sampl_t);
851         if(n > boardtype.ao_fifo_depth / 2)
852                 n = boardtype.ao_fifo_depth / 2;
853
854         ni_ao_fifo_load(dev,s,n);
855
856         s->async->events |= COMEDI_CB_BLOCK;
857
858         return 1;
859 }
860
861 static int ni_ao_prep_fifo(comedi_device *dev,comedi_subdevice *s)
862 {
863         int n;
864
865         /* reset fifo */
866         win_out(0,DAC_FIFO_Clear);
867         if(boardtype.reg_type & ni_reg_6xxx_mask)
868                 ni_ao_win_outl(dev, 0x6, AO_FIFO_Offset_Load_611x);
869
870         /* load some data */
871         n = comedi_buf_read_n_available(s);
872         if(n==0)return 0;
873
874         n /= sizeof(sampl_t);
875         if(n > boardtype.ao_fifo_depth)
876                 n = boardtype.ao_fifo_depth;
877
878         ni_ao_fifo_load(dev,s,n);
879
880         return n;
881 }
882
883 static void ni_ai_fifo_read(comedi_device *dev,comedi_subdevice *s,
884         int n)
885 {
886         comedi_async *async = s->async;
887         int i;
888
889         if(boardtype.reg_type == ni_reg_611x){
890                 sampl_t data[2];
891                 u32 dl;
892
893                 for( i = 0; i < n / 2; i++ ){
894                         dl=ni_readl(ADC_FIFO_Data_611x);
895                         /* This may get the hi/lo data in the wrong order */
896                         data[0] = (dl>>16) & 0xffff;
897                         data[1] = dl & 0xffff;
898                         cfc_write_array_to_buffer(s, data, sizeof(data));
899                 }
900                 /* Check if there's a single sample stuck in the FIFO */
901                 if( n % 2){
902                         dl=ni_readl(ADC_FIFO_Data_611x);
903                         data[0] = dl & 0xffff;
904                         cfc_write_to_buffer(s, data[0]);
905                 }
906         }else{
907                 if( n > sizeof(devpriv->ai_fifo_buffer) / sizeof(devpriv->ai_fifo_buffer[0]))
908                 {
909                         comedi_error( dev, "bug! ai_fifo_buffer too small" );
910                         async->events |= COMEDI_CB_ERROR;
911                         return;
912                 }
913                 for(i = 0; i < n; i++){
914                         devpriv->ai_fifo_buffer[i] = ni_readw(ADC_FIFO_Data_Register);
915                 }
916                 cfc_write_array_to_buffer( s, devpriv->ai_fifo_buffer,
917                         n * sizeof(devpriv->ai_fifo_buffer[0]) );
918         }
919 }
920
921 static void ni_handle_fifo_half_full(comedi_device *dev)
922 {
923         int n;
924         comedi_subdevice *s=dev->subdevices+0;
925
926         n=boardtype.ai_fifo_depth/2;
927
928         ni_ai_fifo_read(dev,s,n);
929 }
930 #endif
931
932 #ifdef PCIDMA
933 static int ni_ai_drain_dma(comedi_device *dev )
934 {
935         struct mite_struct *mite = devpriv->mite;
936         int i;
937         static const int timeout = 10000;
938
939         for( i = 0; i < timeout; i++ )
940         {
941                 if((win_in(AI_Status_1_Register) & AI_FIFO_Empty_St) &&
942                         mite_bytes_in_transit(mite, AI_DMA_CHAN) == 0)
943                         break;
944                 comedi_udelay(2);
945         }
946         if(i == timeout)
947         {
948                 rt_printk("ni_mio_common: wait for dma drain timed out\n");
949                 rt_printk("mite_bytes_in_transit=%i, AI_Status1_Register=0x%x\n",
950                         mite_bytes_in_transit(mite, AI_DMA_CHAN), win_in(AI_Status_1_Register));
951                 return -1;
952         }
953
954         ni_sync_ai_dma( mite, dev );
955
956         return 0;
957 }
958 #endif
959 /*
960    Empties the AI fifo
961 */
962 static void ni_handle_fifo_dregs(comedi_device *dev)
963 {
964         comedi_subdevice *s=dev->subdevices+0;
965         sampl_t data[2];
966         u32 dl;
967         short fifo_empty;
968         int i;
969
970         if(boardtype.reg_type == ni_reg_611x){
971                 while((win_in(AI_Status_1_Register)&AI_FIFO_Empty_St) == 0){
972                         dl=ni_readl(ADC_FIFO_Data_611x);
973
974                         /* This may get the hi/lo data in the wrong order */
975                         data[0] = (dl>>16);
976                         data[1] = (dl&0xffff);
977                         cfc_write_array_to_buffer(s, data, sizeof(data));
978                 }
979         }else{
980                 fifo_empty = win_in(AI_Status_1_Register) & AI_FIFO_Empty_St;
981                 while(fifo_empty == 0)
982                 {
983                         for(i = 0; i < sizeof(devpriv->ai_fifo_buffer) / sizeof(devpriv->ai_fifo_buffer[0]); i++)
984                         {
985                                 fifo_empty = win_in(AI_Status_1_Register) & AI_FIFO_Empty_St;
986                                 if(fifo_empty) break;
987                                 devpriv->ai_fifo_buffer[i] = ni_readw(ADC_FIFO_Data_Register);
988                         }
989                         cfc_write_array_to_buffer( s, devpriv->ai_fifo_buffer,
990                                 i * sizeof(devpriv->ai_fifo_buffer[0]) );
991                 }
992         }
993 }
994
995 static void get_last_sample_611x( comedi_device *dev )
996 {
997         comedi_subdevice *s=dev->subdevices+0;
998         sampl_t data;
999         u32 dl;
1000
1001         if(boardtype.reg_type != ni_reg_611x) return;
1002
1003         /* Check if there's a single sample stuck in the FIFO */
1004         if(ni_readb(XXX_Status)&0x80){
1005                 dl=ni_readl(ADC_FIFO_Data_611x);
1006                 data = (dl&0xffff);
1007                 cfc_write_to_buffer(s, data);
1008         }
1009 }
1010
1011 static void ni_ai_munge(comedi_device *dev, comedi_subdevice *s,
1012         void *data, unsigned int num_bytes, unsigned int chan_index )
1013 {
1014         comedi_async *async = s->async;
1015         unsigned int i;
1016         unsigned int length = num_bytes / sizeof( sampl_t );
1017         sampl_t *array = data;
1018
1019         for(i = 0; i < length; i++)
1020         {
1021 #ifdef PCIDMA
1022                 array[i] = le16_to_cpu(array[i]);
1023 #endif
1024                 array[i] += devpriv->ai_offset[ chan_index ];
1025                 chan_index++;
1026                 chan_index %= async->cmd.chanlist_len;
1027         }
1028 }
1029
1030 #ifdef PCIDMA
1031
1032 static void ni_ai_setup_MITE_dma(comedi_device *dev,comedi_cmd *cmd)
1033 {
1034         struct mite_struct *mite = devpriv->mite;
1035         struct mite_channel *mite_chan = &mite->channels[ AI_DMA_CHAN ];
1036         comedi_subdevice *s = dev->subdevices + 0;
1037
1038         /* write alloc the entire buffer */
1039         comedi_buf_write_alloc(s->async, s->async->prealloc_bufsz);
1040
1041         mite_chan->current_link = 0;
1042         mite_chan->dir = COMEDI_INPUT;
1043         if(boardtype.reg_type == ni_reg_611x)
1044                 mite_prep_dma(mite, AI_DMA_CHAN, 32, 16);
1045         else
1046                 mite_prep_dma(mite, AI_DMA_CHAN, 16, 16);
1047
1048         /*start the MITE*/
1049         mite_dma_arm(mite, AI_DMA_CHAN);
1050 }
1051
1052 static void ni_ao_setup_MITE_dma(comedi_device *dev,comedi_cmd *cmd)
1053 {
1054         struct mite_struct *mite = devpriv->mite;
1055         struct mite_channel *mite_chan = &mite->channels[ AO_DMA_CHAN ];
1056         comedi_subdevice *s = dev->subdevices + 1;
1057
1058         devpriv->last_buf_write_count = s->async->buf_write_count;
1059
1060         mite_chan->current_link = 0;
1061         mite_chan->dir = COMEDI_OUTPUT;
1062         if(boardtype.reg_type & (ni_reg_611x | ni_reg_6713))
1063                 mite_prep_dma(mite, AO_DMA_CHAN, 32, 32);
1064         else
1065                 mite_prep_dma(mite, AO_DMA_CHAN, 16, 16);
1066
1067         /*start the MITE*/
1068         mite_dma_arm(mite, AO_DMA_CHAN);
1069 }
1070
1071 #endif // PCIDMA
1072
1073 /*
1074    used for both cancel ioctl and board initialization
1075
1076    this is pretty harsh for a cancel, but it works...
1077  */
1078
1079 static int ni_ai_reset(comedi_device *dev,comedi_subdevice *s)
1080 {
1081 #ifdef PCIDMA
1082         mite_dma_disarm(devpriv->mite, AI_DMA_CHAN);
1083 #endif
1084         /* ai configuration */
1085         win_out(AI_Configuration_Start | AI_Reset, Joint_Reset_Register);
1086
1087         ni_set_bits(dev, Interrupt_A_Enable_Register,
1088                 AI_SC_TC_Interrupt_Enable | AI_START1_Interrupt_Enable|
1089                 AI_START2_Interrupt_Enable| AI_START_Interrupt_Enable|
1090                 AI_STOP_Interrupt_Enable|   AI_Error_Interrupt_Enable|
1091                 AI_FIFO_Interrupt_Enable,0);
1092
1093         win_out(1,ADC_FIFO_Clear);
1094
1095         ni_writeb(0, Misc_Command);
1096
1097         win_out(AI_Disarm, AI_Command_1_Register); /* reset pulses */
1098         win_out(AI_Start_Stop | AI_Mode_1_Reserved /*| AI_Trigger_Once */,
1099                 AI_Mode_1_Register);
1100         win_out(0x0000,AI_Mode_2_Register);
1101         /* generate FIFO interrupts on non-empty */
1102         win_out((0<<6)|0x0000,AI_Mode_3_Register);
1103         if(boardtype.reg_type == ni_reg_normal){
1104                 win_out(AI_SHIFTIN_Pulse_Width |
1105                         AI_SOC_Polarity |
1106                         AI_CONVERT_Pulse_Width |
1107                         AI_LOCALMUX_CLK_Pulse_Width, AI_Personal_Register);
1108                 win_out(AI_SCAN_IN_PROG_Output_Select(3) |
1109                         AI_EXTMUX_CLK_Output_Select(0) |
1110                         AI_LOCALMUX_CLK_Output_Select(2) |
1111                         AI_SC_TC_Output_Select(3) |
1112                         AI_CONVERT_Output_Select(2),AI_Output_Control_Register);
1113         }else{/* 611x boards */
1114                 win_out(AI_SHIFTIN_Pulse_Width |
1115                         AI_SOC_Polarity |
1116                         AI_LOCALMUX_CLK_Pulse_Width, AI_Personal_Register);
1117                 win_out(AI_SCAN_IN_PROG_Output_Select(3) |
1118                         AI_EXTMUX_CLK_Output_Select(0) |
1119                         AI_LOCALMUX_CLK_Output_Select(2) |
1120                         AI_SC_TC_Output_Select(3) |
1121                         AI_CONVERT_Output_Select(3),AI_Output_Control_Register);
1122         }
1123
1124         /* the following registers should not be changed, because there
1125          * are no backup registers in devpriv.  If you want to change
1126          * any of these, add a backup register and other appropriate code:
1127          *      AI_Mode_1_Register
1128          *      AI_Mode_3_Register
1129          *      AI_Personal_Register
1130          *      AI_Output_Control_Register
1131         */
1132         win_out(AI_SC_TC_Error_Confirm | AI_START_Interrupt_Ack |
1133                 AI_START2_Interrupt_Ack | AI_START1_Interrupt_Ack |
1134                 AI_SC_TC_Interrupt_Ack | AI_Error_Interrupt_Ack |
1135                 AI_STOP_Interrupt_Ack, Interrupt_A_Ack_Register); /* clear interrupts */
1136
1137         win_out(AI_Configuration_End,Joint_Reset_Register);
1138
1139         return 0;
1140 }
1141
1142 static int ni_ai_poll(comedi_device *dev,comedi_subdevice *s)
1143 {
1144         unsigned long flags = 0;
1145         int count;
1146
1147         // lock to avoid race with interrupt handler
1148         if(in_interrupt() == 0)
1149                 comedi_spin_lock_irqsave(&dev->spinlock, flags);
1150 #ifndef PCIDMA
1151         ni_handle_fifo_dregs(dev);
1152 #else
1153         ni_sync_ai_dma(devpriv->mite, dev);
1154 #endif
1155         count = s->async->buf_write_count - s->async->buf_read_count;
1156         if(in_interrupt() == 0)
1157                 comedi_spin_unlock_irqrestore(&dev->spinlock, flags);
1158
1159         return count;
1160 }
1161
1162
1163 static int ni_ai_insn_read(comedi_device *dev,comedi_subdevice *s,comedi_insn *insn,lsampl_t *data)
1164 {
1165         int i,n;
1166         unsigned int mask;
1167         unsigned short signbits;
1168         unsigned short d;
1169
1170         ni_load_channelgain_list(dev,1,&insn->chanspec);
1171
1172         win_out(1,ADC_FIFO_Clear);
1173
1174         mask=(1<<boardtype.adbits)-1;
1175         signbits=devpriv->ai_offset[0];
1176         if(boardtype.reg_type == ni_reg_611x){
1177                 for(n=0; n < num_adc_stages_611x; n++){
1178                         win_out(AI_CONVERT_Pulse, AI_Command_1_Register);
1179                         comedi_udelay(1);
1180                 }
1181                 for(n=0; n<insn->n; n++){
1182                         win_out(AI_CONVERT_Pulse, AI_Command_1_Register);
1183                         /* The 611x has screwy 32-bit FIFOs. */
1184                         d = 0;
1185                         for(i=0; i<NI_TIMEOUT; i++){
1186                                 if(ni_readb(XXX_Status)&0x80)
1187                                 {
1188                                         d = ( ni_readl(ADC_FIFO_Data_611x) >> 16 ) & 0xffff;
1189                                         break;
1190                                 }
1191                                 if(!(win_in(AI_Status_1_Register)&AI_FIFO_Empty_St))
1192                                 {
1193                                         d = ni_readl(ADC_FIFO_Data_611x) & 0xffff;
1194                                         break;
1195                                 }
1196                         }
1197                         if(i==NI_TIMEOUT){
1198                                 rt_printk("ni_mio_common: timeout in 611x ni_ai_insn_read\n");
1199                                 return -ETIME;
1200                         }
1201                         d += signbits; /* subtle: needs to be short addition */
1202                         data[ n ] = d;
1203                 }
1204         }else{
1205                 for(n=0;n<insn->n;n++){
1206                         win_out(AI_CONVERT_Pulse, AI_Command_1_Register);
1207                         for(i=0;i<NI_TIMEOUT;i++){
1208                                 if(!(win_in(AI_Status_1_Register)&AI_FIFO_Empty_St))
1209                                         break;
1210                         }
1211                         if(i==NI_TIMEOUT){
1212                                 rt_printk("ni_mio_common: timeout in ni_ai_insn_read\n");
1213                                 return -ETIME;
1214                         }
1215                         d = ni_readw(ADC_FIFO_Data_Register);
1216                         d += signbits; /* subtle: needs to be short addition */
1217                         data[n] = d;
1218                 }
1219         }
1220         return insn->n;
1221 }
1222
1223 /*
1224  * Notes on the 6110 and 6111:
1225  * These boards a slightly different than the rest of the series, since
1226  * they have multiple A/D converters.
1227  * From the driver side, the configuration memory is a
1228  * little different.
1229  * Configuration Memory Low:
1230  *   bits 15-9: same
1231  *   bit 8: unipolar/bipolar (should be 0 for bipolar)
1232  *   bits 0-3: gain.  This is 4 bits instead of 3 for the other boards
1233  *       1001 gain=0.1 (+/- 50)
1234  *       1010 0.2
1235  *       1011 0.1
1236  *       0001 1
1237  *       0010 2
1238  *       0011 5
1239  *       0100 10
1240  *       0101 20
1241  *       0110 50
1242  * Configuration Memory High:
1243  *   bits 12-14: Channel Type
1244  *       001 for differential
1245  *       000 for calibration
1246  *   bit 11: coupling  (this is not currently handled)
1247  *       1 AC coupling
1248  *       0 DC coupling
1249  *   bits 0-2: channel
1250  *       valid channels are 0-3
1251  */
1252 static void ni_load_channelgain_list(comedi_device *dev,unsigned int n_chan,
1253         unsigned int *list)
1254 {
1255         unsigned int chan,range,aref;
1256         unsigned int i;
1257         unsigned int hi,lo;
1258         unsigned short offset;
1259         unsigned int dither;
1260
1261         if(n_chan == 1 && boardtype.reg_type == ni_reg_normal){
1262                 if(devpriv->changain_state && devpriv->changain_spec==list[0]){
1263                         // ready to go.
1264                         return;
1265                 }
1266                 devpriv->changain_state=1;
1267                 devpriv->changain_spec=list[0];
1268         }else{
1269                 devpriv->changain_state=0;
1270         }
1271
1272         win_out(1,Configuration_Memory_Clear);
1273
1274         offset=1<<(boardtype.adbits-1);
1275         for(i=0;i<n_chan;i++){
1276                 if(list[i]&CR_ALT_SOURCE){
1277                         chan=devpriv->ai_calib_source;
1278                 }else{
1279                         chan=CR_CHAN(list[i]);
1280                 }
1281                 aref=CR_AREF(list[i]);
1282                 range=CR_RANGE(list[i]);
1283                 dither=((list[i]&CR_ALT_FILTER)!=0);
1284
1285                 /* fix the external/internal range differences */
1286                 range = ni_gainlkup[boardtype.gainlkup][range];
1287                 if(boardtype.reg_type == ni_reg_611x)
1288                         devpriv->ai_offset[i] = offset;
1289                 else
1290                         devpriv->ai_offset[i] = (range&0x100)?0:offset;
1291
1292                 hi = 0;
1293                 if( ( list[i] & CR_ALT_SOURCE ) )
1294                 {
1295                         if(boardtype.reg_type == ni_reg_611x)
1296                                 ni_writew(CR_CHAN(list[i])&0x0003, Calibration_Channel_Select_611x);
1297                 }else
1298                 {
1299                         if(boardtype.reg_type == ni_reg_611x)
1300                                 aref = AREF_DIFF;
1301                         switch( aref )
1302                         {
1303                                 case AREF_DIFF:
1304                                         hi |= AI_DIFFERENTIAL;
1305                                         break;
1306                                 case AREF_COMMON:
1307                                         hi |= AI_COMMON;
1308                                         break;
1309                                 case AREF_GROUND:
1310                                         hi |= AI_GROUND;
1311                                         break;
1312                                 case AREF_OTHER:
1313                                         break;
1314                         }
1315                 }
1316                 hi |= AI_CONFIG_CHANNEL( chan );
1317
1318                 ni_writew(hi,Configuration_Memory_High);
1319
1320                 lo = range;
1321                 if(i == n_chan - 1) lo |= AI_LAST_CHANNEL;
1322                 if( dither ) lo |= AI_DITHER;
1323
1324                 ni_writew(lo,Configuration_Memory_Low);
1325         }
1326
1327         /* prime the channel/gain list */
1328         if(boardtype.reg_type == ni_reg_normal){
1329                 win_out(AI_CONVERT_Pulse, AI_Command_1_Register);
1330                 for(i=0;i<NI_TIMEOUT;i++){
1331                         if(!(win_in(AI_Status_1_Register)&AI_FIFO_Empty_St)){
1332                                 win_out(1,ADC_FIFO_Clear);
1333                                 return;
1334                         }
1335                         comedi_udelay(1);
1336                 }
1337                 rt_printk("ni_mio_common: timeout loading channel/gain list\n");
1338         }
1339 }
1340
1341 #define TIMER_BASE 50 /* 20 Mhz base */
1342
1343 static int ni_ns_to_timer(int *nanosec,int round_mode)
1344 {
1345         int divider,base;
1346
1347         base=TIMER_BASE;
1348
1349         switch(round_mode){
1350         case TRIG_ROUND_NEAREST:
1351         default:
1352                 divider=(*nanosec+base/2)/base;
1353                 break;
1354         case TRIG_ROUND_DOWN:
1355                 divider=(*nanosec)/base;
1356                 break;
1357         case TRIG_ROUND_UP:
1358                 divider=(*nanosec+base-1)/base;
1359                 break;
1360         }
1361
1362         *nanosec=base*divider;
1363         return divider-1;
1364 }
1365
1366 static int ni_ai_cmdtest(comedi_device *dev,comedi_subdevice *s,comedi_cmd *cmd)
1367 {
1368         int err=0;
1369         int tmp;
1370         int sources;
1371
1372         /* step 1: make sure trigger sources are trivially valid */
1373
1374         tmp=cmd->start_src;
1375         cmd->start_src &= TRIG_NOW|TRIG_INT|TRIG_EXT;
1376         if(!cmd->start_src || tmp!=cmd->start_src)err++;
1377
1378         tmp=cmd->scan_begin_src;
1379         cmd->scan_begin_src &= TRIG_TIMER|TRIG_EXT;
1380         if(!cmd->scan_begin_src || tmp!=cmd->scan_begin_src)err++;
1381
1382         tmp=cmd->convert_src;
1383         sources = TRIG_TIMER | TRIG_EXT;
1384         if(boardtype.reg_type == ni_reg_611x) sources |= TRIG_NOW;
1385         cmd->convert_src &= sources;
1386         if(!cmd->convert_src || tmp!=cmd->convert_src)err++;
1387
1388         tmp=cmd->scan_end_src;
1389         cmd->scan_end_src &= TRIG_COUNT;
1390         if(!cmd->scan_end_src || tmp!=cmd->scan_end_src)err++;
1391
1392         tmp=cmd->stop_src;
1393         cmd->stop_src &= TRIG_COUNT|TRIG_NONE;
1394         if(!cmd->stop_src || tmp!=cmd->stop_src)err++;
1395
1396         if(err)return 1;
1397
1398         /* step 2: make sure trigger sources are unique and mutually compatible */
1399
1400         /* note that mutual compatiblity is not an issue here */
1401         if(cmd->start_src!=TRIG_NOW &&
1402            cmd->start_src!=TRIG_INT &&
1403            cmd->start_src!=TRIG_EXT)err++;
1404         if(cmd->scan_begin_src!=TRIG_TIMER &&
1405            cmd->scan_begin_src!=TRIG_EXT &&
1406            cmd->scan_begin_src!=TRIG_OTHER)err++;
1407         if(cmd->convert_src!=TRIG_TIMER &&
1408            cmd->convert_src!=TRIG_EXT &&
1409            cmd->convert_src!=TRIG_NOW)err++;
1410         if(cmd->stop_src!=TRIG_COUNT &&
1411            cmd->stop_src!=TRIG_NONE)err++;
1412
1413         if(err)return 2;
1414
1415         /* step 3: make sure arguments are trivially compatible */
1416
1417         if(cmd->start_src==TRIG_EXT){
1418                 /* external trigger */
1419                 unsigned int tmp = CR_CHAN(cmd->start_arg);
1420
1421                 if(tmp > 9) tmp = 9;
1422                 tmp |= (cmd->start_arg & (CR_INVERT | CR_EDGE));
1423                 if(cmd->start_arg != tmp){
1424                         cmd->start_arg = tmp;
1425                         err++;
1426                 }
1427         }else{
1428                 if(cmd->start_arg!=0){
1429                         /* true for both TRIG_NOW and TRIG_INT */
1430                         cmd->start_arg=0;
1431                         err++;
1432                 }
1433         }
1434         if(cmd->scan_begin_src==TRIG_TIMER){
1435                 if(cmd->scan_begin_arg<boardtype.ai_speed){
1436                         cmd->scan_begin_arg=boardtype.ai_speed;
1437                         err++;
1438                 }
1439                 if(cmd->scan_begin_arg>TIMER_BASE*0xffffff){
1440                         cmd->scan_begin_arg=TIMER_BASE*0xffffff;
1441                         err++;
1442                 }
1443         }else if(cmd->scan_begin_src==TRIG_EXT){
1444                 /* external trigger */
1445                 unsigned int tmp = CR_CHAN(cmd->scan_begin_arg);
1446
1447                 if(tmp>9)tmp=9;
1448                 tmp |= (cmd->scan_begin_arg & (CR_INVERT | CR_EDGE));
1449                 if(cmd->scan_begin_arg!=tmp){
1450                         cmd->scan_begin_arg = tmp;
1451                         err++;
1452                 }
1453         }else{ /* TRIG_OTHER */
1454                 if(cmd->scan_begin_arg){
1455                         cmd->scan_begin_arg=0;
1456                         err++;
1457                 }
1458         }
1459         if(cmd->convert_src==TRIG_TIMER){
1460                 if(boardtype.reg_type == ni_reg_611x){
1461                         if(cmd->convert_arg != 0){
1462                                 cmd->convert_arg = 0;
1463                                 err++;
1464                         }
1465                 }else{
1466                         if(cmd->convert_arg<boardtype.ai_speed){
1467                                 cmd->convert_arg=boardtype.ai_speed;
1468                                 err++;
1469                         }
1470                         if(cmd->convert_arg>TIMER_BASE*0xffff){
1471                                 cmd->convert_arg=TIMER_BASE*0xffff;
1472                                 err++;
1473                         }
1474                 }
1475         }else if(cmd->convert_src == TRIG_EXT){
1476                 /* external trigger */
1477                 unsigned int tmp = CR_CHAN(cmd->convert_arg);
1478
1479                 if(tmp>9)tmp=9;
1480                 tmp |= (cmd->convert_arg&(CR_ALT_FILTER|CR_INVERT));
1481                 if(cmd->convert_arg!=tmp){
1482                         cmd->convert_arg = tmp;
1483                         err++;
1484                 }
1485         }else if(cmd->convert_src == TRIG_NOW){
1486                 if(cmd->convert_arg != 0){
1487                         cmd->convert_arg = 0;
1488                         err++;
1489                 }
1490         }
1491
1492         if(cmd->scan_end_arg!=cmd->chanlist_len){
1493                 cmd->scan_end_arg=cmd->chanlist_len;
1494                 err++;
1495         }
1496         if(cmd->stop_src==TRIG_COUNT){
1497                 unsigned int max_count = 0x01000000;
1498
1499                 if(boardtype.reg_type == ni_reg_611x )
1500                         max_count -= num_adc_stages_611x;
1501                 if(cmd->stop_arg > max_count){
1502                         cmd->stop_arg = max_count;
1503                         err++;
1504                 }
1505                 if(cmd->stop_arg < 1){
1506                         cmd->stop_arg = 1;
1507                         err++;
1508                 }
1509         }else{
1510                 /* TRIG_NONE */
1511                 if(cmd->stop_arg!=0){
1512                         cmd->stop_arg=0;
1513                         err++;
1514                 }
1515         }
1516
1517         if(err)return 3;
1518
1519         /* step 4: fix up any arguments */
1520
1521         if(cmd->scan_begin_src==TRIG_TIMER){
1522                 tmp=cmd->scan_begin_arg;
1523                 ni_ns_to_timer(&cmd->scan_begin_arg,cmd->flags&TRIG_ROUND_MASK);
1524                 if(tmp!=cmd->scan_begin_arg)err++;
1525         }
1526         if(cmd->convert_src==TRIG_TIMER){
1527                 if(boardtype.reg_type == ni_reg_normal){
1528                         tmp=cmd->convert_arg;
1529                         ni_ns_to_timer(&cmd->convert_arg,cmd->flags&TRIG_ROUND_MASK);
1530                         if(tmp!=cmd->convert_arg)err++;
1531                         if(cmd->scan_begin_src==TRIG_TIMER &&
1532                         cmd->scan_begin_arg<cmd->convert_arg*cmd->scan_end_arg){
1533                                 cmd->scan_begin_arg=cmd->convert_arg*cmd->scan_end_arg;
1534                                 err++;
1535                         }
1536                 }
1537         }
1538
1539         if(err)return 4;
1540
1541         return 0;
1542 }
1543
1544 static int ni_ai_cmd(comedi_device *dev,comedi_subdevice *s)
1545 {
1546         comedi_cmd *cmd=&s->async->cmd;
1547         int timer;
1548         int mode1=0; /* mode1 is needed for both stop and convert */
1549         int mode2=0;
1550         int start_stop_select=0;
1551         unsigned int stop_count;
1552         int interrupt_a_enable=0;
1553
1554         MDPRINTK("ni_ai_cmd\n");
1555         if(dev->irq == 0)
1556         {
1557                 comedi_error(dev, "cannot run command without an irq");
1558                 return -EIO;
1559         }
1560         win_out(1,ADC_FIFO_Clear);
1561
1562         ni_load_channelgain_list(dev,cmd->chanlist_len,cmd->chanlist);
1563
1564         /* start configuration */
1565         win_out(AI_Configuration_Start,Joint_Reset_Register);
1566
1567         /* disable analog triggering for now, since it
1568          * interferes with the use of pfi0 */
1569         devpriv->an_trig_etc_reg &= ~Analog_Trigger_Enable;
1570         win_out(devpriv->an_trig_etc_reg, Analog_Trigger_Etc_Register);
1571
1572         switch(cmd->start_src){
1573                 case TRIG_INT:
1574                 case TRIG_NOW:
1575                         win_out(AI_START2_Select(0)|
1576                                 AI_START1_Sync|AI_START1_Edge|AI_START1_Select(0),
1577                                 AI_Trigger_Select_Register);
1578                         break;
1579                 case TRIG_EXT:
1580                 {
1581                         int chan = CR_CHAN(cmd->start_arg);
1582                         unsigned int bits = AI_START2_Select(0)|
1583                                 AI_START1_Sync |
1584                                 AI_START1_Select(chan + 1);
1585                                 
1586                         if(cmd->start_arg & CR_INVERT)
1587                                 bits |= AI_START1_Polarity;
1588                         if(cmd->start_arg & CR_EDGE)
1589                                 bits |= AI_START1_Edge;
1590                         win_out(bits, AI_Trigger_Select_Register);
1591                         break;
1592                 }
1593         }
1594
1595         mode2 &= ~AI_Pre_Trigger;
1596         mode2 &= ~AI_SC_Initial_Load_Source;
1597         mode2 &= ~AI_SC_Reload_Mode;
1598         win_out(mode2, AI_Mode_2_Register);
1599
1600         if(cmd->chanlist_len == 1 || boardtype.reg_type == ni_reg_611x){
1601                 start_stop_select |= AI_STOP_Polarity;
1602                 start_stop_select |= AI_STOP_Select( 31 ); // logic low
1603                 start_stop_select |= AI_STOP_Sync;
1604         }else
1605         {
1606                 start_stop_select |= AI_STOP_Select(19); // ai configuration memory
1607         }
1608         win_out(start_stop_select, AI_START_STOP_Select_Register);
1609
1610         devpriv->ai_cmd2 = 0;
1611         switch(cmd->stop_src){
1612         case TRIG_COUNT:
1613                 stop_count = cmd->stop_arg - 1;
1614
1615                 if(boardtype.reg_type == ni_reg_611x){
1616                         // have to take 3 stage adc pipeline into account
1617                         stop_count += num_adc_stages_611x;
1618                 }
1619                 /* stage number of scans */
1620                 win_out2( stop_count, AI_SC_Load_A_Registers);
1621
1622                 mode1 |= AI_Start_Stop | AI_Mode_1_Reserved | AI_Trigger_Once;
1623                 win_out(mode1,AI_Mode_1_Register);
1624                 /* load SC (Scan Count) */
1625                 win_out(AI_SC_Load,AI_Command_1_Register);
1626
1627                 devpriv->ai_continuous = 0;
1628                 if( stop_count == 0 ){
1629                         devpriv->ai_cmd2 |= AI_End_On_End_Of_Scan;
1630                         interrupt_a_enable |= AI_STOP_Interrupt_Enable;
1631                         // this is required to get the last sample for chanlist_len > 1, not sure why
1632                         if(cmd->chanlist_len > 1)
1633                                 start_stop_select |= AI_STOP_Polarity | AI_STOP_Edge;
1634                 }
1635                 break;
1636         case TRIG_NONE:
1637                 /* stage number of scans */
1638                 win_out(0,AI_SC_Load_A_Registers);
1639                 win_out(0,AI_SC_Load_A_Registers+1);
1640
1641                 mode1 |= AI_Start_Stop | AI_Mode_1_Reserved | AI_Continuous;
1642                 win_out(mode1,AI_Mode_1_Register);
1643
1644                 /* load SC (Scan Count) */
1645                 win_out(AI_SC_Load,AI_Command_1_Register);
1646
1647                 devpriv->ai_continuous = 1;
1648
1649                 break;
1650         }
1651
1652         switch(cmd->scan_begin_src){
1653         case TRIG_TIMER:
1654                 /*
1655                         stop bits for non 611x boards
1656                         AI_SI_Special_Trigger_Delay=0
1657                         AI_Pre_Trigger=0
1658                         AI_START_STOP_Select_Register:
1659                         AI_START_Polarity=0 (?) rising edge
1660                         AI_START_Edge=1         edge triggered
1661                         AI_START_Sync=1 (?)
1662                         AI_START_Select=0               SI_TC
1663                         AI_STOP_Polarity=0              rising edge
1664                         AI_STOP_Edge=0          level
1665                         AI_STOP_Sync=1
1666                         AI_STOP_Select=19               external pin (configuration mem)
1667                  */
1668                 start_stop_select |= AI_START_Edge | AI_START_Sync;
1669                 win_out(start_stop_select, AI_START_STOP_Select_Register);
1670
1671                 mode2 |= AI_SI_Reload_Mode(0);
1672                 /* AI_SI_Initial_Load_Source=A */
1673                 mode2 &= ~AI_SI_Initial_Load_Source;
1674                 //mode2 |= AI_SC_Reload_Mode;
1675                 win_out(mode2, AI_Mode_2_Register);
1676
1677                 /* load SI */
1678                 timer=ni_ns_to_timer(&cmd->scan_begin_arg,TRIG_ROUND_NEAREST);
1679                 win_out2(timer,AI_SI_Load_A_Registers);
1680                 win_out(AI_SI_Load,AI_Command_1_Register);
1681                 break;
1682         case TRIG_EXT:
1683                 if( cmd->scan_begin_arg & CR_EDGE )
1684                         start_stop_select |= AI_START_Edge;
1685                 /* AI_START_Polarity==1 is falling edge */
1686                 if( cmd->scan_begin_arg & CR_INVERT )
1687                         start_stop_select |= AI_START_Polarity;
1688                 if( cmd->scan_begin_src != cmd->convert_src ||
1689                         ( cmd->scan_begin_arg & ~CR_EDGE ) != ( cmd->convert_arg & ~CR_EDGE ) )
1690                         start_stop_select |= AI_START_Sync;
1691                 start_stop_select |= AI_START_Select(1 + CR_CHAN(cmd->scan_begin_arg));
1692                 win_out(start_stop_select, AI_START_STOP_Select_Register);
1693                 break;
1694         }
1695
1696         switch(cmd->convert_src){
1697         case TRIG_TIMER:
1698         case TRIG_NOW:
1699                 if( cmd->convert_arg == 0 || cmd->convert_src == TRIG_NOW )
1700                         timer = 1;
1701                 else
1702                         timer=ni_ns_to_timer(&cmd->convert_arg, TRIG_ROUND_NEAREST);
1703                 win_out(1,AI_SI2_Load_A_Register); /* 0,0 does not work. */
1704                 win_out(timer,AI_SI2_Load_B_Register);
1705
1706                 /* AI_SI2_Reload_Mode = alternate */
1707                 /* AI_SI2_Initial_Load_Source = A */
1708                 mode2 &= ~AI_SI2_Initial_Load_Source;
1709                 mode2 |= AI_SI2_Reload_Mode;
1710                 win_out( mode2, AI_Mode_2_Register);
1711
1712                 /* AI_SI2_Load */
1713                 win_out(AI_SI2_Load,AI_Command_1_Register);
1714
1715                 mode2 |= AI_SI2_Reload_Mode; // alternate
1716                 mode2 |= AI_SI2_Initial_Load_Source; // B
1717
1718                 win_out(mode2,AI_Mode_2_Register);
1719                 break;
1720         case TRIG_EXT:
1721                 mode1 |= AI_CONVERT_Source_Select(1+cmd->convert_arg);
1722                 if( ( cmd->convert_arg & CR_INVERT ) == 0 )
1723                         mode1 |= AI_CONVERT_Source_Polarity;
1724                 win_out(mode1,AI_Mode_1_Register);
1725
1726                 mode2 |= AI_Start_Stop_Gate_Enable | AI_SC_Gate_Enable;
1727                 win_out(mode2, AI_Mode_2_Register);
1728
1729                 break;
1730         }
1731
1732         if(dev->irq){
1733
1734                 /* interrupt on FIFO, errors, SC_TC */
1735                 interrupt_a_enable |= AI_Error_Interrupt_Enable|
1736                         AI_SC_TC_Interrupt_Enable;
1737
1738 #ifndef PCIDMA
1739                 interrupt_a_enable|=AI_FIFO_Interrupt_Enable;
1740 #endif
1741
1742                 if(cmd->flags & TRIG_WAKE_EOS || (devpriv->ai_cmd2 & AI_End_On_End_Of_Scan)){
1743                         /* wake on end-of-scan */
1744                         devpriv->aimode=AIMODE_SCAN;
1745                 }else{
1746                         devpriv->aimode=AIMODE_HALF_FULL;
1747                 }
1748
1749                 switch(devpriv->aimode){
1750                 case AIMODE_HALF_FULL:
1751                         /*generate FIFO interrupts and DMA requests on half-full */
1752 #ifdef PCIDMA
1753                         win_out(AI_FIFO_Mode_HF_to_E, AI_Mode_3_Register);
1754 #else
1755                         win_out(AI_FIFO_Mode_HF, AI_Mode_3_Register);
1756 #endif
1757                         break;
1758                 case AIMODE_SAMPLE:
1759                         /*generate FIFO interrupts on non-empty */
1760                         win_out(AI_FIFO_Mode_NE, AI_Mode_3_Register);
1761                         break;
1762                 case AIMODE_SCAN:
1763 #ifdef PCIDMA
1764                         win_out(AI_FIFO_Mode_NE, AI_Mode_3_Register);
1765 #else
1766                         win_out(AI_FIFO_Mode_HF, AI_Mode_3_Register);
1767 #endif
1768                         interrupt_a_enable |= AI_STOP_Interrupt_Enable;
1769                         break;
1770                 default:
1771                         break;
1772                 }
1773
1774                 win_out(0x3f80,Interrupt_A_Ack_Register); /* clear interrupts */
1775
1776                 ni_set_bits(dev, Interrupt_A_Enable_Register, interrupt_a_enable, 1);
1777
1778                 MDPRINTK("Interrupt_A_Enable_Register = 0x%04x\n",devpriv->int_a_enable_reg);
1779         }else{
1780                 /* interrupt on nothing */
1781                 ni_set_bits(dev, Interrupt_A_Enable_Register, ~0, 0);
1782
1783                 /* XXX start polling if necessary */
1784                 MDPRINTK("interrupting on nothing\n");
1785         }
1786
1787         /* end configuration */
1788         win_out(AI_Configuration_End,Joint_Reset_Register);
1789
1790         switch(cmd->scan_begin_src){
1791         case TRIG_TIMER:
1792                 win_out(AI_SI2_Arm | AI_SI_Arm | AI_DIV_Arm | AI_SC_Arm,
1793                         AI_Command_1_Register);
1794                 break;
1795         case TRIG_EXT:
1796                 /* XXX AI_SI_Arm? */
1797                 win_out(AI_SI2_Arm | AI_SI_Arm | AI_DIV_Arm | AI_SC_Arm,
1798                         AI_Command_1_Register);
1799                 break;
1800         }
1801
1802 #ifdef PCIDMA
1803         ni_ai_setup_MITE_dma(dev,cmd);
1804         //mite_dump_regs(devpriv->mite);
1805 #endif
1806
1807         switch(cmd->start_src){
1808         case TRIG_NOW:
1809                 /* AI_START1_Pulse */
1810                 win_out( AI_START1_Pulse | devpriv->ai_cmd2, AI_Command_2_Register );
1811                 s->async->inttrig=NULL;
1812                 break;
1813         case TRIG_EXT:
1814                 s->async->inttrig=NULL;
1815                 break;
1816         case TRIG_INT:
1817                 s->async->inttrig=ni_ai_inttrig;
1818                 break;
1819         }
1820
1821         MDPRINTK("exit ni_ai_cmd\n");
1822
1823         return 0;
1824 }
1825
1826 static int ni_ai_inttrig(comedi_device *dev,comedi_subdevice *s,
1827         unsigned int trignum)
1828 {
1829         if(trignum!=0)return -EINVAL;
1830
1831         win_out( AI_START1_Pulse | devpriv->ai_cmd2, AI_Command_2_Register );
1832         s->async->inttrig=NULL;
1833
1834         return 1;
1835 }
1836
1837 static int ni_ai_config_analog_trig(comedi_device *dev,comedi_subdevice *s,
1838         comedi_insn *insn, lsampl_t *data);
1839
1840 static int ni_ai_insn_config(comedi_device *dev,comedi_subdevice *s,
1841         comedi_insn *insn, lsampl_t *data)
1842 {
1843         if(insn->n<1)return -EINVAL;
1844
1845         switch(data[0]){
1846         case INSN_CONFIG_ANALOG_TRIG:
1847                 return ni_ai_config_analog_trig(dev,s,insn,data);
1848         case INSN_CONFIG_ALT_SOURCE:
1849                 {
1850                 unsigned int calib_source;
1851                 unsigned int calib_source_adjust;
1852
1853                 calib_source = data[1] & 0xf;
1854                 calib_source_adjust = ( data[1] >> 4 ) & 0xff;
1855
1856                 if(calib_source >= 8)
1857                         return -EINVAL;
1858                 devpriv->ai_calib_source = calib_source;
1859                 if(boardtype.reg_type == ni_reg_611x){
1860                         ni_writeb( calib_source_adjust, Cal_Gain_Select_611x );
1861                 }
1862                 return 2;
1863                 }
1864         default:
1865                 break;
1866         }
1867
1868         return -EINVAL;
1869 }
1870
1871 static int ni_ai_config_analog_trig(comedi_device *dev,comedi_subdevice *s,
1872         comedi_insn *insn, lsampl_t *data)
1873 {
1874         unsigned int a,b,modebits;
1875         int err=0;
1876
1877         /* data[1] is flags
1878          * data[2] is analog line
1879          * data[3] is set level
1880          * data[4] is reset level */
1881         if(!boardtype.has_analog_trig)return -EINVAL;
1882         if(insn->n!=5)return -EINVAL;
1883         if((data[1]&0xffff0000) != COMEDI_EV_SCAN_BEGIN){
1884                 data[1]&=~(COMEDI_EV_SCAN_BEGIN&0xffff);
1885                 err++;
1886         }
1887         if(data[2]>=boardtype.n_adchan){
1888                 data[2]=boardtype.n_adchan-1;
1889                 err++;
1890         }
1891         if(data[3]>255){ /* a */
1892                 data[3]=255;
1893                 err++;
1894         }
1895         if(data[4]>255){ /* b */
1896                 data[4]=255;
1897                 err++;
1898         }
1899         /*
1900          * 00 ignore
1901          * 01 set
1902          * 10 reset
1903          *
1904          * modes:
1905          *   1 level:                    +b-   +a-
1906          *     high mode                00 00 01 10
1907          *     low mode                 00 00 10 01
1908          *   2 level: (a<b)
1909          *     hysteresis low mode      10 00 00 01
1910          *     hysteresis high mode     01 00 00 10
1911          *     middle mode              10 01 01 10
1912          */
1913
1914         a=data[3];
1915         b=data[4];
1916         modebits=data[1]&0xff;
1917         if(modebits&0xf0){
1918                 /* two level mode */
1919                 if(b<a){
1920                         /* swap order */
1921                         a=data[4];
1922                         b=data[3];
1923                         modebits=((data[1]&0xf)<<4)|((data[1]&0xf0)>>4);
1924                 }
1925                 devpriv->atrig_low = a;
1926                 devpriv->atrig_high = b;
1927                 switch(modebits){
1928                 case 0x81:      /* low hysteresis mode */
1929                         devpriv->atrig_mode = 6;
1930                         break;
1931                 case 0x42:      /* high hysteresis mode */
1932                         devpriv->atrig_mode = 3;
1933                         break;
1934                 case 0x96:      /* middle window mode */
1935                         devpriv->atrig_mode = 2;
1936                         break;
1937                 default:
1938                         data[1]&=~0xff;
1939                         err++;
1940                 }
1941         }else{
1942                 /* one level mode */
1943                 if(b!=0){
1944                         data[4]=0;
1945                         err++;
1946                 }
1947                 switch(modebits){
1948                 case 0x06:      /* high window mode */
1949                         devpriv->atrig_high = a;
1950                         devpriv->atrig_mode = 0;
1951                         break;
1952                 case 0x09:      /* low window mode */
1953                         devpriv->atrig_low = a;
1954                         devpriv->atrig_mode = 1;
1955                         break;
1956                 default:
1957                         data[1]&=~0xff;
1958                         err++;
1959                 }
1960         }
1961         if(err)return -EAGAIN;
1962         return 5;
1963 }
1964
1965 /* munge data from unsigned to 2's complement for analog output bipolar modes */
1966 static void ni_ao_munge(comedi_device *dev, comedi_subdevice *s,
1967         void *data, unsigned int num_bytes, unsigned int chan_index )
1968 {
1969         comedi_async *async = s->async;
1970         unsigned int range;
1971         unsigned int i;
1972         unsigned int offset;
1973         unsigned int length = num_bytes / sizeof( sampl_t );
1974         sampl_t *array = data;
1975
1976         offset = 1 << (boardtype.aobits - 1);
1977         for(i = 0; i < length; i++)
1978         {
1979                 range = CR_RANGE( async->cmd.chanlist[ chan_index ] );
1980                 if(boardtype.ao_unipolar == 0 || (range & 1) == 0 )
1981                         array[i] -= offset;
1982 #ifdef PCIDMA
1983                 array[i] = cpu_to_le16( array[i] );
1984 #endif
1985                 chan_index++;
1986                 chan_index %= async->cmd.chanlist_len;
1987         }
1988 }
1989
1990 static int ni_ao_config_chanlist(comedi_device *dev, comedi_subdevice *s,
1991         unsigned int chanspec[], unsigned int n_chans)
1992 {
1993         unsigned int range;
1994         unsigned int chan;
1995         unsigned int conf;
1996         int i;
1997         int invert = 0;
1998
1999         for(i=0;i<n_chans;i++){
2000                 chan = CR_CHAN(chanspec[i]);
2001                 range = CR_RANGE(chanspec[i]);
2002
2003                 conf = AO_Channel(chan);
2004
2005                 if(boardtype.ao_unipolar){
2006                         if((range&1) == 0){
2007                                 conf |= AO_Bipolar;
2008                                 invert = (1<<(boardtype.aobits-1));
2009                         }else{
2010                                 invert = 0;
2011                         }
2012                         if(range&2)
2013                                 conf |= AO_Ext_Ref;
2014                 }else{
2015                         conf |= AO_Bipolar;
2016                         invert = (1<<(boardtype.aobits-1));
2017                 }
2018
2019                 /* not all boards can deglitch, but this shouldn't hurt */
2020                 if(chanspec[i] & CR_DEGLITCH)
2021                         conf |= AO_Deglitch;
2022
2023                 /* analog reference */
2024                 /* AREF_OTHER connects AO ground to AI ground, i think */
2025                 conf |= (CR_AREF(chanspec[i])==AREF_OTHER)? AO_Ground_Ref : 0;
2026
2027                 devpriv->ao_conf[chan] = conf;
2028
2029                 ni_writew(conf,AO_Configuration);
2030         }
2031         return invert;
2032 }
2033
2034 static int ni_ao_insn_read(comedi_device *dev,comedi_subdevice *s,
2035         comedi_insn *insn,lsampl_t *data)
2036 {
2037         data[0] = devpriv->ao[CR_CHAN(insn->chanspec)];
2038
2039         return 1;
2040 }
2041
2042 static int ni_ao_insn_write(comedi_device *dev,comedi_subdevice *s,
2043         comedi_insn *insn,lsampl_t *data)
2044 {
2045         unsigned int chan = CR_CHAN(insn->chanspec);
2046         unsigned int invert;
2047
2048         invert = ni_ao_config_chanlist(dev,s,&insn->chanspec,1);
2049
2050         devpriv->ao[chan] = data[0];
2051
2052         ni_writew(data[0] ^ invert,(chan)? DAC1_Direct_Data : DAC0_Direct_Data);
2053
2054         return 1;
2055 }
2056
2057 static int ni_ao_insn_write_671x(comedi_device *dev,comedi_subdevice *s,
2058         comedi_insn *insn,lsampl_t *data)
2059 {
2060         unsigned int chan = CR_CHAN(insn->chanspec);
2061         unsigned int invert;
2062
2063         ao_win_out(1 << chan, AO_Immediate_671x);
2064         invert = 1 << (boardtype.aobits - 1);
2065
2066         ni_ao_config_chanlist(dev,s,&insn->chanspec,1);
2067
2068         devpriv->ao[chan] = data[0];
2069         ao_win_out(data[0] ^ invert, DACx_Direct_Data_671x(chan));
2070
2071         return 1;
2072 }
2073
2074 static int ni_ao_inttrig(comedi_device *dev,comedi_subdevice *s,
2075         unsigned int trignum)
2076 {
2077         int ret;
2078         int interrupt_b_bits;
2079         int i;
2080         static const int timeout = 1000;
2081         
2082         if(trignum!=0)return -EINVAL;
2083
2084         ni_set_bits(dev, Interrupt_B_Enable_Register, AO_FIFO_Interrupt_Enable | AO_Error_Interrupt_Enable, 0);
2085         interrupt_b_bits = AO_Error_Interrupt_Enable;
2086 #ifdef PCIDMA
2087         win_out(0, DAC_FIFO_Clear);
2088         if(boardtype.reg_type & ni_reg_6xxx_mask)
2089                 ni_ao_win_outl(dev, 0x6, AO_FIFO_Offset_Load_611x);
2090         ni_ao_setup_MITE_dma(dev, &s->async->cmd);
2091         ret = ni_ao_wait_for_dma_load(dev);
2092         if(ret < 0) return ret;
2093
2094 #else
2095         ret = ni_ao_prep_fifo(dev,s);
2096         if(ret==0)return -EPIPE;
2097
2098         interrupt_b_bits |= AO_FIFO_Interrupt_Enable;
2099 #endif
2100         
2101         win_out(devpriv->ao_mode3|AO_Not_An_UPDATE,AO_Mode_3_Register);
2102         win_out(devpriv->ao_mode3,AO_Mode_3_Register);
2103         /* wait for DACs to be loaded */
2104         for(i = 0; i < timeout; i++)
2105         {
2106                 comedi_udelay(10);
2107                 if((win_in(Joint_Status_2_Register) & AO_TMRDACWRs_In_Progress_St) == 0)
2108                         break;
2109         }
2110         if(i == timeout)
2111         {
2112                 comedi_error(dev, "timed out waiting for AO_TMRDACWRs_In_Progress_St to clear");
2113                 return -EIO;
2114         }
2115         // stc manual says we are need to clear error interrupt after AO_TMRDACWRs_In_Progress_St clears
2116         win_out(AO_Error_Interrupt_Ack, Interrupt_B_Ack_Register);
2117         
2118         ni_set_bits(dev, Interrupt_B_Enable_Register, interrupt_b_bits, 1);
2119
2120         win_out(devpriv->ao_cmd1|AO_UI_Arm|AO_UC_Arm|AO_BC_Arm|AO_DAC1_Update_Mode|AO_DAC0_Update_Mode,
2121                 AO_Command_1_Register);
2122
2123         win_out(devpriv->ao_cmd2|AO_START1_Pulse,AO_Command_2_Register);
2124
2125         s->async->inttrig=NULL;
2126
2127         return 0;
2128 }
2129
2130 static int ni_ao_cmd(comedi_device *dev,comedi_subdevice *s)
2131 {
2132         comedi_cmd *cmd = &s->async->cmd;
2133         int trigvar;
2134         int bits;
2135         int i;
2136         
2137         if(dev->irq == 0)
2138         {
2139                 comedi_error(dev, "cannot run command without an irq");
2140                 return -EIO;
2141         }
2142         trigvar = ni_ns_to_timer(&cmd->scan_begin_arg,TRIG_ROUND_NEAREST);
2143
2144         win_out(AO_Configuration_Start,Joint_Reset_Register);
2145
2146         win_out(AO_Disarm,AO_Command_1_Register);
2147
2148         if(boardtype.reg_type & ni_reg_6xxx_mask)
2149         {
2150                 ao_win_out(CLEAR_WG, AO_Misc_611x);
2151
2152                 bits = 0;
2153                 for(i = 0; i < cmd->chanlist_len; i++)
2154                 {
2155                         int chan;
2156
2157                         chan = CR_CHAN(cmd->chanlist[i]);
2158                         bits |= 1 << chan;
2159                         ao_win_out(chan, AO_Waveform_Generation_611x);
2160                 }
2161                 ao_win_out(bits, AO_Timed_611x);
2162         }
2163
2164         ni_ao_config_chanlist(dev,s,cmd->chanlist,cmd->chanlist_len);
2165
2166         if(cmd->stop_src==TRIG_NONE){
2167                 devpriv->ao_mode1|=AO_Continuous;
2168                 devpriv->ao_mode1&=~AO_Trigger_Once;
2169         }else{
2170                 devpriv->ao_mode1&=~AO_Continuous;
2171                 devpriv->ao_mode1|=AO_Trigger_Once;
2172         }
2173         win_out(devpriv->ao_mode1,AO_Mode_1_Register);
2174         devpriv->ao_trigger_select&=~(AO_START1_Polarity|AO_START1_Select(-1));
2175         devpriv->ao_trigger_select|=AO_START1_Edge|AO_START1_Sync;
2176         win_out(devpriv->ao_trigger_select,AO_Trigger_Select_Register);
2177         devpriv->ao_mode3&=~AO_Trigger_Length;
2178         win_out(devpriv->ao_mode3,AO_Mode_3_Register);
2179
2180         win_out(devpriv->ao_mode1,AO_Mode_1_Register);
2181         devpriv->ao_mode2&=~AO_BC_Initial_Load_Source;
2182         win_out(devpriv->ao_mode2,AO_Mode_2_Register);
2183         if(cmd->stop_src==TRIG_NONE){
2184                 win_out2(0xffffff,AO_BC_Load_A_Register);
2185         }else{
2186                 win_out2(0,AO_BC_Load_A_Register);
2187         }
2188         win_out(AO_BC_Load,AO_Command_1_Register);
2189         devpriv->ao_mode2&=~AO_UC_Initial_Load_Source;
2190         win_out(devpriv->ao_mode2,AO_Mode_2_Register);
2191         switch(cmd->stop_src){
2192         case TRIG_COUNT:
2193                 win_out2(cmd->stop_arg,AO_UC_Load_A_Register);
2194                 win_out(AO_UC_Load,AO_Command_1_Register);
2195                 win_out2(cmd->stop_arg - 1,AO_UC_Load_A_Register);
2196                 break;
2197         case TRIG_NONE:
2198                 win_out2(0xffffff,AO_UC_Load_A_Register);
2199                 win_out(AO_UC_Load,AO_Command_1_Register);
2200                 win_out2(0xffffff,AO_UC_Load_A_Register);
2201                 break;
2202         default:
2203                 win_out2(0,AO_UC_Load_A_Register);
2204                 win_out(AO_UC_Load,AO_Command_1_Register);
2205                 win_out2(cmd->stop_arg,AO_UC_Load_A_Register);
2206         }
2207
2208         devpriv->ao_cmd2&=~AO_BC_Gate_Enable;
2209         win_out(devpriv->ao_cmd2,AO_Command_2_Register);
2210         devpriv->ao_mode1&=~(AO_UI_Source_Select(0x1f)|AO_UI_Source_Polarity);
2211         win_out(devpriv->ao_mode1,AO_Mode_1_Register);
2212         devpriv->ao_mode2&=~(AO_UI_Reload_Mode(3)|AO_UI_Initial_Load_Source);
2213         win_out(devpriv->ao_mode2,AO_Mode_2_Register);
2214         win_out2(1,AO_UI_Load_A_Register);
2215         win_out(AO_UI_Load,AO_Command_1_Register);
2216         win_out2(trigvar,AO_UI_Load_A_Register);
2217
2218         if(boardtype.reg_type == ni_reg_normal){
2219                 if(cmd->scan_end_arg>1){
2220                         devpriv->ao_mode1|=AO_Multiple_Channels;
2221                         win_out(AO_Number_Of_Channels(cmd->scan_end_arg-1)|
2222                                 AO_UPDATE_Output_Select(1),
2223                                 AO_Output_Control_Register);
2224                 }else{
2225                         devpriv->ao_mode1&=~AO_Multiple_Channels;
2226                         win_out(AO_Number_Of_Channels(CR_CHAN(cmd->chanlist[0]))|
2227                                 AO_UPDATE_Output_Select(1),
2228                                 AO_Output_Control_Register);
2229                 }
2230                 win_out(devpriv->ao_mode1,AO_Mode_1_Register);
2231         }
2232
2233         win_out(AO_DAC0_Update_Mode|AO_DAC1_Update_Mode,AO_Command_1_Register);
2234
2235         devpriv->ao_mode3|=AO_Stop_On_Overrun_Error;
2236         win_out(devpriv->ao_mode3,AO_Mode_3_Register);
2237
2238         devpriv->ao_mode2 &= AO_FIFO_Mode_Mask;
2239 #ifdef PCIDMA
2240         devpriv->ao_mode2 |= AO_FIFO_Mode_HF_to_F;
2241 #else
2242         devpriv->ao_mode2 |= AO_FIFO_Mode_HF;
2243 #endif
2244         devpriv->ao_mode2 &= ~AO_FIFO_Retransmit_Enable;
2245         win_out(devpriv->ao_mode2,AO_Mode_2_Register);
2246
2247         bits = AO_BC_Source_Select | AO_UPDATE_Pulse_Width |
2248                 AO_TMRDACWR_Pulse_Width;
2249         if( boardtype.ao_fifo_depth )
2250                 bits |= AO_FIFO_Enable;
2251         win_out(bits, AO_Personal_Register);
2252         // enable sending of ao dma requests
2253         win_out(AO_AOFREQ_Enable, AO_Start_Select_Register);
2254
2255         win_out(AO_Configuration_End,Joint_Reset_Register);
2256
2257         if(cmd->stop_src==TRIG_COUNT) {
2258                 win_out(AO_BC_TC_Interrupt_Ack,Interrupt_B_Ack_Register);
2259                 ni_set_bits(dev, Interrupt_B_Enable_Register,
2260                         AO_BC_TC_Interrupt_Enable, 1);
2261         }
2262
2263         s->async->inttrig=ni_ao_inttrig;
2264
2265         return 0;
2266 }
2267
2268 static int ni_ao_cmdtest(comedi_device *dev,comedi_subdevice *s,comedi_cmd *cmd)
2269 {
2270         int err=0;
2271         int tmp;
2272
2273         /* step 1: make sure trigger sources are trivially valid */
2274
2275         tmp=cmd->start_src;
2276         cmd->start_src &= TRIG_INT;
2277         if(!cmd->start_src || tmp!=cmd->start_src)err++;
2278
2279         tmp=cmd->scan_begin_src;
2280         cmd->scan_begin_src &= TRIG_TIMER;
2281         if(!cmd->scan_begin_src || tmp!=cmd->scan_begin_src)err++;
2282
2283         tmp=cmd->convert_src;
2284         cmd->convert_src &= TRIG_NOW;
2285         if(!cmd->convert_src || tmp!=cmd->convert_src)err++;
2286
2287         tmp=cmd->scan_end_src;
2288         cmd->scan_end_src &= TRIG_COUNT;
2289         if(!cmd->scan_end_src || tmp!=cmd->scan_end_src)err++;
2290
2291         tmp=cmd->stop_src;
2292         cmd->stop_src &= TRIG_COUNT|TRIG_NONE;
2293         if(!cmd->stop_src || tmp!=cmd->stop_src)err++;
2294
2295         if(err)return 1;
2296
2297         /* step 2: make sure trigger sources are unique and mutually compatible */
2298
2299         if(cmd->stop_src!=TRIG_COUNT &&
2300            cmd->stop_src!=TRIG_NONE)err++;
2301
2302         if(err)return 2;
2303
2304         /* step 3: make sure arguments are trivially compatible */
2305
2306         if(cmd->start_arg!=0){
2307                 cmd->start_arg=0;
2308                 err++;
2309         }
2310 #if 0
2311         /* XXX need ao_speed */
2312         if(cmd->scan_begin_arg<boardtype.ao_speed){
2313                 cmd->scan_begin_arg=boardtype.ao_speed;
2314                 err++;
2315         }
2316 #endif
2317         if(cmd->scan_begin_arg>TIMER_BASE*0xffffff){ /* XXX check */
2318                 cmd->scan_begin_arg=TIMER_BASE*0xffffff;
2319                 err++;
2320         }
2321         if(cmd->convert_arg!=0){
2322                 cmd->convert_arg=0;
2323                 err++;
2324         }
2325         if(cmd->scan_end_arg!=cmd->chanlist_len){
2326                 cmd->scan_end_arg=cmd->chanlist_len;
2327                 err++;
2328         }
2329         if(cmd->stop_src==TRIG_COUNT){ /* XXX check */
2330                 if(cmd->stop_arg>0x00ffffff){
2331                         cmd->stop_arg=0x00ffffff;
2332                         err++;
2333                 }
2334         }else{
2335                 /* TRIG_NONE */
2336                 if(cmd->stop_arg!=0){
2337                         cmd->stop_arg=0;
2338                         err++;
2339                 }
2340         }
2341
2342         if(err)return 3;
2343
2344         /* step 4: fix up any arguments */
2345
2346         tmp = cmd->scan_begin_arg;
2347         ni_ns_to_timer(&cmd->scan_begin_arg,cmd->flags&TRIG_ROUND_MASK);
2348         if(tmp!=cmd->scan_begin_arg)err++;
2349
2350         if(err)return 4;
2351
2352         /* step 5: fix up chanlist */
2353
2354         if(err)return 5;
2355
2356         return 0;
2357 }
2358
2359
2360 static int ni_ao_reset(comedi_device *dev,comedi_subdevice *s)
2361 {
2362         //devpriv->ao0p=0x0000;
2363         //ni_writew(devpriv->ao0p,AO_Configuration);
2364
2365         //devpriv->ao1p=AO_Channel(1);
2366         //ni_writew(devpriv->ao1p,AO_Configuration);
2367
2368 #ifdef PCIDMA
2369         mite_dma_disarm(devpriv->mite, AO_DMA_CHAN);
2370         writel(CHOR_DMARESET | CHOR_FRESET, devpriv->mite->mite_io_addr + MITE_CHOR(AO_DMA_CHAN));
2371 #endif
2372
2373         win_out(AO_Configuration_Start,Joint_Reset_Register);
2374         win_out(AO_Disarm,AO_Command_1_Register);
2375         ni_set_bits(dev,Interrupt_B_Enable_Register,~0,0);
2376         win_out(0x0010,AO_Personal_Register);
2377         win_out(0x3f98,Interrupt_B_Ack_Register);
2378         win_out(AO_BC_Source_Select | AO_UPDATE_Pulse_Width |
2379                 AO_TMRDACWR_Pulse_Width, AO_Personal_Register);
2380         win_out(0,AO_Output_Control_Register);
2381         win_out(0,AO_Start_Select_Register);
2382         devpriv->ao_cmd1=0;
2383         win_out(devpriv->ao_cmd1,AO_Command_1_Register);
2384         devpriv->ao_cmd2=0;
2385         devpriv->ao_mode1=0;
2386         devpriv->ao_mode2=0;
2387         devpriv->ao_mode3=0;
2388         devpriv->ao_trigger_select=0;
2389         if(boardtype.reg_type & ni_reg_6xxx_mask){
2390                 ao_win_out(0x3, AO_Immediate_671x);
2391                 ao_win_out(CLEAR_WG, AO_Misc_611x);
2392         }
2393
2394         return 0;
2395 }
2396
2397 static int ni_dio_insn_config(comedi_device *dev,comedi_subdevice *s,
2398         comedi_insn *insn,lsampl_t *data)
2399 {
2400 #ifdef DEBUG_DIO
2401         printk("ni_dio_insn_config() chan=%d io=%d\n",
2402                 CR_CHAN(insn->chanspec),data[0]);
2403 #endif
2404         if(insn->n!=1)return -EINVAL;
2405         switch(data[0]){
2406         case COMEDI_OUTPUT:
2407                 s->io_bits |= 1<<CR_CHAN(insn->chanspec);
2408                 break;
2409         case COMEDI_INPUT:
2410                 s->io_bits &= ~(1<<CR_CHAN(insn->chanspec));
2411                 break;
2412         default:
2413                 return -EINVAL;
2414         }
2415
2416         devpriv->dio_control &= ~DIO_Pins_Dir_Mask;
2417         devpriv->dio_control |= DIO_Pins_Dir(s->io_bits);
2418         win_out(devpriv->dio_control,DIO_Control_Register);
2419
2420         return 1;
2421 }
2422
2423 static int ni_dio_insn_bits(comedi_device *dev,comedi_subdevice *s,
2424         comedi_insn *insn,lsampl_t *data)
2425 {
2426 #ifdef DEBUG_DIO
2427         printk("ni_dio_insn_bits() mask=0x%x bits=0x%x\n",data[0],data[1]);
2428 #endif
2429         if(insn->n!=2)return -EINVAL;
2430         if(data[0]){
2431                 /* Perform check to make sure we're not using the
2432                    serial part of the dio */
2433                 if((data[0] & (DIO_SDIN | DIO_SDOUT)) && devpriv->serial_interval_ns)
2434                         return -EBUSY;
2435
2436                 s->state &= ~data[0];
2437                 s->state |= (data[0]&data[1]);
2438                 devpriv->dio_output &= ~DIO_Parallel_Data_Mask;
2439                 devpriv->dio_output |= DIO_Parallel_Data_Out(s->state);
2440                 win_out(devpriv->dio_output,DIO_Output_Register);
2441         }
2442         data[1] = win_in(DIO_Parallel_Input_Register);
2443
2444         return 2;
2445 }
2446
2447 static int ni_serial_insn_config(comedi_device *dev,comedi_subdevice *s,
2448                                  comedi_insn *insn,lsampl_t *data)
2449 {
2450         int err = insn->n;
2451         unsigned char byte_out, byte_in;
2452
2453         if(insn->n!=2)return -EINVAL;
2454
2455         switch(data[0]) {
2456         case INSN_CONFIG_SERIAL_CLOCK:
2457
2458 #ifdef DEBUG_DIO
2459                 printk("SPI serial clock Config cd\n", data[1]);
2460 #endif
2461                 devpriv->serial_hw_mode = 1;
2462                 devpriv->dio_control |= DIO_HW_Serial_Enable;
2463
2464                 if(data[1] == SERIAL_DISABLED) {
2465                         devpriv->serial_hw_mode = 0;
2466                         devpriv->dio_control &= ~(DIO_HW_Serial_Enable |
2467                                                   DIO_Software_Serial_Control);
2468                         data[1] = SERIAL_DISABLED;
2469                         devpriv->serial_interval_ns = data[1];
2470                 }
2471                 else if(data[1] <= SERIAL_600NS) {
2472                         /* Warning: this clock speed is too fast to reliably
2473                         control SCXI. */
2474                         devpriv->dio_control &= ~DIO_HW_Serial_Timebase;
2475                         devpriv->clock_and_fout |= Slow_Internal_Timebase;
2476                         devpriv->clock_and_fout &= ~DIO_Serial_Out_Divide_By_2;
2477                         data[1] = SERIAL_600NS;
2478                         devpriv->serial_interval_ns = data[1];
2479                 }
2480                 else if(data[1] <= SERIAL_1_2US) {
2481                         devpriv->dio_control &= ~DIO_HW_Serial_Timebase;
2482                         devpriv->clock_and_fout |= Slow_Internal_Timebase |
2483                                 DIO_Serial_Out_Divide_By_2;
2484                         data[1] = SERIAL_1_2US;
2485                         devpriv->serial_interval_ns = data[1];
2486                 }
2487                 else if(data[1] <= SERIAL_10US) {
2488                         devpriv->dio_control |= DIO_HW_Serial_Timebase;
2489                         devpriv->clock_and_fout |= Slow_Internal_Timebase |
2490                                 DIO_Serial_Out_Divide_By_2;
2491                         /* Note: DIO_Serial_Out_Divide_By_2 only affects
2492                         600ns/1.2us. If you turn divide_by_2 off with the
2493                         slow clock, you will still get 10us, except then
2494                         all your delays are wrong. */
2495                         data[1] = SERIAL_10US;
2496                         devpriv->serial_interval_ns = data[1];
2497                 }
2498                 else {
2499                         devpriv->dio_control &= ~(DIO_HW_Serial_Enable |
2500                                                   DIO_Software_Serial_Control);
2501                         devpriv->serial_hw_mode = 0;
2502                         data[1] = (data[1] / 1000) * 1000;
2503                         devpriv->serial_interval_ns = data[1];
2504                 }
2505
2506                 win_out(devpriv->dio_control,DIO_Control_Register);
2507                 win_out(devpriv->clock_and_fout,Clock_and_FOUT_Register);
2508                 return 1;
2509
2510         break;
2511
2512         case INSN_CONFIG_BIDIRECTIONAL_DATA:
2513
2514                 if(devpriv->serial_interval_ns == 0) {
2515                         return -EINVAL;
2516                 }
2517
2518                 byte_out = data[1] & 0xFF;
2519
2520                 if(devpriv->serial_hw_mode) {
2521                         err = ni_serial_hw_readwrite8(dev,s,byte_out,&byte_in);
2522                 } else if(devpriv->serial_interval_ns > 0) {
2523                         err = ni_serial_sw_readwrite8(dev,s,byte_out,&byte_in);
2524                 } else {
2525                         printk("ni_serial_insn_config: serial disabled!\n");
2526                         return -EINVAL;
2527                 }
2528                 if(err < 0) return err;
2529                 data[1] = byte_in & 0xFF;
2530                 return insn->n;
2531
2532         break;
2533         default:
2534                 return -EINVAL;
2535         }
2536
2537 }
2538
2539 static int ni_serial_hw_readwrite8(comedi_device *dev,comedi_subdevice *s,
2540                                    unsigned char data_out,
2541                                    unsigned char *data_in)
2542 {
2543         unsigned int status1;
2544         int err = 0, count = 20;
2545
2546 #ifdef DEBUG_DIO
2547         printk("ni_serial_hw_readwrite8: outputting 0x%x\n", data_out);
2548 #endif
2549
2550         devpriv->dio_output &= ~DIO_Serial_Data_Mask;
2551         devpriv->dio_output |= DIO_Serial_Data_Out(data_out);
2552         win_out(devpriv->dio_output,DIO_Output_Register);
2553
2554         status1 = win_in(Joint_Status_1_Register);
2555         if(status1 & DIO_Serial_IO_In_Progress_St) {
2556                 err = -EBUSY;
2557                 goto Error;
2558         }
2559
2560         devpriv->dio_control |= DIO_HW_Serial_Start;
2561         win_out(devpriv->dio_control,DIO_Control_Register);
2562         devpriv->dio_control &= ~DIO_HW_Serial_Start;
2563
2564         /* Wait until STC says we're done, but don't loop infinitely. */
2565         while((status1 = win_in(Joint_Status_1_Register)) & DIO_Serial_IO_In_Progress_St) {
2566                 /* Delay one bit per loop */
2567                 comedi_udelay((devpriv->serial_interval_ns + 999) / 1000);
2568                 if(--count < 0) {
2569                         printk("ni_serial_hw_readwrite8: SPI serial I/O didn't finish in time!\n");
2570                         err = -ETIME;
2571                         goto Error;
2572                 }
2573         }
2574
2575         /* Delay for last bit. This delay is absolutely necessary, because
2576            DIO_Serial_IO_In_Progress_St goes high one bit too early. */
2577         comedi_udelay((devpriv->serial_interval_ns + 999) / 1000);
2578
2579         if(data_in != NULL) {
2580                 *data_in = win_in(DIO_Serial_Input_Register);
2581 #ifdef DEBUG_DIO
2582                 printk("ni_serial_hw_readwrite8: inputted 0x%x\n", *data_in);
2583 #endif
2584         }
2585
2586  Error:
2587         win_out(devpriv->dio_control,DIO_Control_Register);
2588
2589         return err;
2590 }
2591
2592 static int ni_serial_sw_readwrite8(comedi_device *dev,comedi_subdevice *s,
2593                                    unsigned char data_out,
2594                                    unsigned char *data_in)
2595 {
2596         unsigned char mask, input = 0;
2597
2598 #ifdef DEBUG_DIO
2599         printk("ni_serial_sw_readwrite8: outputting 0x%x\n", data_out);
2600 #endif
2601
2602         /* Wait for one bit before transfer */
2603         comedi_udelay((devpriv->serial_interval_ns + 999) / 1000);
2604
2605         for(mask = 0x80; mask; mask >>= 1) {
2606                 /* Output current bit; note that we cannot touch s->state
2607            because it is a per-subdevice field, and serial is
2608                    a separate subdevice from DIO. */
2609                 devpriv->dio_output &= ~DIO_SDOUT;
2610                 if(data_out & mask) {
2611                         devpriv->dio_output |= DIO_SDOUT;
2612                 }
2613                 win_out(devpriv->dio_output,DIO_Output_Register);
2614
2615                 /* Assert SDCLK (active low, inverted), wait for half of
2616                    the delay, deassert SDCLK, and wait for the other half. */
2617                 devpriv->dio_control |= DIO_Software_Serial_Control;
2618                 win_out(devpriv->dio_control,DIO_Control_Register);
2619
2620                 comedi_udelay((devpriv->serial_interval_ns + 999) / 2000);
2621
2622                 devpriv->dio_control &= ~DIO_Software_Serial_Control;
2623                 win_out(devpriv->dio_control,DIO_Control_Register);
2624
2625                 comedi_udelay((devpriv->serial_interval_ns + 999) / 2000);
2626
2627                 /* Input current bit */
2628                 if(win_in(DIO_Parallel_Input_Register) & DIO_SDIN) {
2629 /*                      printk("DIO_P_I_R: 0x%x\n", win_in(DIO_Parallel_Input_Register)); */
2630                         input |= mask;
2631                 }
2632         }
2633 #ifdef DEBUG_DIO
2634         printk("ni_serial_sw_readwrite8: inputted 0x%x\n", input);
2635 #endif
2636         if(data_in) *data_in = input;
2637
2638         return 0;
2639 }
2640
2641 static void mio_common_detach(comedi_device *dev)
2642 {
2643         if(dev->subdevices && boardtype.has_8255)
2644                 subdev_8255_cleanup(dev,dev->subdevices+3);
2645 }
2646
2647 static void init_ao_67xx(comedi_device *dev, comedi_subdevice *s)
2648 {
2649         int i;
2650
2651         for(i = 0; i < s->n_chan; i++)
2652                 ni_ao_win_outw(dev, AO_Channel(i) | 0x0, AO_Configuration_2_67xx);
2653 }
2654
2655 static int ni_alloc_private(comedi_device *dev)
2656 {
2657         int ret;
2658
2659         ret = alloc_private(dev, sizeof(ni_private));
2660         if(ret < 0) return ret;
2661
2662         spin_lock_init(&devpriv->window_lock);
2663
2664         return 0;
2665 };
2666
2667 static int ni_E_init(comedi_device *dev,comedi_devconfig *it)
2668 {
2669         comedi_subdevice *s;
2670         int bits;
2671
2672         if(alloc_subdevices(dev, 10) < 0)
2673                 return -ENOMEM;
2674
2675         /* analog input subdevice */
2676
2677         s=dev->subdevices+0;
2678         dev->read_subdev=s;
2679         if(boardtype.n_adchan){
2680                 s->type=COMEDI_SUBD_AI;
2681                 s->subdev_flags=SDF_READABLE|SDF_DIFF;
2682                 if(boardtype.reg_type == ni_reg_normal)
2683                         s->subdev_flags |= SDF_GROUND | SDF_COMMON | SDF_OTHER;
2684                 s->subdev_flags|=SDF_DITHER;
2685                 s->n_chan=boardtype.n_adchan;
2686                 s->len_chanlist=512;
2687                 s->maxdata=(1<<boardtype.adbits)-1;
2688                 s->range_table=ni_range_lkup[boardtype.gainlkup];
2689                 s->insn_read=ni_ai_insn_read;
2690                 s->insn_config=ni_ai_insn_config;
2691                 s->do_cmdtest=ni_ai_cmdtest;
2692                 s->do_cmd=ni_ai_cmd;
2693                 s->cancel=ni_ai_reset;
2694                 s->poll=ni_ai_poll;
2695                 s->munge=ni_ai_munge;
2696         }else{
2697                 s->type=COMEDI_SUBD_UNUSED;
2698         }
2699
2700         /* analog output subdevice */
2701
2702         s=dev->subdevices+1;
2703         if(boardtype.n_aochan){
2704                 dev->write_subdev=s;
2705                 s->type=COMEDI_SUBD_AO;
2706                 s->subdev_flags=SDF_WRITABLE|SDF_DEGLITCH|SDF_GROUND;
2707                 s->n_chan=boardtype.n_aochan;
2708                 s->maxdata=(1<<boardtype.aobits)-1;
2709                 if(boardtype.ao_unipolar){
2710                         s->range_table=&range_ni_E_ao_ext;      /* XXX wrong for some boards */
2711                 }else{
2712                         s->range_table=&range_bipolar10;
2713                 }
2714                 s->insn_read=ni_ao_insn_read;
2715                 if(boardtype.reg_type & ni_reg_6xxx_mask){
2716                         s->insn_write=ni_ao_insn_write_671x;
2717                 }else{
2718                         s->insn_write=ni_ao_insn_write;
2719                 }
2720                 if(boardtype.ao_fifo_depth){
2721                         s->do_cmd=ni_ao_cmd;
2722                         s->do_cmdtest=ni_ao_cmdtest;
2723                         s->len_chanlist = boardtype.n_aochan;
2724                         s->munge=ni_ao_munge;
2725                 }
2726                 s->cancel=ni_ao_reset;
2727         }else{
2728                 s->type=COMEDI_SUBD_UNUSED;
2729         }
2730         if((boardtype.reg_type & ni_reg_67xx_mask))
2731                 init_ao_67xx(dev, s);
2732
2733         /* digital i/o subdevice */
2734
2735         s=dev->subdevices+2;
2736         s->type=COMEDI_SUBD_DIO;
2737         s->subdev_flags=SDF_WRITABLE|SDF_READABLE;
2738         s->n_chan=8;
2739         s->maxdata=1;
2740         s->range_table=&range_digital;
2741         s->io_bits=0;           /* all bits input */
2742         s->insn_bits=ni_dio_insn_bits;
2743         s->insn_config=ni_dio_insn_config;
2744
2745         /* dio setup */
2746         devpriv->dio_control = DIO_Pins_Dir(s->io_bits);
2747         win_out(devpriv->dio_control,DIO_Control_Register);
2748         
2749         /* 8255 device */
2750         s=dev->subdevices+3;
2751         if(boardtype.has_8255){
2752                 subdev_8255_init(dev,s,ni_8255_callback,(unsigned long)dev);
2753         }else{
2754                 s->type=COMEDI_SUBD_UNUSED;
2755         }
2756
2757         /* general purpose counter/timer device */
2758         s=dev->subdevices+4;
2759         s->type=COMEDI_SUBD_COUNTER;
2760         s->subdev_flags=SDF_READABLE|SDF_WRITABLE;
2761         s->insn_read=  ni_gpct_insn_read;
2762         s->insn_write= ni_gpct_insn_write;
2763         s->insn_config=ni_gpct_insn_config;
2764         s->n_chan=2;
2765         s->maxdata=1;
2766         devpriv->an_trig_etc_reg = 0;
2767         GPCT_Reset(dev,0);
2768         GPCT_Reset(dev,1);
2769
2770         /* calibration subdevice -- ai and ao */
2771         s=dev->subdevices+5;
2772         s->type=COMEDI_SUBD_CALIB;
2773         s->subdev_flags=SDF_WRITABLE|SDF_INTERNAL;
2774         s->insn_read=ni_calib_insn_read;
2775         s->insn_write=ni_calib_insn_write;
2776         caldac_setup(dev,s);
2777
2778         /* EEPROM */
2779         s=dev->subdevices+6;
2780         s->type=COMEDI_SUBD_MEMORY;
2781         s->subdev_flags=SDF_READABLE|SDF_INTERNAL;
2782         s->n_chan=512;
2783         s->maxdata=0xff;
2784         s->insn_read=ni_eeprom_insn_read;
2785
2786         /* PFI */
2787         s=dev->subdevices+7;
2788         s->type=COMEDI_SUBD_DIO;
2789         s->subdev_flags=SDF_READABLE|SDF_WRITABLE|SDF_INTERNAL;
2790         s->n_chan=10;
2791         s->maxdata=1;
2792         s->insn_bits = ni_pfi_insn_bits;
2793         s->insn_config = ni_pfi_insn_config;
2794         ni_set_bits(dev, IO_Bidirection_Pin_Register, ~0, 0);
2795
2796         /* cs5529 calibration adc */
2797         s = dev->subdevices + 8;
2798         if(boardtype.reg_type & ni_reg_67xx_mask)
2799         {
2800                 s->type = COMEDI_SUBD_AI;
2801                 s->subdev_flags = SDF_READABLE | SDF_DIFF | SDF_INTERNAL;
2802                 // one channel for each analog output channel
2803                 s->n_chan = boardtype.n_aochan;
2804                 s->maxdata = (1 << 16) - 1;
2805                 s->range_table = &range_unknown; /* XXX */
2806                 s->insn_read=cs5529_ai_insn_read;
2807                 s->insn_config=NULL;
2808                 init_cs5529(dev);
2809         }else
2810         {
2811                 s->type=COMEDI_SUBD_UNUSED;
2812         }
2813
2814         /* Serial */
2815         s=dev->subdevices+9;
2816         s->type=COMEDI_SUBD_SERIAL;
2817         s->subdev_flags=SDF_READABLE|SDF_WRITABLE|SDF_INTERNAL;
2818         s->n_chan=1;
2819         s->maxdata=0xff;
2820         s->insn_config = ni_serial_insn_config;
2821         devpriv->serial_interval_ns = 0;
2822         devpriv->serial_hw_mode = 0;
2823
2824         /* ai configuration */
2825         ni_ai_reset(dev,dev->subdevices+0);
2826         if(boardtype.reg_type == ni_reg_normal){
2827                 devpriv->clock_and_fout =
2828                         Slow_Internal_Time_Divide_By_2 |
2829                         Slow_Internal_Timebase |
2830                         Clock_To_Board_Divide_By_2 |
2831                         Clock_To_Board |
2832                         AI_Output_Divide_By_2 |
2833                         AO_Output_Divide_By_2;
2834         }else{
2835                 devpriv->clock_and_fout =
2836                         Slow_Internal_Time_Divide_By_2 |
2837                         Slow_Internal_Timebase |
2838                         Clock_To_Board_Divide_By_2 |
2839                         Clock_To_Board;
2840         }
2841         win_out(devpriv->clock_and_fout, Clock_and_FOUT_Register);
2842
2843         /* analog output configuration */
2844         ni_ao_reset(dev,dev->subdevices + 1);
2845
2846         if(dev->irq){
2847                 win_out((IRQ_POLARITY?Interrupt_Output_Polarity:0) |
2848                         (Interrupt_Output_On_3_Pins&0) |
2849                         Interrupt_A_Enable |
2850                         Interrupt_B_Enable |
2851                         Interrupt_A_Output_Select(interrupt_pin(dev->irq)) |
2852                         Interrupt_B_Output_Select(interrupt_pin(dev->irq)),
2853                         Interrupt_Control_Register
2854                 );
2855         }
2856
2857         /* DMA setup */
2858         /* tell the STC which dma channels to use for AI and AO */
2859         bits = 1 << ( AI_DMA_CHAN );
2860         bits |= 1 << ( AO_DMA_CHAN + 4 );
2861         ni_writeb( bits, AI_AO_Select);
2862         /* tell the STC which dma channels to use for
2863          * General purpose counters 0 and 1 */
2864         bits = 1 << ( GPC0_DMA_CHAN );
2865         bits |= 1 << ( GPC1_DMA_CHAN + 4 );
2866         ni_writeb( bits, G0_G1_Select);
2867
2868         /* 611x init */
2869         if(boardtype.reg_type != ni_reg_normal)
2870         {
2871                 ni_writeb( 0, Magic_611x );
2872         }
2873
2874         printk("\n");
2875
2876         return 0;
2877 }
2878
2879
2880
2881 static int ni_8255_callback(int dir,int port,int data,unsigned long arg)
2882 {
2883         comedi_device *dev=(comedi_device *)arg;
2884
2885         if(dir){
2886                 ni_writeb(data,Port_A+2*port);
2887                 return 0;
2888         }else{
2889                 return ni_readb(Port_A+2*port);
2890         }
2891 }
2892
2893 /*
2894         presents the EEPROM as a subdevice
2895 */
2896
2897 static int ni_eeprom_insn_read(comedi_device *dev,comedi_subdevice *s,
2898         comedi_insn *insn,lsampl_t *data)
2899 {
2900         data[0]=ni_read_eeprom(dev,CR_CHAN(insn->chanspec));
2901
2902         return 1;
2903 }
2904
2905 /*
2906         reads bytes out of eeprom
2907 */
2908
2909 static int ni_read_eeprom(comedi_device *dev,int addr)
2910 {
2911         int bit;
2912         int bitstring;
2913
2914         bitstring=0x0300|((addr&0x100)<<3)|(addr&0xff);
2915         ni_writeb(0x04,Serial_Command);
2916         for(bit=0x8000;bit;bit>>=1){
2917                 ni_writeb(0x04|((bit&bitstring)?0x02:0),Serial_Command);
2918                 ni_writeb(0x05|((bit&bitstring)?0x02:0),Serial_Command);
2919         }
2920         bitstring=0;
2921         for(bit=0x80;bit;bit>>=1){
2922                 ni_writeb(0x04,Serial_Command);
2923                 ni_writeb(0x05,Serial_Command);
2924                 bitstring|=((ni_readb(XXX_Status)&PROMOUT)?bit:0);
2925         }
2926         ni_writeb(0x00,Serial_Command);
2927
2928         return bitstring;
2929 }
2930
2931 static void ni_write_caldac(comedi_device *dev,int addr,int val);
2932 /*
2933         calibration subdevice
2934 */
2935 static int ni_calib_insn_write(comedi_device *dev,comedi_subdevice *s,
2936         comedi_insn *insn,lsampl_t *data)
2937 {
2938         ni_write_caldac(dev,CR_CHAN(insn->chanspec),data[0]);
2939
2940         return 1;
2941 }
2942
2943 static int ni_calib_insn_read(comedi_device *dev,comedi_subdevice *s,
2944         comedi_insn *insn,lsampl_t *data)
2945 {
2946         data[0] = devpriv->caldacs[CR_CHAN(insn->chanspec)];
2947
2948         return 1;
2949 }
2950
2951 static int pack_mb88341(int addr,int val,int *bitstring);
2952 static int pack_dac8800(int addr,int val,int *bitstring);
2953 static int pack_dac8043(int addr,int val,int *bitstring);
2954 static int pack_ad8522(int addr,int val,int *bitstring);
2955 static int pack_ad8804(int addr,int val,int *bitstring);
2956 static int pack_ad8842(int addr,int val,int *bitstring);
2957
2958 struct caldac_struct{
2959         int n_chans;
2960         int n_bits;
2961         int (*packbits)(int,int,int *);
2962 };
2963
2964 static struct caldac_struct caldacs[] = {
2965         [mb88341] = { 12, 8, pack_mb88341 },
2966         [dac8800] = { 8, 8, pack_dac8800 },
2967         [dac8043] = { 1, 12, pack_dac8043 },
2968         [ad8522]  = { 2, 12, pack_ad8522 },
2969         [ad8804] = { 12, 8, pack_ad8804 },
2970         [ad8842] = { 8, 8, pack_ad8842 },
2971         [ad8804_debug] = { 16, 8, pack_ad8804 },
2972 };
2973
2974 static void caldac_setup(comedi_device *dev,comedi_subdevice *s)
2975 {
2976         int i,j;
2977         int n_dacs;
2978         int n_chans=0;
2979         int n_bits;
2980         int diffbits=0;
2981         int type;
2982         int chan;
2983
2984         type = boardtype.caldac[0];
2985         if(type==caldac_none)return;
2986         n_bits=caldacs[type].n_bits;
2987         for(i=0;i<3;i++){
2988                 type = boardtype.caldac[i];
2989                 if(type==caldac_none)break;
2990                 if(caldacs[type].n_bits!=n_bits)diffbits=1;
2991                 n_chans+=caldacs[type].n_chans;
2992         }
2993         n_dacs=i;
2994         s->n_chan=n_chans;
2995
2996         if(diffbits){
2997
2998                 if(n_chans>MAX_N_CALDACS){
2999                         printk("BUG! MAX_N_CALDACS too small\n");
3000                 }
3001                 s->maxdata_list=devpriv->caldac_maxdata_list;
3002                 chan=0;
3003                 for(i=0;i<n_dacs;i++){
3004                         type = boardtype.caldac[i];
3005                         for(j=0;j<caldacs[type].n_chans;j++){
3006                                 s->maxdata_list[chan]=
3007                                         (1<<caldacs[type].n_bits)-1;
3008                                 chan++;
3009                         }
3010                 }
3011
3012                 for( chan = 0; chan < s->n_chan; chan++ )
3013                         ni_write_caldac( dev, i, s->maxdata_list[ i ] / 2 );
3014         }else{
3015                 type = boardtype.caldac[0];
3016                 s->maxdata=(1<<caldacs[type].n_bits)-1;
3017
3018                 for( chan = 0; chan < s->n_chan; chan++ )
3019                         ni_write_caldac( dev, i, s->maxdata / 2 );
3020         }
3021 }
3022
3023 static void ni_write_caldac(comedi_device *dev,int addr,int val)
3024 {
3025         unsigned int loadbit=0,bits=0,bit,bitstring=0;
3026         int i;
3027         int type;
3028
3029         //printk("ni_write_caldac: chan=%d val=%d\n",addr,val);
3030         if( devpriv->caldacs[ addr ] == val ) return;
3031         devpriv->caldacs[ addr ] = val;
3032
3033         for(i=0;i<3;i++){
3034                 type = boardtype.caldac[i];
3035                 if(type==caldac_none)break;
3036                 if(addr<caldacs[type].n_chans){
3037                         bits=caldacs[type].packbits(addr,val,&bitstring);
3038                         loadbit=SerDacLd(i);
3039                         //printk("caldac: using i=%d addr=%d %x\n",i,addr,bitstring);
3040                         break;
3041                 }
3042                 addr-=caldacs[type].n_chans;
3043         }
3044
3045         for(bit=1<<(bits-1);bit;bit>>=1){
3046                 ni_writeb(((bit&bitstring)?0x02:0),Serial_Command);
3047                 comedi_udelay(1);
3048                 ni_writeb(1|((bit&bitstring)?0x02:0),Serial_Command);
3049                 comedi_udelay(1);
3050         }
3051         ni_writeb(loadbit,Serial_Command);
3052         comedi_udelay(1);
3053         ni_writeb(0,Serial_Command);
3054 }
3055
3056
3057
3058 static int pack_mb88341(int addr,int val,int *bitstring)
3059 {
3060         /*
3061            Fujitsu MB 88341
3062            Note that address bits are reversed.  Thanks to
3063            Ingo Keen for noticing this.
3064
3065            Note also that the 88341 expects address values from
3066            1-12, whereas we use channel numbers 0-11.  The NI
3067            docs use 1-12, also, so be careful here.
3068         */
3069         addr++;
3070         *bitstring=((addr&0x1)<<11) |
3071                   ((addr&0x2)<<9)  |
3072                   ((addr&0x4)<<7)  |
3073                   ((addr&0x8)<<5)  |
3074                   (val&0xff);
3075         return 12;
3076 }
3077
3078 static int pack_dac8800(int addr,int val,int *bitstring)
3079 {
3080         *bitstring=((addr&0x7)<<8)|(val&0xff);
3081         return 11;
3082 }
3083
3084 static int pack_dac8043(int addr,int val,int *bitstring)
3085 {
3086         *bitstring=val&0xfff;
3087         return 12;
3088 }
3089         
3090 static int pack_ad8522(int addr,int val,int *bitstring)
3091 {
3092         *bitstring=(val&0xfff)|(addr ? 0xc000:0xa000);
3093         return 16;
3094 }
3095
3096 static int pack_ad8804(int addr,int val,int *bitstring)
3097 {
3098         *bitstring=((addr&0xf)<<8) | (val&0xff);
3099         return 12;
3100 }
3101
3102 static int pack_ad8842(int addr,int val,int *bitstring)
3103 {
3104         *bitstring=((addr+1)<<8) | (val&0xff);
3105         return 12;
3106 }
3107
3108
3109
3110
3111
3112 /*
3113  *
3114  *  General Purpose Counter/Timer section
3115  *
3116  */
3117
3118 /*
3119  * Low level stuff...Each STC counter has two 24 bit load registers
3120  * (A&B).  Just make it easier to access them.
3121  *
3122  * These are inlined _only_ because they are used once in subsequent
3123  * code.  Otherwise they should not be inlined.
3124  */
3125 static inline void GPCT_Load_A(comedi_device *dev, int chan, unsigned int value)
3126 {
3127         win_out2( value & 0x00ffffff, G_Load_A_Register(chan));
3128 }
3129
3130 static inline void GPCT_Load_B(comedi_device *dev, int chan, unsigned int value)
3131 {
3132         win_out2( value & 0x00ffffff, G_Load_B_Register(chan));
3133 }
3134
3135 /*  Load a value into the counter, using register A as the intermediate step.
3136 *  You might use GPCT_Load_Using_A to load a 0x000000 into a counter
3137 *  reset its value.
3138 */
3139 static void GPCT_Load_Using_A(comedi_device *dev, int chan, unsigned int value)
3140 {
3141         devpriv->gpct_mode[chan] &= (~G_Load_Source_Select);
3142         win_out( devpriv->gpct_mode[chan],G_Mode_Register(chan));
3143         GPCT_Load_A(dev,chan,value);
3144         win_out( devpriv->gpct_command[chan]|G_Load,G_Command_Register(chan));
3145 }
3146
3147 /*
3148  *      Read the GPCTs current value.  
3149  */
3150 static int GPCT_G_Watch(comedi_device *dev, int chan)
3151 {
3152         unsigned int hi1,hi2,lo;
3153         
3154         devpriv->gpct_command[chan] &= ~G_Save_Trace;
3155         win_out( devpriv->gpct_command[chan],G_Command_Register(chan));
3156         
3157         devpriv->gpct_command[chan] |= G_Save_Trace;
3158         win_out( devpriv->gpct_command[chan], G_Command_Register(chan));
3159
3160         /* This procedure is used because the two registers cannot
3161          * be read atomically. */
3162         do{
3163                 hi1 = win_in( G_Save_Register_High(chan));
3164                 lo = win_in(G_Save_Register_Low(chan));
3165                 hi2 = win_in( G_Save_Register_High(chan));
3166         }while(hi1!=hi2);
3167
3168         return (hi1<<16)|lo;
3169 }
3170
3171
3172 static int GPCT_Disarm(comedi_device *dev, int chan)
3173 {
3174         win_out( devpriv->gpct_command[chan] | G_Disarm,G_Command_Register(chan));
3175         return 0;
3176 }
3177
3178
3179 static int GPCT_Arm(comedi_device *dev, int chan)
3180 {
3181         win_out( devpriv->gpct_command[chan] | G_Arm,G_Command_Register(chan));
3182         /* If the counter is doing pulse width measurement, then make
3183          sure that the counter did not start counting right away.  This would
3184          indicate that we started acquiring the pulse after it had already 
3185          started and our measurement would be inaccurate */
3186         if(devpriv->gpct_cur_operation[chan] == GPCT_SINGLE_PW){
3187                 int g_status; 
3188
3189                 g_status=win_in(G_Status_Register);
3190                 
3191                 if(chan == 0){
3192                         //TIM 5/2/01 possible error with very short pulses
3193                         if((G0_Counting_St & g_status)|| !(G0_Armed_St&g_status)) {
3194                                 //error: we missed the beginning of the pulse
3195                                 return -EINVAL; //there is probably a more accurate error code...
3196                         }
3197                 }else{
3198                         if((G1_Counting_St & g_status)|| !(G1_Armed_St&g_status)) {
3199                                 //error: we missed the beginning of the pulse
3200                                 return -EINVAL;
3201                         }
3202                 }
3203         }
3204         return 0;
3205 }
3206
3207 static int GPCT_Set_Source(comedi_device *dev,int chan ,int source)
3208 {
3209         //printk("GPCT_Set_Source...");
3210         devpriv->gpct_input_select[chan] &= ~G_Source_Select(0x1f);//reset gate to 0
3211         switch(source) {
3212                 case GPCT_INT_CLOCK:
3213                 devpriv->gpct_input_select[chan] |= G_Source_Select(0);//INT_TIMEBASE
3214                 break;
3215         case GPCT_EXT_PIN:
3216                 if(chan==0)
3217                         devpriv->gpct_input_select[chan] |= G_Source_Select(9);//PFI8
3218                 else
3219                         devpriv->gpct_input_select[chan] |= G_Source_Select(4);//PFI3
3220                 break;
3221         default:
3222                 return -EINVAL;
3223         }
3224         win_out(devpriv->gpct_input_select[chan], G_Input_Select_Register(chan));
3225         //printk("exit GPCT_Set_Source\n");
3226         return 0;
3227 }
3228
3229 static int GPCT_Set_Gate(comedi_device *dev,int chan ,int gate)
3230 {
3231         //printk("GPCT_Set_Gate...");
3232         devpriv->gpct_input_select[chan] &= ~G_Gate_Select(0x1f);//reset gate to 0
3233         switch(gate) {
3234         case GPCT_NO_GATE:
3235                 devpriv->gpct_input_select[chan] |= G_Gate_Select(31);//Low
3236                 devpriv->gpct_mode[chan] |= G_Gate_Polarity;
3237                 break;
3238         case GPCT_EXT_PIN:
3239                 devpriv->gpct_mode[chan] &= ~G_Gate_Polarity;
3240                 if(chan==0){
3241                         devpriv->gpct_input_select[chan] |= G_Gate_Select(10);//PFI9
3242                 }else{
3243                         devpriv->gpct_input_select[chan] |= G_Gate_Select(5);//PFI4
3244                 }
3245                 break;
3246         default:
3247                 return -EINVAL;
3248         }
3249         win_out(devpriv->gpct_input_select[chan], G_Input_Select_Register(chan));
3250         win_out(devpriv->gpct_mode[chan], G_Mode_Register(chan));
3251         //printk("exit GPCT_Set_Gate\n");
3252         return 0;
3253 }
3254
3255 static int GPCT_Set_Direction(comedi_device *dev,int chan,int direction)
3256 {
3257         //printk("GPCT_Set_Direction...");
3258         
3259         devpriv->gpct_command[chan] &= ~G_Up_Down(0x3);
3260         switch (direction) {
3261                 case GPCT_UP:
3262                         devpriv->gpct_command[chan] |= G_Up_Down(1);
3263                         break;
3264                 case GPCT_DOWN:
3265                         devpriv->gpct_command[chan] |= G_Up_Down(0);
3266                         break;
3267                 case GPCT_HWUD:
3268                         devpriv->gpct_command[chan] |= G_Up_Down(2);
3269                         break;
3270                 default:
3271                         printk("Error direction=0x%08x..",direction);
3272                         return -EINVAL;
3273         }
3274         win_out(devpriv->gpct_command[chan], G_Command_Register(chan));
3275         //TIM 4/23/01 win_out(devpriv->gpct_mode[chan], G_Mode_Register(chan));
3276         //printk("exit GPCT_Set_Direction\n");
3277         return 0;
3278 }
3279
3280 static void GPCT_Event_Counting(comedi_device *dev,int chan)
3281 {
3282
3283         //NOTE: possible residual bits from multibit masks can corrupt
3284         //If you config for several measurements between Resets, watch out!
3285         
3286         //printk("GPCT_Event_Counting...");
3287         
3288         devpriv->gpct_cur_operation[chan] = GPCT_SIMPLE_EVENT;
3289         
3290         // Gating_Mode = 1
3291         devpriv->gpct_mode[chan] &= ~(G_Gating_Mode(0x3));
3292         devpriv->gpct_mode[chan] |= G_Gating_Mode(1);
3293         
3294         // Trigger_Mode_For_Edge_Gate = 1
3295         devpriv->gpct_mode[chan] &= ~(G_Trigger_Mode_For_Edge_Gate(0x3));
3296         devpriv->gpct_mode[chan] |= G_Trigger_Mode_For_Edge_Gate(2);
3297
3298         win_out( devpriv->gpct_mode[chan],G_Mode_Register(chan));
3299         //printk("exit GPCT_Event_Counting\n");
3300 }
3301
3302 static void GPCT_Period_Meas(comedi_device *dev, int chan)
3303 {
3304         //printk("GPCT_Period_Meas...");
3305         
3306         devpriv->gpct_cur_operation[chan] = GPCT_SINGLE_PERIOD;
3307
3308         
3309         //NOTE: possible residual bits from multibit masks can corrupt
3310         //If you config for several measurements between Resets, watch out!     
3311         devpriv->gpct_mode[chan] &= ~G_OR_Gate;
3312         devpriv->gpct_mode[chan] &= ~G_Gate_Select_Load_Source;
3313         
3314         // Output_Mode = 3 
3315         devpriv->gpct_mode[chan] &= ~(G_Output_Mode(0x3));
3316         devpriv->gpct_mode[chan] |= G_Output_Mode(3);
3317         
3318         
3319         //Gating Mode=2
3320         devpriv->gpct_mode[chan] &= ~(G_Gating_Mode(0x3));
3321         devpriv->gpct_mode[chan] |= G_Gating_Mode(2);
3322         
3323         // Trigger_Mode_For_Edge_Gate=0
3324         devpriv->gpct_mode[chan] &= ~(G_Trigger_Mode_For_Edge_Gate(0x3));
3325         devpriv->gpct_mode[chan] |= G_Trigger_Mode_For_Edge_Gate(0);
3326
3327         devpriv->gpct_mode[chan] |= G_Reload_Source_Switching;
3328         devpriv->gpct_mode[chan] &= ~G_Loading_On_Gate;
3329         devpriv->gpct_mode[chan] &= ~G_Loading_On_TC;
3330         devpriv->gpct_mode[chan] &= ~G_Gate_On_Both_Edges;
3331
3332         // Stop_Mode = 2
3333         devpriv->gpct_mode[chan] &= ~(G_Stop_Mode(0x3));
3334         devpriv->gpct_mode[chan] |= G_Stop_Mode(0);
3335         
3336         // Counting_Once = 2 
3337         devpriv->gpct_mode[chan] &= ~(G_Counting_Once(0x3));
3338         devpriv->gpct_mode[chan] |= G_Counting_Once(2);
3339
3340         // Up_Down = 1 
3341         devpriv->gpct_command[chan] &= ~(G_Up_Down(0x3));
3342         devpriv->gpct_command[chan] |= G_Up_Down(1);
3343
3344         win_out( devpriv->gpct_mode[chan],G_Mode_Register(chan));
3345         win_out( devpriv->gpct_command[chan],G_Command_Register(chan));
3346         //printk("exit GPCT_Period_Meas\n");
3347 }
3348
3349 static void GPCT_Pulse_Width_Meas(comedi_device *dev, int chan)
3350 {
3351         //printk("GPCT_Pulse_Width_Meas...");
3352
3353         devpriv->gpct_cur_operation[chan] = GPCT_SINGLE_PW;
3354
3355         devpriv->gpct_mode[chan] &= ~G_OR_Gate;
3356         devpriv->gpct_mode[chan] &= ~G_Gate_Select_Load_Source;
3357
3358         // Output_Mode = 3 
3359         devpriv->gpct_mode[chan] &= ~(G_Output_Mode(0x3));
3360         devpriv->gpct_mode[chan] |= G_Output_Mode(3);
3361         
3362         //Gating Mode=1
3363         devpriv->gpct_mode[chan] &= ~(G_Gating_Mode(0x3));
3364         devpriv->gpct_mode[chan] |= G_Gating_Mode(1);//TIM 4/24/01 was 2
3365         
3366         // Trigger_Mode_For_Edge_Gate=2
3367         devpriv->gpct_mode[chan] &= ~(G_Trigger_Mode_For_Edge_Gate(0x3));
3368         devpriv->gpct_mode[chan] |= G_Trigger_Mode_For_Edge_Gate(2);//TIM 4/24/01 was 0
3369
3370
3371         devpriv->gpct_mode[chan] |= G_Reload_Source_Switching;//TIM 4/24/01 was 1
3372         devpriv->gpct_mode[chan] &= ~G_Loading_On_Gate;//TIM 4/24/01 was 0
3373
3374         devpriv->gpct_mode[chan] &= ~G_Loading_On_TC;
3375         devpriv->gpct_mode[chan] &= ~G_Gate_On_Both_Edges;
3376
3377         // Stop_Mode = 0
3378         devpriv->gpct_mode[chan] &= ~(G_Stop_Mode(0x3));
3379         devpriv->gpct_mode[chan] |= G_Stop_Mode(0);
3380         
3381         // Counting_Once = 2 
3382         devpriv->gpct_mode[chan] &= ~(G_Counting_Once(0x3));
3383         devpriv->gpct_mode[chan] |= G_Counting_Once(2);
3384
3385         // Up_Down = 1 
3386         devpriv->gpct_command[chan] &= ~(G_Up_Down(0x3));
3387         devpriv->gpct_command[chan] |= G_Up_Down(1);
3388
3389         win_out( devpriv->gpct_mode[chan],G_Mode_Register(chan));
3390         win_out( devpriv->gpct_command[chan],G_Command_Register(chan));
3391
3392         //printk("exit GPCT_Pulse_Width_Meas\n");
3393 }
3394
3395 /* GPCT_Gen_Single_Pulse() creates pulse of length pulsewidth which starts after the Arm
3396 signal is sent.  The pulse is delayed by the value already in the counter.  This function could
3397 be modified to send a pulse in response to a trigger event at its gate.*/
3398 static void GPCT_Gen_Single_Pulse(comedi_device *dev, int chan, unsigned int length)
3399 {
3400         //printk("GPCT_Gen_Cont...");
3401
3402         devpriv->gpct_cur_operation[chan] = GPCT_SINGLE_PULSE_OUT;
3403
3404         // Set length of the pulse
3405         GPCT_Load_B(dev,chan, length-1);
3406
3407         //Load next time using B, This is reset by GPCT_Load_Using_A()
3408         devpriv->gpct_mode[chan] |= G_Load_Source_Select;
3409         
3410         devpriv->gpct_mode[chan] &= ~G_OR_Gate;
3411         devpriv->gpct_mode[chan] &= ~G_Gate_Select_Load_Source;
3412
3413         // Output_Mode = 3 
3414         devpriv->gpct_mode[chan] &= ~(G_Output_Mode(0x3));
3415         devpriv->gpct_mode[chan] |= G_Output_Mode(2); //TIM 4/26/01 was 3
3416         
3417         //Gating Mode=0 for untriggered single pulse
3418         devpriv->gpct_mode[chan] &= ~(G_Gating_Mode(0x3));
3419         devpriv->gpct_mode[chan] |= G_Gating_Mode(0); //TIM 4/25/01 was 1
3420         
3421         // Trigger_Mode_For_Edge_Gate=0
3422         devpriv->gpct_mode[chan] &= ~(G_Trigger_Mode_For_Edge_Gate(0x3));
3423         devpriv->gpct_mode[chan] |= G_Trigger_Mode_For_Edge_Gate(2);
3424
3425
3426         devpriv->gpct_mode[chan] |= G_Reload_Source_Switching;
3427         devpriv->gpct_mode[chan] &= ~G_Loading_On_Gate;
3428         devpriv->gpct_mode[chan] |= G_Loading_On_TC; //TIM 4/25/01
3429         devpriv->gpct_mode[chan] &= ~G_Gate_On_Both_Edges;
3430
3431         // Stop_Mode = 2
3432         devpriv->gpct_mode[chan] &= ~(G_Stop_Mode(0x3));
3433         devpriv->gpct_mode[chan] |= G_Stop_Mode(2); //TIM 4/25/01
3434         
3435         // Counting_Once = 2 
3436         devpriv->gpct_mode[chan] &= ~(G_Counting_Once(0x3));
3437         devpriv->gpct_mode[chan] |= G_Counting_Once(1); //TIM 4/25/01
3438
3439         // Up_Down = 1 
3440         devpriv->gpct_command[chan] &= ~(G_Up_Down(0x3));
3441         devpriv->gpct_command[chan] |= G_Up_Down(0); //TIM 4/25/01 was 1
3442
3443         win_out( devpriv->gpct_mode[chan],G_Mode_Register(chan));
3444         win_out( devpriv->gpct_command[chan],G_Command_Register(chan));
3445
3446         //printk("exit GPCT_Gen_Cont\n");
3447 }
3448
3449 static void GPCT_Gen_Cont_Pulse(comedi_device *dev, int chan, unsigned int length)
3450 {
3451         //printk("GPCT_Gen_Cont...");
3452
3453         devpriv->gpct_cur_operation[chan] = GPCT_CONT_PULSE_OUT;
3454
3455         // Set length of the pulse
3456         GPCT_Load_B(dev,chan, length-1);
3457
3458         //Load next time using B, This is reset by GPCT_Load_Using_A()
3459         devpriv->gpct_mode[chan] |= G_Load_Source_Select;
3460         
3461         devpriv->gpct_mode[chan] &= ~G_OR_Gate;
3462         devpriv->gpct_mode[chan] &= ~G_Gate_Select_Load_Source;
3463
3464         // Output_Mode = 3 
3465         devpriv->gpct_mode[chan] &= ~(G_Output_Mode(0x3));
3466         devpriv->gpct_mode[chan] |= G_Output_Mode(2); //TIM 4/26/01 was 3
3467         
3468         //Gating Mode=0 for untriggered single pulse
3469         devpriv->gpct_mode[chan] &= ~(G_Gating_Mode(0x3));
3470         devpriv->gpct_mode[chan] |= G_Gating_Mode(0); //TIM 4/26/01 was 0
3471         
3472         // Trigger_Mode_For_Edge_Gate=0
3473         devpriv->gpct_mode[chan] &= ~(G_Trigger_Mode_For_Edge_Gate(0x3));
3474         devpriv->gpct_mode[chan] |= G_Trigger_Mode_For_Edge_Gate(2);
3475
3476
3477         devpriv->gpct_mode[chan] |= G_Reload_Source_Switching;
3478         devpriv->gpct_mode[chan] &= ~G_Loading_On_Gate;
3479         devpriv->gpct_mode[chan] |= G_Loading_On_TC; 
3480         devpriv->gpct_mode[chan] &= ~G_Gate_On_Both_Edges;
3481
3482         // Stop_Mode = 2
3483         devpriv->gpct_mode[chan] &= ~(G_Stop_Mode(0x3));
3484         devpriv->gpct_mode[chan] |= G_Stop_Mode(0); //TIM 4/26/01
3485         
3486         // Counting_Once = 2 
3487         devpriv->gpct_mode[chan] &= ~(G_Counting_Once(0x3));
3488         devpriv->gpct_mode[chan] |= G_Counting_Once(0); //TIM 4/26/01
3489
3490         // Up_Down = 1 
3491         devpriv->gpct_command[chan] &= ~(G_Up_Down(0x3));
3492         devpriv->gpct_command[chan] |= G_Up_Down(0); 
3493
3494         //TIM 4/26/01
3495         //This seems pretty unsafe since I don't think it is cleared anywhere.
3496         //I don't think this is working
3497         //devpriv->gpct_command[chan] &= ~G_Bank_Switch_Enable;
3498         //devpriv->gpct_command[chan] &= ~G_Bank_Switch_Mode;
3499         
3500
3501         win_out( devpriv->gpct_mode[chan],G_Mode_Register(chan));
3502         win_out( devpriv->gpct_command[chan],G_Command_Register(chan));
3503
3504         //printk("exit GPCT_Gen_Cont\n");
3505 }
3506
3507 static void GPCT_Reset(comedi_device *dev, int chan)
3508 {
3509         int temp_ack_reg=0;
3510         
3511         //printk("GPCT_Reset...");
3512         devpriv->gpct_cur_operation[chan] = GPCT_RESET;
3513
3514         switch (chan) {
3515                 case 0:
3516                         win_out(G0_Reset,Joint_Reset_Register);
3517                         ni_set_bits(dev,Interrupt_A_Enable_Register,G0_TC_Interrupt_Enable,  0);
3518                         ni_set_bits(dev,Interrupt_A_Enable_Register,G0_Gate_Interrupt_Enable,0);
3519                         temp_ack_reg |= G0_Gate_Error_Confirm;
3520                         temp_ack_reg |= G0_TC_Error_Confirm;
3521                         temp_ack_reg |= G0_TC_Interrupt_Ack;
3522                         temp_ack_reg |= G0_Gate_Interrupt_Ack;
3523                         win_out(temp_ack_reg,Interrupt_A_Ack_Register);
3524                 
3525                         //problem...this interferes with the other ctr...
3526                         devpriv->an_trig_etc_reg |= GPFO_0_Output_Enable;
3527                         win_out(devpriv->an_trig_etc_reg, Analog_Trigger_Etc_Register);
3528                         break;
3529                 case 1:
3530                         win_out(G1_Reset,Joint_Reset_Register);
3531                         ni_set_bits(dev,Interrupt_B_Enable_Register,G1_TC_Interrupt_Enable,  0);
3532                         ni_set_bits(dev,Interrupt_B_Enable_Register,G0_Gate_Interrupt_Enable,0);
3533                         temp_ack_reg |= G1_Gate_Error_Confirm;
3534                         temp_ack_reg |= G1_TC_Error_Confirm;
3535                         temp_ack_reg |= G1_TC_Interrupt_Ack;
3536                         temp_ack_reg |= G1_Gate_Interrupt_Ack;
3537                         win_out(temp_ack_reg,Interrupt_B_Ack_Register);
3538                 
3539                         devpriv->an_trig_etc_reg |= GPFO_1_Output_Enable;
3540                         win_out(devpriv->an_trig_etc_reg, Analog_Trigger_Etc_Register);
3541                         break;
3542         };
3543         
3544         devpriv->gpct_mode[chan] = 0;
3545         devpriv->gpct_input_select[chan] = 0;
3546         devpriv->gpct_command[chan] = 0;
3547         
3548         devpriv->gpct_command[chan] |= G_Synchronized_Gate;
3549         
3550         win_out( devpriv->gpct_mode[chan],G_Mode_Register(chan));
3551         win_out( devpriv->gpct_input_select[chan],G_Input_Select_Register(chan));
3552         win_out( 0,G_Autoincrement_Register(chan));
3553                 
3554         //printk("exit GPCT_Reset\n");
3555 }
3556
3557 static int ni_gpct_insn_config(comedi_device *dev,comedi_subdevice *s,
3558         comedi_insn *insn,lsampl_t *data)
3559 {
3560         int retval=0;
3561         //printk("data[0] is 0x%08x, data[1] is 0x%08x\n",data[0],data[1]);
3562         switch(data[0]){
3563         case GPCT_RESET:
3564                 if(insn->n!=1)return -EINVAL;
3565                 GPCT_Reset(dev,insn->chanspec);
3566                 break;
3567         case GPCT_SET_SOURCE:
3568                 if(insn->n!=2)return -EINVAL;
3569                 retval=GPCT_Set_Source(dev,insn->chanspec,data[1]);
3570                 break;
3571         case GPCT_SET_GATE:
3572                 if(insn->n!=2)return -EINVAL;
3573                 retval=GPCT_Set_Gate(dev,insn->chanspec,data[1]);
3574                 break;
3575         case GPCT_SET_DIRECTION:
3576                 if(insn->n!=2) return -EINVAL;
3577                 retval=GPCT_Set_Direction(dev,insn->chanspec,data[1]);
3578                 break;
3579         case GPCT_GET_INT_CLK_FRQ:
3580                 if(insn->n!=2) return -EINVAL;
3581                 //There are actually 2 internal clocks on the STC, we always
3582                 //use the fast 20MHz one at this time.  Tim  Ousley 5/1/01
3583                 //NOTE: This is not the final interface, ideally the user
3584                 //will never need to know the int. clk. freq.
3585                 data[1]=50;//50ns = 20MHz = internal timebase of STC
3586                 break;
3587         case GPCT_SET_OPERATION:
3588                 //TIM 5/1/01 if((insn->n<2)||(insn->n>3))return -EINVAL;
3589                 switch(data[1]){
3590                         case GPCT_SIMPLE_EVENT:
3591                                 GPCT_Event_Counting(dev,insn->chanspec);
3592                                 break;
3593                         case GPCT_SINGLE_PERIOD:
3594                                 GPCT_Period_Meas(dev,insn->chanspec);
3595                                 break;
3596                         case GPCT_SINGLE_PW:
3597                                 GPCT_Pulse_Width_Meas(dev,insn->chanspec);
3598                                 break;
3599                         case GPCT_SINGLE_PULSE_OUT:
3600                                 GPCT_Gen_Single_Pulse(dev,insn->chanspec,data[2]);
3601                                 break;
3602                         case GPCT_CONT_PULSE_OUT:
3603                                 GPCT_Gen_Cont_Pulse(dev,insn->chanspec,data[2]);
3604                                 break;
3605                         default:
3606                                 printk("unsupported GPCT operation!\n");
3607                                 return -EINVAL;
3608                 }
3609                 break;
3610         case GPCT_ARM:
3611                 if(insn->n!=1)return -EINVAL;
3612                 retval=GPCT_Arm(dev,insn->chanspec);
3613                 break;
3614         case GPCT_DISARM:
3615                 if(insn->n!=1)return -EINVAL;
3616                 retval=GPCT_Disarm(dev,insn->chanspec);
3617                 break;
3618         default:
3619                 return -EINVAL;
3620         }
3621
3622         //catch any errors from return values
3623         if(retval==0){
3624                 return insn->n;
3625         }else{
3626                 if(data[0]!=GPCT_ARM){ 
3627                         printk("error: retval was %d\n",retval);
3628                         printk("data[0] is 0x%08x, data[1] is 0x%08x\n",data[0],data[1]);
3629                 }
3630
3631                 return retval;
3632         }
3633 }
3634
3635 static int ni_gpct_insn_read(comedi_device *dev,comedi_subdevice *s,
3636         comedi_insn *insn,lsampl_t *data) {
3637
3638         int chan=insn->chanspec;
3639         int cur_op = devpriv->gpct_cur_operation[chan];
3640
3641         //printk("in ni_gpct_insn_read, n=%d, data[0]=%d\n",insn->chanspec,data[0]);
3642         if(insn->n!=1)return -EINVAL;
3643                 
3644         data[0] = GPCT_G_Watch(dev,insn->chanspec);
3645                 
3646         /* for certain modes (period and pulse width measurment), the value
3647         in the counter is not valid until the counter stops.  If the value is 
3648         invalid, return a 0 */
3649         if((cur_op == GPCT_SINGLE_PERIOD) || (cur_op == GPCT_SINGLE_PW)){
3650                 /* is the counter still running? */
3651                 if(win_in(G_Status_Register) & (chan?G1_Counting_St:G0_Counting_St))
3652                         data[0]=0;
3653         }
3654         return 1;
3655 }
3656
3657 static int ni_gpct_insn_write(comedi_device *dev,comedi_subdevice *s,
3658         comedi_insn *insn,lsampl_t *data) {
3659
3660         //printk("in ni_gpct_insn_write");
3661         if(insn->n!=1)return -EINVAL;
3662         GPCT_Load_Using_A(dev,insn->chanspec,data[0]);
3663         return 1;
3664 }
3665
3666
3667 /*
3668  *
3669  *  Programmable Function Inputs
3670  *
3671  */
3672
3673 static int ni_pfi_insn_bits(comedi_device *dev,comedi_subdevice *s,
3674         comedi_insn *insn,lsampl_t *data)
3675 {
3676         if(insn->n!=2)return -EINVAL;
3677
3678         data[1] = 0;
3679
3680         return 2;
3681 }
3682
3683 static int ni_pfi_insn_config(comedi_device *dev,comedi_subdevice *s,
3684         comedi_insn *insn,lsampl_t *data)
3685 {
3686         unsigned int chan;
3687
3688         if(insn->n!=1)return -EINVAL;
3689
3690         chan = CR_CHAN(insn->chanspec);
3691         if(chan>10)return -EINVAL;
3692
3693         switch(data[0]){
3694         case COMEDI_OUTPUT:
3695                 ni_set_bits(dev, IO_Bidirection_Pin_Register, 1<<chan, 1);
3696                 break;
3697         case COMEDI_INPUT:
3698                 ni_set_bits(dev, IO_Bidirection_Pin_Register, 1<<chan, 0);
3699                 break;
3700         default:
3701                 return -EINVAL;
3702         }
3703
3704         return 1;
3705 }
3706
3707 static int cs5529_wait_for_idle(comedi_device *dev)
3708 {
3709         unsigned short status;
3710         const int timeout = HZ;
3711         int i;
3712
3713         for(i = 0; i < timeout; i++)
3714         {
3715                 status = ni_ao_win_inw(dev, CAL_ADC_Status_67xx);
3716                 if((status & CSS_ADC_BUSY) == 0)
3717                 {
3718                         break;
3719                 }
3720                 set_current_state(TASK_INTERRUPTIBLE);
3721                 if(schedule_timeout(1))
3722                 {
3723                         return -EIO;
3724                 }
3725         }
3726 //printk("looped %i times waiting for idle\n", i);
3727         if(i == timeout)
3728         {
3729                 rt_printk("%s: %s: timeout\n", __FILE__, __FUNCTION__);
3730                 return -ETIME;
3731         }
3732         return 0;
3733 }
3734
3735 static void cs5529_command(comedi_device *dev, unsigned short value)
3736 {
3737         static const int timeout = 100;
3738         int i;
3739
3740         ni_ao_win_outw(dev, value, CAL_ADC_Command_67xx);
3741         /* give time for command to start being serially clocked into cs5529.
3742          * this insures that the CSS_ADC_BUSY bit will get properly
3743          * set before we exit this function.
3744         */
3745         for(i = 0; i < timeout; i++)
3746         {
3747                 if((ni_ao_win_inw(dev, CAL_ADC_Status_67xx) & CSS_ADC_BUSY))
3748                         break;
3749                 comedi_udelay(1);
3750         }
3751 //printk("looped %i times writing command to cs5529\n", i);
3752         if(i == timeout)
3753         {
3754                 comedi_error(dev, "possible problem - never saw adc go busy?");
3755         }
3756 }
3757
3758 /* write to cs5529 register */
3759 static void cs5529_config_write(comedi_device *dev, unsigned int value, unsigned int reg_select_bits)
3760 {
3761         ni_ao_win_outw(dev, ((value >> 16) & 0xff), CAL_ADC_Config_Data_High_Word_67xx);
3762         ni_ao_win_outw(dev, (value & 0xffff), CAL_ADC_Config_Data_Low_Word_67xx);
3763         reg_select_bits &= CSCMD_REGISTER_SELECT_MASK;
3764         cs5529_command(dev, CSCMD_COMMAND | reg_select_bits);
3765         if(cs5529_wait_for_idle(dev))
3766                 comedi_error(dev, "time or signal in cs5529_config_write()");
3767 }
3768
3769 /* read from cs5529 register */
3770 static unsigned int cs5529_config_read(comedi_device *dev, unsigned int reg_select_bits)
3771 {
3772         unsigned int value;
3773
3774         reg_select_bits &= CSCMD_REGISTER_SELECT_MASK;
3775         cs5529_command(dev, CSCMD_COMMAND | CSCMD_READ | reg_select_bits);
3776         if(cs5529_wait_for_idle(dev))
3777                 comedi_error(dev, "timeout or signal in cs5529_config_read()");
3778         value = (ni_ao_win_inw(dev, CAL_ADC_Config_Data_High_Word_67xx) << 16) & 0xff0000;
3779         value |= ni_ao_win_inw(dev, CAL_ADC_Config_Data_Low_Word_67xx) & 0xffff;
3780         return value;
3781 }
3782
3783 static int cs5529_do_conversion(comedi_device *dev, unsigned short *data)
3784 {
3785         int retval;
3786         unsigned short status;
3787
3788         cs5529_command(dev, CSCMD_COMMAND | CSCMD_SINGLE_CONVERSION);
3789         retval = cs5529_wait_for_idle(dev);
3790         if(retval)
3791         {
3792                 comedi_error(dev, "timeout or signal in cs5529_do_conversion()");
3793                 return -ETIME;
3794         }
3795         status = ni_ao_win_inw(dev, CAL_ADC_Status_67xx);
3796         if(status & CSS_OSC_DETECT)
3797         {
3798                 rt_printk("ni_mio_common: cs5529 conversion error, status CSS_OSC_DETECT\n");
3799                 return -EIO;
3800         }
3801         if(status & CSS_OVERRANGE)
3802         {
3803                 rt_printk("ni_mio_common: cs5529 conversion error, overrange (ignoring)\n");
3804         }
3805         if(data)
3806         {
3807                 *data = ni_ao_win_inw(dev, CAL_ADC_Data_67xx);
3808                 /* cs5529 returns 16 bit signed data in bipolar mode */
3809                 *data ^= (1 << 15);
3810         }
3811         return 0;
3812 }
3813
3814 static int cs5529_ai_insn_read(comedi_device *dev,comedi_subdevice *s,comedi_insn *insn,lsampl_t *data)
3815 {
3816         int n, retval;
3817         unsigned short sample;
3818         unsigned int channel_select;
3819         const unsigned int INTERNAL_REF = 0x1000;
3820
3821         /* Set calibration adc source.  Docs lie, reference select bits 8 to 11
3822          * do nothing. bit 12 seems to chooses internal reference voltage, bit
3823          * 13 causes the adc input to go overrange (maybe reads external reference?) */
3824         if(insn->chanspec & CR_ALT_SOURCE)
3825                 channel_select = INTERNAL_REF;
3826         else
3827                 channel_select = CR_CHAN(insn->chanspec);
3828         ni_ao_win_outw(dev, channel_select, AO_Calibration_Channel_Select_67xx);
3829
3830         for(n = 0; n < insn->n; n++)
3831         {
3832                 retval = cs5529_do_conversion(dev, &sample);
3833                 if(retval < 0) return retval;
3834                 data[n] = sample;
3835         }
3836         return insn->n;
3837 }
3838
3839 static int init_cs5529(comedi_device *dev)
3840 {
3841         unsigned int config_bits = CSCFG_PORT_MODE | CSCFG_WORD_RATE_2180_CYCLES;
3842
3843 #if 1
3844         /* do self-calibration */
3845         cs5529_config_write(dev, config_bits | CSCFG_SELF_CAL_OFFSET_GAIN, CSCMD_CONFIG_REGISTER);
3846         /* need to force a conversion for calibration to run */
3847         cs5529_do_conversion(dev, NULL);
3848 #else
3849         /* force gain calibration to 1 */
3850         cs5529_config_write(dev, 0x400000, CSCMD_GAIN_REGISTER);
3851         cs5529_config_write(dev, config_bits | CSCFG_SELF_CAL_OFFSET, CSCMD_CONFIG_REGISTER);
3852         if(cs5529_wait_for_idle(dev))
3853                 comedi_error(dev, "timeout or signal in init_cs5529()\n");
3854 #endif
3855         if(0)
3856         {
3857                 rt_printk("config: 0x%x\n", cs5529_config_read(dev, CSCMD_CONFIG_REGISTER));
3858                 rt_printk("gain: 0x%x\n", cs5529_config_read(dev, CSCMD_GAIN_REGISTER));
3859                 rt_printk("offset: 0x%x\n", cs5529_config_read(dev, CSCMD_OFFSET_REGISTER));
3860         }
3861         return 0;
3862 }
3863
3864