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