Ported ni_660x.c to use counter support provided by ni_tio.c
[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 static 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_HW_Save_Reg:
3138                 stc_register = G_HW_Save_Register(0);
3139                 break;
3140         case NITIO_G1_HW_Save_Reg:
3141                 stc_register = G_HW_Save_Register(1);
3142                 break;
3143         case NITIO_G0_SW_Save_Reg:
3144                 stc_register = G_Save_Register(0);
3145                 break;
3146         case NITIO_G1_SW_Save_Reg:
3147                 stc_register = G_Save_Register(1);
3148                 break;
3149         case NITIO_G0_Mode_Reg:
3150                 stc_register = G_Mode_Register(0);
3151                 break;
3152         case NITIO_G1_Mode_Reg:
3153                 stc_register = G_Mode_Register(1);
3154                 break;
3155         case NITIO_G0_LoadA_Reg:
3156                 stc_register = G_Load_A_Register(0);
3157                 break;
3158         case NITIO_G1_LoadA_Reg:
3159                 stc_register = G_Load_A_Register(1);
3160                 break;
3161         case NITIO_G0_LoadB_Reg:
3162                 stc_register = G_Load_B_Register(0);
3163                 break;
3164         case NITIO_G1_LoadB_Reg:
3165                 stc_register = G_Load_B_Register(1);
3166                 break;
3167         case NITIO_G0_Input_Select_Reg:
3168                 stc_register = G_Input_Select_Register(0);
3169                 break;
3170         case NITIO_G1_Input_Select_Reg:
3171                 stc_register = G_Input_Select_Register(1);
3172                 break;
3173         case NITIO_G01_Status_Reg:
3174                 stc_register = G_Status_Register;
3175                 break;
3176         case NITIO_G01_Joint_Reset_Reg:
3177                 stc_register = Joint_Reset_Register;
3178                 break;
3179         case NITIO_G01_Joint_Status1_Reg:
3180                 stc_register = Joint_Status_1_Register;
3181                 break;
3182         case NITIO_G01_Joint_Status2_Reg:
3183                 stc_register = Joint_Status_2_Register;
3184                 break;
3185         default:
3186                 rt_printk("%s: unhandled register 0x%x in switch.\n", __FUNCTION__, reg);
3187                 BUG();
3188                 return 0;
3189                 break;
3190         }
3191         return stc_register;
3192 }
3193
3194 static void ni_gpct_write_register(struct ni_gpct *counter, unsigned bits, enum ni_gpct_register reg)
3195 {
3196         comedi_device *dev = counter->dev;
3197         unsigned stc_register;
3198         /* bits in the join reset register which are relevant to counters */
3199         static const unsigned gpct_joint_reset_mask = G0_Reset | G1_Reset;
3200         switch(reg)
3201         {
3202         /* m-series-only registers */
3203         case NITIO_G0_Counting_Mode_Reg:
3204                 ni_writew(bits, M_Offset_G0_Counting_Mode);
3205                 break;
3206         case NITIO_G1_Counting_Mode_Reg:
3207                 ni_writew(bits, M_Offset_G1_Counting_Mode);
3208                 break;
3209         case NITIO_G0_Second_Gate_Reg:
3210                 ni_writew(bits, M_Offset_G0_Second_Gate);
3211                 break;
3212         case NITIO_G1_Second_Gate_Reg:
3213                 ni_writew(bits, M_Offset_G1_Second_Gate);
3214                 break;
3215         /* 32 bit registers */
3216         case NITIO_G0_LoadA_Reg:
3217         case NITIO_G1_LoadA_Reg:
3218         case NITIO_G0_LoadB_Reg:
3219         case NITIO_G1_LoadB_Reg:
3220                 stc_register = ni_gpct_to_stc_register(reg);
3221                 devpriv->stc_writel(dev, bits, stc_register);
3222                 break;
3223         /* 16 bit registers */
3224         case NITIO_G01_Joint_Reset_Reg:
3225                 BUG_ON(bits & ~gpct_joint_reset_mask);
3226                 /* fall-through */
3227         default:
3228                 stc_register = ni_gpct_to_stc_register(reg);
3229                 devpriv->stc_writew(dev, bits, stc_register);
3230         }
3231 }
3232
3233 static unsigned ni_gpct_read_register(struct ni_gpct *counter, enum ni_gpct_register reg)
3234 {
3235         comedi_device *dev = counter->dev;
3236         unsigned stc_register;
3237         switch(reg)
3238         {
3239         /* 32 bit registers */
3240         case NITIO_G0_HW_Save_Reg:
3241         case NITIO_G1_HW_Save_Reg:
3242         case NITIO_G0_SW_Save_Reg:
3243         case NITIO_G1_SW_Save_Reg:
3244                 stc_register = ni_gpct_to_stc_register(reg);
3245                 return devpriv->stc_readl(dev, stc_register);
3246                 break;
3247         /* 16 bit registers */
3248         default:
3249                 stc_register = ni_gpct_to_stc_register(reg);
3250                 return devpriv->stc_readw(dev, stc_register);
3251                 break;
3252         }
3253         return 0;
3254 }
3255
3256 static int ni_alloc_private(comedi_device *dev)
3257 {
3258         int ret;
3259
3260         ret = alloc_private(dev, sizeof(ni_private));
3261         if(ret < 0) return ret;
3262
3263         spin_lock_init(&devpriv->window_lock);
3264
3265         return 0;
3266 };
3267
3268 static int ni_E_init(comedi_device *dev,comedi_devconfig *it)
3269 {
3270         comedi_subdevice *s;
3271         int bits;
3272         unsigned j;
3273
3274         if(boardtype.n_aochan > MAX_N_AO_CHAN)
3275         {
3276                 printk("bug! boardtype.n_aochan > MAX_N_AO_CHAN\n");
3277                 return -EINVAL;
3278         }
3279
3280         if(alloc_subdevices(dev, 11 + NUM_GPCT) < 0)
3281                 return -ENOMEM;
3282
3283         /* analog input subdevice */
3284
3285         s=dev->subdevices+0;
3286         dev->read_subdev=s;
3287         if(boardtype.n_adchan){
3288                 s->type=COMEDI_SUBD_AI;
3289                 s->subdev_flags=SDF_READABLE | SDF_DIFF | SDF_DITHER | SDF_CMD_READ;
3290                 if(boardtype.reg_type != ni_reg_611x)
3291                         s->subdev_flags |= SDF_GROUND | SDF_COMMON | SDF_OTHER;
3292                 if(boardtype.adbits > 16)
3293                         s->subdev_flags |= SDF_LSAMPL;
3294                 if(boardtype.reg_type & ni_reg_m_series_mask)
3295                         s->subdev_flags |= SDF_SOFT_CALIBRATED;
3296                 s->n_chan=boardtype.n_adchan;
3297                 s->len_chanlist=512;
3298                 s->maxdata=(1<<boardtype.adbits)-1;
3299                 s->range_table=ni_range_lkup[boardtype.gainlkup];
3300                 s->insn_read=ni_ai_insn_read;
3301                 s->insn_config=ni_ai_insn_config;
3302                 s->do_cmdtest=ni_ai_cmdtest;
3303                 s->do_cmd=ni_ai_cmd;
3304                 s->cancel=ni_ai_reset;
3305                 s->poll=ni_ai_poll;
3306                 s->munge=ni_ai_munge;
3307         }else{
3308                 s->type=COMEDI_SUBD_UNUSED;
3309         }
3310
3311         /* analog output subdevice */
3312
3313         s=dev->subdevices+1;
3314         if(boardtype.n_aochan){
3315                 s->type=COMEDI_SUBD_AO;
3316                 s->subdev_flags=SDF_WRITABLE|SDF_DEGLITCH|SDF_GROUND;
3317                 if(boardtype.reg_type & ni_reg_m_series_mask)
3318                         s->subdev_flags |= SDF_SOFT_CALIBRATED;
3319                 s->n_chan=boardtype.n_aochan;
3320                 s->maxdata=(1<<boardtype.aobits)-1;
3321                 s->range_table = boardtype.ao_range_table;
3322                 s->insn_read=ni_ao_insn_read;
3323                 if(boardtype.reg_type & ni_reg_6xxx_mask){
3324                         s->insn_write=ni_ao_insn_write_671x;
3325                 }else{
3326                         s->insn_write=ni_ao_insn_write;
3327                 }
3328 #ifdef PCIDMA
3329                 if(boardtype.n_aochan){
3330 #else
3331                 if(boardtype.ao_fifo_depth){
3332 #endif
3333                         dev->write_subdev=s;
3334                         s->subdev_flags |= SDF_CMD_WRITE;
3335                         s->do_cmd=ni_ao_cmd;
3336                         s->do_cmdtest=ni_ao_cmdtest;
3337                         s->len_chanlist = boardtype.n_aochan;
3338                         if((boardtype.reg_type & ni_reg_m_series_mask) == 0)
3339                                 s->munge=ni_ao_munge;
3340                 }
3341                 s->cancel=ni_ao_reset;
3342         }else{
3343                 s->type=COMEDI_SUBD_UNUSED;
3344         }
3345         if((boardtype.reg_type & ni_reg_67xx_mask))
3346                 init_ao_67xx(dev, s);
3347
3348         /* digital i/o subdevice */
3349
3350         s=dev->subdevices+2;
3351         s->type=COMEDI_SUBD_DIO;
3352         s->subdev_flags=SDF_WRITABLE|SDF_READABLE;
3353         s->maxdata=1;
3354         s->io_bits=0;           /* all bits input */
3355         s->range_table=&range_digital;
3356         if(boardtype.reg_type & ni_reg_m_series_mask)
3357         {
3358                 s->n_chan = 32;
3359                 s->insn_bits = ni_m_series_dio_insn_bits;
3360                 s->insn_config=ni_m_series_dio_insn_config;
3361                 ni_writel(s->io_bits, M_Offset_DIO_Direction);
3362         }else
3363         {
3364                 s->n_chan=8;
3365                 s->insn_bits=ni_dio_insn_bits;
3366                 s->insn_config=ni_dio_insn_config;
3367                 devpriv->dio_control = DIO_Pins_Dir(s->io_bits);
3368                 ni_writew(devpriv->dio_control, DIO_Control_Register);
3369         }
3370
3371         /* 8255 device */
3372         s=dev->subdevices+3;
3373         if(boardtype.has_8255){
3374                 subdev_8255_init(dev,s,ni_8255_callback,(unsigned long)dev);
3375         }else{
3376                 s->type=COMEDI_SUBD_UNUSED;
3377         }
3378
3379         /* formerly general purpose counter/timer device, but no longer used */
3380         s=dev->subdevices+4;
3381         s->type = COMEDI_SUBD_UNUSED;
3382
3383         /* calibration subdevice -- ai and ao */
3384         s=dev->subdevices+5;
3385         s->type=COMEDI_SUBD_CALIB;
3386         if(boardtype.reg_type & ni_reg_m_series_mask)
3387         {
3388                 // internal PWM analog output used for AI nonlinearity calibration
3389                 s->subdev_flags = SDF_INTERNAL;
3390                 s->insn_config = &ni_m_series_pwm_config;
3391                 s->n_chan = 1;
3392                 s->maxdata = 0;
3393                 ni_writel(0x0, M_Offset_Cal_PWM);
3394         } else if(boardtype.reg_type == ni_reg_6143)
3395         {
3396                 // internal PWM analog output used for AI nonlinearity calibration
3397                 s->subdev_flags = SDF_INTERNAL;
3398                 s->insn_config = &ni_6143_pwm_config;
3399                 s->n_chan = 1;
3400                 s->maxdata = 0;
3401         }else
3402         {
3403                 s->subdev_flags = SDF_WRITABLE | SDF_INTERNAL;
3404                 s->insn_read = &ni_calib_insn_read;
3405                 s->insn_write = &ni_calib_insn_write;
3406                 caldac_setup(dev, s);
3407         }
3408
3409         /* EEPROM */
3410         s=dev->subdevices+6;
3411         s->type=COMEDI_SUBD_MEMORY;
3412         s->subdev_flags=SDF_READABLE|SDF_INTERNAL;
3413         s->maxdata=0xff;
3414         if(boardtype.reg_type & ni_reg_m_series_mask)
3415         {
3416                 s->n_chan = M_SERIES_EEPROM_SIZE;
3417                 s->insn_read = &ni_m_series_eeprom_insn_read;
3418         }else
3419         {
3420                 s->n_chan = 512;
3421                 s->insn_read = &ni_eeprom_insn_read;
3422         }
3423         /* PFI */
3424         s=dev->subdevices + 7;
3425         s->type = COMEDI_SUBD_DIO;
3426         s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
3427         if(boardtype.reg_type & ni_reg_m_series_mask)
3428         {
3429                 unsigned i;
3430                 s->n_chan = 16;
3431                 ni_writew(s->state, M_Offset_PFI_DO);
3432                 for(i = 0; i < NUM_PFI_OUTPUT_SELECT_REGS; ++i)
3433                 {
3434                         ni_writew(devpriv->pfi_output_select_reg[i], M_Offset_PFI_Output_Select(i + 1));
3435                 }
3436         }else
3437         {
3438                 s->n_chan = 10;
3439         }
3440         s->maxdata = 1;
3441         s->insn_bits = ni_pfi_insn_bits;
3442         s->insn_config = ni_pfi_insn_config;
3443         ni_set_bits(dev, IO_Bidirection_Pin_Register, ~0, 0);
3444
3445         /* cs5529 calibration adc */
3446         s = dev->subdevices + 8;
3447         if(boardtype.reg_type & ni_reg_67xx_mask)
3448         {
3449                 s->type = COMEDI_SUBD_AI;
3450                 s->subdev_flags = SDF_READABLE | SDF_DIFF | SDF_INTERNAL;
3451                 // one channel for each analog output channel
3452                 s->n_chan = boardtype.n_aochan;
3453                 s->maxdata = (1 << 16) - 1;
3454                 s->range_table = &range_unknown; /* XXX */
3455                 s->insn_read=cs5529_ai_insn_read;
3456                 s->insn_config=NULL;
3457                 init_cs5529(dev);
3458         }else
3459         {
3460                 s->type=COMEDI_SUBD_UNUSED;
3461         }
3462
3463         /* Serial */
3464         s=dev->subdevices+9;
3465         s->type=COMEDI_SUBD_SERIAL;
3466         s->subdev_flags=SDF_READABLE|SDF_WRITABLE|SDF_INTERNAL;
3467         s->n_chan=1;
3468         s->maxdata=0xff;
3469         s->insn_config = ni_serial_insn_config;
3470         devpriv->serial_interval_ns = 0;
3471         devpriv->serial_hw_mode = 0;
3472
3473         /* RTSI */
3474         s=dev->subdevices + 10;
3475         s->type = COMEDI_SUBD_DIO;
3476         s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
3477         s->n_chan = 8;
3478         s->maxdata = 1;
3479         s->insn_bits = ni_rtsi_insn_bits;
3480         s->insn_config = ni_rtsi_insn_config;
3481         ni_rtsi_init(dev);
3482
3483         /* General purpose counters */
3484         for(j = 0; j < NUM_GPCT; ++j)
3485         {
3486                 s = dev->subdevices + 11 + j;
3487                 s->type = COMEDI_SUBD_COUNTER;
3488                 s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
3489                 s->n_chan = 3;
3490                 if(boardtype.reg_type & ni_reg_m_series_mask)
3491                         s->maxdata = 0xffffffff;
3492                 else
3493                         s->maxdata = 0xffffff;
3494                 s->insn_read = ni_gpct_insn_read;
3495                 s->insn_write = ni_gpct_insn_write;
3496                 s->insn_config = ni_gpct_insn_config;
3497                 s->private = &devpriv->counters[j];
3498
3499                 devpriv->counters[j].dev = dev;
3500                 devpriv->counters[j].chip_index = 0;
3501                 devpriv->counters[j].counter_index = j;
3502                 devpriv->counters[j].write_register = ni_gpct_write_register;
3503                 devpriv->counters[j].read_register = ni_gpct_read_register;
3504                 if(boardtype.reg_type & ni_reg_m_series_mask)
3505                 {
3506                         devpriv->counters[j].variant = ni_gpct_variant_m_series;
3507                 }else
3508                 {
3509                         devpriv->counters[j].variant = ni_gpct_variant_e_series;
3510                 }
3511                 devpriv->counters[j].clock_period_ps = 0;
3512                 ni_tio_init_counter(&devpriv->counters[j]);
3513         }
3514
3515         /* ai configuration */
3516         ni_ai_reset(dev,dev->subdevices+0);
3517         if((boardtype.reg_type & ni_reg_6xxx_mask) == 0){
3518                 // BEAM is this needed for PCI-6143 ??
3519                 devpriv->clock_and_fout =
3520                         Slow_Internal_Time_Divide_By_2 |
3521                         Slow_Internal_Timebase |
3522                         Clock_To_Board_Divide_By_2 |
3523                         Clock_To_Board |
3524                         AI_Output_Divide_By_2 |
3525                         AO_Output_Divide_By_2;
3526         }else{
3527                 devpriv->clock_and_fout =
3528                         Slow_Internal_Time_Divide_By_2 |
3529                         Slow_Internal_Timebase |
3530                         Clock_To_Board_Divide_By_2 |
3531                         Clock_To_Board;
3532         }
3533         devpriv->stc_writew(dev, devpriv->clock_and_fout, Clock_and_FOUT_Register);
3534
3535         /* analog output configuration */
3536         ni_ao_reset(dev,dev->subdevices + 1);
3537
3538         if(dev->irq){
3539                 devpriv->stc_writew(dev, (IRQ_POLARITY?Interrupt_Output_Polarity:0) |
3540                         (Interrupt_Output_On_3_Pins&0) |
3541                         Interrupt_A_Enable |
3542                         Interrupt_B_Enable |
3543                         Interrupt_A_Output_Select(interrupt_pin(dev->irq)) |
3544                         Interrupt_B_Output_Select(interrupt_pin(dev->irq)),
3545                         Interrupt_Control_Register
3546                 );
3547         }
3548
3549         /* DMA setup */
3550         /* tell the STC which dma channels to use for AI and AO */
3551         bits = 1 << ( AI_DMA_CHAN );
3552         bits |= 1 << ( AO_DMA_CHAN + 4 );
3553         ni_writeb( bits, AI_AO_Select);
3554         /* tell the STC which dma channels to use for
3555          * General purpose counters 0 and 1 */
3556         bits = 1 << ( GPC0_DMA_CHAN );
3557         bits |= 1 << ( GPC1_DMA_CHAN + 4 );
3558         ni_writeb( bits, G0_G1_Select);
3559
3560         if(boardtype.reg_type & ni_reg_6xxx_mask)
3561         {
3562                 ni_writeb( 0, Magic_611x );
3563         }else if(boardtype.reg_type & ni_reg_m_series_mask)
3564         {
3565                 int channel;
3566                 for(channel = 0; channel < boardtype.n_aochan; ++channel)
3567                 {
3568                         ni_writeb(0xf, M_Offset_AO_Waveform_Order(channel));
3569                         ni_writeb(0x0, M_Offset_AO_Reference_Attenuation(channel));
3570                 }
3571                 ni_writeb(0x0, M_Offset_AO_Calibration);
3572         }
3573
3574         printk("\n");
3575         return 0;
3576 }
3577
3578
3579
3580 static int ni_8255_callback(int dir,int port,int data,unsigned long arg)
3581 {
3582         comedi_device *dev=(comedi_device *)arg;
3583
3584         if(dir){
3585                 ni_writeb(data,Port_A+2*port);
3586                 return 0;
3587         }else{
3588                 return ni_readb(Port_A+2*port);
3589         }
3590 }
3591
3592 /*
3593         presents the EEPROM as a subdevice
3594 */
3595
3596 static int ni_eeprom_insn_read(comedi_device *dev,comedi_subdevice *s,
3597         comedi_insn *insn,lsampl_t *data)
3598 {
3599         data[0]=ni_read_eeprom(dev,CR_CHAN(insn->chanspec));
3600
3601         return 1;
3602 }
3603
3604 /*
3605         reads bytes out of eeprom
3606 */
3607
3608 static int ni_read_eeprom(comedi_device *dev,int addr)
3609 {
3610         int bit;
3611         int bitstring;
3612
3613         bitstring=0x0300|((addr&0x100)<<3)|(addr&0xff);
3614         ni_writeb(0x04,Serial_Command);
3615         for(bit=0x8000;bit;bit>>=1){
3616                 ni_writeb(0x04|((bit&bitstring)?0x02:0),Serial_Command);
3617                 ni_writeb(0x05|((bit&bitstring)?0x02:0),Serial_Command);
3618         }
3619         bitstring=0;
3620         for(bit=0x80;bit;bit>>=1){
3621                 ni_writeb(0x04,Serial_Command);
3622                 ni_writeb(0x05,Serial_Command);
3623                 bitstring|=((ni_readb(XXX_Status)&PROMOUT)?bit:0);
3624         }
3625         ni_writeb(0x00,Serial_Command);
3626
3627         return bitstring;
3628 }
3629
3630 static int ni_m_series_eeprom_insn_read(comedi_device *dev,comedi_subdevice *s,
3631         comedi_insn *insn,lsampl_t *data)
3632 {
3633         data[0] = devpriv->eeprom_buffer[CR_CHAN(insn->chanspec)];
3634
3635         return 1;
3636 }
3637
3638 static int ni_get_pwm_config(comedi_device *dev, lsampl_t *data)
3639 {
3640         data[1] = devpriv->pwm_up_count * devpriv->clock_ns;
3641         data[2] = devpriv->pwm_down_count * devpriv->clock_ns;
3642         return 3;
3643 }
3644
3645 static int ni_m_series_pwm_config(comedi_device *dev, comedi_subdevice *s,
3646         comedi_insn *insn, lsampl_t *data)
3647 {
3648         unsigned up_count, down_count;
3649         switch(data[0])
3650         {
3651         case INSN_CONFIG_PWM_OUTPUT:
3652                 switch(data[1])
3653                 {
3654                 case TRIG_ROUND_NEAREST:
3655                         up_count = (data[2] + devpriv->clock_ns / 2) / devpriv->clock_ns;
3656                         break;
3657                 case TRIG_ROUND_DOWN:
3658                         up_count = data[2] / devpriv->clock_ns;
3659                         break;
3660                 case TRIG_ROUND_UP:
3661                         up_count = (data[2] + devpriv->clock_ns - 1) / devpriv->clock_ns;
3662                         break;
3663                 default:
3664                         return -EINVAL;
3665                         break;
3666                 }
3667                 switch(data[3])
3668                 {
3669                 case TRIG_ROUND_NEAREST:
3670                         down_count = (data[4] + devpriv->clock_ns / 2) / devpriv->clock_ns;
3671                         break;
3672                 case TRIG_ROUND_DOWN:
3673                         down_count = data[4] / devpriv->clock_ns;
3674                         break;
3675                 case TRIG_ROUND_UP:
3676                         down_count = (data[4] + devpriv->clock_ns - 1) / devpriv->clock_ns;
3677                         break;
3678                 default:
3679                         return -EINVAL;
3680                         break;
3681                 }
3682                 if(up_count * devpriv->clock_ns != data[2] ||
3683                         down_count * devpriv->clock_ns != data[4])
3684                 {
3685                         data[2] = up_count * devpriv->clock_ns;
3686                         data[4] = down_count * devpriv->clock_ns;
3687                         return -EAGAIN;
3688                 }
3689                 ni_writel(MSeries_Cal_PWM_High_Time_Bits(up_count) | MSeries_Cal_PWM_Low_Time_Bits(down_count), M_Offset_Cal_PWM);
3690                 devpriv->pwm_up_count = up_count;
3691                 devpriv->pwm_down_count = down_count;
3692                 return 5;
3693                 break;
3694         case INSN_CONFIG_GET_PWM_OUTPUT:
3695                 return ni_get_pwm_config(dev, data);
3696                 break;
3697         default:
3698                 return -EINVAL;
3699                 break;
3700         }
3701         return 0;
3702 }
3703
3704 static int ni_6143_pwm_config(comedi_device *dev, comedi_subdevice *s,
3705         comedi_insn *insn, lsampl_t *data)
3706 {
3707         unsigned up_count, down_count;
3708         switch(data[0])
3709         {
3710         case INSN_CONFIG_PWM_OUTPUT:
3711                 switch(data[1])
3712                 {
3713                 case TRIG_ROUND_NEAREST:
3714                         up_count = (data[2] + devpriv->clock_ns / 2) / devpriv->clock_ns;
3715                         break;
3716                 case TRIG_ROUND_DOWN:
3717                         up_count = data[2] / devpriv->clock_ns;
3718                         break;
3719                 case TRIG_ROUND_UP:
3720                         up_count = (data[2] + devpriv->clock_ns - 1) / devpriv->clock_ns;
3721                         break;
3722                 default:
3723                         return -EINVAL;
3724                         break;
3725                 }
3726                 switch(data[3])
3727                 {
3728                 case TRIG_ROUND_NEAREST:
3729                         down_count = (data[4] + devpriv->clock_ns / 2) / devpriv->clock_ns;
3730                         break;
3731                 case TRIG_ROUND_DOWN:
3732                         down_count = data[4] / devpriv->clock_ns;
3733                         break;
3734                 case TRIG_ROUND_UP:
3735                         down_count = (data[4] + devpriv->clock_ns - 1) / devpriv->clock_ns;
3736                         break;
3737                 default:
3738                         return -EINVAL;
3739                         break;
3740                 }
3741                 if(up_count * devpriv->clock_ns != data[2] ||
3742                         down_count * devpriv->clock_ns != data[4])
3743                 {
3744                         data[2] = up_count * devpriv->clock_ns;
3745                         data[4] = down_count * devpriv->clock_ns;
3746                         return -EAGAIN;
3747                 }
3748                 ni_writel(up_count, Calibration_HighTime_6143);
3749                 devpriv->pwm_up_count = up_count;
3750                 ni_writel(down_count, Calibration_LowTime_6143);
3751                 devpriv->pwm_down_count = down_count;
3752                 return 5;
3753                 break;
3754         case INSN_CONFIG_GET_PWM_OUTPUT:
3755                 return ni_get_pwm_config(dev, data);
3756         default:
3757                 return -EINVAL;
3758                 break;
3759         }
3760         return 0;
3761 }
3762
3763 static void ni_write_caldac(comedi_device *dev,int addr,int val);
3764 /*
3765         calibration subdevice
3766 */
3767 static int ni_calib_insn_write(comedi_device *dev,comedi_subdevice *s,
3768         comedi_insn *insn,lsampl_t *data)
3769 {
3770         ni_write_caldac(dev,CR_CHAN(insn->chanspec),data[0]);
3771
3772         return 1;
3773 }
3774
3775 static int ni_calib_insn_read(comedi_device *dev,comedi_subdevice *s,
3776         comedi_insn *insn,lsampl_t *data)
3777 {
3778         data[0] = devpriv->caldacs[CR_CHAN(insn->chanspec)];
3779
3780         return 1;
3781 }
3782
3783 static int pack_mb88341(int addr,int val,int *bitstring);
3784 static int pack_dac8800(int addr,int val,int *bitstring);
3785 static int pack_dac8043(int addr,int val,int *bitstring);
3786 static int pack_ad8522(int addr,int val,int *bitstring);
3787 static int pack_ad8804(int addr,int val,int *bitstring);
3788 static int pack_ad8842(int addr,int val,int *bitstring);
3789
3790 struct caldac_struct{
3791         int n_chans;
3792         int n_bits;
3793         int (*packbits)(int,int,int *);
3794 };
3795
3796 static struct caldac_struct caldacs[] = {
3797         [mb88341] = { 12, 8, pack_mb88341 },
3798         [dac8800] = { 8, 8, pack_dac8800 },
3799         [dac8043] = { 1, 12, pack_dac8043 },
3800         [ad8522]  = { 2, 12, pack_ad8522 },
3801         [ad8804] = { 12, 8, pack_ad8804 },
3802         [ad8842] = { 8, 8, pack_ad8842 },
3803         [ad8804_debug] = { 16, 8, pack_ad8804 },
3804 };
3805
3806 static void caldac_setup(comedi_device *dev,comedi_subdevice *s)
3807 {
3808         int i,j;
3809         int n_dacs;
3810         int n_chans=0;
3811         int n_bits;
3812         int diffbits=0;
3813         int type;
3814         int chan;
3815
3816         type = boardtype.caldac[0];
3817         if(type==caldac_none)return;
3818         n_bits=caldacs[type].n_bits;
3819         for(i=0;i<3;i++){
3820                 type = boardtype.caldac[i];
3821                 if(type==caldac_none)break;
3822                 if(caldacs[type].n_bits!=n_bits)diffbits=1;
3823                 n_chans+=caldacs[type].n_chans;
3824         }
3825         n_dacs=i;
3826         s->n_chan=n_chans;
3827
3828         if(diffbits){
3829
3830                 if(n_chans>MAX_N_CALDACS){
3831                         printk("BUG! MAX_N_CALDACS too small\n");
3832                 }
3833                 s->maxdata_list=devpriv->caldac_maxdata_list;
3834                 chan=0;
3835                 for(i=0;i<n_dacs;i++){
3836                         type = boardtype.caldac[i];
3837                         for(j=0;j<caldacs[type].n_chans;j++){
3838                                 s->maxdata_list[chan]=
3839                                         (1<<caldacs[type].n_bits)-1;
3840                                 chan++;
3841                         }
3842                 }
3843
3844                 for( chan = 0; chan < s->n_chan; chan++ )
3845                         ni_write_caldac( dev, i, s->maxdata_list[ i ] / 2 );
3846         }else{
3847                 type = boardtype.caldac[0];
3848                 s->maxdata=(1<<caldacs[type].n_bits)-1;
3849
3850                 for( chan = 0; chan < s->n_chan; chan++ )
3851                         ni_write_caldac( dev, i, s->maxdata / 2 );
3852         }
3853 }
3854
3855 static void ni_write_caldac(comedi_device *dev,int addr,int val)
3856 {
3857         unsigned int loadbit=0,bits=0,bit,bitstring=0;
3858         int i;
3859         int type;
3860
3861         //printk("ni_write_caldac: chan=%d val=%d\n",addr,val);
3862         if( devpriv->caldacs[ addr ] == val ) return;
3863         devpriv->caldacs[ addr ] = val;
3864
3865         for(i=0;i<3;i++){
3866                 type = boardtype.caldac[i];
3867                 if(type==caldac_none)break;
3868                 if(addr<caldacs[type].n_chans){
3869                         bits=caldacs[type].packbits(addr,val,&bitstring);
3870                         loadbit=SerDacLd(i);
3871                         //printk("caldac: using i=%d addr=%d %x\n",i,addr,bitstring);
3872                         break;
3873                 }
3874                 addr-=caldacs[type].n_chans;
3875         }
3876
3877         for(bit=1<<(bits-1);bit;bit>>=1){
3878                 ni_writeb(((bit&bitstring)?0x02:0),Serial_Command);
3879                 comedi_udelay(1);
3880                 ni_writeb(1|((bit&bitstring)?0x02:0),Serial_Command);
3881                 comedi_udelay(1);
3882         }
3883         ni_writeb(loadbit,Serial_Command);
3884         comedi_udelay(1);
3885         ni_writeb(0,Serial_Command);
3886 }
3887
3888
3889
3890 static int pack_mb88341(int addr,int val,int *bitstring)
3891 {
3892         /*
3893            Fujitsu MB 88341
3894            Note that address bits are reversed.  Thanks to
3895            Ingo Keen for noticing this.
3896
3897            Note also that the 88341 expects address values from
3898            1-12, whereas we use channel numbers 0-11.  The NI
3899            docs use 1-12, also, so be careful here.
3900         */
3901         addr++;
3902         *bitstring=((addr&0x1)<<11) |
3903                   ((addr&0x2)<<9)  |
3904                   ((addr&0x4)<<7)  |
3905                   ((addr&0x8)<<5)  |
3906                   (val&0xff);
3907         return 12;
3908 }
3909
3910 static int pack_dac8800(int addr,int val,int *bitstring)
3911 {
3912         *bitstring=((addr&0x7)<<8)|(val&0xff);
3913         return 11;
3914 }
3915
3916 static int pack_dac8043(int addr,int val,int *bitstring)
3917 {
3918         *bitstring=val&0xfff;
3919         return 12;
3920 }
3921
3922 static int pack_ad8522(int addr,int val,int *bitstring)
3923 {
3924         *bitstring=(val&0xfff)|(addr ? 0xc000:0xa000);
3925         return 16;
3926 }
3927
3928 static int pack_ad8804(int addr,int val,int *bitstring)
3929 {
3930         *bitstring=((addr&0xf)<<8) | (val&0xff);
3931         return 12;
3932 }
3933
3934 static int pack_ad8842(int addr,int val,int *bitstring)
3935 {
3936         *bitstring=((addr+1)<<8) | (val&0xff);
3937         return 12;
3938 }
3939
3940
3941 #if 0
3942 /*
3943  *      Read the GPCTs current value.
3944  */
3945 static int GPCT_G_Watch(comedi_device *dev, int chan)
3946 {
3947         unsigned int hi1,hi2,lo;
3948
3949         devpriv->gpct_command[chan] &= ~G_Save_Trace;
3950         devpriv->stc_writew(dev,  devpriv->gpct_command[chan],G_Command_Register(chan));
3951
3952         devpriv->gpct_command[chan] |= G_Save_Trace;
3953         devpriv->stc_writew(dev,  devpriv->gpct_command[chan], G_Command_Register(chan));
3954
3955         /* This procedure is used because the two registers cannot
3956          * be read atomically. */
3957         do{
3958                 hi1 = devpriv->stc_readw(dev,  G_Save_Register_High(chan));
3959                 lo = devpriv->stc_readw(dev, G_Save_Register_Low(chan));
3960                 hi2 = devpriv->stc_readw(dev,  G_Save_Register_High(chan));
3961         }while(hi1!=hi2);
3962
3963         return (hi1<<16)|lo;
3964 }
3965
3966 static void GPCT_Reset(comedi_device *dev, int chan)
3967 {
3968         int temp_ack_reg=0;
3969
3970         //printk("GPCT_Reset...");
3971         devpriv->gpct_cur_operation[chan] = GPCT_RESET;
3972
3973         switch (chan) {
3974                 case 0:
3975                         devpriv->stc_writew(dev, G0_Reset,Joint_Reset_Register);
3976                         ni_set_bits(dev,Interrupt_A_Enable_Register,G0_TC_Interrupt_Enable,  0);
3977                         ni_set_bits(dev,Interrupt_A_Enable_Register,G0_Gate_Interrupt_Enable,0);
3978                         temp_ack_reg |= G0_Gate_Error_Confirm;
3979                         temp_ack_reg |= G0_TC_Error_Confirm;
3980                         temp_ack_reg |= G0_TC_Interrupt_Ack;
3981                         temp_ack_reg |= G0_Gate_Interrupt_Ack;
3982                         devpriv->stc_writew(dev, temp_ack_reg,Interrupt_A_Ack_Register);
3983
3984                         //problem...this interferes with the other ctr...
3985                         devpriv->an_trig_etc_reg |= GPFO_0_Output_Enable;
3986                         devpriv->stc_writew(dev, devpriv->an_trig_etc_reg, Analog_Trigger_Etc_Register);
3987                         break;
3988                 case 1:
3989                         devpriv->stc_writew(dev, G1_Reset,Joint_Reset_Register);
3990                         ni_set_bits(dev,Interrupt_B_Enable_Register,G1_TC_Interrupt_Enable,  0);
3991                         ni_set_bits(dev,Interrupt_B_Enable_Register,G0_Gate_Interrupt_Enable,0);
3992                         temp_ack_reg |= G1_Gate_Error_Confirm;
3993                         temp_ack_reg |= G1_TC_Error_Confirm;
3994                         temp_ack_reg |= G1_TC_Interrupt_Ack;
3995                         temp_ack_reg |= G1_Gate_Interrupt_Ack;
3996                         devpriv->stc_writew(dev, temp_ack_reg,Interrupt_B_Ack_Register);
3997
3998                         devpriv->an_trig_etc_reg |= GPFO_1_Output_Enable;
3999                         devpriv->stc_writew(dev, devpriv->an_trig_etc_reg, Analog_Trigger_Etc_Register);
4000                         break;
4001         };
4002
4003         devpriv->gpct_mode[chan] = 0;
4004         devpriv->gpct_input_select[chan] = 0;
4005         devpriv->gpct_command[chan] = 0;
4006
4007         devpriv->gpct_command[chan] |= G_Synchronized_Gate;
4008
4009         devpriv->stc_writew(dev,  devpriv->gpct_mode[chan],G_Mode_Register(chan));
4010         devpriv->stc_writew(dev,  devpriv->gpct_input_select[chan],G_Input_Select_Register(chan));
4011         devpriv->stc_writew(dev,  0,G_Autoincrement_Register(chan));
4012
4013         //printk("exit GPCT_Reset\n");
4014 }
4015
4016 #endif
4017
4018 static int ni_gpct_insn_config(comedi_device *dev, comedi_subdevice *s,
4019         comedi_insn *insn, lsampl_t *data)
4020 {
4021         struct ni_gpct *counter = s->private;
4022         return ni_tio_insn_config(counter, insn, data);
4023 }
4024
4025 static int ni_gpct_insn_read(comedi_device *dev, comedi_subdevice *s,
4026         comedi_insn *insn,lsampl_t *data)
4027 {
4028         struct ni_gpct *counter = s->private;
4029         return ni_tio_rinsn(counter, insn, data);
4030 }
4031
4032 static int ni_gpct_insn_write(comedi_device *dev, comedi_subdevice *s,
4033         comedi_insn *insn, lsampl_t *data)
4034 {
4035         struct ni_gpct *counter = s->private;
4036         return ni_tio_winsn(counter, insn, data);
4037 }
4038
4039 static int ni_gpct_cmd(comedi_device *dev, comedi_subdevice *s)
4040 {
4041         return 0;
4042 }
4043
4044 static int ni_gpct_cmdtest(comedi_device *dev, comedi_subdevice *s, comedi_cmd *cmd)
4045 {
4046         return 0;
4047 }
4048
4049 static int ni_gpct_cancel(comedi_device *dev, comedi_subdevice *s)
4050 {
4051         return 0;
4052 }
4053
4054 /*
4055  *
4056  *  Programmable Function Inputs
4057  *
4058  */
4059
4060 static int ni_m_series_set_pfi_routing(comedi_device *dev, unsigned chan, unsigned source)
4061 {
4062         unsigned pfi_reg_index;
4063         unsigned array_offset;
4064         if((source & 0x1f) != source) return -EINVAL;
4065         pfi_reg_index = 1 + chan / 3;
4066         array_offset = pfi_reg_index - 1;
4067         devpriv->pfi_output_select_reg[array_offset] &= ~MSeries_PFI_Output_Select_Mask(chan);
4068         devpriv->pfi_output_select_reg[array_offset] |= MSeries_PFI_Output_Select_Bits(chan, source);
4069         ni_writew(devpriv->pfi_output_select_reg[array_offset], M_Offset_PFI_Output_Select(pfi_reg_index));
4070         return 2;
4071 }
4072
4073 static int ni_old_set_pfi_routing(comedi_device *dev, unsigned chan, unsigned source)
4074 {
4075         // pre-m-series boards have fixed signals on pfi pins
4076         if(source != ni_old_get_pfi_routing(dev, chan)) return -EINVAL;
4077         return 2;
4078 }
4079
4080 static int ni_set_pfi_routing(comedi_device *dev, unsigned chan, unsigned source)
4081 {
4082         if(boardtype.reg_type & ni_reg_m_series_mask)
4083                 return ni_m_series_set_pfi_routing(dev, chan, source);
4084         else
4085                 return ni_old_set_pfi_routing(dev, chan, source);
4086 }
4087
4088 static unsigned ni_m_series_get_pfi_routing(comedi_device *dev, unsigned chan)
4089 {
4090         const unsigned array_offset = chan / 3;
4091         return MSeries_PFI_Output_Select_Source(chan, devpriv->pfi_output_select_reg[array_offset]);
4092 }
4093
4094 static unsigned ni_old_get_pfi_routing(comedi_device *dev, unsigned chan)
4095 {
4096         // pre-m-series boards have fixed signals on pfi pins
4097         switch(chan)
4098         {
4099         case 0:
4100                 return NI_PFI_OUTPUT_AI_START1;
4101                 break;
4102         case 1:
4103                 return NI_PFI_OUTPUT_AI_START2;
4104                 break;
4105         case 2:
4106                 return NI_PFI_OUTPUT_AI_CONVERT;
4107                 break;
4108         case 3:
4109                 return NI_PFI_OUTPUT_G_SRC1;
4110                 break;
4111         case 4:
4112                 return NI_PFI_OUTPUT_G_GATE1;
4113                 break;
4114         case 5:
4115                 return NI_PFI_OUTPUT_AO_UPDATE_N;
4116                 break;
4117         case 6:
4118                 return NI_PFI_OUTPUT_AO_START1;
4119                 break;
4120         case 7:
4121                 return NI_PFI_OUTPUT_AI_START_PULSE;
4122                 break;
4123         case 8:
4124                 return NI_PFI_OUTPUT_G_SRC0;
4125                 break;
4126         case 9:
4127                 return NI_PFI_OUTPUT_G_GATE0;
4128                 break;
4129         default:
4130                 rt_printk("%s: bug, unhandled case in switch.\n", __FUNCTION__);
4131                 break;
4132         }
4133         return 0;
4134 }
4135
4136 static unsigned ni_get_pfi_routing(comedi_device *dev, unsigned chan)
4137 {
4138         if(boardtype.reg_type & ni_reg_m_series_mask)
4139                 return ni_m_series_get_pfi_routing(dev, chan);
4140         else
4141                 return ni_old_get_pfi_routing(dev, chan);
4142 }
4143
4144 static int ni_pfi_insn_bits(comedi_device *dev,comedi_subdevice *s,
4145         comedi_insn *insn,lsampl_t *data)
4146 {
4147         if((boardtype.reg_type & ni_reg_m_series_mask) == 0)
4148         {
4149                 data[1] = 0;
4150                 return 2;
4151         }
4152         if(data[0])
4153         {
4154                 s->state &= ~data[0];
4155                 s->state |= (data[0] & data[1]);
4156                 ni_writew(s->state, M_Offset_PFI_DO);
4157         }
4158         data[1] = ni_readw(M_Offset_PFI_DI);
4159         return 2;
4160 }
4161
4162 static int ni_pfi_insn_config(comedi_device *dev,comedi_subdevice *s,
4163         comedi_insn *insn,lsampl_t *data)
4164 {
4165         unsigned int chan;
4166
4167         if(insn->n < 1)return -EINVAL;
4168
4169         chan = CR_CHAN(insn->chanspec);
4170
4171         switch(data[0]){
4172         case COMEDI_OUTPUT:
4173                 ni_set_bits(dev, IO_Bidirection_Pin_Register, 1<<chan, 1);
4174                 break;
4175         case COMEDI_INPUT:
4176                 ni_set_bits(dev, IO_Bidirection_Pin_Register, 1<<chan, 0);
4177                 break;
4178         case INSN_CONFIG_DIO_QUERY:
4179                 data[1] = (devpriv->io_bidirection_pin_reg & (1<<chan)) ? COMEDI_OUTPUT : COMEDI_INPUT;
4180                 return insn->n;
4181                 break;
4182         case INSN_CONFIG_SET_ROUTING:
4183                 return ni_set_pfi_routing(dev, chan, data[1]);
4184                 break;
4185         case INSN_CONFIG_GET_ROUTING:
4186                 data[1] = ni_get_pfi_routing(dev, chan);
4187                 return 2;
4188                 break;
4189         default:
4190                 return -EINVAL;
4191         }
4192
4193         return 1;
4194 }
4195
4196 /*
4197  *
4198  *  NI RTSI Bus Functions
4199  *
4200  */
4201 static void ni_rtsi_init(comedi_device *dev)
4202 {
4203         // Initialises the RTSI bus signal switch to a default state
4204
4205         // Set clock mode to internal
4206         devpriv->clock_and_fout2 = MSeries_RTSI_10MHz_Bit;
4207         if(ni_set_master_clock(dev, NI_MIO_INTERNAL_CLOCK, 0) < 0)
4208         {
4209                 rt_printk("ni_set_master_clock failed, bug?");
4210         }
4211         // default internal lines routing to RTSI bus lines
4212         devpriv->rtsi_trig_a_output_reg = RTSI_Trig_Output_Bits(0, NI_RTSI_OUTPUT_ADR_START1) |
4213                 RTSI_Trig_Output_Bits(1, NI_RTSI_OUTPUT_ADR_START2) |
4214                 RTSI_Trig_Output_Bits(2, NI_RTSI_OUTPUT_SCLKG) |
4215                 RTSI_Trig_Output_Bits(3, NI_RTSI_OUTPUT_DACUPDN);
4216         devpriv->stc_writew(dev, devpriv->rtsi_trig_a_output_reg,
4217                 RTSI_Trig_A_Output_Register);
4218         devpriv->rtsi_trig_b_output_reg = RTSI_Trig_Output_Bits(4, NI_RTSI_OUTPUT_DA_START1) |
4219                 RTSI_Trig_Output_Bits(5, NI_RTSI_OUTPUT_G_SRC0) |
4220                 RTSI_Trig_Output_Bits(6, NI_RTSI_OUTPUT_G_GATE0);
4221         if(boardtype.reg_type & ni_reg_m_series_mask)
4222                 devpriv->rtsi_trig_b_output_reg |= RTSI_Trig_Output_Bits(7, NI_RTSI_OUTPUT_RTSI_OSC);
4223         devpriv->stc_writew(dev, devpriv->rtsi_trig_b_output_reg,
4224                 RTSI_Trig_B_Output_Register);
4225
4226         // Sets the source and direction of the 4 on board lines
4227 //      devpriv->stc_writew(dev, 0x0000, RTSI_Board_Register);
4228 }
4229
4230 static int ni_rtsi_insn_bits(comedi_device *dev,comedi_subdevice *s,
4231         comedi_insn *insn,lsampl_t *data)
4232 {
4233         if(insn->n != 2) return -EINVAL;
4234
4235         data[1] = 0;
4236
4237         return 2;
4238 }
4239
4240 /* Find best multiplier/divider to try and get the PLL running at 80 MHz
4241  * given an arbitrary frequency input clock */
4242 static int ni_mseries_get_pll_parameters(unsigned reference_period_ns,
4243         unsigned *freq_divider, unsigned *freq_multiplier, unsigned *actual_period_ns)
4244 {
4245         unsigned div;
4246         unsigned best_div = 1;
4247         static const unsigned max_div = 0x10;
4248         unsigned mult;
4249         unsigned best_mult = 1;
4250         static const unsigned max_mult = 0x100;
4251         static const unsigned pico_per_nano = 1000;
4252
4253         const unsigned reference_picosec = reference_period_ns * pico_per_nano;
4254         /* m-series wants the phased-locked loop to output 80MHz, which is divided by 4 to
4255          * 20 MHz for most timing clocks */
4256         static const unsigned target_picosec = 12500;
4257         static const unsigned fudge_factor_80_to_20Mhz = 4;
4258         int best_period_picosec = 0;
4259         for(div = 1; div <= max_div; ++div)
4260         {
4261                 for(mult = 1; mult <= max_mult; ++mult)
4262                 {
4263                         unsigned new_period_ps = (reference_picosec * div) / mult;
4264                         if(abs(new_period_ps - target_picosec) < abs(best_period_picosec - target_picosec))
4265                         {
4266                                 best_period_picosec = new_period_ps;
4267                                 best_div = div;
4268                                 best_mult = mult;
4269                         }
4270                 }
4271         }
4272         if(best_period_picosec == 0)
4273         {
4274                 rt_printk("%s: bug, failed to find pll parameters\n", __FUNCTION__);
4275                 return -EIO;
4276         }
4277         *freq_divider = best_div;
4278         *freq_multiplier = best_mult;
4279         *actual_period_ns = (best_period_picosec * fudge_factor_80_to_20Mhz + (pico_per_nano / 2)) / pico_per_nano;
4280         return 0;
4281 }
4282
4283 static inline unsigned num_configurable_rtsi_channels(comedi_device *dev)
4284 {
4285         if(boardtype.reg_type & ni_reg_m_series_mask) return 8;
4286         else return 7;
4287 }
4288
4289 static int ni_mseries_set_pll_master_clock(comedi_device *dev, unsigned source, unsigned period_ns)
4290 {
4291         static const unsigned min_period_ns = 50;
4292         static const unsigned max_period_ns = 1000;
4293         static const unsigned timeout = 1000;
4294         unsigned pll_control_bits;
4295         unsigned freq_divider;
4296         unsigned freq_multiplier;
4297         unsigned i;
4298         int retval;
4299         if(source == NI_MIO_PLL_PXI10_CLOCK) period_ns = 100;
4300         // these limits are somewhat arbitrary, but NI advertises 1 to 20MHz range so we'll use that
4301         if(period_ns < min_period_ns || period_ns > max_period_ns)
4302         {
4303                 rt_printk("%s: you must specify an input clock frequency between %i and %i nanosec "
4304                         "for the phased-lock loop.\n", __FUNCTION__, min_period_ns, max_period_ns);
4305                 return -EINVAL;
4306         }
4307         devpriv->rtsi_trig_direction_reg &= ~Use_RTSI_Clock_Bit;
4308         devpriv->stc_writew(dev, devpriv->rtsi_trig_direction_reg, RTSI_Trig_Direction_Register);
4309         pll_control_bits = MSeries_PLL_Enable_Bit | MSeries_PLL_VCO_Mode_75_150MHz_Bits;
4310         devpriv->clock_and_fout2 |= MSeries_Timebase1_Select_Bit | MSeries_Timebase3_Select_Bit;
4311         devpriv->clock_and_fout2 &= ~MSeries_PLL_In_Source_Select_Mask;
4312         switch(source)
4313         {
4314         case NI_MIO_PLL_PXI_STAR_TRIGGER_CLOCK:
4315                 devpriv->clock_and_fout2 |= MSeries_PLL_In_Source_Select_Star_Trigger_Bits;
4316                 retval = ni_mseries_get_pll_parameters(period_ns, &freq_divider,
4317                         &freq_multiplier, &devpriv->clock_ns);
4318                 if(retval < 0) return retval;
4319                 break;
4320         case NI_MIO_PLL_PXI10_CLOCK:
4321                 /* pxi clock is 10MHz */
4322                 devpriv->clock_and_fout2 |= MSeries_PLL_In_Source_Select_PXI_Clock10;
4323                 retval = ni_mseries_get_pll_parameters(period_ns, &freq_divider,
4324                         &freq_multiplier, &devpriv->clock_ns);
4325                 if(retval < 0) return retval;
4326                 break;
4327         default:
4328                 {
4329                         unsigned rtsi_channel;
4330                         static const unsigned max_rtsi_channel = 7;
4331                         for(rtsi_channel = 0; rtsi_channel <= max_rtsi_channel; ++rtsi_channel)
4332                         {
4333                                 if(source == NI_MIO_PLL_RTSI_CLOCK(rtsi_channel))
4334                                 {
4335                                         devpriv->clock_and_fout2 |= MSeries_PLL_In_Source_Select_RTSI_Bits(rtsi_channel);
4336                                         break;
4337                                 }
4338                         }
4339                         if(rtsi_channel > max_rtsi_channel) return -EINVAL;
4340                         retval = ni_mseries_get_pll_parameters(period_ns, &freq_divider,
4341                                 &freq_multiplier, &devpriv->clock_ns);
4342                         if(retval < 0) return retval;
4343                 }
4344                 break;
4345         }
4346         ni_writew(devpriv->clock_and_fout2, M_Offset_Clock_and_Fout2);
4347         pll_control_bits |= MSeries_PLL_Divisor_Bits(freq_divider) | MSeries_PLL_Multiplier_Bits(freq_multiplier);
4348 //      rt_printk("using divider=%i, multiplier=%i for PLL.  pll_control_bits = 0x%x\n", freq_divider, freq_multiplier, pll_control_bits);
4349 //      rt_printk("clock_ns=%d\n", devpriv->clock_ns);
4350         ni_writew(pll_control_bits, M_Offset_PLL_Control);
4351         devpriv->clock_source = source;
4352         /* it seems to typically take a few hundred microseconds for PLL to lock */
4353         for(i = 0; i < timeout; ++i)
4354         {
4355                 if(ni_readw(M_Offset_PLL_Status) & MSeries_PLL_Locked_Bit)
4356                 {
4357                         break;
4358                 }
4359                 udelay(1);
4360         }
4361         if(i == timeout)
4362         {
4363                 rt_printk("%s: timed out waiting for PLL to lock to reference clock source %i with period %i ns.\n",
4364                         __FUNCTION__, source, period_ns);
4365                 return -ETIMEDOUT;
4366         }
4367         return 3;
4368 }
4369
4370 static int ni_set_master_clock(comedi_device *dev, unsigned source, unsigned period_ns)
4371 {
4372         if(source == NI_MIO_INTERNAL_CLOCK)
4373         {
4374                 devpriv->rtsi_trig_direction_reg &= ~Use_RTSI_Clock_Bit;
4375                 devpriv->stc_writew(dev, devpriv->rtsi_trig_direction_reg, RTSI_Trig_Direction_Register);
4376                 devpriv->clock_ns = 50;
4377                 if(boardtype.reg_type & ni_reg_m_series_mask)
4378                 {
4379                         devpriv->clock_and_fout2 &= ~(MSeries_Timebase1_Select_Bit | MSeries_Timebase3_Select_Bit);
4380                         ni_writew(devpriv->clock_and_fout2, M_Offset_Clock_and_Fout2);
4381                         ni_writew(0, M_Offset_PLL_Control);
4382                 }
4383                 devpriv->clock_source = source;
4384         }else
4385         {
4386                 if(boardtype.reg_type & ni_reg_m_series_mask)
4387                 {
4388                         return ni_mseries_set_pll_master_clock(dev, source, period_ns);
4389                 }else
4390                 {
4391                         if(source == NI_MIO_RTSI_CLOCK)
4392                         {
4393                                 devpriv->rtsi_trig_direction_reg |= Use_RTSI_Clock_Bit;
4394                                 devpriv->stc_writew(dev, devpriv->rtsi_trig_direction_reg, RTSI_Trig_Direction_Register);
4395                                 if(devpriv->clock_ns == 0)
4396                                 {
4397                                         rt_printk("%s: we don't handle an unspecified clock period correctly yet, returning error.\n",
4398                                                 __FUNCTION__);
4399                                         return -EINVAL;
4400                                 }else
4401                                 {
4402                                         devpriv->clock_ns = period_ns;
4403                                 }
4404                                 devpriv->clock_source = source;
4405                         }else
4406                                 return -EINVAL;
4407                 }
4408         }
4409         return 3;
4410 }
4411
4412 static int ni_valid_rtsi_output_source(comedi_device *dev, unsigned chan, unsigned source)
4413 {
4414         if(chan >= num_configurable_rtsi_channels(dev))
4415         {
4416                 if(chan == old_RTSI_clock_channel)
4417                 {
4418                         if(source == NI_RTSI_OUTPUT_RTSI_OSC) return 1;
4419                         else
4420                         {
4421                                 rt_printk("%s: invalid source for channel=%i, channel %i is always the RTSI clock for pre-m-series boards.\n",
4422                                         __FUNCTION__, chan, old_RTSI_clock_channel);
4423                                 return 0;
4424                         }
4425                 }
4426                 return 0;
4427         }
4428         switch(source)
4429         {
4430         case NI_RTSI_OUTPUT_ADR_START1:
4431         case NI_RTSI_OUTPUT_ADR_START2:
4432         case NI_RTSI_OUTPUT_SCLKG:
4433         case NI_RTSI_OUTPUT_DACUPDN:
4434         case NI_RTSI_OUTPUT_DA_START1:
4435         case NI_RTSI_OUTPUT_G_SRC0:
4436         case NI_RTSI_OUTPUT_G_GATE0:
4437         case NI_RTSI_OUTPUT_RGOUT0:
4438         case NI_RTSI_OUTPUT_RTSI_BRD_0:
4439                 return 1;
4440                 break;
4441         case NI_RTSI_OUTPUT_RTSI_OSC:
4442                 if(boardtype.reg_type & ni_reg_m_series_mask)
4443                         return 1;
4444                 else return 0;
4445                 break;
4446         default:
4447                 return 0;
4448                 break;
4449         }
4450 }
4451
4452 static int ni_set_rtsi_routing(comedi_device *dev, unsigned chan, unsigned source)
4453 {
4454         if(ni_valid_rtsi_output_source(dev, chan, source) == 0) return -EINVAL;
4455         if(chan < 4)
4456         {
4457                 devpriv->rtsi_trig_a_output_reg &= ~RTSI_Trig_Output_Mask(chan);
4458                 devpriv->rtsi_trig_a_output_reg |= RTSI_Trig_Output_Bits(chan, source);
4459                 devpriv->stc_writew(dev, devpriv->rtsi_trig_a_output_reg,
4460                         RTSI_Trig_A_Output_Register);
4461         }else if(chan < 8)
4462         {
4463                 devpriv->rtsi_trig_b_output_reg &= ~RTSI_Trig_Output_Mask(chan);
4464                 devpriv->rtsi_trig_b_output_reg |= RTSI_Trig_Output_Bits(chan, source);
4465                 devpriv->stc_writew(dev, devpriv->rtsi_trig_b_output_reg,
4466                         RTSI_Trig_B_Output_Register);
4467         }
4468         return 2;
4469 }
4470
4471 static unsigned ni_get_rtsi_routing(comedi_device *dev, unsigned chan)
4472 {
4473         if(chan < 4)
4474         {
4475                 return RTSI_Trig_Output_Source(chan, devpriv->rtsi_trig_a_output_reg);
4476         }else if(chan < num_configurable_rtsi_channels(dev))
4477         {
4478                 return RTSI_Trig_Output_Source(chan, devpriv->rtsi_trig_b_output_reg);
4479         }else
4480         {
4481                 if(chan == old_RTSI_clock_channel)
4482                         return NI_RTSI_OUTPUT_RTSI_OSC;
4483                 rt_printk("%s: bug! should never get here?\n", __FUNCTION__);
4484                 return 0;
4485         }
4486 }
4487
4488 static int ni_rtsi_insn_config(comedi_device *dev,comedi_subdevice *s,
4489         comedi_insn *insn,lsampl_t *data)
4490 {
4491         unsigned int chan = CR_CHAN(insn->chanspec);
4492         switch(data[0]){
4493         case INSN_CONFIG_DIO_OUTPUT:
4494                 if(chan < num_configurable_rtsi_channels(dev))
4495                 {
4496                         devpriv->rtsi_trig_direction_reg |= RTSI_Output_Bit(chan, (boardtype.reg_type & ni_reg_m_series_mask) != 0);
4497                 }else if(chan == old_RTSI_clock_channel)
4498                 {
4499                         devpriv->rtsi_trig_direction_reg |= Drive_RTSI_Clock_Bit;
4500                 }
4501                 devpriv->stc_writew(dev, devpriv->rtsi_trig_direction_reg, RTSI_Trig_Direction_Register);
4502                 break;
4503         case INSN_CONFIG_DIO_INPUT:
4504                 if(chan < num_configurable_rtsi_channels(dev))
4505                 {
4506                         devpriv->rtsi_trig_direction_reg &= ~RTSI_Output_Bit(chan, (boardtype.reg_type & ni_reg_m_series_mask) != 0);
4507                 }else if(chan == old_RTSI_clock_channel)
4508                 {
4509                         devpriv->rtsi_trig_direction_reg &= ~Drive_RTSI_Clock_Bit;
4510                 }
4511                 devpriv->stc_writew(dev, devpriv->rtsi_trig_direction_reg, RTSI_Trig_Direction_Register);
4512                 break;
4513         case INSN_CONFIG_DIO_QUERY:
4514                 if(chan < num_configurable_rtsi_channels(dev))
4515                 {
4516                         data[1] = (devpriv->rtsi_trig_direction_reg & RTSI_Output_Bit(chan, (boardtype.reg_type & ni_reg_m_series_mask) != 0)) ?
4517                                 INSN_CONFIG_DIO_OUTPUT : INSN_CONFIG_DIO_INPUT;
4518                 }else if(chan == old_RTSI_clock_channel)
4519                 {
4520                         data[1] = (devpriv->rtsi_trig_direction_reg & Drive_RTSI_Clock_Bit) ? INSN_CONFIG_DIO_OUTPUT : INSN_CONFIG_DIO_INPUT;
4521                 }
4522                 return 2;
4523                 break;
4524         case INSN_CONFIG_SET_CLOCK_SRC:
4525                 return ni_set_master_clock(dev, data[1], data[2]);
4526                 break;
4527         case INSN_CONFIG_GET_CLOCK_SRC:
4528                 data[1] = devpriv->clock_source;
4529                 data[2] = devpriv->clock_ns;
4530                 return 3;
4531                 break;
4532         case INSN_CONFIG_SET_ROUTING:
4533                 return ni_set_rtsi_routing(dev, chan, data[1]);
4534                 break;
4535         case INSN_CONFIG_GET_ROUTING:
4536                 data[1] = ni_get_rtsi_routing(dev, chan);
4537                 return 2;
4538                 break;
4539         default:
4540                 return -EINVAL;
4541                 break;
4542         }
4543         return 1;
4544 }
4545
4546 static int cs5529_wait_for_idle(comedi_device *dev)
4547 {
4548         unsigned short status;
4549         const int timeout = HZ;
4550         int i;
4551
4552         for(i = 0; i < timeout; i++)
4553         {
4554                 status = ni_ao_win_inw(dev, CAL_ADC_Status_67xx);
4555                 if((status & CSS_ADC_BUSY) == 0)
4556                 {
4557                         break;
4558                 }
4559                 set_current_state(TASK_INTERRUPTIBLE);
4560                 if(schedule_timeout(1))
4561                 {
4562                         return -EIO;
4563                 }
4564         }
4565 //printk("looped %i times waiting for idle\n", i);
4566         if(i == timeout)
4567         {
4568                 rt_printk("%s: %s: timeout\n", __FILE__, __FUNCTION__);
4569                 return -ETIME;
4570         }
4571         return 0;
4572 }
4573
4574 static void cs5529_command(comedi_device *dev, unsigned short value)
4575 {
4576         static const int timeout = 100;
4577         int i;
4578
4579         ni_ao_win_outw(dev, value, CAL_ADC_Command_67xx);
4580         /* give time for command to start being serially clocked into cs5529.
4581          * this insures that the CSS_ADC_BUSY bit will get properly
4582          * set before we exit this function.
4583         */
4584         for(i = 0; i < timeout; i++)
4585         {
4586                 if((ni_ao_win_inw(dev, CAL_ADC_Status_67xx) & CSS_ADC_BUSY))
4587                         break;
4588                 comedi_udelay(1);
4589         }
4590 //printk("looped %i times writing command to cs5529\n", i);
4591         if(i == timeout)
4592         {
4593                 comedi_error(dev, "possible problem - never saw adc go busy?");
4594         }
4595 }
4596
4597 /* write to cs5529 register */
4598 static void cs5529_config_write(comedi_device *dev, unsigned int value, unsigned int reg_select_bits)
4599 {
4600         ni_ao_win_outw(dev, ((value >> 16) & 0xff), CAL_ADC_Config_Data_High_Word_67xx);
4601         ni_ao_win_outw(dev, (value & 0xffff), CAL_ADC_Config_Data_Low_Word_67xx);
4602         reg_select_bits &= CSCMD_REGISTER_SELECT_MASK;
4603         cs5529_command(dev, CSCMD_COMMAND | reg_select_bits);
4604         if(cs5529_wait_for_idle(dev))
4605                 comedi_error(dev, "time or signal in cs5529_config_write()");
4606 }
4607
4608 /* read from cs5529 register */
4609 static unsigned int cs5529_config_read(comedi_device *dev, unsigned int reg_select_bits)
4610 {
4611         unsigned int value;
4612
4613         reg_select_bits &= CSCMD_REGISTER_SELECT_MASK;
4614         cs5529_command(dev, CSCMD_COMMAND | CSCMD_READ | reg_select_bits);
4615         if(cs5529_wait_for_idle(dev))
4616                 comedi_error(dev, "timeout or signal in cs5529_config_read()");
4617         value = (ni_ao_win_inw(dev, CAL_ADC_Config_Data_High_Word_67xx) << 16) & 0xff0000;
4618         value |= ni_ao_win_inw(dev, CAL_ADC_Config_Data_Low_Word_67xx) & 0xffff;
4619         return value;
4620 }
4621
4622 static int cs5529_do_conversion(comedi_device *dev, unsigned short *data)
4623 {
4624         int retval;
4625         unsigned short status;
4626
4627         cs5529_command(dev, CSCMD_COMMAND | CSCMD_SINGLE_CONVERSION);
4628         retval = cs5529_wait_for_idle(dev);
4629         if(retval)
4630         {
4631                 comedi_error(dev, "timeout or signal in cs5529_do_conversion()");
4632                 return -ETIME;
4633         }
4634         status = ni_ao_win_inw(dev, CAL_ADC_Status_67xx);
4635         if(status & CSS_OSC_DETECT)
4636         {
4637                 rt_printk("ni_mio_common: cs5529 conversion error, status CSS_OSC_DETECT\n");
4638                 return -EIO;
4639         }
4640         if(status & CSS_OVERRANGE)
4641         {
4642                 rt_printk("ni_mio_common: cs5529 conversion error, overrange (ignoring)\n");
4643         }
4644         if(data)
4645         {
4646                 *data = ni_ao_win_inw(dev, CAL_ADC_Data_67xx);
4647                 /* cs5529 returns 16 bit signed data in bipolar mode */
4648                 *data ^= (1 << 15);
4649         }
4650         return 0;
4651 }
4652
4653 static int cs5529_ai_insn_read(comedi_device *dev,comedi_subdevice *s,comedi_insn *insn,lsampl_t *data)
4654 {
4655         int n, retval;
4656         unsigned short sample;
4657         unsigned int channel_select;
4658         const unsigned int INTERNAL_REF = 0x1000;
4659
4660         /* Set calibration adc source.  Docs lie, reference select bits 8 to 11
4661          * do nothing. bit 12 seems to chooses internal reference voltage, bit
4662          * 13 causes the adc input to go overrange (maybe reads external reference?) */
4663         if(insn->chanspec & CR_ALT_SOURCE)
4664                 channel_select = INTERNAL_REF;
4665         else
4666                 channel_select = CR_CHAN(insn->chanspec);
4667         ni_ao_win_outw(dev, channel_select, AO_Calibration_Channel_Select_67xx);
4668
4669         for(n = 0; n < insn->n; n++)
4670         {
4671                 retval = cs5529_do_conversion(dev, &sample);
4672                 if(retval < 0) return retval;
4673                 data[n] = sample;
4674         }
4675         return insn->n;
4676 }
4677
4678 static int init_cs5529(comedi_device *dev)
4679 {
4680         unsigned int config_bits = CSCFG_PORT_MODE | CSCFG_WORD_RATE_2180_CYCLES;
4681
4682 #if 1
4683         /* do self-calibration */
4684         cs5529_config_write(dev, config_bits | CSCFG_SELF_CAL_OFFSET_GAIN, CSCMD_CONFIG_REGISTER);
4685         /* need to force a conversion for calibration to run */
4686         cs5529_do_conversion(dev, NULL);
4687 #else
4688         /* force gain calibration to 1 */
4689         cs5529_config_write(dev, 0x400000, CSCMD_GAIN_REGISTER);
4690         cs5529_config_write(dev, config_bits | CSCFG_SELF_CAL_OFFSET, CSCMD_CONFIG_REGISTER);
4691         if(cs5529_wait_for_idle(dev))
4692                 comedi_error(dev, "timeout or signal in init_cs5529()\n");
4693 #endif
4694         if(0)
4695         {
4696                 rt_printk("config: 0x%x\n", cs5529_config_read(dev, CSCMD_CONFIG_REGISTER));
4697                 rt_printk("gain: 0x%x\n", cs5529_config_read(dev, CSCMD_GAIN_REGISTER));
4698                 rt_printk("offset: 0x%x\n", cs5529_config_read(dev, CSCMD_OFFSET_REGISTER));
4699         }
4700         return 0;
4701 }
4702
4703