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