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