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