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