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