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