]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/staging/comedi/drivers/ni_mio_common.c
drivers: Remove explicit invocations of mmiowb()
[linux.git] / drivers / staging / comedi / drivers / ni_mio_common.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
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
10 /*
11  * This file is meant to be included by another file, e.g.,
12  * ni_atmio.c or ni_pcimio.c.
13  *
14  * Interrupt support originally added by Truxton Fulton <trux@truxton.com>
15  *
16  * References (ftp://ftp.natinst.com/support/manuals):
17  *   340747b.pdf  AT-MIO E series Register Level Programmer Manual
18  *   341079b.pdf  PCI E Series RLPM
19  *   340934b.pdf  DAQ-STC reference manual
20  *
21  * 67xx and 611x registers (ftp://ftp.ni.com/support/daq/mhddk/documentation/)
22  *   release_ni611x.pdf
23  *   release_ni67xx.pdf
24  *
25  * Other possibly relevant info:
26  *   320517c.pdf  User manual (obsolete)
27  *   320517f.pdf  User manual (new)
28  *   320889a.pdf  delete
29  *   320906c.pdf  maximum signal ratings
30  *   321066a.pdf  about 16x
31  *   321791a.pdf  discontinuation of at-mio-16e-10 rev. c
32  *   321808a.pdf  about at-mio-16e-10 rev P
33  *   321837a.pdf  discontinuation of at-mio-16de-10 rev d
34  *   321838a.pdf  about at-mio-16de-10 rev N
35  *
36  * ISSUES:
37  *   - the interrupt routine needs to be cleaned up
38  *
39  * 2006-02-07: S-Series PCI-6143: Support has been added but is not
40  * fully tested as yet. Terry Barnaby, BEAM Ltd.
41  */
42
43 #include <linux/interrupt.h>
44 #include <linux/sched.h>
45 #include <linux/delay.h>
46 #include "8255.h"
47 #include "mite.h"
48
49 /* A timeout count */
50 #define NI_TIMEOUT 1000
51
52 /* Note: this table must match the ai_gain_* definitions */
53 static const short ni_gainlkup[][16] = {
54         [ai_gain_16] = {0, 1, 2, 3, 4, 5, 6, 7,
55                         0x100, 0x101, 0x102, 0x103, 0x104, 0x105, 0x106, 0x107},
56         [ai_gain_8] = {1, 2, 4, 7, 0x101, 0x102, 0x104, 0x107},
57         [ai_gain_14] = {1, 2, 3, 4, 5, 6, 7,
58                         0x101, 0x102, 0x103, 0x104, 0x105, 0x106, 0x107},
59         [ai_gain_4] = {0, 1, 4, 7},
60         [ai_gain_611x] = {0x00a, 0x00b, 0x001, 0x002,
61                           0x003, 0x004, 0x005, 0x006},
62         [ai_gain_622x] = {0, 1, 4, 5},
63         [ai_gain_628x] = {1, 2, 3, 4, 5, 6, 7},
64         [ai_gain_6143] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
65 };
66
67 static const struct comedi_lrange range_ni_E_ai = {
68         16, {
69                 BIP_RANGE(10),
70                 BIP_RANGE(5),
71                 BIP_RANGE(2.5),
72                 BIP_RANGE(1),
73                 BIP_RANGE(0.5),
74                 BIP_RANGE(0.25),
75                 BIP_RANGE(0.1),
76                 BIP_RANGE(0.05),
77                 UNI_RANGE(20),
78                 UNI_RANGE(10),
79                 UNI_RANGE(5),
80                 UNI_RANGE(2),
81                 UNI_RANGE(1),
82                 UNI_RANGE(0.5),
83                 UNI_RANGE(0.2),
84                 UNI_RANGE(0.1)
85         }
86 };
87
88 static const struct comedi_lrange range_ni_E_ai_limited = {
89         8, {
90                 BIP_RANGE(10),
91                 BIP_RANGE(5),
92                 BIP_RANGE(1),
93                 BIP_RANGE(0.1),
94                 UNI_RANGE(10),
95                 UNI_RANGE(5),
96                 UNI_RANGE(1),
97                 UNI_RANGE(0.1)
98         }
99 };
100
101 static const struct comedi_lrange range_ni_E_ai_limited14 = {
102         14, {
103                 BIP_RANGE(10),
104                 BIP_RANGE(5),
105                 BIP_RANGE(2),
106                 BIP_RANGE(1),
107                 BIP_RANGE(0.5),
108                 BIP_RANGE(0.2),
109                 BIP_RANGE(0.1),
110                 UNI_RANGE(10),
111                 UNI_RANGE(5),
112                 UNI_RANGE(2),
113                 UNI_RANGE(1),
114                 UNI_RANGE(0.5),
115                 UNI_RANGE(0.2),
116                 UNI_RANGE(0.1)
117         }
118 };
119
120 static const struct comedi_lrange range_ni_E_ai_bipolar4 = {
121         4, {
122                 BIP_RANGE(10),
123                 BIP_RANGE(5),
124                 BIP_RANGE(0.5),
125                 BIP_RANGE(0.05)
126         }
127 };
128
129 static const struct comedi_lrange range_ni_E_ai_611x = {
130         8, {
131                 BIP_RANGE(50),
132                 BIP_RANGE(20),
133                 BIP_RANGE(10),
134                 BIP_RANGE(5),
135                 BIP_RANGE(2),
136                 BIP_RANGE(1),
137                 BIP_RANGE(0.5),
138                 BIP_RANGE(0.2)
139         }
140 };
141
142 static const struct comedi_lrange range_ni_M_ai_622x = {
143         4, {
144                 BIP_RANGE(10),
145                 BIP_RANGE(5),
146                 BIP_RANGE(1),
147                 BIP_RANGE(0.2)
148         }
149 };
150
151 static const struct comedi_lrange range_ni_M_ai_628x = {
152         7, {
153                 BIP_RANGE(10),
154                 BIP_RANGE(5),
155                 BIP_RANGE(2),
156                 BIP_RANGE(1),
157                 BIP_RANGE(0.5),
158                 BIP_RANGE(0.2),
159                 BIP_RANGE(0.1)
160         }
161 };
162
163 static const struct comedi_lrange range_ni_E_ao_ext = {
164         4, {
165                 BIP_RANGE(10),
166                 UNI_RANGE(10),
167                 RANGE_ext(-1, 1),
168                 RANGE_ext(0, 1)
169         }
170 };
171
172 static const struct comedi_lrange *const ni_range_lkup[] = {
173         [ai_gain_16] = &range_ni_E_ai,
174         [ai_gain_8] = &range_ni_E_ai_limited,
175         [ai_gain_14] = &range_ni_E_ai_limited14,
176         [ai_gain_4] = &range_ni_E_ai_bipolar4,
177         [ai_gain_611x] = &range_ni_E_ai_611x,
178         [ai_gain_622x] = &range_ni_M_ai_622x,
179         [ai_gain_628x] = &range_ni_M_ai_628x,
180         [ai_gain_6143] = &range_bipolar5
181 };
182
183 enum aimodes {
184         AIMODE_NONE = 0,
185         AIMODE_HALF_FULL = 1,
186         AIMODE_SCAN = 2,
187         AIMODE_SAMPLE = 3,
188 };
189
190 enum ni_common_subdevices {
191         NI_AI_SUBDEV,
192         NI_AO_SUBDEV,
193         NI_DIO_SUBDEV,
194         NI_8255_DIO_SUBDEV,
195         NI_UNUSED_SUBDEV,
196         NI_CALIBRATION_SUBDEV,
197         NI_EEPROM_SUBDEV,
198         NI_PFI_DIO_SUBDEV,
199         NI_CS5529_CALIBRATION_SUBDEV,
200         NI_SERIAL_SUBDEV,
201         NI_RTSI_SUBDEV,
202         NI_GPCT0_SUBDEV,
203         NI_GPCT1_SUBDEV,
204         NI_FREQ_OUT_SUBDEV,
205         NI_NUM_SUBDEVICES
206 };
207
208 #define NI_GPCT_SUBDEV(x)       (NI_GPCT0_SUBDEV + (x))
209
210 enum timebase_nanoseconds {
211         TIMEBASE_1_NS = 50,
212         TIMEBASE_2_NS = 10000
213 };
214
215 #define SERIAL_DISABLED         0
216 #define SERIAL_600NS            600
217 #define SERIAL_1_2US            1200
218 #define SERIAL_10US                     10000
219
220 static const int num_adc_stages_611x = 3;
221
222 static void ni_writel(struct comedi_device *dev, unsigned int data, int reg)
223 {
224         if (dev->mmio)
225                 writel(data, dev->mmio + reg);
226         else
227                 outl(data, dev->iobase + reg);
228 }
229
230 static void ni_writew(struct comedi_device *dev, unsigned int data, int reg)
231 {
232         if (dev->mmio)
233                 writew(data, dev->mmio + reg);
234         else
235                 outw(data, dev->iobase + reg);
236 }
237
238 static void ni_writeb(struct comedi_device *dev, unsigned int data, int reg)
239 {
240         if (dev->mmio)
241                 writeb(data, dev->mmio + reg);
242         else
243                 outb(data, dev->iobase + reg);
244 }
245
246 static unsigned int ni_readl(struct comedi_device *dev, int reg)
247 {
248         if (dev->mmio)
249                 return readl(dev->mmio + reg);
250
251         return inl(dev->iobase + reg);
252 }
253
254 static unsigned int ni_readw(struct comedi_device *dev, int reg)
255 {
256         if (dev->mmio)
257                 return readw(dev->mmio + reg);
258
259         return inw(dev->iobase + reg);
260 }
261
262 static unsigned int ni_readb(struct comedi_device *dev, int reg)
263 {
264         if (dev->mmio)
265                 return readb(dev->mmio + reg);
266
267         return inb(dev->iobase + reg);
268 }
269
270 /*
271  * We automatically take advantage of STC registers that can be
272  * read/written directly in the I/O space of the board.
273  *
274  * The AT-MIO and DAQCard devices map the low 8 STC registers to
275  * iobase+reg*2.
276  *
277  * Most PCIMIO devices also map the low 8 STC registers but the
278  * 611x devices map the read registers to iobase+(addr-1)*2.
279  * For now non-windowed STC access is disabled if a PCIMIO device
280  * is detected (devpriv->mite has been initialized).
281  *
282  * The M series devices do not used windowed registers for the
283  * STC registers. The functions below handle the mapping of the
284  * windowed STC registers to the m series register offsets.
285  */
286
287 struct mio_regmap {
288         unsigned int mio_reg;
289         int size;
290 };
291
292 static const struct mio_regmap m_series_stc_write_regmap[] = {
293         [NISTC_INTA_ACK_REG]            = { 0x104, 2 },
294         [NISTC_INTB_ACK_REG]            = { 0x106, 2 },
295         [NISTC_AI_CMD2_REG]             = { 0x108, 2 },
296         [NISTC_AO_CMD2_REG]             = { 0x10a, 2 },
297         [NISTC_G0_CMD_REG]              = { 0x10c, 2 },
298         [NISTC_G1_CMD_REG]              = { 0x10e, 2 },
299         [NISTC_AI_CMD1_REG]             = { 0x110, 2 },
300         [NISTC_AO_CMD1_REG]             = { 0x112, 2 },
301         /*
302          * NISTC_DIO_OUT_REG maps to:
303          * { NI_M_DIO_REG, 4 } and { NI_M_SCXI_SER_DO_REG, 1 }
304          */
305         [NISTC_DIO_OUT_REG]             = { 0, 0 }, /* DOES NOT MAP CLEANLY */
306         [NISTC_DIO_CTRL_REG]            = { 0, 0 }, /* DOES NOT MAP CLEANLY */
307         [NISTC_AI_MODE1_REG]            = { 0x118, 2 },
308         [NISTC_AI_MODE2_REG]            = { 0x11a, 2 },
309         [NISTC_AI_SI_LOADA_REG]         = { 0x11c, 4 },
310         [NISTC_AI_SI_LOADB_REG]         = { 0x120, 4 },
311         [NISTC_AI_SC_LOADA_REG]         = { 0x124, 4 },
312         [NISTC_AI_SC_LOADB_REG]         = { 0x128, 4 },
313         [NISTC_AI_SI2_LOADA_REG]        = { 0x12c, 4 },
314         [NISTC_AI_SI2_LOADB_REG]        = { 0x130, 4 },
315         [NISTC_G0_MODE_REG]             = { 0x134, 2 },
316         [NISTC_G1_MODE_REG]             = { 0x136, 2 },
317         [NISTC_G0_LOADA_REG]            = { 0x138, 4 },
318         [NISTC_G0_LOADB_REG]            = { 0x13c, 4 },
319         [NISTC_G1_LOADA_REG]            = { 0x140, 4 },
320         [NISTC_G1_LOADB_REG]            = { 0x144, 4 },
321         [NISTC_G0_INPUT_SEL_REG]        = { 0x148, 2 },
322         [NISTC_G1_INPUT_SEL_REG]        = { 0x14a, 2 },
323         [NISTC_AO_MODE1_REG]            = { 0x14c, 2 },
324         [NISTC_AO_MODE2_REG]            = { 0x14e, 2 },
325         [NISTC_AO_UI_LOADA_REG]         = { 0x150, 4 },
326         [NISTC_AO_UI_LOADB_REG]         = { 0x154, 4 },
327         [NISTC_AO_BC_LOADA_REG]         = { 0x158, 4 },
328         [NISTC_AO_BC_LOADB_REG]         = { 0x15c, 4 },
329         [NISTC_AO_UC_LOADA_REG]         = { 0x160, 4 },
330         [NISTC_AO_UC_LOADB_REG]         = { 0x164, 4 },
331         [NISTC_CLK_FOUT_REG]            = { 0x170, 2 },
332         [NISTC_IO_BIDIR_PIN_REG]        = { 0x172, 2 },
333         [NISTC_RTSI_TRIG_DIR_REG]       = { 0x174, 2 },
334         [NISTC_INT_CTRL_REG]            = { 0x176, 2 },
335         [NISTC_AI_OUT_CTRL_REG]         = { 0x178, 2 },
336         [NISTC_ATRIG_ETC_REG]           = { 0x17a, 2 },
337         [NISTC_AI_START_STOP_REG]       = { 0x17c, 2 },
338         [NISTC_AI_TRIG_SEL_REG]         = { 0x17e, 2 },
339         [NISTC_AI_DIV_LOADA_REG]        = { 0x180, 4 },
340         [NISTC_AO_START_SEL_REG]        = { 0x184, 2 },
341         [NISTC_AO_TRIG_SEL_REG]         = { 0x186, 2 },
342         [NISTC_G0_AUTOINC_REG]          = { 0x188, 2 },
343         [NISTC_G1_AUTOINC_REG]          = { 0x18a, 2 },
344         [NISTC_AO_MODE3_REG]            = { 0x18c, 2 },
345         [NISTC_RESET_REG]               = { 0x190, 2 },
346         [NISTC_INTA_ENA_REG]            = { 0x192, 2 },
347         [NISTC_INTA2_ENA_REG]           = { 0, 0 }, /* E-Series only */
348         [NISTC_INTB_ENA_REG]            = { 0x196, 2 },
349         [NISTC_INTB2_ENA_REG]           = { 0, 0 }, /* E-Series only */
350         [NISTC_AI_PERSONAL_REG]         = { 0x19a, 2 },
351         [NISTC_AO_PERSONAL_REG]         = { 0x19c, 2 },
352         [NISTC_RTSI_TRIGA_OUT_REG]      = { 0x19e, 2 },
353         [NISTC_RTSI_TRIGB_OUT_REG]      = { 0x1a0, 2 },
354         /* doc for following line: mhddk/nimseries/ChipObjects/tMSeries.h */
355         [NISTC_RTSI_BOARD_REG]          = { 0x1a2, 2 },
356         [NISTC_CFG_MEM_CLR_REG]         = { 0x1a4, 2 },
357         [NISTC_ADC_FIFO_CLR_REG]        = { 0x1a6, 2 },
358         [NISTC_DAC_FIFO_CLR_REG]        = { 0x1a8, 2 },
359         [NISTC_AO_OUT_CTRL_REG]         = { 0x1ac, 2 },
360         [NISTC_AI_MODE3_REG]            = { 0x1ae, 2 },
361 };
362
363 static void m_series_stc_write(struct comedi_device *dev,
364                                unsigned int data, unsigned int reg)
365 {
366         const struct mio_regmap *regmap;
367
368         if (reg < ARRAY_SIZE(m_series_stc_write_regmap)) {
369                 regmap = &m_series_stc_write_regmap[reg];
370         } else {
371                 dev_warn(dev->class_dev, "%s: unhandled register=0x%x\n",
372                          __func__, reg);
373                 return;
374         }
375
376         switch (regmap->size) {
377         case 4:
378                 ni_writel(dev, data, regmap->mio_reg);
379                 break;
380         case 2:
381                 ni_writew(dev, data, regmap->mio_reg);
382                 break;
383         default:
384                 dev_warn(dev->class_dev, "%s: unmapped register=0x%x\n",
385                          __func__, reg);
386                 break;
387         }
388 }
389
390 static const struct mio_regmap m_series_stc_read_regmap[] = {
391         [NISTC_AI_STATUS1_REG]          = { 0x104, 2 },
392         [NISTC_AO_STATUS1_REG]          = { 0x106, 2 },
393         [NISTC_G01_STATUS_REG]          = { 0x108, 2 },
394         [NISTC_AI_STATUS2_REG]          = { 0, 0 }, /* Unknown */
395         [NISTC_AO_STATUS2_REG]          = { 0x10c, 2 },
396         [NISTC_DIO_IN_REG]              = { 0, 0 }, /* Unknown */
397         [NISTC_G0_HW_SAVE_REG]          = { 0x110, 4 },
398         [NISTC_G1_HW_SAVE_REG]          = { 0x114, 4 },
399         [NISTC_G0_SAVE_REG]             = { 0x118, 4 },
400         [NISTC_G1_SAVE_REG]             = { 0x11c, 4 },
401         [NISTC_AO_UI_SAVE_REG]          = { 0x120, 4 },
402         [NISTC_AO_BC_SAVE_REG]          = { 0x124, 4 },
403         [NISTC_AO_UC_SAVE_REG]          = { 0x128, 4 },
404         [NISTC_STATUS1_REG]             = { 0x136, 2 },
405         [NISTC_DIO_SERIAL_IN_REG]       = { 0x009, 1 },
406         [NISTC_STATUS2_REG]             = { 0x13a, 2 },
407         [NISTC_AI_SI_SAVE_REG]          = { 0x180, 4 },
408         [NISTC_AI_SC_SAVE_REG]          = { 0x184, 4 },
409 };
410
411 static unsigned int m_series_stc_read(struct comedi_device *dev,
412                                       unsigned int reg)
413 {
414         const struct mio_regmap *regmap;
415
416         if (reg < ARRAY_SIZE(m_series_stc_read_regmap)) {
417                 regmap = &m_series_stc_read_regmap[reg];
418         } else {
419                 dev_warn(dev->class_dev, "%s: unhandled register=0x%x\n",
420                          __func__, reg);
421                 return 0;
422         }
423
424         switch (regmap->size) {
425         case 4:
426                 return ni_readl(dev, regmap->mio_reg);
427         case 2:
428                 return ni_readw(dev, regmap->mio_reg);
429         case 1:
430                 return ni_readb(dev, regmap->mio_reg);
431         default:
432                 dev_warn(dev->class_dev, "%s: unmapped register=0x%x\n",
433                          __func__, reg);
434                 return 0;
435         }
436 }
437
438 static void ni_stc_writew(struct comedi_device *dev,
439                           unsigned int data, int reg)
440 {
441         struct ni_private *devpriv = dev->private;
442         unsigned long flags;
443
444         if (devpriv->is_m_series) {
445                 m_series_stc_write(dev, data, reg);
446         } else {
447                 spin_lock_irqsave(&devpriv->window_lock, flags);
448                 if (!devpriv->mite && reg < 8) {
449                         ni_writew(dev, data, reg * 2);
450                 } else {
451                         ni_writew(dev, reg, NI_E_STC_WINDOW_ADDR_REG);
452                         ni_writew(dev, data, NI_E_STC_WINDOW_DATA_REG);
453                 }
454                 spin_unlock_irqrestore(&devpriv->window_lock, flags);
455         }
456 }
457
458 static void ni_stc_writel(struct comedi_device *dev,
459                           unsigned int data, int reg)
460 {
461         struct ni_private *devpriv = dev->private;
462
463         if (devpriv->is_m_series) {
464                 m_series_stc_write(dev, data, reg);
465         } else {
466                 ni_stc_writew(dev, data >> 16, reg);
467                 ni_stc_writew(dev, data & 0xffff, reg + 1);
468         }
469 }
470
471 static unsigned int ni_stc_readw(struct comedi_device *dev, int reg)
472 {
473         struct ni_private *devpriv = dev->private;
474         unsigned long flags;
475         unsigned int val;
476
477         if (devpriv->is_m_series) {
478                 val = m_series_stc_read(dev, reg);
479         } else {
480                 spin_lock_irqsave(&devpriv->window_lock, flags);
481                 if (!devpriv->mite && reg < 8) {
482                         val = ni_readw(dev, reg * 2);
483                 } else {
484                         ni_writew(dev, reg, NI_E_STC_WINDOW_ADDR_REG);
485                         val = ni_readw(dev, NI_E_STC_WINDOW_DATA_REG);
486                 }
487                 spin_unlock_irqrestore(&devpriv->window_lock, flags);
488         }
489         return val;
490 }
491
492 static unsigned int ni_stc_readl(struct comedi_device *dev, int reg)
493 {
494         struct ni_private *devpriv = dev->private;
495         unsigned int val;
496
497         if (devpriv->is_m_series) {
498                 val = m_series_stc_read(dev, reg);
499         } else {
500                 val = ni_stc_readw(dev, reg) << 16;
501                 val |= ni_stc_readw(dev, reg + 1);
502         }
503         return val;
504 }
505
506 static inline void ni_set_bitfield(struct comedi_device *dev, int reg,
507                                    unsigned int bit_mask,
508                                    unsigned int bit_values)
509 {
510         struct ni_private *devpriv = dev->private;
511         unsigned long flags;
512
513         spin_lock_irqsave(&devpriv->soft_reg_copy_lock, flags);
514         switch (reg) {
515         case NISTC_INTA_ENA_REG:
516                 devpriv->int_a_enable_reg &= ~bit_mask;
517                 devpriv->int_a_enable_reg |= bit_values & bit_mask;
518                 ni_stc_writew(dev, devpriv->int_a_enable_reg, reg);
519                 break;
520         case NISTC_INTB_ENA_REG:
521                 devpriv->int_b_enable_reg &= ~bit_mask;
522                 devpriv->int_b_enable_reg |= bit_values & bit_mask;
523                 ni_stc_writew(dev, devpriv->int_b_enable_reg, reg);
524                 break;
525         case NISTC_IO_BIDIR_PIN_REG:
526                 devpriv->io_bidirection_pin_reg &= ~bit_mask;
527                 devpriv->io_bidirection_pin_reg |= bit_values & bit_mask;
528                 ni_stc_writew(dev, devpriv->io_bidirection_pin_reg, reg);
529                 break;
530         case NI_E_DMA_AI_AO_SEL_REG:
531                 devpriv->ai_ao_select_reg &= ~bit_mask;
532                 devpriv->ai_ao_select_reg |= bit_values & bit_mask;
533                 ni_writeb(dev, devpriv->ai_ao_select_reg, reg);
534                 break;
535         case NI_E_DMA_G0_G1_SEL_REG:
536                 devpriv->g0_g1_select_reg &= ~bit_mask;
537                 devpriv->g0_g1_select_reg |= bit_values & bit_mask;
538                 ni_writeb(dev, devpriv->g0_g1_select_reg, reg);
539                 break;
540         case NI_M_CDIO_DMA_SEL_REG:
541                 devpriv->cdio_dma_select_reg &= ~bit_mask;
542                 devpriv->cdio_dma_select_reg |= bit_values & bit_mask;
543                 ni_writeb(dev, devpriv->cdio_dma_select_reg, reg);
544                 break;
545         default:
546                 dev_err(dev->class_dev, "called with invalid register %d\n",
547                         reg);
548                 break;
549         }
550         spin_unlock_irqrestore(&devpriv->soft_reg_copy_lock, flags);
551 }
552
553 #ifdef PCIDMA
554
555 /* selects the MITE channel to use for DMA */
556 #define NI_STC_DMA_CHAN_SEL(x)  (((x) < 4) ? BIT(x) :   \
557                                  ((x) == 4) ? 0x3 :     \
558                                  ((x) == 5) ? 0x5 : 0x0)
559
560 /* DMA channel setup */
561 static int ni_request_ai_mite_channel(struct comedi_device *dev)
562 {
563         struct ni_private *devpriv = dev->private;
564         struct mite_channel *mite_chan;
565         unsigned long flags;
566         unsigned int bits;
567
568         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
569         mite_chan = mite_request_channel(devpriv->mite, devpriv->ai_mite_ring);
570         if (!mite_chan) {
571                 spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
572                 dev_err(dev->class_dev,
573                         "failed to reserve mite dma channel for analog input\n");
574                 return -EBUSY;
575         }
576         mite_chan->dir = COMEDI_INPUT;
577         devpriv->ai_mite_chan = mite_chan;
578
579         bits = NI_STC_DMA_CHAN_SEL(mite_chan->channel);
580         ni_set_bitfield(dev, NI_E_DMA_AI_AO_SEL_REG,
581                         NI_E_DMA_AI_SEL_MASK, NI_E_DMA_AI_SEL(bits));
582
583         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
584         return 0;
585 }
586
587 static int ni_request_ao_mite_channel(struct comedi_device *dev)
588 {
589         struct ni_private *devpriv = dev->private;
590         struct mite_channel *mite_chan;
591         unsigned long flags;
592         unsigned int bits;
593
594         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
595         mite_chan = mite_request_channel(devpriv->mite, devpriv->ao_mite_ring);
596         if (!mite_chan) {
597                 spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
598                 dev_err(dev->class_dev,
599                         "failed to reserve mite dma channel for analog outut\n");
600                 return -EBUSY;
601         }
602         mite_chan->dir = COMEDI_OUTPUT;
603         devpriv->ao_mite_chan = mite_chan;
604
605         bits = NI_STC_DMA_CHAN_SEL(mite_chan->channel);
606         ni_set_bitfield(dev, NI_E_DMA_AI_AO_SEL_REG,
607                         NI_E_DMA_AO_SEL_MASK, NI_E_DMA_AO_SEL(bits));
608
609         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
610         return 0;
611 }
612
613 static int ni_request_gpct_mite_channel(struct comedi_device *dev,
614                                         unsigned int gpct_index,
615                                         enum comedi_io_direction direction)
616 {
617         struct ni_private *devpriv = dev->private;
618         struct ni_gpct *counter = &devpriv->counter_dev->counters[gpct_index];
619         struct mite_channel *mite_chan;
620         unsigned long flags;
621         unsigned int bits;
622
623         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
624         mite_chan = mite_request_channel(devpriv->mite,
625                                          devpriv->gpct_mite_ring[gpct_index]);
626         if (!mite_chan) {
627                 spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
628                 dev_err(dev->class_dev,
629                         "failed to reserve mite dma channel for counter\n");
630                 return -EBUSY;
631         }
632         mite_chan->dir = direction;
633         ni_tio_set_mite_channel(counter, mite_chan);
634
635         bits = NI_STC_DMA_CHAN_SEL(mite_chan->channel);
636         ni_set_bitfield(dev, NI_E_DMA_G0_G1_SEL_REG,
637                         NI_E_DMA_G0_G1_SEL_MASK(gpct_index),
638                         NI_E_DMA_G0_G1_SEL(gpct_index, bits));
639
640         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
641         return 0;
642 }
643
644 static int ni_request_cdo_mite_channel(struct comedi_device *dev)
645 {
646         struct ni_private *devpriv = dev->private;
647         struct mite_channel *mite_chan;
648         unsigned long flags;
649         unsigned int bits;
650
651         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
652         mite_chan = mite_request_channel(devpriv->mite, devpriv->cdo_mite_ring);
653         if (!mite_chan) {
654                 spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
655                 dev_err(dev->class_dev,
656                         "failed to reserve mite dma channel for correlated digital output\n");
657                 return -EBUSY;
658         }
659         mite_chan->dir = COMEDI_OUTPUT;
660         devpriv->cdo_mite_chan = mite_chan;
661
662         /*
663          * XXX just guessing NI_STC_DMA_CHAN_SEL()
664          * returns the right bits, under the assumption the cdio dma
665          * selection works just like ai/ao/gpct.
666          * Definitely works for dma channels 0 and 1.
667          */
668         bits = NI_STC_DMA_CHAN_SEL(mite_chan->channel);
669         ni_set_bitfield(dev, NI_M_CDIO_DMA_SEL_REG,
670                         NI_M_CDIO_DMA_SEL_CDO_MASK,
671                         NI_M_CDIO_DMA_SEL_CDO(bits));
672
673         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
674         return 0;
675 }
676 #endif /*  PCIDMA */
677
678 static void ni_release_ai_mite_channel(struct comedi_device *dev)
679 {
680 #ifdef PCIDMA
681         struct ni_private *devpriv = dev->private;
682         unsigned long flags;
683
684         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
685         if (devpriv->ai_mite_chan) {
686                 ni_set_bitfield(dev, NI_E_DMA_AI_AO_SEL_REG,
687                                 NI_E_DMA_AI_SEL_MASK, 0);
688                 mite_release_channel(devpriv->ai_mite_chan);
689                 devpriv->ai_mite_chan = NULL;
690         }
691         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
692 #endif /*  PCIDMA */
693 }
694
695 static void ni_release_ao_mite_channel(struct comedi_device *dev)
696 {
697 #ifdef PCIDMA
698         struct ni_private *devpriv = dev->private;
699         unsigned long flags;
700
701         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
702         if (devpriv->ao_mite_chan) {
703                 ni_set_bitfield(dev, NI_E_DMA_AI_AO_SEL_REG,
704                                 NI_E_DMA_AO_SEL_MASK, 0);
705                 mite_release_channel(devpriv->ao_mite_chan);
706                 devpriv->ao_mite_chan = NULL;
707         }
708         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
709 #endif /*  PCIDMA */
710 }
711
712 #ifdef PCIDMA
713 static void ni_release_gpct_mite_channel(struct comedi_device *dev,
714                                          unsigned int gpct_index)
715 {
716         struct ni_private *devpriv = dev->private;
717         unsigned long flags;
718
719         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
720         if (devpriv->counter_dev->counters[gpct_index].mite_chan) {
721                 struct mite_channel *mite_chan =
722                     devpriv->counter_dev->counters[gpct_index].mite_chan;
723
724                 ni_set_bitfield(dev, NI_E_DMA_G0_G1_SEL_REG,
725                                 NI_E_DMA_G0_G1_SEL_MASK(gpct_index), 0);
726                 ni_tio_set_mite_channel(&devpriv->
727                                         counter_dev->counters[gpct_index],
728                                         NULL);
729                 mite_release_channel(mite_chan);
730         }
731         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
732 }
733
734 static void ni_release_cdo_mite_channel(struct comedi_device *dev)
735 {
736         struct ni_private *devpriv = dev->private;
737         unsigned long flags;
738
739         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
740         if (devpriv->cdo_mite_chan) {
741                 ni_set_bitfield(dev, NI_M_CDIO_DMA_SEL_REG,
742                                 NI_M_CDIO_DMA_SEL_CDO_MASK, 0);
743                 mite_release_channel(devpriv->cdo_mite_chan);
744                 devpriv->cdo_mite_chan = NULL;
745         }
746         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
747 }
748
749 static void ni_e_series_enable_second_irq(struct comedi_device *dev,
750                                           unsigned int gpct_index, short enable)
751 {
752         struct ni_private *devpriv = dev->private;
753         unsigned int val = 0;
754         int reg;
755
756         if (devpriv->is_m_series || gpct_index > 1)
757                 return;
758
759         /*
760          * e-series boards use the second irq signals to generate
761          * dma requests for their counters
762          */
763         if (gpct_index == 0) {
764                 reg = NISTC_INTA2_ENA_REG;
765                 if (enable)
766                         val = NISTC_INTA_ENA_G0_GATE;
767         } else {
768                 reg = NISTC_INTB2_ENA_REG;
769                 if (enable)
770                         val = NISTC_INTB_ENA_G1_GATE;
771         }
772         ni_stc_writew(dev, val, reg);
773 }
774 #endif /*  PCIDMA */
775
776 static void ni_clear_ai_fifo(struct comedi_device *dev)
777 {
778         struct ni_private *devpriv = dev->private;
779         static const int timeout = 10000;
780         int i;
781
782         if (devpriv->is_6143) {
783                 /*  Flush the 6143 data FIFO */
784                 ni_writel(dev, 0x10, NI6143_AI_FIFO_CTRL_REG);
785                 ni_writel(dev, 0x00, NI6143_AI_FIFO_CTRL_REG);
786                 /*  Wait for complete */
787                 for (i = 0; i < timeout; i++) {
788                         if (!(ni_readl(dev, NI6143_AI_FIFO_STATUS_REG) & 0x10))
789                                 break;
790                         udelay(1);
791                 }
792                 if (i == timeout)
793                         dev_err(dev->class_dev, "FIFO flush timeout\n");
794         } else {
795                 ni_stc_writew(dev, 1, NISTC_ADC_FIFO_CLR_REG);
796                 if (devpriv->is_625x) {
797                         ni_writeb(dev, 0, NI_M_STATIC_AI_CTRL_REG(0));
798                         ni_writeb(dev, 1, NI_M_STATIC_AI_CTRL_REG(0));
799 #if 0
800                         /*
801                          * The NI example code does 3 convert pulses for 625x
802                          * boards, But that appears to be wrong in practice.
803                          */
804                         ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
805                                       NISTC_AI_CMD1_REG);
806                         ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
807                                       NISTC_AI_CMD1_REG);
808                         ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
809                                       NISTC_AI_CMD1_REG);
810 #endif
811                 }
812         }
813 }
814
815 static inline void ni_ao_win_outw(struct comedi_device *dev,
816                                   unsigned int data, int addr)
817 {
818         struct ni_private *devpriv = dev->private;
819         unsigned long flags;
820
821         spin_lock_irqsave(&devpriv->window_lock, flags);
822         ni_writew(dev, addr, NI611X_AO_WINDOW_ADDR_REG);
823         ni_writew(dev, data, NI611X_AO_WINDOW_DATA_REG);
824         spin_unlock_irqrestore(&devpriv->window_lock, flags);
825 }
826
827 static inline void ni_ao_win_outl(struct comedi_device *dev,
828                                   unsigned int data, int addr)
829 {
830         struct ni_private *devpriv = dev->private;
831         unsigned long flags;
832
833         spin_lock_irqsave(&devpriv->window_lock, flags);
834         ni_writew(dev, addr, NI611X_AO_WINDOW_ADDR_REG);
835         ni_writel(dev, data, NI611X_AO_WINDOW_DATA_REG);
836         spin_unlock_irqrestore(&devpriv->window_lock, flags);
837 }
838
839 static inline unsigned short ni_ao_win_inw(struct comedi_device *dev, int addr)
840 {
841         struct ni_private *devpriv = dev->private;
842         unsigned long flags;
843         unsigned short data;
844
845         spin_lock_irqsave(&devpriv->window_lock, flags);
846         ni_writew(dev, addr, NI611X_AO_WINDOW_ADDR_REG);
847         data = ni_readw(dev, NI611X_AO_WINDOW_DATA_REG);
848         spin_unlock_irqrestore(&devpriv->window_lock, flags);
849         return data;
850 }
851
852 /*
853  * ni_set_bits( ) allows different parts of the ni_mio_common driver to
854  * share registers (such as Interrupt_A_Register) without interfering with
855  * each other.
856  *
857  * NOTE: the switch/case statements are optimized out for a constant argument
858  * so this is actually quite fast---  If you must wrap another function around
859  * this make it inline to avoid a large speed penalty.
860  *
861  * value should only be 1 or 0.
862  */
863 static inline void ni_set_bits(struct comedi_device *dev, int reg,
864                                unsigned int bits, unsigned int value)
865 {
866         unsigned int bit_values;
867
868         if (value)
869                 bit_values = bits;
870         else
871                 bit_values = 0;
872         ni_set_bitfield(dev, reg, bits, bit_values);
873 }
874
875 #ifdef PCIDMA
876 static void ni_sync_ai_dma(struct comedi_device *dev)
877 {
878         struct ni_private *devpriv = dev->private;
879         struct comedi_subdevice *s = dev->read_subdev;
880         unsigned long flags;
881
882         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
883         if (devpriv->ai_mite_chan)
884                 mite_sync_dma(devpriv->ai_mite_chan, s);
885         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
886 }
887
888 static int ni_ai_drain_dma(struct comedi_device *dev)
889 {
890         struct ni_private *devpriv = dev->private;
891         int i;
892         static const int timeout = 10000;
893         unsigned long flags;
894         int retval = 0;
895
896         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
897         if (devpriv->ai_mite_chan) {
898                 for (i = 0; i < timeout; i++) {
899                         if ((ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
900                              NISTC_AI_STATUS1_FIFO_E) &&
901                             mite_bytes_in_transit(devpriv->ai_mite_chan) == 0)
902                                 break;
903                         udelay(5);
904                 }
905                 if (i == timeout) {
906                         dev_err(dev->class_dev, "timed out\n");
907                         dev_err(dev->class_dev,
908                                 "mite_bytes_in_transit=%i, AI_Status1_Register=0x%x\n",
909                                 mite_bytes_in_transit(devpriv->ai_mite_chan),
910                                 ni_stc_readw(dev, NISTC_AI_STATUS1_REG));
911                         retval = -1;
912                 }
913         }
914         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
915
916         ni_sync_ai_dma(dev);
917
918         return retval;
919 }
920
921 static int ni_ao_wait_for_dma_load(struct comedi_device *dev)
922 {
923         static const int timeout = 10000;
924         int i;
925
926         for (i = 0; i < timeout; i++) {
927                 unsigned short b_status;
928
929                 b_status = ni_stc_readw(dev, NISTC_AO_STATUS1_REG);
930                 if (b_status & NISTC_AO_STATUS1_FIFO_HF)
931                         break;
932                 /*
933                  * If we poll too often, the pci bus activity seems
934                  * to slow the dma transfer down.
935                  */
936                 usleep_range(10, 100);
937         }
938         if (i == timeout) {
939                 dev_err(dev->class_dev, "timed out waiting for dma load\n");
940                 return -EPIPE;
941         }
942         return 0;
943 }
944 #endif /* PCIDMA */
945
946 #ifndef PCIDMA
947
948 static void ni_ao_fifo_load(struct comedi_device *dev,
949                             struct comedi_subdevice *s, int n)
950 {
951         struct ni_private *devpriv = dev->private;
952         int i;
953         unsigned short d;
954         unsigned int packed_data;
955
956         for (i = 0; i < n; i++) {
957                 comedi_buf_read_samples(s, &d, 1);
958
959                 if (devpriv->is_6xxx) {
960                         packed_data = d & 0xffff;
961                         /* 6711 only has 16 bit wide ao fifo */
962                         if (!devpriv->is_6711) {
963                                 comedi_buf_read_samples(s, &d, 1);
964                                 i++;
965                                 packed_data |= (d << 16) & 0xffff0000;
966                         }
967                         ni_writel(dev, packed_data, NI611X_AO_FIFO_DATA_REG);
968                 } else {
969                         ni_writew(dev, d, NI_E_AO_FIFO_DATA_REG);
970                 }
971         }
972 }
973
974 /*
975  *  There's a small problem if the FIFO gets really low and we
976  *  don't have the data to fill it.  Basically, if after we fill
977  *  the FIFO with all the data available, the FIFO is _still_
978  *  less than half full, we never clear the interrupt.  If the
979  *  IRQ is in edge mode, we never get another interrupt, because
980  *  this one wasn't cleared.  If in level mode, we get flooded
981  *  with interrupts that we can't fulfill, because nothing ever
982  *  gets put into the buffer.
983  *
984  *  This kind of situation is recoverable, but it is easier to
985  *  just pretend we had a FIFO underrun, since there is a good
986  *  chance it will happen anyway.  This is _not_ the case for
987  *  RT code, as RT code might purposely be running close to the
988  *  metal.  Needs to be fixed eventually.
989  */
990 static int ni_ao_fifo_half_empty(struct comedi_device *dev,
991                                  struct comedi_subdevice *s)
992 {
993         const struct ni_board_struct *board = dev->board_ptr;
994         unsigned int nbytes;
995         unsigned int nsamples;
996
997         nbytes = comedi_buf_read_n_available(s);
998         if (nbytes == 0) {
999                 s->async->events |= COMEDI_CB_OVERFLOW;
1000                 return 0;
1001         }
1002
1003         nsamples = comedi_bytes_to_samples(s, nbytes);
1004         if (nsamples > board->ao_fifo_depth / 2)
1005                 nsamples = board->ao_fifo_depth / 2;
1006
1007         ni_ao_fifo_load(dev, s, nsamples);
1008
1009         return 1;
1010 }
1011
1012 static int ni_ao_prep_fifo(struct comedi_device *dev,
1013                            struct comedi_subdevice *s)
1014 {
1015         const struct ni_board_struct *board = dev->board_ptr;
1016         struct ni_private *devpriv = dev->private;
1017         unsigned int nbytes;
1018         unsigned int nsamples;
1019
1020         /* reset fifo */
1021         ni_stc_writew(dev, 1, NISTC_DAC_FIFO_CLR_REG);
1022         if (devpriv->is_6xxx)
1023                 ni_ao_win_outl(dev, 0x6, NI611X_AO_FIFO_OFFSET_LOAD_REG);
1024
1025         /* load some data */
1026         nbytes = comedi_buf_read_n_available(s);
1027         if (nbytes == 0)
1028                 return 0;
1029
1030         nsamples = comedi_bytes_to_samples(s, nbytes);
1031         if (nsamples > board->ao_fifo_depth)
1032                 nsamples = board->ao_fifo_depth;
1033
1034         ni_ao_fifo_load(dev, s, nsamples);
1035
1036         return nsamples;
1037 }
1038
1039 static void ni_ai_fifo_read(struct comedi_device *dev,
1040                             struct comedi_subdevice *s, int n)
1041 {
1042         struct ni_private *devpriv = dev->private;
1043         struct comedi_async *async = s->async;
1044         unsigned int dl;
1045         unsigned short data;
1046         int i;
1047
1048         if (devpriv->is_611x) {
1049                 for (i = 0; i < n / 2; i++) {
1050                         dl = ni_readl(dev, NI611X_AI_FIFO_DATA_REG);
1051                         /* This may get the hi/lo data in the wrong order */
1052                         data = (dl >> 16) & 0xffff;
1053                         comedi_buf_write_samples(s, &data, 1);
1054                         data = dl & 0xffff;
1055                         comedi_buf_write_samples(s, &data, 1);
1056                 }
1057                 /* Check if there's a single sample stuck in the FIFO */
1058                 if (n % 2) {
1059                         dl = ni_readl(dev, NI611X_AI_FIFO_DATA_REG);
1060                         data = dl & 0xffff;
1061                         comedi_buf_write_samples(s, &data, 1);
1062                 }
1063         } else if (devpriv->is_6143) {
1064                 /*
1065                  * This just reads the FIFO assuming the data is present,
1066                  * no checks on the FIFO status are performed.
1067                  */
1068                 for (i = 0; i < n / 2; i++) {
1069                         dl = ni_readl(dev, NI6143_AI_FIFO_DATA_REG);
1070
1071                         data = (dl >> 16) & 0xffff;
1072                         comedi_buf_write_samples(s, &data, 1);
1073                         data = dl & 0xffff;
1074                         comedi_buf_write_samples(s, &data, 1);
1075                 }
1076                 if (n % 2) {
1077                         /* Assume there is a single sample stuck in the FIFO */
1078                         /* Get stranded sample into FIFO */
1079                         ni_writel(dev, 0x01, NI6143_AI_FIFO_CTRL_REG);
1080                         dl = ni_readl(dev, NI6143_AI_FIFO_DATA_REG);
1081                         data = (dl >> 16) & 0xffff;
1082                         comedi_buf_write_samples(s, &data, 1);
1083                 }
1084         } else {
1085                 if (n > ARRAY_SIZE(devpriv->ai_fifo_buffer)) {
1086                         dev_err(dev->class_dev,
1087                                 "bug! ai_fifo_buffer too small\n");
1088                         async->events |= COMEDI_CB_ERROR;
1089                         return;
1090                 }
1091                 for (i = 0; i < n; i++) {
1092                         devpriv->ai_fifo_buffer[i] =
1093                             ni_readw(dev, NI_E_AI_FIFO_DATA_REG);
1094                 }
1095                 comedi_buf_write_samples(s, devpriv->ai_fifo_buffer, n);
1096         }
1097 }
1098
1099 static void ni_handle_fifo_half_full(struct comedi_device *dev)
1100 {
1101         const struct ni_board_struct *board = dev->board_ptr;
1102         struct comedi_subdevice *s = dev->read_subdev;
1103         int n;
1104
1105         n = board->ai_fifo_depth / 2;
1106
1107         ni_ai_fifo_read(dev, s, n);
1108 }
1109 #endif
1110
1111 /* Empties the AI fifo */
1112 static void ni_handle_fifo_dregs(struct comedi_device *dev)
1113 {
1114         struct ni_private *devpriv = dev->private;
1115         struct comedi_subdevice *s = dev->read_subdev;
1116         unsigned int dl;
1117         unsigned short data;
1118         int i;
1119
1120         if (devpriv->is_611x) {
1121                 while ((ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
1122                         NISTC_AI_STATUS1_FIFO_E) == 0) {
1123                         dl = ni_readl(dev, NI611X_AI_FIFO_DATA_REG);
1124
1125                         /* This may get the hi/lo data in the wrong order */
1126                         data = dl >> 16;
1127                         comedi_buf_write_samples(s, &data, 1);
1128                         data = dl & 0xffff;
1129                         comedi_buf_write_samples(s, &data, 1);
1130                 }
1131         } else if (devpriv->is_6143) {
1132                 i = 0;
1133                 while (ni_readl(dev, NI6143_AI_FIFO_STATUS_REG) & 0x04) {
1134                         dl = ni_readl(dev, NI6143_AI_FIFO_DATA_REG);
1135
1136                         /* This may get the hi/lo data in the wrong order */
1137                         data = dl >> 16;
1138                         comedi_buf_write_samples(s, &data, 1);
1139                         data = dl & 0xffff;
1140                         comedi_buf_write_samples(s, &data, 1);
1141                         i += 2;
1142                 }
1143                 /*  Check if stranded sample is present */
1144                 if (ni_readl(dev, NI6143_AI_FIFO_STATUS_REG) & 0x01) {
1145                         /* Get stranded sample into FIFO */
1146                         ni_writel(dev, 0x01, NI6143_AI_FIFO_CTRL_REG);
1147                         dl = ni_readl(dev, NI6143_AI_FIFO_DATA_REG);
1148                         data = (dl >> 16) & 0xffff;
1149                         comedi_buf_write_samples(s, &data, 1);
1150                 }
1151
1152         } else {
1153                 unsigned short fe;      /* fifo empty */
1154
1155                 fe = ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
1156                      NISTC_AI_STATUS1_FIFO_E;
1157                 while (fe == 0) {
1158                         for (i = 0;
1159                              i < ARRAY_SIZE(devpriv->ai_fifo_buffer); i++) {
1160                                 fe = ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
1161                                      NISTC_AI_STATUS1_FIFO_E;
1162                                 if (fe)
1163                                         break;
1164                                 devpriv->ai_fifo_buffer[i] =
1165                                     ni_readw(dev, NI_E_AI_FIFO_DATA_REG);
1166                         }
1167                         comedi_buf_write_samples(s, devpriv->ai_fifo_buffer, i);
1168                 }
1169         }
1170 }
1171
1172 static void get_last_sample_611x(struct comedi_device *dev)
1173 {
1174         struct ni_private *devpriv = dev->private;
1175         struct comedi_subdevice *s = dev->read_subdev;
1176         unsigned short data;
1177         unsigned int dl;
1178
1179         if (!devpriv->is_611x)
1180                 return;
1181
1182         /* Check if there's a single sample stuck in the FIFO */
1183         if (ni_readb(dev, NI_E_STATUS_REG) & 0x80) {
1184                 dl = ni_readl(dev, NI611X_AI_FIFO_DATA_REG);
1185                 data = dl & 0xffff;
1186                 comedi_buf_write_samples(s, &data, 1);
1187         }
1188 }
1189
1190 static void get_last_sample_6143(struct comedi_device *dev)
1191 {
1192         struct ni_private *devpriv = dev->private;
1193         struct comedi_subdevice *s = dev->read_subdev;
1194         unsigned short data;
1195         unsigned int dl;
1196
1197         if (!devpriv->is_6143)
1198                 return;
1199
1200         /* Check if there's a single sample stuck in the FIFO */
1201         if (ni_readl(dev, NI6143_AI_FIFO_STATUS_REG) & 0x01) {
1202                 /* Get stranded sample into FIFO */
1203                 ni_writel(dev, 0x01, NI6143_AI_FIFO_CTRL_REG);
1204                 dl = ni_readl(dev, NI6143_AI_FIFO_DATA_REG);
1205
1206                 /* This may get the hi/lo data in the wrong order */
1207                 data = (dl >> 16) & 0xffff;
1208                 comedi_buf_write_samples(s, &data, 1);
1209         }
1210 }
1211
1212 static void shutdown_ai_command(struct comedi_device *dev)
1213 {
1214         struct comedi_subdevice *s = dev->read_subdev;
1215
1216 #ifdef PCIDMA
1217         ni_ai_drain_dma(dev);
1218 #endif
1219         ni_handle_fifo_dregs(dev);
1220         get_last_sample_611x(dev);
1221         get_last_sample_6143(dev);
1222
1223         s->async->events |= COMEDI_CB_EOA;
1224 }
1225
1226 static void ni_handle_eos(struct comedi_device *dev, struct comedi_subdevice *s)
1227 {
1228         struct ni_private *devpriv = dev->private;
1229
1230         if (devpriv->aimode == AIMODE_SCAN) {
1231 #ifdef PCIDMA
1232                 static const int timeout = 10;
1233                 int i;
1234
1235                 for (i = 0; i < timeout; i++) {
1236                         ni_sync_ai_dma(dev);
1237                         if ((s->async->events & COMEDI_CB_EOS))
1238                                 break;
1239                         udelay(1);
1240                 }
1241 #else
1242                 ni_handle_fifo_dregs(dev);
1243                 s->async->events |= COMEDI_CB_EOS;
1244 #endif
1245         }
1246         /* handle special case of single scan */
1247         if (devpriv->ai_cmd2 & NISTC_AI_CMD2_END_ON_EOS)
1248                 shutdown_ai_command(dev);
1249 }
1250
1251 static void handle_gpct_interrupt(struct comedi_device *dev,
1252                                   unsigned short counter_index)
1253 {
1254 #ifdef PCIDMA
1255         struct ni_private *devpriv = dev->private;
1256         struct comedi_subdevice *s;
1257
1258         s = &dev->subdevices[NI_GPCT_SUBDEV(counter_index)];
1259
1260         ni_tio_handle_interrupt(&devpriv->counter_dev->counters[counter_index],
1261                                 s);
1262         comedi_handle_events(dev, s);
1263 #endif
1264 }
1265
1266 static void ack_a_interrupt(struct comedi_device *dev, unsigned short a_status)
1267 {
1268         unsigned short ack = 0;
1269
1270         if (a_status & NISTC_AI_STATUS1_SC_TC)
1271                 ack |= NISTC_INTA_ACK_AI_SC_TC;
1272         if (a_status & NISTC_AI_STATUS1_START1)
1273                 ack |= NISTC_INTA_ACK_AI_START1;
1274         if (a_status & NISTC_AI_STATUS1_START)
1275                 ack |= NISTC_INTA_ACK_AI_START;
1276         if (a_status & NISTC_AI_STATUS1_STOP)
1277                 ack |= NISTC_INTA_ACK_AI_STOP;
1278         if (a_status & NISTC_AI_STATUS1_OVER)
1279                 ack |= NISTC_INTA_ACK_AI_ERR;
1280         if (ack)
1281                 ni_stc_writew(dev, ack, NISTC_INTA_ACK_REG);
1282 }
1283
1284 static void handle_a_interrupt(struct comedi_device *dev,
1285                                struct comedi_subdevice *s,
1286                                unsigned short status)
1287 {
1288         struct comedi_cmd *cmd = &s->async->cmd;
1289
1290         /* test for all uncommon interrupt events at the same time */
1291         if (status & (NISTC_AI_STATUS1_ERR |
1292                       NISTC_AI_STATUS1_SC_TC | NISTC_AI_STATUS1_START1)) {
1293                 if (status == 0xffff) {
1294                         dev_err(dev->class_dev, "Card removed?\n");
1295                         /*
1296                          * We probably aren't even running a command now,
1297                          * so it's a good idea to be careful.
1298                          */
1299                         if (comedi_is_subdevice_running(s))
1300                                 s->async->events |= COMEDI_CB_ERROR;
1301                         return;
1302                 }
1303                 if (status & NISTC_AI_STATUS1_ERR) {
1304                         dev_err(dev->class_dev, "ai error a_status=%04x\n",
1305                                 status);
1306
1307                         shutdown_ai_command(dev);
1308
1309                         s->async->events |= COMEDI_CB_ERROR;
1310                         if (status & NISTC_AI_STATUS1_OVER)
1311                                 s->async->events |= COMEDI_CB_OVERFLOW;
1312                         return;
1313                 }
1314                 if (status & NISTC_AI_STATUS1_SC_TC) {
1315                         if (cmd->stop_src == TRIG_COUNT)
1316                                 shutdown_ai_command(dev);
1317                 }
1318         }
1319 #ifndef PCIDMA
1320         if (status & NISTC_AI_STATUS1_FIFO_HF) {
1321                 int i;
1322                 static const int timeout = 10;
1323                 /*
1324                  * PCMCIA cards (at least 6036) seem to stop producing
1325                  * interrupts if we fail to get the fifo less than half
1326                  * full, so loop to be sure.
1327                  */
1328                 for (i = 0; i < timeout; ++i) {
1329                         ni_handle_fifo_half_full(dev);
1330                         if ((ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
1331                              NISTC_AI_STATUS1_FIFO_HF) == 0)
1332                                 break;
1333                 }
1334         }
1335 #endif /*  !PCIDMA */
1336
1337         if (status & NISTC_AI_STATUS1_STOP)
1338                 ni_handle_eos(dev, s);
1339 }
1340
1341 static void ack_b_interrupt(struct comedi_device *dev, unsigned short b_status)
1342 {
1343         unsigned short ack = 0;
1344
1345         if (b_status & NISTC_AO_STATUS1_BC_TC)
1346                 ack |= NISTC_INTB_ACK_AO_BC_TC;
1347         if (b_status & NISTC_AO_STATUS1_OVERRUN)
1348                 ack |= NISTC_INTB_ACK_AO_ERR;
1349         if (b_status & NISTC_AO_STATUS1_START)
1350                 ack |= NISTC_INTB_ACK_AO_START;
1351         if (b_status & NISTC_AO_STATUS1_START1)
1352                 ack |= NISTC_INTB_ACK_AO_START1;
1353         if (b_status & NISTC_AO_STATUS1_UC_TC)
1354                 ack |= NISTC_INTB_ACK_AO_UC_TC;
1355         if (b_status & NISTC_AO_STATUS1_UI2_TC)
1356                 ack |= NISTC_INTB_ACK_AO_UI2_TC;
1357         if (b_status & NISTC_AO_STATUS1_UPDATE)
1358                 ack |= NISTC_INTB_ACK_AO_UPDATE;
1359         if (ack)
1360                 ni_stc_writew(dev, ack, NISTC_INTB_ACK_REG);
1361 }
1362
1363 static void handle_b_interrupt(struct comedi_device *dev,
1364                                struct comedi_subdevice *s,
1365                                unsigned short b_status)
1366 {
1367         if (b_status == 0xffff)
1368                 return;
1369         if (b_status & NISTC_AO_STATUS1_OVERRUN) {
1370                 dev_err(dev->class_dev,
1371                         "AO FIFO underrun status=0x%04x status2=0x%04x\n",
1372                         b_status, ni_stc_readw(dev, NISTC_AO_STATUS2_REG));
1373                 s->async->events |= COMEDI_CB_OVERFLOW;
1374         }
1375
1376         if (s->async->cmd.stop_src != TRIG_NONE &&
1377             b_status & NISTC_AO_STATUS1_BC_TC)
1378                 s->async->events |= COMEDI_CB_EOA;
1379
1380 #ifndef PCIDMA
1381         if (b_status & NISTC_AO_STATUS1_FIFO_REQ) {
1382                 int ret;
1383
1384                 ret = ni_ao_fifo_half_empty(dev, s);
1385                 if (!ret) {
1386                         dev_err(dev->class_dev, "AO buffer underrun\n");
1387                         ni_set_bits(dev, NISTC_INTB_ENA_REG,
1388                                     NISTC_INTB_ENA_AO_FIFO |
1389                                     NISTC_INTB_ENA_AO_ERR, 0);
1390                         s->async->events |= COMEDI_CB_OVERFLOW;
1391                 }
1392         }
1393 #endif
1394 }
1395
1396 static void ni_ai_munge(struct comedi_device *dev, struct comedi_subdevice *s,
1397                         void *data, unsigned int num_bytes,
1398                         unsigned int chan_index)
1399 {
1400         struct ni_private *devpriv = dev->private;
1401         struct comedi_async *async = s->async;
1402         struct comedi_cmd *cmd = &async->cmd;
1403         unsigned int nsamples = comedi_bytes_to_samples(s, num_bytes);
1404         unsigned short *array = data;
1405         unsigned int *larray = data;
1406         unsigned int i;
1407 #ifdef PCIDMA
1408         __le16 *barray = data;
1409         __le32 *blarray = data;
1410 #endif
1411
1412         for (i = 0; i < nsamples; i++) {
1413 #ifdef PCIDMA
1414                 if (s->subdev_flags & SDF_LSAMPL)
1415                         larray[i] = le32_to_cpu(blarray[i]);
1416                 else
1417                         array[i] = le16_to_cpu(barray[i]);
1418 #endif
1419                 if (s->subdev_flags & SDF_LSAMPL)
1420                         larray[i] += devpriv->ai_offset[chan_index];
1421                 else
1422                         array[i] += devpriv->ai_offset[chan_index];
1423                 chan_index++;
1424                 chan_index %= cmd->chanlist_len;
1425         }
1426 }
1427
1428 #ifdef PCIDMA
1429
1430 static int ni_ai_setup_MITE_dma(struct comedi_device *dev)
1431 {
1432         struct ni_private *devpriv = dev->private;
1433         struct comedi_subdevice *s = dev->read_subdev;
1434         int retval;
1435         unsigned long flags;
1436
1437         retval = ni_request_ai_mite_channel(dev);
1438         if (retval)
1439                 return retval;
1440
1441         /* write alloc the entire buffer */
1442         comedi_buf_write_alloc(s, s->async->prealloc_bufsz);
1443
1444         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
1445         if (!devpriv->ai_mite_chan) {
1446                 spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
1447                 return -EIO;
1448         }
1449
1450         if (devpriv->is_611x || devpriv->is_6143)
1451                 mite_prep_dma(devpriv->ai_mite_chan, 32, 16);
1452         else if (devpriv->is_628x)
1453                 mite_prep_dma(devpriv->ai_mite_chan, 32, 32);
1454         else
1455                 mite_prep_dma(devpriv->ai_mite_chan, 16, 16);
1456
1457         /*start the MITE */
1458         mite_dma_arm(devpriv->ai_mite_chan);
1459         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
1460
1461         return 0;
1462 }
1463
1464 static int ni_ao_setup_MITE_dma(struct comedi_device *dev)
1465 {
1466         struct ni_private *devpriv = dev->private;
1467         struct comedi_subdevice *s = dev->write_subdev;
1468         int retval;
1469         unsigned long flags;
1470
1471         retval = ni_request_ao_mite_channel(dev);
1472         if (retval)
1473                 return retval;
1474
1475         /* read alloc the entire buffer */
1476         comedi_buf_read_alloc(s, s->async->prealloc_bufsz);
1477
1478         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
1479         if (devpriv->ao_mite_chan) {
1480                 if (devpriv->is_611x || devpriv->is_6713) {
1481                         mite_prep_dma(devpriv->ao_mite_chan, 32, 32);
1482                 } else {
1483                         /*
1484                          * Doing 32 instead of 16 bit wide transfers from
1485                          * memory makes the mite do 32 bit pci transfers,
1486                          * doubling pci bandwidth.
1487                          */
1488                         mite_prep_dma(devpriv->ao_mite_chan, 16, 32);
1489                 }
1490                 mite_dma_arm(devpriv->ao_mite_chan);
1491         } else {
1492                 retval = -EIO;
1493         }
1494         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
1495
1496         return retval;
1497 }
1498
1499 #endif /*  PCIDMA */
1500
1501 /*
1502  * used for both cancel ioctl and board initialization
1503  *
1504  * this is pretty harsh for a cancel, but it works...
1505  */
1506 static int ni_ai_reset(struct comedi_device *dev, struct comedi_subdevice *s)
1507 {
1508         struct ni_private *devpriv = dev->private;
1509         unsigned int ai_personal;
1510         unsigned int ai_out_ctrl;
1511
1512         ni_release_ai_mite_channel(dev);
1513         /* ai configuration */
1514         ni_stc_writew(dev, NISTC_RESET_AI_CFG_START | NISTC_RESET_AI,
1515                       NISTC_RESET_REG);
1516
1517         ni_set_bits(dev, NISTC_INTA_ENA_REG, NISTC_INTA_ENA_AI_MASK, 0);
1518
1519         ni_clear_ai_fifo(dev);
1520
1521         if (!devpriv->is_6143)
1522                 ni_writeb(dev, NI_E_MISC_CMD_EXT_ATRIG, NI_E_MISC_CMD_REG);
1523
1524         ni_stc_writew(dev, NISTC_AI_CMD1_DISARM, NISTC_AI_CMD1_REG);
1525         ni_stc_writew(dev, NISTC_AI_MODE1_START_STOP |
1526                            NISTC_AI_MODE1_RSVD
1527                             /*| NISTC_AI_MODE1_TRIGGER_ONCE */,
1528                       NISTC_AI_MODE1_REG);
1529         ni_stc_writew(dev, 0, NISTC_AI_MODE2_REG);
1530         /* generate FIFO interrupts on non-empty */
1531         ni_stc_writew(dev, NISTC_AI_MODE3_FIFO_MODE_NE,
1532                       NISTC_AI_MODE3_REG);
1533
1534         ai_personal = NISTC_AI_PERSONAL_SHIFTIN_PW |
1535                       NISTC_AI_PERSONAL_SOC_POLARITY |
1536                       NISTC_AI_PERSONAL_LOCALMUX_CLK_PW;
1537         ai_out_ctrl = NISTC_AI_OUT_CTRL_SCAN_IN_PROG_SEL(3) |
1538                       NISTC_AI_OUT_CTRL_EXTMUX_CLK_SEL(0) |
1539                       NISTC_AI_OUT_CTRL_LOCALMUX_CLK_SEL(2) |
1540                       NISTC_AI_OUT_CTRL_SC_TC_SEL(3);
1541         if (devpriv->is_611x) {
1542                 ai_out_ctrl |= NISTC_AI_OUT_CTRL_CONVERT_HIGH;
1543         } else if (devpriv->is_6143) {
1544                 ai_out_ctrl |= NISTC_AI_OUT_CTRL_CONVERT_LOW;
1545         } else {
1546                 ai_personal |= NISTC_AI_PERSONAL_CONVERT_PW;
1547                 if (devpriv->is_622x)
1548                         ai_out_ctrl |= NISTC_AI_OUT_CTRL_CONVERT_HIGH;
1549                 else
1550                         ai_out_ctrl |= NISTC_AI_OUT_CTRL_CONVERT_LOW;
1551         }
1552         ni_stc_writew(dev, ai_personal, NISTC_AI_PERSONAL_REG);
1553         ni_stc_writew(dev, ai_out_ctrl, NISTC_AI_OUT_CTRL_REG);
1554
1555         /* the following registers should not be changed, because there
1556          * are no backup registers in devpriv.  If you want to change
1557          * any of these, add a backup register and other appropriate code:
1558          *      NISTC_AI_MODE1_REG
1559          *      NISTC_AI_MODE3_REG
1560          *      NISTC_AI_PERSONAL_REG
1561          *      NISTC_AI_OUT_CTRL_REG
1562          */
1563
1564         /* clear interrupts */
1565         ni_stc_writew(dev, NISTC_INTA_ACK_AI_ALL, NISTC_INTA_ACK_REG);
1566
1567         ni_stc_writew(dev, NISTC_RESET_AI_CFG_END, NISTC_RESET_REG);
1568
1569         return 0;
1570 }
1571
1572 static int ni_ai_poll(struct comedi_device *dev, struct comedi_subdevice *s)
1573 {
1574         unsigned long flags;
1575         int count;
1576
1577         /*  lock to avoid race with interrupt handler */
1578         spin_lock_irqsave(&dev->spinlock, flags);
1579 #ifndef PCIDMA
1580         ni_handle_fifo_dregs(dev);
1581 #else
1582         ni_sync_ai_dma(dev);
1583 #endif
1584         count = comedi_buf_n_bytes_ready(s);
1585         spin_unlock_irqrestore(&dev->spinlock, flags);
1586
1587         return count;
1588 }
1589
1590 static void ni_prime_channelgain_list(struct comedi_device *dev)
1591 {
1592         int i;
1593
1594         ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE, NISTC_AI_CMD1_REG);
1595         for (i = 0; i < NI_TIMEOUT; ++i) {
1596                 if (!(ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
1597                       NISTC_AI_STATUS1_FIFO_E)) {
1598                         ni_stc_writew(dev, 1, NISTC_ADC_FIFO_CLR_REG);
1599                         return;
1600                 }
1601                 udelay(1);
1602         }
1603         dev_err(dev->class_dev, "timeout loading channel/gain list\n");
1604 }
1605
1606 static void ni_m_series_load_channelgain_list(struct comedi_device *dev,
1607                                               unsigned int n_chan,
1608                                               unsigned int *list)
1609 {
1610         const struct ni_board_struct *board = dev->board_ptr;
1611         struct ni_private *devpriv = dev->private;
1612         unsigned int chan, range, aref;
1613         unsigned int i;
1614         unsigned int dither;
1615         unsigned int range_code;
1616
1617         ni_stc_writew(dev, 1, NISTC_CFG_MEM_CLR_REG);
1618
1619         if ((list[0] & CR_ALT_SOURCE)) {
1620                 unsigned int bypass_bits;
1621
1622                 chan = CR_CHAN(list[0]);
1623                 range = CR_RANGE(list[0]);
1624                 range_code = ni_gainlkup[board->gainlkup][range];
1625                 dither = (list[0] & CR_ALT_FILTER) != 0;
1626                 bypass_bits = NI_M_CFG_BYPASS_FIFO |
1627                               NI_M_CFG_BYPASS_AI_CHAN(chan) |
1628                               NI_M_CFG_BYPASS_AI_GAIN(range_code) |
1629                               devpriv->ai_calib_source;
1630                 if (dither)
1631                         bypass_bits |= NI_M_CFG_BYPASS_AI_DITHER;
1632                 /*  don't use 2's complement encoding */
1633                 bypass_bits |= NI_M_CFG_BYPASS_AI_POLARITY;
1634                 ni_writel(dev, bypass_bits, NI_M_CFG_BYPASS_FIFO_REG);
1635         } else {
1636                 ni_writel(dev, 0, NI_M_CFG_BYPASS_FIFO_REG);
1637         }
1638         for (i = 0; i < n_chan; i++) {
1639                 unsigned int config_bits = 0;
1640
1641                 chan = CR_CHAN(list[i]);
1642                 aref = CR_AREF(list[i]);
1643                 range = CR_RANGE(list[i]);
1644                 dither = (list[i] & CR_ALT_FILTER) != 0;
1645
1646                 range_code = ni_gainlkup[board->gainlkup][range];
1647                 devpriv->ai_offset[i] = 0;
1648                 switch (aref) {
1649                 case AREF_DIFF:
1650                         config_bits |= NI_M_AI_CFG_CHAN_TYPE_DIFF;
1651                         break;
1652                 case AREF_COMMON:
1653                         config_bits |= NI_M_AI_CFG_CHAN_TYPE_COMMON;
1654                         break;
1655                 case AREF_GROUND:
1656                         config_bits |= NI_M_AI_CFG_CHAN_TYPE_GROUND;
1657                         break;
1658                 case AREF_OTHER:
1659                         break;
1660                 }
1661                 config_bits |= NI_M_AI_CFG_CHAN_SEL(chan);
1662                 config_bits |= NI_M_AI_CFG_BANK_SEL(chan);
1663                 config_bits |= NI_M_AI_CFG_GAIN(range_code);
1664                 if (i == n_chan - 1)
1665                         config_bits |= NI_M_AI_CFG_LAST_CHAN;
1666                 if (dither)
1667                         config_bits |= NI_M_AI_CFG_DITHER;
1668                 /*  don't use 2's complement encoding */
1669                 config_bits |= NI_M_AI_CFG_POLARITY;
1670                 ni_writew(dev, config_bits, NI_M_AI_CFG_FIFO_DATA_REG);
1671         }
1672         ni_prime_channelgain_list(dev);
1673 }
1674
1675 /*
1676  * Notes on the 6110 and 6111:
1677  * These boards a slightly different than the rest of the series, since
1678  * they have multiple A/D converters.
1679  * From the driver side, the configuration memory is a
1680  * little different.
1681  * Configuration Memory Low:
1682  *   bits 15-9: same
1683  *   bit 8: unipolar/bipolar (should be 0 for bipolar)
1684  *   bits 0-3: gain.  This is 4 bits instead of 3 for the other boards
1685  *       1001 gain=0.1 (+/- 50)
1686  *       1010 0.2
1687  *       1011 0.1
1688  *       0001 1
1689  *       0010 2
1690  *       0011 5
1691  *       0100 10
1692  *       0101 20
1693  *       0110 50
1694  * Configuration Memory High:
1695  *   bits 12-14: Channel Type
1696  *       001 for differential
1697  *       000 for calibration
1698  *   bit 11: coupling  (this is not currently handled)
1699  *       1 AC coupling
1700  *       0 DC coupling
1701  *   bits 0-2: channel
1702  *       valid channels are 0-3
1703  */
1704 static void ni_load_channelgain_list(struct comedi_device *dev,
1705                                      struct comedi_subdevice *s,
1706                                      unsigned int n_chan, unsigned int *list)
1707 {
1708         const struct ni_board_struct *board = dev->board_ptr;
1709         struct ni_private *devpriv = dev->private;
1710         unsigned int offset = (s->maxdata + 1) >> 1;
1711         unsigned int chan, range, aref;
1712         unsigned int i;
1713         unsigned int hi, lo;
1714         unsigned int dither;
1715
1716         if (devpriv->is_m_series) {
1717                 ni_m_series_load_channelgain_list(dev, n_chan, list);
1718                 return;
1719         }
1720         if (n_chan == 1 && !devpriv->is_611x && !devpriv->is_6143) {
1721                 if (devpriv->changain_state &&
1722                     devpriv->changain_spec == list[0]) {
1723                         /*  ready to go. */
1724                         return;
1725                 }
1726                 devpriv->changain_state = 1;
1727                 devpriv->changain_spec = list[0];
1728         } else {
1729                 devpriv->changain_state = 0;
1730         }
1731
1732         ni_stc_writew(dev, 1, NISTC_CFG_MEM_CLR_REG);
1733
1734         /*  Set up Calibration mode if required */
1735         if (devpriv->is_6143) {
1736                 if ((list[0] & CR_ALT_SOURCE) &&
1737                     !devpriv->ai_calib_source_enabled) {
1738                         /*  Strobe Relay enable bit */
1739                         ni_writew(dev, devpriv->ai_calib_source |
1740                                        NI6143_CALIB_CHAN_RELAY_ON,
1741                                   NI6143_CALIB_CHAN_REG);
1742                         ni_writew(dev, devpriv->ai_calib_source,
1743                                   NI6143_CALIB_CHAN_REG);
1744                         devpriv->ai_calib_source_enabled = 1;
1745                         /* Allow relays to change */
1746                         msleep_interruptible(100);
1747                 } else if (!(list[0] & CR_ALT_SOURCE) &&
1748                            devpriv->ai_calib_source_enabled) {
1749                         /*  Strobe Relay disable bit */
1750                         ni_writew(dev, devpriv->ai_calib_source |
1751                                        NI6143_CALIB_CHAN_RELAY_OFF,
1752                                   NI6143_CALIB_CHAN_REG);
1753                         ni_writew(dev, devpriv->ai_calib_source,
1754                                   NI6143_CALIB_CHAN_REG);
1755                         devpriv->ai_calib_source_enabled = 0;
1756                         /* Allow relays to change */
1757                         msleep_interruptible(100);
1758                 }
1759         }
1760
1761         for (i = 0; i < n_chan; i++) {
1762                 if (!devpriv->is_6143 && (list[i] & CR_ALT_SOURCE))
1763                         chan = devpriv->ai_calib_source;
1764                 else
1765                         chan = CR_CHAN(list[i]);
1766                 aref = CR_AREF(list[i]);
1767                 range = CR_RANGE(list[i]);
1768                 dither = (list[i] & CR_ALT_FILTER) != 0;
1769
1770                 /* fix the external/internal range differences */
1771                 range = ni_gainlkup[board->gainlkup][range];
1772                 if (devpriv->is_611x)
1773                         devpriv->ai_offset[i] = offset;
1774                 else
1775                         devpriv->ai_offset[i] = (range & 0x100) ? 0 : offset;
1776
1777                 hi = 0;
1778                 if ((list[i] & CR_ALT_SOURCE)) {
1779                         if (devpriv->is_611x)
1780                                 ni_writew(dev, CR_CHAN(list[i]) & 0x0003,
1781                                           NI611X_CALIB_CHAN_SEL_REG);
1782                 } else {
1783                         if (devpriv->is_611x)
1784                                 aref = AREF_DIFF;
1785                         else if (devpriv->is_6143)
1786                                 aref = AREF_OTHER;
1787                         switch (aref) {
1788                         case AREF_DIFF:
1789                                 hi |= NI_E_AI_CFG_HI_TYPE_DIFF;
1790                                 break;
1791                         case AREF_COMMON:
1792                                 hi |= NI_E_AI_CFG_HI_TYPE_COMMON;
1793                                 break;
1794                         case AREF_GROUND:
1795                                 hi |= NI_E_AI_CFG_HI_TYPE_GROUND;
1796                                 break;
1797                         case AREF_OTHER:
1798                                 break;
1799                         }
1800                 }
1801                 hi |= NI_E_AI_CFG_HI_CHAN(chan);
1802
1803                 ni_writew(dev, hi, NI_E_AI_CFG_HI_REG);
1804
1805                 if (!devpriv->is_6143) {
1806                         lo = NI_E_AI_CFG_LO_GAIN(range);
1807
1808                         if (i == n_chan - 1)
1809                                 lo |= NI_E_AI_CFG_LO_LAST_CHAN;
1810                         if (dither)
1811                                 lo |= NI_E_AI_CFG_LO_DITHER;
1812
1813                         ni_writew(dev, lo, NI_E_AI_CFG_LO_REG);
1814                 }
1815         }
1816
1817         /* prime the channel/gain list */
1818         if (!devpriv->is_611x && !devpriv->is_6143)
1819                 ni_prime_channelgain_list(dev);
1820 }
1821
1822 static int ni_ai_insn_read(struct comedi_device *dev,
1823                            struct comedi_subdevice *s,
1824                            struct comedi_insn *insn,
1825                            unsigned int *data)
1826 {
1827         struct ni_private *devpriv = dev->private;
1828         unsigned int mask = s->maxdata;
1829         int i, n;
1830         unsigned int signbits;
1831         unsigned int d;
1832
1833         ni_load_channelgain_list(dev, s, 1, &insn->chanspec);
1834
1835         ni_clear_ai_fifo(dev);
1836
1837         signbits = devpriv->ai_offset[0];
1838         if (devpriv->is_611x) {
1839                 for (n = 0; n < num_adc_stages_611x; n++) {
1840                         ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
1841                                       NISTC_AI_CMD1_REG);
1842                         udelay(1);
1843                 }
1844                 for (n = 0; n < insn->n; n++) {
1845                         ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
1846                                       NISTC_AI_CMD1_REG);
1847                         /* The 611x has screwy 32-bit FIFOs. */
1848                         d = 0;
1849                         for (i = 0; i < NI_TIMEOUT; i++) {
1850                                 if (ni_readb(dev, NI_E_STATUS_REG) & 0x80) {
1851                                         d = ni_readl(dev,
1852                                                      NI611X_AI_FIFO_DATA_REG);
1853                                         d >>= 16;
1854                                         d &= 0xffff;
1855                                         break;
1856                                 }
1857                                 if (!(ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
1858                                       NISTC_AI_STATUS1_FIFO_E)) {
1859                                         d = ni_readl(dev,
1860                                                      NI611X_AI_FIFO_DATA_REG);
1861                                         d &= 0xffff;
1862                                         break;
1863                                 }
1864                         }
1865                         if (i == NI_TIMEOUT) {
1866                                 dev_err(dev->class_dev, "timeout\n");
1867                                 return -ETIME;
1868                         }
1869                         d += signbits;
1870                         data[n] = d & 0xffff;
1871                 }
1872         } else if (devpriv->is_6143) {
1873                 for (n = 0; n < insn->n; n++) {
1874                         ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
1875                                       NISTC_AI_CMD1_REG);
1876
1877                         /*
1878                          * The 6143 has 32-bit FIFOs. You need to strobe a
1879                          * bit to move a single 16bit stranded sample into
1880                          * the FIFO.
1881                          */
1882                         d = 0;
1883                         for (i = 0; i < NI_TIMEOUT; i++) {
1884                                 if (ni_readl(dev, NI6143_AI_FIFO_STATUS_REG) &
1885                                     0x01) {
1886                                         /* Get stranded sample into FIFO */
1887                                         ni_writel(dev, 0x01,
1888                                                   NI6143_AI_FIFO_CTRL_REG);
1889                                         d = ni_readl(dev,
1890                                                      NI6143_AI_FIFO_DATA_REG);
1891                                         break;
1892                                 }
1893                         }
1894                         if (i == NI_TIMEOUT) {
1895                                 dev_err(dev->class_dev, "timeout\n");
1896                                 return -ETIME;
1897                         }
1898                         data[n] = (((d >> 16) & 0xFFFF) + signbits) & 0xFFFF;
1899                 }
1900         } else {
1901                 for (n = 0; n < insn->n; n++) {
1902                         ni_stc_writew(dev, NISTC_AI_CMD1_CONVERT_PULSE,
1903                                       NISTC_AI_CMD1_REG);
1904                         for (i = 0; i < NI_TIMEOUT; i++) {
1905                                 if (!(ni_stc_readw(dev, NISTC_AI_STATUS1_REG) &
1906                                       NISTC_AI_STATUS1_FIFO_E))
1907                                         break;
1908                         }
1909                         if (i == NI_TIMEOUT) {
1910                                 dev_err(dev->class_dev, "timeout\n");
1911                                 return -ETIME;
1912                         }
1913                         if (devpriv->is_m_series) {
1914                                 d = ni_readl(dev, NI_M_AI_FIFO_DATA_REG);
1915                                 d &= mask;
1916                                 data[n] = d;
1917                         } else {
1918                                 d = ni_readw(dev, NI_E_AI_FIFO_DATA_REG);
1919                                 d += signbits;
1920                                 data[n] = d & 0xffff;
1921                         }
1922                 }
1923         }
1924         return insn->n;
1925 }
1926
1927 static int ni_ns_to_timer(const struct comedi_device *dev,
1928                           unsigned int nanosec, unsigned int flags)
1929 {
1930         struct ni_private *devpriv = dev->private;
1931         int divider;
1932
1933         switch (flags & CMDF_ROUND_MASK) {
1934         case CMDF_ROUND_NEAREST:
1935         default:
1936                 divider = DIV_ROUND_CLOSEST(nanosec, devpriv->clock_ns);
1937                 break;
1938         case CMDF_ROUND_DOWN:
1939                 divider = (nanosec) / devpriv->clock_ns;
1940                 break;
1941         case CMDF_ROUND_UP:
1942                 divider = DIV_ROUND_UP(nanosec, devpriv->clock_ns);
1943                 break;
1944         }
1945         return divider - 1;
1946 }
1947
1948 static unsigned int ni_timer_to_ns(const struct comedi_device *dev, int timer)
1949 {
1950         struct ni_private *devpriv = dev->private;
1951
1952         return devpriv->clock_ns * (timer + 1);
1953 }
1954
1955 static void ni_cmd_set_mite_transfer(struct mite_ring *ring,
1956                                      struct comedi_subdevice *sdev,
1957                                      const struct comedi_cmd *cmd,
1958                                      unsigned int max_count)
1959 {
1960 #ifdef PCIDMA
1961         unsigned int nbytes = max_count;
1962
1963         if (cmd->stop_arg > 0 && cmd->stop_arg < max_count)
1964                 nbytes = cmd->stop_arg;
1965         nbytes *= comedi_bytes_per_scan(sdev);
1966
1967         if (nbytes > sdev->async->prealloc_bufsz) {
1968                 if (cmd->stop_arg > 0)
1969                         dev_err(sdev->device->class_dev,
1970                                 "%s: tried exact data transfer limits greater than buffer size\n",
1971                                 __func__);
1972
1973                 /*
1974                  * we can only transfer up to the size of the buffer.  In this
1975                  * case, the user is expected to continue to write into the
1976                  * comedi buffer (already implemented as a ring buffer).
1977                  */
1978                 nbytes = sdev->async->prealloc_bufsz;
1979         }
1980
1981         mite_init_ring_descriptors(ring, sdev, nbytes);
1982 #else
1983         dev_err(sdev->device->class_dev,
1984                 "%s: exact data transfer limits not implemented yet without DMA\n",
1985                 __func__);
1986 #endif
1987 }
1988
1989 static unsigned int ni_min_ai_scan_period_ns(struct comedi_device *dev,
1990                                              unsigned int num_channels)
1991 {
1992         const struct ni_board_struct *board = dev->board_ptr;
1993         struct ni_private *devpriv = dev->private;
1994
1995         /* simultaneously-sampled inputs */
1996         if (devpriv->is_611x || devpriv->is_6143)
1997                 return board->ai_speed;
1998
1999         /* multiplexed inputs */
2000         return board->ai_speed * num_channels;
2001 }
2002
2003 static int ni_ai_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
2004                          struct comedi_cmd *cmd)
2005 {
2006         const struct ni_board_struct *board = dev->board_ptr;
2007         struct ni_private *devpriv = dev->private;
2008         int err = 0;
2009         unsigned int sources;
2010
2011         /* Step 1 : check if triggers are trivially valid */
2012
2013         err |= comedi_check_trigger_src(&cmd->start_src,
2014                                         TRIG_NOW | TRIG_INT | TRIG_EXT);
2015         err |= comedi_check_trigger_src(&cmd->scan_begin_src,
2016                                         TRIG_TIMER | TRIG_EXT);
2017
2018         sources = TRIG_TIMER | TRIG_EXT;
2019         if (devpriv->is_611x || devpriv->is_6143)
2020                 sources |= TRIG_NOW;
2021         err |= comedi_check_trigger_src(&cmd->convert_src, sources);
2022
2023         err |= comedi_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
2024         err |= comedi_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);
2025
2026         if (err)
2027                 return 1;
2028
2029         /* Step 2a : make sure trigger sources are unique */
2030
2031         err |= comedi_check_trigger_is_unique(cmd->start_src);
2032         err |= comedi_check_trigger_is_unique(cmd->scan_begin_src);
2033         err |= comedi_check_trigger_is_unique(cmd->convert_src);
2034         err |= comedi_check_trigger_is_unique(cmd->stop_src);
2035
2036         /* Step 2b : and mutually compatible */
2037
2038         if (err)
2039                 return 2;
2040
2041         /* Step 3: check if arguments are trivially valid */
2042
2043         switch (cmd->start_src) {
2044         case TRIG_NOW:
2045         case TRIG_INT:
2046                 err |= comedi_check_trigger_arg_is(&cmd->start_arg, 0);
2047                 break;
2048         case TRIG_EXT:
2049                 err |= ni_check_trigger_arg_roffs(CR_CHAN(cmd->start_arg),
2050                                                   NI_AI_StartTrigger,
2051                                                   &devpriv->routing_tables, 1);
2052                 break;
2053         }
2054
2055         if (cmd->scan_begin_src == TRIG_TIMER) {
2056                 err |= comedi_check_trigger_arg_min(&cmd->scan_begin_arg,
2057                         ni_min_ai_scan_period_ns(dev, cmd->chanlist_len));
2058                 err |= comedi_check_trigger_arg_max(&cmd->scan_begin_arg,
2059                                                     devpriv->clock_ns *
2060                                                     0xffffff);
2061         } else if (cmd->scan_begin_src == TRIG_EXT) {
2062                 /* external trigger */
2063                 err |= ni_check_trigger_arg_roffs(CR_CHAN(cmd->scan_begin_arg),
2064                                                   NI_AI_SampleClock,
2065                                                   &devpriv->routing_tables, 1);
2066         } else {                /* TRIG_OTHER */
2067                 err |= comedi_check_trigger_arg_is(&cmd->scan_begin_arg, 0);
2068         }
2069
2070         if (cmd->convert_src == TRIG_TIMER) {
2071                 if (devpriv->is_611x || devpriv->is_6143) {
2072                         err |= comedi_check_trigger_arg_is(&cmd->convert_arg,
2073                                                            0);
2074                 } else {
2075                         err |= comedi_check_trigger_arg_min(&cmd->convert_arg,
2076                                                             board->ai_speed);
2077                         err |= comedi_check_trigger_arg_max(&cmd->convert_arg,
2078                                                             devpriv->clock_ns *
2079                                                             0xffff);
2080                 }
2081         } else if (cmd->convert_src == TRIG_EXT) {
2082                 /* external trigger */
2083                 err |= ni_check_trigger_arg_roffs(CR_CHAN(cmd->convert_arg),
2084                                                   NI_AI_ConvertClock,
2085                                                   &devpriv->routing_tables, 1);
2086         } else if (cmd->convert_src == TRIG_NOW) {
2087                 err |= comedi_check_trigger_arg_is(&cmd->convert_arg, 0);
2088         }
2089
2090         err |= comedi_check_trigger_arg_is(&cmd->scan_end_arg,
2091                                            cmd->chanlist_len);
2092
2093         if (cmd->stop_src == TRIG_COUNT) {
2094                 unsigned int max_count = 0x01000000;
2095
2096                 if (devpriv->is_611x)
2097                         max_count -= num_adc_stages_611x;
2098                 err |= comedi_check_trigger_arg_max(&cmd->stop_arg, max_count);
2099                 err |= comedi_check_trigger_arg_min(&cmd->stop_arg, 1);
2100         } else {
2101                 /* TRIG_NONE */
2102                 err |= comedi_check_trigger_arg_is(&cmd->stop_arg, 0);
2103         }
2104
2105         if (err)
2106                 return 3;
2107
2108         /* step 4: fix up any arguments */
2109
2110         if (cmd->scan_begin_src == TRIG_TIMER) {
2111                 unsigned int tmp = cmd->scan_begin_arg;
2112                 cmd->scan_begin_arg =
2113                     ni_timer_to_ns(dev, ni_ns_to_timer(dev,
2114                                                        cmd->scan_begin_arg,
2115                                                        cmd->flags));
2116                 if (tmp != cmd->scan_begin_arg)
2117                         err++;
2118         }
2119         if (cmd->convert_src == TRIG_TIMER) {
2120                 if (!devpriv->is_611x && !devpriv->is_6143) {
2121                         unsigned int tmp = cmd->convert_arg;
2122                         cmd->convert_arg =
2123                             ni_timer_to_ns(dev, ni_ns_to_timer(dev,
2124                                                                cmd->convert_arg,
2125                                                                cmd->flags));
2126                         if (tmp != cmd->convert_arg)
2127                                 err++;
2128                         if (cmd->scan_begin_src == TRIG_TIMER &&
2129                             cmd->scan_begin_arg <
2130                             cmd->convert_arg * cmd->scan_end_arg) {
2131                                 cmd->scan_begin_arg =
2132                                     cmd->convert_arg * cmd->scan_end_arg;
2133                                 err++;
2134                         }
2135                 }
2136         }
2137
2138         if (err)
2139                 return 4;
2140
2141         return 0;
2142 }
2143
2144 static int ni_ai_inttrig(struct comedi_device *dev,
2145                          struct comedi_subdevice *s,
2146                          unsigned int trig_num)
2147 {
2148         struct ni_private *devpriv = dev->private;
2149         struct comedi_cmd *cmd = &s->async->cmd;
2150
2151         if (trig_num != cmd->start_arg)
2152                 return -EINVAL;
2153
2154         ni_stc_writew(dev, NISTC_AI_CMD2_START1_PULSE | devpriv->ai_cmd2,
2155                       NISTC_AI_CMD2_REG);
2156         s->async->inttrig = NULL;
2157
2158         return 1;
2159 }
2160
2161 static int ni_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
2162 {
2163         struct ni_private *devpriv = dev->private;
2164         const struct comedi_cmd *cmd = &s->async->cmd;
2165         int timer;
2166         int mode1 = 0;          /* mode1 is needed for both stop and convert */
2167         int mode2 = 0;
2168         int start_stop_select = 0;
2169         unsigned int stop_count;
2170         int interrupt_a_enable = 0;
2171         unsigned int ai_trig;
2172
2173         if (dev->irq == 0) {
2174                 dev_err(dev->class_dev, "cannot run command without an irq\n");
2175                 return -EIO;
2176         }
2177         ni_clear_ai_fifo(dev);
2178
2179         ni_load_channelgain_list(dev, s, cmd->chanlist_len, cmd->chanlist);
2180
2181         /* start configuration */
2182         ni_stc_writew(dev, NISTC_RESET_AI_CFG_START, NISTC_RESET_REG);
2183
2184         /*
2185          * Disable analog triggering for now, since it interferes
2186          * with the use of pfi0.
2187          */
2188         devpriv->an_trig_etc_reg &= ~NISTC_ATRIG_ETC_ENA;
2189         ni_stc_writew(dev, devpriv->an_trig_etc_reg, NISTC_ATRIG_ETC_REG);
2190
2191         ai_trig = NISTC_AI_TRIG_START2_SEL(0) | NISTC_AI_TRIG_START1_SYNC;
2192         switch (cmd->start_src) {
2193         case TRIG_INT:
2194         case TRIG_NOW:
2195                 ai_trig |= NISTC_AI_TRIG_START1_EDGE |
2196                            NISTC_AI_TRIG_START1_SEL(0);
2197                 break;
2198         case TRIG_EXT:
2199                 ai_trig |= NISTC_AI_TRIG_START1_SEL(
2200                         ni_get_reg_value_roffs(CR_CHAN(cmd->start_arg),
2201                                                NI_AI_StartTrigger,
2202                                                &devpriv->routing_tables, 1));
2203
2204                 if (cmd->start_arg & CR_INVERT)
2205                         ai_trig |= NISTC_AI_TRIG_START1_POLARITY;
2206                 if (cmd->start_arg & CR_EDGE)
2207                         ai_trig |= NISTC_AI_TRIG_START1_EDGE;
2208                 break;
2209         }
2210         ni_stc_writew(dev, ai_trig, NISTC_AI_TRIG_SEL_REG);
2211
2212         mode2 &= ~NISTC_AI_MODE2_PRE_TRIGGER;
2213         mode2 &= ~NISTC_AI_MODE2_SC_INIT_LOAD_SRC;
2214         mode2 &= ~NISTC_AI_MODE2_SC_RELOAD_MODE;
2215         ni_stc_writew(dev, mode2, NISTC_AI_MODE2_REG);
2216
2217         if (cmd->chanlist_len == 1 || devpriv->is_611x || devpriv->is_6143) {
2218                 /* logic low */
2219                 start_stop_select |= NISTC_AI_STOP_POLARITY |
2220                                      NISTC_AI_STOP_SEL(31) |
2221                                      NISTC_AI_STOP_SYNC;
2222         } else {
2223                 /*  ai configuration memory */
2224                 start_stop_select |= NISTC_AI_STOP_SEL(19);
2225         }
2226         ni_stc_writew(dev, start_stop_select, NISTC_AI_START_STOP_REG);
2227
2228         devpriv->ai_cmd2 = 0;
2229         switch (cmd->stop_src) {
2230         case TRIG_COUNT:
2231                 stop_count = cmd->stop_arg - 1;
2232
2233                 if (devpriv->is_611x) {
2234                         /*  have to take 3 stage adc pipeline into account */
2235                         stop_count += num_adc_stages_611x;
2236                 }
2237                 /* stage number of scans */
2238                 ni_stc_writel(dev, stop_count, NISTC_AI_SC_LOADA_REG);
2239
2240                 mode1 |= NISTC_AI_MODE1_START_STOP |
2241                          NISTC_AI_MODE1_RSVD |
2242                          NISTC_AI_MODE1_TRIGGER_ONCE;
2243                 ni_stc_writew(dev, mode1, NISTC_AI_MODE1_REG);
2244                 /* load SC (Scan Count) */
2245                 ni_stc_writew(dev, NISTC_AI_CMD1_SC_LOAD, NISTC_AI_CMD1_REG);
2246
2247                 if (stop_count == 0) {
2248                         devpriv->ai_cmd2 |= NISTC_AI_CMD2_END_ON_EOS;
2249                         interrupt_a_enable |= NISTC_INTA_ENA_AI_STOP;
2250                         /*
2251                          * This is required to get the last sample for
2252                          * chanlist_len > 1, not sure why.
2253                          */
2254                         if (cmd->chanlist_len > 1)
2255                                 start_stop_select |= NISTC_AI_STOP_POLARITY |
2256                                                      NISTC_AI_STOP_EDGE;
2257                 }
2258                 break;
2259         case TRIG_NONE:
2260                 /* stage number of scans */
2261                 ni_stc_writel(dev, 0, NISTC_AI_SC_LOADA_REG);
2262
2263                 mode1 |= NISTC_AI_MODE1_START_STOP |
2264                          NISTC_AI_MODE1_RSVD |
2265                          NISTC_AI_MODE1_CONTINUOUS;
2266                 ni_stc_writew(dev, mode1, NISTC_AI_MODE1_REG);
2267
2268                 /* load SC (Scan Count) */
2269                 ni_stc_writew(dev, NISTC_AI_CMD1_SC_LOAD, NISTC_AI_CMD1_REG);
2270                 break;
2271         }
2272
2273         switch (cmd->scan_begin_src) {
2274         case TRIG_TIMER:
2275                 /*
2276                  * stop bits for non 611x boards
2277                  * NISTC_AI_MODE3_SI_TRIG_DELAY=0
2278                  * NISTC_AI_MODE2_PRE_TRIGGER=0
2279                  * NISTC_AI_START_STOP_REG:
2280                  * NISTC_AI_START_POLARITY=0    (?) rising edge
2281                  * NISTC_AI_START_EDGE=1        edge triggered
2282                  * NISTC_AI_START_SYNC=1        (?)
2283                  * NISTC_AI_START_SEL=0         SI_TC
2284                  * NISTC_AI_STOP_POLARITY=0     rising edge
2285                  * NISTC_AI_STOP_EDGE=0         level
2286                  * NISTC_AI_STOP_SYNC=1
2287                  * NISTC_AI_STOP_SEL=19         external pin (configuration mem)
2288                  */
2289                 start_stop_select |= NISTC_AI_START_EDGE | NISTC_AI_START_SYNC;
2290                 ni_stc_writew(dev, start_stop_select, NISTC_AI_START_STOP_REG);
2291
2292                 mode2 &= ~NISTC_AI_MODE2_SI_INIT_LOAD_SRC;      /* A */
2293                 mode2 |= NISTC_AI_MODE2_SI_RELOAD_MODE(0);
2294                 /* mode2 |= NISTC_AI_MODE2_SC_RELOAD_MODE; */
2295                 ni_stc_writew(dev, mode2, NISTC_AI_MODE2_REG);
2296
2297                 /* load SI */
2298                 timer = ni_ns_to_timer(dev, cmd->scan_begin_arg,
2299                                        CMDF_ROUND_NEAREST);
2300                 ni_stc_writel(dev, timer, NISTC_AI_SI_LOADA_REG);
2301                 ni_stc_writew(dev, NISTC_AI_CMD1_SI_LOAD, NISTC_AI_CMD1_REG);
2302                 break;
2303         case TRIG_EXT:
2304                 if (cmd->scan_begin_arg & CR_EDGE)
2305                         start_stop_select |= NISTC_AI_START_EDGE;
2306                 if (cmd->scan_begin_arg & CR_INVERT)    /* falling edge */
2307                         start_stop_select |= NISTC_AI_START_POLARITY;
2308                 if (cmd->scan_begin_src != cmd->convert_src ||
2309                     (cmd->scan_begin_arg & ~CR_EDGE) !=
2310                     (cmd->convert_arg & ~CR_EDGE))
2311                         start_stop_select |= NISTC_AI_START_SYNC;
2312                 start_stop_select |= NISTC_AI_START_SEL(
2313                         ni_get_reg_value_roffs(CR_CHAN(cmd->scan_begin_arg),
2314                                                NI_AI_SampleClock,
2315                                                &devpriv->routing_tables, 1));
2316                 ni_stc_writew(dev, start_stop_select, NISTC_AI_START_STOP_REG);
2317                 break;
2318         }
2319
2320         switch (cmd->convert_src) {
2321         case TRIG_TIMER:
2322         case TRIG_NOW:
2323                 if (cmd->convert_arg == 0 || cmd->convert_src == TRIG_NOW)
2324                         timer = 1;
2325                 else
2326                         timer = ni_ns_to_timer(dev, cmd->convert_arg,
2327                                                CMDF_ROUND_NEAREST);
2328                 /* 0,0 does not work */
2329                 ni_stc_writew(dev, 1, NISTC_AI_SI2_LOADA_REG);
2330                 ni_stc_writew(dev, timer, NISTC_AI_SI2_LOADB_REG);
2331
2332                 mode2 &= ~NISTC_AI_MODE2_SI2_INIT_LOAD_SRC;     /* A */
2333                 mode2 |= NISTC_AI_MODE2_SI2_RELOAD_MODE;        /* alternate */
2334                 ni_stc_writew(dev, mode2, NISTC_AI_MODE2_REG);
2335
2336                 ni_stc_writew(dev, NISTC_AI_CMD1_SI2_LOAD, NISTC_AI_CMD1_REG);
2337
2338                 mode2 |= NISTC_AI_MODE2_SI2_INIT_LOAD_SRC;      /* B */
2339                 mode2 |= NISTC_AI_MODE2_SI2_RELOAD_MODE;        /* alternate */
2340                 ni_stc_writew(dev, mode2, NISTC_AI_MODE2_REG);
2341                 break;
2342         case TRIG_EXT:
2343                 mode1 |= NISTC_AI_MODE1_CONVERT_SRC(
2344                         ni_get_reg_value_roffs(CR_CHAN(cmd->convert_arg),
2345                                                NI_AI_ConvertClock,
2346                                                &devpriv->routing_tables, 1));
2347                 if ((cmd->convert_arg & CR_INVERT) == 0)
2348                         mode1 |= NISTC_AI_MODE1_CONVERT_POLARITY;
2349                 ni_stc_writew(dev, mode1, NISTC_AI_MODE1_REG);
2350
2351                 mode2 |= NISTC_AI_MODE2_SC_GATE_ENA |
2352                          NISTC_AI_MODE2_START_STOP_GATE_ENA;
2353                 ni_stc_writew(dev, mode2, NISTC_AI_MODE2_REG);
2354
2355                 break;
2356         }
2357
2358         if (dev->irq) {
2359                 /* interrupt on FIFO, errors, SC_TC */
2360                 interrupt_a_enable |= NISTC_INTA_ENA_AI_ERR |
2361                                       NISTC_INTA_ENA_AI_SC_TC;
2362
2363 #ifndef PCIDMA
2364                 interrupt_a_enable |= NISTC_INTA_ENA_AI_FIFO;
2365 #endif
2366
2367                 if ((cmd->flags & CMDF_WAKE_EOS) ||
2368                     (devpriv->ai_cmd2 & NISTC_AI_CMD2_END_ON_EOS)) {
2369                         /* wake on end-of-scan */
2370                         devpriv->aimode = AIMODE_SCAN;
2371                 } else {
2372                         devpriv->aimode = AIMODE_HALF_FULL;
2373                 }
2374
2375                 switch (devpriv->aimode) {
2376                 case AIMODE_HALF_FULL:
2377                         /* FIFO interrupts and DMA requests on half-full */
2378 #ifdef PCIDMA
2379                         ni_stc_writew(dev, NISTC_AI_MODE3_FIFO_MODE_HF_E,
2380                                       NISTC_AI_MODE3_REG);
2381 #else
2382                         ni_stc_writew(dev, NISTC_AI_MODE3_FIFO_MODE_HF,
2383                                       NISTC_AI_MODE3_REG);
2384 #endif
2385                         break;
2386                 case AIMODE_SAMPLE:
2387                         /*generate FIFO interrupts on non-empty */
2388                         ni_stc_writew(dev, NISTC_AI_MODE3_FIFO_MODE_NE,
2389                                       NISTC_AI_MODE3_REG);
2390                         break;
2391                 case AIMODE_SCAN:
2392 #ifdef PCIDMA
2393                         ni_stc_writew(dev, NISTC_AI_MODE3_FIFO_MODE_NE,
2394                                       NISTC_AI_MODE3_REG);
2395 #else
2396                         ni_stc_writew(dev, NISTC_AI_MODE3_FIFO_MODE_HF,
2397                                       NISTC_AI_MODE3_REG);
2398 #endif
2399                         interrupt_a_enable |= NISTC_INTA_ENA_AI_STOP;
2400                         break;
2401                 default:
2402                         break;
2403                 }
2404
2405                 /* clear interrupts */
2406                 ni_stc_writew(dev, NISTC_INTA_ACK_AI_ALL, NISTC_INTA_ACK_REG);
2407
2408                 ni_set_bits(dev, NISTC_INTA_ENA_REG, interrupt_a_enable, 1);
2409         } else {
2410                 /* interrupt on nothing */
2411                 ni_set_bits(dev, NISTC_INTA_ENA_REG, ~0, 0);
2412
2413                 /* XXX start polling if necessary */
2414         }
2415
2416         /* end configuration */
2417         ni_stc_writew(dev, NISTC_RESET_AI_CFG_END, NISTC_RESET_REG);
2418
2419         switch (cmd->scan_begin_src) {
2420         case TRIG_TIMER:
2421                 ni_stc_writew(dev, NISTC_AI_CMD1_SI2_ARM |
2422                                    NISTC_AI_CMD1_SI_ARM |
2423                                    NISTC_AI_CMD1_DIV_ARM |
2424                                    NISTC_AI_CMD1_SC_ARM,
2425                               NISTC_AI_CMD1_REG);
2426                 break;
2427         case TRIG_EXT:
2428                 ni_stc_writew(dev, NISTC_AI_CMD1_SI2_ARM |
2429                                    NISTC_AI_CMD1_SI_ARM |       /* XXX ? */
2430                                    NISTC_AI_CMD1_DIV_ARM |
2431                                    NISTC_AI_CMD1_SC_ARM,
2432                               NISTC_AI_CMD1_REG);
2433                 break;
2434         }
2435
2436 #ifdef PCIDMA
2437         {
2438                 int retval = ni_ai_setup_MITE_dma(dev);
2439
2440                 if (retval)
2441                         return retval;
2442         }
2443 #endif
2444
2445         if (cmd->start_src == TRIG_NOW) {
2446                 ni_stc_writew(dev, NISTC_AI_CMD2_START1_PULSE |
2447                                    devpriv->ai_cmd2,
2448                               NISTC_AI_CMD2_REG);
2449                 s->async->inttrig = NULL;
2450         } else if (cmd->start_src == TRIG_EXT) {
2451                 s->async->inttrig = NULL;
2452         } else {        /* TRIG_INT */
2453                 s->async->inttrig = ni_ai_inttrig;
2454         }
2455
2456         return 0;
2457 }
2458
2459 static int ni_ai_insn_config(struct comedi_device *dev,
2460                              struct comedi_subdevice *s,
2461                              struct comedi_insn *insn, unsigned int *data)
2462 {
2463         const struct ni_board_struct *board = dev->board_ptr;
2464         struct ni_private *devpriv = dev->private;
2465
2466         if (insn->n < 1)
2467                 return -EINVAL;
2468
2469         switch (data[0]) {
2470         case INSN_CONFIG_ALT_SOURCE:
2471                 if (devpriv->is_m_series) {
2472                         if (data[1] & ~NI_M_CFG_BYPASS_AI_CAL_MASK)
2473                                 return -EINVAL;
2474                         devpriv->ai_calib_source = data[1];
2475                 } else if (devpriv->is_6143) {
2476                         unsigned int calib_source;
2477
2478                         calib_source = data[1] & 0xf;
2479
2480                         devpriv->ai_calib_source = calib_source;
2481                         ni_writew(dev, calib_source, NI6143_CALIB_CHAN_REG);
2482                 } else {
2483                         unsigned int calib_source;
2484                         unsigned int calib_source_adjust;
2485
2486                         calib_source = data[1] & 0xf;
2487                         calib_source_adjust = (data[1] >> 4) & 0xff;
2488
2489                         if (calib_source >= 8)
2490                                 return -EINVAL;
2491                         devpriv->ai_calib_source = calib_source;
2492                         if (devpriv->is_611x) {
2493                                 ni_writeb(dev, calib_source_adjust,
2494                                           NI611X_CAL_GAIN_SEL_REG);
2495                         }
2496                 }
2497                 return 2;
2498         case INSN_CONFIG_GET_CMD_TIMING_CONSTRAINTS:
2499                 /* we don't care about actual channels */
2500                 /* data[3] : chanlist_len */
2501                 data[1] = ni_min_ai_scan_period_ns(dev, data[3]);
2502                 if (devpriv->is_611x || devpriv->is_6143)
2503                         data[2] = 0; /* simultaneous output */
2504                 else
2505                         data[2] = board->ai_speed;
2506                 return 0;
2507         default:
2508                 break;
2509         }
2510
2511         return -EINVAL;
2512 }
2513
2514 static void ni_ao_munge(struct comedi_device *dev, struct comedi_subdevice *s,
2515                         void *data, unsigned int num_bytes,
2516                         unsigned int chan_index)
2517 {
2518         struct comedi_cmd *cmd = &s->async->cmd;
2519         unsigned int nsamples = comedi_bytes_to_samples(s, num_bytes);
2520         unsigned short *array = data;
2521         unsigned int i;
2522 #ifdef PCIDMA
2523         __le16 buf, *barray = data;
2524 #endif
2525
2526         for (i = 0; i < nsamples; i++) {
2527                 unsigned int range = CR_RANGE(cmd->chanlist[chan_index]);
2528                 unsigned short val = array[i];
2529
2530                 /*
2531                  * Munge data from unsigned to two's complement for
2532                  * bipolar ranges.
2533                  */
2534                 if (comedi_range_is_bipolar(s, range))
2535                         val = comedi_offset_munge(s, val);
2536 #ifdef PCIDMA
2537                 buf = cpu_to_le16(val);
2538                 barray[i] = buf;
2539 #else
2540                 array[i] = val;
2541 #endif
2542                 chan_index++;
2543                 chan_index %= cmd->chanlist_len;
2544         }
2545 }
2546
2547 static int ni_m_series_ao_config_chanlist(struct comedi_device *dev,
2548                                           struct comedi_subdevice *s,
2549                                           unsigned int chanspec[],
2550                                           unsigned int n_chans, int timed)
2551 {
2552         struct ni_private *devpriv = dev->private;
2553         unsigned int range;
2554         unsigned int chan;
2555         unsigned int conf;
2556         int i;
2557         int invert = 0;
2558
2559         if (timed) {
2560                 for (i = 0; i < s->n_chan; ++i) {
2561                         devpriv->ao_conf[i] &= ~NI_M_AO_CFG_BANK_UPDATE_TIMED;
2562                         ni_writeb(dev, devpriv->ao_conf[i],
2563                                   NI_M_AO_CFG_BANK_REG(i));
2564                         ni_writeb(dev, 0xf, NI_M_AO_WAVEFORM_ORDER_REG(i));
2565                 }
2566         }
2567         for (i = 0; i < n_chans; i++) {
2568                 const struct comedi_krange *krange;
2569
2570                 chan = CR_CHAN(chanspec[i]);
2571                 range = CR_RANGE(chanspec[i]);
2572                 krange = s->range_table->range + range;
2573                 invert = 0;
2574                 conf = 0;
2575                 switch (krange->max - krange->min) {
2576                 case 20000000:
2577                         conf |= NI_M_AO_CFG_BANK_REF_INT_10V;
2578                         ni_writeb(dev, 0, NI_M_AO_REF_ATTENUATION_REG(chan));
2579                         break;
2580                 case 10000000:
2581                         conf |= NI_M_AO_CFG_BANK_REF_INT_5V;
2582                         ni_writeb(dev, 0, NI_M_AO_REF_ATTENUATION_REG(chan));
2583                         break;
2584                 case 4000000:
2585                         conf |= NI_M_AO_CFG_BANK_REF_INT_10V;
2586                         ni_writeb(dev, NI_M_AO_REF_ATTENUATION_X5,
2587                                   NI_M_AO_REF_ATTENUATION_REG(chan));
2588                         break;
2589                 case 2000000:
2590                         conf |= NI_M_AO_CFG_BANK_REF_INT_5V;
2591                         ni_writeb(dev, NI_M_AO_REF_ATTENUATION_X5,
2592                                   NI_M_AO_REF_ATTENUATION_REG(chan));
2593                         break;
2594                 default:
2595                         dev_err(dev->class_dev,
2596                                 "bug! unhandled ao reference voltage\n");
2597                         break;
2598                 }
2599                 switch (krange->max + krange->min) {
2600                 case 0:
2601                         conf |= NI_M_AO_CFG_BANK_OFFSET_0V;
2602                         break;
2603                 case 10000000:
2604                         conf |= NI_M_AO_CFG_BANK_OFFSET_5V;
2605                         break;
2606                 default:
2607                         dev_err(dev->class_dev,
2608                                 "bug! unhandled ao offset voltage\n");
2609                         break;
2610                 }
2611                 if (timed)
2612                         conf |= NI_M_AO_CFG_BANK_UPDATE_TIMED;
2613                 ni_writeb(dev, conf, NI_M_AO_CFG_BANK_REG(chan));
2614                 devpriv->ao_conf[chan] = conf;
2615                 ni_writeb(dev, i, NI_M_AO_WAVEFORM_ORDER_REG(chan));
2616         }
2617         return invert;
2618 }
2619
2620 static int ni_old_ao_config_chanlist(struct comedi_device *dev,
2621                                      struct comedi_subdevice *s,
2622                                      unsigned int chanspec[],
2623                                      unsigned int n_chans)
2624 {
2625         struct ni_private *devpriv = dev->private;
2626         unsigned int range;
2627         unsigned int chan;
2628         unsigned int conf;
2629         int i;
2630         int invert = 0;
2631
2632         for (i = 0; i < n_chans; i++) {
2633                 chan = CR_CHAN(chanspec[i]);
2634                 range = CR_RANGE(chanspec[i]);
2635                 conf = NI_E_AO_DACSEL(chan);
2636
2637                 if (comedi_range_is_bipolar(s, range)) {
2638                         conf |= NI_E_AO_CFG_BIP;
2639                         invert = (s->maxdata + 1) >> 1;
2640                 } else {
2641                         invert = 0;
2642                 }
2643                 if (comedi_range_is_external(s, range))
2644                         conf |= NI_E_AO_EXT_REF;
2645
2646                 /* not all boards can deglitch, but this shouldn't hurt */
2647                 if (chanspec[i] & CR_DEGLITCH)
2648                         conf |= NI_E_AO_DEGLITCH;
2649
2650                 /* analog reference */
2651                 /* AREF_OTHER connects AO ground to AI ground, i think */
2652                 if (CR_AREF(chanspec[i]) == AREF_OTHER)
2653                         conf |= NI_E_AO_GROUND_REF;
2654
2655                 ni_writew(dev, conf, NI_E_AO_CFG_REG);
2656                 devpriv->ao_conf[chan] = conf;
2657         }
2658         return invert;
2659 }
2660
2661 static int ni_ao_config_chanlist(struct comedi_device *dev,
2662                                  struct comedi_subdevice *s,
2663                                  unsigned int chanspec[], unsigned int n_chans,
2664                                  int timed)
2665 {
2666         struct ni_private *devpriv = dev->private;
2667
2668         if (devpriv->is_m_series)
2669                 return ni_m_series_ao_config_chanlist(dev, s, chanspec, n_chans,
2670                                                       timed);
2671         else
2672                 return ni_old_ao_config_chanlist(dev, s, chanspec, n_chans);
2673 }
2674
2675 static int ni_ao_insn_write(struct comedi_device *dev,
2676                             struct comedi_subdevice *s,
2677                             struct comedi_insn *insn,
2678                             unsigned int *data)
2679 {
2680         struct ni_private *devpriv = dev->private;
2681         unsigned int chan = CR_CHAN(insn->chanspec);
2682         unsigned int range = CR_RANGE(insn->chanspec);
2683         int reg;
2684         int i;
2685
2686         if (devpriv->is_6xxx) {
2687                 ni_ao_win_outw(dev, 1 << chan, NI671X_AO_IMMEDIATE_REG);
2688
2689                 reg = NI671X_DAC_DIRECT_DATA_REG(chan);
2690         } else if (devpriv->is_m_series) {
2691                 reg = NI_M_DAC_DIRECT_DATA_REG(chan);
2692         } else {
2693                 reg = NI_E_DAC_DIRECT_DATA_REG(chan);
2694         }
2695
2696         ni_ao_config_chanlist(dev, s, &insn->chanspec, 1, 0);
2697
2698         for (i = 0; i < insn->n; i++) {
2699                 unsigned int val = data[i];
2700
2701                 s->readback[chan] = val;
2702
2703                 if (devpriv->is_6xxx) {
2704                         /*
2705                          * 6xxx boards have bipolar outputs, munge the
2706                          * unsigned comedi values to 2's complement
2707                          */
2708                         val = comedi_offset_munge(s, val);
2709
2710                         ni_ao_win_outw(dev, val, reg);
2711                 } else if (devpriv->is_m_series) {
2712                         /*
2713                          * M-series boards use offset binary values for
2714                          * bipolar and uinpolar outputs
2715                          */
2716                         ni_writew(dev, val, reg);
2717                 } else {
2718                         /*
2719                          * Non-M series boards need two's complement values
2720                          * for bipolar ranges.
2721                          */
2722                         if (comedi_range_is_bipolar(s, range))
2723                                 val = comedi_offset_munge(s, val);
2724
2725                         ni_writew(dev, val, reg);
2726                 }
2727         }
2728
2729         return insn->n;
2730 }
2731
2732 /*
2733  * Arms the AO device in preparation for a trigger event.
2734  * This function also allocates and prepares a DMA channel (or FIFO if DMA is
2735  * not used).  As a part of this preparation, this function preloads the DAC
2736  * registers with the first values of the output stream.  This ensures that the
2737  * first clock cycle after the trigger can be used for output.
2738  *
2739  * Note that this function _must_ happen after a user has written data to the
2740  * output buffers via either mmap or write(fileno,...).
2741  */
2742 static int ni_ao_arm(struct comedi_device *dev,
2743                      struct comedi_subdevice *s)
2744 {
2745         struct ni_private *devpriv = dev->private;
2746         int ret;
2747         int interrupt_b_bits;
2748         int i;
2749         static const int timeout = 1000;
2750
2751         /*
2752          * Prevent ao from doing things like trying to allocate the ao dma
2753          * channel multiple times.
2754          */
2755         if (!devpriv->ao_needs_arming) {
2756                 dev_dbg(dev->class_dev, "%s: device does not need arming!\n",
2757                         __func__);
2758                 return -EINVAL;
2759         }
2760
2761         devpriv->ao_needs_arming = 0;
2762
2763         ni_set_bits(dev, NISTC_INTB_ENA_REG,
2764                     NISTC_INTB_ENA_AO_FIFO | NISTC_INTB_ENA_AO_ERR, 0);
2765         interrupt_b_bits = NISTC_INTB_ENA_AO_ERR;
2766 #ifdef PCIDMA
2767         ni_stc_writew(dev, 1, NISTC_DAC_FIFO_CLR_REG);
2768         if (devpriv->is_6xxx)
2769                 ni_ao_win_outl(dev, 0x6, NI611X_AO_FIFO_OFFSET_LOAD_REG);
2770         ret = ni_ao_setup_MITE_dma(dev);
2771         if (ret)
2772                 return ret;
2773         ret = ni_ao_wait_for_dma_load(dev);
2774         if (ret < 0)
2775                 return ret;
2776 #else
2777         ret = ni_ao_prep_fifo(dev, s);
2778         if (ret == 0)
2779                 return -EPIPE;
2780
2781         interrupt_b_bits |= NISTC_INTB_ENA_AO_FIFO;
2782 #endif
2783
2784         ni_stc_writew(dev, devpriv->ao_mode3 | NISTC_AO_MODE3_NOT_AN_UPDATE,
2785                       NISTC_AO_MODE3_REG);
2786         ni_stc_writew(dev, devpriv->ao_mode3, NISTC_AO_MODE3_REG);
2787         /* wait for DACs to be loaded */
2788         for (i = 0; i < timeout; i++) {
2789                 udelay(1);
2790                 if ((ni_stc_readw(dev, NISTC_STATUS2_REG) &
2791                      NISTC_STATUS2_AO_TMRDACWRS_IN_PROGRESS) == 0)
2792                         break;
2793         }
2794         if (i == timeout) {
2795                 dev_err(dev->class_dev,
2796                         "timed out waiting for AO_TMRDACWRs_In_Progress_St to clear\n");
2797                 return -EIO;
2798         }
2799         /*
2800          * stc manual says we are need to clear error interrupt after
2801          * AO_TMRDACWRs_In_Progress_St clears
2802          */
2803         ni_stc_writew(dev, NISTC_INTB_ACK_AO_ERR, NISTC_INTB_ACK_REG);
2804
2805         ni_set_bits(dev, NISTC_INTB_ENA_REG, interrupt_b_bits, 1);
2806
2807         ni_stc_writew(dev, NISTC_AO_CMD1_UI_ARM |
2808                            NISTC_AO_CMD1_UC_ARM |
2809                            NISTC_AO_CMD1_BC_ARM |
2810                            devpriv->ao_cmd1,
2811                       NISTC_AO_CMD1_REG);
2812
2813         return 0;
2814 }
2815
2816 static int ni_ao_insn_config(struct comedi_device *dev,
2817                              struct comedi_subdevice *s,
2818                              struct comedi_insn *insn, unsigned int *data)
2819 {
2820         const struct ni_board_struct *board = dev->board_ptr;
2821         struct ni_private *devpriv = dev->private;
2822         unsigned int nbytes;
2823
2824         switch (data[0]) {
2825         case INSN_CONFIG_GET_HARDWARE_BUFFER_SIZE:
2826                 switch (data[1]) {
2827                 case COMEDI_OUTPUT:
2828                         nbytes = comedi_samples_to_bytes(s,
2829                                                          board->ao_fifo_depth);
2830                         data[2] = 1 + nbytes;
2831                         if (devpriv->mite)
2832                                 data[2] += devpriv->mite->fifo_size;
2833                         break;
2834                 case COMEDI_INPUT:
2835                         data[2] = 0;
2836                         break;
2837                 default:
2838                         return -EINVAL;
2839                 }
2840                 return 0;
2841         case INSN_CONFIG_ARM:
2842                 return ni_ao_arm(dev, s);
2843         case INSN_CONFIG_GET_CMD_TIMING_CONSTRAINTS:
2844                 /* we don't care about actual channels */
2845                 /* data[3] : chanlist_len */
2846                 data[1] = board->ao_speed * data[3];
2847                 data[2] = 0;
2848                 return 0;
2849         default:
2850                 break;
2851         }
2852
2853         return -EINVAL;
2854 }
2855
2856 static int ni_ao_inttrig(struct comedi_device *dev,
2857                          struct comedi_subdevice *s,
2858                          unsigned int trig_num)
2859 {
2860         struct ni_private *devpriv = dev->private;
2861         struct comedi_cmd *cmd = &s->async->cmd;
2862         int ret;
2863
2864         /*
2865          * Require trig_num == cmd->start_arg when cmd->start_src == TRIG_INT.
2866          * For backwards compatibility, also allow trig_num == 0 when
2867          * cmd->start_src != TRIG_INT (i.e. when cmd->start_src == TRIG_EXT);
2868          * in that case, the internal trigger is being used as a pre-trigger
2869          * before the external trigger.
2870          */
2871         if (!(trig_num == cmd->start_arg ||
2872               (trig_num == 0 && cmd->start_src != TRIG_INT)))
2873                 return -EINVAL;
2874
2875         /*
2876          * Null trig at beginning prevent ao start trigger from executing more
2877          * than once per command.
2878          */
2879         s->async->inttrig = NULL;
2880
2881         if (devpriv->ao_needs_arming) {
2882                 /* only arm this device if it still needs arming */
2883                 ret = ni_ao_arm(dev, s);
2884                 if (ret)
2885                         return ret;
2886         }
2887
2888         ni_stc_writew(dev, NISTC_AO_CMD2_START1_PULSE | devpriv->ao_cmd2,
2889                       NISTC_AO_CMD2_REG);
2890
2891         return 0;
2892 }
2893
2894 /*
2895  * begin ni_ao_cmd.
2896  * Organized similar to NI-STC and MHDDK examples.
2897  * ni_ao_cmd is broken out into configuration sub-routines for clarity.
2898  */
2899
2900 static void ni_ao_cmd_personalize(struct comedi_device *dev,
2901                                   const struct comedi_cmd *cmd)
2902 {
2903         const struct ni_board_struct *board = dev->board_ptr;
2904         unsigned int bits;
2905
2906         ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);
2907
2908         bits =
2909           /* fast CPU interface--only eseries */
2910           /* ((slow CPU interface) ? 0 : AO_Fast_CPU) | */
2911           NISTC_AO_PERSONAL_BC_SRC_SEL  |
2912           0 /* (use_original_pulse ? 0 : NISTC_AO_PERSONAL_UPDATE_TIMEBASE) */ |
2913           /*
2914            * FIXME:  start setting following bit when appropriate.  Need to
2915            * determine whether board is E4 or E1.
2916            * FROM MHHDK:
2917            * if board is E4 or E1
2918            *   Set bit "NISTC_AO_PERSONAL_UPDATE_PW" to 0
2919            * else
2920            *   set it to 1
2921            */
2922           NISTC_AO_PERSONAL_UPDATE_PW   |
2923           /* FIXME:  when should we set following bit to zero? */
2924           NISTC_AO_PERSONAL_TMRDACWR_PW |
2925           (board->ao_fifo_depth ?
2926             NISTC_AO_PERSONAL_FIFO_ENA : NISTC_AO_PERSONAL_DMA_PIO_CTRL)
2927           ;
2928 #if 0
2929         /*
2930          * FIXME:
2931          * add something like ".has_individual_dacs = 0" to ni_board_struct
2932          * since, as F Hess pointed out, not all in m series have singles.  not
2933          * sure if e-series all have duals...
2934          */
2935
2936         /*
2937          * F Hess: windows driver does not set NISTC_AO_PERSONAL_NUM_DAC bit for
2938          * 6281, verified with bus analyzer.
2939          */
2940         if (devpriv->is_m_series)
2941                 bits |= NISTC_AO_PERSONAL_NUM_DAC;
2942 #endif
2943         ni_stc_writew(dev, bits, NISTC_AO_PERSONAL_REG);
2944
2945         ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
2946 }
2947
2948 static void ni_ao_cmd_set_trigger(struct comedi_device *dev,
2949                                   const struct comedi_cmd *cmd)
2950 {
2951         struct ni_private *devpriv = dev->private;
2952         unsigned int trigsel;
2953
2954         ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);
2955
2956         /* sync */
2957         if (cmd->stop_src == TRIG_NONE) {
2958                 devpriv->ao_mode1 |= NISTC_AO_MODE1_CONTINUOUS;
2959                 devpriv->ao_mode1 &= ~NISTC_AO_MODE1_TRIGGER_ONCE;
2960         } else {
2961                 devpriv->ao_mode1 &= ~NISTC_AO_MODE1_CONTINUOUS;
2962                 devpriv->ao_mode1 |= NISTC_AO_MODE1_TRIGGER_ONCE;
2963         }
2964         ni_stc_writew(dev, devpriv->ao_mode1, NISTC_AO_MODE1_REG);
2965
2966         if (cmd->start_src == TRIG_INT) {
2967                 trigsel = NISTC_AO_TRIG_START1_EDGE |
2968                           NISTC_AO_TRIG_START1_SYNC;
2969         } else { /* TRIG_EXT */
2970                 trigsel = NISTC_AO_TRIG_START1_SEL(
2971                         ni_get_reg_value_roffs(CR_CHAN(cmd->start_arg),
2972                                                NI_AO_StartTrigger,
2973                                                &devpriv->routing_tables, 1));
2974                 /* 0=active high, 1=active low. see daq-stc 3-24 (p186) */
2975                 if (cmd->start_arg & CR_INVERT)
2976                         trigsel |= NISTC_AO_TRIG_START1_POLARITY;
2977                 /* 0=edge detection disabled, 1=enabled */
2978                 if (cmd->start_arg & CR_EDGE)
2979                         trigsel |= NISTC_AO_TRIG_START1_EDGE;
2980         }
2981         ni_stc_writew(dev, trigsel, NISTC_AO_TRIG_SEL_REG);
2982
2983         /* AO_Delayed_START1 = 0, we do not support delayed start...yet */
2984
2985         /* sync */
2986         /* select DA_START1 as PFI6/AO_START1 when configured as an output */
2987         devpriv->ao_mode3 &= ~NISTC_AO_MODE3_TRIG_LEN;
2988         ni_stc_writew(dev, devpriv->ao_mode3, NISTC_AO_MODE3_REG);
2989
2990         ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
2991 }
2992
2993 static void ni_ao_cmd_set_counters(struct comedi_device *dev,
2994                                    const struct comedi_cmd *cmd)
2995 {
2996         struct ni_private *devpriv = dev->private;
2997         /* Not supporting 'waveform staging' or 'local buffer with pauses' */
2998
2999         ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);
3000         /*
3001          * This relies on ao_mode1/(Trigger_Once | Continuous) being set in
3002          * set_trigger above.  It is unclear whether we really need to re-write
3003          * this register with these values.  The mhddk examples for e-series
3004          * show writing this in both places, but the examples for m-series show
3005          * a single write in the set_counters function (here).
3006          */
3007         ni_stc_writew(dev, devpriv->ao_mode1, NISTC_AO_MODE1_REG);
3008
3009         /* sync (upload number of buffer iterations -1) */
3010         /* indicate that we want to use BC_Load_A_Register as the source */
3011         devpriv->ao_mode2 &= ~NISTC_AO_MODE2_BC_INIT_LOAD_SRC;
3012         ni_stc_writew(dev, devpriv->ao_mode2, NISTC_AO_MODE2_REG);
3013
3014         /*
3015          * if the BC_TC interrupt is still issued in spite of UC, BC, UI
3016          * ignoring BC_TC, then we will need to find a way to ignore that
3017          * interrupt in continuous mode.
3018          */
3019         ni_stc_writel(dev, 0, NISTC_AO_BC_LOADA_REG); /* iter once */
3020
3021         /* sync (issue command to load number of buffer iterations -1) */
3022         ni_stc_writew(dev, NISTC_AO_CMD1_BC_LOAD, NISTC_AO_CMD1_REG);
3023
3024         /* sync (upload number of updates in buffer) */
3025         /* indicate that we want to use UC_Load_A_Register as the source */
3026         devpriv->ao_mode2 &= ~NISTC_AO_MODE2_UC_INIT_LOAD_SRC;
3027         ni_stc_writew(dev, devpriv->ao_mode2, NISTC_AO_MODE2_REG);
3028
3029         /*
3030          * if a user specifies '0', this automatically assumes the entire 24bit
3031          * address space is available for the (multiple iterations of single
3032          * buffer) MISB.  Otherwise, stop_arg specifies the MISB length that
3033          * will be used, regardless of whether we are in continuous mode or not.
3034          * In continuous mode, the output will just iterate indefinitely over
3035          * the MISB.
3036          */
3037         {
3038                 unsigned int stop_arg = cmd->stop_arg > 0 ?
3039                         (cmd->stop_arg & 0xffffff) : 0xffffff;
3040
3041                 if (devpriv->is_m_series) {
3042                         /*
3043                          * this is how the NI example code does it for m-series
3044                          * boards, verified correct with 6259
3045                          */
3046                         ni_stc_writel(dev, stop_arg - 1, NISTC_AO_UC_LOADA_REG);
3047
3048                         /* sync (issue cmd to load number of updates in MISB) */
3049                         ni_stc_writew(dev, NISTC_AO_CMD1_UC_LOAD,
3050                                       NISTC_AO_CMD1_REG);
3051                 } else {
3052                         ni_stc_writel(dev, stop_arg, NISTC_AO_UC_LOADA_REG);
3053
3054                         /* sync (issue cmd to load number of updates in MISB) */
3055                         ni_stc_writew(dev, NISTC_AO_CMD1_UC_LOAD,
3056                                       NISTC_AO_CMD1_REG);
3057
3058                         /*
3059                          * sync (upload number of updates-1 in MISB)
3060                          * --eseries only?
3061                          */
3062                         ni_stc_writel(dev, stop_arg - 1, NISTC_AO_UC_LOADA_REG);
3063                 }
3064         }
3065
3066         ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
3067 }
3068
3069 static void ni_ao_cmd_set_update(struct comedi_device *dev,
3070                                  const struct comedi_cmd *cmd)
3071 {
3072         struct ni_private *devpriv = dev->private;
3073
3074         ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);
3075
3076         /*
3077          * zero out these bit fields to be set below. Does an ao-reset do this
3078          * automatically?
3079          */
3080         devpriv->ao_mode1 &= ~(
3081           NISTC_AO_MODE1_UI_SRC_MASK         |
3082           NISTC_AO_MODE1_UI_SRC_POLARITY     |
3083           NISTC_AO_MODE1_UPDATE_SRC_MASK     |
3084           NISTC_AO_MODE1_UPDATE_SRC_POLARITY
3085         );
3086
3087         if (cmd->scan_begin_src == TRIG_TIMER) {
3088                 unsigned int trigvar;
3089
3090                 devpriv->ao_cmd2  &= ~NISTC_AO_CMD2_BC_GATE_ENA;
3091
3092                 /*
3093                  * NOTE: there are several other ways of configuring internal
3094                  * updates, but we'll only support one for now:  using
3095                  * AO_IN_TIMEBASE, w/o waveform staging, w/o a delay between
3096                  * START1 and first update, and also w/o local buffer mode w/
3097                  * pauses.
3098                  */
3099
3100                 /*
3101                  * This is already done above:
3102                  * devpriv->ao_mode1 &= ~(
3103                  *   // set UPDATE_Source to UI_TC:
3104                  *   NISTC_AO_MODE1_UPDATE_SRC_MASK |
3105                  *   // set UPDATE_Source_Polarity to rising (required?)
3106                  *   NISTC_AO_MODE1_UPDATE_SRC_POLARITY |
3107                  *   // set UI_Source to AO_IN_TIMEBASE1:
3108                  *   NISTC_AO_MODE1_UI_SRC_MASK     |
3109                  *   // set UI_Source_Polarity to rising (required?)
3110                  *   NISTC_AO_MODE1_UI_SRC_POLARITY
3111                  * );
3112                  */
3113
3114                 /*
3115                  * TODO:  use ao_ui_clock_source to allow all possible signals
3116                  * to be routed to UI_Source_Select.  See tSTC.h for
3117                  * eseries/ni67xx and tMSeries.h for mseries.
3118                  */
3119
3120                 trigvar = ni_ns_to_timer(dev, cmd->scan_begin_arg,
3121                                          CMDF_ROUND_NEAREST);
3122
3123                 /*
3124                  * Wait N TB3 ticks after the start trigger before
3125                  * clocking (N must be >=2).
3126                  */
3127                 /* following line: 2-1 per STC */
3128                 ni_stc_writel(dev, 1, NISTC_AO_UI_LOADA_REG);
3129                 ni_stc_writew(dev, NISTC_AO_CMD1_UI_LOAD, NISTC_AO_CMD1_REG);
3130                 ni_stc_writel(dev, trigvar, NISTC_AO_UI_LOADA_REG);
3131         } else { /* TRIG_EXT */
3132                 /* FIXME:  assert scan_begin_arg != 0, ret failure otherwise */
3133                 devpriv->ao_cmd2  |= NISTC_AO_CMD2_BC_GATE_ENA;
3134                 devpriv->ao_mode1 |= NISTC_AO_MODE1_UPDATE_SRC(
3135                         ni_get_reg_value(CR_CHAN(cmd->scan_begin_arg),
3136                                          NI_AO_SampleClock,
3137                                          &devpriv->routing_tables));
3138                 if (cmd->scan_begin_arg & CR_INVERT)
3139                         devpriv->ao_mode1 |= NISTC_AO_MODE1_UPDATE_SRC_POLARITY;
3140         }
3141
3142         ni_stc_writew(dev, devpriv->ao_cmd2, NISTC_AO_CMD2_REG);
3143         ni_stc_writew(dev, devpriv->ao_mode1, NISTC_AO_MODE1_REG);
3144         devpriv->ao_mode2 &= ~(NISTC_AO_MODE2_UI_RELOAD_MODE(3) |
3145                                NISTC_AO_MODE2_UI_INIT_LOAD_SRC);
3146         ni_stc_writew(dev, devpriv->ao_mode2, NISTC_AO_MODE2_REG);
3147
3148         /* Configure DAQ-STC for Timed update mode */
3149         devpriv->ao_cmd1 |= NISTC_AO_CMD1_DAC1_UPDATE_MODE |
3150                             NISTC_AO_CMD1_DAC0_UPDATE_MODE;
3151         /* We are not using UPDATE2-->don't have to set DACx_Source_Select */
3152         ni_stc_writew(dev, devpriv->ao_cmd1, NISTC_AO_CMD1_REG);
3153
3154         ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
3155 }
3156
3157 static void ni_ao_cmd_set_channels(struct comedi_device *dev,
3158                                    struct comedi_subdevice *s)
3159 {
3160         struct ni_private *devpriv = dev->private;
3161         const struct comedi_cmd *cmd = &s->async->cmd;
3162         unsigned int bits = 0;
3163
3164         ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);
3165
3166         if (devpriv->is_6xxx) {
3167                 unsigned int i;
3168
3169                 bits = 0;
3170                 for (i = 0; i < cmd->chanlist_len; ++i) {
3171                         int chan = CR_CHAN(cmd->chanlist[i]);
3172
3173                         bits |= 1 << chan;
3174                         ni_ao_win_outw(dev, chan, NI611X_AO_WAVEFORM_GEN_REG);
3175                 }
3176                 ni_ao_win_outw(dev, bits, NI611X_AO_TIMED_REG);
3177         }
3178
3179         ni_ao_config_chanlist(dev, s, cmd->chanlist, cmd->chanlist_len, 1);
3180
3181         if (cmd->scan_end_arg > 1) {
3182                 devpriv->ao_mode1 |= NISTC_AO_MODE1_MULTI_CHAN;
3183                 bits = NISTC_AO_OUT_CTRL_CHANS(cmd->scan_end_arg - 1)
3184                                  | NISTC_AO_OUT_CTRL_UPDATE_SEL_HIGHZ;
3185
3186         } else {
3187                 devpriv->ao_mode1 &= ~NISTC_AO_MODE1_MULTI_CHAN;
3188                 bits = NISTC_AO_OUT_CTRL_UPDATE_SEL_HIGHZ;
3189                 if (devpriv->is_m_series | devpriv->is_6xxx)
3190                         bits |= NISTC_AO_OUT_CTRL_CHANS(0);
3191                 else
3192                         bits |= NISTC_AO_OUT_CTRL_CHANS(
3193                                         CR_CHAN(cmd->chanlist[0]));
3194         }
3195
3196         ni_stc_writew(dev, devpriv->ao_mode1, NISTC_AO_MODE1_REG);
3197         ni_stc_writew(dev, bits,              NISTC_AO_OUT_CTRL_REG);
3198
3199         ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
3200 }
3201
3202 static void ni_ao_cmd_set_stop_conditions(struct comedi_device *dev,
3203                                           const struct comedi_cmd *cmd)
3204 {
3205         struct ni_private *devpriv = dev->private;
3206
3207         ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);
3208
3209         devpriv->ao_mode3 |= NISTC_AO_MODE3_STOP_ON_OVERRUN_ERR;
3210         ni_stc_writew(dev, devpriv->ao_mode3, NISTC_AO_MODE3_REG);
3211
3212         /*
3213          * Since we are not supporting waveform staging, we ignore these errors:
3214          * NISTC_AO_MODE3_STOP_ON_BC_TC_ERR,
3215          * NISTC_AO_MODE3_STOP_ON_BC_TC_TRIG_ERR
3216          */
3217
3218         ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
3219 }
3220
3221 static void ni_ao_cmd_set_fifo_mode(struct comedi_device *dev)
3222 {
3223         struct ni_private *devpriv = dev->private;
3224
3225         ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);
3226
3227         devpriv->ao_mode2 &= ~NISTC_AO_MODE2_FIFO_MODE_MASK;
3228 #ifdef PCIDMA
3229         devpriv->ao_mode2 |= NISTC_AO_MODE2_FIFO_MODE_HF_F;
3230 #else
3231         devpriv->ao_mode2 |= NISTC_AO_MODE2_FIFO_MODE_HF;
3232 #endif
3233         /* NOTE:  this is where use_onboard_memory=True would be implemented */
3234         devpriv->ao_mode2 &= ~NISTC_AO_MODE2_FIFO_REXMIT_ENA;
3235         ni_stc_writew(dev, devpriv->ao_mode2, NISTC_AO_MODE2_REG);
3236
3237         /* enable sending of ao fifo requests (dma request) */
3238         ni_stc_writew(dev, NISTC_AO_START_AOFREQ_ENA, NISTC_AO_START_SEL_REG);
3239
3240         ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
3241
3242         /* we are not supporting boards with virtual fifos */
3243 }
3244
3245 static void ni_ao_cmd_set_interrupts(struct comedi_device *dev,
3246                                      struct comedi_subdevice *s)
3247 {
3248         if (s->async->cmd.stop_src == TRIG_COUNT)
3249                 ni_set_bits(dev, NISTC_INTB_ENA_REG,
3250                             NISTC_INTB_ENA_AO_BC_TC, 1);
3251
3252         s->async->inttrig = ni_ao_inttrig;
3253 }
3254
3255 static int ni_ao_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
3256 {
3257         struct ni_private *devpriv = dev->private;
3258         const struct comedi_cmd *cmd = &s->async->cmd;
3259
3260         if (dev->irq == 0) {
3261                 dev_err(dev->class_dev, "cannot run command without an irq");
3262                 return -EIO;
3263         }
3264
3265         /* ni_ao_reset should have already been done */
3266         ni_ao_cmd_personalize(dev, cmd);
3267         /* clearing fifo and preload happens elsewhere */
3268
3269         ni_ao_cmd_set_trigger(dev, cmd);
3270         ni_ao_cmd_set_counters(dev, cmd);
3271         ni_ao_cmd_set_update(dev, cmd);
3272         ni_ao_cmd_set_channels(dev, s);
3273         ni_ao_cmd_set_stop_conditions(dev, cmd);
3274         ni_ao_cmd_set_fifo_mode(dev);
3275         ni_cmd_set_mite_transfer(devpriv->ao_mite_ring, s, cmd, 0x00ffffff);
3276         ni_ao_cmd_set_interrupts(dev, s);
3277
3278         /*
3279          * arm(ing) must happen later so that DMA can be setup and DACs
3280          * preloaded with the actual output buffer before starting.
3281          *
3282          * start(ing) must happen _after_ arming is completed.  Starting can be
3283          * done either via ni_ao_inttrig, or via an external trigger.
3284          *
3285          * **Currently, ni_ao_inttrig will automatically attempt a call to
3286          * ni_ao_arm if the device still needs arming at that point.  This
3287          * allows backwards compatibility.
3288          */
3289         devpriv->ao_needs_arming = 1;
3290         return 0;
3291 }
3292
3293 /* end ni_ao_cmd */
3294
3295 static int ni_ao_cmdtest(struct comedi_device *dev, struct comedi_subdevice *s,
3296                          struct comedi_cmd *cmd)
3297 {
3298         const struct ni_board_struct *board = dev->board_ptr;
3299         struct ni_private *devpriv = dev->private;
3300         int err = 0;
3301         unsigned int tmp;
3302
3303         /* Step 1 : check if triggers are trivially valid */
3304
3305         err |= comedi_check_trigger_src(&cmd->start_src, TRIG_INT | TRIG_EXT);
3306         err |= comedi_check_trigger_src(&cmd->scan_begin_src,
3307                                         TRIG_TIMER | TRIG_EXT);
3308         err |= comedi_check_trigger_src(&cmd->convert_src, TRIG_NOW);
3309         err |= comedi_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
3310         err |= comedi_check_trigger_src(&cmd->stop_src, TRIG_COUNT | TRIG_NONE);
3311
3312         if (err)
3313                 return 1;
3314
3315         /* Step 2a : make sure trigger sources are unique */
3316
3317         err |= comedi_check_trigger_is_unique(cmd->start_src);
3318         err |= comedi_check_trigger_is_unique(cmd->scan_begin_src);
3319         err |= comedi_check_trigger_is_unique(cmd->stop_src);
3320
3321         /* Step 2b : and mutually compatible */
3322
3323         if (err)
3324                 return 2;
3325
3326         /* Step 3: check if arguments are trivially valid */
3327
3328         switch (cmd->start_src) {
3329         case TRIG_INT:
3330                 err |= comedi_check_trigger_arg_is(&cmd->start_arg, 0);
3331                 break;
3332         case TRIG_EXT:
3333                 err |= ni_check_trigger_arg_roffs(CR_CHAN(cmd->start_arg),
3334                                                   NI_AO_StartTrigger,
3335                                                   &devpriv->routing_tables, 1);
3336                 break;
3337         }
3338
3339         if (cmd->scan_begin_src == TRIG_TIMER) {
3340                 err |= comedi_check_trigger_arg_min(&cmd->scan_begin_arg,
3341                                                     board->ao_speed);
3342                 err |= comedi_check_trigger_arg_max(&cmd->scan_begin_arg,
3343                                                     devpriv->clock_ns *
3344                                                     0xffffff);
3345         } else {                /* TRIG_EXT */
3346                 err |= ni_check_trigger_arg(CR_CHAN(cmd->scan_begin_arg),
3347                                             NI_AO_SampleClock,
3348                                             &devpriv->routing_tables);
3349         }
3350
3351         err |= comedi_check_trigger_arg_is(&cmd->convert_arg, 0);
3352         err |= comedi_check_trigger_arg_is(&cmd->scan_end_arg,
3353                                            cmd->chanlist_len);
3354         err |= comedi_check_trigger_arg_max(&cmd->stop_arg, 0x00ffffff);
3355
3356         if (err)
3357                 return 3;
3358
3359         /* step 4: fix up any arguments */
3360         if (cmd->scan_begin_src == TRIG_TIMER) {
3361                 tmp = cmd->scan_begin_arg;
3362                 cmd->scan_begin_arg =
3363                     ni_timer_to_ns(dev, ni_ns_to_timer(dev,
3364                                                        cmd->scan_begin_arg,
3365                                                        cmd->flags));
3366                 if (tmp != cmd->scan_begin_arg)
3367                         err++;
3368         }
3369         if (err)
3370                 return 4;
3371
3372         return 0;
3373 }
3374
3375 static int ni_ao_reset(struct comedi_device *dev, struct comedi_subdevice *s)
3376 {
3377         /* See 3.6.1.2 "Resetting", of DAQ-STC Technical Reference Manual */
3378
3379         /*
3380          * In the following, the "--sync" comments are meant to denote
3381          * asynchronous boundaries for setting the registers as described in the
3382          * DAQ-STC mostly in the order also described in the DAQ-STC.
3383          */
3384
3385         struct ni_private *devpriv = dev->private;
3386
3387         ni_release_ao_mite_channel(dev);
3388
3389         /* --sync (reset AO) */
3390         if (devpriv->is_m_series)
3391                 /* following example in mhddk for m-series */
3392                 ni_stc_writew(dev, NISTC_RESET_AO, NISTC_RESET_REG);
3393
3394         /*--sync (start config) */
3395         ni_stc_writew(dev, NISTC_RESET_AO_CFG_START, NISTC_RESET_REG);
3396
3397         /*--sync (Disarm) */
3398         ni_stc_writew(dev, NISTC_AO_CMD1_DISARM, NISTC_AO_CMD1_REG);
3399
3400         /*
3401          * --sync
3402          * (clear bunch of registers--mseries mhddk examples do not include
3403          * this)
3404          */
3405         devpriv->ao_cmd1  = 0;
3406         devpriv->ao_cmd2  = 0;
3407         devpriv->ao_mode1 = 0;
3408         devpriv->ao_mode2 = 0;
3409         if (devpriv->is_m_series)
3410                 devpriv->ao_mode3 = NISTC_AO_MODE3_LAST_GATE_DISABLE;
3411         else
3412                 devpriv->ao_mode3 = 0;
3413
3414         ni_stc_writew(dev, 0, NISTC_AO_PERSONAL_REG);
3415         ni_stc_writew(dev, 0, NISTC_AO_CMD1_REG);
3416         ni_stc_writew(dev, 0, NISTC_AO_CMD2_REG);
3417         ni_stc_writew(dev, 0, NISTC_AO_MODE1_REG);
3418         ni_stc_writew(dev, 0, NISTC_AO_MODE2_REG);
3419         ni_stc_writew(dev, 0, NISTC_AO_OUT_CTRL_REG);
3420         ni_stc_writew(dev, devpriv->ao_mode3, NISTC_AO_MODE3_REG);
3421         ni_stc_writew(dev, 0, NISTC_AO_START_SEL_REG);
3422         ni_stc_writew(dev, 0, NISTC_AO_TRIG_SEL_REG);
3423
3424         /*--sync (disable interrupts) */
3425         ni_set_bits(dev, NISTC_INTB_ENA_REG, ~0, 0);
3426
3427         /*--sync (ack) */
3428         ni_stc_writew(dev, NISTC_AO_PERSONAL_BC_SRC_SEL, NISTC_AO_PERSONAL_REG);
3429         ni_stc_writew(dev, NISTC_INTB_ACK_AO_ALL, NISTC_INTB_ACK_REG);
3430
3431         /*--not in DAQ-STC.  which doc? */
3432         if (devpriv->is_6xxx) {
3433                 ni_ao_win_outw(dev, (1u << s->n_chan) - 1u,
3434                                NI671X_AO_IMMEDIATE_REG);
3435                 ni_ao_win_outw(dev, NI611X_AO_MISC_CLEAR_WG,
3436                                NI611X_AO_MISC_REG);
3437         }
3438         ni_stc_writew(dev, NISTC_RESET_AO_CFG_END, NISTC_RESET_REG);
3439         /*--end */
3440
3441         return 0;
3442 }
3443
3444 /* digital io */
3445
3446 static int ni_dio_insn_config(struct comedi_device *dev,
3447                               struct comedi_subdevice *s,
3448                               struct comedi_insn *insn,
3449                               unsigned int *data)
3450 {
3451         struct ni_private *devpriv = dev->private;
3452         int ret;
3453
3454         ret = comedi_dio_insn_config(dev, s, insn, data, 0);
3455         if (ret)
3456                 return ret;
3457
3458         devpriv->dio_control &= ~NISTC_DIO_CTRL_DIR_MASK;
3459         devpriv->dio_control |= NISTC_DIO_CTRL_DIR(s->io_bits);
3460         ni_stc_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);
3461
3462         return insn->n;
3463 }
3464
3465 static int ni_dio_insn_bits(struct comedi_device *dev,
3466                             struct comedi_subdevice *s,
3467                             struct comedi_insn *insn,
3468                             unsigned int *data)
3469 {
3470         struct ni_private *devpriv = dev->private;
3471
3472         /* Make sure we're not using the serial part of the dio */
3473         if ((data[0] & (NISTC_DIO_SDIN | NISTC_DIO_SDOUT)) &&
3474             devpriv->serial_interval_ns)
3475                 return -EBUSY;
3476
3477         if (comedi_dio_update_state(s, data)) {
3478                 devpriv->dio_output &= ~NISTC_DIO_OUT_PARALLEL_MASK;
3479                 devpriv->dio_output |= NISTC_DIO_OUT_PARALLEL(s->state);
3480                 ni_stc_writew(dev, devpriv->dio_output, NISTC_DIO_OUT_REG);
3481         }
3482
3483         data[1] = ni_stc_readw(dev, NISTC_DIO_IN_REG);
3484
3485         return insn->n;
3486 }
3487
3488 #ifdef PCIDMA
3489 static int ni_m_series_dio_insn_config(struct comedi_device *dev,
3490                                        struct comedi_subdevice *s,
3491                                        struct comedi_insn *insn,
3492                                        unsigned int *data)
3493 {
3494         int ret;
3495
3496         if (data[0] == INSN_CONFIG_GET_CMD_TIMING_CONSTRAINTS) {
3497                 const struct ni_board_struct *board = dev->board_ptr;
3498
3499                 /* we don't care about actual channels */
3500                 data[1] = board->dio_speed;
3501                 data[2] = 0;
3502                 return 0;
3503         }
3504
3505         ret = comedi_dio_insn_config(dev, s, insn, data, 0);
3506         if (ret)
3507                 return ret;
3508
3509         ni_writel(dev, s->io_bits, NI_M_DIO_DIR_REG);
3510
3511         return insn->n;
3512 }
3513
3514 static int ni_m_series_dio_insn_bits(struct comedi_device *dev,
3515                                      struct comedi_subdevice *s,
3516                                      struct comedi_insn *insn,
3517                                      unsigned int *data)
3518 {
3519         if (comedi_dio_update_state(s, data))
3520                 ni_writel(dev, s->state, NI_M_DIO_REG);
3521
3522         data[1] = ni_readl(dev, NI_M_DIO_REG);
3523
3524         return insn->n;
3525 }
3526
3527 static int ni_cdio_check_chanlist(struct comedi_device *dev,
3528                                   struct comedi_subdevice *s,
3529                                   struct comedi_cmd *cmd)
3530 {
3531         int i;
3532
3533         for (i = 0; i < cmd->chanlist_len; ++i) {
3534                 unsigned int chan = CR_CHAN(cmd->chanlist[i]);
3535
3536                 if (chan != i)
3537                         return -EINVAL;
3538         }
3539
3540         return 0;
3541 }
3542
3543 static int ni_cdio_cmdtest(struct comedi_device *dev,
3544                            struct comedi_subdevice *s, struct comedi_cmd *cmd)
3545 {
3546         struct ni_private *devpriv = dev->private;
3547         unsigned int bytes_per_scan;
3548         int err = 0;
3549
3550         /* Step 1 : check if triggers are trivially valid */
3551
3552         err |= comedi_check_trigger_src(&cmd->start_src, TRIG_INT);
3553         err |= comedi_check_trigger_src(&cmd->scan_begin_src, TRIG_EXT);
3554         err |= comedi_check_trigger_src(&cmd->convert_src, TRIG_NOW);
3555         err |= comedi_check_trigger_src(&cmd->scan_end_src, TRIG_COUNT);
3556         err |= comedi_check_trigger_src(&cmd->stop_src, TRIG_NONE);
3557
3558         if (err)
3559                 return 1;
3560
3561         /* Step 2a : make sure trigger sources are unique */
3562         /* Step 2b : and mutually compatible */
3563
3564         /* Step 3: check if arguments are trivially valid */
3565
3566         err |= comedi_check_trigger_arg_is(&cmd->start_arg, 0);
3567
3568         /*
3569          * Although NI_D[IO]_SampleClock are the same, perhaps we should still,
3570          * for completeness, test whether the cmd is output or input?
3571          */
3572         err |= ni_check_trigger_arg(CR_CHAN(cmd->scan_begin_arg),
3573                                     NI_DO_SampleClock,
3574                                     &devpriv->routing_tables);
3575         if (CR_RANGE(cmd->scan_begin_arg) != 0 ||
3576             CR_AREF(cmd->scan_begin_arg) != 0)
3577                 err |= -EINVAL;
3578
3579         err |= comedi_check_trigger_arg_is(&cmd->convert_arg, 0);
3580         err |= comedi_check_trigger_arg_is(&cmd->scan_end_arg,
3581                                            cmd->chanlist_len);
3582         bytes_per_scan = comedi_bytes_per_scan_cmd(s, cmd);
3583         if (bytes_per_scan) {
3584                 err |= comedi_check_trigger_arg_max(&cmd->stop_arg,
3585                                                     s->async->prealloc_bufsz /
3586                                                     bytes_per_scan);
3587         }
3588
3589         if (err)
3590                 return 3;
3591
3592         /* Step 4: fix up any arguments */
3593
3594         /* Step 5: check channel list if it exists */
3595
3596         if (cmd->chanlist && cmd->chanlist_len > 0)
3597                 err |= ni_cdio_check_chanlist(dev, s, cmd);
3598
3599         if (err)
3600                 return 5;
3601
3602         return 0;
3603 }
3604
3605 static int ni_cdo_inttrig(struct comedi_device *dev,
3606                           struct comedi_subdevice *s,
3607                           unsigned int trig_num)
3608 {
3609         struct comedi_cmd *cmd = &s->async->cmd;
3610         const unsigned int timeout = 1000;
3611         int retval = 0;
3612         unsigned int i;
3613         struct ni_private *devpriv = dev->private;
3614         unsigned long flags;
3615
3616         if (trig_num != cmd->start_arg)
3617                 return -EINVAL;
3618
3619         s->async->inttrig = NULL;
3620
3621         /* read alloc the entire buffer */
3622         comedi_buf_read_alloc(s, s->async->prealloc_bufsz);
3623
3624         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
3625         if (devpriv->cdo_mite_chan) {
3626                 mite_prep_dma(devpriv->cdo_mite_chan, 32, 32);
3627                 mite_dma_arm(devpriv->cdo_mite_chan);
3628         } else {
3629                 dev_err(dev->class_dev, "BUG: no cdo mite channel?\n");
3630                 retval = -EIO;
3631         }
3632         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
3633         if (retval < 0)
3634                 return retval;
3635
3636         /*
3637          * XXX not sure what interrupt C group does
3638          * wait for dma to fill output fifo
3639          * ni_writeb(dev, NI_M_INTC_ENA, NI_M_INTC_ENA_REG);
3640          */
3641         for (i = 0; i < timeout; ++i) {
3642                 if (ni_readl(dev, NI_M_CDIO_STATUS_REG) &
3643                     NI_M_CDIO_STATUS_CDO_FIFO_FULL)
3644                         break;
3645                 usleep_range(10, 100);
3646         }
3647         if (i == timeout) {
3648                 dev_err(dev->class_dev, "dma failed to fill cdo fifo!\n");
3649                 s->cancel(dev, s);
3650                 return -EIO;
3651         }
3652         ni_writel(dev, NI_M_CDO_CMD_ARM |
3653                        NI_M_CDO_CMD_ERR_INT_ENA_SET |
3654                        NI_M_CDO_CMD_F_E_INT_ENA_SET,
3655                   NI_M_CDIO_CMD_REG);
3656         return retval;
3657 }
3658
3659 static int ni_cdio_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
3660 {
3661         struct ni_private *devpriv = dev->private;
3662         const struct comedi_cmd *cmd = &s->async->cmd;
3663         unsigned int cdo_mode_bits;
3664         int retval;
3665
3666         ni_writel(dev, NI_M_CDO_CMD_RESET, NI_M_CDIO_CMD_REG);
3667         /*
3668          * Although NI_D[IO]_SampleClock are the same, perhaps we should still,
3669          * for completeness, test whether the cmd is output or input(?)
3670          */
3671         cdo_mode_bits = NI_M_CDO_MODE_FIFO_MODE |
3672                         NI_M_CDO_MODE_HALT_ON_ERROR |
3673                         NI_M_CDO_MODE_SAMPLE_SRC(
3674                                 ni_get_reg_value(CR_CHAN(cmd->scan_begin_arg),
3675                                                  NI_DO_SampleClock,
3676                                                  &devpriv->routing_tables));
3677         if (cmd->scan_begin_arg & CR_INVERT)
3678                 cdo_mode_bits |= NI_M_CDO_MODE_POLARITY;
3679         ni_writel(dev, cdo_mode_bits, NI_M_CDO_MODE_REG);
3680         if (s->io_bits) {
3681                 ni_writel(dev, s->state, NI_M_CDO_FIFO_DATA_REG);
3682                 ni_writel(dev, NI_M_CDO_CMD_SW_UPDATE, NI_M_CDIO_CMD_REG);
3683                 ni_writel(dev, s->io_bits, NI_M_CDO_MASK_ENA_REG);
3684         } else {
3685                 dev_err(dev->class_dev,
3686                         "attempted to run digital output command with no lines configured as outputs\n");
3687                 return -EIO;
3688         }
3689         retval = ni_request_cdo_mite_channel(dev);
3690         if (retval < 0)
3691                 return retval;
3692
3693         ni_cmd_set_mite_transfer(devpriv->cdo_mite_ring, s, cmd,
3694                                  s->async->prealloc_bufsz /
3695                                  comedi_bytes_per_scan(s));
3696
3697         s->async->inttrig = ni_cdo_inttrig;
3698
3699         return 0;
3700 }
3701
3702 static int ni_cdio_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
3703 {
3704         ni_writel(dev, NI_M_CDO_CMD_DISARM |
3705                        NI_M_CDO_CMD_ERR_INT_ENA_CLR |
3706                        NI_M_CDO_CMD_F_E_INT_ENA_CLR |
3707                        NI_M_CDO_CMD_F_REQ_INT_ENA_CLR,
3708                   NI_M_CDIO_CMD_REG);
3709         /*
3710          * XXX not sure what interrupt C group does
3711          * ni_writeb(dev, 0, NI_M_INTC_ENA_REG);
3712          */
3713         ni_writel(dev, 0, NI_M_CDO_MASK_ENA_REG);
3714         ni_release_cdo_mite_channel(dev);
3715         return 0;
3716 }
3717
3718 static void handle_cdio_interrupt(struct comedi_device *dev)
3719 {
3720         struct ni_private *devpriv = dev->private;
3721         unsigned int cdio_status;
3722         struct comedi_subdevice *s = &dev->subdevices[NI_DIO_SUBDEV];
3723         unsigned long flags;
3724
3725         spin_lock_irqsave(&devpriv->mite_channel_lock, flags);
3726         if (devpriv->cdo_mite_chan)
3727                 mite_ack_linkc(devpriv->cdo_mite_chan, s, true);
3728         spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags);
3729
3730         cdio_status = ni_readl(dev, NI_M_CDIO_STATUS_REG);
3731         if (cdio_status & NI_M_CDIO_STATUS_CDO_ERROR) {
3732                 /* XXX just guessing this is needed and does something useful */
3733                 ni_writel(dev, NI_M_CDO_CMD_ERR_INT_CONFIRM,
3734                           NI_M_CDIO_CMD_REG);
3735                 s->async->events |= COMEDI_CB_OVERFLOW;
3736         }
3737         if (cdio_status & NI_M_CDIO_STATUS_CDO_FIFO_EMPTY) {
3738                 ni_writel(dev, NI_M_CDO_CMD_F_E_INT_ENA_CLR,
3739                           NI_M_CDIO_CMD_REG);
3740                 /* s->async->events |= COMEDI_CB_EOA; */
3741         }
3742         comedi_handle_events(dev, s);
3743 }
3744 #endif /*  PCIDMA */
3745
3746 static int ni_serial_hw_readwrite8(struct comedi_device *dev,
3747                                    struct comedi_subdevice *s,
3748                                    unsigned char data_out,
3749                                    unsigned char *data_in)
3750 {
3751         struct ni_private *devpriv = dev->private;
3752         unsigned int status1;
3753         int err = 0, count = 20;
3754
3755         devpriv->dio_output &= ~NISTC_DIO_OUT_SERIAL_MASK;
3756         devpriv->dio_output |= NISTC_DIO_OUT_SERIAL(data_out);
3757         ni_stc_writew(dev, devpriv->dio_output, NISTC_DIO_OUT_REG);
3758
3759         status1 = ni_stc_readw(dev, NISTC_STATUS1_REG);
3760         if (status1 & NISTC_STATUS1_SERIO_IN_PROG) {
3761                 err = -EBUSY;
3762                 goto error;
3763         }
3764
3765         devpriv->dio_control |= NISTC_DIO_CTRL_HW_SER_START;
3766         ni_stc_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);
3767         devpriv->dio_control &= ~NISTC_DIO_CTRL_HW_SER_START;
3768
3769         /* Wait until STC says we're done, but don't loop infinitely. */
3770         while ((status1 = ni_stc_readw(dev, NISTC_STATUS1_REG)) &
3771                NISTC_STATUS1_SERIO_IN_PROG) {
3772                 /* Delay one bit per loop */
3773                 udelay((devpriv->serial_interval_ns + 999) / 1000);
3774                 if (--count < 0) {
3775                         dev_err(dev->class_dev,
3776                                 "SPI serial I/O didn't finish in time!\n");
3777                         err = -ETIME;
3778                         goto error;
3779                 }
3780         }
3781
3782         /*
3783          * Delay for last bit. This delay is absolutely necessary, because
3784          * NISTC_STATUS1_SERIO_IN_PROG goes high one bit too early.
3785          */
3786         udelay((devpriv->serial_interval_ns + 999) / 1000);
3787
3788         if (data_in)
3789                 *data_in = ni_stc_readw(dev, NISTC_DIO_SERIAL_IN_REG);
3790
3791 error:
3792         ni_stc_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);
3793
3794         return err;
3795 }
3796
3797 static int ni_serial_sw_readwrite8(struct comedi_device *dev,
3798                                    struct comedi_subdevice *s,
3799                                    unsigned char data_out,
3800                                    unsigned char *data_in)
3801 {
3802         struct ni_private *devpriv = dev->private;
3803         unsigned char mask, input = 0;
3804
3805         /* Wait for one bit before transfer */
3806         udelay((devpriv->serial_interval_ns + 999) / 1000);
3807
3808         for (mask = 0x80; mask; mask >>= 1) {
3809                 /*
3810                  * Output current bit; note that we cannot touch s->state
3811                  * because it is a per-subdevice field, and serial is
3812                  * a separate subdevice from DIO.
3813                  */
3814                 devpriv->dio_output &= ~NISTC_DIO_SDOUT;
3815                 if (data_out & mask)
3816                         devpriv->dio_output |= NISTC_DIO_SDOUT;
3817                 ni_stc_writew(dev, devpriv->dio_output, NISTC_DIO_OUT_REG);
3818
3819                 /*
3820                  * Assert SDCLK (active low, inverted), wait for half of
3821                  * the delay, deassert SDCLK, and wait for the other half.
3822                  */
3823                 devpriv->dio_control |= NISTC_DIO_SDCLK;
3824                 ni_stc_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);
3825
3826                 udelay((devpriv->serial_interval_ns + 999) / 2000);
3827
3828                 devpriv->dio_control &= ~NISTC_DIO_SDCLK;
3829                 ni_stc_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);
3830
3831                 udelay((devpriv->serial_interval_ns + 999) / 2000);
3832
3833                 /* Input current bit */
3834                 if (ni_stc_readw(dev, NISTC_DIO_IN_REG) & NISTC_DIO_SDIN)
3835                         input |= mask;
3836         }
3837
3838         if (data_in)
3839                 *data_in = input;
3840
3841         return 0;
3842 }
3843
3844 static int ni_serial_insn_config(struct comedi_device *dev,
3845                                  struct comedi_subdevice *s,
3846                                  struct comedi_insn *insn,
3847                                  unsigned int *data)
3848 {
3849         struct ni_private *devpriv = dev->private;
3850         unsigned int clk_fout = devpriv->clock_and_fout;
3851         int err = insn->n;
3852         unsigned char byte_out, byte_in = 0;
3853
3854         if (insn->n != 2)
3855                 return -EINVAL;
3856
3857         switch (data[0]) {
3858         case INSN_CONFIG_SERIAL_CLOCK:
3859                 devpriv->serial_hw_mode = 1;
3860                 devpriv->dio_control |= NISTC_DIO_CTRL_HW_SER_ENA;
3861
3862                 if (data[1] == SERIAL_DISABLED) {
3863                         devpriv->serial_hw_mode = 0;
3864                         devpriv->dio_control &= ~(NISTC_DIO_CTRL_HW_SER_ENA |
3865                                                   NISTC_DIO_SDCLK);
3866                         data[1] = SERIAL_DISABLED;
3867                         devpriv->serial_interval_ns = data[1];
3868                 } else if (data[1] <= SERIAL_600NS) {
3869                         /*
3870                          * Warning: this clock speed is too fast to reliably
3871                          * control SCXI.
3872                          */
3873                         devpriv->dio_control &= ~NISTC_DIO_CTRL_HW_SER_TIMEBASE;
3874                         clk_fout |= NISTC_CLK_FOUT_SLOW_TIMEBASE;
3875                         clk_fout &= ~NISTC_CLK_FOUT_DIO_SER_OUT_DIV2;
3876                         data[1] = SERIAL_600NS;
3877                         devpriv->serial_interval_ns = data[1];
3878                 } else if (data[1] <= SERIAL_1_2US) {
3879                         devpriv->dio_control &= ~NISTC_DIO_CTRL_HW_SER_TIMEBASE;
3880                         clk_fout |= NISTC_CLK_FOUT_SLOW_TIMEBASE |
3881                                     NISTC_CLK_FOUT_DIO_SER_OUT_DIV2;
3882                         data[1] = SERIAL_1_2US;
3883                         devpriv->serial_interval_ns = data[1];
3884                 } else if (data[1] <= SERIAL_10US) {
3885                         devpriv->dio_control |= NISTC_DIO_CTRL_HW_SER_TIMEBASE;
3886                         clk_fout |= NISTC_CLK_FOUT_SLOW_TIMEBASE |
3887                                     NISTC_CLK_FOUT_DIO_SER_OUT_DIV2;
3888                         /*
3889                          * Note: NISTC_CLK_FOUT_DIO_SER_OUT_DIV2 only affects
3890                          * 600ns/1.2us. If you turn divide_by_2 off with the
3891                          * slow clock, you will still get 10us, except then
3892                          * all your delays are wrong.
3893                          */
3894                         data[1] = SERIAL_10US;
3895                         devpriv->serial_interval_ns = data[1];
3896                 } else {
3897                         devpriv->dio_control &= ~(NISTC_DIO_CTRL_HW_SER_ENA |
3898                                                   NISTC_DIO_SDCLK);
3899                         devpriv->serial_hw_mode = 0;
3900                         data[1] = (data[1] / 1000) * 1000;
3901                         devpriv->serial_interval_ns = data[1];
3902                 }
3903                 devpriv->clock_and_fout = clk_fout;
3904
3905                 ni_stc_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);
3906                 ni_stc_writew(dev, devpriv->clock_and_fout, NISTC_CLK_FOUT_REG);
3907                 return 1;
3908
3909         case INSN_CONFIG_BIDIRECTIONAL_DATA:
3910
3911                 if (devpriv->serial_interval_ns == 0)
3912                         return -EINVAL;
3913
3914                 byte_out = data[1] & 0xFF;
3915
3916                 if (devpriv->serial_hw_mode) {
3917                         err = ni_serial_hw_readwrite8(dev, s, byte_out,
3918                                                       &byte_in);
3919                 } else if (devpriv->serial_interval_ns > 0) {
3920                         err = ni_serial_sw_readwrite8(dev, s, byte_out,
3921                                                       &byte_in);
3922                 } else {
3923                         dev_err(dev->class_dev, "serial disabled!\n");
3924                         return -EINVAL;
3925                 }
3926                 if (err < 0)
3927                         return err;
3928                 data[1] = byte_in & 0xFF;
3929                 return insn->n;
3930
3931                 break;
3932         default:
3933                 return -EINVAL;
3934         }
3935 }
3936
3937 static void init_ao_67xx(struct comedi_device *dev, struct comedi_subdevice *s)
3938 {
3939         int i;
3940
3941         for (i = 0; i < s->n_chan; i++) {
3942                 ni_ao_win_outw(dev, NI_E_AO_DACSEL(i) | 0x0,
3943                                NI67XX_AO_CFG2_REG);
3944         }
3945         ni_ao_win_outw(dev, 0x0, NI67XX_AO_SP_UPDATES_REG);
3946 }
3947
3948 static const struct mio_regmap ni_gpct_to_stc_regmap[] = {
3949         [NITIO_G0_AUTO_INC]     = { NISTC_G0_AUTOINC_REG, 2 },
3950         [NITIO_G1_AUTO_INC]     = { NISTC_G1_AUTOINC_REG, 2 },
3951         [NITIO_G0_CMD]          = { NISTC_G0_CMD_REG, 2 },
3952         [NITIO_G1_CMD]          = { NISTC_G1_CMD_REG, 2 },
3953         [NITIO_G0_HW_SAVE]      = { NISTC_G0_HW_SAVE_REG, 4 },
3954         [NITIO_G1_HW_SAVE]      = { NISTC_G1_HW_SAVE_REG, 4 },
3955         [NITIO_G0_SW_SAVE]      = { NISTC_G0_SAVE_REG, 4 },
3956         [NITIO_G1_SW_SAVE]      = { NISTC_G1_SAVE_REG, 4 },
3957         [NITIO_G0_MODE]         = { NISTC_G0_MODE_REG, 2 },
3958         [NITIO_G1_MODE]         = { NISTC_G1_MODE_REG, 2 },
3959         [NITIO_G0_LOADA]        = { NISTC_G0_LOADA_REG, 4 },
3960         [NITIO_G1_LOADA]        = { NISTC_G1_LOADA_REG, 4 },
3961         [NITIO_G0_LOADB]        = { NISTC_G0_LOADB_REG, 4 },
3962         [NITIO_G1_LOADB]        = { NISTC_G1_LOADB_REG, 4 },
3963         [NITIO_G0_INPUT_SEL]    = { NISTC_G0_INPUT_SEL_REG, 2 },
3964         [NITIO_G1_INPUT_SEL]    = { NISTC_G1_INPUT_SEL_REG, 2 },
3965         [NITIO_G0_CNT_MODE]     = { 0x1b0, 2 }, /* M-Series only */
3966         [NITIO_G1_CNT_MODE]     = { 0x1b2, 2 }, /* M-Series only */
3967         [NITIO_G0_GATE2]        = { 0x1b4, 2 }, /* M-Series only */
3968         [NITIO_G1_GATE2]        = { 0x1b6, 2 }, /* M-Series only */
3969         [NITIO_G01_STATUS]      = { NISTC_G01_STATUS_REG, 2 },
3970         [NITIO_G01_RESET]       = { NISTC_RESET_REG, 2 },
3971         [NITIO_G01_STATUS1]     = { NISTC_STATUS1_REG, 2 },
3972         [NITIO_G01_STATUS2]     = { NISTC_STATUS2_REG, 2 },
3973         [NITIO_G0_DMA_CFG]      = { 0x1b8, 2 }, /* M-Series only */
3974         [NITIO_G1_DMA_CFG]      = { 0x1ba, 2 }, /* M-Series only */
3975         [NITIO_G0_DMA_STATUS]   = { 0x1b8, 2 }, /* M-Series only */
3976         [NITIO_G1_DMA_STATUS]   = { 0x1ba, 2 }, /* M-Series only */
3977         [NITIO_G0_ABZ]          = { 0x1c0, 2 }, /* M-Series only */
3978         [NITIO_G1_ABZ]          = { 0x1c2, 2 }, /* M-Series only */
3979         [NITIO_G0_INT_ACK]      = { NISTC_INTA_ACK_REG, 2 },
3980         [NITIO_G1_INT_ACK]      = { NISTC_INTB_ACK_REG, 2 },
3981         [NITIO_G0_STATUS]       = { NISTC_AI_STATUS1_REG, 2 },
3982         [NITIO_G1_STATUS]       = { NISTC_AO_STATUS1_REG, 2 },
3983         [NITIO_G0_INT_ENA]      = { NISTC_INTA_ENA_REG, 2 },
3984         [NITIO_G1_INT_ENA]      = { NISTC_INTB_ENA_REG, 2 },
3985 };
3986
3987 static unsigned int ni_gpct_to_stc_register(struct comedi_device *dev,
3988                                             enum ni_gpct_register reg)
3989 {
3990         const struct mio_regmap *regmap;
3991
3992         if (reg < ARRAY_SIZE(ni_gpct_to_stc_regmap)) {
3993                 regmap = &ni_gpct_to_stc_regmap[reg];
3994         } else {
3995                 dev_warn(dev->class_dev, "%s: unhandled register=0x%x\n",
3996                          __func__, reg);
3997                 return 0;
3998         }
3999
4000         return regmap->mio_reg;
4001 }
4002
4003 static void ni_gpct_write_register(struct ni_gpct *counter, unsigned int bits,
4004                                    enum ni_gpct_register reg)
4005 {
4006         struct comedi_device *dev = counter->counter_dev->dev;
4007         unsigned int stc_register = ni_gpct_to_stc_register(dev, reg);
4008
4009         if (stc_register == 0)
4010                 return;
4011
4012         switch (reg) {
4013                 /* m-series only registers */
4014         case NITIO_G0_CNT_MODE:
4015         case NITIO_G1_CNT_MODE:
4016         case NITIO_G0_GATE2:
4017         case NITIO_G1_GATE2:
4018         case NITIO_G0_DMA_CFG:
4019         case NITIO_G1_DMA_CFG:
4020         case NITIO_G0_ABZ:
4021         case NITIO_G1_ABZ:
4022                 ni_writew(dev, bits, stc_register);
4023                 break;
4024
4025                 /* 32 bit registers */
4026         case NITIO_G0_LOADA:
4027         case NITIO_G1_LOADA:
4028         case NITIO_G0_LOADB:
4029         case NITIO_G1_LOADB:
4030                 ni_stc_writel(dev, bits, stc_register);
4031                 break;
4032
4033                 /* 16 bit registers */
4034         case NITIO_G0_INT_ENA:
4035                 ni_set_bitfield(dev, stc_register,
4036                                 NISTC_INTA_ENA_G0_GATE | NISTC_INTA_ENA_G0_TC,
4037                                 bits);
4038                 break;
4039         case NITIO_G1_INT_ENA:
4040                 ni_set_bitfield(dev, stc_register,
4041                                 NISTC_INTB_ENA_G1_GATE | NISTC_INTB_ENA_G1_TC,
4042                                 bits);
4043                 break;
4044         default:
4045                 ni_stc_writew(dev, bits, stc_register);
4046         }
4047 }
4048
4049 static unsigned int ni_gpct_read_register(struct ni_gpct *counter,
4050                                           enum ni_gpct_register reg)
4051 {
4052         struct comedi_device *dev = counter->counter_dev->dev;
4053         unsigned int stc_register = ni_gpct_to_stc_register(dev, reg);
4054
4055         if (stc_register == 0)
4056                 return 0;
4057
4058         switch (reg) {
4059                 /* m-series only registers */
4060         case NITIO_G0_DMA_STATUS:
4061         case NITIO_G1_DMA_STATUS:
4062                 return ni_readw(dev, stc_register);
4063
4064                 /* 32 bit registers */
4065         case NITIO_G0_HW_SAVE:
4066         case NITIO_G1_HW_SAVE:
4067         case NITIO_G0_SW_SAVE:
4068         case NITIO_G1_SW_SAVE:
4069                 return ni_stc_readl(dev, stc_register);
4070
4071                 /* 16 bit registers */
4072         default:
4073                 return ni_stc_readw(dev, stc_register);
4074         }
4075 }
4076
4077 static int ni_freq_out_insn_read(struct comedi_device *dev,
4078                                  struct comedi_subdevice *s,
4079                                  struct comedi_insn *insn,
4080                                  unsigned int *data)
4081 {
4082         struct ni_private *devpriv = dev->private;
4083         unsigned int val = NISTC_CLK_FOUT_TO_DIVIDER(devpriv->clock_and_fout);
4084         int i;
4085
4086         for (i = 0; i < insn->n; i++)
4087                 data[i] = val;
4088
4089         return insn->n;
4090 }
4091
4092 static int ni_freq_out_insn_write(struct comedi_device *dev,
4093                                   struct comedi_subdevice *s,
4094                                   struct comedi_insn *insn,
4095                                   unsigned int *data)
4096 {
4097         struct ni_private *devpriv = dev->private;
4098
4099         if (insn->n) {
4100                 unsigned int val = data[insn->n - 1];
4101
4102                 devpriv->clock_and_fout &= ~NISTC_CLK_FOUT_ENA;
4103                 ni_stc_writew(dev, devpriv->clock_and_fout, NISTC_CLK_FOUT_REG);
4104                 devpriv->clock_and_fout &= ~NISTC_CLK_FOUT_DIVIDER_MASK;
4105
4106                 /* use the last data value to set the fout divider */
4107                 devpriv->clock_and_fout |= NISTC_CLK_FOUT_DIVIDER(val);
4108
4109                 devpriv->clock_and_fout |= NISTC_CLK_FOUT_ENA;
4110                 ni_stc_writew(dev, devpriv->clock_and_fout, NISTC_CLK_FOUT_REG);
4111         }
4112         return insn->n;
4113 }
4114
4115 static int ni_freq_out_insn_config(struct comedi_device *dev,
4116                                    struct comedi_subdevice *s,
4117                                    struct comedi_insn *insn,
4118                                    unsigned int *data)
4119 {
4120         struct ni_private *devpriv = dev->private;
4121
4122         switch (data[0]) {
4123         case INSN_CONFIG_SET_CLOCK_SRC:
4124                 switch (data[1]) {
4125                 case NI_FREQ_OUT_TIMEBASE_1_DIV_2_CLOCK_SRC:
4126                         devpriv->clock_and_fout &= ~NISTC_CLK_FOUT_TIMEBASE_SEL;
4127                         break;
4128                 case NI_FREQ_OUT_TIMEBASE_2_CLOCK_SRC:
4129                         devpriv->clock_and_fout |= NISTC_CLK_FOUT_TIMEBASE_SEL;
4130                         break;
4131                 default:
4132                         return -EINVAL;
4133                 }
4134                 ni_stc_writew(dev, devpriv->clock_and_fout, NISTC_CLK_FOUT_REG);
4135                 break;
4136         case INSN_CONFIG_GET_CLOCK_SRC:
4137                 if (devpriv->clock_and_fout & NISTC_CLK_FOUT_TIMEBASE_SEL) {
4138                         data[1] = NI_FREQ_OUT_TIMEBASE_2_CLOCK_SRC;
4139                         data[2] = TIMEBASE_2_NS;
4140                 } else {
4141                         data[1] = NI_FREQ_OUT_TIMEBASE_1_DIV_2_CLOCK_SRC;
4142                         data[2] = TIMEBASE_1_NS * 2;
4143                 }
4144                 break;
4145         default:
4146                 return -EINVAL;
4147         }
4148         return insn->n;
4149 }
4150
4151 static int ni_8255_callback(struct comedi_device *dev,
4152                             int dir, int port, int data, unsigned long iobase)
4153 {
4154         if (dir) {
4155                 ni_writeb(dev, data, iobase + 2 * port);
4156                 return 0;
4157         }
4158
4159         return ni_readb(dev, iobase + 2 * port);
4160 }
4161
4162 static int ni_get_pwm_config(struct comedi_device *dev, unsigned int *data)
4163 {
4164         struct ni_private *devpriv = dev->private;
4165
4166         data[1] = devpriv->pwm_up_count * devpriv->clock_ns;
4167         data[2] = devpriv->pwm_down_count * devpriv->clock_ns;
4168         return 3;
4169 }
4170
4171 static int ni_m_series_pwm_config(struct comedi_device *dev,
4172                                   struct comedi_subdevice *s,
4173                                   struct comedi_insn *insn,
4174                                   unsigned int *data)
4175 {
4176         struct ni_private *devpriv = dev->private;
4177         unsigned int up_count, down_count;
4178
4179         switch (data[0]) {
4180         case INSN_CONFIG_PWM_OUTPUT:
4181                 switch (data[1]) {
4182                 case CMDF_ROUND_NEAREST:
4183                         up_count = DIV_ROUND_CLOSEST(data[2],
4184                                                      devpriv->clock_ns);
4185                         break;
4186                 case CMDF_ROUND_DOWN:
4187                         up_count = data[2] / devpriv->clock_ns;
4188                         break;
4189                 case CMDF_ROUND_UP:
4190                         up_count =
4191                             DIV_ROUND_UP(data[2], devpriv->clock_ns);
4192                         break;
4193                 default:
4194                         return -EINVAL;
4195                 }
4196                 switch (data[3]) {
4197                 case CMDF_ROUND_NEAREST:
4198                         down_count = DIV_ROUND_CLOSEST(data[4],
4199                                                        devpriv->clock_ns);
4200                         break;
4201                 case CMDF_ROUND_DOWN:
4202                         down_count = data[4] / devpriv->clock_ns;
4203                         break;
4204                 case CMDF_ROUND_UP:
4205                         down_count =
4206                             DIV_ROUND_UP(data[4], devpriv->clock_ns);
4207                         break;
4208                 default:
4209                         return -EINVAL;
4210                 }
4211                 if (up_count * devpriv->clock_ns != data[2] ||
4212                     down_count * devpriv->clock_ns != data[4]) {
4213                         data[2] = up_count * devpriv->clock_ns;
4214                         data[4] = down_count * devpriv->clock_ns;
4215                         return -EAGAIN;
4216                 }
4217                 ni_writel(dev, NI_M_CAL_PWM_HIGH_TIME(up_count) |
4218                                NI_M_CAL_PWM_LOW_TIME(down_count),
4219                           NI_M_CAL_PWM_REG);
4220                 devpriv->pwm_up_count = up_count;
4221                 devpriv->pwm_down_count = down_count;
4222                 return 5;
4223         case INSN_CONFIG_GET_PWM_OUTPUT:
4224                 return ni_get_pwm_config(dev, data);
4225         default:
4226                 return -EINVAL;
4227         }
4228         return 0;
4229 }
4230
4231 static int ni_6143_pwm_config(struct comedi_device *dev,
4232                               struct comedi_subdevice *s,
4233                               struct comedi_insn *insn,
4234                               unsigned int *data)
4235 {
4236         struct ni_private *devpriv = dev->private;
4237         unsigned int up_count, down_count;
4238
4239         switch (data[0]) {
4240         case INSN_CONFIG_PWM_OUTPUT:
4241                 switch (data[1]) {
4242                 case CMDF_ROUND_NEAREST:
4243                         up_count = DIV_ROUND_CLOSEST(data[2],
4244                                                      devpriv->clock_ns);
4245                         break;
4246                 case CMDF_ROUND_DOWN:
4247                         up_count = data[2] / devpriv->clock_ns;
4248                         break;
4249                 case CMDF_ROUND_UP:
4250                         up_count =
4251                             DIV_ROUND_UP(data[2], devpriv->clock_ns);
4252                         break;
4253                 default:
4254                         return -EINVAL;
4255                 }
4256                 switch (data[3]) {
4257                 case CMDF_ROUND_NEAREST:
4258                         down_count = DIV_ROUND_CLOSEST(data[4],
4259                                                        devpriv->clock_ns);
4260                         break;
4261                 case CMDF_ROUND_DOWN:
4262                         down_count = data[4] / devpriv->clock_ns;
4263                         break;
4264                 case CMDF_ROUND_UP:
4265                         down_count =
4266                             DIV_ROUND_UP(data[4], devpriv->clock_ns);
4267                         break;
4268                 default:
4269                         return -EINVAL;
4270                 }
4271                 if (up_count * devpriv->clock_ns != data[2] ||
4272                     down_count * devpriv->clock_ns != data[4]) {
4273                         data[2] = up_count * devpriv->clock_ns;
4274                         data[4] = down_count * devpriv->clock_ns;
4275                         return -EAGAIN;
4276                 }
4277                 ni_writel(dev, up_count, NI6143_CALIB_HI_TIME_REG);
4278                 devpriv->pwm_up_count = up_count;
4279                 ni_writel(dev, down_count, NI6143_CALIB_LO_TIME_REG);
4280                 devpriv->pwm_down_count = down_count;
4281                 return 5;
4282         case INSN_CONFIG_GET_PWM_OUTPUT:
4283                 return ni_get_pwm_config(dev, data);
4284         default:
4285                 return -EINVAL;
4286         }
4287         return 0;
4288 }
4289
4290 static int pack_mb88341(int addr, int val, int *bitstring)
4291 {
4292         /*
4293          * Fujitsu MB 88341
4294          * Note that address bits are reversed.  Thanks to
4295          * Ingo Keen for noticing this.
4296          *
4297          * Note also that the 88341 expects address values from
4298          * 1-12, whereas we use channel numbers 0-11.  The NI
4299          * docs use 1-12, also, so be careful here.
4300          */
4301         addr++;
4302         *bitstring = ((addr & 0x1) << 11) |
4303             ((addr & 0x2) << 9) |
4304             ((addr & 0x4) << 7) | ((addr & 0x8) << 5) | (val & 0xff);
4305         return 12;
4306 }
4307
4308 static int pack_dac8800(int addr, int val, int *bitstring)
4309 {
4310         *bitstring = ((addr & 0x7) << 8) | (val & 0xff);
4311         return 11;
4312 }
4313
4314 static int pack_dac8043(int addr, int val, int *bitstring)
4315 {
4316         *bitstring = val & 0xfff;
4317         return 12;
4318 }
4319
4320 static int pack_ad8522(int addr, int val, int *bitstring)
4321 {
4322         *bitstring = (val & 0xfff) | (addr ? 0xc000 : 0xa000);
4323         return 16;
4324 }
4325
4326 static int pack_ad8804(int addr, int val, int *bitstring)
4327 {
4328         *bitstring = ((addr & 0xf) << 8) | (val & 0xff);
4329         return 12;
4330 }
4331
4332 static int pack_ad8842(int addr, int val, int *bitstring)
4333 {
4334         *bitstring = ((addr + 1) << 8) | (val & 0xff);
4335         return 12;
4336 }
4337
4338 struct caldac_struct {
4339         int n_chans;
4340         int n_bits;
4341         int (*packbits)(int address, int value, int *bitstring);
4342 };
4343
4344 static struct caldac_struct caldacs[] = {
4345         [mb88341] = {12, 8, pack_mb88341},
4346         [dac8800] = {8, 8, pack_dac8800},
4347         [dac8043] = {1, 12, pack_dac8043},
4348         [ad8522] = {2, 12, pack_ad8522},
4349         [ad8804] = {12, 8, pack_ad8804},
4350         [ad8842] = {8, 8, pack_ad8842},
4351         [ad8804_debug] = {16, 8, pack_ad8804},
4352 };
4353
4354 static void ni_write_caldac(struct comedi_device *dev, int addr, int val)
4355 {
4356         const struct ni_board_struct *board = dev->board_ptr;
4357         struct ni_private *devpriv = dev->private;
4358         unsigned int loadbit = 0, bits = 0, bit, bitstring = 0;
4359         unsigned int cmd;
4360         int i;
4361         int type;
4362
4363         if (devpriv->caldacs[addr] == val)
4364                 return;
4365         devpriv->caldacs[addr] = val;
4366
4367         for (i = 0; i < 3; i++) {
4368                 type = board->caldac[i];
4369                 if (type == caldac_none)
4370                         break;
4371                 if (addr < caldacs[type].n_chans) {
4372                         bits = caldacs[type].packbits(addr, val, &bitstring);
4373                         loadbit = NI_E_SERIAL_CMD_DAC_LD(i);
4374                         break;
4375                 }
4376                 addr -= caldacs[type].n_chans;
4377         }
4378
4379         /* bits will be 0 if there is no caldac for the given addr */
4380         if (bits == 0)
4381                 return;
4382
4383         for (bit = 1 << (bits - 1); bit; bit >>= 1) {
4384                 cmd = (bit & bitstring) ? NI_E_SERIAL_CMD_SDATA : 0;
4385                 ni_writeb(dev, cmd, NI_E_SERIAL_CMD_REG);
4386                 udelay(1);
4387                 ni_writeb(dev, NI_E_SERIAL_CMD_SCLK | cmd, NI_E_SERIAL_CMD_REG);
4388                 udelay(1);
4389         }
4390         ni_writeb(dev, loadbit, NI_E_SERIAL_CMD_REG);
4391         udelay(1);
4392         ni_writeb(dev, 0, NI_E_SERIAL_CMD_REG);
4393 }
4394
4395 static int ni_calib_insn_write(struct comedi_device *dev,
4396                                struct comedi_subdevice *s,
4397                                struct comedi_insn *insn,
4398                                unsigned int *data)
4399 {
4400         ni_write_caldac(dev, CR_CHAN(insn->chanspec), data[0]);
4401
4402         return 1;
4403 }
4404
4405 static int ni_calib_insn_read(struct comedi_device *dev,
4406                               struct comedi_subdevice *s,
4407                               struct comedi_insn *insn,
4408                               unsigned int *data)
4409 {
4410         struct ni_private *devpriv = dev->private;
4411
4412         data[0] = devpriv->caldacs[CR_CHAN(insn->chanspec)];
4413
4414         return 1;
4415 }
4416
4417 static void caldac_setup(struct comedi_device *dev, struct comedi_subdevice *s)
4418 {
4419         const struct ni_board_struct *board = dev->board_ptr;
4420         struct ni_private *devpriv = dev->private;
4421         int i, j;
4422         int n_dacs;
4423         int n_chans = 0;
4424         int n_bits;
4425         int diffbits = 0;
4426         int type;
4427         int chan;
4428
4429         type = board->caldac[0];
4430         if (type == caldac_none)
4431                 return;
4432         n_bits = caldacs[type].n_bits;
4433         for (i = 0; i < 3; i++) {
4434                 type = board->caldac[i];
4435                 if (type == caldac_none)
4436                         break;
4437                 if (caldacs[type].n_bits != n_bits)
4438                         diffbits = 1;
4439                 n_chans += caldacs[type].n_chans;
4440         }
4441         n_dacs = i;
4442         s->n_chan = n_chans;
4443
4444         if (diffbits) {
4445                 unsigned int *maxdata_list = devpriv->caldac_maxdata_list;
4446
4447                 if (n_chans > MAX_N_CALDACS)
4448                         dev_err(dev->class_dev,
4449                                 "BUG! MAX_N_CALDACS too small\n");
4450                 s->maxdata_list = maxdata_list;
4451                 chan = 0;
4452                 for (i = 0; i < n_dacs; i++) {
4453                         type = board->caldac[i];
4454                         for (j = 0; j < caldacs[type].n_chans; j++) {
4455                                 maxdata_list[chan] =
4456                                     (1 << caldacs[type].n_bits) - 1;
4457                                 chan++;
4458                         }
4459                 }
4460
4461                 for (chan = 0; chan < s->n_chan; chan++)
4462                         ni_write_caldac(dev, i, s->maxdata_list[i] / 2);
4463         } else {
4464                 type = board->caldac[0];
4465                 s->maxdata = (1 << caldacs[type].n_bits) - 1;
4466
4467                 for (chan = 0; chan < s->n_chan; chan++)
4468                         ni_write_caldac(dev, i, s->maxdata / 2);
4469         }
4470 }
4471
4472 static int ni_read_eeprom(struct comedi_device *dev, int addr)
4473 {
4474         unsigned int cmd = NI_E_SERIAL_CMD_EEPROM_CS;
4475         int bit;
4476         int bitstring;
4477
4478         bitstring = 0x0300 | ((addr & 0x100) << 3) | (addr & 0xff);
4479         ni_writeb(dev, cmd, NI_E_SERIAL_CMD_REG);
4480         for (bit = 0x8000; bit; bit >>= 1) {
4481                 if (bit & bitstring)
4482                         cmd |= NI_E_SERIAL_CMD_SDATA;
4483                 else
4484                         cmd &= ~NI_E_SERIAL_CMD_SDATA;
4485
4486                 ni_writeb(dev, cmd, NI_E_SERIAL_CMD_REG);
4487                 ni_writeb(dev, NI_E_SERIAL_CMD_SCLK | cmd, NI_E_SERIAL_CMD_REG);
4488         }
4489         cmd = NI_E_SERIAL_CMD_EEPROM_CS;
4490         bitstring = 0;
4491         for (bit = 0x80; bit; bit >>= 1) {
4492                 ni_writeb(dev, cmd, NI_E_SERIAL_CMD_REG);
4493                 ni_writeb(dev, NI_E_SERIAL_CMD_SCLK | cmd, NI_E_SERIAL_CMD_REG);
4494                 if (ni_readb(dev, NI_E_STATUS_REG) & NI_E_STATUS_PROMOUT)
4495                         bitstring |= bit;
4496         }
4497         ni_writeb(dev, 0, NI_E_SERIAL_CMD_REG);
4498
4499         return bitstring;
4500 }
4501
4502 static int ni_eeprom_insn_read(struct comedi_device *dev,
4503                                struct comedi_subdevice *s,
4504                                struct comedi_insn *insn,
4505                                unsigned int *data)
4506 {
4507         data[0] = ni_read_eeprom(dev, CR_CHAN(insn->chanspec));
4508
4509         return 1;
4510 }
4511
4512 static int ni_m_series_eeprom_insn_read(struct comedi_device *dev,
4513                                         struct comedi_subdevice *s,
4514                                         struct comedi_insn *insn,
4515                                         unsigned int *data)
4516 {
4517         struct ni_private *devpriv = dev->private;
4518
4519         data[0] = devpriv->eeprom_buffer[CR_CHAN(insn->chanspec)];
4520
4521         return 1;
4522 }
4523
4524 static unsigned int ni_old_get_pfi_routing(struct comedi_device *dev,
4525                                            unsigned int chan)
4526 {
4527         /*  pre-m-series boards have fixed signals on pfi pins */
4528         switch (chan) {
4529         case 0:
4530                 return NI_PFI_OUTPUT_AI_START1;
4531         case 1:
4532                 return NI_PFI_OUTPUT_AI_START2;
4533         case 2:
4534                 return NI_PFI_OUTPUT_AI_CONVERT;
4535         case 3:
4536                 return NI_PFI_OUTPUT_G_SRC1;
4537         case 4:
4538                 return NI_PFI_OUTPUT_G_GATE1;
4539         case 5:
4540                 return NI_PFI_OUTPUT_AO_UPDATE_N;
4541         case 6:
4542                 return NI_PFI_OUTPUT_AO_START1;
4543         case 7:
4544                 return NI_PFI_OUTPUT_AI_START_PULSE;
4545         case 8:
4546                 return NI_PFI_OUTPUT_G_SRC0;
4547         case 9:
4548                 return NI_PFI_OUTPUT_G_GATE0;
4549         default:
4550                 dev_err(dev->class_dev, "bug, unhandled case in switch.\n");
4551                 break;
4552         }
4553         return 0;
4554 }
4555
4556 static int ni_old_set_pfi_routing(struct comedi_device *dev,
4557                                   unsigned int chan, unsigned int source)
4558 {
4559         /*  pre-m-series boards have fixed signals on pfi pins */
4560         if (source != ni_old_get_pfi_routing(dev, chan))
4561                 return -EINVAL;
4562         return 2;
4563 }
4564
4565 static unsigned int ni_m_series_get_pfi_routing(struct comedi_device *dev,
4566                                                 unsigned int chan)
4567 {
4568         struct ni_private *devpriv = dev->private;
4569         const unsigned int array_offset = chan / 3;
4570
4571         return NI_M_PFI_OUT_SEL_TO_SRC(chan,
4572                                 devpriv->pfi_output_select_reg[array_offset]);
4573 }
4574
4575 static int ni_m_series_set_pfi_routing(struct comedi_device *dev,
4576                                        unsigned int chan, unsigned int source)
4577 {
4578         struct ni_private *devpriv = dev->private;
4579         unsigned int index = chan / 3;
4580         unsigned short val = devpriv->pfi_output_select_reg[index];
4581
4582         if ((source & 0x1f) != source)
4583                 return -EINVAL;
4584
4585         val &= ~NI_M_PFI_OUT_SEL_MASK(chan);
4586         val |= NI_M_PFI_OUT_SEL(chan, source);
4587         ni_writew(dev, val, NI_M_PFI_OUT_SEL_REG(index));
4588         devpriv->pfi_output_select_reg[index] = val;
4589
4590         return 2;
4591 }
4592
4593 static unsigned int ni_get_pfi_routing(struct comedi_device *dev,
4594                                        unsigned int chan)
4595 {
4596         struct ni_private *devpriv = dev->private;
4597
4598         if (chan >= NI_PFI(0)) {
4599                 /* allow new and old names of pfi channels to work. */
4600                 chan -= NI_PFI(0);
4601         }
4602         return (devpriv->is_m_series)
4603                         ? ni_m_series_get_pfi_routing(dev, chan)
4604                         : ni_old_get_pfi_routing(dev, chan);
4605 }
4606
4607 /* Sets the output mux for the specified PFI channel. */
4608 static int ni_set_pfi_routing(struct comedi_device *dev,
4609                               unsigned int chan, unsigned int source)
4610 {
4611         struct ni_private *devpriv = dev->private;
4612
4613         if (chan >= NI_PFI(0)) {
4614                 /* allow new and old names of pfi channels to work. */
4615                 chan -= NI_PFI(0);
4616         }
4617         return (devpriv->is_m_series)
4618                         ? ni_m_series_set_pfi_routing(dev, chan, source)
4619                         : ni_old_set_pfi_routing(dev, chan, source);
4620 }
4621
4622 static int ni_config_pfi_filter(struct comedi_device *dev,
4623                                 unsigned int chan,
4624                                 enum ni_pfi_filter_select filter)
4625 {
4626         struct ni_private *devpriv = dev->private;
4627         unsigned int bits;
4628
4629         if (!devpriv->is_m_series)
4630                 return -ENOTSUPP;
4631
4632         if (chan >= NI_PFI(0)) {
4633                 /* allow new and old names of pfi channels to work. */
4634                 chan -= NI_PFI(0);
4635         }
4636
4637         bits = ni_readl(dev, NI_M_PFI_FILTER_REG);
4638         bits &= ~NI_M_PFI_FILTER_SEL_MASK(chan);
4639         bits |= NI_M_PFI_FILTER_SEL(chan, filter);
4640         ni_writel(dev, bits, NI_M_PFI_FILTER_REG);
4641         return 0;
4642 }
4643
4644 static void ni_set_pfi_direction(struct comedi_device *dev, int chan,
4645                                  unsigned int direction)
4646 {
4647         if (chan >= NI_PFI(0)) {
4648                 /* allow new and old names of pfi channels to work. */
4649                 chan -= NI_PFI(0);
4650         }
4651         direction = (direction == COMEDI_OUTPUT) ? 1u : 0u;
4652         ni_set_bits(dev, NISTC_IO_BIDIR_PIN_REG, 1 << chan, direction);
4653 }
4654
4655 static int ni_get_pfi_direction(struct comedi_device *dev, int chan)
4656 {
4657         struct ni_private *devpriv = dev->private;
4658
4659         if (chan >= NI_PFI(0)) {
4660                 /* allow new and old names of pfi channels to work. */
4661                 chan -= NI_PFI(0);
4662         }
4663         return devpriv->io_bidirection_pin_reg & (1 << chan) ?
4664                COMEDI_OUTPUT : COMEDI_INPUT;
4665 }
4666
4667 static int ni_pfi_insn_config(struct comedi_device *dev,
4668                               struct comedi_subdevice *s,
4669                               struct comedi_insn *insn,
4670                               unsigned int *data)
4671 {
4672         unsigned int chan;
4673
4674         if (insn->n < 1)
4675                 return -EINVAL;
4676
4677         chan = CR_CHAN(insn->chanspec);
4678
4679         switch (data[0]) {
4680         case COMEDI_OUTPUT:
4681         case COMEDI_INPUT:
4682                 ni_set_pfi_direction(dev, chan, data[0]);
4683                 break;
4684         case INSN_CONFIG_DIO_QUERY:
4685                 data[1] = ni_get_pfi_direction(dev, chan);
4686                 break;
4687         case INSN_CONFIG_SET_ROUTING:
4688                 return ni_set_pfi_routing(dev, chan, data[1]);
4689         case INSN_CONFIG_GET_ROUTING:
4690                 data[1] = ni_get_pfi_routing(dev, chan);
4691                 break;
4692         case INSN_CONFIG_FILTER:
4693                 return ni_config_pfi_filter(dev, chan, data[1]);
4694         default:
4695                 return -EINVAL;
4696         }
4697         return 0;
4698 }
4699
4700 static int ni_pfi_insn_bits(struct comedi_device *dev,
4701                             struct comedi_subdevice *s,
4702                             struct comedi_insn *insn,
4703                             unsigned int *data)
4704 {
4705         struct ni_private *devpriv = dev->private;
4706
4707         if (!devpriv->is_m_series)
4708                 return -ENOTSUPP;
4709
4710         if (comedi_dio_update_state(s, data))
4711                 ni_writew(dev, s->state, NI_M_PFI_DO_REG);
4712
4713         data[1] = ni_readw(dev, NI_M_PFI_DI_REG);
4714
4715         return insn->n;
4716 }
4717
4718 static int cs5529_wait_for_idle(struct comedi_device *dev)
4719 {
4720         unsigned short status;
4721         const int timeout = HZ;
4722         int i;
4723
4724         for (i = 0; i < timeout; i++) {
4725                 status = ni_ao_win_inw(dev, NI67XX_CAL_STATUS_REG);
4726                 if ((status & NI67XX_CAL_STATUS_BUSY) == 0)
4727                         break;
4728                 set_current_state(TASK_INTERRUPTIBLE);
4729                 if (schedule_timeout(1))
4730                         return -EIO;
4731         }
4732         if (i == timeout) {
4733                 dev_err(dev->class_dev, "timeout\n");
4734                 return -ETIME;
4735         }
4736         return 0;
4737 }
4738
4739 static void cs5529_command(struct comedi_device *dev, unsigned short value)
4740 {
4741         static const int timeout = 100;
4742         int i;
4743
4744         ni_ao_win_outw(dev, value, NI67XX_CAL_CMD_REG);
4745         /* give time for command to start being serially clocked into cs5529.
4746          * this insures that the NI67XX_CAL_STATUS_BUSY bit will get properly
4747          * set before we exit this function.
4748          */
4749         for (i = 0; i < timeout; i++) {
4750                 if (ni_ao_win_inw(dev, NI67XX_CAL_STATUS_REG) &
4751                     NI67XX_CAL_STATUS_BUSY)
4752                         break;
4753                 udelay(1);
4754         }
4755         if (i == timeout)
4756                 dev_err(dev->class_dev,
4757                         "possible problem - never saw adc go busy?\n");
4758 }
4759
4760 static int cs5529_do_conversion(struct comedi_device *dev,
4761                                 unsigned short *data)
4762 {
4763         int retval;
4764         unsigned short status;
4765
4766         cs5529_command(dev, CS5529_CMD_CB | CS5529_CMD_SINGLE_CONV);
4767         retval = cs5529_wait_for_idle(dev);
4768         if (retval) {
4769                 dev_err(dev->class_dev,
4770                         "timeout or signal in %s()\n", __func__);
4771                 return -ETIME;
4772         }
4773         status = ni_ao_win_inw(dev, NI67XX_CAL_STATUS_REG);
4774         if (status & NI67XX_CAL_STATUS_OSC_DETECT) {
4775                 dev_err(dev->class_dev,
4776                         "cs5529 conversion error, status CSS_OSC_DETECT\n");
4777                 return -EIO;
4778         }
4779         if (status & NI67XX_CAL_STATUS_OVERRANGE) {
4780                 dev_err(dev->class_dev,
4781                         "cs5529 conversion error, overrange (ignoring)\n");
4782         }
4783         if (data) {
4784                 *data = ni_ao_win_inw(dev, NI67XX_CAL_DATA_REG);
4785                 /* cs5529 returns 16 bit signed data in bipolar mode */
4786                 *data ^= (1 << 15);
4787         }
4788         return 0;
4789 }
4790
4791 static int cs5529_ai_insn_read(struct comedi_device *dev,
4792                                struct comedi_subdevice *s,
4793                                struct comedi_insn *insn,
4794                                unsigned int *data)
4795 {
4796         int n, retval;
4797         unsigned short sample;
4798         unsigned int channel_select;
4799         const unsigned int INTERNAL_REF = 0x1000;
4800
4801         /*
4802          * Set calibration adc source.  Docs lie, reference select bits 8 to 11
4803          * do nothing. bit 12 seems to chooses internal reference voltage, bit
4804          * 13 causes the adc input to go overrange (maybe reads external
4805          * reference?)
4806          */
4807         if (insn->chanspec & CR_ALT_SOURCE)
4808                 channel_select = INTERNAL_REF;
4809         else
4810                 channel_select = CR_CHAN(insn->chanspec);
4811         ni_ao_win_outw(dev, channel_select, NI67XX_AO_CAL_CHAN_SEL_REG);
4812
4813         for (n = 0; n < insn->n; n++) {
4814                 retval = cs5529_do_conversion(dev, &sample);
4815                 if (retval < 0)
4816                         return retval;
4817                 data[n] = sample;
4818         }
4819         return insn->n;
4820 }
4821
4822 static void cs5529_config_write(struct comedi_device *dev, unsigned int value,
4823                                 unsigned int reg_select_bits)
4824 {
4825         ni_ao_win_outw(dev, (value >> 16) & 0xff, NI67XX_CAL_CFG_HI_REG);
4826         ni_ao_win_outw(dev, value & 0xffff, NI67XX_CAL_CFG_LO_REG);
4827         reg_select_bits &= CS5529_CMD_REG_MASK;
4828         cs5529_command(dev, CS5529_CMD_CB | reg_select_bits);
4829         if (cs5529_wait_for_idle(dev))
4830                 dev_err(dev->class_dev,
4831                         "timeout or signal in %s\n", __func__);
4832 }
4833
4834 static int init_cs5529(struct comedi_device *dev)
4835 {
4836         unsigned int config_bits = CS5529_CFG_PORT_FLAG |
4837                                    CS5529_CFG_WORD_RATE_2180;
4838
4839 #if 1
4840         /* do self-calibration */
4841         cs5529_config_write(dev, config_bits | CS5529_CFG_CALIB_BOTH_SELF,
4842                             CS5529_CFG_REG);
4843         /* need to force a conversion for calibration to run */
4844         cs5529_do_conversion(dev, NULL);
4845 #else
4846         /* force gain calibration to 1 */
4847         cs5529_config_write(dev, 0x400000, CS5529_GAIN_REG);
4848         cs5529_config_write(dev, config_bits | CS5529_CFG_CALIB_OFFSET_SELF,
4849                             CS5529_CFG_REG);
4850         if (cs5529_wait_for_idle(dev))
4851                 dev_err(dev->class_dev,
4852                         "timeout or signal in %s\n", __func__);
4853 #endif
4854         return 0;
4855 }
4856
4857 /*
4858  * Find best multiplier/divider to try and get the PLL running at 80 MHz
4859  * given an arbitrary frequency input clock.
4860  */
4861 static int ni_mseries_get_pll_parameters(unsigned int reference_period_ns,
4862                                          unsigned int *freq_divider,
4863                                          unsigned int *freq_multiplier,
4864                                          unsigned int *actual_period_ns)
4865 {
4866         unsigned int div;
4867         unsigned int best_div = 1;
4868         unsigned int mult;
4869         unsigned int best_mult = 1;
4870         static const unsigned int pico_per_nano = 1000;
4871         const unsigned int reference_picosec = reference_period_ns *
4872                                                pico_per_nano;
4873         /*
4874          * m-series wants the phased-locked loop to output 80MHz, which is
4875          * divided by 4 to 20 MHz for most timing clocks
4876          */
4877         static const unsigned int target_picosec = 12500;
4878         int best_period_picosec = 0;
4879
4880         for (div = 1; div <= NI_M_PLL_MAX_DIVISOR; ++div) {
4881                 for (mult = 1; mult <= NI_M_PLL_MAX_MULTIPLIER; ++mult) {
4882                         unsigned int new_period_ps =
4883                             (reference_picosec * div) / mult;
4884                         if (abs(new_period_ps - target_picosec) <
4885                             abs(best_period_picosec - target_picosec)) {
4886                                 best_period_picosec = new_period_ps;
4887                                 best_div = div;
4888                                 best_mult = mult;
4889                         }
4890                 }
4891         }
4892         if (best_period_picosec == 0)
4893                 return -EIO;
4894
4895         *freq_divider = best_div;
4896         *freq_multiplier = best_mult;
4897         /* return the actual period (* fudge factor for 80 to 20 MHz) */
4898         *actual_period_ns = DIV_ROUND_CLOSEST(best_period_picosec * 4,
4899                                               pico_per_nano);
4900         return 0;
4901 }
4902
4903 static int ni_mseries_set_pll_master_clock(struct comedi_device *dev,
4904                                            unsigned int source,
4905                                            unsigned int period_ns)
4906 {
4907         struct ni_private *devpriv = dev->private;
4908         static const unsigned int min_period_ns = 50;
4909         static const unsigned int max_period_ns = 1000;
4910         static const unsigned int timeout = 1000;
4911         unsigned int pll_control_bits;
4912         unsigned int freq_divider;
4913         unsigned int freq_multiplier;
4914         unsigned int rtsi;
4915         unsigned int i;
4916         int retval;
4917
4918         if (source == NI_MIO_PLL_PXI10_CLOCK)
4919                 period_ns = 100;
4920         /*
4921          * These limits are somewhat arbitrary, but NI advertises 1 to 20MHz
4922          * range so we'll use that.
4923          */
4924         if (period_ns < min_period_ns || period_ns > max_period_ns) {
4925                 dev_err(dev->class_dev,
4926                         "%s: you must specify an input clock frequency between %i and %i nanosec for the phased-lock loop\n",
4927                         __func__, min_period_ns, max_period_ns);
4928                 return -EINVAL;
4929         }
4930         devpriv->rtsi_trig_direction_reg &= ~NISTC_RTSI_TRIG_USE_CLK;
4931         ni_stc_writew(dev, devpriv->rtsi_trig_direction_reg,
4932                       NISTC_RTSI_TRIG_DIR_REG);
4933         pll_control_bits = NI_M_PLL_CTRL_ENA | NI_M_PLL_CTRL_VCO_MODE_75_150MHZ;
4934         devpriv->clock_and_fout2 |= NI_M_CLK_FOUT2_TIMEBASE1_PLL |
4935                                     NI_M_CLK_FOUT2_TIMEBASE3_PLL;
4936         devpriv->clock_and_fout2 &= ~NI_M_CLK_FOUT2_PLL_SRC_MASK;
4937         switch (source) {
4938         case NI_MIO_PLL_PXI_STAR_TRIGGER_CLOCK:
4939                 devpriv->clock_and_fout2 |= NI_M_CLK_FOUT2_PLL_SRC_STAR;
4940                 break;
4941         case NI_MIO_PLL_PXI10_CLOCK:
4942                 /* pxi clock is 10MHz */
4943                 devpriv->clock_and_fout2 |= NI_M_CLK_FOUT2_PLL_SRC_PXI10;
4944                 break;
4945         default:
4946                 for (rtsi = 0; rtsi <= NI_M_MAX_RTSI_CHAN; ++rtsi) {
4947                         if (source == NI_MIO_PLL_RTSI_CLOCK(rtsi)) {
4948                                 devpriv->clock_and_fout2 |=
4949                                         NI_M_CLK_FOUT2_PLL_SRC_RTSI(rtsi);
4950                                 break;
4951                         }
4952                 }
4953                 if (rtsi > NI_M_MAX_RTSI_CHAN)
4954                         return -EINVAL;
4955                 break;
4956         }
4957         retval = ni_mseries_get_pll_parameters(period_ns,
4958                                                &freq_divider,
4959                                                &freq_multiplier,
4960                                                &devpriv->clock_ns);
4961         if (retval < 0) {
4962                 dev_err(dev->class_dev,
4963                         "bug, failed to find pll parameters\n");
4964                 return retval;
4965         }
4966
4967         ni_writew(dev, devpriv->clock_and_fout2, NI_M_CLK_FOUT2_REG);
4968         pll_control_bits |= NI_M_PLL_CTRL_DIVISOR(freq_divider) |
4969                             NI_M_PLL_CTRL_MULTIPLIER(freq_multiplier);
4970
4971         ni_writew(dev, pll_control_bits, NI_M_PLL_CTRL_REG);
4972         devpriv->clock_source = source;
4973         /* it takes a few hundred microseconds for PLL to lock */
4974         for (i = 0; i < timeout; ++i) {
4975                 if (ni_readw(dev, NI_M_PLL_STATUS_REG) & NI_M_PLL_STATUS_LOCKED)
4976                         break;
4977                 udelay(1);
4978         }
4979         if (i == timeout) {
4980                 dev_err(dev->class_dev,
4981                         "%s: timed out waiting for PLL to lock to reference clock source %i with period %i ns\n",
4982                         __func__, source, period_ns);
4983                 return -ETIMEDOUT;
4984         }
4985         return 3;
4986 }
4987
4988 static int ni_set_master_clock(struct comedi_device *dev,
4989                                unsigned int source, unsigned int period_ns)
4990 {
4991         struct ni_private *devpriv = dev->private;
4992
4993         if (source == NI_MIO_INTERNAL_CLOCK) {
4994                 devpriv->rtsi_trig_direction_reg &= ~NISTC_RTSI_TRIG_USE_CLK;
4995                 ni_stc_writew(dev, devpriv->rtsi_trig_direction_reg,
4996                               NISTC_RTSI_TRIG_DIR_REG);
4997                 devpriv->clock_ns = TIMEBASE_1_NS;
4998                 if (devpriv->is_m_series) {
4999                         devpriv->clock_and_fout2 &=
5000                             ~(NI_M_CLK_FOUT2_TIMEBASE1_PLL |
5001                               NI_M_CLK_FOUT2_TIMEBASE3_PLL);
5002                         ni_writew(dev, devpriv->clock_and_fout2,
5003                                   NI_M_CLK_FOUT2_REG);
5004                         ni_writew(dev, 0, NI_M_PLL_CTRL_REG);
5005                 }
5006                 devpriv->clock_source = source;
5007         } else {
5008                 if (devpriv->is_m_series) {
5009                         return ni_mseries_set_pll_master_clock(dev, source,
5010                                                                period_ns);
5011                 } else {
5012                         if (source == NI_MIO_RTSI_CLOCK) {
5013                                 devpriv->rtsi_trig_direction_reg |=
5014                                     NISTC_RTSI_TRIG_USE_CLK;
5015                                 ni_stc_writew(dev,
5016                                               devpriv->rtsi_trig_direction_reg,
5017                                               NISTC_RTSI_TRIG_DIR_REG);
5018                                 if (period_ns == 0) {
5019                                         dev_err(dev->class_dev,
5020                                                 "we don't handle an unspecified clock period correctly yet, returning error\n");
5021                                         return -EINVAL;
5022                                 }
5023                                 devpriv->clock_ns = period_ns;
5024                                 devpriv->clock_source = source;
5025                         } else {
5026                                 return -EINVAL;
5027                         }
5028                 }
5029         }
5030         return 3;
5031 }
5032
5033 static int ni_valid_rtsi_output_source(struct comedi_device *dev,
5034                                        unsigned int chan, unsigned int source)
5035 {
5036         struct ni_private *devpriv = dev->private;
5037
5038         if (chan >= NISTC_RTSI_TRIG_NUM_CHAN(devpriv->is_m_series)) {
5039                 if (chan == NISTC_RTSI_TRIG_OLD_CLK_CHAN) {
5040                         if (source == NI_RTSI_OUTPUT_RTSI_OSC)
5041                                 return 1;
5042
5043                         dev_err(dev->class_dev,
5044                                 "%s: invalid source for channel=%i, channel %i is always the RTSI clock for pre-m-series boards\n",
5045                                 __func__, chan, NISTC_RTSI_TRIG_OLD_CLK_CHAN);
5046                         return 0;
5047                 }
5048                 return 0;
5049         }
5050         switch (source) {
5051         case NI_RTSI_OUTPUT_ADR_START1:
5052         case NI_RTSI_OUTPUT_ADR_START2:
5053         case NI_RTSI_OUTPUT_SCLKG:
5054         case NI_RTSI_OUTPUT_DACUPDN:
5055         case NI_RTSI_OUTPUT_DA_START1:
5056         case NI_RTSI_OUTPUT_G_SRC0:
5057         case NI_RTSI_OUTPUT_G_GATE0:
5058         case NI_RTSI_OUTPUT_RGOUT0:
5059         case NI_RTSI_OUTPUT_RTSI_BRD(0):
5060         case NI_RTSI_OUTPUT_RTSI_BRD(1):
5061         case NI_RTSI_OUTPUT_RTSI_BRD(2):
5062         case NI_RTSI_OUTPUT_RTSI_BRD(3):
5063                 return 1;
5064         case NI_RTSI_OUTPUT_RTSI_OSC:
5065                 return (devpriv->is_m_series) ? 1 : 0;
5066         default:
5067                 return 0;
5068         }
5069 }
5070
5071 static int ni_set_rtsi_routing(struct comedi_device *dev,
5072                                unsigned int chan, unsigned int src)
5073 {
5074         struct ni_private *devpriv = dev->private;
5075
5076         if (chan >= TRIGGER_LINE(0))
5077                 /* allow new and old names of rtsi channels to work. */
5078                 chan -= TRIGGER_LINE(0);
5079
5080         if (ni_valid_rtsi_output_source(dev, chan, src) == 0)
5081                 return -EINVAL;
5082         if (chan < 4) {
5083                 devpriv->rtsi_trig_a_output_reg &= ~NISTC_RTSI_TRIG_MASK(chan);
5084                 devpriv->rtsi_trig_a_output_reg |= NISTC_RTSI_TRIG(chan, src);
5085                 ni_stc_writew(dev, devpriv->rtsi_trig_a_output_reg,
5086                               NISTC_RTSI_TRIGA_OUT_REG);
5087         } else if (chan < NISTC_RTSI_TRIG_NUM_CHAN(devpriv->is_m_series)) {
5088                 devpriv->rtsi_trig_b_output_reg &= ~NISTC_RTSI_TRIG_MASK(chan);
5089                 devpriv->rtsi_trig_b_output_reg |= NISTC_RTSI_TRIG(chan, src);
5090                 ni_stc_writew(dev, devpriv->rtsi_trig_b_output_reg,
5091                               NISTC_RTSI_TRIGB_OUT_REG);
5092         } else if (chan != NISTC_RTSI_TRIG_OLD_CLK_CHAN) {
5093                 /* probably should never reach this, since the
5094                  * ni_valid_rtsi_output_source above errors out if chan is too
5095                  * high
5096                  */
5097                 dev_err(dev->class_dev, "%s: unknown rtsi channel\n", __func__);
5098                 return -EINVAL;
5099         }
5100         return 2;
5101 }
5102
5103 static unsigned int ni_get_rtsi_routing(struct comedi_device *dev,
5104                                         unsigned int chan)
5105 {
5106         struct ni_private *devpriv = dev->private;
5107
5108         if (chan >= TRIGGER_LINE(0))
5109                 /* allow new and old names of rtsi channels to work. */
5110                 chan -= TRIGGER_LINE(0);
5111
5112         if (chan < 4) {
5113                 return NISTC_RTSI_TRIG_TO_SRC(chan,
5114                                               devpriv->rtsi_trig_a_output_reg);
5115         } else if (chan < NISTC_RTSI_TRIG_NUM_CHAN(devpriv->is_m_series)) {
5116                 return NISTC_RTSI_TRIG_TO_SRC(chan,
5117                                               devpriv->rtsi_trig_b_output_reg);
5118         } else if (chan == NISTC_RTSI_TRIG_OLD_CLK_CHAN) {
5119                 return NI_RTSI_OUTPUT_RTSI_OSC;
5120         }
5121
5122         dev_err(dev->class_dev, "%s: unknown rtsi channel\n", __func__);
5123         return -EINVAL;
5124 }
5125
5126 static void ni_set_rtsi_direction(struct comedi_device *dev, int chan,
5127                                   unsigned int direction)
5128 {
5129         struct ni_private *devpriv = dev->private;
5130         unsigned int max_chan = NISTC_RTSI_TRIG_NUM_CHAN(devpriv->is_m_series);
5131
5132         if (chan >= TRIGGER_LINE(0))
5133                 /* allow new and old names of rtsi channels to work. */
5134                 chan -= TRIGGER_LINE(0);
5135
5136         if (direction == COMEDI_OUTPUT) {
5137                 if (chan < max_chan) {
5138                         devpriv->rtsi_trig_direction_reg |=
5139                             NISTC_RTSI_TRIG_DIR(chan, devpriv->is_m_series);
5140                 } else if (chan == NISTC_RTSI_TRIG_OLD_CLK_CHAN) {
5141                         devpriv->rtsi_trig_direction_reg |=
5142                             NISTC_RTSI_TRIG_DRV_CLK;
5143                 }
5144         } else {
5145                 if (chan < max_chan) {
5146                         devpriv->rtsi_trig_direction_reg &=
5147                             ~NISTC_RTSI_TRIG_DIR(chan, devpriv->is_m_series);
5148                 } else if (chan == NISTC_RTSI_TRIG_OLD_CLK_CHAN) {
5149                         devpriv->rtsi_trig_direction_reg &=
5150                             ~NISTC_RTSI_TRIG_DRV_CLK;
5151                 }
5152         }
5153         ni_stc_writew(dev, devpriv->rtsi_trig_direction_reg,
5154                       NISTC_RTSI_TRIG_DIR_REG);
5155 }
5156
5157 static int ni_get_rtsi_direction(struct comedi_device *dev, int chan)
5158 {
5159         struct ni_private *devpriv = dev->private;
5160         unsigned int max_chan = NISTC_RTSI_TRIG_NUM_CHAN(devpriv->is_m_series);
5161
5162         if (chan >= TRIGGER_LINE(0))
5163                 /* allow new and old names of rtsi channels to work. */
5164                 chan -= TRIGGER_LINE(0);
5165
5166         if (chan < max_chan) {
5167                 return (devpriv->rtsi_trig_direction_reg &
5168                         NISTC_RTSI_TRIG_DIR(chan, devpriv->is_m_series))
5169                            ? COMEDI_OUTPUT : COMEDI_INPUT;
5170         } else if (chan == NISTC_RTSI_TRIG_OLD_CLK_CHAN) {
5171                 return (devpriv->rtsi_trig_direction_reg &
5172                         NISTC_RTSI_TRIG_DRV_CLK)
5173                            ? COMEDI_OUTPUT : COMEDI_INPUT;
5174         }
5175         return -EINVAL;
5176 }
5177
5178 static int ni_rtsi_insn_config(struct comedi_device *dev,
5179                                struct comedi_subdevice *s,
5180                                struct comedi_insn *insn,
5181                                unsigned int *data)
5182 {
5183         struct ni_private *devpriv = dev->private;
5184         unsigned int chan = CR_CHAN(insn->chanspec);
5185
5186         switch (data[0]) {
5187         case COMEDI_OUTPUT:
5188         case COMEDI_INPUT:
5189                 ni_set_rtsi_direction(dev, chan, data[0]);
5190                 break;
5191         case INSN_CONFIG_DIO_QUERY: {
5192                 int ret = ni_get_rtsi_direction(dev, chan);
5193
5194                 if (ret < 0)
5195                         return ret;
5196                 data[1] = ret;
5197                 return 2;
5198         }
5199         case INSN_CONFIG_SET_CLOCK_SRC:
5200                 return ni_set_master_clock(dev, data[1], data[2]);
5201         case INSN_CONFIG_GET_CLOCK_SRC:
5202                 data[1] = devpriv->clock_source;
5203                 data[2] = devpriv->clock_ns;
5204                 return 3;
5205         case INSN_CONFIG_SET_ROUTING:
5206                 return ni_set_rtsi_routing(dev, chan, data[1]);
5207         case INSN_CONFIG_GET_ROUTING: {
5208                 int ret = ni_get_rtsi_routing(dev, chan);
5209
5210                 if (ret < 0)
5211                         return ret;
5212                 data[1] = ret;
5213                 return 2;
5214         }
5215         default:
5216                 return -EINVAL;
5217         }
5218         return 1;
5219 }
5220
5221 static int ni_rtsi_insn_bits(struct comedi_device *dev,
5222                              struct comedi_subdevice *s,
5223                              struct comedi_insn *insn,
5224                              unsigned int *data)
5225 {
5226         data[1] = 0;
5227
5228         return insn->n;
5229 }
5230
5231 /*
5232  * Default routing for RTSI trigger lines.
5233  *
5234  * These values are used here in the init function, as well as in the
5235  * disconnect_route function, after a RTSI route has been disconnected.
5236  */
5237 static const int default_rtsi_routing[] = {
5238         [0] = NI_RTSI_OUTPUT_ADR_START1,
5239         [1] = NI_RTSI_OUTPUT_ADR_START2,
5240         [2] = NI_RTSI_OUTPUT_SCLKG,
5241         [3] = NI_RTSI_OUTPUT_DACUPDN,
5242         [4] = NI_RTSI_OUTPUT_DA_START1,
5243         [5] = NI_RTSI_OUTPUT_G_SRC0,
5244         [6] = NI_RTSI_OUTPUT_G_GATE0,
5245         [7] = NI_RTSI_OUTPUT_RTSI_OSC,
5246 };
5247
5248 /*
5249  * Route signals through RGOUT0 terminal.
5250  * @reg: raw register value of RGOUT0 bits (only bit0 is important).
5251  * @dev: comedi device handle.
5252  */
5253 static void set_rgout0_reg(int reg, struct comedi_device *dev)
5254 {
5255         struct ni_private *devpriv = dev->private;
5256
5257         if (devpriv->is_m_series) {
5258                 devpriv->rtsi_trig_direction_reg &=
5259                         ~NISTC_RTSI_TRIG_DIR_SUB_SEL1;
5260                 devpriv->rtsi_trig_direction_reg |=
5261                         (reg << NISTC_RTSI_TRIG_DIR_SUB_SEL1_SHIFT) &
5262                         NISTC_RTSI_TRIG_DIR_SUB_SEL1;
5263                 ni_stc_writew(dev, devpriv->rtsi_trig_direction_reg,
5264                               NISTC_RTSI_TRIG_DIR_REG);
5265         } else {
5266                 devpriv->rtsi_trig_b_output_reg &= ~NISTC_RTSI_TRIGB_SUB_SEL1;
5267                 devpriv->rtsi_trig_b_output_reg |=
5268                         (reg << NISTC_RTSI_TRIGB_SUB_SEL1_SHIFT) &
5269                         NISTC_RTSI_TRIGB_SUB_SEL1;
5270                 ni_stc_writew(dev, devpriv->rtsi_trig_b_output_reg,
5271                               NISTC_RTSI_TRIGB_OUT_REG);
5272         }
5273 }
5274
5275 static int get_rgout0_reg(struct comedi_device *dev)
5276 {
5277         struct ni_private *devpriv = dev->private;
5278         int reg;
5279
5280         if (devpriv->is_m_series)
5281                 reg = (devpriv->rtsi_trig_direction_reg &
5282                        NISTC_RTSI_TRIG_DIR_SUB_SEL1)
5283                     >> NISTC_RTSI_TRIG_DIR_SUB_SEL1_SHIFT;
5284         else
5285                 reg = (devpriv->rtsi_trig_b_output_reg &
5286                        NISTC_RTSI_TRIGB_SUB_SEL1)
5287                     >> NISTC_RTSI_TRIGB_SUB_SEL1_SHIFT;
5288         return reg;
5289 }
5290
5291 static inline int get_rgout0_src(struct comedi_device *dev)
5292 {
5293         struct ni_private *devpriv = dev->private;
5294         int reg = get_rgout0_reg(dev);
5295
5296         return ni_find_route_source(reg, NI_RGOUT0, &devpriv->routing_tables);
5297 }
5298
5299 /*
5300  * Route signals through RGOUT0 terminal and increment the RGOUT0 use for this
5301  * particular route.
5302  * @src: device-global signal name
5303  * @dev: comedi device handle
5304  *
5305  * Return: -EINVAL if the source is not valid to route to RGOUT0;
5306  *         -EBUSY if the RGOUT0 is already used;
5307  *         0 if successful.
5308  */
5309 static int incr_rgout0_src_use(int src, struct comedi_device *dev)
5310 {
5311         struct ni_private *devpriv = dev->private;
5312         s8 reg = ni_lookup_route_register(CR_CHAN(src), NI_RGOUT0,
5313                                           &devpriv->routing_tables);
5314
5315         if (reg < 0)
5316                 return -EINVAL;
5317
5318         if (devpriv->rgout0_usage > 0 && get_rgout0_reg(dev) != reg)
5319                 return -EBUSY;
5320
5321         ++devpriv->rgout0_usage;
5322         set_rgout0_reg(reg, dev);
5323         return 0;
5324 }
5325
5326 /*
5327  * Unroute signals through RGOUT0 terminal and deccrement the RGOUT0 use for
5328  * this particular source.  This function does not actually unroute anything
5329  * with respect to RGOUT0.  It does, on the other hand, decrement the usage
5330  * counter for the current src->RGOUT0 mapping.
5331  *
5332  * Return: -EINVAL if the source is not already routed to RGOUT0 (or usage is
5333  *      already at zero); 0 if successful.
5334  */
5335 static int decr_rgout0_src_use(int src, struct comedi_device *dev)
5336 {
5337         struct ni_private *devpriv = dev->private;
5338         s8 reg = ni_lookup_route_register(CR_CHAN(src), NI_RGOUT0,
5339                                           &devpriv->routing_tables);
5340
5341         if (devpriv->rgout0_usage > 0 && get_rgout0_reg(dev) == reg) {
5342                 --devpriv->rgout0_usage;
5343                 if (!devpriv->rgout0_usage)
5344                         set_rgout0_reg(0, dev); /* ok default? */
5345                 return 0;
5346         }
5347         return -EINVAL;
5348 }
5349
5350 /*
5351  * Route signals through given NI_RTSI_BRD mux.
5352  * @i: index of mux to route
5353  * @reg: raw register value of RTSI_BRD bits
5354  * @dev: comedi device handle
5355  */
5356 static void set_ith_rtsi_brd_reg(int i, int reg, struct comedi_device *dev)
5357 {
5358         struct ni_private *devpriv = dev->private;
5359         int reg_i_sz = 3; /* value for e-series */
5360         int reg_i_mask;
5361         int reg_i_shift;
5362
5363         if (devpriv->is_m_series)
5364                 reg_i_sz = 4;
5365         reg_i_mask = ~((~0) << reg_i_sz);
5366         reg_i_shift = i * reg_i_sz;
5367
5368         /* clear out the current reg_i for ith brd */
5369         devpriv->rtsi_shared_mux_reg &= ~(reg_i_mask       << reg_i_shift);
5370         /* (softcopy) write the new reg_i for ith brd */
5371         devpriv->rtsi_shared_mux_reg |= (reg & reg_i_mask) << reg_i_shift;
5372         /* (hardcopy) write the new reg_i for ith brd */
5373         ni_stc_writew(dev, devpriv->rtsi_shared_mux_reg, NISTC_RTSI_BOARD_REG);
5374 }
5375
5376 static int get_ith_rtsi_brd_reg(int i, struct comedi_device *dev)
5377 {
5378         struct ni_private *devpriv = dev->private;
5379         int reg_i_sz = 3; /* value for e-series */
5380         int reg_i_mask;
5381         int reg_i_shift;
5382
5383         if (devpriv->is_m_series)
5384                 reg_i_sz = 4;
5385         reg_i_mask = ~((~0) << reg_i_sz);
5386         reg_i_shift = i * reg_i_sz;
5387
5388         return (devpriv->rtsi_shared_mux_reg >> reg_i_shift) & reg_i_mask;
5389 }
5390
5391 static inline int get_rtsi_brd_src(int brd, struct comedi_device *dev)
5392 {
5393         struct ni_private *devpriv = dev->private;
5394         int brd_index = brd;
5395         int reg;
5396
5397         if (brd >= NI_RTSI_BRD(0))
5398                 brd_index = brd - NI_RTSI_BRD(0);
5399         else
5400                 brd = NI_RTSI_BRD(brd);
5401         /*
5402          * And now:
5403          * brd : device-global name
5404          * brd_index : index number of RTSI_BRD mux
5405          */
5406
5407         reg = get_ith_rtsi_brd_reg(brd_index, dev);
5408
5409         return ni_find_route_source(reg, brd, &devpriv->routing_tables);
5410 }
5411
5412 /*
5413  * Route signals through NI_RTSI_BRD mux and increment the use counter for this
5414  * particular route.
5415  *
5416  * Return: -EINVAL if the source is not valid to route to NI_RTSI_BRD(i);
5417  *         -EBUSY if all NI_RTSI_BRD muxes are already used;
5418  *         NI_RTSI_BRD(i) of allocated ith mux if successful.
5419  */
5420 static int incr_rtsi_brd_src_use(int src, struct comedi_device *dev)
5421 {
5422         struct ni_private *devpriv = dev->private;
5423         int first_available = -1;
5424         int err = -EINVAL;
5425         s8 reg;
5426         int i;
5427
5428         /* first look for a mux that is already configured to provide src */
5429         for (i = 0; i < NUM_RTSI_SHARED_MUXS; ++i) {
5430                 reg = ni_lookup_route_register(CR_CHAN(src), NI_RTSI_BRD(i),
5431                                                &devpriv->routing_tables);
5432
5433                 if (reg < 0)
5434                         continue; /* invalid route */
5435
5436                 if (!devpriv->rtsi_shared_mux_usage[i]) {
5437                         if (first_available < 0)
5438                                 /* found the first unused, but usable mux */
5439                                 first_available = i;
5440                 } else {
5441                         /*
5442                          * we've seen at least one possible route, so change the
5443                          * final error to -EBUSY in case there are no muxes
5444                          * available.
5445                          */
5446                         err = -EBUSY;
5447
5448                         if (get_ith_rtsi_brd_reg(i, dev) == reg) {
5449                                 /*
5450                                  * we've found a mux that is already being used
5451                                  * to provide the requested signal.  Reuse it.
5452                                  */
5453                                 goto success;
5454                         }
5455                 }
5456         }
5457
5458         if (first_available < 0)
5459                 return err;
5460
5461         /* we did not find a mux to reuse, but there is at least one usable */
5462         i = first_available;
5463
5464 success:
5465         ++devpriv->rtsi_shared_mux_usage[i];
5466         set_ith_rtsi_brd_reg(i, reg, dev);
5467         return NI_RTSI_BRD(i);
5468 }
5469
5470 /*
5471  * Unroute signals through NI_RTSI_BRD mux and decrement the user counter for
5472  * this particular route.
5473  *
5474  * Return: -EINVAL if the source is not already routed to rtsi_brd(i) (or usage
5475  *      is already at zero); 0 if successful.
5476  */
5477 static int decr_rtsi_brd_src_use(int src, int rtsi_brd,
5478                                  struct comedi_device *dev)
5479 {
5480         struct ni_private *devpriv = dev->private;
5481         s8 reg = ni_lookup_route_register(CR_CHAN(src), rtsi_brd,
5482                                           &devpriv->routing_tables);
5483         const int i = rtsi_brd - NI_RTSI_BRD(0);
5484
5485         if (devpriv->rtsi_shared_mux_usage[i] > 0 &&
5486             get_ith_rtsi_brd_reg(i, dev) == reg) {
5487                 --devpriv->rtsi_shared_mux_usage[i];
5488                 if (!devpriv->rtsi_shared_mux_usage[i])
5489                         set_ith_rtsi_brd_reg(i, 0, dev); /* ok default? */
5490                 return 0;
5491         }
5492
5493         return -EINVAL;
5494 }
5495
5496 static void ni_rtsi_init(struct comedi_device *dev)
5497 {
5498         struct ni_private *devpriv = dev->private;
5499         int i;
5500
5501         /*  Initialises the RTSI bus signal switch to a default state */
5502
5503         /*
5504          * Use 10MHz instead of 20MHz for RTSI clock frequency. Appears
5505          * to have no effect, at least on pxi-6281, which always uses
5506          * 20MHz rtsi clock frequency
5507          */
5508         devpriv->clock_and_fout2 = NI_M_CLK_FOUT2_RTSI_10MHZ;
5509         /*  Set clock mode to internal */
5510         if (ni_set_master_clock(dev, NI_MIO_INTERNAL_CLOCK, 0) < 0)
5511                 dev_err(dev->class_dev, "ni_set_master_clock failed, bug?\n");
5512
5513         /* default internal lines routing to RTSI bus lines */
5514         for (i = 0; i < 8; ++i) {
5515                 ni_set_rtsi_direction(dev, i, COMEDI_INPUT);
5516                 ni_set_rtsi_routing(dev, i, default_rtsi_routing[i]);
5517         }
5518
5519         /*
5520          * Sets the source and direction of the 4 on board lines.
5521          * This configures all board lines to be:
5522          * for e-series:
5523          *   1) inputs (not sure what "output" would mean)
5524          *   2) copying TRIGGER_LINE(0) (or RTSI0) output
5525          * for m-series:
5526          *   copying NI_PFI(0) output
5527          */
5528         devpriv->rtsi_shared_mux_reg = 0;
5529         for (i = 0; i < 4; ++i)
5530                 set_ith_rtsi_brd_reg(i, 0, dev);
5531         memset(devpriv->rtsi_shared_mux_usage, 0,
5532                sizeof(devpriv->rtsi_shared_mux_usage));
5533
5534         /* initialize rgout0 pin as unused. */
5535         devpriv->rgout0_usage = 0;
5536         set_rgout0_reg(0, dev);
5537 }
5538
5539 /* Get route of GPFO_i/CtrOut pins */
5540 static inline int ni_get_gout_routing(unsigned int dest,
5541                                       struct comedi_device *dev)
5542 {
5543         struct ni_private *devpriv = dev->private;
5544         unsigned int reg = devpriv->an_trig_etc_reg;
5545
5546         switch (dest) {
5547         case 0:
5548                 if (reg & NISTC_ATRIG_ETC_GPFO_0_ENA)
5549                         return NISTC_ATRIG_ETC_GPFO_0_SEL_TO_SRC(reg);
5550                 break;
5551         case 1:
5552                 if (reg & NISTC_ATRIG_ETC_GPFO_1_ENA)
5553                         return NISTC_ATRIG_ETC_GPFO_1_SEL_TO_SRC(reg);
5554                 break;
5555         }
5556
5557         return -EINVAL;
5558 }
5559
5560 /* Set route of GPFO_i/CtrOut pins */
5561 static inline int ni_disable_gout_routing(unsigned int dest,
5562                                           struct comedi_device *dev)
5563 {
5564         struct ni_private *devpriv = dev->private;
5565
5566         switch (dest) {
5567         case 0:
5568                 devpriv->an_trig_etc_reg &= ~NISTC_ATRIG_ETC_GPFO_0_ENA;
5569                 break;
5570         case 1:
5571                 devpriv->an_trig_etc_reg &= ~NISTC_ATRIG_ETC_GPFO_1_ENA;
5572                 break;
5573         default:
5574                 return -EINVAL;
5575         }
5576
5577         ni_stc_writew(dev, devpriv->an_trig_etc_reg, NISTC_ATRIG_ETC_REG);
5578         return 0;
5579 }
5580
5581 /* Set route of GPFO_i/CtrOut pins */
5582 static inline int ni_set_gout_routing(unsigned int src, unsigned int dest,
5583                                       struct comedi_device *dev)
5584 {
5585         struct ni_private *devpriv = dev->private;
5586
5587         switch (dest) {
5588         case 0:
5589                 /* clear reg */
5590                 devpriv->an_trig_etc_reg &= ~NISTC_ATRIG_ETC_GPFO_0_SEL(-1);
5591                 /* set reg */
5592                 devpriv->an_trig_etc_reg |= NISTC_ATRIG_ETC_GPFO_0_ENA
5593                                          |  NISTC_ATRIG_ETC_GPFO_0_SEL(src);
5594                 break;
5595         case 1:
5596                 /* clear reg */
5597                 devpriv->an_trig_etc_reg &= ~NISTC_ATRIG_ETC_GPFO_1_SEL;
5598                 src = src ? NISTC_ATRIG_ETC_GPFO_1_SEL : 0;
5599                 /* set reg */
5600                 devpriv->an_trig_etc_reg |= NISTC_ATRIG_ETC_GPFO_1_ENA | src;
5601                 break;
5602         default:
5603                 return -EINVAL;
5604         }
5605
5606         ni_stc_writew(dev, devpriv->an_trig_etc_reg, NISTC_ATRIG_ETC_REG);
5607         return 0;
5608 }
5609
5610 /*
5611  * Retrieves the current source of the output selector for the given
5612  * destination.  If the terminal for the destination is not already configured
5613  * as an output, this function returns -EINVAL as error.
5614  *
5615  * Return: the register value of the destination output selector;
5616  *         -EINVAL if terminal is not configured for output.
5617  */
5618 static int get_output_select_source(int dest, struct comedi_device *dev)
5619 {
5620         struct ni_private *devpriv = dev->private;
5621         int reg = -1;
5622
5623         if (channel_is_pfi(dest)) {
5624                 if (ni_get_pfi_direction(dev, dest) == COMEDI_OUTPUT)
5625                         reg = ni_get_pfi_routing(dev, dest);
5626         } else if (channel_is_rtsi(dest)) {
5627                 if (ni_get_rtsi_direction(dev, dest) == COMEDI_OUTPUT) {
5628                         reg = ni_get_rtsi_routing(dev, dest);
5629
5630                         if (reg == NI_RTSI_OUTPUT_RGOUT0) {
5631                                 dest = NI_RGOUT0; /* prepare for lookup below */
5632                                 reg = get_rgout0_reg(dev);
5633                         } else if (reg >= NI_RTSI_OUTPUT_RTSI_BRD(0) &&
5634                                    reg <= NI_RTSI_OUTPUT_RTSI_BRD(3)) {
5635                                 const int i = reg - NI_RTSI_OUTPUT_RTSI_BRD(0);
5636
5637                                 dest = NI_RTSI_BRD(i); /* prepare for lookup */
5638                                 reg = get_ith_rtsi_brd_reg(i, dev);
5639                         }
5640                 }
5641         } else if (dest >= NI_CtrOut(0) && dest <= NI_CtrOut(-1)) {
5642                 /*
5643                  * not handled by ni_tio.  Only available for GPFO registers in
5644                  * e/m series.
5645                  */
5646                 dest -= NI_CtrOut(0);
5647                 if (dest > 1)
5648                         /* there are only two g_out outputs. */
5649                         return -EINVAL;
5650                 reg = ni_get_gout_routing(dest, dev);
5651         } else if (channel_is_ctr(dest)) {
5652                 reg = ni_tio_get_routing(devpriv->counter_dev, dest);
5653         } else {
5654                 dev_dbg(dev->class_dev, "%s: unhandled destination (%d) queried\n",
5655                         __func__, dest);
5656         }
5657
5658         if (reg >= 0)
5659                 return ni_find_route_source(CR_CHAN(reg), dest,
5660                                             &devpriv->routing_tables);
5661         return -EINVAL;
5662 }
5663
5664 /*
5665  * Test a route:
5666  *
5667  * Return: -1 if not connectible;
5668  *          0 if connectible and not connected;
5669  *          1 if connectible and connected.
5670  */
5671 static int test_route(unsigned int src, unsigned int dest,
5672                       struct comedi_device *dev)
5673 {
5674         struct ni_private *devpriv = dev->private;
5675         s8 reg = ni_route_to_register(CR_CHAN(src), dest,
5676                                       &devpriv->routing_tables);
5677
5678         if (reg < 0)
5679                 return -1;
5680         if (get_output_select_source(dest, dev) != CR_CHAN(src))
5681                 return 0;
5682         return 1;
5683 }
5684
5685 /* Connect the actual route.  */
5686 static int connect_route(unsigned int src, unsigned int dest,
5687                          struct comedi_device *dev)
5688 {
5689         struct ni_private *devpriv = dev->private;
5690         s8 reg = ni_route_to_register(CR_CHAN(src), dest,
5691                                       &devpriv->routing_tables);
5692         s8 current_src;
5693
5694         if (reg < 0)
5695                 /* route is not valid */
5696                 return -EINVAL;
5697
5698         current_src = get_output_select_source(dest, dev);
5699         if (current_src == CR_CHAN(src))
5700                 return -EALREADY;
5701         if (current_src >= 0)
5702                 /* destination mux is already busy. complain, don't overwrite */
5703                 return -EBUSY;
5704
5705         /* The route is valid and available. Now connect... */
5706         if (channel_is_pfi(dest)) {
5707                 /* set routing source, then open output */
5708                 ni_set_pfi_routing(dev, dest, reg);
5709                 ni_set_pfi_direction(dev, dest, COMEDI_OUTPUT);
5710         } else if (channel_is_rtsi(dest)) {
5711                 if (reg == NI_RTSI_OUTPUT_RGOUT0) {
5712                         int ret = incr_rgout0_src_use(src, dev);
5713
5714                         if (ret < 0)
5715                                 return ret;
5716                 } else if (ni_rtsi_route_requires_mux(reg)) {
5717                         /* Attempt to allocate and  route (src->brd) */
5718                         int brd = incr_rtsi_brd_src_use(src, dev);
5719
5720                         if (brd < 0)
5721                                 return brd;
5722
5723                         /* Now lookup the register value for (brd->dest) */
5724                         reg = ni_lookup_route_register(
5725                                 brd, dest, &devpriv->routing_tables);
5726                 }
5727
5728                 ni_set_rtsi_direction(dev, dest, COMEDI_OUTPUT);
5729                 ni_set_rtsi_routing(dev, dest, reg);
5730         } else if (dest >= NI_CtrOut(0) && dest <= NI_CtrOut(-1)) {
5731                 /*
5732                  * not handled by ni_tio.  Only available for GPFO registers in
5733                  * e/m series.
5734                  */
5735                 dest -= NI_CtrOut(0);
5736                 if (dest > 1)
5737                         /* there are only two g_out outputs. */
5738                         return -EINVAL;
5739                 if (ni_set_gout_routing(src, dest, dev))
5740                         return -EINVAL;
5741         } else if (channel_is_ctr(dest)) {
5742                 /*
5743                  * we are adding back the channel modifier info to set
5744                  * invert/edge info passed by the user
5745                  */
5746                 ni_tio_set_routing(devpriv->counter_dev, dest,
5747                                    reg | (src & ~CR_CHAN(-1)));
5748         } else {
5749                 return -EINVAL;
5750         }
5751         return 0;
5752 }
5753
5754 static int disconnect_route(unsigned int src, unsigned int dest,
5755                             struct comedi_device *dev)
5756 {
5757         struct ni_private *devpriv = dev->private;
5758         s8 reg = ni_route_to_register(CR_CHAN(src), dest,
5759                                       &devpriv->routing_tables);
5760
5761         if (reg < 0)
5762                 /* route is not valid */
5763                 return -EINVAL;
5764         if (get_output_select_source(dest, dev) != src)
5765                 /* cannot disconnect something not connected */
5766                 return -EINVAL;
5767
5768         /* The route is valid and is connected.  Now disconnect... */
5769         if (channel_is_pfi(dest)) {
5770                 /* set the pfi to high impedance, and disconnect */
5771                 ni_set_pfi_direction(dev, dest, COMEDI_INPUT);
5772                 ni_set_pfi_routing(dev, dest, NI_PFI_OUTPUT_PFI_DEFAULT);
5773         } else if (channel_is_rtsi(dest)) {
5774                 if (reg == NI_RTSI_OUTPUT_RGOUT0) {
5775                         int ret = decr_rgout0_src_use(src, dev);
5776
5777                         if (ret < 0)
5778                                 return ret;
5779                 } else if (ni_rtsi_route_requires_mux(reg)) {
5780                         /* find which RTSI_BRD line is source for rtsi pin */
5781                         int brd = ni_find_route_source(
5782                                 ni_get_rtsi_routing(dev, dest), dest,
5783                                 &devpriv->routing_tables);
5784
5785                         if (brd < 0)
5786                                 return brd;
5787
5788                         /* decrement/disconnect RTSI_BRD line from source */
5789                         decr_rtsi_brd_src_use(src, brd, dev);
5790                 }
5791
5792                 /* set rtsi output selector to default state */
5793                 reg = default_rtsi_routing[dest - TRIGGER_LINE(0)];
5794                 ni_set_rtsi_direction(dev, dest, COMEDI_INPUT);
5795                 ni_set_rtsi_routing(dev, dest, reg);
5796         } else if (dest >= NI_CtrOut(0) && dest <= NI_CtrOut(-1)) {
5797                 /*
5798                  * not handled by ni_tio.  Only available for GPFO registers in
5799                  * e/m series.
5800                  */
5801                 dest -= NI_CtrOut(0);
5802                 if (dest > 1)
5803                         /* there are only two g_out outputs. */
5804                         return -EINVAL;
5805                 reg = ni_disable_gout_routing(dest, dev);
5806         } else if (channel_is_ctr(dest)) {
5807                 ni_tio_unset_routing(devpriv->counter_dev, dest);
5808         } else {
5809                 return -EINVAL;
5810         }
5811         return 0;
5812 }
5813
5814 static int ni_global_insn_config(struct comedi_device *dev,
5815                                  struct comedi_insn *insn,
5816                                  unsigned int *data)
5817 {
5818         switch (data[0]) {
5819         case INSN_DEVICE_CONFIG_TEST_ROUTE:
5820                 data[0] = test_route(data[1], data[2], dev);
5821                 return 2;
5822         case INSN_DEVICE_CONFIG_CONNECT_ROUTE:
5823                 return connect_route(data[1], data[2], dev);
5824         case INSN_DEVICE_CONFIG_DISCONNECT_ROUTE:
5825                 return disconnect_route(data[1], data[2], dev);
5826         /*
5827          * This case is already handled one level up.
5828          * case INSN_DEVICE_CONFIG_GET_ROUTES:
5829          */
5830         default:
5831                 return -EINVAL;
5832         }
5833         return 1;
5834 }
5835
5836 #ifdef PCIDMA
5837 static int ni_gpct_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
5838 {
5839         struct ni_gpct *counter = s->private;
5840         int retval;
5841
5842         retval = ni_request_gpct_mite_channel(dev, counter->counter_index,
5843                                               COMEDI_INPUT);
5844         if (retval) {
5845                 dev_err(dev->class_dev,
5846                         "no dma channel available for use by counter\n");
5847                 return retval;
5848         }
5849         ni_tio_acknowledge(counter);
5850         ni_e_series_enable_second_irq(dev, counter->counter_index, 1);
5851
5852         return ni_tio_cmd(dev, s);
5853 }
5854
5855 static int ni_gpct_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
5856 {
5857         struct ni_gpct *counter = s->private;
5858         int retval;
5859
5860         retval = ni_tio_cancel(counter);
5861         ni_e_series_enable_second_irq(dev, counter->counter_index, 0);
5862         ni_release_gpct_mite_channel(dev, counter->counter_index);
5863         return retval;
5864 }
5865 #endif
5866
5867 static irqreturn_t ni_E_interrupt(int irq, void *d)
5868 {
5869         struct comedi_device *dev = d;
5870         struct comedi_subdevice *s_ai = dev->read_subdev;
5871         struct comedi_subdevice *s_ao = dev->write_subdev;
5872         unsigned short a_status;
5873         unsigned short b_status;
5874         unsigned long flags;
5875 #ifdef PCIDMA
5876         struct ni_private *devpriv = dev->private;
5877 #endif
5878
5879         if (!dev->attached)
5880                 return IRQ_NONE;
5881         smp_mb();               /* make sure dev->attached is checked */
5882
5883         /*  lock to avoid race with comedi_poll */
5884         spin_lock_irqsave(&dev->spinlock, flags);
5885         a_status = ni_stc_readw(dev, NISTC_AI_STATUS1_REG);
5886         b_status = ni_stc_readw(dev, NISTC_AO_STATUS1_REG);
5887 #ifdef PCIDMA
5888         if (devpriv->mite) {
5889                 unsigned long flags_too;
5890
5891                 spin_lock_irqsave(&devpriv->mite_channel_lock, flags_too);
5892                 if (s_ai && devpriv->ai_mite_chan)
5893                         mite_ack_linkc(devpriv->ai_mite_chan, s_ai, false);
5894                 if (s_ao && devpriv->ao_mite_chan)
5895                         mite_ack_linkc(devpriv->ao_mite_chan, s_ao, false);
5896                 spin_unlock_irqrestore(&devpriv->mite_channel_lock, flags_too);
5897         }
5898 #endif
5899         ack_a_interrupt(dev, a_status);
5900         ack_b_interrupt(dev, b_status);
5901         if (s_ai) {
5902                 if (a_status & NISTC_AI_STATUS1_INTA)
5903                         handle_a_interrupt(dev, s_ai, a_status);
5904                 /* handle any interrupt or dma events */
5905                 comedi_handle_events(dev, s_ai);
5906         }
5907         if (s_ao) {
5908                 if (b_status & NISTC_AO_STATUS1_INTB)
5909                         handle_b_interrupt(dev, s_ao, b_status);
5910                 /* handle any interrupt or dma events */
5911                 comedi_handle_events(dev, s_ao);
5912         }
5913         handle_gpct_interrupt(dev, 0);
5914         handle_gpct_interrupt(dev, 1);
5915 #ifdef PCIDMA
5916         if (devpriv->is_m_series)
5917                 handle_cdio_interrupt(dev);
5918 #endif
5919
5920         spin_unlock_irqrestore(&dev->spinlock, flags);
5921         return IRQ_HANDLED;
5922 }
5923
5924 static int ni_alloc_private(struct comedi_device *dev)
5925 {
5926         struct ni_private *devpriv;
5927
5928         devpriv = comedi_alloc_devpriv(dev, sizeof(*devpriv));
5929         if (!devpriv)
5930                 return -ENOMEM;
5931
5932         spin_lock_init(&devpriv->window_lock);
5933         spin_lock_init(&devpriv->soft_reg_copy_lock);
5934         spin_lock_init(&devpriv->mite_channel_lock);
5935
5936         return 0;
5937 }
5938
5939 static unsigned int _ni_get_valid_routes(struct comedi_device *dev,
5940                                          unsigned int n_pairs,
5941                                          unsigned int *pair_data)
5942 {
5943         struct ni_private *devpriv = dev->private;
5944
5945         return ni_get_valid_routes(&devpriv->routing_tables, n_pairs,
5946                                    pair_data);
5947 }
5948
5949 static int ni_E_init(struct comedi_device *dev,
5950                      unsigned int interrupt_pin, unsigned int irq_polarity)
5951 {
5952         const struct ni_board_struct *board = dev->board_ptr;
5953         struct ni_private *devpriv = dev->private;
5954         struct comedi_subdevice *s;
5955         int ret;
5956         int i;
5957         const char *dev_family = devpriv->is_m_series ? "ni_mseries"
5958                                                       : "ni_eseries";
5959
5960         /* prepare the device for globally-named routes. */
5961         if (ni_assign_device_routes(dev_family, board->name,
5962                                     &devpriv->routing_tables) < 0) {
5963                 dev_warn(dev->class_dev, "%s: %s device has no signal routing table.\n",
5964                          __func__, board->name);
5965                 dev_warn(dev->class_dev, "%s: High level NI signal names will not be available for this %s board.\n",
5966                          __func__, board->name);
5967         } else {
5968                 /*
5969                  * only(?) assign insn_device_config if we have global names for
5970                  * this device.
5971                  */
5972                 dev->insn_device_config = ni_global_insn_config;
5973                 dev->get_valid_routes = _ni_get_valid_routes;
5974         }
5975
5976         if (board->n_aochan > MAX_N_AO_CHAN) {
5977                 dev_err(dev->class_dev, "bug! n_aochan > MAX_N_AO_CHAN\n");
5978                 return -EINVAL;
5979         }
5980
5981         /* initialize clock dividers */
5982         devpriv->clock_and_fout = NISTC_CLK_FOUT_SLOW_DIV2 |
5983                                   NISTC_CLK_FOUT_SLOW_TIMEBASE |
5984                                   NISTC_CLK_FOUT_TO_BOARD_DIV2 |
5985                                   NISTC_CLK_FOUT_TO_BOARD;
5986         if (!devpriv->is_6xxx) {
5987                 /* BEAM is this needed for PCI-6143 ?? */
5988                 devpriv->clock_and_fout |= (NISTC_CLK_FOUT_AI_OUT_DIV2 |
5989                                             NISTC_CLK_FOUT_AO_OUT_DIV2);
5990         }
5991         ni_stc_writew(dev, devpriv->clock_and_fout, NISTC_CLK_FOUT_REG);
5992
5993         ret = comedi_alloc_subdevices(dev, NI_NUM_SUBDEVICES);
5994         if (ret)
5995                 return ret;
5996
5997         /* Analog Input subdevice */
5998         s = &dev->subdevices[NI_AI_SUBDEV];
5999         if (board->n_adchan) {
6000                 s->type         = COMEDI_SUBD_AI;
6001                 s->subdev_flags = SDF_READABLE | SDF_DIFF | SDF_DITHER;
6002                 if (!devpriv->is_611x)
6003                         s->subdev_flags |= SDF_GROUND | SDF_COMMON | SDF_OTHER;
6004                 if (board->ai_maxdata > 0xffff)
6005                         s->subdev_flags |= SDF_LSAMPL;
6006                 if (devpriv->is_m_series)
6007                         s->subdev_flags |= SDF_SOFT_CALIBRATED;
6008                 s->n_chan       = board->n_adchan;
6009                 s->maxdata      = board->ai_maxdata;
6010                 s->range_table  = ni_range_lkup[board->gainlkup];
6011                 s->insn_read    = ni_ai_insn_read;
6012                 s->insn_config  = ni_ai_insn_config;
6013                 if (dev->irq) {
6014                         dev->read_subdev = s;
6015                         s->subdev_flags |= SDF_CMD_READ;
6016                         s->len_chanlist = 512;
6017                         s->do_cmdtest   = ni_ai_cmdtest;
6018                         s->do_cmd       = ni_ai_cmd;
6019                         s->cancel       = ni_ai_reset;
6020                         s->poll         = ni_ai_poll;
6021                         s->munge        = ni_ai_munge;
6022
6023                         if (devpriv->mite)
6024                                 s->async_dma_dir = DMA_FROM_DEVICE;
6025                 }
6026
6027                 /* reset the analog input configuration */
6028                 ni_ai_reset(dev, s);
6029         } else {
6030                 s->type         = COMEDI_SUBD_UNUSED;
6031         }
6032
6033         /* Analog Output subdevice */
6034         s = &dev->subdevices[NI_AO_SUBDEV];
6035         if (board->n_aochan) {
6036                 s->type         = COMEDI_SUBD_AO;
6037                 s->subdev_flags = SDF_WRITABLE | SDF_DEGLITCH | SDF_GROUND;
6038                 if (devpriv->is_m_series)
6039                         s->subdev_flags |= SDF_SOFT_CALIBRATED;
6040                 s->n_chan       = board->n_aochan;
6041                 s->maxdata      = board->ao_maxdata;
6042                 s->range_table  = board->ao_range_table;
6043                 s->insn_config  = ni_ao_insn_config;
6044                 s->insn_write   = ni_ao_insn_write;
6045
6046                 ret = comedi_alloc_subdev_readback(s);
6047                 if (ret)
6048                         return ret;
6049
6050                 /*
6051                  * Along with the IRQ we need either a FIFO or DMA for
6052                  * async command support.
6053                  */
6054                 if (dev->irq && (board->ao_fifo_depth || devpriv->mite)) {
6055                         dev->write_subdev = s;
6056                         s->subdev_flags |= SDF_CMD_WRITE;
6057                         s->len_chanlist = s->n_chan;
6058                         s->do_cmdtest   = ni_ao_cmdtest;
6059                         s->do_cmd       = ni_ao_cmd;
6060                         s->cancel       = ni_ao_reset;
6061                         if (!devpriv->is_m_series)
6062                                 s->munge        = ni_ao_munge;
6063
6064                         if (devpriv->mite)
6065                                 s->async_dma_dir = DMA_TO_DEVICE;
6066                 }
6067
6068                 if (devpriv->is_67xx)
6069                         init_ao_67xx(dev, s);
6070
6071                 /* reset the analog output configuration */
6072                 ni_ao_reset(dev, s);
6073         } else {
6074                 s->type         = COMEDI_SUBD_UNUSED;
6075         }
6076
6077         /* Digital I/O subdevice */
6078         s = &dev->subdevices[NI_DIO_SUBDEV];
6079         s->type         = COMEDI_SUBD_DIO;
6080         s->subdev_flags = SDF_WRITABLE | SDF_READABLE;
6081         s->n_chan       = board->has_32dio_chan ? 32 : 8;
6082         s->maxdata      = 1;
6083         s->range_table  = &range_digital;
6084         if (devpriv->is_m_series) {
6085 #ifdef PCIDMA
6086                 s->subdev_flags |= SDF_LSAMPL;
6087                 s->insn_bits    = ni_m_series_dio_insn_bits;
6088                 s->insn_config  = ni_m_series_dio_insn_config;
6089                 if (dev->irq) {
6090                         s->subdev_flags |= SDF_CMD_WRITE /* | SDF_CMD_READ */;
6091                         s->len_chanlist = s->n_chan;
6092                         s->do_cmdtest   = ni_cdio_cmdtest;
6093                         s->do_cmd       = ni_cdio_cmd;
6094                         s->cancel       = ni_cdio_cancel;
6095
6096                         /* M-series boards use DMA */
6097                         s->async_dma_dir = DMA_BIDIRECTIONAL;
6098                 }
6099
6100                 /* reset DIO and set all channels to inputs */
6101                 ni_writel(dev, NI_M_CDO_CMD_RESET |
6102                                NI_M_CDI_CMD_RESET,
6103                           NI_M_CDIO_CMD_REG);
6104                 ni_writel(dev, s->io_bits, NI_M_DIO_DIR_REG);
6105 #endif /* PCIDMA */
6106         } else {
6107                 s->insn_bits    = ni_dio_insn_bits;
6108                 s->insn_config  = ni_dio_insn_config;
6109
6110                 /* set all channels to inputs */
6111                 devpriv->dio_control = NISTC_DIO_CTRL_DIR(s->io_bits);
6112                 ni_writew(dev, devpriv->dio_control, NISTC_DIO_CTRL_REG);
6113         }
6114
6115         /* 8255 device */
6116         s = &dev->subdevices[NI_8255_DIO_SUBDEV];
6117         if (board->has_8255) {
6118                 ret = subdev_8255_init(dev, s, ni_8255_callback,
6119                                        NI_E_8255_BASE);
6120                 if (ret)
6121                         return ret;
6122         } else {
6123                 s->type = COMEDI_SUBD_UNUSED;
6124         }
6125
6126         /* formerly general purpose counter/timer device, but no longer used */
6127         s = &dev->subdevices[NI_UNUSED_SUBDEV];
6128         s->type = COMEDI_SUBD_UNUSED;
6129
6130         /* Calibration subdevice */
6131         s = &dev->subdevices[NI_CALIBRATION_SUBDEV];
6132         s->type         = COMEDI_SUBD_CALIB;
6133         s->subdev_flags = SDF_INTERNAL;
6134         s->n_chan       = 1;
6135         s->maxdata      = 0;
6136         if (devpriv->is_m_series) {
6137                 /* internal PWM output used for AI nonlinearity calibration */
6138                 s->insn_config  = ni_m_series_pwm_config;
6139
6140                 ni_writel(dev, 0x0, NI_M_CAL_PWM_REG);
6141         } else if (devpriv->is_6143) {
6142                 /* internal PWM output used for AI nonlinearity calibration */
6143                 s->insn_config  = ni_6143_pwm_config;
6144         } else {
6145                 s->subdev_flags |= SDF_WRITABLE;
6146                 s->insn_read    = ni_calib_insn_read;
6147                 s->insn_write   = ni_calib_insn_write;
6148
6149                 /* setup the caldacs and find the real n_chan and maxdata */
6150                 caldac_setup(dev, s);
6151         }
6152
6153         /* EEPROM subdevice */
6154         s = &dev->subdevices[NI_EEPROM_SUBDEV];
6155         s->type         = COMEDI_SUBD_MEMORY;
6156         s->subdev_flags = SDF_READABLE | SDF_INTERNAL;
6157         s->maxdata      = 0xff;
6158         if (devpriv->is_m_series) {
6159                 s->n_chan       = M_SERIES_EEPROM_SIZE;
6160                 s->insn_read    = ni_m_series_eeprom_insn_read;
6161         } else {
6162                 s->n_chan       = 512;
6163                 s->insn_read    = ni_eeprom_insn_read;
6164         }
6165
6166         /* Digital I/O (PFI) subdevice */
6167         s = &dev->subdevices[NI_PFI_DIO_SUBDEV];
6168         s->type         = COMEDI_SUBD_DIO;
6169         s->maxdata      = 1;
6170         if (devpriv->is_m_series) {
6171                 s->n_chan       = 16;
6172                 s->insn_bits    = ni_pfi_insn_bits;
6173                 s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
6174
6175                 ni_writew(dev, s->state, NI_M_PFI_DO_REG);
6176                 for (i = 0; i < NUM_PFI_OUTPUT_SELECT_REGS; ++i) {
6177                         ni_writew(dev, devpriv->pfi_output_select_reg[i],
6178                                   NI_M_PFI_OUT_SEL_REG(i));
6179                 }
6180         } else {
6181                 s->n_chan       = 10;
6182                 s->subdev_flags = SDF_INTERNAL;
6183         }
6184         s->insn_config  = ni_pfi_insn_config;
6185
6186         ni_set_bits(dev, NISTC_IO_BIDIR_PIN_REG, ~0, 0);
6187
6188         /* cs5529 calibration adc */
6189         s = &dev->subdevices[NI_CS5529_CALIBRATION_SUBDEV];
6190         if (devpriv->is_67xx) {
6191                 s->type = COMEDI_SUBD_AI;
6192                 s->subdev_flags = SDF_READABLE | SDF_DIFF | SDF_INTERNAL;
6193                 /*  one channel for each analog output channel */
6194                 s->n_chan = board->n_aochan;
6195                 s->maxdata = (1 << 16) - 1;
6196                 s->range_table = &range_unknown;        /* XXX */
6197                 s->insn_read = cs5529_ai_insn_read;
6198                 s->insn_config = NULL;
6199                 init_cs5529(dev);
6200         } else {
6201                 s->type = COMEDI_SUBD_UNUSED;
6202         }
6203
6204         /* Serial */
6205         s = &dev->subdevices[NI_SERIAL_SUBDEV];
6206         s->type = COMEDI_SUBD_SERIAL;
6207         s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
6208         s->n_chan = 1;
6209         s->maxdata = 0xff;
6210         s->insn_config = ni_serial_insn_config;
6211         devpriv->serial_interval_ns = 0;
6212         devpriv->serial_hw_mode = 0;
6213
6214         /* RTSI */
6215         s = &dev->subdevices[NI_RTSI_SUBDEV];
6216         s->type = COMEDI_SUBD_DIO;
6217         s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
6218         s->n_chan = 8;
6219         s->maxdata = 1;
6220         s->insn_bits = ni_rtsi_insn_bits;
6221         s->insn_config = ni_rtsi_insn_config;
6222         ni_rtsi_init(dev);
6223
6224         /* allocate and initialize the gpct counter device */
6225         devpriv->counter_dev = ni_gpct_device_construct(dev,
6226                                         ni_gpct_write_register,
6227                                         ni_gpct_read_register,
6228                                         (devpriv->is_m_series)
6229                                                 ? ni_gpct_variant_m_series
6230                                                 : ni_gpct_variant_e_series,
6231                                         NUM_GPCT,
6232                                         NUM_GPCT,
6233                                         &devpriv->routing_tables);
6234         if (!devpriv->counter_dev)
6235                 return -ENOMEM;
6236
6237         /* Counter (gpct) subdevices */
6238         for (i = 0; i < NUM_GPCT; ++i) {
6239                 struct ni_gpct *gpct = &devpriv->counter_dev->counters[i];
6240
6241                 /* setup and initialize the counter */
6242                 ni_tio_init_counter(gpct);
6243
6244                 s = &dev->subdevices[NI_GPCT_SUBDEV(i)];
6245                 s->type         = COMEDI_SUBD_COUNTER;
6246                 s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_LSAMPL;
6247                 s->n_chan       = 3;
6248                 s->maxdata      = (devpriv->is_m_series) ? 0xffffffff
6249                                                          : 0x00ffffff;
6250                 s->insn_read    = ni_tio_insn_read;
6251                 s->insn_write   = ni_tio_insn_write;
6252                 s->insn_config  = ni_tio_insn_config;
6253 #ifdef PCIDMA
6254                 if (dev->irq && devpriv->mite) {
6255                         s->subdev_flags |= SDF_CMD_READ /* | SDF_CMD_WRITE */;
6256                         s->len_chanlist = 1;
6257                         s->do_cmdtest   = ni_tio_cmdtest;
6258                         s->do_cmd       = ni_gpct_cmd;
6259                         s->cancel       = ni_gpct_cancel;
6260
6261                         s->async_dma_dir = DMA_BIDIRECTIONAL;
6262                 }
6263 #endif
6264                 s->private      = gpct;
6265         }
6266
6267         /* Initialize GPFO_{0,1} to produce output of counters */
6268         ni_set_gout_routing(0, 0, dev); /* output of counter 0; DAQ STC, p338 */
6269         ni_set_gout_routing(0, 1, dev); /* output of counter 1; DAQ STC, p338 */
6270
6271         /* Frequency output subdevice */
6272         s = &dev->subdevices[NI_FREQ_OUT_SUBDEV];
6273         s->type         = COMEDI_SUBD_COUNTER;
6274         s->subdev_flags = SDF_READABLE | SDF_WRITABLE;
6275         s->n_chan       = 1;
6276         s->maxdata      = 0xf;
6277         s->insn_read    = ni_freq_out_insn_read;
6278         s->insn_write   = ni_freq_out_insn_write;
6279         s->insn_config  = ni_freq_out_insn_config;
6280
6281         if (dev->irq) {
6282                 ni_stc_writew(dev,
6283                               (irq_polarity ? NISTC_INT_CTRL_INT_POL : 0) |
6284                               (NISTC_INT_CTRL_3PIN_INT & 0) |
6285                               NISTC_INT_CTRL_INTA_ENA |
6286                               NISTC_INT_CTRL_INTB_ENA |
6287                               NISTC_INT_CTRL_INTA_SEL(interrupt_pin) |
6288                               NISTC_INT_CTRL_INTB_SEL(interrupt_pin),
6289                               NISTC_INT_CTRL_REG);
6290         }
6291
6292         /* DMA setup */
6293         ni_writeb(dev, devpriv->ai_ao_select_reg, NI_E_DMA_AI_AO_SEL_REG);
6294         ni_writeb(dev, devpriv->g0_g1_select_reg, NI_E_DMA_G0_G1_SEL_REG);
6295
6296         if (devpriv->is_6xxx) {
6297                 ni_writeb(dev, 0, NI611X_MAGIC_REG);
6298         } else if (devpriv->is_m_series) {
6299                 int channel;
6300
6301                 for (channel = 0; channel < board->n_aochan; ++channel) {
6302                         ni_writeb(dev, 0xf,
6303                                   NI_M_AO_WAVEFORM_ORDER_REG(channel));
6304                         ni_writeb(dev, 0x0,
6305                                   NI_M_AO_REF_ATTENUATION_REG(channel));
6306                 }
6307                 ni_writeb(dev, 0x0, NI_M_AO_CALIB_REG);
6308         }
6309
6310         return 0;
6311 }
6312
6313 static void mio_common_detach(struct comedi_device *dev)
6314 {
6315         struct ni_private *devpriv = dev->private;
6316
6317         if (devpriv)
6318                 ni_gpct_device_destroy(devpriv->counter_dev);
6319 }