Added SDF_SOFT_CALIBRATED subdevice flag.
[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 range_code;
1418
1419         devpriv->stc_writew(dev, 1, Configuration_Memory_Clear);
1420
1421 //      offset = 1 << (boardtype.adbits - 1);
1422         if((list[0] & CR_ALT_SOURCE))
1423         {
1424                 chan = CR_CHAN(list[0]);
1425                 range = CR_RANGE(list[0]);
1426                 range_code = ni_gainlkup[boardtype.gainlkup][range];
1427                 dither = ((list[0] & CR_ALT_FILTER) != 0);
1428                 unsigned bypass_bits = MSeries_AI_Bypass_Config_FIFO_Bit;
1429                 bypass_bits |= chan;
1430                 bypass_bits |= (devpriv->ai_calib_source) & (MSeries_AI_Bypass_Cal_Sel_Pos_Mask |
1431                         MSeries_AI_Bypass_Cal_Sel_Neg_Mask | MSeries_AI_Bypass_Mode_Mux_Mask |
1432                         MSeries_AO_Bypass_AO_Cal_Sel_Mask);
1433                 bypass_bits |= MSeries_AI_Bypass_Gain_Bits(range_code);
1434                 if(dither)
1435                         bypass_bits |= MSeries_AI_Bypass_Dither_Bit;
1436                 // don't use 2's complement encoding
1437                 bypass_bits |= MSeries_AI_Bypass_Polarity_Bit;
1438                 ni_writel(bypass_bits, M_Offset_AI_Config_FIFO_Bypass);
1439         }else
1440         {
1441                 ni_writel(0, M_Offset_AI_Config_FIFO_Bypass);
1442         }
1443         offset = 0;
1444         for(i = 0; i < n_chan; i++)
1445         {
1446                 chan = CR_CHAN(list[i]);
1447                 aref = CR_AREF(list[i]);
1448                 range = CR_RANGE(list[i]);
1449                 dither = ((list[i] & CR_ALT_FILTER) != 0);
1450
1451                 range_code = ni_gainlkup[boardtype.gainlkup][range];
1452                 devpriv->ai_offset[i] = offset;
1453
1454                 switch( aref )
1455                 {
1456                         case AREF_DIFF:
1457                                 config_bits |= MSeries_AI_Config_Channel_Type_Differential_Bits;
1458                                 break;
1459                         case AREF_COMMON:
1460                                 config_bits |= MSeries_AI_Config_Channel_Type_Common_Ref_Bits;
1461                                 break;
1462                         case AREF_GROUND:
1463                                 config_bits |= MSeries_AI_Config_Channel_Type_Ground_Ref_Bits;
1464                                 break;
1465                         case AREF_OTHER:
1466                                 break;
1467                 }
1468                 config_bits |= MSeries_AI_Config_Channel_Bits(chan);
1469                 config_bits |= MSeries_AI_Config_Bank_Bits(chan);
1470                 config_bits |= MSeries_AI_Config_Gain_Bits(range_code);
1471                 if(i == n_chan - 1) config_bits |= MSeries_AI_Config_Last_Channel_Bit;
1472                 if(dither) config_bits |= MSeries_AI_Config_Dither_Bit;
1473                 // don't use 2's complement encoding
1474                 config_bits |= MSeries_AI_Config_Polarity_Bit;
1475                 ni_writew(config_bits, M_Offset_AI_Config_FIFO_Data);
1476         }
1477         ni_prime_channelgain_list(dev);
1478 }
1479
1480 /*
1481  * Notes on the 6110 and 6111:
1482  * These boards a slightly different than the rest of the series, since
1483  * they have multiple A/D converters.
1484  * From the driver side, the configuration memory is a
1485  * little different.
1486  * Configuration Memory Low:
1487  *   bits 15-9: same
1488  *   bit 8: unipolar/bipolar (should be 0 for bipolar)
1489  *   bits 0-3: gain.  This is 4 bits instead of 3 for the other boards
1490  *       1001 gain=0.1 (+/- 50)
1491  *       1010 0.2
1492  *       1011 0.1
1493  *       0001 1
1494  *       0010 2
1495  *       0011 5
1496  *       0100 10
1497  *       0101 20
1498  *       0110 50
1499  * Configuration Memory High:
1500  *   bits 12-14: Channel Type
1501  *       001 for differential
1502  *       000 for calibration
1503  *   bit 11: coupling  (this is not currently handled)
1504  *       1 AC coupling
1505  *       0 DC coupling
1506  *   bits 0-2: channel
1507  *       valid channels are 0-3
1508  */
1509 static void ni_load_channelgain_list(comedi_device *dev,unsigned int n_chan,
1510         unsigned int *list)
1511 {
1512         unsigned int chan,range,aref;
1513         unsigned int i;
1514         unsigned int hi,lo;
1515         unsigned offset;
1516         unsigned int dither;
1517
1518         if(boardtype.reg_type == ni_reg_m_series)
1519         {
1520                 ni_m_series_load_channelgain_list(dev, n_chan, list);
1521                 return;
1522         }
1523         if(n_chan == 1 && (boardtype.reg_type != ni_reg_611x) && (boardtype.reg_type != ni_reg_6143)){
1524                 if(devpriv->changain_state && devpriv->changain_spec==list[0]){
1525                         // ready to go.
1526                         return;
1527                 }
1528                 devpriv->changain_state=1;
1529                 devpriv->changain_spec=list[0];
1530         }else{
1531                 devpriv->changain_state=0;
1532         }
1533
1534         devpriv->stc_writew(dev, 1,Configuration_Memory_Clear);
1535
1536         // Set up Calibration mode if required
1537         if(boardtype.reg_type == ni_reg_6143){
1538                 if((list[0] & CR_ALT_SOURCE) && !devpriv->ai_calib_source_enabled){
1539                         // Strobe Relay enable bit
1540                         ni_writew(devpriv->ai_calib_source | Calibration_Channel_6143_RelayOn, Calibration_Channel_6143);
1541                         ni_writew(devpriv->ai_calib_source, Calibration_Channel_6143);
1542                         devpriv->ai_calib_source_enabled = 1;
1543                         msleep_interruptible(100);      // Allow relays to change
1544                 }
1545                 else if(!(list[0] & CR_ALT_SOURCE) && devpriv->ai_calib_source_enabled){
1546                         // Strobe Relay disable bit
1547                         ni_writew(devpriv->ai_calib_source | Calibration_Channel_6143_RelayOff, Calibration_Channel_6143);
1548                         ni_writew(devpriv->ai_calib_source, Calibration_Channel_6143);
1549                         devpriv->ai_calib_source_enabled = 0;
1550                         msleep_interruptible(100);      // Allow relays to change
1551                 }
1552         }
1553
1554         offset=1<<(boardtype.adbits-1);
1555         for(i=0;i<n_chan;i++){
1556                 if((boardtype.reg_type != ni_reg_6143) && (list[i] & CR_ALT_SOURCE)){
1557                         chan=devpriv->ai_calib_source;
1558                 }else{
1559                         chan=CR_CHAN(list[i]);
1560                 }
1561                 aref=CR_AREF(list[i]);
1562                 range=CR_RANGE(list[i]);
1563                 dither=((list[i]&CR_ALT_FILTER)!=0);
1564
1565                 /* fix the external/internal range differences */
1566                 range = ni_gainlkup[boardtype.gainlkup][range];
1567                 if(boardtype.reg_type == ni_reg_611x)
1568                         devpriv->ai_offset[i] = offset;
1569                 else
1570                         devpriv->ai_offset[i] = (range&0x100)?0:offset;
1571
1572                 hi = 0;
1573                 if( ( list[i] & CR_ALT_SOURCE ) )
1574                 {
1575                         if(boardtype.reg_type == ni_reg_611x)
1576                                 ni_writew(CR_CHAN(list[i])&0x0003, Calibration_Channel_Select_611x);
1577                 }else
1578                 {
1579                         if(boardtype.reg_type == ni_reg_611x)
1580                                 aref = AREF_DIFF;
1581                         else if(boardtype.reg_type == ni_reg_6143)
1582                                 aref = AREF_OTHER;
1583                         switch( aref )
1584                         {
1585                                 case AREF_DIFF:
1586                                         hi |= AI_DIFFERENTIAL;
1587                                         break;
1588                                 case AREF_COMMON:
1589                                         hi |= AI_COMMON;
1590                                         break;
1591                                 case AREF_GROUND:
1592                                         hi |= AI_GROUND;
1593                                         break;
1594                                 case AREF_OTHER:
1595                                         break;
1596                         }
1597                 }
1598                 hi |= AI_CONFIG_CHANNEL( chan );
1599
1600                 ni_writew(hi,Configuration_Memory_High);
1601
1602                 if(boardtype.reg_type != ni_reg_6143){
1603                         lo = range;
1604                         if(i == n_chan - 1) lo |= AI_LAST_CHANNEL;
1605                         if( dither ) lo |= AI_DITHER;
1606
1607                         ni_writew(lo,Configuration_Memory_Low);
1608                 }
1609         }
1610
1611         /* prime the channel/gain list */
1612         if((boardtype.reg_type != ni_reg_611x) && (boardtype.reg_type != ni_reg_6143)){
1613                 ni_prime_channelgain_list(dev);
1614         }
1615 }
1616
1617 #define TIMER_BASE 50 /* 20 Mhz base */
1618
1619 static int ni_ns_to_timer(int *nanosec,int round_mode)
1620 {
1621         int divider,base;
1622
1623         base=TIMER_BASE;
1624
1625         switch(round_mode){
1626         case TRIG_ROUND_NEAREST:
1627         default:
1628                 divider=(*nanosec+base/2)/base;
1629                 break;
1630         case TRIG_ROUND_DOWN:
1631                 divider=(*nanosec)/base;
1632                 break;
1633         case TRIG_ROUND_UP:
1634                 divider=(*nanosec+base-1)/base;
1635                 break;
1636         }
1637
1638         *nanosec=base*divider;
1639         return divider-1;
1640 }
1641
1642 static int ni_ai_cmdtest(comedi_device *dev,comedi_subdevice *s,comedi_cmd *cmd)
1643 {
1644         int err=0;
1645         int tmp;
1646         int sources;
1647
1648         /* step 1: make sure trigger sources are trivially valid */
1649
1650         tmp=cmd->start_src;
1651         cmd->start_src &= TRIG_NOW|TRIG_INT|TRIG_EXT;
1652         if(!cmd->start_src || tmp!=cmd->start_src)err++;
1653
1654         tmp=cmd->scan_begin_src;
1655         cmd->scan_begin_src &= TRIG_TIMER|TRIG_EXT;
1656         if(!cmd->scan_begin_src || tmp!=cmd->scan_begin_src)err++;
1657
1658         tmp=cmd->convert_src;
1659         sources = TRIG_TIMER | TRIG_EXT;
1660         if((boardtype.reg_type == ni_reg_611x) || (boardtype.reg_type == ni_reg_6143)) sources |= TRIG_NOW;
1661         cmd->convert_src &= sources;
1662         if(!cmd->convert_src || tmp!=cmd->convert_src)err++;
1663
1664         tmp=cmd->scan_end_src;
1665         cmd->scan_end_src &= TRIG_COUNT;
1666         if(!cmd->scan_end_src || tmp!=cmd->scan_end_src)err++;
1667
1668         tmp=cmd->stop_src;
1669         cmd->stop_src &= TRIG_COUNT|TRIG_NONE;
1670         if(!cmd->stop_src || tmp!=cmd->stop_src)err++;
1671
1672         if(err)return 1;
1673
1674         /* step 2: make sure trigger sources are unique and mutually compatible */
1675
1676         /* note that mutual compatiblity is not an issue here */
1677         if(cmd->start_src!=TRIG_NOW &&
1678            cmd->start_src!=TRIG_INT &&
1679            cmd->start_src!=TRIG_EXT)err++;
1680         if(cmd->scan_begin_src!=TRIG_TIMER &&
1681            cmd->scan_begin_src!=TRIG_EXT &&
1682            cmd->scan_begin_src!=TRIG_OTHER)err++;
1683         if(cmd->convert_src!=TRIG_TIMER &&
1684            cmd->convert_src!=TRIG_EXT &&
1685            cmd->convert_src!=TRIG_NOW)err++;
1686         if(cmd->stop_src!=TRIG_COUNT &&
1687            cmd->stop_src!=TRIG_NONE)err++;
1688
1689         if(err)return 2;
1690
1691         /* step 3: make sure arguments are trivially compatible */
1692
1693         if(cmd->start_src==TRIG_EXT){
1694                 /* external trigger */
1695                 unsigned int tmp = CR_CHAN(cmd->start_arg);
1696
1697                 if(tmp > 16) tmp = 16;
1698                 tmp |= (cmd->start_arg & (CR_INVERT | CR_EDGE));
1699                 if(cmd->start_arg != tmp){
1700                         cmd->start_arg = tmp;
1701                         err++;
1702                 }
1703         }else{
1704                 if(cmd->start_arg!=0){
1705                         /* true for both TRIG_NOW and TRIG_INT */
1706                         cmd->start_arg=0;
1707                         err++;
1708                 }
1709         }
1710         if(cmd->scan_begin_src==TRIG_TIMER){
1711                 if(cmd->scan_begin_arg<boardtype.ai_speed){
1712                         cmd->scan_begin_arg=boardtype.ai_speed;
1713                         err++;
1714                 }
1715                 if(cmd->scan_begin_arg>TIMER_BASE*0xffffff){
1716                         cmd->scan_begin_arg=TIMER_BASE*0xffffff;
1717                         err++;
1718                 }
1719         }else if(cmd->scan_begin_src==TRIG_EXT){
1720                 /* external trigger */
1721                 unsigned int tmp = CR_CHAN(cmd->scan_begin_arg);
1722
1723                 if(tmp>16)tmp=16;
1724                 tmp |= (cmd->scan_begin_arg & (CR_INVERT | CR_EDGE));
1725                 if(cmd->scan_begin_arg!=tmp){
1726                         cmd->scan_begin_arg = tmp;
1727                         err++;
1728                 }
1729         }else{ /* TRIG_OTHER */
1730                 if(cmd->scan_begin_arg){
1731                         cmd->scan_begin_arg=0;
1732                         err++;
1733                 }
1734         }
1735         if(cmd->convert_src==TRIG_TIMER){
1736                 if((boardtype.reg_type == ni_reg_611x) || (boardtype.reg_type == ni_reg_6143)){
1737                         if(cmd->convert_arg != 0){
1738                                 cmd->convert_arg = 0;
1739                                 err++;
1740                         }
1741                 }else{
1742                         if(cmd->convert_arg<boardtype.ai_speed){
1743                                 cmd->convert_arg=boardtype.ai_speed;
1744                                 err++;
1745                         }
1746                         if(cmd->convert_arg>TIMER_BASE*0xffff){
1747                                 cmd->convert_arg=TIMER_BASE*0xffff;
1748                                 err++;
1749                         }
1750                 }
1751         }else if(cmd->convert_src == TRIG_EXT){
1752                 /* external trigger */
1753                 unsigned int tmp = CR_CHAN(cmd->convert_arg);
1754
1755                 if(tmp>16)tmp=16;
1756                 tmp |= (cmd->convert_arg&(CR_ALT_FILTER|CR_INVERT));
1757                 if(cmd->convert_arg!=tmp){
1758                         cmd->convert_arg = tmp;
1759                         err++;
1760                 }
1761         }else if(cmd->convert_src == TRIG_NOW){
1762                 if(cmd->convert_arg != 0){
1763                         cmd->convert_arg = 0;
1764                         err++;
1765                 }
1766         }
1767
1768         if(cmd->scan_end_arg!=cmd->chanlist_len){
1769                 cmd->scan_end_arg=cmd->chanlist_len;
1770                 err++;
1771         }
1772         if(cmd->stop_src==TRIG_COUNT){
1773                 unsigned int max_count = 0x01000000;
1774
1775                 if(boardtype.reg_type == ni_reg_611x )
1776                         max_count -= num_adc_stages_611x;
1777                 if(cmd->stop_arg > max_count){
1778                         cmd->stop_arg = max_count;
1779                         err++;
1780                 }
1781                 if(cmd->stop_arg < 1){
1782                         cmd->stop_arg = 1;
1783                         err++;
1784                 }
1785         }else{
1786                 /* TRIG_NONE */
1787                 if(cmd->stop_arg!=0){
1788                         cmd->stop_arg=0;
1789                         err++;
1790                 }
1791         }
1792
1793         if(err)return 3;
1794
1795         /* step 4: fix up any arguments */
1796
1797         if(cmd->scan_begin_src==TRIG_TIMER){
1798                 tmp=cmd->scan_begin_arg;
1799                 ni_ns_to_timer(&cmd->scan_begin_arg,cmd->flags&TRIG_ROUND_MASK);
1800                 if(tmp!=cmd->scan_begin_arg)err++;
1801         }
1802         if(cmd->convert_src==TRIG_TIMER){
1803                 if((boardtype.reg_type != ni_reg_611x) && (boardtype.reg_type != ni_reg_6143)){
1804                         tmp=cmd->convert_arg;
1805                         ni_ns_to_timer(&cmd->convert_arg,cmd->flags&TRIG_ROUND_MASK);
1806                         if(tmp!=cmd->convert_arg)err++;
1807                         if(cmd->scan_begin_src==TRIG_TIMER &&
1808                         cmd->scan_begin_arg<cmd->convert_arg*cmd->scan_end_arg){
1809                                 cmd->scan_begin_arg=cmd->convert_arg*cmd->scan_end_arg;
1810                                 err++;
1811                         }
1812                 }
1813         }
1814
1815         if(err)return 4;
1816
1817         return 0;
1818 }
1819
1820 static int ni_ai_cmd(comedi_device *dev,comedi_subdevice *s)
1821 {
1822         comedi_cmd *cmd=&s->async->cmd;
1823         int timer;
1824         int mode1=0; /* mode1 is needed for both stop and convert */
1825         int mode2=0;
1826         int start_stop_select=0;
1827         unsigned int stop_count;
1828         int interrupt_a_enable=0;
1829
1830         MDPRINTK("ni_ai_cmd\n");
1831         if(dev->irq == 0)
1832         {
1833                 comedi_error(dev, "cannot run command without an irq");
1834                 return -EIO;
1835         }
1836         ni_flush_ai_fifo(dev);
1837
1838         ni_load_channelgain_list(dev,cmd->chanlist_len,cmd->chanlist);
1839
1840         /* start configuration */
1841         devpriv->stc_writew(dev, AI_Configuration_Start,Joint_Reset_Register);
1842
1843         /* disable analog triggering for now, since it
1844          * interferes with the use of pfi0 */
1845         devpriv->an_trig_etc_reg &= ~Analog_Trigger_Enable;
1846         devpriv->stc_writew(dev, devpriv->an_trig_etc_reg, Analog_Trigger_Etc_Register);
1847
1848         switch(cmd->start_src){
1849                 case TRIG_INT:
1850                 case TRIG_NOW:
1851                         devpriv->stc_writew(dev, AI_START2_Select(0)|
1852                                 AI_START1_Sync|AI_START1_Edge|AI_START1_Select(0),
1853                                 AI_Trigger_Select_Register);
1854                         break;
1855                 case TRIG_EXT:
1856                 {
1857                         int chan = CR_CHAN(cmd->start_arg);
1858                         unsigned int bits = AI_START2_Select(0)|
1859                                 AI_START1_Sync |
1860                                 AI_START1_Select(chan + 1);
1861
1862                         if(cmd->start_arg & CR_INVERT)
1863                                 bits |= AI_START1_Polarity;
1864                         if(cmd->start_arg & CR_EDGE)
1865                                 bits |= AI_START1_Edge;
1866                         devpriv->stc_writew(dev, bits, AI_Trigger_Select_Register);
1867                         break;
1868                 }
1869         }
1870
1871         mode2 &= ~AI_Pre_Trigger;
1872         mode2 &= ~AI_SC_Initial_Load_Source;
1873         mode2 &= ~AI_SC_Reload_Mode;
1874         devpriv->stc_writew(dev, mode2, AI_Mode_2_Register);
1875
1876         if(cmd->chanlist_len == 1 || (boardtype.reg_type == ni_reg_611x) || (boardtype.reg_type == ni_reg_6143)){
1877                 start_stop_select |= AI_STOP_Polarity;
1878                 start_stop_select |= AI_STOP_Select( 31 ); // logic low
1879                 start_stop_select |= AI_STOP_Sync;
1880         }else
1881         {
1882                 start_stop_select |= AI_STOP_Select(19); // ai configuration memory
1883         }
1884         devpriv->stc_writew(dev, start_stop_select, AI_START_STOP_Select_Register);
1885
1886         devpriv->ai_cmd2 = 0;
1887         switch(cmd->stop_src){
1888         case TRIG_COUNT:
1889                 stop_count = cmd->stop_arg - 1;
1890
1891                 if(boardtype.reg_type == ni_reg_611x){
1892                         // have to take 3 stage adc pipeline into account
1893                         stop_count += num_adc_stages_611x;
1894                 }
1895                 /* stage number of scans */
1896                 devpriv->stc_writel(dev,  stop_count, AI_SC_Load_A_Registers);
1897
1898                 mode1 |= AI_Start_Stop | AI_Mode_1_Reserved | AI_Trigger_Once;
1899                 devpriv->stc_writew(dev, mode1,AI_Mode_1_Register);
1900                 /* load SC (Scan Count) */
1901                 devpriv->stc_writew(dev, AI_SC_Load,AI_Command_1_Register);
1902
1903                 devpriv->ai_continuous = 0;
1904                 if( stop_count == 0 ){
1905                         devpriv->ai_cmd2 |= AI_End_On_End_Of_Scan;
1906                         interrupt_a_enable |= AI_STOP_Interrupt_Enable;
1907                         // this is required to get the last sample for chanlist_len > 1, not sure why
1908                         if(cmd->chanlist_len > 1)
1909                                 start_stop_select |= AI_STOP_Polarity | AI_STOP_Edge;
1910                 }
1911                 break;
1912         case TRIG_NONE:
1913                 /* stage number of scans */
1914                 devpriv->stc_writel(dev, 0,AI_SC_Load_A_Registers);
1915
1916                 mode1 |= AI_Start_Stop | AI_Mode_1_Reserved | AI_Continuous;
1917                 devpriv->stc_writew(dev, mode1,AI_Mode_1_Register);
1918
1919                 /* load SC (Scan Count) */
1920                 devpriv->stc_writew(dev, AI_SC_Load,AI_Command_1_Register);
1921
1922                 devpriv->ai_continuous = 1;
1923
1924                 break;
1925         }
1926
1927         switch(cmd->scan_begin_src){
1928         case TRIG_TIMER:
1929                 /*
1930                         stop bits for non 611x boards
1931                         AI_SI_Special_Trigger_Delay=0
1932                         AI_Pre_Trigger=0
1933                         AI_START_STOP_Select_Register:
1934                         AI_START_Polarity=0 (?) rising edge
1935                         AI_START_Edge=1         edge triggered
1936                         AI_START_Sync=1 (?)
1937                         AI_START_Select=0               SI_TC
1938                         AI_STOP_Polarity=0              rising edge
1939                         AI_STOP_Edge=0          level
1940                         AI_STOP_Sync=1
1941                         AI_STOP_Select=19               external pin (configuration mem)
1942                  */
1943                 start_stop_select |= AI_START_Edge | AI_START_Sync;
1944                 devpriv->stc_writew(dev, start_stop_select, AI_START_STOP_Select_Register);
1945
1946                 mode2 |= AI_SI_Reload_Mode(0);
1947                 /* AI_SI_Initial_Load_Source=A */
1948                 mode2 &= ~AI_SI_Initial_Load_Source;
1949                 //mode2 |= AI_SC_Reload_Mode;
1950                 devpriv->stc_writew(dev, mode2, AI_Mode_2_Register);
1951
1952                 /* load SI */
1953                 timer=ni_ns_to_timer(&cmd->scan_begin_arg,TRIG_ROUND_NEAREST);
1954                 devpriv->stc_writel(dev, timer,AI_SI_Load_A_Registers);
1955                 devpriv->stc_writew(dev, AI_SI_Load,AI_Command_1_Register);
1956                 break;
1957         case TRIG_EXT:
1958                 if( cmd->scan_begin_arg & CR_EDGE )
1959                         start_stop_select |= AI_START_Edge;
1960                 /* AI_START_Polarity==1 is falling edge */
1961                 if( cmd->scan_begin_arg & CR_INVERT )
1962                         start_stop_select |= AI_START_Polarity;
1963                 if( cmd->scan_begin_src != cmd->convert_src ||
1964                         ( cmd->scan_begin_arg & ~CR_EDGE ) != ( cmd->convert_arg & ~CR_EDGE ) )
1965                         start_stop_select |= AI_START_Sync;
1966                 start_stop_select |= AI_START_Select(1 + CR_CHAN(cmd->scan_begin_arg));
1967                 devpriv->stc_writew(dev, start_stop_select, AI_START_STOP_Select_Register);
1968                 break;
1969         }
1970
1971         switch(cmd->convert_src){
1972         case TRIG_TIMER:
1973         case TRIG_NOW:
1974                 if( cmd->convert_arg == 0 || cmd->convert_src == TRIG_NOW )
1975                         timer = 1;
1976                 else
1977                         timer=ni_ns_to_timer(&cmd->convert_arg, TRIG_ROUND_NEAREST);
1978                 devpriv->stc_writew(dev, 1,AI_SI2_Load_A_Register); /* 0,0 does not work. */
1979                 devpriv->stc_writew(dev, timer,AI_SI2_Load_B_Register);
1980
1981                 /* AI_SI2_Reload_Mode = alternate */
1982                 /* AI_SI2_Initial_Load_Source = A */
1983                 mode2 &= ~AI_SI2_Initial_Load_Source;
1984                 mode2 |= AI_SI2_Reload_Mode;
1985                 devpriv->stc_writew(dev,  mode2, AI_Mode_2_Register);
1986
1987                 /* AI_SI2_Load */
1988                 devpriv->stc_writew(dev, AI_SI2_Load,AI_Command_1_Register);
1989
1990                 mode2 |= AI_SI2_Reload_Mode; // alternate
1991                 mode2 |= AI_SI2_Initial_Load_Source; // B
1992
1993                 devpriv->stc_writew(dev, mode2,AI_Mode_2_Register);
1994                 break;
1995         case TRIG_EXT:
1996                 mode1 |= AI_CONVERT_Source_Select(1+cmd->convert_arg);
1997                 if( ( cmd->convert_arg & CR_INVERT ) == 0 )
1998                         mode1 |= AI_CONVERT_Source_Polarity;
1999                 devpriv->stc_writew(dev, mode1,AI_Mode_1_Register);
2000
2001                 mode2 |= AI_Start_Stop_Gate_Enable | AI_SC_Gate_Enable;
2002                 devpriv->stc_writew(dev, mode2, AI_Mode_2_Register);
2003
2004                 break;
2005         }
2006
2007         if(dev->irq){
2008
2009                 /* interrupt on FIFO, errors, SC_TC */
2010                 interrupt_a_enable |= AI_Error_Interrupt_Enable|
2011                         AI_SC_TC_Interrupt_Enable;
2012
2013 #ifndef PCIDMA
2014                 interrupt_a_enable|=AI_FIFO_Interrupt_Enable;
2015 #endif
2016
2017                 if(cmd->flags & TRIG_WAKE_EOS || (devpriv->ai_cmd2 & AI_End_On_End_Of_Scan)){
2018                         /* wake on end-of-scan */
2019                         devpriv->aimode=AIMODE_SCAN;
2020                 }else{
2021                         devpriv->aimode=AIMODE_HALF_FULL;
2022                 }
2023
2024                 switch(devpriv->aimode){
2025                 case AIMODE_HALF_FULL:
2026                         /*generate FIFO interrupts and DMA requests on half-full */
2027 #ifdef PCIDMA
2028                         devpriv->stc_writew(dev, AI_FIFO_Mode_HF_to_E, AI_Mode_3_Register);
2029 #else
2030                         devpriv->stc_writew(dev, AI_FIFO_Mode_HF, AI_Mode_3_Register);
2031 #endif
2032                         break;
2033                 case AIMODE_SAMPLE:
2034                         /*generate FIFO interrupts on non-empty */
2035                         devpriv->stc_writew(dev, AI_FIFO_Mode_NE, AI_Mode_3_Register);
2036                         break;
2037                 case AIMODE_SCAN:
2038 #ifdef PCIDMA
2039                         devpriv->stc_writew(dev, AI_FIFO_Mode_NE, AI_Mode_3_Register);
2040 #else
2041                         devpriv->stc_writew(dev, AI_FIFO_Mode_HF, AI_Mode_3_Register);
2042 #endif
2043                         interrupt_a_enable |= AI_STOP_Interrupt_Enable;
2044                         break;
2045                 default:
2046                         break;
2047                 }
2048
2049                 devpriv->stc_writew(dev, 0x3f80,Interrupt_A_Ack_Register); /* clear interrupts */
2050
2051                 ni_set_bits(dev, Interrupt_A_Enable_Register, interrupt_a_enable, 1);
2052
2053                 MDPRINTK("Interrupt_A_Enable_Register = 0x%04x\n",devpriv->int_a_enable_reg);
2054         }else{
2055                 /* interrupt on nothing */
2056                 ni_set_bits(dev, Interrupt_A_Enable_Register, ~0, 0);
2057
2058                 /* XXX start polling if necessary */
2059                 MDPRINTK("interrupting on nothing\n");
2060         }
2061
2062         /* end configuration */
2063         devpriv->stc_writew(dev, AI_Configuration_End,Joint_Reset_Register);
2064
2065         switch(cmd->scan_begin_src){
2066         case TRIG_TIMER:
2067                 devpriv->stc_writew(dev, AI_SI2_Arm | AI_SI_Arm | AI_DIV_Arm | AI_SC_Arm,
2068                         AI_Command_1_Register);
2069                 break;
2070         case TRIG_EXT:
2071                 /* XXX AI_SI_Arm? */
2072                 devpriv->stc_writew(dev, AI_SI2_Arm | AI_SI_Arm | AI_DIV_Arm | AI_SC_Arm,
2073                         AI_Command_1_Register);
2074                 break;
2075         }
2076
2077 #ifdef PCIDMA
2078         ni_ai_setup_MITE_dma(dev,cmd);
2079         //mite_dump_regs(devpriv->mite);
2080 #endif
2081
2082         switch(cmd->start_src){
2083         case TRIG_NOW:
2084                 /* AI_START1_Pulse */
2085                 devpriv->stc_writew(dev,  AI_START1_Pulse | devpriv->ai_cmd2, AI_Command_2_Register );
2086                 s->async->inttrig=NULL;
2087                 break;
2088         case TRIG_EXT:
2089                 s->async->inttrig=NULL;
2090                 break;
2091         case TRIG_INT:
2092                 s->async->inttrig=ni_ai_inttrig;
2093                 break;
2094         }
2095
2096         MDPRINTK("exit ni_ai_cmd\n");
2097
2098         return 0;
2099 }
2100
2101 static int ni_ai_inttrig(comedi_device *dev,comedi_subdevice *s,
2102         unsigned int trignum)
2103 {
2104         if(trignum!=0)return -EINVAL;
2105
2106         devpriv->stc_writew(dev,  AI_START1_Pulse | devpriv->ai_cmd2, AI_Command_2_Register );
2107         s->async->inttrig=NULL;
2108
2109         return 1;
2110 }
2111
2112 static int ni_ai_config_analog_trig(comedi_device *dev,comedi_subdevice *s,
2113         comedi_insn *insn, lsampl_t *data);
2114
2115 static int ni_ai_insn_config(comedi_device *dev,comedi_subdevice *s,
2116         comedi_insn *insn, lsampl_t *data)
2117 {
2118         if(insn->n<1)return -EINVAL;
2119
2120         switch(data[0]){
2121         case INSN_CONFIG_ANALOG_TRIG:
2122                 return ni_ai_config_analog_trig(dev,s,insn,data);
2123         case INSN_CONFIG_ALT_SOURCE:
2124                 if(boardtype.reg_type == ni_reg_m_series)
2125                 {
2126                         if(data[1] & ~(MSeries_AI_Bypass_Cal_Sel_Pos_Mask |
2127                                 MSeries_AI_Bypass_Cal_Sel_Neg_Mask | MSeries_AI_Bypass_Mode_Mux_Mask |
2128                                 MSeries_AO_Bypass_AO_Cal_Sel_Mask))
2129                         {
2130                                 return -EINVAL;
2131                         }
2132                         devpriv->ai_calib_source = data[1];
2133                 } else if(boardtype.reg_type == ni_reg_6143)
2134                 {
2135                         unsigned int calib_source;
2136
2137                         calib_source = data[1] & 0xf;
2138
2139
2140                         if(calib_source > 0xF)
2141                                 return -EINVAL;
2142
2143                         devpriv->ai_calib_source = calib_source;
2144                         ni_writew(calib_source, Calibration_Channel_6143);
2145                 }else
2146                 {
2147                         unsigned int calib_source;
2148                         unsigned int calib_source_adjust;
2149
2150                         calib_source = data[1] & 0xf;
2151                         calib_source_adjust = ( data[1] >> 4 ) & 0xff;
2152
2153                         if(calib_source >= 8)
2154                                 return -EINVAL;
2155                         devpriv->ai_calib_source = calib_source;
2156                         if(boardtype.reg_type == ni_reg_611x){
2157                                 ni_writeb( calib_source_adjust, Cal_Gain_Select_611x );
2158                         }
2159                 }
2160                 return 2;
2161         default:
2162                 break;
2163         }
2164
2165         return -EINVAL;
2166 }
2167
2168 static int ni_ai_config_analog_trig(comedi_device *dev,comedi_subdevice *s,
2169         comedi_insn *insn, lsampl_t *data)
2170 {
2171         unsigned int a,b,modebits;
2172         int err=0;
2173
2174         /* data[1] is flags
2175          * data[2] is analog line
2176          * data[3] is set level
2177          * data[4] is reset level */
2178         if(!boardtype.has_analog_trig)return -EINVAL;
2179         if(insn->n!=5)return -EINVAL;
2180         if((data[1]&0xffff0000) != COMEDI_EV_SCAN_BEGIN){
2181                 data[1]&=~(COMEDI_EV_SCAN_BEGIN&0xffff);
2182                 err++;
2183         }
2184         if(data[2]>=boardtype.n_adchan){
2185                 data[2]=boardtype.n_adchan-1;
2186                 err++;
2187         }
2188         if(data[3]>255){ /* a */
2189                 data[3]=255;
2190                 err++;
2191         }
2192         if(data[4]>255){ /* b */
2193                 data[4]=255;
2194                 err++;
2195         }
2196         /*
2197          * 00 ignore
2198          * 01 set
2199          * 10 reset
2200          *
2201          * modes:
2202          *   1 level:                    +b-   +a-
2203          *     high mode                00 00 01 10
2204          *     low mode                 00 00 10 01
2205          *   2 level: (a<b)
2206          *     hysteresis low mode      10 00 00 01
2207          *     hysteresis high mode     01 00 00 10
2208          *     middle mode              10 01 01 10
2209          */
2210
2211         a=data[3];
2212         b=data[4];
2213         modebits=data[1]&0xff;
2214         if(modebits&0xf0){
2215                 /* two level mode */
2216                 if(b<a){
2217                         /* swap order */
2218                         a=data[4];
2219                         b=data[3];
2220                         modebits=((data[1]&0xf)<<4)|((data[1]&0xf0)>>4);
2221                 }
2222                 devpriv->atrig_low = a;
2223                 devpriv->atrig_high = b;
2224                 switch(modebits){
2225                 case 0x81:      /* low hysteresis mode */
2226                         devpriv->atrig_mode = 6;
2227                         break;
2228                 case 0x42:      /* high hysteresis mode */
2229                         devpriv->atrig_mode = 3;
2230                         break;
2231                 case 0x96:      /* middle window mode */
2232                         devpriv->atrig_mode = 2;
2233                         break;
2234                 default:
2235                         data[1]&=~0xff;
2236                         err++;
2237                 }
2238         }else{
2239                 /* one level mode */
2240                 if(b!=0){
2241                         data[4]=0;
2242                         err++;
2243                 }
2244                 switch(modebits){
2245                 case 0x06:      /* high window mode */
2246                         devpriv->atrig_high = a;
2247                         devpriv->atrig_mode = 0;
2248                         break;
2249                 case 0x09:      /* low window mode */
2250                         devpriv->atrig_low = a;
2251                         devpriv->atrig_mode = 1;
2252                         break;
2253                 default:
2254                         data[1]&=~0xff;
2255                         err++;
2256                 }
2257         }
2258         if(err)return -EAGAIN;
2259         return 5;
2260 }
2261
2262 /* munge data from unsigned to 2's complement for analog output bipolar modes */
2263 static void ni_ao_munge(comedi_device *dev, comedi_subdevice *s,
2264         void *data, unsigned int num_bytes, unsigned int chan_index )
2265 {
2266         comedi_async *async = s->async;
2267         unsigned int range;
2268         unsigned int i;
2269         unsigned int offset;
2270         unsigned int length = num_bytes / sizeof( sampl_t );
2271         sampl_t *array = data;
2272
2273         offset = 1 << (boardtype.aobits - 1);
2274         for(i = 0; i < length; i++)
2275         {
2276                 range = CR_RANGE( async->cmd.chanlist[ chan_index ] );
2277                 if(boardtype.ao_unipolar == 0 || (range & 1) == 0 )
2278                         array[i] -= offset;
2279 #ifdef PCIDMA
2280                 array[i] = cpu_to_le16( array[i] );
2281 #endif
2282                 chan_index++;
2283                 chan_index %= async->cmd.chanlist_len;
2284         }
2285 }
2286
2287 static int ni_ao_config_chanlist(comedi_device *dev, comedi_subdevice *s,
2288         unsigned int chanspec[], unsigned int n_chans)
2289 {
2290         unsigned int range;
2291         unsigned int chan;
2292         unsigned int conf;
2293         int i;
2294         int invert = 0;
2295
2296         for(i=0;i<n_chans;i++){
2297                 chan = CR_CHAN(chanspec[i]);
2298                 range = CR_RANGE(chanspec[i]);
2299                 if(boardtype.reg_type == ni_reg_m_series)
2300                 {
2301                         comedi_krange *krange = s->range_table->range + range;
2302                         invert = 0;
2303                         conf = 0;
2304                         switch(krange->max - krange->min)
2305                         {
2306                         case 20000000:
2307                                 conf |= MSeries_AO_DAC_Reference_10V_Internal_Bits;
2308                                 ni_writeb(0, M_Offset_AO_Reference_Attenuation(chan));
2309                                 break;
2310                         case 10000000:
2311                                 conf |= MSeries_AO_DAC_Reference_5V_Internal_Bits;
2312                                 ni_writeb(0, M_Offset_AO_Reference_Attenuation(chan));
2313                                 break;
2314                         case 4000000:
2315                                 conf |= MSeries_AO_DAC_Reference_10V_Internal_Bits;
2316                                 ni_writeb(MSeries_Attenuate_x5_Bit, M_Offset_AO_Reference_Attenuation(chan));
2317                                 break;
2318                         case 2000000:
2319                                 conf |= MSeries_AO_DAC_Reference_5V_Internal_Bits;
2320                                 ni_writeb(MSeries_Attenuate_x5_Bit, M_Offset_AO_Reference_Attenuation(chan));
2321                                 break;
2322                         default:
2323                                 rt_printk("%s: bug! unhandled ao reference voltage\n", __FUNCTION__);
2324                                 break;
2325                         }
2326                         switch(krange->max + krange->min)
2327                         {
2328                         case 0:
2329                                 conf |= MSeries_AO_DAC_Offset_0V_Bits;
2330                                 break;
2331                         case 10000000:
2332                                 conf |= MSeries_AO_DAC_Offset_5V_Bits;
2333                                 break;
2334                         default:
2335                                 rt_printk("%s: bug! unhandled ao offset voltage\n", __FUNCTION__);
2336                                 break;
2337                         }
2338                         ni_writeb(conf, M_Offset_AO_Config_Bank(chan));
2339                 }else
2340                 {
2341                         conf = AO_Channel(chan);
2342
2343                         if(boardtype.ao_unipolar){
2344                                 if((range&1) == 0){
2345                                         conf |= AO_Bipolar;
2346                                         invert = (1<<(boardtype.aobits-1));
2347                                 }else{
2348                                         invert = 0;
2349                                 }
2350                                 if(range&2)
2351                                         conf |= AO_Ext_Ref;
2352                         }else{
2353                                 conf |= AO_Bipolar;
2354                                 invert = (1<<(boardtype.aobits-1));
2355                         }
2356
2357                         /* not all boards can deglitch, but this shouldn't hurt */
2358                         if(chanspec[i] & CR_DEGLITCH)
2359                                 conf |= AO_Deglitch;
2360
2361                         /* analog reference */
2362                         /* AREF_OTHER connects AO ground to AI ground, i think */
2363                         conf |= (CR_AREF(chanspec[i])==AREF_OTHER)? AO_Ground_Ref : 0;
2364
2365                         ni_writew(conf,AO_Configuration);
2366                 }
2367                 devpriv->ao_conf[chan] = conf;
2368         }
2369         return invert;
2370 }
2371
2372 static int ni_ao_insn_read(comedi_device *dev,comedi_subdevice *s,
2373         comedi_insn *insn,lsampl_t *data)
2374 {
2375         data[0] = devpriv->ao[CR_CHAN(insn->chanspec)];
2376
2377         return 1;
2378 }
2379
2380 static int ni_ao_insn_write(comedi_device *dev,comedi_subdevice *s,
2381         comedi_insn *insn,lsampl_t *data)
2382 {
2383         unsigned int chan = CR_CHAN(insn->chanspec);
2384         unsigned int invert;
2385
2386         invert = ni_ao_config_chanlist(dev,s,&insn->chanspec,1);
2387
2388         devpriv->ao[chan] = data[0];
2389
2390         if(boardtype.reg_type == ni_reg_m_series)
2391         {
2392                 ni_writew(data[0], M_Offset_DAC_Direct_Data(chan));
2393         }
2394         else
2395                 ni_writew(data[0] ^ invert,(chan)? DAC1_Direct_Data : DAC0_Direct_Data);
2396
2397         return 1;
2398 }
2399
2400 static int ni_ao_insn_write_671x(comedi_device *dev,comedi_subdevice *s,
2401         comedi_insn *insn,lsampl_t *data)
2402 {
2403         unsigned int chan = CR_CHAN(insn->chanspec);
2404         unsigned int invert;
2405
2406         ao_win_out(1 << chan, AO_Immediate_671x);
2407         invert = 1 << (boardtype.aobits - 1);
2408
2409         ni_ao_config_chanlist(dev,s,&insn->chanspec,1);
2410
2411         devpriv->ao[chan] = data[0];
2412         ao_win_out(data[0] ^ invert, DACx_Direct_Data_671x(chan));
2413
2414         return 1;
2415 }
2416
2417 static int ni_ao_inttrig(comedi_device *dev,comedi_subdevice *s,
2418         unsigned int trignum)
2419 {
2420         int ret;
2421         int interrupt_b_bits;
2422         int i;
2423         static const int timeout = 1000;
2424
2425         if(trignum!=0)return -EINVAL;
2426
2427         ni_set_bits(dev, Interrupt_B_Enable_Register, AO_FIFO_Interrupt_Enable | AO_Error_Interrupt_Enable, 0);
2428         interrupt_b_bits = AO_Error_Interrupt_Enable;
2429 #ifdef PCIDMA
2430         devpriv->stc_writew(dev, 1, DAC_FIFO_Clear);
2431         if(boardtype.reg_type & ni_reg_6xxx_mask)
2432                 ni_ao_win_outl(dev, 0x6, AO_FIFO_Offset_Load_611x);
2433         ni_ao_setup_MITE_dma(dev, &s->async->cmd);
2434         ret = ni_ao_wait_for_dma_load(dev);
2435         if(ret < 0) return ret;
2436
2437 #else
2438         ret = ni_ao_prep_fifo(dev,s);
2439         if(ret==0)return -EPIPE;
2440
2441         interrupt_b_bits |= AO_FIFO_Interrupt_Enable;
2442 #endif
2443
2444         devpriv->stc_writew(dev, devpriv->ao_mode3|AO_Not_An_UPDATE,AO_Mode_3_Register);
2445         devpriv->stc_writew(dev, devpriv->ao_mode3,AO_Mode_3_Register);
2446         /* wait for DACs to be loaded */
2447         for(i = 0; i < timeout; i++)
2448         {
2449                 comedi_udelay(10);
2450                 if((devpriv->stc_readw(dev, Joint_Status_2_Register) & AO_TMRDACWRs_In_Progress_St) == 0)
2451                         break;
2452         }
2453         if(i == timeout)
2454         {
2455                 comedi_error(dev, "timed out waiting for AO_TMRDACWRs_In_Progress_St to clear");
2456                 return -EIO;
2457         }
2458         // stc manual says we are need to clear error interrupt after AO_TMRDACWRs_In_Progress_St clears
2459         devpriv->stc_writew(dev, AO_Error_Interrupt_Ack, Interrupt_B_Ack_Register);
2460
2461         ni_set_bits(dev, Interrupt_B_Enable_Register, interrupt_b_bits, 1);
2462
2463         devpriv->stc_writew(dev, devpriv->ao_cmd1|AO_UI_Arm|AO_UC_Arm|AO_BC_Arm|AO_DAC1_Update_Mode|AO_DAC0_Update_Mode,
2464                 AO_Command_1_Register);
2465
2466         devpriv->stc_writew(dev, devpriv->ao_cmd2|AO_START1_Pulse,AO_Command_2_Register);
2467
2468         s->async->inttrig=NULL;
2469
2470         return 0;
2471 }
2472
2473 static int ni_ao_cmd(comedi_device *dev,comedi_subdevice *s)
2474 {
2475         comedi_cmd *cmd = &s->async->cmd;
2476         int trigvar;
2477         int bits;
2478         int i;
2479
2480         if(dev->irq == 0)
2481         {
2482                 comedi_error(dev, "cannot run command without an irq");
2483                 return -EIO;
2484         }
2485         trigvar = ni_ns_to_timer(&cmd->scan_begin_arg,TRIG_ROUND_NEAREST);
2486
2487         devpriv->stc_writew(dev, AO_Configuration_Start,Joint_Reset_Register);
2488
2489         devpriv->stc_writew(dev, AO_Disarm,AO_Command_1_Register);
2490
2491         if(boardtype.reg_type & ni_reg_6xxx_mask)
2492         {
2493                 ao_win_out(CLEAR_WG, AO_Misc_611x);
2494
2495                 bits = 0;
2496                 for(i = 0; i < cmd->chanlist_len; i++)
2497                 {
2498                         int chan;
2499
2500                         chan = CR_CHAN(cmd->chanlist[i]);
2501                         bits |= 1 << chan;
2502                         ao_win_out(chan, AO_Waveform_Generation_611x);
2503                 }
2504                 ao_win_out(bits, AO_Timed_611x);
2505         }
2506
2507         ni_ao_config_chanlist(dev,s,cmd->chanlist,cmd->chanlist_len);
2508
2509         if(cmd->stop_src==TRIG_NONE){
2510                 devpriv->ao_mode1|=AO_Continuous;
2511                 devpriv->ao_mode1&=~AO_Trigger_Once;
2512         }else{
2513                 devpriv->ao_mode1&=~AO_Continuous;
2514                 devpriv->ao_mode1|=AO_Trigger_Once;
2515         }
2516         devpriv->stc_writew(dev, devpriv->ao_mode1,AO_Mode_1_Register);
2517         devpriv->ao_trigger_select&=~(AO_START1_Polarity|AO_START1_Select(-1));
2518         devpriv->ao_trigger_select|=AO_START1_Edge|AO_START1_Sync;
2519         devpriv->stc_writew(dev, devpriv->ao_trigger_select,AO_Trigger_Select_Register);
2520         devpriv->ao_mode3&=~AO_Trigger_Length;
2521         devpriv->stc_writew(dev, devpriv->ao_mode3,AO_Mode_3_Register);
2522
2523         devpriv->stc_writew(dev, devpriv->ao_mode1,AO_Mode_1_Register);
2524         devpriv->ao_mode2&=~AO_BC_Initial_Load_Source;
2525         devpriv->stc_writew(dev, devpriv->ao_mode2,AO_Mode_2_Register);
2526         if(cmd->stop_src==TRIG_NONE){
2527                 devpriv->stc_writel(dev, 0xffffff,AO_BC_Load_A_Register);
2528         }else{
2529                 devpriv->stc_writel(dev, 0,AO_BC_Load_A_Register);
2530         }
2531         devpriv->stc_writew(dev, AO_BC_Load,AO_Command_1_Register);
2532         devpriv->ao_mode2&=~AO_UC_Initial_Load_Source;
2533         devpriv->stc_writew(dev, devpriv->ao_mode2,AO_Mode_2_Register);
2534         switch(cmd->stop_src){
2535         case TRIG_COUNT:
2536                 devpriv->stc_writel(dev, cmd->stop_arg,AO_UC_Load_A_Register);
2537                 devpriv->stc_writew(dev, AO_UC_Load,AO_Command_1_Register);
2538                 devpriv->stc_writel(dev, cmd->stop_arg - 1,AO_UC_Load_A_Register);
2539                 break;
2540         case TRIG_NONE:
2541                 devpriv->stc_writel(dev, 0xffffff,AO_UC_Load_A_Register);
2542                 devpriv->stc_writew(dev, AO_UC_Load,AO_Command_1_Register);
2543                 devpriv->stc_writel(dev, 0xffffff,AO_UC_Load_A_Register);
2544                 break;
2545         default:
2546                 devpriv->stc_writel(dev, 0,AO_UC_Load_A_Register);
2547                 devpriv->stc_writew(dev, AO_UC_Load,AO_Command_1_Register);
2548                 devpriv->stc_writel(dev, cmd->stop_arg,AO_UC_Load_A_Register);
2549         }
2550
2551         devpriv->ao_cmd2&=~AO_BC_Gate_Enable;
2552         devpriv->stc_writew(dev, devpriv->ao_cmd2,AO_Command_2_Register);
2553         devpriv->ao_mode1&=~(AO_UI_Source_Select(0x1f)|AO_UI_Source_Polarity);
2554         devpriv->stc_writew(dev, devpriv->ao_mode1,AO_Mode_1_Register);
2555         devpriv->ao_mode2&=~(AO_UI_Reload_Mode(3)|AO_UI_Initial_Load_Source);
2556         devpriv->stc_writew(dev, devpriv->ao_mode2,AO_Mode_2_Register);
2557         devpriv->stc_writel(dev, 1,AO_UI_Load_A_Register);
2558         devpriv->stc_writew(dev, AO_UI_Load,AO_Command_1_Register);
2559         devpriv->stc_writel(dev, trigvar,AO_UI_Load_A_Register);
2560
2561         if((boardtype.reg_type & ni_reg_6xxx_mask) == 0){
2562                 if(cmd->scan_end_arg>1){
2563                         devpriv->ao_mode1|=AO_Multiple_Channels;
2564                         devpriv->stc_writew(dev, AO_Number_Of_Channels(cmd->scan_end_arg-1)|
2565                                 AO_UPDATE_Output_Select(1),
2566                                 AO_Output_Control_Register);
2567                 }else{
2568                         devpriv->ao_mode1&=~AO_Multiple_Channels;
2569                         devpriv->stc_writew(dev, AO_Number_Of_Channels(CR_CHAN(cmd->chanlist[0]))|
2570                                 AO_UPDATE_Output_Select(1),
2571                                 AO_Output_Control_Register);
2572                 }
2573                 devpriv->stc_writew(dev, devpriv->ao_mode1,AO_Mode_1_Register);
2574         }
2575
2576         devpriv->stc_writew(dev, AO_DAC0_Update_Mode|AO_DAC1_Update_Mode,AO_Command_1_Register);
2577
2578         devpriv->ao_mode3|=AO_Stop_On_Overrun_Error;
2579         devpriv->stc_writew(dev, devpriv->ao_mode3,AO_Mode_3_Register);
2580
2581         devpriv->ao_mode2 &= AO_FIFO_Mode_Mask;
2582 #ifdef PCIDMA
2583         devpriv->ao_mode2 |= AO_FIFO_Mode_HF_to_F;
2584 #else
2585         devpriv->ao_mode2 |= AO_FIFO_Mode_HF;
2586 #endif
2587         devpriv->ao_mode2 &= ~AO_FIFO_Retransmit_Enable;
2588         devpriv->stc_writew(dev, devpriv->ao_mode2,AO_Mode_2_Register);
2589
2590         bits = AO_BC_Source_Select | AO_UPDATE_Pulse_Width |
2591                 AO_TMRDACWR_Pulse_Width;
2592         if( boardtype.ao_fifo_depth )
2593                 bits |= AO_FIFO_Enable;
2594         else
2595                 bits |= AO_DMA_PIO_Control;
2596         devpriv->stc_writew(dev, bits, AO_Personal_Register);
2597         // enable sending of ao dma requests
2598         devpriv->stc_writew(dev, AO_AOFREQ_Enable, AO_Start_Select_Register);
2599
2600         devpriv->stc_writew(dev, AO_Configuration_End,Joint_Reset_Register);
2601
2602         if(cmd->stop_src==TRIG_COUNT) {
2603                 devpriv->stc_writew(dev, AO_BC_TC_Interrupt_Ack,Interrupt_B_Ack_Register);
2604                 ni_set_bits(dev, Interrupt_B_Enable_Register,
2605                         AO_BC_TC_Interrupt_Enable, 1);
2606         }
2607
2608         s->async->inttrig=ni_ao_inttrig;
2609
2610         return 0;
2611 }
2612
2613 static int ni_ao_cmdtest(comedi_device *dev,comedi_subdevice *s,comedi_cmd *cmd)
2614 {
2615         int err=0;
2616         int tmp;
2617
2618         /* step 1: make sure trigger sources are trivially valid */
2619
2620         tmp=cmd->start_src;
2621         cmd->start_src &= TRIG_INT;
2622         if(!cmd->start_src || tmp!=cmd->start_src)err++;
2623
2624         tmp=cmd->scan_begin_src;
2625         cmd->scan_begin_src &= TRIG_TIMER;
2626         if(!cmd->scan_begin_src || tmp!=cmd->scan_begin_src)err++;
2627
2628         tmp=cmd->convert_src;
2629         cmd->convert_src &= TRIG_NOW;
2630         if(!cmd->convert_src || tmp!=cmd->convert_src)err++;
2631
2632         tmp=cmd->scan_end_src;
2633         cmd->scan_end_src &= TRIG_COUNT;
2634         if(!cmd->scan_end_src || tmp!=cmd->scan_end_src)err++;
2635
2636         tmp=cmd->stop_src;
2637         cmd->stop_src &= TRIG_COUNT|TRIG_NONE;
2638         if(!cmd->stop_src || tmp!=cmd->stop_src)err++;
2639
2640         if(err)return 1;
2641
2642         /* step 2: make sure trigger sources are unique and mutually compatible */
2643
2644         if(cmd->stop_src!=TRIG_COUNT &&
2645            cmd->stop_src!=TRIG_NONE)err++;
2646
2647         if(err)return 2;
2648
2649         /* step 3: make sure arguments are trivially compatible */
2650
2651         if(cmd->start_arg!=0){
2652                 cmd->start_arg=0;
2653                 err++;
2654         }
2655 #if 0
2656         /* XXX need ao_speed */
2657         if(cmd->scan_begin_arg<boardtype.ao_speed){
2658                 cmd->scan_begin_arg=boardtype.ao_speed;
2659                 err++;
2660         }
2661 #endif
2662         if(cmd->scan_begin_arg>TIMER_BASE*0xffffff){ /* XXX check */
2663                 cmd->scan_begin_arg=TIMER_BASE*0xffffff;
2664                 err++;
2665         }
2666         if(cmd->convert_arg!=0){
2667                 cmd->convert_arg=0;
2668                 err++;
2669         }
2670         if(cmd->scan_end_arg!=cmd->chanlist_len){
2671                 cmd->scan_end_arg=cmd->chanlist_len;
2672                 err++;
2673         }
2674         if(cmd->stop_src==TRIG_COUNT){ /* XXX check */
2675                 if(cmd->stop_arg>0x00ffffff){
2676                         cmd->stop_arg=0x00ffffff;
2677                         err++;
2678                 }
2679         }else{
2680                 /* TRIG_NONE */
2681                 if(cmd->stop_arg!=0){
2682                         cmd->stop_arg=0;
2683                         err++;
2684                 }
2685         }
2686
2687         if(err)return 3;
2688
2689         /* step 4: fix up any arguments */
2690
2691         tmp = cmd->scan_begin_arg;
2692         ni_ns_to_timer(&cmd->scan_begin_arg,cmd->flags&TRIG_ROUND_MASK);
2693         if(tmp!=cmd->scan_begin_arg)err++;
2694
2695         if(err)return 4;
2696
2697         /* step 5: fix up chanlist */
2698
2699         if(err)return 5;
2700
2701         return 0;
2702 }
2703
2704
2705 static int ni_ao_reset(comedi_device *dev,comedi_subdevice *s)
2706 {
2707         //devpriv->ao0p=0x0000;
2708         //ni_writew(devpriv->ao0p,AO_Configuration);
2709
2710         //devpriv->ao1p=AO_Channel(1);
2711         //ni_writew(devpriv->ao1p,AO_Configuration);
2712
2713 #ifdef PCIDMA
2714         mite_dma_disarm(devpriv->mite, AO_DMA_CHAN);
2715         writel(CHOR_DMARESET | CHOR_FRESET, devpriv->mite->mite_io_addr + MITE_CHOR(AO_DMA_CHAN));
2716 #endif
2717
2718         devpriv->stc_writew(dev, AO_Configuration_Start,Joint_Reset_Register);
2719         devpriv->stc_writew(dev, AO_Disarm,AO_Command_1_Register);
2720         ni_set_bits(dev,Interrupt_B_Enable_Register,~0,0);
2721         devpriv->stc_writew(dev, AO_BC_Source_Select, AO_Personal_Register);
2722         devpriv->stc_writew(dev, 0x3f98,Interrupt_B_Ack_Register);
2723         devpriv->stc_writew(dev, AO_BC_Source_Select | AO_UPDATE_Pulse_Width |
2724                 AO_TMRDACWR_Pulse_Width, AO_Personal_Register);
2725         devpriv->stc_writew(dev, 0,AO_Output_Control_Register);
2726         devpriv->stc_writew(dev, 0,AO_Start_Select_Register);
2727         devpriv->ao_cmd1=0;
2728         devpriv->stc_writew(dev, devpriv->ao_cmd1,AO_Command_1_Register);
2729         devpriv->ao_cmd2=0;
2730         devpriv->ao_mode1=0;
2731         devpriv->ao_mode2=0;
2732         if(boardtype.reg_type == ni_reg_m_series)
2733                 devpriv->ao_mode3 = AO_Last_Gate_Disable;
2734         else
2735                 devpriv->ao_mode3 = 0;
2736         devpriv->stc_writew(dev, devpriv->ao_mode3, AO_Mode_3_Register);
2737         devpriv->ao_trigger_select=0;
2738         if(boardtype.reg_type & ni_reg_6xxx_mask){
2739                 ao_win_out(0x3, AO_Immediate_671x);
2740                 ao_win_out(CLEAR_WG, AO_Misc_611x);
2741         }
2742         devpriv->stc_writew(dev, AO_Configuration_End, Joint_Reset_Register);
2743
2744         return 0;
2745 }
2746
2747 static int ni_dio_insn_config(comedi_device *dev,comedi_subdevice *s,
2748         comedi_insn *insn,lsampl_t *data)
2749 {
2750 #ifdef DEBUG_DIO
2751         printk("ni_dio_insn_config() chan=%d io=%d\n",
2752                 CR_CHAN(insn->chanspec),data[0]);
2753 #endif
2754         switch(data[0]){
2755         case INSN_CONFIG_DIO_OUTPUT:
2756                 s->io_bits |= 1<<CR_CHAN(insn->chanspec);
2757                 break;
2758         case INSN_CONFIG_DIO_INPUT:
2759                 s->io_bits &= ~(1<<CR_CHAN(insn->chanspec));
2760                 break;
2761         case INSN_CONFIG_DIO_QUERY:
2762                 data[1] = (s->io_bits & (1<<CR_CHAN(insn->chanspec))) ? COMEDI_OUTPUT : COMEDI_INPUT;
2763                 return insn->n;
2764                 break;
2765         default:
2766                 return -EINVAL;
2767         }
2768
2769         devpriv->dio_control &= ~DIO_Pins_Dir_Mask;
2770         devpriv->dio_control |= DIO_Pins_Dir(s->io_bits);
2771         devpriv->stc_writew(dev, devpriv->dio_control,DIO_Control_Register);
2772
2773         return 1;
2774 }
2775
2776 static int ni_dio_insn_bits(comedi_device *dev,comedi_subdevice *s,
2777         comedi_insn *insn,lsampl_t *data)
2778 {
2779 #ifdef DEBUG_DIO
2780         printk("ni_dio_insn_bits() mask=0x%x bits=0x%x\n",data[0],data[1]);
2781 #endif
2782         if(insn->n!=2)return -EINVAL;
2783         if(data[0]){
2784                 /* Perform check to make sure we're not using the
2785                    serial part of the dio */
2786                 if((data[0] & (DIO_SDIN | DIO_SDOUT)) && devpriv->serial_interval_ns)
2787                         return -EBUSY;
2788
2789                 s->state &= ~data[0];
2790                 s->state |= (data[0]&data[1]);
2791                 devpriv->dio_output &= ~DIO_Parallel_Data_Mask;
2792                 devpriv->dio_output |= DIO_Parallel_Data_Out(s->state);
2793                 devpriv->stc_writew(dev, devpriv->dio_output,DIO_Output_Register);
2794         }
2795         data[1] = devpriv->stc_readw(dev, DIO_Parallel_Input_Register);
2796
2797         return 2;
2798 }
2799
2800 static int ni_serial_insn_config(comedi_device *dev,comedi_subdevice *s,
2801                                  comedi_insn *insn,lsampl_t *data)
2802 {
2803         int err = insn->n;
2804         unsigned char byte_out, byte_in;
2805
2806         if(insn->n!=2)return -EINVAL;
2807
2808         switch(data[0]) {
2809         case INSN_CONFIG_SERIAL_CLOCK:
2810
2811 #ifdef DEBUG_DIO
2812                 printk("SPI serial clock Config cd\n", data[1]);
2813 #endif
2814                 devpriv->serial_hw_mode = 1;
2815                 devpriv->dio_control |= DIO_HW_Serial_Enable;
2816
2817                 if(data[1] == SERIAL_DISABLED) {
2818                         devpriv->serial_hw_mode = 0;
2819                         devpriv->dio_control &= ~(DIO_HW_Serial_Enable |
2820                                                   DIO_Software_Serial_Control);
2821                         data[1] = SERIAL_DISABLED;
2822                         devpriv->serial_interval_ns = data[1];
2823                 }
2824                 else if(data[1] <= SERIAL_600NS) {
2825                         /* Warning: this clock speed is too fast to reliably
2826                         control SCXI. */
2827                         devpriv->dio_control &= ~DIO_HW_Serial_Timebase;
2828                         devpriv->clock_and_fout |= Slow_Internal_Timebase;
2829                         devpriv->clock_and_fout &= ~DIO_Serial_Out_Divide_By_2;
2830                         data[1] = SERIAL_600NS;
2831                         devpriv->serial_interval_ns = data[1];
2832                 }
2833                 else if(data[1] <= SERIAL_1_2US) {
2834                         devpriv->dio_control &= ~DIO_HW_Serial_Timebase;
2835                         devpriv->clock_and_fout |= Slow_Internal_Timebase |
2836                                 DIO_Serial_Out_Divide_By_2;
2837                         data[1] = SERIAL_1_2US;
2838                         devpriv->serial_interval_ns = data[1];
2839                 }
2840                 else if(data[1] <= SERIAL_10US) {
2841                         devpriv->dio_control |= DIO_HW_Serial_Timebase;
2842                         devpriv->clock_and_fout |= Slow_Internal_Timebase |
2843                                 DIO_Serial_Out_Divide_By_2;
2844                         /* Note: DIO_Serial_Out_Divide_By_2 only affects
2845                         600ns/1.2us. If you turn divide_by_2 off with the
2846                         slow clock, you will still get 10us, except then
2847                         all your delays are wrong. */
2848                         data[1] = SERIAL_10US;
2849                         devpriv->serial_interval_ns = data[1];
2850                 }
2851                 else {
2852                         devpriv->dio_control &= ~(DIO_HW_Serial_Enable |
2853                                                   DIO_Software_Serial_Control);
2854                         devpriv->serial_hw_mode = 0;
2855                         data[1] = (data[1] / 1000) * 1000;
2856                         devpriv->serial_interval_ns = data[1];
2857                 }
2858
2859                 devpriv->stc_writew(dev, devpriv->dio_control,DIO_Control_Register);
2860                 devpriv->stc_writew(dev, devpriv->clock_and_fout,Clock_and_FOUT_Register);
2861                 return 1;
2862
2863         break;
2864
2865         case INSN_CONFIG_BIDIRECTIONAL_DATA:
2866
2867                 if(devpriv->serial_interval_ns == 0) {
2868                         return -EINVAL;
2869                 }
2870
2871                 byte_out = data[1] & 0xFF;
2872
2873                 if(devpriv->serial_hw_mode) {
2874                         err = ni_serial_hw_readwrite8(dev,s,byte_out,&byte_in);
2875                 } else if(devpriv->serial_interval_ns > 0) {
2876                         err = ni_serial_sw_readwrite8(dev,s,byte_out,&byte_in);
2877                 } else {
2878                         printk("ni_serial_insn_config: serial disabled!\n");
2879                         return -EINVAL;
2880                 }
2881                 if(err < 0) return err;
2882                 data[1] = byte_in & 0xFF;
2883                 return insn->n;
2884
2885         break;
2886         default:
2887                 return -EINVAL;
2888         }
2889
2890 }
2891
2892 static int ni_serial_hw_readwrite8(comedi_device *dev,comedi_subdevice *s,
2893                                    unsigned char data_out,
2894                                    unsigned char *data_in)
2895 {
2896         unsigned int status1;
2897         int err = 0, count = 20;
2898
2899 #ifdef DEBUG_DIO
2900         printk("ni_serial_hw_readwrite8: outputting 0x%x\n", data_out);
2901 #endif
2902
2903         devpriv->dio_output &= ~DIO_Serial_Data_Mask;
2904         devpriv->dio_output |= DIO_Serial_Data_Out(data_out);
2905         devpriv->stc_writew(dev, devpriv->dio_output,DIO_Output_Register);
2906
2907         status1 = devpriv->stc_readw(dev, Joint_Status_1_Register);
2908         if(status1 & DIO_Serial_IO_In_Progress_St) {
2909                 err = -EBUSY;
2910                 goto Error;
2911         }
2912
2913         devpriv->dio_control |= DIO_HW_Serial_Start;
2914         devpriv->stc_writew(dev, devpriv->dio_control,DIO_Control_Register);
2915         devpriv->dio_control &= ~DIO_HW_Serial_Start;
2916
2917         /* Wait until STC says we're done, but don't loop infinitely. */
2918         while((status1 = devpriv->stc_readw(dev, Joint_Status_1_Register)) & DIO_Serial_IO_In_Progress_St) {
2919                 /* Delay one bit per loop */
2920                 comedi_udelay((devpriv->serial_interval_ns + 999) / 1000);
2921                 if(--count < 0) {
2922                         printk("ni_serial_hw_readwrite8: SPI serial I/O didn't finish in time!\n");
2923                         err = -ETIME;
2924                         goto Error;
2925                 }
2926         }
2927
2928         /* Delay for last bit. This delay is absolutely necessary, because
2929            DIO_Serial_IO_In_Progress_St goes high one bit too early. */
2930         comedi_udelay((devpriv->serial_interval_ns + 999) / 1000);
2931
2932         if(data_in != NULL) {
2933                 *data_in = devpriv->stc_readw(dev, DIO_Serial_Input_Register);
2934 #ifdef DEBUG_DIO
2935                 printk("ni_serial_hw_readwrite8: inputted 0x%x\n", *data_in);
2936 #endif
2937         }
2938
2939  Error:
2940         devpriv->stc_writew(dev, devpriv->dio_control,DIO_Control_Register);
2941
2942         return err;
2943 }
2944
2945 static int ni_serial_sw_readwrite8(comedi_device *dev,comedi_subdevice *s,
2946                                    unsigned char data_out,
2947                                    unsigned char *data_in)
2948 {
2949         unsigned char mask, input = 0;
2950
2951 #ifdef DEBUG_DIO
2952         printk("ni_serial_sw_readwrite8: outputting 0x%x\n", data_out);
2953 #endif
2954
2955         /* Wait for one bit before transfer */
2956         comedi_udelay((devpriv->serial_interval_ns + 999) / 1000);
2957
2958         for(mask = 0x80; mask; mask >>= 1) {
2959                 /* Output current bit; note that we cannot touch s->state
2960            because it is a per-subdevice field, and serial is
2961                    a separate subdevice from DIO. */
2962                 devpriv->dio_output &= ~DIO_SDOUT;
2963                 if(data_out & mask) {
2964                         devpriv->dio_output |= DIO_SDOUT;
2965                 }
2966                 devpriv->stc_writew(dev, devpriv->dio_output,DIO_Output_Register);
2967
2968                 /* Assert SDCLK (active low, inverted), wait for half of
2969                    the delay, deassert SDCLK, and wait for the other half. */
2970                 devpriv->dio_control |= DIO_Software_Serial_Control;
2971                 devpriv->stc_writew(dev, devpriv->dio_control,DIO_Control_Register);
2972
2973                 comedi_udelay((devpriv->serial_interval_ns + 999) / 2000);
2974
2975                 devpriv->dio_control &= ~DIO_Software_Serial_Control;
2976                 devpriv->stc_writew(dev, devpriv->dio_control,DIO_Control_Register);
2977
2978                 comedi_udelay((devpriv->serial_interval_ns + 999) / 2000);
2979
2980                 /* Input current bit */
2981                 if(devpriv->stc_readw(dev, DIO_Parallel_Input_Register) & DIO_SDIN) {
2982 /*                      printk("DIO_P_I_R: 0x%x\n", devpriv->stc_readw(dev, DIO_Parallel_Input_Register)); */
2983                         input |= mask;
2984                 }
2985         }
2986 #ifdef DEBUG_DIO
2987         printk("ni_serial_sw_readwrite8: inputted 0x%x\n", input);
2988 #endif
2989         if(data_in) *data_in = input;
2990
2991         return 0;
2992 }
2993
2994 static void mio_common_detach(comedi_device *dev)
2995 {
2996         if(dev->subdevices && boardtype.has_8255)
2997                 subdev_8255_cleanup(dev,dev->subdevices+3);
2998 }
2999
3000 static void init_ao_67xx(comedi_device *dev, comedi_subdevice *s)
3001 {
3002         int i;
3003
3004         for(i = 0; i < s->n_chan; i++)
3005                 ni_ao_win_outw(dev, AO_Channel(i) | 0x0, AO_Configuration_2_67xx);
3006 }
3007
3008 static int ni_alloc_private(comedi_device *dev)
3009 {
3010         int ret;
3011
3012         ret = alloc_private(dev, sizeof(ni_private));
3013         if(ret < 0) return ret;
3014
3015         spin_lock_init(&devpriv->window_lock);
3016
3017         return 0;
3018 };
3019
3020 static int ni_E_init(comedi_device *dev,comedi_devconfig *it)
3021 {
3022         comedi_subdevice *s;
3023         int bits;
3024
3025         if(boardtype.n_aochan > MAX_N_AO_CHAN)
3026         {
3027                 printk("bug! boardtype.n_aochan > MAX_N_AO_CHAN\n");
3028                 return -EINVAL;
3029         }
3030
3031         if(alloc_subdevices(dev, 11) < 0)
3032                 return -ENOMEM;
3033
3034         /* analog input subdevice */
3035
3036         s=dev->subdevices+0;
3037         dev->read_subdev=s;
3038         if(boardtype.n_adchan){
3039                 s->type=COMEDI_SUBD_AI;
3040                 s->subdev_flags=SDF_READABLE | SDF_DIFF | SDF_DITHER;
3041                 if(boardtype.reg_type != ni_reg_611x)
3042                         s->subdev_flags |= SDF_GROUND | SDF_COMMON | SDF_OTHER;
3043                 if(boardtype.adbits > 16)
3044                         s->subdev_flags |= SDF_LSAMPL;
3045                 if(boardtype.reg_type == ni_reg_m_series)
3046                         s->subdev_flags |= SDF_SOFT_CALIBRATED;
3047                 s->n_chan=boardtype.n_adchan;
3048                 s->len_chanlist=512;
3049                 s->maxdata=(1<<boardtype.adbits)-1;
3050                 s->range_table=ni_range_lkup[boardtype.gainlkup];
3051                 s->insn_read=ni_ai_insn_read;
3052                 s->insn_config=ni_ai_insn_config;
3053                 s->do_cmdtest=ni_ai_cmdtest;
3054                 s->do_cmd=ni_ai_cmd;
3055                 s->cancel=ni_ai_reset;
3056                 s->poll=ni_ai_poll;
3057                 s->munge=ni_ai_munge;
3058         }else{
3059                 s->type=COMEDI_SUBD_UNUSED;
3060         }
3061
3062         /* analog output subdevice */
3063
3064         s=dev->subdevices+1;
3065         if(boardtype.n_aochan){
3066                 dev->write_subdev=s;
3067                 s->type=COMEDI_SUBD_AO;
3068                 s->subdev_flags=SDF_WRITABLE|SDF_DEGLITCH|SDF_GROUND;
3069                 if(boardtype.reg_type == ni_reg_m_series)
3070                         s->subdev_flags |= SDF_SOFT_CALIBRATED;
3071                 s->n_chan=boardtype.n_aochan;
3072                 s->maxdata=(1<<boardtype.aobits)-1;
3073                 s->range_table = boardtype.ao_range_table;
3074                 s->insn_read=ni_ao_insn_read;
3075                 if(boardtype.reg_type & ni_reg_6xxx_mask){
3076                         s->insn_write=ni_ao_insn_write_671x;
3077                 }else{
3078                         s->insn_write=ni_ao_insn_write;
3079                 }
3080 #ifdef PCIDMA
3081                 if(boardtype.n_aochan){
3082 #else
3083                 if(boardtype.ao_fifo_depth){
3084 #endif
3085                         s->do_cmd=ni_ao_cmd;
3086                         s->do_cmdtest=ni_ao_cmdtest;
3087                         s->len_chanlist = boardtype.n_aochan;
3088                         if(boardtype.reg_type != ni_reg_m_series)
3089                                 s->munge=ni_ao_munge;
3090                 }
3091                 s->cancel=ni_ao_reset;
3092         }else{
3093                 s->type=COMEDI_SUBD_UNUSED;
3094         }
3095         if((boardtype.reg_type & ni_reg_67xx_mask))
3096                 init_ao_67xx(dev, s);
3097
3098         /* digital i/o subdevice */
3099
3100         s=dev->subdevices+2;
3101         s->type=COMEDI_SUBD_DIO;
3102         s->subdev_flags=SDF_WRITABLE|SDF_READABLE;
3103         s->n_chan=8;
3104         s->maxdata=1;
3105         s->range_table=&range_digital;
3106         s->io_bits=0;           /* all bits input */
3107         s->insn_bits=ni_dio_insn_bits;
3108         s->insn_config=ni_dio_insn_config;
3109
3110         /* dio setup */
3111         devpriv->dio_control = DIO_Pins_Dir(s->io_bits);
3112         devpriv->stc_writew(dev, devpriv->dio_control,DIO_Control_Register);
3113
3114         /* 8255 device */
3115         s=dev->subdevices+3;
3116         if(boardtype.has_8255){
3117                 subdev_8255_init(dev,s,ni_8255_callback,(unsigned long)dev);
3118         }else{
3119                 s->type=COMEDI_SUBD_UNUSED;
3120         }
3121
3122         /* general purpose counter/timer device */
3123         s=dev->subdevices+4;
3124         s->type=COMEDI_SUBD_COUNTER;
3125         s->subdev_flags=SDF_READABLE|SDF_WRITABLE;
3126         s->insn_read=  ni_gpct_insn_read;
3127         s->insn_write= ni_gpct_insn_write;
3128         s->insn_config=ni_gpct_insn_config;
3129         s->n_chan=2;
3130         s->maxdata=1;
3131         devpriv->an_trig_etc_reg = 0;
3132         GPCT_Reset(dev,0);
3133         GPCT_Reset(dev,1);
3134
3135         /* calibration subdevice -- ai and ao */
3136         s=dev->subdevices+5;
3137         s->type=COMEDI_SUBD_CALIB;
3138         if(boardtype.reg_type == ni_reg_m_series)
3139         {
3140                 // internal PWM analog output used for AI nonlinearity calibration
3141                 s->subdev_flags = SDF_INTERNAL;
3142                 s->insn_config = &ni_m_series_pwm_config;
3143                 s->n_chan = 1;
3144                 s->maxdata = 0;
3145                 ni_writel(0x0, M_Offset_Cal_PWM);
3146         } else if(boardtype.reg_type == ni_reg_6143)
3147         {
3148                 // internal PWM analog output used for AI nonlinearity calibration
3149                 s->subdev_flags = SDF_INTERNAL;
3150                 s->insn_config = &ni_6143_pwm_config;
3151                 s->n_chan = 1;
3152                 s->maxdata = 0;
3153         }else
3154         {
3155                 s->subdev_flags = SDF_WRITABLE | SDF_INTERNAL;
3156                 s->insn_read = &ni_calib_insn_read;
3157                 s->insn_write = &ni_calib_insn_write;
3158                 caldac_setup(dev, s);
3159         }
3160
3161         /* EEPROM */
3162         s=dev->subdevices+6;
3163         s->type=COMEDI_SUBD_MEMORY;
3164         s->subdev_flags=SDF_READABLE|SDF_INTERNAL;
3165         s->maxdata=0xff;
3166         if(boardtype.reg_type == ni_reg_m_series)
3167         {
3168                 s->n_chan = M_SERIES_EEPROM_SIZE;
3169                 s->insn_read = &ni_m_series_eeprom_insn_read;
3170         }else
3171         {
3172                 s->n_chan = 512;
3173                 s->insn_read = &ni_eeprom_insn_read;
3174         }
3175         /* PFI */
3176         s=dev->subdevices+7;
3177         s->type=COMEDI_SUBD_DIO;
3178         s->subdev_flags=SDF_READABLE|SDF_WRITABLE|SDF_INTERNAL;
3179         s->n_chan=10;
3180         s->maxdata=1;
3181         s->insn_bits = ni_pfi_insn_bits;
3182         s->insn_config = ni_pfi_insn_config;
3183         ni_set_bits(dev, IO_Bidirection_Pin_Register, ~0, 0);
3184
3185         /* cs5529 calibration adc */
3186         s = dev->subdevices + 8;
3187         if(boardtype.reg_type & ni_reg_67xx_mask)
3188         {
3189                 s->type = COMEDI_SUBD_AI;
3190                 s->subdev_flags = SDF_READABLE | SDF_DIFF | SDF_INTERNAL;
3191                 // one channel for each analog output channel
3192                 s->n_chan = boardtype.n_aochan;
3193                 s->maxdata = (1 << 16) - 1;
3194                 s->range_table = &range_unknown; /* XXX */
3195                 s->insn_read=cs5529_ai_insn_read;
3196                 s->insn_config=NULL;
3197                 init_cs5529(dev);
3198         }else
3199         {
3200                 s->type=COMEDI_SUBD_UNUSED;
3201         }
3202
3203         /* Serial */
3204         s=dev->subdevices+9;
3205         s->type=COMEDI_SUBD_SERIAL;
3206         s->subdev_flags=SDF_READABLE|SDF_WRITABLE|SDF_INTERNAL;
3207         s->n_chan=1;
3208         s->maxdata=0xff;
3209         s->insn_config = ni_serial_insn_config;
3210         devpriv->serial_interval_ns = 0;
3211         devpriv->serial_hw_mode = 0;
3212
3213         /* RTSI */
3214         s=dev->subdevices+10;
3215         s->type=COMEDI_SUBD_DIO;
3216         s->subdev_flags=SDF_READABLE|SDF_WRITABLE|SDF_INTERNAL;
3217         s->n_chan=7;
3218         s->maxdata=1;
3219         s->insn_bits = ni_rtsi_insn_bits;
3220         s->insn_config = ni_rtsi_insn_config;
3221         ni_rtsi_init(dev);
3222
3223         /* ai configuration */
3224         ni_ai_reset(dev,dev->subdevices+0);
3225         if((boardtype.reg_type & ni_reg_6xxx_mask) == 0){
3226                 // BEAM is this needed for PCI-6143 ??
3227                 devpriv->clock_and_fout =
3228                         Slow_Internal_Time_Divide_By_2 |
3229                         Slow_Internal_Timebase |
3230                         Clock_To_Board_Divide_By_2 |
3231                         Clock_To_Board |
3232                         AI_Output_Divide_By_2 |
3233                         AO_Output_Divide_By_2;
3234         }else{
3235                 devpriv->clock_and_fout =
3236                         Slow_Internal_Time_Divide_By_2 |
3237                         Slow_Internal_Timebase |
3238                         Clock_To_Board_Divide_By_2 |
3239                         Clock_To_Board;
3240         }
3241         devpriv->stc_writew(dev, devpriv->clock_and_fout, Clock_and_FOUT_Register);
3242
3243         /* analog output configuration */
3244         ni_ao_reset(dev,dev->subdevices + 1);
3245
3246         if(dev->irq){
3247                 devpriv->stc_writew(dev, (IRQ_POLARITY?Interrupt_Output_Polarity:0) |
3248                         (Interrupt_Output_On_3_Pins&0) |
3249                         Interrupt_A_Enable |
3250                         Interrupt_B_Enable |
3251                         Interrupt_A_Output_Select(interrupt_pin(dev->irq)) |
3252                         Interrupt_B_Output_Select(interrupt_pin(dev->irq)),
3253                         Interrupt_Control_Register
3254                 );
3255         }
3256
3257         /* DMA setup */
3258         /* tell the STC which dma channels to use for AI and AO */
3259         bits = 1 << ( AI_DMA_CHAN );
3260         bits |= 1 << ( AO_DMA_CHAN + 4 );
3261         ni_writeb( bits, AI_AO_Select);
3262         /* tell the STC which dma channels to use for
3263          * General purpose counters 0 and 1 */
3264         bits = 1 << ( GPC0_DMA_CHAN );
3265         bits |= 1 << ( GPC1_DMA_CHAN + 4 );
3266         ni_writeb( bits, G0_G1_Select);
3267
3268         if(boardtype.reg_type & ni_reg_6xxx_mask)
3269         {
3270                 ni_writeb( 0, Magic_611x );
3271         }else if(boardtype.reg_type == ni_reg_m_series)
3272         {
3273                 int channel;
3274                 for(channel = 0; channel < boardtype.n_aochan; ++channel)
3275                 {
3276                         ni_writeb(0xf, M_Offset_AO_Waveform_Order(channel));
3277                         ni_writeb(0x0, M_Offset_AO_Reference_Attenuation(channel));
3278                 }
3279                 ni_writeb(0x0, M_Offset_AO_Calibration);
3280         }
3281
3282         printk("\n");
3283
3284         return 0;
3285 }
3286
3287
3288
3289 static int ni_8255_callback(int dir,int port,int data,unsigned long arg)
3290 {
3291         comedi_device *dev=(comedi_device *)arg;
3292
3293         if(dir){
3294                 ni_writeb(data,Port_A+2*port);
3295                 return 0;
3296         }else{
3297                 return ni_readb(Port_A+2*port);
3298         }
3299 }
3300
3301 /*
3302         presents the EEPROM as a subdevice
3303 */
3304
3305 static int ni_eeprom_insn_read(comedi_device *dev,comedi_subdevice *s,
3306         comedi_insn *insn,lsampl_t *data)
3307 {
3308         data[0]=ni_read_eeprom(dev,CR_CHAN(insn->chanspec));
3309
3310         return 1;
3311 }
3312
3313 /*
3314         reads bytes out of eeprom
3315 */
3316
3317 static int ni_read_eeprom(comedi_device *dev,int addr)
3318 {
3319         int bit;
3320         int bitstring;
3321
3322         bitstring=0x0300|((addr&0x100)<<3)|(addr&0xff);
3323         ni_writeb(0x04,Serial_Command);
3324         for(bit=0x8000;bit;bit>>=1){
3325                 ni_writeb(0x04|((bit&bitstring)?0x02:0),Serial_Command);
3326                 ni_writeb(0x05|((bit&bitstring)?0x02:0),Serial_Command);
3327         }
3328         bitstring=0;
3329         for(bit=0x80;bit;bit>>=1){
3330                 ni_writeb(0x04,Serial_Command);
3331                 ni_writeb(0x05,Serial_Command);
3332                 bitstring|=((ni_readb(XXX_Status)&PROMOUT)?bit:0);
3333         }
3334         ni_writeb(0x00,Serial_Command);
3335
3336         return bitstring;
3337 }
3338
3339 static int ni_m_series_eeprom_insn_read(comedi_device *dev,comedi_subdevice *s,
3340         comedi_insn *insn,lsampl_t *data)
3341 {
3342         data[0] = devpriv->eeprom_buffer[CR_CHAN(insn->chanspec)];
3343
3344         return 1;
3345 }
3346
3347 static int ni_get_pwm_config(comedi_device *dev, lsampl_t *data)
3348 {
3349         data[1] = devpriv->pwm_up_count * TIMER_BASE;
3350         data[2] = devpriv->pwm_down_count * TIMER_BASE;
3351         return 3;
3352 }
3353
3354 static int ni_m_series_pwm_config(comedi_device *dev, comedi_subdevice *s,
3355         comedi_insn *insn, lsampl_t *data)
3356 {
3357         unsigned up_count, down_count;
3358         switch(data[0])
3359         {
3360         case INSN_CONFIG_PWM_OUTPUT:
3361                 switch(data[1])
3362                 {
3363                 case TRIG_ROUND_NEAREST:
3364                         up_count = (data[2] + TIMER_BASE / 2) / TIMER_BASE;
3365                         break;
3366                 case TRIG_ROUND_DOWN:
3367                         up_count = data[2] / TIMER_BASE;
3368                         break;
3369                 case TRIG_ROUND_UP:
3370                         up_count = (data[2] + TIMER_BASE - 1) / TIMER_BASE;
3371                         break;
3372                 default:
3373                         return -EINVAL;
3374                         break;
3375                 }
3376                 switch(data[3])
3377                 {
3378                 case TRIG_ROUND_NEAREST:
3379                         down_count = (data[4] + TIMER_BASE / 2) / TIMER_BASE;
3380                         break;
3381                 case TRIG_ROUND_DOWN:
3382                         down_count = data[4] / TIMER_BASE;
3383                         break;
3384                 case TRIG_ROUND_UP:
3385                         down_count = (data[4] + TIMER_BASE - 1) / TIMER_BASE;
3386                         break;
3387                 default:
3388                         return -EINVAL;
3389                         break;
3390                 }
3391                 if(up_count * TIMER_BASE != data[2] ||
3392                         down_count * TIMER_BASE != data[4])
3393                 {
3394                         data[2] = up_count * TIMER_BASE;
3395                         data[4] = down_count * TIMER_BASE;
3396                         return -EAGAIN;
3397                 }
3398                 ni_writel(MSeries_Cal_PWM_High_Time_Bits(up_count) | MSeries_Cal_PWM_Low_Time_Bits(down_count), M_Offset_Cal_PWM);
3399                 devpriv->pwm_up_count = up_count;
3400                 devpriv->pwm_down_count = down_count;
3401                 return 5;
3402                 break;
3403         case INSN_CONFIG_GET_PWM_OUTPUT:
3404                 return ni_get_pwm_config(dev, data);
3405                 break;
3406         default:
3407                 return -EINVAL;
3408                 break;
3409         }
3410         return 0;
3411 }
3412
3413 static int ni_6143_pwm_config(comedi_device *dev, comedi_subdevice *s,
3414         comedi_insn *insn, lsampl_t *data)
3415 {
3416         unsigned up_count, down_count;
3417         switch(data[0])
3418         {
3419         case INSN_CONFIG_PWM_OUTPUT:
3420                 switch(data[1])
3421                 {
3422                 case TRIG_ROUND_NEAREST:
3423                         up_count = (data[2] + TIMER_BASE / 2) / TIMER_BASE;
3424                         break;
3425                 case TRIG_ROUND_DOWN:
3426                         up_count = data[2] / TIMER_BASE;
3427                         break;
3428                 case TRIG_ROUND_UP:
3429                         up_count = (data[2] + TIMER_BASE - 1) / TIMER_BASE;
3430                         break;
3431                 default:
3432                         return -EINVAL;
3433                         break;
3434                 }
3435                 switch(data[3])
3436                 {
3437                 case TRIG_ROUND_NEAREST:
3438                         down_count = (data[4] + TIMER_BASE / 2) / TIMER_BASE;
3439                         break;
3440                 case TRIG_ROUND_DOWN:
3441                         down_count = data[4] / TIMER_BASE;
3442                         break;
3443                 case TRIG_ROUND_UP:
3444                         down_count = (data[4] + TIMER_BASE - 1) / TIMER_BASE;
3445                         break;
3446                 default:
3447                         return -EINVAL;
3448                         break;
3449                 }
3450                 if(up_count * TIMER_BASE != data[2] ||
3451                         down_count * TIMER_BASE != data[4])
3452                 {
3453                         data[2] = up_count * TIMER_BASE;
3454                         data[4] = down_count * TIMER_BASE;
3455                         return -EAGAIN;
3456                 }
3457                 ni_writel(up_count, Calibration_HighTime_6143);
3458                 devpriv->pwm_up_count = up_count;
3459                 ni_writel(down_count, Calibration_LowTime_6143);
3460                 devpriv->pwm_down_count = down_count;
3461                 return 5;
3462                 break;
3463         case INSN_CONFIG_GET_PWM_OUTPUT:
3464                 return ni_get_pwm_config(dev, data);
3465         default:
3466                 return -EINVAL;
3467                 break;
3468         }
3469         return 0;
3470 }
3471
3472 static void ni_write_caldac(comedi_device *dev,int addr,int val);
3473 /*
3474         calibration subdevice
3475 */
3476 static int ni_calib_insn_write(comedi_device *dev,comedi_subdevice *s,
3477         comedi_insn *insn,lsampl_t *data)
3478 {
3479         ni_write_caldac(dev,CR_CHAN(insn->chanspec),data[0]);
3480
3481         return 1;
3482 }
3483
3484 static int ni_calib_insn_read(comedi_device *dev,comedi_subdevice *s,
3485         comedi_insn *insn,lsampl_t *data)
3486 {
3487         data[0] = devpriv->caldacs[CR_CHAN(insn->chanspec)];
3488
3489         return 1;
3490 }
3491
3492 static int pack_mb88341(int addr,int val,int *bitstring);
3493 static int pack_dac8800(int addr,int val,int *bitstring);
3494 static int pack_dac8043(int addr,int val,int *bitstring);
3495 static int pack_ad8522(int addr,int val,int *bitstring);
3496 static int pack_ad8804(int addr,int val,int *bitstring);
3497 static int pack_ad8842(int addr,int val,int *bitstring);
3498
3499 struct caldac_struct{
3500         int n_chans;
3501         int n_bits;
3502         int (*packbits)(int,int,int *);
3503 };
3504
3505 static struct caldac_struct caldacs[] = {
3506         [mb88341] = { 12, 8, pack_mb88341 },
3507         [dac8800] = { 8, 8, pack_dac8800 },
3508         [dac8043] = { 1, 12, pack_dac8043 },
3509         [ad8522]  = { 2, 12, pack_ad8522 },
3510         [ad8804] = { 12, 8, pack_ad8804 },
3511         [ad8842] = { 8, 8, pack_ad8842 },
3512         [ad8804_debug] = { 16, 8, pack_ad8804 },
3513 };
3514
3515 static void caldac_setup(comedi_device *dev,comedi_subdevice *s)
3516 {
3517         int i,j;
3518         int n_dacs;
3519         int n_chans=0;
3520         int n_bits;
3521         int diffbits=0;
3522         int type;
3523         int chan;
3524
3525         type = boardtype.caldac[0];
3526         if(type==caldac_none)return;
3527         n_bits=caldacs[type].n_bits;
3528         for(i=0;i<3;i++){
3529                 type = boardtype.caldac[i];
3530                 if(type==caldac_none)break;
3531                 if(caldacs[type].n_bits!=n_bits)diffbits=1;
3532                 n_chans+=caldacs[type].n_chans;
3533         }
3534         n_dacs=i;
3535         s->n_chan=n_chans;
3536
3537         if(diffbits){
3538
3539                 if(n_chans>MAX_N_CALDACS){
3540                         printk("BUG! MAX_N_CALDACS too small\n");
3541                 }
3542                 s->maxdata_list=devpriv->caldac_maxdata_list;
3543                 chan=0;
3544                 for(i=0;i<n_dacs;i++){
3545                         type = boardtype.caldac[i];
3546                         for(j=0;j<caldacs[type].n_chans;j++){
3547                                 s->maxdata_list[chan]=
3548                                         (1<<caldacs[type].n_bits)-1;
3549                                 chan++;
3550                         }
3551                 }
3552
3553                 for( chan = 0; chan < s->n_chan; chan++ )
3554                         ni_write_caldac( dev, i, s->maxdata_list[ i ] / 2 );
3555         }else{
3556                 type = boardtype.caldac[0];
3557                 s->maxdata=(1<<caldacs[type].n_bits)-1;
3558
3559                 for( chan = 0; chan < s->n_chan; chan++ )
3560                         ni_write_caldac( dev, i, s->maxdata / 2 );
3561         }
3562 }
3563
3564 static void ni_write_caldac(comedi_device *dev,int addr,int val)
3565 {
3566         unsigned int loadbit=0,bits=0,bit,bitstring=0;
3567         int i;
3568         int type;
3569
3570         //printk("ni_write_caldac: chan=%d val=%d\n",addr,val);
3571         if( devpriv->caldacs[ addr ] == val ) return;
3572         devpriv->caldacs[ addr ] = val;
3573
3574         for(i=0;i<3;i++){
3575                 type = boardtype.caldac[i];
3576                 if(type==caldac_none)break;
3577                 if(addr<caldacs[type].n_chans){
3578                         bits=caldacs[type].packbits(addr,val,&bitstring);
3579                         loadbit=SerDacLd(i);
3580                         //printk("caldac: using i=%d addr=%d %x\n",i,addr,bitstring);
3581                         break;
3582                 }
3583                 addr-=caldacs[type].n_chans;
3584         }
3585
3586         for(bit=1<<(bits-1);bit;bit>>=1){
3587                 ni_writeb(((bit&bitstring)?0x02:0),Serial_Command);
3588                 comedi_udelay(1);
3589                 ni_writeb(1|((bit&bitstring)?0x02:0),Serial_Command);
3590                 comedi_udelay(1);
3591         }
3592         ni_writeb(loadbit,Serial_Command);
3593         comedi_udelay(1);
3594         ni_writeb(0,Serial_Command);
3595 }
3596
3597
3598
3599 static int pack_mb88341(int addr,int val,int *bitstring)
3600 {
3601         /*
3602            Fujitsu MB 88341
3603            Note that address bits are reversed.  Thanks to
3604            Ingo Keen for noticing this.
3605
3606            Note also that the 88341 expects address values from
3607            1-12, whereas we use channel numbers 0-11.  The NI
3608            docs use 1-12, also, so be careful here.
3609         */
3610         addr++;
3611         *bitstring=((addr&0x1)<<11) |
3612                   ((addr&0x2)<<9)  |
3613                   ((addr&0x4)<<7)  |
3614                   ((addr&0x8)<<5)  |
3615                   (val&0xff);
3616         return 12;
3617 }
3618
3619 static int pack_dac8800(int addr,int val,int *bitstring)
3620 {
3621         *bitstring=((addr&0x7)<<8)|(val&0xff);
3622         return 11;
3623 }
3624
3625 static int pack_dac8043(int addr,int val,int *bitstring)
3626 {
3627         *bitstring=val&0xfff;
3628         return 12;
3629 }
3630
3631 static int pack_ad8522(int addr,int val,int *bitstring)
3632 {
3633         *bitstring=(val&0xfff)|(addr ? 0xc000:0xa000);
3634         return 16;
3635 }
3636
3637 static int pack_ad8804(int addr,int val,int *bitstring)
3638 {
3639         *bitstring=((addr&0xf)<<8) | (val&0xff);
3640         return 12;
3641 }
3642
3643 static int pack_ad8842(int addr,int val,int *bitstring)
3644 {
3645         *bitstring=((addr+1)<<8) | (val&0xff);
3646         return 12;
3647 }
3648
3649
3650
3651
3652
3653 /*
3654  *
3655  *  General Purpose Counter/Timer section
3656  *
3657  */
3658
3659 /*
3660  * Low level stuff...Each STC counter has two 24 bit load registers
3661  * (A&B).  Just make it easier to access them.
3662  *
3663  * These are inlined _only_ because they are used once in subsequent
3664  * code.  Otherwise they should not be inlined.
3665  */
3666 static inline void GPCT_Load_A(comedi_device *dev, int chan, unsigned int value)
3667 {
3668         devpriv->stc_writel(dev,  value & 0x00ffffff, G_Load_A_Register(chan));
3669 }
3670
3671 static inline void GPCT_Load_B(comedi_device *dev, int chan, unsigned int value)
3672 {
3673         devpriv->stc_writel(dev,  value & 0x00ffffff, G_Load_B_Register(chan));
3674 }
3675
3676 /*  Load a value into the counter, using register A as the intermediate step.
3677 *  You might use GPCT_Load_Using_A to load a 0x000000 into a counter
3678 *  reset its value.
3679 */
3680 static void GPCT_Load_Using_A(comedi_device *dev, int chan, unsigned int value)
3681 {
3682         devpriv->gpct_mode[chan] &= (~G_Load_Source_Select);
3683         devpriv->stc_writew(dev,  devpriv->gpct_mode[chan],G_Mode_Register(chan));
3684         GPCT_Load_A(dev,chan,value);
3685         devpriv->stc_writew(dev,  devpriv->gpct_command[chan]|G_Load,G_Command_Register(chan));
3686 }
3687
3688 /*
3689  *      Read the GPCTs current value.
3690  */
3691 static int GPCT_G_Watch(comedi_device *dev, int chan)
3692 {
3693         unsigned int hi1,hi2,lo;
3694
3695         devpriv->gpct_command[chan] &= ~G_Save_Trace;
3696         devpriv->stc_writew(dev,  devpriv->gpct_command[chan],G_Command_Register(chan));
3697
3698         devpriv->gpct_command[chan] |= G_Save_Trace;
3699         devpriv->stc_writew(dev,  devpriv->gpct_command[chan], G_Command_Register(chan));
3700
3701         /* This procedure is used because the two registers cannot
3702          * be read atomically. */
3703         do{
3704                 hi1 = devpriv->stc_readw(dev,  G_Save_Register_High(chan));
3705                 lo = devpriv->stc_readw(dev, G_Save_Register_Low(chan));
3706                 hi2 = devpriv->stc_readw(dev,  G_Save_Register_High(chan));
3707         }while(hi1!=hi2);
3708
3709         return (hi1<<16)|lo;
3710 }
3711
3712
3713 static int GPCT_Disarm(comedi_device *dev, int chan)
3714 {
3715         devpriv->stc_writew(dev,  devpriv->gpct_command[chan] | G_Disarm,G_Command_Register(chan));
3716         return 0;
3717 }
3718
3719
3720 static int GPCT_Arm(comedi_device *dev, int chan)
3721 {
3722         devpriv->stc_writew(dev,  devpriv->gpct_command[chan] | G_Arm,G_Command_Register(chan));
3723         /* If the counter is doing pulse width measurement, then make
3724          sure that the counter did not start counting right away.  This would
3725          indicate that we started acquiring the pulse after it had already
3726          started and our measurement would be inaccurate */
3727         if(devpriv->gpct_cur_operation[chan] == GPCT_SINGLE_PW){
3728                 int g_status;
3729
3730                 g_status=devpriv->stc_readw(dev, G_Status_Register);
3731
3732                 if(chan == 0){
3733                         //TIM 5/2/01 possible error with very short pulses
3734                         if((G0_Counting_St & g_status)|| !(G0_Armed_St&g_status)) {
3735                                 //error: we missed the beginning of the pulse
3736                                 return -EINVAL; //there is probably a more accurate error code...
3737                         }
3738                 }else{
3739                         if((G1_Counting_St & g_status)|| !(G1_Armed_St&g_status)) {
3740                                 //error: we missed the beginning of the pulse
3741                                 return -EINVAL;
3742                         }
3743                 }
3744         }
3745         return 0;
3746 }
3747
3748 static int GPCT_Set_Source(comedi_device *dev,int chan ,int source)
3749 {
3750         //printk("GPCT_Set_Source...");
3751         devpriv->gpct_input_select[chan] &= ~G_Source_Select(0x1f);//reset gate to 0
3752         switch(source) {
3753                 case GPCT_INT_CLOCK:
3754                 devpriv->gpct_input_select[chan] |= G_Source_Select(0);//INT_TIMEBASE
3755                 break;
3756         case GPCT_EXT_PIN:
3757                 if(chan==0)
3758                         devpriv->gpct_input_select[chan] |= G_Source_Select(9);//PFI8
3759                 else
3760                         devpriv->gpct_input_select[chan] |= G_Source_Select(4);//PFI3
3761                 break;
3762         default:
3763                 return -EINVAL;
3764         }
3765         devpriv->stc_writew(dev, devpriv->gpct_input_select[chan], G_Input_Select_Register(chan));
3766         //printk("exit GPCT_Set_Source\n");
3767         return 0;
3768 }
3769
3770 static int GPCT_Set_Gate(comedi_device *dev,int chan ,int gate)
3771 {
3772         //printk("GPCT_Set_Gate...");
3773         devpriv->gpct_input_select[chan] &= ~G_Gate_Select(0x1f);//reset gate to 0
3774         switch(gate) {
3775         case GPCT_NO_GATE:
3776                 devpriv->gpct_input_select[chan] |= G_Gate_Select(31);//Low
3777                 devpriv->gpct_mode[chan] |= G_Gate_Polarity;
3778                 break;
3779         case GPCT_EXT_PIN:
3780                 devpriv->gpct_mode[chan] &= ~G_Gate_Polarity;
3781                 if(chan==0){
3782                         devpriv->gpct_input_select[chan] |= G_Gate_Select(10);//PFI9
3783                 }else{
3784                         devpriv->gpct_input_select[chan] |= G_Gate_Select(5);//PFI4
3785                 }
3786                 break;
3787         default:
3788                 return -EINVAL;
3789         }
3790         devpriv->stc_writew(dev, devpriv->gpct_input_select[chan], G_Input_Select_Register(chan));
3791         devpriv->stc_writew(dev, devpriv->gpct_mode[chan], G_Mode_Register(chan));
3792         //printk("exit GPCT_Set_Gate\n");
3793         return 0;
3794 }
3795
3796 static int GPCT_Set_Direction(comedi_device *dev,int chan,int direction)
3797 {
3798         //printk("GPCT_Set_Direction...");
3799
3800         devpriv->gpct_command[chan] &= ~G_Up_Down(0x3);
3801         switch (direction) {
3802                 case GPCT_UP:
3803                         devpriv->gpct_command[chan] |= G_Up_Down(1);
3804                         break;
3805                 case GPCT_DOWN:
3806                         devpriv->gpct_command[chan] |= G_Up_Down(0);
3807                         break;
3808                 case GPCT_HWUD:
3809                         devpriv->gpct_command[chan] |= G_Up_Down(2);
3810                         break;
3811                 default:
3812                         printk("Error direction=0x%08x..",direction);
3813                         return -EINVAL;
3814         }
3815         devpriv->stc_writew(dev, devpriv->gpct_command[chan], G_Command_Register(chan));
3816         //TIM 4/23/01 devpriv->stc_writew(dev, devpriv->gpct_mode[chan], G_Mode_Register(chan));
3817         //printk("exit GPCT_Set_Direction\n");
3818         return 0;
3819 }
3820
3821 static void GPCT_Event_Counting(comedi_device *dev,int chan)
3822 {
3823
3824         //NOTE: possible residual bits from multibit masks can corrupt
3825         //If you config for several measurements between Resets, watch out!
3826
3827         //printk("GPCT_Event_Counting...");
3828
3829         devpriv->gpct_cur_operation[chan] = GPCT_SIMPLE_EVENT;
3830
3831         // Gating_Mode = 1
3832         devpriv->gpct_mode[chan] &= ~(G_Gating_Mode(0x3));
3833         devpriv->gpct_mode[chan] |= G_Gating_Mode(1);
3834
3835         // Trigger_Mode_For_Edge_Gate = 1
3836         devpriv->gpct_mode[chan] &= ~(G_Trigger_Mode_For_Edge_Gate(0x3));
3837         devpriv->gpct_mode[chan] |= G_Trigger_Mode_For_Edge_Gate(2);
3838
3839         devpriv->stc_writew(dev,  devpriv->gpct_mode[chan],G_Mode_Register(chan));
3840         //printk("exit GPCT_Event_Counting\n");
3841 }
3842
3843 static void GPCT_Period_Meas(comedi_device *dev, int chan)
3844 {
3845         //printk("GPCT_Period_Meas...");
3846
3847         devpriv->gpct_cur_operation[chan] = GPCT_SINGLE_PERIOD;
3848
3849
3850         //NOTE: possible residual bits from multibit masks can corrupt
3851         //If you config for several measurements between Resets, watch out!
3852         devpriv->gpct_mode[chan] &= ~G_OR_Gate;
3853         devpriv->gpct_mode[chan] &= ~G_Gate_Select_Load_Source;
3854
3855         // Output_Mode = 3
3856         devpriv->gpct_mode[chan] &= ~(G_Output_Mode(0x3));
3857         devpriv->gpct_mode[chan] |= G_Output_Mode(3);
3858
3859
3860         //Gating Mode=2
3861         devpriv->gpct_mode[chan] &= ~(G_Gating_Mode(0x3));
3862         devpriv->gpct_mode[chan] |= G_Gating_Mode(2);
3863
3864         // Trigger_Mode_For_Edge_Gate=0
3865         devpriv->gpct_mode[chan] &= ~(G_Trigger_Mode_For_Edge_Gate(0x3));
3866         devpriv->gpct_mode[chan] |= G_Trigger_Mode_For_Edge_Gate(0);
3867
3868         devpriv->gpct_mode[chan] |= G_Reload_Source_Switching;
3869         devpriv->gpct_mode[chan] &= ~G_Loading_On_Gate;
3870         devpriv->gpct_mode[chan] &= ~G_Loading_On_TC;
3871         devpriv->gpct_mode[chan] &= ~G_Gate_On_Both_Edges;
3872
3873         // Stop_Mode = 2
3874         devpriv->gpct_mode[chan] &= ~(G_Stop_Mode(0x3));
3875         devpriv->gpct_mode[chan] |= G_Stop_Mode(0);
3876
3877         // Counting_Once = 2
3878         devpriv->gpct_mode[chan] &= ~(G_Counting_Once(0x3));
3879         devpriv->gpct_mode[chan] |= G_Counting_Once(2);
3880
3881         // Up_Down = 1
3882         devpriv->gpct_command[chan] &= ~(G_Up_Down(0x3));
3883         devpriv->gpct_command[chan] |= G_Up_Down(1);
3884
3885         devpriv->stc_writew(dev,  devpriv->gpct_mode[chan],G_Mode_Register(chan));
3886         devpriv->stc_writew(dev,  devpriv->gpct_command[chan],G_Command_Register(chan));
3887         //printk("exit GPCT_Period_Meas\n");
3888 }
3889
3890 static void GPCT_Pulse_Width_Meas(comedi_device *dev, int chan)
3891 {
3892         //printk("GPCT_Pulse_Width_Meas...");
3893
3894         devpriv->gpct_cur_operation[chan] = GPCT_SINGLE_PW;
3895
3896         devpriv->gpct_mode[chan] &= ~G_OR_Gate;
3897         devpriv->gpct_mode[chan] &= ~G_Gate_Select_Load_Source;
3898
3899         // Output_Mode = 3
3900         devpriv->gpct_mode[chan] &= ~(G_Output_Mode(0x3));
3901         devpriv->gpct_mode[chan] |= G_Output_Mode(3);
3902
3903         //Gating Mode=1
3904         devpriv->gpct_mode[chan] &= ~(G_Gating_Mode(0x3));
3905         devpriv->gpct_mode[chan] |= G_Gating_Mode(1);//TIM 4/24/01 was 2
3906
3907         // Trigger_Mode_For_Edge_Gate=2
3908         devpriv->gpct_mode[chan] &= ~(G_Trigger_Mode_For_Edge_Gate(0x3));
3909         devpriv->gpct_mode[chan] |= G_Trigger_Mode_For_Edge_Gate(2);//TIM 4/24/01 was 0
3910
3911
3912         devpriv->gpct_mode[chan] |= G_Reload_Source_Switching;//TIM 4/24/01 was 1
3913         devpriv->gpct_mode[chan] &= ~G_Loading_On_Gate;//TIM 4/24/01 was 0
3914
3915         devpriv->gpct_mode[chan] &= ~G_Loading_On_TC;
3916         devpriv->gpct_mode[chan] &= ~G_Gate_On_Both_Edges;
3917
3918         // Stop_Mode = 0
3919         devpriv->gpct_mode[chan] &= ~(G_Stop_Mode(0x3));
3920         devpriv->gpct_mode[chan] |= G_Stop_Mode(0);
3921
3922         // Counting_Once = 2
3923         devpriv->gpct_mode[chan] &= ~(G_Counting_Once(0x3));
3924         devpriv->gpct_mode[chan] |= G_Counting_Once(2);
3925
3926         // Up_Down = 1
3927         devpriv->gpct_command[chan] &= ~(G_Up_Down(0x3));
3928         devpriv->gpct_command[chan] |= G_Up_Down(1);
3929
3930         devpriv->stc_writew(dev,  devpriv->gpct_mode[chan],G_Mode_Register(chan));
3931         devpriv->stc_writew(dev,  devpriv->gpct_command[chan],G_Command_Register(chan));
3932
3933         //printk("exit GPCT_Pulse_Width_Meas\n");
3934 }
3935
3936 /* GPCT_Gen_Single_Pulse() creates pulse of length pulsewidth which starts after the Arm
3937 signal is sent.  The pulse is delayed by the value already in the counter.  This function could
3938 be modified to send a pulse in response to a trigger event at its gate.*/
3939 static void GPCT_Gen_Single_Pulse(comedi_device *dev, int chan, unsigned int length)
3940 {
3941         //printk("GPCT_Gen_Cont...");
3942
3943         devpriv->gpct_cur_operation[chan] = GPCT_SINGLE_PULSE_OUT;
3944
3945         // Set length of the pulse
3946         GPCT_Load_B(dev,chan, length-1);
3947
3948         //Load next time using B, This is reset by GPCT_Load_Using_A()
3949         devpriv->gpct_mode[chan] |= G_Load_Source_Select;
3950
3951         devpriv->gpct_mode[chan] &= ~G_OR_Gate;
3952         devpriv->gpct_mode[chan] &= ~G_Gate_Select_Load_Source;
3953
3954         // Output_Mode = 3
3955         devpriv->gpct_mode[chan] &= ~(G_Output_Mode(0x3));
3956         devpriv->gpct_mode[chan] |= G_Output_Mode(2); //TIM 4/26/01 was 3
3957
3958         //Gating Mode=0 for untriggered single pulse
3959         devpriv->gpct_mode[chan] &= ~(G_Gating_Mode(0x3));
3960         devpriv->gpct_mode[chan] |= G_Gating_Mode(0); //TIM 4/25/01 was 1
3961
3962         // Trigger_Mode_For_Edge_Gate=0
3963         devpriv->gpct_mode[chan] &= ~(G_Trigger_Mode_For_Edge_Gate(0x3));
3964         devpriv->gpct_mode[chan] |= G_Trigger_Mode_For_Edge_Gate(2);
3965
3966
3967         devpriv->gpct_mode[chan] |= G_Reload_Source_Switching;
3968         devpriv->gpct_mode[chan] &= ~G_Loading_On_Gate;
3969         devpriv->gpct_mode[chan] |= G_Loading_On_TC; //TIM 4/25/01
3970         devpriv->gpct_mode[chan] &= ~G_Gate_On_Both_Edges;
3971
3972         // Stop_Mode = 2
3973         devpriv->gpct_mode[chan] &= ~(G_Stop_Mode(0x3));
3974         devpriv->gpct_mode[chan] |= G_Stop_Mode(2); //TIM 4/25/01
3975
3976         // Counting_Once = 2
3977         devpriv->gpct_mode[chan] &= ~(G_Counting_Once(0x3));
3978         devpriv->gpct_mode[chan] |= G_Counting_Once(1); //TIM 4/25/01
3979
3980         // Up_Down = 1
3981         devpriv->gpct_command[chan] &= ~(G_Up_Down(0x3));
3982         devpriv->gpct_command[chan] |= G_Up_Down(0); //TIM 4/25/01 was 1
3983
3984         devpriv->stc_writew(dev,  devpriv->gpct_mode[chan],G_Mode_Register(chan));
3985         devpriv->stc_writew(dev,  devpriv->gpct_command[chan],G_Command_Register(chan));
3986
3987         //printk("exit GPCT_Gen_Cont\n");
3988 }
3989
3990 static void GPCT_Gen_Cont_Pulse(comedi_device *dev, int chan, unsigned int length)
3991 {
3992         //printk("GPCT_Gen_Cont...");
3993
3994         devpriv->gpct_cur_operation[chan] = GPCT_CONT_PULSE_OUT;
3995
3996         // Set length of the pulse
3997         GPCT_Load_B(dev,chan, length-1);
3998
3999         //Load next time using B, This is reset by GPCT_Load_Using_A()
4000         devpriv->gpct_mode[chan] |= G_Load_Source_Select;
4001
4002         devpriv->gpct_mode[chan] &= ~G_OR_Gate;
4003         devpriv->gpct_mode[chan] &= ~G_Gate_Select_Load_Source;
4004
4005         // Output_Mode = 3
4006         devpriv->gpct_mode[chan] &= ~(G_Output_Mode(0x3));
4007         devpriv->gpct_mode[chan] |= G_Output_Mode(2); //TIM 4/26/01 was 3
4008
4009         //Gating Mode=0 for untriggered single pulse
4010         devpriv->gpct_mode[chan] &= ~(G_Gating_Mode(0x3));
4011         devpriv->gpct_mode[chan] |= G_Gating_Mode(0); //TIM 4/26/01 was 0
4012
4013         // Trigger_Mode_For_Edge_Gate=0
4014         devpriv->gpct_mode[chan] &= ~(G_Trigger_Mode_For_Edge_Gate(0x3));
4015         devpriv->gpct_mode[chan] |= G_Trigger_Mode_For_Edge_Gate(2);
4016
4017
4018         devpriv->gpct_mode[chan] |= G_Reload_Source_Switching;
4019         devpriv->gpct_mode[chan] &= ~G_Loading_On_Gate;
4020         devpriv->gpct_mode[chan] |= G_Loading_On_TC;
4021         devpriv->gpct_mode[chan] &= ~G_Gate_On_Both_Edges;
4022
4023         // Stop_Mode = 2
4024         devpriv->gpct_mode[chan] &= ~(G_Stop_Mode(0x3));
4025         devpriv->gpct_mode[chan] |= G_Stop_Mode(0); //TIM 4/26/01
4026
4027         // Counting_Once = 2
4028         devpriv->gpct_mode[chan] &= ~(G_Counting_Once(0x3));
4029         devpriv->gpct_mode[chan] |= G_Counting_Once(0); //TIM 4/26/01
4030
4031         // Up_Down = 1
4032         devpriv->gpct_command[chan] &= ~(G_Up_Down(0x3));
4033         devpriv->gpct_command[chan] |= G_Up_Down(0);
4034
4035         //TIM 4/26/01
4036         //This seems pretty unsafe since I don't think it is cleared anywhere.
4037         //I don't think this is working
4038         //devpriv->gpct_command[chan] &= ~G_Bank_Switch_Enable;
4039         //devpriv->gpct_command[chan] &= ~G_Bank_Switch_Mode;
4040
4041
4042         devpriv->stc_writew(dev,  devpriv->gpct_mode[chan],G_Mode_Register(chan));
4043         devpriv->stc_writew(dev,  devpriv->gpct_command[chan],G_Command_Register(chan));
4044
4045         //printk("exit GPCT_Gen_Cont\n");
4046 }
4047
4048 static void GPCT_Reset(comedi_device *dev, int chan)
4049 {
4050         int temp_ack_reg=0;
4051
4052         //printk("GPCT_Reset...");
4053         devpriv->gpct_cur_operation[chan] = GPCT_RESET;
4054
4055         switch (chan) {
4056                 case 0:
4057                         devpriv->stc_writew(dev, G0_Reset,Joint_Reset_Register);
4058                         ni_set_bits(dev,Interrupt_A_Enable_Register,G0_TC_Interrupt_Enable,  0);
4059                         ni_set_bits(dev,Interrupt_A_Enable_Register,G0_Gate_Interrupt_Enable,0);
4060                         temp_ack_reg |= G0_Gate_Error_Confirm;
4061                         temp_ack_reg |= G0_TC_Error_Confirm;
4062                         temp_ack_reg |= G0_TC_Interrupt_Ack;
4063                         temp_ack_reg |= G0_Gate_Interrupt_Ack;
4064                         devpriv->stc_writew(dev, temp_ack_reg,Interrupt_A_Ack_Register);
4065
4066                         //problem...this interferes with the other ctr...
4067                         devpriv->an_trig_etc_reg |= GPFO_0_Output_Enable;
4068                         devpriv->stc_writew(dev, devpriv->an_trig_etc_reg, Analog_Trigger_Etc_Register);
4069                         break;
4070                 case 1:
4071                         devpriv->stc_writew(dev, G1_Reset,Joint_Reset_Register);
4072                         ni_set_bits(dev,Interrupt_B_Enable_Register,G1_TC_Interrupt_Enable,  0);
4073                         ni_set_bits(dev,Interrupt_B_Enable_Register,G0_Gate_Interrupt_Enable,0);
4074                         temp_ack_reg |= G1_Gate_Error_Confirm;
4075                         temp_ack_reg |= G1_TC_Error_Confirm;
4076                         temp_ack_reg |= G1_TC_Interrupt_Ack;
4077                         temp_ack_reg |= G1_Gate_Interrupt_Ack;
4078                         devpriv->stc_writew(dev, temp_ack_reg,Interrupt_B_Ack_Register);
4079
4080                         devpriv->an_trig_etc_reg |= GPFO_1_Output_Enable;
4081                         devpriv->stc_writew(dev, devpriv->an_trig_etc_reg, Analog_Trigger_Etc_Register);
4082                         break;
4083         };
4084
4085         devpriv->gpct_mode[chan] = 0;
4086         devpriv->gpct_input_select[chan] = 0;
4087         devpriv->gpct_command[chan] = 0;
4088
4089         devpriv->gpct_command[chan] |= G_Synchronized_Gate;
4090
4091         devpriv->stc_writew(dev,  devpriv->gpct_mode[chan],G_Mode_Register(chan));
4092         devpriv->stc_writew(dev,  devpriv->gpct_input_select[chan],G_Input_Select_Register(chan));
4093         devpriv->stc_writew(dev,  0,G_Autoincrement_Register(chan));
4094
4095         //printk("exit GPCT_Reset\n");
4096 }
4097
4098 static int ni_gpct_insn_config(comedi_device *dev,comedi_subdevice *s,
4099         comedi_insn *insn,lsampl_t *data)
4100 {
4101         int retval=0;
4102         //printk("data[0] is 0x%08x, data[1] is 0x%08x\n",data[0],data[1]);
4103         switch(data[0]){
4104         case GPCT_RESET:
4105                 if(insn->n!=1)return -EINVAL;
4106                 GPCT_Reset(dev,insn->chanspec);
4107                 break;
4108         case GPCT_SET_SOURCE:
4109                 if(insn->n!=2)return -EINVAL;
4110                 retval=GPCT_Set_Source(dev,insn->chanspec,data[1]);
4111                 break;
4112         case GPCT_SET_GATE:
4113                 if(insn->n!=2)return -EINVAL;
4114                 retval=GPCT_Set_Gate(dev,insn->chanspec,data[1]);
4115                 break;
4116         case GPCT_SET_DIRECTION:
4117                 if(insn->n!=2) return -EINVAL;
4118                 retval=GPCT_Set_Direction(dev,insn->chanspec,data[1]);
4119                 break;
4120         case GPCT_GET_INT_CLK_FRQ:
4121                 if(insn->n!=2) return -EINVAL;
4122                 //There are actually 2 internal clocks on the STC, we always
4123                 //use the fast 20MHz one at this time.  Tim  Ousley 5/1/01
4124                 //NOTE: This is not the final interface, ideally the user
4125                 //will never need to know the int. clk. freq.
4126                 data[1]=50;//50ns = 20MHz = internal timebase of STC
4127                 break;
4128         case GPCT_SET_OPERATION:
4129                 //TIM 5/1/01 if((insn->n<2)||(insn->n>3))return -EINVAL;
4130                 switch(data[1]){
4131                         case GPCT_SIMPLE_EVENT:
4132                                 GPCT_Event_Counting(dev,insn->chanspec);
4133                                 break;
4134                         case GPCT_SINGLE_PERIOD:
4135                                 GPCT_Period_Meas(dev,insn->chanspec);
4136                                 break;
4137                         case GPCT_SINGLE_PW:
4138                                 GPCT_Pulse_Width_Meas(dev,insn->chanspec);
4139                                 break;
4140                         case GPCT_SINGLE_PULSE_OUT:
4141                                 GPCT_Gen_Single_Pulse(dev,insn->chanspec,data[2]);
4142                                 break;
4143                         case GPCT_CONT_PULSE_OUT:
4144                                 GPCT_Gen_Cont_Pulse(dev,insn->chanspec,data[2]);
4145                                 break;
4146                         default:
4147                                 printk("unsupported GPCT operation!\n");
4148                                 return -EINVAL;
4149                 }
4150                 break;
4151         case GPCT_ARM:
4152                 if(insn->n!=1)return -EINVAL;
4153                 retval=GPCT_Arm(dev,insn->chanspec);
4154                 break;
4155         case GPCT_DISARM:
4156                 if(insn->n!=1)return -EINVAL;
4157                 retval=GPCT_Disarm(dev,insn->chanspec);
4158                 break;
4159         default:
4160                 return -EINVAL;
4161         }
4162
4163         //catch any errors from return values
4164         if(retval==0){
4165                 return insn->n;
4166         }else{
4167                 if(data[0]!=GPCT_ARM){
4168                         printk("error: retval was %d\n",retval);
4169                         printk("data[0] is 0x%08x, data[1] is 0x%08x\n",data[0],data[1]);
4170                 }
4171
4172                 return retval;
4173         }
4174 }
4175
4176 static int ni_gpct_insn_read(comedi_device *dev,comedi_subdevice *s,
4177         comedi_insn *insn,lsampl_t *data) {
4178
4179         int chan=insn->chanspec;
4180         int cur_op = devpriv->gpct_cur_operation[chan];
4181
4182         //printk("in ni_gpct_insn_read, n=%d, data[0]=%d\n",insn->chanspec,data[0]);
4183         if(insn->n!=1)return -EINVAL;
4184
4185         data[0] = GPCT_G_Watch(dev,insn->chanspec);
4186
4187         /* for certain modes (period and pulse width measurment), the value
4188         in the counter is not valid until the counter stops.  If the value is
4189         invalid, return a 0 */
4190         if((cur_op == GPCT_SINGLE_PERIOD) || (cur_op == GPCT_SINGLE_PW)){
4191                 /* is the counter still running? */
4192                 if(devpriv->stc_readw(dev, G_Status_Register) & (chan?G1_Counting_St:G0_Counting_St))
4193                         data[0]=0;
4194         }
4195         return 1;
4196 }
4197
4198 static int ni_gpct_insn_write(comedi_device *dev,comedi_subdevice *s,
4199         comedi_insn *insn,lsampl_t *data) {
4200
4201         //printk("in ni_gpct_insn_write");
4202         if(insn->n!=1)return -EINVAL;
4203         GPCT_Load_Using_A(dev,insn->chanspec,data[0]);
4204         return 1;
4205 }
4206
4207
4208 /*
4209  *
4210  *  Programmable Function Inputs
4211  *
4212  */
4213
4214 static int ni_pfi_insn_bits(comedi_device *dev,comedi_subdevice *s,
4215         comedi_insn *insn,lsampl_t *data)
4216 {
4217         if(insn->n!=2)return -EINVAL;
4218
4219         data[1] = 0;
4220
4221         return 2;
4222 }
4223
4224 static int ni_pfi_insn_config(comedi_device *dev,comedi_subdevice *s,
4225         comedi_insn *insn,lsampl_t *data)
4226 {
4227         unsigned int chan;
4228
4229         if(insn->n < 1)return -EINVAL;
4230
4231         chan = CR_CHAN(insn->chanspec);
4232         if(chan>10)return -EINVAL;
4233
4234         switch(data[0]){
4235         case COMEDI_OUTPUT:
4236                 ni_set_bits(dev, IO_Bidirection_Pin_Register, 1<<chan, 1);
4237                 break;
4238         case COMEDI_INPUT:
4239                 ni_set_bits(dev, IO_Bidirection_Pin_Register, 1<<chan, 0);
4240                 break;
4241         case INSN_CONFIG_DIO_QUERY:
4242                 data[1] = (devpriv->io_bidirection_pin_reg & (1<<chan)) ? COMEDI_OUTPUT : COMEDI_INPUT;
4243                 return insn->n;
4244                 break;
4245         default:
4246                 return -EINVAL;
4247         }
4248
4249         return 1;
4250 }
4251
4252 /*
4253  *
4254  *  NI RTSI Bus Functions
4255  *
4256  */
4257 static void ni_rtsi_init(comedi_device *dev)
4258 {
4259         // Initialises the RTSI bus signal switch to a default state
4260
4261         // Set clock mode to internal
4262         devpriv->stc_writew(dev, COMEDI_RTSI_CLOCK_MODE_INTERNAL, RTSI_Trig_Direction_Register);
4263
4264         // Standard internal lines are routed to standard RTSI bus lines
4265         devpriv->stc_writew(dev, 0x3210, RTSI_Trig_A_Output_Register);
4266         devpriv->stc_writew(dev, 0x0654, RTSI_Trig_B_Output_Register);
4267
4268         // Sets the source and direction of the 4 on board lines
4269 //      devpriv->stc_writew(dev, 0x0000, RTSI_Board_Register);
4270 }
4271
4272 static int ni_rtsi_insn_bits(comedi_device *dev,comedi_subdevice *s,
4273         comedi_insn *insn,lsampl_t *data)
4274 {
4275         if(insn->n != 2) return -EINVAL;
4276
4277         data[1] = 0;
4278
4279         return 2;
4280 }
4281
4282 static int ni_rtsi_insn_config(comedi_device *dev,comedi_subdevice *s,
4283         comedi_insn *insn,lsampl_t *data)
4284 {
4285         unsigned int chan;
4286         unsigned int bit;
4287
4288         if(insn->n < 1) return -EINVAL;
4289
4290         if(data[0] == INSN_CONFIG_SET_RTSI_CLOCK_MODE){
4291                 if(data[1] > 3)
4292                         return -EINVAL;
4293
4294                 devpriv->rtsi_trig_direction_reg &= ~0x03;
4295                 devpriv->rtsi_trig_direction_reg |= data[1];
4296                 devpriv->stc_writew(dev, devpriv->rtsi_trig_direction_reg, RTSI_Trig_Direction_Register);
4297         }
4298         else {
4299                 chan = CR_CHAN(insn->chanspec);
4300                 if(chan > 6) return -EINVAL;
4301
4302                 bit = 9 + chan;
4303
4304                 switch(data[0]){
4305                 case INSN_CONFIG_DIO_OUTPUT:
4306                         devpriv->rtsi_trig_direction_reg |= (1 << bit);
4307                         devpriv->stc_writew(dev, devpriv->rtsi_trig_direction_reg, RTSI_Trig_Direction_Register);
4308                         break;
4309                 case INSN_CONFIG_DIO_INPUT:
4310                         devpriv->rtsi_trig_direction_reg &= ~(1 << bit);
4311                         devpriv->stc_writew(dev, devpriv->rtsi_trig_direction_reg, RTSI_Trig_Direction_Register);
4312                         break;
4313                 case INSN_CONFIG_DIO_QUERY:
4314                         data[1] = (devpriv->rtsi_trig_direction_reg & (1<<bit)) ? INSN_CONFIG_DIO_OUTPUT : INSN_CONFIG_DIO_INPUT;
4315                         return 2;
4316                         break;
4317                 default:
4318                         return -EINVAL;
4319                 }
4320         }
4321
4322         return 1;
4323 }
4324
4325 static int cs5529_wait_for_idle(comedi_device *dev)
4326 {
4327         unsigned short status;
4328         const int timeout = HZ;
4329         int i;
4330
4331         for(i = 0; i < timeout; i++)
4332         {
4333                 status = ni_ao_win_inw(dev, CAL_ADC_Status_67xx);
4334                 if((status & CSS_ADC_BUSY) == 0)
4335                 {
4336                         break;
4337                 }
4338                 set_current_state(TASK_INTERRUPTIBLE);
4339                 if(schedule_timeout(1))
4340                 {
4341                         return -EIO;
4342                 }
4343         }
4344 //printk("looped %i times waiting for idle\n", i);
4345         if(i == timeout)
4346         {
4347                 rt_printk("%s: %s: timeout\n", __FILE__, __FUNCTION__);
4348                 return -ETIME;
4349         }
4350         return 0;
4351 }
4352
4353 static void cs5529_command(comedi_device *dev, unsigned short value)
4354 {
4355         static const int timeout = 100;
4356         int i;
4357
4358         ni_ao_win_outw(dev, value, CAL_ADC_Command_67xx);
4359         /* give time for command to start being serially clocked into cs5529.
4360          * this insures that the CSS_ADC_BUSY bit will get properly
4361          * set before we exit this function.
4362         */
4363         for(i = 0; i < timeout; i++)
4364         {
4365                 if((ni_ao_win_inw(dev, CAL_ADC_Status_67xx) & CSS_ADC_BUSY))
4366                         break;
4367                 comedi_udelay(1);
4368         }
4369 //printk("looped %i times writing command to cs5529\n", i);
4370         if(i == timeout)
4371         {
4372                 comedi_error(dev, "possible problem - never saw adc go busy?");
4373         }
4374 }
4375
4376 /* write to cs5529 register */
4377 static void cs5529_config_write(comedi_device *dev, unsigned int value, unsigned int reg_select_bits)
4378 {
4379         ni_ao_win_outw(dev, ((value >> 16) & 0xff), CAL_ADC_Config_Data_High_Word_67xx);
4380         ni_ao_win_outw(dev, (value & 0xffff), CAL_ADC_Config_Data_Low_Word_67xx);
4381         reg_select_bits &= CSCMD_REGISTER_SELECT_MASK;
4382         cs5529_command(dev, CSCMD_COMMAND | reg_select_bits);
4383         if(cs5529_wait_for_idle(dev))
4384                 comedi_error(dev, "time or signal in cs5529_config_write()");
4385 }
4386
4387 /* read from cs5529 register */
4388 static unsigned int cs5529_config_read(comedi_device *dev, unsigned int reg_select_bits)
4389 {
4390         unsigned int value;
4391
4392         reg_select_bits &= CSCMD_REGISTER_SELECT_MASK;
4393         cs5529_command(dev, CSCMD_COMMAND | CSCMD_READ | reg_select_bits);
4394         if(cs5529_wait_for_idle(dev))
4395                 comedi_error(dev, "timeout or signal in cs5529_config_read()");
4396         value = (ni_ao_win_inw(dev, CAL_ADC_Config_Data_High_Word_67xx) << 16) & 0xff0000;
4397         value |= ni_ao_win_inw(dev, CAL_ADC_Config_Data_Low_Word_67xx) & 0xffff;
4398         return value;
4399 }
4400
4401 static int cs5529_do_conversion(comedi_device *dev, unsigned short *data)
4402 {
4403         int retval;
4404         unsigned short status;
4405
4406         cs5529_command(dev, CSCMD_COMMAND | CSCMD_SINGLE_CONVERSION);
4407         retval = cs5529_wait_for_idle(dev);
4408         if(retval)
4409         {
4410                 comedi_error(dev, "timeout or signal in cs5529_do_conversion()");
4411                 return -ETIME;
4412         }
4413         status = ni_ao_win_inw(dev, CAL_ADC_Status_67xx);
4414         if(status & CSS_OSC_DETECT)
4415         {
4416                 rt_printk("ni_mio_common: cs5529 conversion error, status CSS_OSC_DETECT\n");
4417                 return -EIO;
4418         }
4419         if(status & CSS_OVERRANGE)
4420         {
4421                 rt_printk("ni_mio_common: cs5529 conversion error, overrange (ignoring)\n");
4422         }
4423         if(data)
4424         {
4425                 *data = ni_ao_win_inw(dev, CAL_ADC_Data_67xx);
4426                 /* cs5529 returns 16 bit signed data in bipolar mode */
4427                 *data ^= (1 << 15);
4428         }
4429         return 0;
4430 }
4431
4432 static int cs5529_ai_insn_read(comedi_device *dev,comedi_subdevice *s,comedi_insn *insn,lsampl_t *data)
4433 {
4434         int n, retval;
4435         unsigned short sample;
4436         unsigned int channel_select;
4437         const unsigned int INTERNAL_REF = 0x1000;
4438
4439         /* Set calibration adc source.  Docs lie, reference select bits 8 to 11
4440          * do nothing. bit 12 seems to chooses internal reference voltage, bit
4441          * 13 causes the adc input to go overrange (maybe reads external reference?) */
4442         if(insn->chanspec & CR_ALT_SOURCE)
4443                 channel_select = INTERNAL_REF;
4444         else
4445                 channel_select = CR_CHAN(insn->chanspec);
4446         ni_ao_win_outw(dev, channel_select, AO_Calibration_Channel_Select_67xx);
4447
4448         for(n = 0; n < insn->n; n++)
4449         {
4450                 retval = cs5529_do_conversion(dev, &sample);
4451                 if(retval < 0) return retval;
4452                 data[n] = sample;
4453         }
4454         return insn->n;
4455 }
4456
4457 static int init_cs5529(comedi_device *dev)
4458 {
4459         unsigned int config_bits = CSCFG_PORT_MODE | CSCFG_WORD_RATE_2180_CYCLES;
4460
4461 #if 1
4462         /* do self-calibration */
4463         cs5529_config_write(dev, config_bits | CSCFG_SELF_CAL_OFFSET_GAIN, CSCMD_CONFIG_REGISTER);
4464         /* need to force a conversion for calibration to run */
4465         cs5529_do_conversion(dev, NULL);
4466 #else
4467         /* force gain calibration to 1 */
4468         cs5529_config_write(dev, 0x400000, CSCMD_GAIN_REGISTER);
4469         cs5529_config_write(dev, config_bits | CSCFG_SELF_CAL_OFFSET, CSCMD_CONFIG_REGISTER);
4470         if(cs5529_wait_for_idle(dev))
4471                 comedi_error(dev, "timeout or signal in init_cs5529()\n");
4472 #endif
4473         if(0)
4474         {
4475                 rt_printk("config: 0x%x\n", cs5529_config_read(dev, CSCMD_CONFIG_REGISTER));
4476                 rt_printk("gain: 0x%x\n", cs5529_config_read(dev, CSCMD_GAIN_REGISTER));
4477                 rt_printk("offset: 0x%x\n", cs5529_config_read(dev, CSCMD_OFFSET_REGISTER));
4478         }
4479         return 0;
4480 }
4481
4482