change address parameter to unsigned long for inb/outb/readb/writeb
[comedi.git] / comedi / drivers / ni_labpc.c
1 /*
2     ni_labpc.c driver for National Instruments Lab-PC series boards and compatibles
3     Copyright (C) 2001, 2002 Frank Mori Hess <fmhess@users.sourceforge.net>
4
5     PCMCIA crap at end of file is adapted from dummy_cs.c 1.31 2001/08/24 12:13:13
6     from the pcmcia package.
7     The initial developer of the pcmcia dummy_cs.c code is David A. Hinds
8     <dahinds@users.sourceforge.net>.  Portions created by David A. Hinds
9     are Copyright (C) 1999 David A. Hinds.  All Rights Reserved.
10
11     This program is free software; you can redistribute it and/or modify
12     it under the terms of the GNU General Public License as published by
13     the Free Software Foundation; either version 2 of the License, or
14     (at your option) any later version.
15
16     This program is distributed in the hope that it will be useful,
17     but WITHOUT ANY WARRANTY; without even the implied warranty of
18     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19     GNU General Public License for more details.
20
21     You should have received a copy of the GNU General Public License
22     along with this program; if not, write to the Free Software
23     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
24
25 ************************************************************************
26 */
27 /*
28 Driver: ni_labpc.o
29 Description: National Instruments Lab-PC (& compatibles)
30 Author: Frank Mori Hess <fmhess@users.sourceforge.net>
31 Devices: [National Instruments] DAQCard-1200 (daqcard-1200), Lab-PC-1200 (labpc-1200),
32   Lab-PC-1200AI (labpc-1200ai), Lab-PC+ (lab-pc+), PCI-1200 (pci-1200)
33 Status: works
34
35 Thanks go to Fredrik Lingvall for much testing and perseverance in
36 helping to debug daqcard-1200 support.
37
38 Tested with lab-pc-1200.  For the older Lab-PC+, not all input ranges
39 and analog references will work, the available ranges/arefs will
40 depend on how you have configured the jumpers on your board
41 (see your owner's manual).
42
43 The 1200 series boards have onboard calibration dacs for correcting
44 analog input/output offsets and gains.  The proper settings for these
45 caldacs are stored on the board's eeprom.  To read the caldac values
46 from the eeprom and store them into a file that can be then be used by
47 comedilib, use the comedi_calibrate program.
48
49 Configuration options - ISA boards:
50   [0] - I/O port base address
51   [1] - IRQ (optional, required for timed or externally triggered conversions)
52   [2] - DMA channel (optional)
53
54 Configuration options - PCI boards:
55   [0] - bus (optional)
56   [1] - slot (optional)
57
58 Configuration options - PCMCIA boards:
59   none
60
61 The Lab-pc+ and daqcard-1200 have quirky chanlist requirements
62 when scanning multiple channels.  Multiple channel scan
63 sequence must start at highest channel, then decrement down to
64 channel 0.  The rest of the cards can scan down like lab-pc+ or scan
65 up from channel zero.  Chanlists consisting of all one channel
66 are also legal, and allow you to pace conversions in bursts.
67
68 */
69
70 /*
71
72 NI manuals:
73 341309a (labpc-1200 register manual)
74 340988a (daqcard-1200)
75 340914a (pci-1200)
76 320502b (lab-pc+)
77
78 */
79
80 #undef LABPC_DEBUG
81 //#define LABPC_DEBUG   // enable debugging messages
82
83 #include <linux/comedidev.h>
84
85 #include <linux/delay.h>
86 #include <asm/dma.h>
87
88 #include "8253.h"
89 #include "8255.h"
90 #include "mite.h"
91 #include "comedi_fc.h"
92
93 #if defined(CONFIG_PCMCIA) || defined(CONFIG_PCMCIA_MODULE)
94
95 #include <pcmcia/version.h>
96 #include <pcmcia/cs_types.h>
97 #include <pcmcia/cs.h>
98 #include <pcmcia/cistpl.h>
99 #include <pcmcia/cisreg.h>
100 #include <pcmcia/ds.h>
101 #include <pcmcia/bus_ops.h>
102
103 /*
104    A linked list of "instances" of the dummy device.  Each actual
105    PCMCIA card corresponds to one device instance, and is described
106    by one dev_link_t structure (defined in ds.h).
107
108    You may not want to use a linked list for this -- for example, the
109    memory card driver uses an array of dev_link_t pointers, where minor
110    device numbers are used to derive the corresponding array index.
111 */
112
113 static dev_link_t *pcmcia_dev_list = NULL;
114
115 #endif // CONFIG_PCMCIA
116
117 #define LABPC_SIZE           32 // size of io region used by board
118 #define LABPC_TIMER_BASE            500 // 2 MHz master clock
119 #define EEPROM_SIZE     256     // 256 byte eeprom
120 #define NUM_AO_CHAN     2       // boards have two analog output channels
121
122 /* Registers for the lab-pc+ */
123
124 //write-only registers
125 #define COMMAND1_REG    0x0
126 #define   ADC_GAIN_MASK (0x7 << 4)
127 #define   ADC_CHAN_BITS(x)      ((x) & 0x7)
128 #define   ADC_SCAN_EN_BIT       0x80    // enables multi channel scans
129 #define COMMAND2_REG    0x1
130 #define   PRETRIG_BIT   0x1     // enable pretriggering (used in conjunction with SWTRIG)
131 #define   HWTRIG_BIT    0x2     // enable paced conversions on external trigger
132 #define   SWTRIG_BIT    0x4     // enable paced conversions
133 #define   CASCADE_BIT   0x8     // use two cascaded counters for pacing
134 #define   DAC_PACED_BIT(channel)        (0x40 << ((channel) & 0x1))
135 #define COMMAND3_REG    0x2
136 #define   DMA_EN_BIT    0x1     // enable dma transfers
137 #define   DIO_INTR_EN_BIT       0x2     // enable interrupts for 8255
138 #define   DMATC_INTR_EN_BIT     0x4     // enable dma terminal count interrupt
139 #define   TIMER_INTR_EN_BIT     0x8     // enable timer interrupt
140 #define   ERR_INTR_EN_BIT       0x10    // enable error interrupt
141 #define   ADC_FNE_INTR_EN_BIT   0x20    // enable fifo not empty interrupt
142 #define ADC_CONVERT_REG 0x3
143 #define DAC_LSB_REG(channel)    (0x4 + 2 * ((channel) & 0x1))
144 #define DAC_MSB_REG(channel)    (0x5 + 2 * ((channel) & 0x1))
145 #define ADC_CLEAR_REG   0x8
146 #define DMATC_CLEAR_REG 0xa
147 #define TIMER_CLEAR_REG 0xc
148 #define COMMAND6_REG    0xe     // 1200 boards only
149 #define   ADC_COMMON_BIT        0x1     // select ground or common-mode reference
150 #define   ADC_UNIP_BIT  0x2     // adc unipolar
151 #define   DAC_UNIP_BIT(channel) (0x4 << ((channel) & 0x1))      // dac unipolar
152 #define   ADC_FHF_INTR_EN_BIT   0x20    // enable fifo half full interrupt
153 #define   A1_INTR_EN_BIT        0x40    // enable interrupt on end of hardware count
154 #define   ADC_SCAN_UP_BIT 0x80  // scan up from channel zero instead of down to zero
155 #define COMMAND4_REG    0xf
156 #define   INTERVAL_SCAN_EN_BIT  0x1     // enables 'interval' scanning
157 #define   EXT_SCAN_EN_BIT       0x2     // enables external signal on counter b1 output to trigger scan
158 #define   EXT_CONVERT_OUT_BIT   0x4     // chooses direction (output or input) for EXTCONV* line
159 #define   ADC_DIFF_BIT  0x8     // chooses differential inputs for adc (in conjunction with board jumper)
160 #define   EXT_CONVERT_DISABLE_BIT       0x10
161 #define COMMAND5_REG    0x1c    // 1200 boards only, calibration stuff
162 #define   EEPROM_WRITE_UNPROTECT_BIT    0x4// enable eeprom for write
163 #define   DITHER_EN_BIT 0x8     // enable dithering
164 #define   CALDAC_LOAD_BIT       0x10    // load calibration dac
165 #define   SCLOCK_BIT    0x20    // serial clock - rising edge writes, falling edge reads
166 #define   SDATA_BIT     0x40    // serial data bit for writing to eeprom or calibration dacs
167 #define   EEPROM_EN_BIT 0x80    // enable eeprom for read/write
168 #define INTERVAL_COUNT_REG      0x1e
169 #define INTERVAL_LOAD_REG       0x1f
170 #define   INTERVAL_LOAD_BITS    0x1
171
172 // read-only registers
173 #define STATUS1_REG     0x0
174 #define   DATA_AVAIL_BIT        0x1     // data is available in fifo
175 #define   OVERRUN_BIT   0x2     // overrun has occurred
176 #define   OVERFLOW_BIT  0x4     // fifo overflow
177 #define   TIMER_BIT     0x8     // timer interrupt has occured
178 #define   DMATC_BIT     0x10    // dma terminal count has occured
179 #define   EXT_TRIG_BIT  0x40    // external trigger has occured
180 #define STATUS2_REG     0x1d    // 1200 boards only
181 #define   EEPROM_OUT_BIT        0x1     // programmable eeprom serial output
182 #define   A1_TC_BIT     0x2     // counter A1 terminal count
183 #define   FNHF_BIT      0x4     // fifo not half full
184 #define ADC_FIFO_REG    0xa
185
186 #define DIO_BASE_REG    0x10
187 #define COUNTER_A_BASE_REG      0x14
188 #define COUNTER_A_CONTROL_REG   (COUNTER_A_BASE_REG + 0x3)
189 #define   INIT_A0_BITS  0x14    // check modes put conversion pacer output in harmless state (a0 mode 2)
190 #define   INIT_A1_BITS  0x70    // put hardware conversion counter output in harmless state (a1 mode 0)
191 #define COUNTER_B_BASE_REG      0x18
192
193
194 static int labpc_attach(comedi_device *dev,comedi_devconfig *it);
195 static int labpc_detach(comedi_device *dev);
196 static int labpc_cancel(comedi_device *dev, comedi_subdevice *s);
197 static void labpc_interrupt(int irq, void *d, struct pt_regs *regs);
198 static int labpc_drain_fifo(comedi_device *dev);
199 static void labpc_drain_dma(comedi_device *dev);
200 static void handle_isa_dma(comedi_device *dev);
201 static void labpc_drain_dregs(comedi_device *dev);
202 static int labpc_ai_cmdtest(comedi_device *dev,comedi_subdevice *s,comedi_cmd *cmd);
203 static int labpc_ai_cmd(comedi_device *dev, comedi_subdevice *s);
204 static int labpc_ai_rinsn(comedi_device *dev, comedi_subdevice *s, comedi_insn *insn, lsampl_t *data);
205 static int labpc_ao_winsn(comedi_device *dev, comedi_subdevice *s, comedi_insn *insn, lsampl_t *data);
206 static int labpc_ao_rinsn(comedi_device *dev, comedi_subdevice *s, comedi_insn *insn, lsampl_t *data);
207 static int labpc_calib_read_insn(comedi_device *dev, comedi_subdevice *s, comedi_insn *insn, lsampl_t *data);
208 static int labpc_calib_write_insn(comedi_device *dev, comedi_subdevice *s, comedi_insn *insn, lsampl_t *data);
209 static int labpc_eeprom_read_insn(comedi_device *dev, comedi_subdevice *s, comedi_insn *insn, lsampl_t *data);
210 static int labpc_eeprom_write_insn(comedi_device *dev, comedi_subdevice *s, comedi_insn *insn, lsampl_t *data);
211 static unsigned int labpc_suggest_transfer_size(comedi_cmd cmd);
212 static void labpc_adc_timing(comedi_device *dev, comedi_cmd *cmd);
213 static struct mite_struct* labpc_find_device(int bus, int slot);
214 static unsigned int labpc_inb(unsigned long address);
215 static void labpc_outb(unsigned int byte, unsigned long address);
216 static unsigned int labpc_readb(unsigned long address);
217 static void labpc_writeb(unsigned int byte, unsigned long address);
218 static int labpc_dio_mem_callback(int dir, int port, int data, unsigned long arg);
219 static void labpc_serial_out(comedi_device *dev, unsigned int value, unsigned int num_bits);
220 static unsigned int labpc_serial_in(comedi_device *dev);
221 static unsigned int labpc_eeprom_read(comedi_device *dev, unsigned int address);
222 static unsigned int labpc_eeprom_read_status(comedi_device *dev);
223 static unsigned int labpc_eeprom_write(comedi_device *dev, unsigned int address, unsigned int value);
224 static void write_caldac(comedi_device *dev, unsigned int channel, unsigned int value);
225
226 enum labpc_bustype {isa_bustype, pci_bustype, pcmcia_bustype};
227 enum labpc_register_layout {labpc_plus_layout, labpc_1200_layout};
228 enum transfer_type {fifo_not_empty_transfer, fifo_half_full_transfer, isa_dma_transfer};
229 enum scan_mode
230 {
231         MODE_SINGLE_CHAN,
232         MODE_SINGLE_CHAN_INTERVAL,
233         MODE_MULT_CHAN_UP,
234         MODE_MULT_CHAN_DOWN,
235 };
236
237 typedef struct labpc_board_struct{
238         char *name;
239         int device_id;  // device id for pci and pcmcia boards
240         int ai_speed;   // maximum input speed in nanoseconds
241         enum labpc_bustype bustype;     // ISA/PCI/etc.
242         enum labpc_register_layout register_layout;     // 1200 has extra registers compared to pc+
243         int has_ao;     // has analog output true/false
244         // function pointers so we can use inb/outb or readb/writeb as appropriate
245         unsigned int (*read_byte)(unsigned long address);
246         void (*write_byte)(unsigned int byte, unsigned long address);
247         comedi_lrange *ai_range_table;
248         int *ai_range_code;
249         int *ai_range_is_unipolar;
250         unsigned ai_scan_up : 1;        // board can auto scan up in ai channels, not just down
251 }labpc_board;
252
253 //analog input ranges
254
255 #define NUM_LABPC_PLUS_AI_RANGES 16
256 // indicates unipolar ranges
257 static int labpc_plus_is_unipolar[NUM_LABPC_PLUS_AI_RANGES] =
258 {
259         0,
260         0,
261         0,
262         0,
263         0,
264         0,
265         0,
266         0,
267         1,
268         1,
269         1,
270         1,
271         1,
272         1,
273         1,
274         1,
275 };
276 // map range index to gain bits
277 static int labpc_plus_ai_gain_bits[NUM_LABPC_PLUS_AI_RANGES] =
278 {
279         0x00,
280         0x10,
281         0x20,
282         0x30,
283         0x40,
284         0x50,
285         0x60,
286         0x70,
287         0x00,
288         0x10,
289         0x20,
290         0x30,
291         0x40,
292         0x50,
293         0x60,
294         0x70,
295 };
296 static comedi_lrange range_labpc_plus_ai = {
297         NUM_LABPC_PLUS_AI_RANGES,
298         {
299                 BIP_RANGE(5),
300                 BIP_RANGE(4),
301                 BIP_RANGE(2.5),
302                 BIP_RANGE(1),
303                 BIP_RANGE(0.5),
304                 BIP_RANGE(0.25),
305                 BIP_RANGE(0.1),
306                 BIP_RANGE(0.05),
307                 UNI_RANGE(10),
308                 UNI_RANGE(8),
309                 UNI_RANGE(5),
310                 UNI_RANGE(2),
311                 UNI_RANGE(1),
312                 UNI_RANGE(0.5),
313                 UNI_RANGE(0.2),
314                 UNI_RANGE(0.1),
315         }
316 };
317
318 #define NUM_LABPC_1200_AI_RANGES 14
319 // indicates unipolar ranges
320 static int labpc_1200_is_unipolar[NUM_LABPC_1200_AI_RANGES] =
321 {
322         0,
323         0,
324         0,
325         0,
326         0,
327         0,
328         0,
329         1,
330         1,
331         1,
332         1,
333         1,
334         1,
335         1,
336 };
337 // map range index to gain bits
338 static int labpc_1200_ai_gain_bits[NUM_LABPC_1200_AI_RANGES] =
339 {
340         0x00,
341         0x20,
342         0x30,
343         0x40,
344         0x50,
345         0x60,
346         0x70,
347         0x00,
348         0x20,
349         0x30,
350         0x40,
351         0x50,
352         0x60,
353         0x70,
354 };
355 static comedi_lrange range_labpc_1200_ai = {
356         NUM_LABPC_1200_AI_RANGES,
357         {
358                 BIP_RANGE(5),
359                 BIP_RANGE(2.5),
360                 BIP_RANGE(1),
361                 BIP_RANGE(0.5),
362                 BIP_RANGE(0.25),
363                 BIP_RANGE(0.1),
364                 BIP_RANGE(0.05),
365                 UNI_RANGE(10),
366                 UNI_RANGE(5),
367                 UNI_RANGE(2),
368                 UNI_RANGE(1),
369                 UNI_RANGE(0.5),
370                 UNI_RANGE(0.2),
371                 UNI_RANGE(0.1),
372         }
373 };
374
375 //analog output ranges
376
377 #define AO_RANGE_IS_UNIPOLAR 0x1
378
379 static comedi_lrange range_labpc_ao = {
380         2,
381         {
382                 BIP_RANGE(5),
383                 UNI_RANGE(10),
384         }
385 };
386
387 static labpc_board labpc_boards[] =
388 {
389 #if defined(CONFIG_PCMCIA) || defined(CONFIG_PCMCIA_MODULE)
390         {
391                 name:   "daqcard-1200",
392                 device_id:      0x103,  // 0x10b is manufacturer id, 0x103 is device id
393                 ai_speed:       10000,
394                 bustype:        pcmcia_bustype,
395                 register_layout:        labpc_1200_layout,
396                 has_ao: 1,
397                 read_byte:      labpc_inb,
398                 write_byte:     labpc_outb,
399                 ai_range_table: &range_labpc_1200_ai,
400                 ai_range_code: labpc_1200_ai_gain_bits,
401                 ai_range_is_unipolar: labpc_1200_is_unipolar,
402                 ai_scan_up: 0,
403         },
404 #endif // CONFIG_PCMCIA
405         {
406                 name:   "lab-pc-1200",
407                 ai_speed:       10000,
408                 bustype:        isa_bustype,
409                 register_layout:        labpc_1200_layout,
410                 has_ao: 1,
411                 read_byte:      labpc_inb,
412                 write_byte:     labpc_outb,
413                 ai_range_table: &range_labpc_1200_ai,
414                 ai_range_code: labpc_1200_ai_gain_bits,
415                 ai_range_is_unipolar: labpc_1200_is_unipolar,
416                 ai_scan_up: 1,
417         },
418         {
419                 name:   "lab-pc-1200ai",
420                 ai_speed:       10000,
421                 bustype:        isa_bustype,
422                 register_layout:        labpc_1200_layout,
423                 has_ao: 0,
424                 read_byte:      labpc_inb,
425                 write_byte:     labpc_outb,
426                 ai_range_table: &range_labpc_1200_ai,
427                 ai_range_code: labpc_1200_ai_gain_bits,
428                 ai_range_is_unipolar: labpc_1200_is_unipolar,
429                 ai_scan_up: 1,
430         },
431         {
432                 name:   "lab-pc+",
433                 ai_speed:       12000,
434                 bustype:        isa_bustype,
435                 register_layout:        labpc_plus_layout,
436                 has_ao: 1,
437                 read_byte:      labpc_inb,
438                 write_byte:     labpc_outb,
439                 ai_range_table: &range_labpc_plus_ai,
440                 ai_range_code: labpc_plus_ai_gain_bits,
441                 ai_range_is_unipolar: labpc_plus_is_unipolar,
442                 ai_scan_up: 0,
443         },
444         {
445                 name:   "pci-1200",
446                 device_id:      0x161,
447                 ai_speed:       10000,
448                 bustype:        pci_bustype,
449                 register_layout:        labpc_1200_layout,
450                 has_ao: 1,
451                 read_byte:      labpc_readb,
452                 write_byte:     labpc_writeb,
453                 ai_range_table: &range_labpc_1200_ai,
454                 ai_range_code: labpc_1200_ai_gain_bits,
455                 ai_range_is_unipolar: labpc_1200_is_unipolar,
456                 ai_scan_up: 1,
457         },
458 };
459
460 /*
461  * Useful for shorthand access to the particular board structure
462  */
463 #define thisboard ((labpc_board *)dev->board_ptr)
464
465 static const int dma_buffer_size = 0xff00;      // size in bytes of dma buffer
466 static const int sample_size = 2;       // 2 bytes per sample
467
468 typedef struct{
469         struct mite_struct *mite;       // for mite chip on pci-1200
470         volatile unsigned long long count;  /* number of data points left to be taken */
471         unsigned int ao_value[NUM_AO_CHAN];     // software copy of analog output values
472         // software copys of bits written to command registers
473         volatile unsigned int command1_bits;
474         volatile unsigned int command2_bits;
475         volatile unsigned int command3_bits;
476         volatile unsigned int command4_bits;
477         volatile unsigned int command5_bits;
478         volatile unsigned int command6_bits;
479         // store last read of board status registers
480         volatile unsigned int status1_bits;
481         volatile unsigned int status2_bits;
482         unsigned int divisor_a0;        /* value to load into board's counter a0 (conversion pacing) for timed conversions */
483         unsigned int divisor_b0;        /* value to load into board's counter b0 (master) for timed conversions */
484         unsigned int divisor_b1;        /* value to load into board's counter b1 (scan pacing) for timed conversions */
485         unsigned int dma_chan;  // dma channel to use
486         u16 *dma_buffer;        // buffer ai will dma into
487         unsigned int dma_transfer_size; // transfer size in bytes for current transfer
488         enum transfer_type current_transfer;    // we are using dma/fifo-half-full/etc.
489         unsigned int eeprom_data[EEPROM_SIZE];  // stores contents of board's eeprom
490         unsigned int caldac[16];        // stores settings of calibration dacs
491 }labpc_private;
492
493 #define devpriv ((labpc_private *)dev->private)
494
495 static comedi_driver driver_labpc={
496         driver_name:    "ni_labpc",
497         module:         THIS_MODULE,
498         attach:         labpc_attach,
499         detach:         labpc_detach,
500         num_names:      sizeof(labpc_boards) / sizeof(labpc_board),
501         board_name:     (char **)labpc_boards,
502         offset:         sizeof(labpc_board),
503 };
504
505 static struct pci_device_id labpc_pci_table[] __devinitdata = {
506         { PCI_VENDOR_ID_NATINST, 0x161, PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
507         { 0 }
508 };
509 MODULE_DEVICE_TABLE(pci, labpc_pci_table);
510
511 static int labpc_attach(comedi_device *dev, comedi_devconfig *it)
512 {
513         comedi_subdevice *s;
514         int iobase = 0;
515         int irq = 0;
516         int dma_chan = 0;
517         int lsb, msb;
518         int i;
519         unsigned long flags, isr_flags;
520         int ret;
521 #if defined(CONFIG_PCMCIA) || defined(CONFIG_PCMCIA_MODULE)
522         dev_link_t *link;
523 #endif
524
525         /* allocate and initialize dev->private */
526         if(alloc_private(dev, sizeof(labpc_private)) < 0)
527                 return -ENOMEM;
528
529         // get base address, irq etc. based on bustype
530         switch(thisboard->bustype)
531         {
532                 case isa_bustype:
533                         iobase = it->options[0];
534                         irq = it->options[1];
535                         dma_chan = it->options[2];
536                         break;
537                 case pci_bustype:
538                         devpriv->mite = labpc_find_device(it->options[0], it->options[1]);
539                         if(devpriv->mite == NULL)
540                         {
541                                 return -EIO;
542                         }
543                         if(thisboard->device_id != mite_device_id(devpriv->mite))
544                         {       // this should never happen since this driver only supports one type of pci board
545                                 printk("bug! mite device id does not match boardtype definition\n");
546                                 return -EINVAL;
547                         }
548                         ret = mite_setup(devpriv->mite);
549                         if(ret < 0) return ret;
550                         iobase = mite_iobase(devpriv->mite);
551                         irq = mite_irq(devpriv->mite);
552                         break;
553                 case pcmcia_bustype:
554 #if defined(CONFIG_PCMCIA) || defined(CONFIG_PCMCIA_MODULE)
555                         link = pcmcia_dev_list; /* XXX hack */
556                         if(!link) return -EIO;
557                         iobase = link->io.BasePort1;
558                         irq = link->irq.AssignedIRQ;
559 #else
560                         printk(" driver was not compiled with pcmcia support\n");
561                         return -EINVAL;
562 #endif // CONFIG_PCMCIA
563                         break;
564                 default:
565                         printk("bug! couldn't determine board type\n");\
566                         return -EINVAL;
567                         break;
568         }
569         printk("comedi%d: ni_labpc: %s, io 0x%x", dev->minor, thisboard->name, iobase);
570         if(irq)
571         {
572                 printk(", irq %i", irq);
573         }
574         if(dma_chan)
575         {
576                 printk(", dma %i", dma_chan);
577         }
578         printk("\n");
579
580         if(iobase == 0)
581         {
582                 printk("io base address is zero!\n");
583                 return -EINVAL;
584         }
585
586         // request io regions for isa boards
587         if(thisboard->bustype == isa_bustype)
588         {
589                 /* check if io addresses are available */
590                 if(check_region(iobase, LABPC_SIZE) < 0)
591                 {
592                         printk("I/O port conflict\n");
593                         return -EIO;
594                 }
595                 request_region(iobase, LABPC_SIZE, driver_labpc.driver_name);
596         }
597         dev->iobase = iobase;
598
599         // initialize board's command registers
600         thisboard->write_byte(devpriv->command1_bits, dev->iobase + COMMAND1_REG);
601         thisboard->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
602         thisboard->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
603         thisboard->write_byte(devpriv->command4_bits, dev->iobase + COMMAND4_REG);
604         if(thisboard->register_layout == labpc_1200_layout)
605         {
606                 thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
607                 thisboard->write_byte(devpriv->command6_bits, dev->iobase + COMMAND6_REG);
608         }
609
610         /* grab our IRQ */
611         if(irq < 0)
612         {
613                 printk("irq out of range\n");
614                 return -EINVAL;
615         }
616         if(irq)
617         {
618                 isr_flags = 0;
619                 if((thisboard->bustype == pci_bustype)
620 #if 0
621                                 // I'm fairly sure the daqcard-1200 interrupt cannot be shared
622                                 || (thisboard->bustype == pcmcia_bustype)
623 #endif
624                                 )
625                         isr_flags |= SA_SHIRQ;
626                 if(comedi_request_irq( irq, labpc_interrupt, isr_flags, driver_labpc.driver_name, dev))
627                 {
628                         printk( "unable to allocate irq %d\n", irq);
629                         return -EINVAL;
630                 }
631         }
632         dev->irq = irq;
633
634         // grab dma channel
635         if(dma_chan < 0 || dma_chan > 3)
636         {
637                 printk(" invalid dma channel\n");
638                 return -EINVAL;
639         }else if(dma_chan)
640         {
641                 // allocate dma buffer
642                 devpriv->dma_buffer = kmalloc(dma_buffer_size, GFP_KERNEL | GFP_DMA);
643                 if(devpriv->dma_buffer == NULL)
644                 {
645                         printk(" failed to allocate dma buffer\n");
646                         return -ENOMEM;
647                 }
648                 if(request_dma(dma_chan, driver_labpc.driver_name))
649                 {
650                         printk(" failed to allocate dma channel %i\n", dma_chan);
651                         return -EINVAL;
652                 }
653                 devpriv->dma_chan = dma_chan;
654                 flags = claim_dma_lock();
655                 disable_dma(devpriv->dma_chan);
656                 set_dma_mode(devpriv->dma_chan, DMA_MODE_READ);
657                 release_dma_lock(flags);
658         }
659
660         dev->board_name = thisboard->name;
661
662         if(alloc_subdevices(dev, 5) < 0)
663                 return -ENOMEM;
664
665         /* analog input subdevice */
666         s = dev->subdevices + 0;
667         dev->read_subdev = s;
668         s->type = COMEDI_SUBD_AI;
669         s->subdev_flags = SDF_READABLE | SDF_GROUND | SDF_COMMON | SDF_DIFF;
670         s->n_chan = 8;
671         s->len_chanlist = 8;
672         s->maxdata = (1 << 12) - 1;     // 12 bit resolution
673         s->range_table = thisboard->ai_range_table;
674         s->do_cmd = labpc_ai_cmd;
675         s->do_cmdtest = labpc_ai_cmdtest;
676         s->insn_read = labpc_ai_rinsn;
677         s->cancel = labpc_cancel;
678
679         /* analog output */
680         s = dev->subdevices + 1;
681         if(thisboard->has_ao)
682         {
683 /* Could provide command support, except it only has a one sample
684  * hardware buffer for analog output and no underrun flag. */
685                 s->type=COMEDI_SUBD_AO;
686                 s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_GROUND;
687                 s->n_chan = NUM_AO_CHAN;
688                 s->maxdata = (1 << 12) - 1;     // 12 bit resolution
689                 s->range_table = &range_labpc_ao;
690                 s->insn_read = labpc_ao_rinsn;
691                 s->insn_write = labpc_ao_winsn;
692                 /* initialize analog outputs to a known value */
693                 for(i = 0; i < s->n_chan; i++)
694                 {
695                         devpriv->ao_value[i] = s->maxdata / 2;
696                         lsb = devpriv->ao_value[i] & 0xff;
697                         msb = (devpriv->ao_value[i] >> 8) & 0xff;
698                         thisboard->write_byte(lsb, dev->iobase + DAC_LSB_REG(i));
699                         thisboard->write_byte(msb, dev->iobase + DAC_MSB_REG(i));
700                 }
701         }else
702         {
703                 s->type = COMEDI_SUBD_UNUSED;
704         }
705
706         /* 8255 dio */
707         s = dev->subdevices + 2;
708         // if board uses io memory we have to give a custom callback function to the 8255 driver
709         if(thisboard->write_byte == labpc_writeb)
710                 subdev_8255_init(dev, s, labpc_dio_mem_callback, (unsigned long)(dev->iobase + DIO_BASE_REG));
711         else
712                 subdev_8255_init(dev, s, NULL, dev->iobase + DIO_BASE_REG);
713
714         // calibration subdevices for boards that have one
715         s = dev->subdevices + 3;
716         if(thisboard->register_layout == labpc_1200_layout)
717         {
718                 s->type=COMEDI_SUBD_CALIB;
719                 s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
720                 s->n_chan = 16;
721                 s->maxdata = 0xff;
722                 s->insn_read = labpc_calib_read_insn;
723                 s->insn_write = labpc_calib_write_insn;
724
725                 for( i = 0; i < s->n_chan; i++ )
726                         write_caldac( dev, i, s->maxdata / 2 );
727         }else
728                 s->type = COMEDI_SUBD_UNUSED;
729
730         /* EEPROM */
731         s = dev->subdevices + 4;
732         if(thisboard->register_layout == labpc_1200_layout)
733         {
734                 s->type = COMEDI_SUBD_MEMORY;
735                 s->subdev_flags = SDF_READABLE | SDF_WRITABLE | SDF_INTERNAL;
736                 s->n_chan = EEPROM_SIZE;
737                 s->maxdata = 0xff;
738                 s->insn_read = labpc_eeprom_read_insn;
739                 s->insn_write = labpc_eeprom_write_insn;
740
741                 for(i = 0; i < EEPROM_SIZE; i++)
742                 {
743                         devpriv->eeprom_data[i] = labpc_eeprom_read(dev, i);
744                 }
745 #ifdef LABPC_DEBUG
746                 printk(" eeprom:");
747                 for(i = 0; i < EEPROM_SIZE; i++)
748                 {
749                         printk(" %i:0x%x ", i, devpriv->eeprom_data[i]);
750                 }
751                 printk("\n");
752 #endif
753         }else
754                 s->type = COMEDI_SUBD_UNUSED;
755
756         return 0;
757 };
758
759 // adapted from ni_pcimio for finding mite based boards (pc-1200)
760 static struct mite_struct* labpc_find_device(int bus, int slot)
761 {
762         struct mite_struct *mite;
763         int i;
764         for(mite = mite_devices; mite; mite = mite->next)
765         {
766                 if(mite->used) continue;
767                 // if bus/slot are specified then make sure we have the right bus/slot
768                 if(bus || slot)
769                 {
770                         if(bus != mite->pcidev->bus->number || slot != PCI_SLOT(mite->pcidev->devfn)) continue;
771                 }
772                 for(i = 0; i < driver_labpc.num_names; i++)
773                 {
774                         if(labpc_boards[i].bustype != pci_bustype) continue;
775                         if(mite_device_id(mite) == labpc_boards[i].device_id)
776                         {
777                                  return mite;
778                          }
779                 }
780         }
781         printk("no device found\n");
782         mite_list_devices();
783         return NULL;
784 }
785
786 static int labpc_detach(comedi_device *dev)
787 {
788         printk("comedi%d: ni_labpc: remove\n", dev->minor);
789
790         if(dev->subdevices)
791                 subdev_8255_cleanup(dev,dev->subdevices + 2);
792
793         /* only free stuff if it has been allocated by _attach */
794         if(devpriv->dma_buffer)
795                 kfree(devpriv->dma_buffer);
796         if(devpriv->dma_chan)
797                 free_dma(devpriv->dma_chan);
798         if(dev->irq)
799                 comedi_free_irq(dev->irq, dev);
800         if(thisboard->bustype == isa_bustype &&
801                 dev->iobase)
802                 release_region(dev->iobase, LABPC_SIZE);
803         if( devpriv->mite )
804                 mite_unsetup( devpriv->mite );
805
806         return 0;
807 };
808
809 static void labpc_clear_adc_fifo( const comedi_device *dev )
810 {
811         thisboard->write_byte(0x1, dev->iobase + ADC_CLEAR_REG);
812         thisboard->read_byte(dev->iobase + ADC_FIFO_REG);
813         thisboard->read_byte(dev->iobase + ADC_FIFO_REG);
814 }
815
816 static int labpc_cancel(comedi_device *dev, comedi_subdevice *s)
817 {
818         unsigned long flags;
819
820         comedi_spin_lock_irqsave( &dev->spinlock, flags );
821         devpriv->command2_bits &= ~SWTRIG_BIT & ~HWTRIG_BIT & ~PRETRIG_BIT;
822         thisboard->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
823         comedi_spin_unlock_irqrestore( &dev->spinlock, flags );
824
825         devpriv->command3_bits = 0;
826         thisboard->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
827
828         return 0;
829 }
830
831 static enum scan_mode labpc_ai_scan_mode( const comedi_cmd *cmd )
832 {
833         if( cmd->chanlist_len == 1 )
834                 return MODE_SINGLE_CHAN;
835
836         if( CR_CHAN( cmd->chanlist[0] ) == CR_CHAN( cmd->chanlist[1] ) )
837                 return MODE_SINGLE_CHAN_INTERVAL;
838
839         if( CR_CHAN( cmd->chanlist[0] ) < CR_CHAN( cmd->chanlist[1] ) )
840                 return MODE_MULT_CHAN_UP;
841
842         if( CR_CHAN( cmd->chanlist[0] ) > CR_CHAN( cmd->chanlist[1] ) )
843                 return MODE_MULT_CHAN_DOWN;
844
845         rt_printk( "ni_labpc: bug! this should never happen\n");
846
847         return 0;
848 }
849
850 static int labpc_ai_chanlist_invalid( const comedi_device *dev,
851         const comedi_cmd *cmd )
852 {
853         int mode, channel, range, aref, i;
854
855         if( cmd->chanlist == NULL ) return 0;
856
857         mode = labpc_ai_scan_mode( cmd );
858
859         if( mode == MODE_SINGLE_CHAN ) return 0;
860
861         if( mode == MODE_SINGLE_CHAN_INTERVAL )
862         {
863                 if( cmd->chanlist_len > 0xff )
864                 {
865                         comedi_error(dev, "ni_labpc: chanlist too long for single channel interval mode\n");
866                         return 1;
867                 }
868         }
869
870         channel = CR_CHAN( cmd->chanlist[ 0 ] );
871         range = CR_RANGE( cmd->chanlist[ 0 ] );
872         aref = CR_AREF( cmd->chanlist[ 0 ] );
873
874         for( i = 0; i < cmd->chanlist_len; i++ )
875         {
876
877                 switch( mode )
878                 {
879                         case MODE_SINGLE_CHAN_INTERVAL:
880                                 if( CR_CHAN( cmd->chanlist[ i ] ) != channel )
881                                 {
882                                         comedi_error(dev, "channel scanning order specified in chanlist is not supported by hardware.\n");
883                                         return 1;
884                                 }
885                                 break;
886                         case MODE_MULT_CHAN_UP:
887                                 if( CR_CHAN( cmd->chanlist[ i ] ) != i )
888                                 {
889                                         comedi_error(dev, "channel scanning order specified in chanlist is not supported by hardware.\n");
890                                         return 1;
891                                 }
892                                 break;
893                         case MODE_MULT_CHAN_DOWN:
894                                 if( CR_CHAN( cmd->chanlist[i] ) !=
895                                         cmd->chanlist_len - i - 1 )
896                                 {
897                                         comedi_error(dev, "channel scanning order specified in chanlist is not supported by hardware.\n");
898                                         return 1;
899                                 }
900                                 break;
901                         default:
902                                 rt_printk( "ni_labpc: bug! in chanlist check\n");
903                                 return 1;
904                                 break;
905                 }
906
907                 if( CR_RANGE( cmd->chanlist[i] ) != range )
908                 {
909                         comedi_error(dev, "entries in chanlist must all have the same range\n");
910                         return 1;
911                 }
912
913                 if( CR_AREF( cmd->chanlist[i] ) != aref )
914                 {
915                         comedi_error(dev, "entries in chanlist must all have the same reference\n");
916                         return 1;
917                 }
918         }
919
920         return 0;
921 }
922
923 static int labpc_use_continuous_mode( const comedi_cmd *cmd )
924 {
925         if( labpc_ai_scan_mode( cmd ) == MODE_SINGLE_CHAN ) return 1;
926
927         if( cmd->scan_begin_src == TRIG_FOLLOW ) return 1;
928
929         return 0;
930 }
931
932 static unsigned int labpc_ai_convert_period( const comedi_cmd *cmd )
933 {
934         if( cmd->convert_src != TRIG_TIMER ) return 0;
935
936         if( labpc_ai_scan_mode( cmd ) == MODE_SINGLE_CHAN &&
937                 cmd->scan_begin_src == TRIG_TIMER )
938                 return cmd->scan_begin_arg;
939
940         return cmd->convert_arg;
941 }
942
943 static void labpc_set_ai_convert_period( comedi_cmd *cmd, unsigned int ns )
944 {
945         if( cmd->convert_src != TRIG_TIMER ) return;
946
947         if( labpc_ai_scan_mode( cmd ) == MODE_SINGLE_CHAN &&
948                 cmd->scan_begin_src == TRIG_TIMER )
949         {
950                 cmd->scan_begin_arg = ns;
951                 if( cmd->convert_arg > cmd->scan_begin_arg )
952                         cmd->convert_arg = cmd->scan_begin_arg;
953         }else
954                 cmd->convert_arg = ns;
955 }
956
957 static unsigned int labpc_ai_scan_period( const comedi_cmd *cmd )
958 {
959         if( cmd->scan_begin_src != TRIG_TIMER ) return 0;
960
961         if( labpc_ai_scan_mode( cmd ) == MODE_SINGLE_CHAN &&
962                 cmd->convert_src == TRIG_TIMER )
963                 return 0;
964
965         return cmd->scan_begin_arg;
966 }
967
968 static void labpc_set_ai_scan_period( comedi_cmd *cmd, unsigned int ns )
969 {
970         if( cmd->scan_begin_src != TRIG_TIMER ) return;
971
972         if( labpc_ai_scan_mode( cmd ) == MODE_SINGLE_CHAN &&
973                 cmd->convert_src == TRIG_TIMER )
974                 return;
975
976         cmd->scan_begin_arg = ns;
977 }
978
979 static int labpc_ai_cmdtest(comedi_device *dev,comedi_subdevice *s,comedi_cmd *cmd)
980 {
981         int err = 0;
982         int tmp, tmp2;
983         int stop_mask;
984
985         /* step 1: make sure trigger sources are trivially valid */
986
987         tmp = cmd->start_src;
988         cmd->start_src &= TRIG_NOW | TRIG_EXT;
989         if(!cmd->start_src || tmp != cmd->start_src) err++;
990
991         tmp = cmd->scan_begin_src;
992         cmd->scan_begin_src &= TRIG_TIMER | TRIG_FOLLOW | TRIG_EXT;
993         if(!cmd->scan_begin_src || tmp != cmd->scan_begin_src) err++;
994
995         tmp = cmd->convert_src;
996         cmd->convert_src &= TRIG_TIMER | TRIG_EXT;
997         if(!cmd->convert_src || tmp != cmd->convert_src) err++;
998
999         tmp = cmd->scan_end_src;
1000         cmd->scan_end_src &= TRIG_COUNT;
1001         if(!cmd->scan_end_src || tmp != cmd->scan_end_src) err++;
1002
1003         tmp=cmd->stop_src;
1004         stop_mask = TRIG_COUNT | TRIG_NONE;
1005         if(thisboard->register_layout == labpc_1200_layout)
1006                 stop_mask |= TRIG_EXT;
1007         cmd->stop_src &= stop_mask;
1008         if(!cmd->stop_src || tmp!=cmd->stop_src) err++;
1009
1010         if(err) return 1;
1011
1012         /* step 2: make sure trigger sources are unique and mutually compatible */
1013
1014         if(cmd->start_src != TRIG_NOW &&
1015                 cmd->start_src != TRIG_EXT) err++;
1016         if(cmd->scan_begin_src != TRIG_TIMER &&
1017                 cmd->scan_begin_src != TRIG_FOLLOW &&
1018                 cmd->scan_begin_src != TRIG_EXT) err++;
1019         if(cmd->convert_src != TRIG_TIMER &&
1020            cmd->convert_src != TRIG_EXT) err++;
1021         if(cmd->stop_src != TRIG_COUNT &&
1022                 cmd->stop_src != TRIG_EXT &&
1023                 cmd->stop_src != TRIG_NONE) err++;
1024
1025         // can't have external stop and start triggers at once
1026         if(cmd->start_src == TRIG_EXT &&
1027                 cmd->stop_src == TRIG_EXT) err++;
1028
1029         if(err)return 2;
1030
1031         /* step 3: make sure arguments are trivially compatible */
1032
1033         if(cmd->start_arg == TRIG_NOW && cmd->start_arg != 0)
1034         {
1035                 cmd->start_arg = 0;
1036                 err++;
1037         }
1038
1039         if(!cmd->chanlist_len)
1040         {
1041                 err++;
1042         }
1043         if(cmd->scan_end_arg != cmd->chanlist_len)
1044         {
1045                 cmd->scan_end_arg = cmd->chanlist_len;
1046                 err++;
1047         }
1048
1049         if(cmd->convert_src == TRIG_TIMER)
1050         {
1051                 if(cmd->convert_arg < thisboard->ai_speed)
1052                 {
1053                         cmd->convert_arg = thisboard->ai_speed;
1054                         err++;
1055                 }
1056         }
1057
1058         // make sure scan timing is not too fast
1059         if(cmd->scan_begin_src == TRIG_TIMER)
1060         {
1061                 if(cmd->convert_src == TRIG_TIMER &&
1062                         cmd->scan_begin_arg < cmd->convert_arg * cmd->chanlist_len)
1063                 {
1064                         cmd->scan_begin_arg = cmd->convert_arg * cmd->chanlist_len;
1065                         err++;
1066                 }
1067                 if(cmd->scan_begin_arg < thisboard->ai_speed * cmd->chanlist_len)
1068                 {
1069                         cmd->scan_begin_arg = thisboard->ai_speed * cmd->chanlist_len;
1070                         err++;
1071                 }
1072         }
1073
1074         // stop source
1075         switch(cmd->stop_src)
1076         {
1077                 case TRIG_COUNT:
1078                         if(!cmd->stop_arg)
1079                         {
1080                                 cmd->stop_arg = 1;
1081                                 err++;
1082                         }
1083                         break;
1084                 case TRIG_NONE:
1085                         if(cmd->stop_arg != 0)
1086                         {
1087                                 cmd->stop_arg = 0;
1088                                 err++;
1089                         }
1090                         break;
1091                 // TRIG_EXT doesn't care since it doesn't trigger off a numbered channel
1092                 default:
1093                         break;
1094         }
1095
1096         if(err)return 3;
1097
1098         /* step 4: fix up any arguments */
1099
1100         tmp = cmd->convert_arg;
1101         tmp2 = cmd->scan_begin_arg;
1102         labpc_adc_timing(dev, cmd);
1103         if(tmp != cmd->convert_arg ||
1104                 tmp2 != cmd->scan_begin_arg) err++;
1105
1106         if(err)return 4;
1107
1108         if( labpc_ai_chanlist_invalid( dev, cmd ) )
1109                 return 5;
1110
1111         return 0;
1112 }
1113
1114 static int labpc_ai_cmd(comedi_device *dev, comedi_subdevice *s)
1115 {
1116         int channel, range, aref;
1117         unsigned long irq_flags;
1118         int ret;
1119         comedi_async *async = s->async;
1120         comedi_cmd *cmd = &async->cmd;
1121         enum transfer_type xfer;
1122         unsigned long flags;
1123
1124         if(!dev->irq)
1125         {
1126                 comedi_error(dev, "no irq assigned, cannot perform command");
1127                 return -1;
1128         }
1129
1130         range = CR_RANGE(cmd->chanlist[0]);
1131         aref = CR_AREF(cmd->chanlist[0]);
1132
1133         // make sure board is disabled before setting up aquisition
1134         comedi_spin_lock_irqsave( &dev->spinlock, flags );
1135         devpriv->command2_bits &= ~SWTRIG_BIT & ~HWTRIG_BIT & ~PRETRIG_BIT;
1136         thisboard->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
1137         comedi_spin_unlock_irqrestore( &dev->spinlock, flags );
1138
1139         devpriv->command3_bits = 0;
1140         thisboard->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
1141
1142         // initialize software conversion count
1143         if(cmd->stop_src == TRIG_COUNT)
1144         {
1145                 devpriv->count = cmd->stop_arg * cmd->chanlist_len;
1146         }
1147         // setup hardware conversion counter
1148         if(cmd->stop_src == TRIG_EXT)
1149         {
1150                 // load counter a1 with count of 3 (pc+ manual says this is minimum allowed) using mode 0
1151                 ret = i8254_load(dev->iobase + COUNTER_A_BASE_REG, 1, 3, 0);
1152                 if(ret < 0)
1153                 {
1154                         comedi_error(dev, "error loading counter a1");
1155                         return -1;
1156                 }
1157         }else   // otherwise, just put a1 in mode 0 with no count to set its output low
1158                 thisboard->write_byte(INIT_A1_BITS, dev->iobase + COUNTER_A_CONTROL_REG);
1159
1160         // figure out what method we will use to transfer data
1161         if(devpriv->dma_chan && // need a dma channel allocated
1162                 // dma unsafe at RT priority, and too much setup time for TRIG_WAKE_EOS for
1163                 (cmd->flags & (TRIG_WAKE_EOS | TRIG_RT)) == 0 &&
1164                 // only available on the isa boards
1165                 thisboard->bustype == isa_bustype)
1166         {
1167                 xfer = isa_dma_transfer;
1168         }else if(thisboard->register_layout == labpc_1200_layout &&     // pc-plus has no fifo-half full interrupt
1169                 // wake-end-of-scan should interrupt on fifo not empty
1170                 (cmd->flags & TRIG_WAKE_EOS) == 0 &&
1171                 // make sure we are taking more than just a few points
1172                 (cmd->stop_src != TRIG_COUNT || devpriv->count > 256))
1173         {
1174                 xfer = fifo_half_full_transfer;
1175         }else
1176                 xfer = fifo_not_empty_transfer;
1177         devpriv->current_transfer = xfer;
1178
1179         // setup command6 register for 1200 boards
1180         if(thisboard->register_layout == labpc_1200_layout)
1181         {
1182                 // reference inputs to ground or common?
1183                 if(aref != AREF_GROUND)
1184                         devpriv->command6_bits |= ADC_COMMON_BIT;
1185                 else
1186                         devpriv->command6_bits &= ~ADC_COMMON_BIT;
1187                 // bipolar or unipolar range?
1188                 if(thisboard->ai_range_is_unipolar[range])
1189                         devpriv->command6_bits |= ADC_UNIP_BIT;
1190                 else
1191                         devpriv->command6_bits &= ~ADC_UNIP_BIT;
1192                 // interrupt on fifo half full?
1193                 if(xfer == fifo_half_full_transfer)
1194                         devpriv->command6_bits |= ADC_FHF_INTR_EN_BIT;
1195                 else
1196                         devpriv->command6_bits &= ~ADC_FHF_INTR_EN_BIT;
1197                 // enable interrupt on counter a1 terminal count?
1198                 if(cmd->stop_src == TRIG_EXT)
1199                         devpriv->command6_bits |= A1_INTR_EN_BIT;
1200                 else
1201                         devpriv->command6_bits &= ~A1_INTR_EN_BIT;
1202                 // are we scanning up or down through channels?
1203                 if( labpc_ai_scan_mode( cmd ) == MODE_MULT_CHAN_UP )
1204                         devpriv->command6_bits |= ADC_SCAN_UP_BIT;
1205                 else
1206                         devpriv->command6_bits &= ~ADC_SCAN_UP_BIT;
1207                 // write to register
1208                 thisboard->write_byte(devpriv->command6_bits, dev->iobase + COMMAND6_REG);
1209         }
1210
1211         /* setup channel list, etc (command1 register) */
1212         devpriv->command1_bits = 0;
1213         if( labpc_ai_scan_mode( cmd ) == MODE_MULT_CHAN_UP )
1214                 channel = CR_CHAN(cmd->chanlist[cmd->chanlist_len - 1]);
1215         else
1216                 channel = CR_CHAN(cmd->chanlist[0]);
1217         // munge channel bits for differential / scan disabled mode
1218         if( labpc_ai_scan_mode( cmd ) != MODE_SINGLE_CHAN && aref == AREF_DIFF )
1219                 channel *= 2;
1220         devpriv->command1_bits |= ADC_CHAN_BITS(channel);
1221         devpriv->command1_bits |= thisboard->ai_range_code[range];
1222         thisboard->write_byte(devpriv->command1_bits, dev->iobase + COMMAND1_REG);
1223         // manual says to set scan enable bit on second pass
1224         if( labpc_ai_scan_mode( cmd ) == MODE_MULT_CHAN_UP ||
1225                 labpc_ai_scan_mode( cmd ) == MODE_MULT_CHAN_DOWN )
1226         {
1227                 devpriv->command1_bits |= ADC_SCAN_EN_BIT;
1228                 /* need a brief delay before enabling scan, or scan list will get screwed when you switch
1229                  * between scan up to scan down mode - dunno why */
1230                 comedi_udelay(1);
1231                 thisboard->write_byte(devpriv->command1_bits, dev->iobase + COMMAND1_REG);
1232         }
1233
1234         // setup any external triggering/pacing (command4 register)
1235         devpriv->command4_bits = 0;
1236         if(cmd->convert_src != TRIG_EXT)
1237                 devpriv->command4_bits |= EXT_CONVERT_DISABLE_BIT;
1238         /* XXX should discard first scan when using interval scanning
1239          * since manual says it is not synced with scan clock */
1240         if( labpc_use_continuous_mode( cmd ) == 0 )
1241         {
1242                 devpriv->command4_bits |= INTERVAL_SCAN_EN_BIT;
1243                 if( cmd->scan_begin_src == TRIG_EXT )
1244                         devpriv->command4_bits |= EXT_SCAN_EN_BIT;
1245         }
1246         // single-ended/differential
1247         if(aref == AREF_DIFF)
1248                 devpriv->command4_bits |= ADC_DIFF_BIT;
1249         thisboard->write_byte(devpriv->command4_bits, dev->iobase + COMMAND4_REG);
1250
1251         thisboard->write_byte( cmd->chanlist_len, dev->iobase + INTERVAL_COUNT_REG);
1252         // load count
1253         thisboard->write_byte(INTERVAL_LOAD_BITS, dev->iobase + INTERVAL_LOAD_REG);
1254
1255         if(cmd->convert_src == TRIG_TIMER || cmd->scan_begin_src == TRIG_TIMER)
1256         {
1257                 // set up pacing
1258                 labpc_adc_timing(dev, cmd);
1259                 // load counter b0 in mode 3
1260                 ret = i8254_load(dev->iobase + COUNTER_B_BASE_REG, 0, devpriv->divisor_b0, 3);
1261                 if(ret < 0)
1262                 {
1263                         comedi_error(dev, "error loading counter b0");
1264                         return -1;
1265                 }
1266         }
1267         // set up conversion pacing
1268         if( labpc_ai_convert_period( cmd ) )
1269         {
1270                 // load counter a0 in mode 2
1271                 ret = i8254_load(dev->iobase + COUNTER_A_BASE_REG, 0, devpriv->divisor_a0, 2);
1272                 if(ret < 0)
1273                 {
1274                         comedi_error(dev, "error loading counter a0");
1275                         return -1;
1276                 }
1277         }else
1278                 thisboard->write_byte(INIT_A0_BITS, dev->iobase + COUNTER_A_CONTROL_REG);
1279
1280         // set up scan pacing
1281         if( labpc_ai_scan_period( cmd ) )
1282         {
1283                 // load counter b1 in mode 2
1284                 ret = i8254_load(dev->iobase + COUNTER_B_BASE_REG, 1, devpriv->divisor_b1, 2);
1285                 if(ret < 0)
1286                 {
1287                         comedi_error(dev, "error loading counter b1");
1288                         return -1;
1289                 }
1290         }
1291
1292         labpc_clear_adc_fifo( dev );
1293
1294         // set up dma transfer
1295         if(xfer == isa_dma_transfer)
1296         {
1297                 irq_flags = claim_dma_lock();
1298                 disable_dma(devpriv->dma_chan);
1299                 /* clear flip-flop to make sure 2-byte registers for
1300                 * count and address get set correctly */
1301                 clear_dma_ff(devpriv->dma_chan);
1302                 set_dma_addr(devpriv->dma_chan, virt_to_bus(devpriv->dma_buffer));
1303                 // set appropriate size of transfer
1304                 devpriv->dma_transfer_size = labpc_suggest_transfer_size(*cmd);
1305                 if(cmd->stop_src == TRIG_COUNT &&
1306                         devpriv->count * sample_size < devpriv->dma_transfer_size)
1307                 {
1308                         devpriv->dma_transfer_size = devpriv->count * sample_size;
1309                 }
1310                 set_dma_count(devpriv->dma_chan, devpriv->dma_transfer_size);
1311                 enable_dma(devpriv->dma_chan);
1312                 release_dma_lock(irq_flags);
1313                 // enable board's dma
1314                 devpriv->command3_bits |= DMA_EN_BIT | DMATC_INTR_EN_BIT;
1315         }else
1316                 devpriv->command3_bits &= ~DMA_EN_BIT & ~DMATC_INTR_EN_BIT;
1317
1318         // enable error interrupts
1319         devpriv->command3_bits |= ERR_INTR_EN_BIT;
1320         // enable fifo not empty interrupt?
1321         if(xfer == fifo_not_empty_transfer)
1322                 devpriv->command3_bits |= ADC_FNE_INTR_EN_BIT;
1323         else
1324                 devpriv->command3_bits &= ~ADC_FNE_INTR_EN_BIT;
1325         thisboard->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
1326
1327         // startup aquisition
1328
1329         // command2 reg
1330         // use 2 cascaded counters for pacing
1331         comedi_spin_lock_irqsave( &dev->spinlock, flags );
1332         devpriv->command2_bits |= CASCADE_BIT;
1333         switch(cmd->start_src)
1334         {
1335                 case TRIG_EXT:
1336                         devpriv->command2_bits |= HWTRIG_BIT;
1337                         devpriv->command2_bits &= ~PRETRIG_BIT & ~SWTRIG_BIT;
1338                         break;
1339                 case TRIG_NOW:
1340                         devpriv->command2_bits |= SWTRIG_BIT;
1341                         devpriv->command2_bits &= ~PRETRIG_BIT & ~HWTRIG_BIT;
1342                         break;
1343                 default:
1344                         comedi_error(dev, "bug with start_src");
1345                         return -1;
1346                         break;
1347         }
1348         switch(cmd->stop_src)
1349         {
1350                 case TRIG_EXT:
1351                         devpriv->command2_bits |= HWTRIG_BIT | PRETRIG_BIT;
1352                         break;
1353                 case TRIG_COUNT:
1354                 case TRIG_NONE:
1355                         break;
1356                 default:
1357                         comedi_error(dev, "bug with stop_src");
1358                         return -1;
1359         }
1360         thisboard->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
1361         comedi_spin_unlock_irqrestore( &dev->spinlock, flags );
1362
1363         return 0;
1364 }
1365
1366 /* interrupt service routine */
1367 static void labpc_interrupt(int irq, void *d, struct pt_regs *regs)
1368 {
1369         comedi_device *dev = d;
1370         comedi_subdevice *s = dev->read_subdev;
1371         comedi_async *async;
1372         comedi_cmd *cmd;
1373
1374         if(dev->attached == 0)
1375         {
1376                 comedi_error(dev, "premature interrupt");
1377                 return;
1378         }
1379
1380         async = s->async;
1381         cmd = &async->cmd;
1382         async->events = 0;
1383
1384         // read board status
1385         devpriv->status1_bits = thisboard->read_byte(dev->iobase + STATUS1_REG);
1386         if(thisboard->register_layout == labpc_1200_layout)
1387                 devpriv->status2_bits = thisboard->read_byte(dev->iobase + STATUS2_REG);
1388
1389         if((devpriv->status1_bits & (DMATC_BIT | TIMER_BIT | OVERFLOW_BIT | OVERRUN_BIT | DATA_AVAIL_BIT)) == 0 &&
1390                 (devpriv->status2_bits & A1_TC_BIT) == 0 &&
1391                 (devpriv->status2_bits & FNHF_BIT))
1392         {
1393                 return;
1394         }
1395
1396         if(devpriv->status1_bits & OVERRUN_BIT)
1397         {
1398                 // clear error interrupt
1399                 thisboard->write_byte(0x1, dev->iobase + ADC_CLEAR_REG);
1400                 async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
1401                 comedi_event(dev, s, async->events);
1402                 comedi_error(dev, "overrun");
1403                 return;
1404         }
1405
1406         if(devpriv->current_transfer == isa_dma_transfer)
1407         {
1408                 // if a dma terminal count of external stop trigger has occurred
1409                 if(devpriv->status1_bits & DMATC_BIT ||
1410                         (thisboard->register_layout == labpc_1200_layout && devpriv->status2_bits & A1_TC_BIT))
1411                 {
1412                         handle_isa_dma(dev);
1413                 }
1414         }else labpc_drain_fifo(dev);
1415
1416         if(devpriv->status1_bits & TIMER_BIT)
1417         {
1418                 comedi_error(dev, "handled timer interrupt?");
1419                 // clear it
1420                 thisboard->write_byte(0x1, dev->iobase + TIMER_CLEAR_REG);
1421         }
1422
1423         if(devpriv->status1_bits & OVERFLOW_BIT)
1424         {
1425                 // clear error interrupt
1426                 thisboard->write_byte(0x1, dev->iobase + ADC_CLEAR_REG);
1427                 async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
1428                 comedi_error(dev, "overflow");
1429                 return;
1430         }
1431
1432         // handle external stop trigger
1433         if(cmd->stop_src == TRIG_EXT)
1434         {
1435                 if(devpriv->status2_bits & A1_TC_BIT)
1436                 {
1437                         labpc_drain_dregs(dev);
1438                         labpc_cancel(dev, s);
1439                         async->events |= COMEDI_CB_EOA;
1440                 }
1441         }
1442
1443         /* TRIG_COUNT end of acquisition */
1444         if(cmd->stop_src == TRIG_COUNT)
1445         {
1446                 if(devpriv->count == 0)
1447                 {
1448                         labpc_cancel(dev, s);
1449                         async->events |= COMEDI_CB_EOA;
1450                 }
1451         }
1452
1453         comedi_event(dev, s, async->events);
1454 }
1455
1456 // read all available samples from ai fifo
1457 static int labpc_drain_fifo(comedi_device *dev)
1458 {
1459         unsigned int lsb, msb;
1460         sampl_t data;
1461         comedi_async *async = dev->read_subdev->async;
1462         const int timeout = 10000;
1463         unsigned int i;
1464
1465         devpriv->status1_bits = thisboard->read_byte(dev->iobase + STATUS1_REG);
1466
1467         for(i = 0; (devpriv->status1_bits & DATA_AVAIL_BIT) && i < timeout; i++)
1468         {
1469                 // quit if we have all the data we want
1470                 if(async->cmd.stop_src == TRIG_COUNT)
1471                 {
1472                         if(devpriv->count == 0) break;
1473                         devpriv->count--;
1474                 }
1475                 lsb = thisboard->read_byte(dev->iobase + ADC_FIFO_REG);
1476                 msb = thisboard->read_byte(dev->iobase + ADC_FIFO_REG);
1477                 data = (msb << 8) | lsb;
1478                 cfc_write_to_buffer( dev->read_subdev, data );
1479                 devpriv->status1_bits = thisboard->read_byte(dev->iobase + STATUS1_REG);
1480         }
1481         if(i == timeout)
1482         {
1483                 comedi_error(dev, "ai timeout, fifo never empties");
1484                 async->events |= COMEDI_CB_ERROR | COMEDI_CB_EOA;
1485                 return -1;
1486         }
1487
1488         return 0;
1489 }
1490
1491 static void labpc_drain_dma(comedi_device *dev)
1492 {
1493         comedi_subdevice *s = dev->read_subdev;
1494         comedi_async *async = s->async;
1495         int status;
1496         unsigned long flags;
1497         unsigned int max_points, num_points, residue, leftover;
1498         int i;
1499
1500         status = devpriv->status1_bits;
1501
1502         flags = claim_dma_lock();
1503         disable_dma(devpriv->dma_chan);
1504         /* clear flip-flop to make sure 2-byte registers for
1505         * count and address get set correctly */
1506         clear_dma_ff(devpriv->dma_chan);
1507
1508         // figure out how many points to read
1509         max_points = devpriv->dma_transfer_size  / sample_size;
1510         /* residue is the number of points left to be done on the dma
1511         * transfer.  It should always be zero at this point unless
1512         * the stop_src is set to external triggering.
1513         */
1514         residue = get_dma_residue(devpriv->dma_chan) / sample_size;
1515         num_points = max_points - residue;
1516         if(devpriv->count < num_points &&
1517                 async->cmd.stop_src == TRIG_COUNT)
1518                 num_points = devpriv->count;
1519
1520         // figure out how many points will be stored next time
1521         leftover = 0;
1522         if(async->cmd.stop_src != TRIG_COUNT)
1523         {
1524                 leftover = devpriv->dma_transfer_size / sample_size;
1525         }else if(devpriv->count > num_points)
1526         {
1527                 leftover = devpriv->count - num_points;
1528                 if(leftover > max_points)
1529                         leftover = max_points;
1530         }
1531
1532         /* write data to comedi buffer */
1533         for( i = 0; i < num_points; i++)
1534         {
1535                 cfc_write_to_buffer( s, devpriv->dma_buffer[i] );
1536         }
1537         if(async->cmd.stop_src == TRIG_COUNT) devpriv->count -= num_points;
1538
1539         // set address and count for next transfer
1540         set_dma_addr(devpriv->dma_chan, virt_to_bus(devpriv->dma_buffer));
1541         set_dma_count(devpriv->dma_chan, leftover * sample_size);
1542         release_dma_lock(flags);
1543
1544         async->events |= COMEDI_CB_BLOCK;
1545 }
1546
1547 static void handle_isa_dma(comedi_device *dev)
1548 {
1549         labpc_drain_dma(dev);
1550
1551         enable_dma(devpriv->dma_chan);
1552
1553         // clear dma tc interrupt
1554         thisboard->write_byte(0x1, dev->iobase + DMATC_CLEAR_REG);
1555 }
1556
1557 /* makes sure all data aquired by board is transfered to comedi (used
1558  * when aquisition is terminated by stop_src == TRIG_EXT). */
1559 static void labpc_drain_dregs(comedi_device *dev)
1560 {
1561         if(devpriv->current_transfer == isa_dma_transfer)
1562                 labpc_drain_dma(dev);
1563
1564         labpc_drain_fifo(dev);
1565 }
1566
1567 static int labpc_ai_rinsn(comedi_device *dev, comedi_subdevice *s, comedi_insn *insn, lsampl_t *data)
1568 {
1569         int i, n;
1570         int chan, range;
1571         int lsb, msb;
1572         int timeout = 1000;
1573         unsigned long flags;
1574
1575         // disable timed conversions
1576         comedi_spin_lock_irqsave( &dev->spinlock, flags );
1577         devpriv->command2_bits &= ~SWTRIG_BIT & ~HWTRIG_BIT & ~PRETRIG_BIT;
1578         thisboard->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
1579         comedi_spin_unlock_irqrestore( &dev->spinlock, flags );
1580
1581         // disable interrupt generation and dma
1582         devpriv->command3_bits = 0;
1583         thisboard->write_byte(devpriv->command3_bits, dev->iobase + COMMAND3_REG);
1584
1585                 /* set gain and channel */
1586         devpriv->command1_bits = 0;
1587         chan = CR_CHAN(insn->chanspec);
1588         range = CR_RANGE(insn->chanspec);
1589         devpriv->command1_bits |= thisboard->ai_range_code[range];
1590         // munge channel bits for differential/scan disabled mode
1591         if(CR_AREF(insn->chanspec) == AREF_DIFF)
1592                 chan *= 2;
1593         devpriv->command1_bits |= ADC_CHAN_BITS(chan);
1594         thisboard->write_byte(devpriv->command1_bits, dev->iobase + COMMAND1_REG);
1595
1596         // setup command6 register for 1200 boards
1597         if(thisboard->register_layout == labpc_1200_layout)
1598         {
1599                 // reference inputs to ground or common?
1600                 if(CR_AREF(insn->chanspec) != AREF_GROUND)
1601                         devpriv->command6_bits |= ADC_COMMON_BIT;
1602                 else
1603                         devpriv->command6_bits &= ~ADC_COMMON_BIT;
1604                 // bipolar or unipolar range?
1605                 if(thisboard->ai_range_is_unipolar[range])
1606                         devpriv->command6_bits |= ADC_UNIP_BIT;
1607                 else
1608                         devpriv->command6_bits &= ~ADC_UNIP_BIT;
1609                 // don't interrupt on fifo half full
1610                 devpriv->command6_bits &= ~ADC_FHF_INTR_EN_BIT;
1611                 // don't enable interrupt on counter a1 terminal count?
1612                 devpriv->command6_bits &= ~A1_INTR_EN_BIT;
1613                 // write to register
1614                 thisboard->write_byte(devpriv->command6_bits, dev->iobase + COMMAND6_REG);
1615         }
1616
1617         // setup command4 register
1618         devpriv->command4_bits = 0;
1619         devpriv->command4_bits |= EXT_CONVERT_DISABLE_BIT;
1620         // single-ended/differential
1621         if(CR_AREF(insn->chanspec) == AREF_DIFF)
1622                 devpriv->command4_bits |= ADC_DIFF_BIT;
1623         thisboard->write_byte(devpriv->command4_bits, dev->iobase + COMMAND4_REG);
1624
1625         // initialize pacer counter output to make sure it doesn't cause any problems
1626         thisboard->write_byte(INIT_A0_BITS, dev->iobase + COUNTER_A_CONTROL_REG);
1627
1628         labpc_clear_adc_fifo( dev );
1629
1630         for(n = 0; n < insn->n; n++)
1631         {
1632                 /* trigger conversion */
1633                 thisboard->write_byte(0x1, dev->iobase + ADC_CONVERT_REG);
1634
1635                 for(i = 0; i < timeout; i++)
1636                 {
1637                         if(thisboard->read_byte(dev->iobase + STATUS1_REG) & DATA_AVAIL_BIT)
1638                                 break;
1639                         comedi_udelay( 1 );
1640                 }
1641                 if(i == timeout)
1642                 {
1643                         comedi_error(dev, "timeout");
1644                         return -ETIME;
1645                 }
1646                 lsb = thisboard->read_byte(dev->iobase + ADC_FIFO_REG);
1647                 msb = thisboard->read_byte(dev->iobase + ADC_FIFO_REG);
1648                 data[n] = (msb << 8) | lsb;
1649         }
1650
1651         return n;
1652 }
1653
1654 // analog output insn
1655 static int labpc_ao_winsn(comedi_device *dev, comedi_subdevice *s,
1656         comedi_insn *insn, lsampl_t *data)
1657 {
1658         int channel, range;
1659         unsigned long flags;
1660         int lsb, msb;
1661
1662         channel = CR_CHAN(insn->chanspec);
1663
1664         // turn off pacing of analog output channel
1665         /* note: hardware bug in daqcard-1200 means pacing cannot
1666          * be independently enabled/disabled for its the two channels */
1667         comedi_spin_lock_irqsave( &dev->spinlock, flags );
1668         devpriv->command2_bits &= ~DAC_PACED_BIT(channel);
1669         thisboard->write_byte(devpriv->command2_bits, dev->iobase + COMMAND2_REG);
1670         comedi_spin_unlock_irqrestore( &dev->spinlock, flags );
1671
1672         // set range
1673         if(thisboard->register_layout == labpc_1200_layout)
1674         {
1675                 range = CR_RANGE(insn->chanspec);
1676                 if(range & AO_RANGE_IS_UNIPOLAR)
1677                         devpriv->command6_bits |= DAC_UNIP_BIT(channel);
1678                 else
1679                         devpriv->command6_bits &= ~DAC_UNIP_BIT(channel);
1680                 // write to register
1681                 thisboard->write_byte(devpriv->command6_bits, dev->iobase + COMMAND6_REG);
1682         }
1683
1684         // send data
1685         lsb = data[0] & 0xff;
1686         msb = (data[0] >> 8 ) & 0xff;
1687         thisboard->write_byte(lsb, dev->iobase + DAC_LSB_REG(channel));
1688         thisboard->write_byte(msb, dev->iobase + DAC_MSB_REG(channel));
1689
1690         // remember value for readback
1691         devpriv->ao_value[channel] = data[0];
1692
1693         return 1;
1694 }
1695
1696 // analog output readback insn
1697 static int labpc_ao_rinsn(comedi_device *dev, comedi_subdevice *s,
1698         comedi_insn *insn, lsampl_t *data)
1699 {
1700         data[0] = devpriv->ao_value[CR_CHAN(insn->chanspec)];
1701
1702         return 1;
1703 }
1704
1705 static int labpc_calib_read_insn(comedi_device *dev, comedi_subdevice *s, comedi_insn *insn, lsampl_t *data)
1706 {
1707         data[0] = devpriv->caldac[CR_CHAN(insn->chanspec)];
1708
1709         return 1;
1710 }
1711
1712 static int labpc_calib_write_insn(comedi_device *dev, comedi_subdevice *s, comedi_insn *insn, lsampl_t *data)
1713 {
1714         int channel = CR_CHAN(insn->chanspec);
1715
1716         write_caldac( dev, channel, data[ 0 ] );
1717         return 1;
1718 }
1719
1720 static int labpc_eeprom_read_insn(comedi_device *dev, comedi_subdevice *s, comedi_insn *insn, lsampl_t *data)
1721 {
1722         data[0] = devpriv->eeprom_data[CR_CHAN(insn->chanspec)];
1723
1724         return 1;
1725 }
1726
1727 static int labpc_eeprom_write_insn(comedi_device *dev, comedi_subdevice *s, comedi_insn *insn, lsampl_t *data)
1728 {
1729         int channel = CR_CHAN(insn->chanspec);
1730         int ret;
1731
1732         // only allow writes to user area of eeprom
1733         if(channel < 16 || channel > 127)
1734         {
1735                 printk("eeprom writes are only allowed to channels 16 through 127 (the pointer and user areas)");
1736                 return -EINVAL;
1737         }
1738
1739         ret = labpc_eeprom_write(dev, channel, data[0]);
1740         if(ret < 0) return ret;
1741
1742         return 1;
1743 }
1744
1745 // utility function that suggests a dma transfer size in bytes
1746 static unsigned int labpc_suggest_transfer_size(comedi_cmd cmd)
1747 {
1748         unsigned int size;
1749         unsigned int freq;
1750
1751         if(cmd.convert_src == TRIG_TIMER)
1752                 freq = 1000000000 / cmd.convert_arg;
1753         // return some default value
1754         else
1755                 freq = 0xffffffff;
1756
1757         // make buffer fill in no more than 1/3 second
1758         size = (freq / 3) * sample_size;
1759
1760         // set a minimum and maximum size allowed
1761         if(size > dma_buffer_size)
1762                 size = dma_buffer_size - dma_buffer_size % sample_size;
1763         else if(size < sample_size)
1764                 size = sample_size;
1765
1766         return size;
1767 }
1768
1769 // figures out what counter values to use based on command
1770 static void labpc_adc_timing(comedi_device *dev, comedi_cmd *cmd)
1771 {
1772         const int max_counter_value = 0x10000;  // max value for 16 bit counter in mode 2
1773         const int min_counter_value = 2;  // min value for 16 bit counter in mode 2
1774         unsigned int base_period;
1775
1776         // if both convert and scan triggers are TRIG_TIMER, then they both rely on counter b0
1777         if( labpc_ai_convert_period( cmd ) && labpc_ai_scan_period( cmd ) )
1778         {
1779                 // pick the lowest b0 divisor value we can (for maximum input clock speed on convert and scan counters)
1780                 devpriv->divisor_b0 = (labpc_ai_scan_period( cmd ) - 1) /
1781                         (LABPC_TIMER_BASE * max_counter_value) + 1;
1782                 if(devpriv->divisor_b0 < min_counter_value)
1783                         devpriv->divisor_b0 = min_counter_value;
1784                 if(devpriv->divisor_b0 > max_counter_value)
1785                         devpriv->divisor_b0 = max_counter_value;
1786
1787                 base_period = LABPC_TIMER_BASE * devpriv->divisor_b0;
1788
1789                 // set a0 for conversion frequency and b1 for scan frequency
1790                 switch(cmd->flags & TRIG_ROUND_MASK)
1791                 {
1792                         default:
1793                         case TRIG_ROUND_NEAREST:
1794                                 devpriv->divisor_a0 = (labpc_ai_convert_period( cmd ) + (base_period / 2)) / base_period;
1795                                 devpriv->divisor_b1 = (labpc_ai_scan_period( cmd ) + (base_period / 2)) / base_period;
1796                                 break;
1797                         case TRIG_ROUND_UP:
1798                                 devpriv->divisor_a0 = (labpc_ai_convert_period( cmd ) + (base_period - 1)) / base_period;
1799                                 devpriv->divisor_b1 = (labpc_ai_scan_period( cmd ) + (base_period - 1)) / base_period;
1800                                 break;
1801                         case TRIG_ROUND_DOWN:
1802                                 devpriv->divisor_a0 = labpc_ai_convert_period( cmd ) / base_period;
1803                                 devpriv->divisor_b1 = labpc_ai_scan_period( cmd ) / base_period;
1804                                 break;
1805                 }
1806                 // make sure a0 and b1 values are acceptable
1807                 if(devpriv->divisor_a0 < min_counter_value)
1808                         devpriv->divisor_a0 = min_counter_value;
1809                 if(devpriv->divisor_a0 > max_counter_value)
1810                         devpriv->divisor_a0 = max_counter_value;
1811                 if(devpriv->divisor_b1 < min_counter_value)
1812                         devpriv->divisor_b1 = min_counter_value;
1813                 if(devpriv->divisor_b1 > max_counter_value)
1814                         devpriv->divisor_b1 = max_counter_value;
1815                 // write corrected timings to command
1816                 labpc_set_ai_convert_period( cmd, base_period * devpriv->divisor_a0 );
1817                 labpc_set_ai_scan_period( cmd, base_period * devpriv->divisor_b1 );
1818         // if only one TRIG_TIMER is used, we can employ the generic cascaded timing functions
1819         }else if( labpc_ai_scan_period( cmd ) )
1820         {
1821                 unsigned int scan_period;
1822
1823                 scan_period = labpc_ai_scan_period( cmd );
1824                 /* calculate cascaded counter values that give desired scan timing */
1825                 i8253_cascade_ns_to_timer_2div(LABPC_TIMER_BASE, &(devpriv->divisor_b1), &(devpriv->divisor_b0),
1826                         &scan_period, cmd->flags & TRIG_ROUND_MASK);
1827                 labpc_set_ai_scan_period( cmd, scan_period );
1828         }else if( labpc_ai_convert_period( cmd ) )
1829         {
1830                 unsigned int convert_period;
1831
1832                 convert_period = labpc_ai_convert_period( cmd );
1833                 /* calculate cascaded counter values that give desired conversion timing */
1834                 i8253_cascade_ns_to_timer_2div(LABPC_TIMER_BASE, &(devpriv->divisor_a0), &(devpriv->divisor_b0),
1835                         &convert_period, cmd->flags & TRIG_ROUND_MASK);
1836                 labpc_set_ai_convert_period( cmd, convert_period );
1837         }
1838 }
1839
1840 /* functions that do inb/outb and readb/writeb so we can use
1841  * function pointers to decide which to use */
1842 static unsigned int labpc_inb(unsigned long address)
1843 {
1844         return inb(address);
1845 }
1846
1847 static void labpc_outb(unsigned int byte, unsigned long address)
1848 {
1849         outb(byte, address);
1850 }
1851
1852 static unsigned int labpc_readb(unsigned long address)
1853 {
1854         return readb(address);
1855 }
1856
1857 static void labpc_writeb(unsigned int byte, unsigned long address)
1858 {
1859         writeb(byte, address);
1860 }
1861
1862 static int labpc_dio_mem_callback(int dir, int port, int data, unsigned long iobase)
1863 {
1864         if(dir)
1865         {
1866                 writeb(data, iobase + port);
1867                 return 0;
1868         }else
1869         {
1870                 return readb(iobase + port);
1871         }
1872 }
1873
1874 // lowlevel write to eeprom/dac
1875 static void labpc_serial_out(comedi_device *dev, unsigned int value, unsigned int value_width)
1876 {
1877         int i;
1878
1879         for(i = 1; i <= value_width; i++)
1880         {
1881                 // clear serial clock
1882                 devpriv->command5_bits &= ~SCLOCK_BIT;
1883                 // send bits most significant bit first
1884                 if(value & (1 << (value_width - i)))
1885                         devpriv->command5_bits |= SDATA_BIT;
1886                 else
1887                         devpriv->command5_bits &= ~SDATA_BIT;
1888                 comedi_udelay(1);
1889                 thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
1890                 // set clock to load bit
1891                 devpriv->command5_bits |= SCLOCK_BIT;
1892                 comedi_udelay(1);
1893                 thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
1894         }
1895 }
1896
1897 // lowlevel read from eeprom
1898 static unsigned int labpc_serial_in(comedi_device *dev)
1899 {
1900         unsigned int value = 0;
1901         int i;
1902         const int value_width = 8;      // number of bits wide values are
1903
1904         for(i = 1; i <= value_width; i++)
1905         {
1906                 // set serial clock
1907                 devpriv->command5_bits |= SCLOCK_BIT;
1908                 comedi_udelay(1);
1909                 thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
1910                 // clear clock bit
1911                 devpriv->command5_bits &= ~SCLOCK_BIT;
1912                 comedi_udelay(1);
1913                 thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
1914                 // read bits most significant bit first
1915                 comedi_udelay(1);
1916                 devpriv->status2_bits = thisboard->read_byte(dev->iobase + STATUS2_REG);
1917                 if(devpriv->status2_bits & EEPROM_OUT_BIT)
1918                 {
1919                         value |= 1 << (value_width - i);
1920                 }
1921         }
1922
1923         return value;
1924 }
1925
1926 static unsigned int labpc_eeprom_read(comedi_device *dev, unsigned int address)
1927 {
1928         unsigned int value;
1929         const int read_instruction = 0x3;       // bits to tell eeprom to expect a read
1930         const int write_length = 8;     // 8 bit write lengths to eeprom
1931
1932         // enable read/write to eeprom
1933         devpriv->command5_bits &= ~EEPROM_EN_BIT;
1934         comedi_udelay(1);
1935         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
1936         devpriv->command5_bits |= EEPROM_EN_BIT | EEPROM_WRITE_UNPROTECT_BIT;
1937         comedi_udelay(1);
1938         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
1939
1940         // send read instruction
1941         labpc_serial_out(dev, read_instruction, write_length);
1942         // send 8 bit address to read from
1943         labpc_serial_out(dev, address, write_length);
1944         // read result
1945         value = labpc_serial_in(dev);
1946
1947         // disable read/write to eeprom
1948         devpriv->command5_bits &= ~EEPROM_EN_BIT & ~EEPROM_WRITE_UNPROTECT_BIT;
1949         comedi_udelay(1);
1950         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
1951
1952         return value;
1953 }
1954
1955 static unsigned int labpc_eeprom_write(comedi_device *dev, unsigned int address, unsigned int value)
1956 {
1957         const int write_enable_instruction = 0x6;
1958         const int write_instruction = 0x2;
1959         const int write_length = 8;     // 8 bit write lengths to eeprom
1960         const int write_in_progress_bit = 0x1;
1961         const int timeout = 10000;
1962         int i;
1963
1964         // make sure there isn't already a write in progress
1965         for(i = 0; i < timeout; i++)
1966         {
1967                 if((labpc_eeprom_read_status(dev) & write_in_progress_bit) == 0)
1968                         break;
1969         }
1970         if(i == timeout)
1971         {
1972                 comedi_error(dev, "eeprom write timed out");
1973                 return -ETIME;
1974         }
1975
1976         // update software copy of eeprom
1977         devpriv->eeprom_data[address] = value;
1978
1979         // enable read/write to eeprom
1980         devpriv->command5_bits &= ~EEPROM_EN_BIT;
1981         comedi_udelay(1);
1982         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
1983         devpriv->command5_bits |= EEPROM_EN_BIT | EEPROM_WRITE_UNPROTECT_BIT;
1984         comedi_udelay(1);
1985         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
1986
1987         // send write_enable instruction
1988         labpc_serial_out(dev, write_enable_instruction, write_length);
1989         devpriv->command5_bits &= ~EEPROM_EN_BIT;
1990         comedi_udelay(1);
1991         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
1992
1993
1994         // send write instruction
1995         devpriv->command5_bits |= EEPROM_EN_BIT;
1996         comedi_udelay(1);
1997         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
1998         labpc_serial_out(dev, write_instruction, write_length);
1999         // send 8 bit address to write to
2000         labpc_serial_out(dev, address, write_length);
2001         // write value
2002         labpc_serial_out(dev, value, write_length);
2003         devpriv->command5_bits &= ~EEPROM_EN_BIT;
2004         comedi_udelay(1);
2005         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
2006
2007         // disable read/write to eeprom
2008         devpriv->command5_bits &= ~EEPROM_EN_BIT & ~EEPROM_WRITE_UNPROTECT_BIT;
2009         comedi_udelay(1);
2010         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
2011
2012         return 0;
2013 }
2014
2015 static unsigned int labpc_eeprom_read_status(comedi_device *dev)
2016 {
2017         unsigned int value;
2018         const int read_status_instruction = 0x5;
2019         const int write_length = 8;     // 8 bit write lengths to eeprom
2020
2021         // enable read/write to eeprom
2022         devpriv->command5_bits &= ~EEPROM_EN_BIT;
2023         comedi_udelay(1);
2024         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
2025         devpriv->command5_bits |= EEPROM_EN_BIT | EEPROM_WRITE_UNPROTECT_BIT;
2026         comedi_udelay(1);
2027         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
2028
2029         // send read status instruction
2030         labpc_serial_out(dev, read_status_instruction, write_length);
2031         // read result
2032         value = labpc_serial_in(dev);
2033
2034         // disable read/write to eeprom
2035         devpriv->command5_bits &= ~EEPROM_EN_BIT & ~EEPROM_WRITE_UNPROTECT_BIT;
2036         comedi_udelay(1);
2037         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
2038
2039         return value;
2040 }
2041
2042 // writes to 8 bit calibration dacs
2043 static void write_caldac(comedi_device *dev, unsigned int channel, unsigned int value)
2044 {
2045         if( value == devpriv->caldac[ channel ] ) return;
2046         devpriv->caldac[ channel ] = value;
2047
2048         // clear caldac load bit and make sure we don't write to eeprom
2049         devpriv->command5_bits &= ~CALDAC_LOAD_BIT & ~EEPROM_EN_BIT & ~EEPROM_WRITE_UNPROTECT_BIT;
2050         comedi_udelay(1);
2051         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
2052
2053         // write 4 bit channel
2054         labpc_serial_out(dev, channel, 4);
2055         // write 8 bit caldac value
2056         labpc_serial_out(dev, value, 8);
2057
2058         // set and clear caldac bit to load caldac value
2059         devpriv->command5_bits |= CALDAC_LOAD_BIT;
2060         comedi_udelay(1);
2061         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
2062         devpriv->command5_bits &= ~CALDAC_LOAD_BIT;
2063         comedi_udelay(1);
2064         thisboard->write_byte(devpriv->command5_bits, dev->iobase + COMMAND5_REG);
2065 }
2066
2067 // PCMCIA crap
2068 #if defined(CONFIG_PCMCIA) || defined(CONFIG_PCMCIA_MODULE)
2069
2070 /*
2071    All the PCMCIA modules use PCMCIA_DEBUG to control debugging.  If
2072    you do not define PCMCIA_DEBUG at all, all the debug code will be
2073    left out.  If you compile with PCMCIA_DEBUG=0, the debug code will
2074    be present but disabled -- but it can then be enabled for specific
2075    modules at load time with a 'pc_debug=#' option to insmod.
2076 */
2077 #ifdef PCMCIA_DEBUG
2078 static int pc_debug = PCMCIA_DEBUG;
2079 MODULE_PARM(pc_debug, "i");
2080 #define DEBUG(n, args...) if (pc_debug>(n)) printk(KERN_DEBUG args)
2081 static char *version =
2082 "ni_labpc.c, based on dummy_cs.c 1.31 2001/08/24 12:13:13";
2083 #else
2084 #define DEBUG(n, args...)
2085 #endif
2086
2087 /*====================================================================*/
2088
2089 /* Parameters that can be set with 'insmod' */
2090
2091 /* The old way: bit map of interrupts to choose from */
2092 /* This means pick from 15, 14, 12, 11, 10, 9, 7, 5, 4, and 3 */
2093 static u_int irq_mask = 0xdeb8;
2094 /* Newer, simpler way of listing specific interrupts */
2095 static int irq_list[4] = { -1 };
2096
2097 MODULE_PARM(irq_mask, "i");
2098 MODULE_PARM(irq_list, "1-4i");
2099
2100 /*====================================================================*/
2101
2102 /*
2103    The event() function is this driver's Card Services event handler.
2104    It will be called by Card Services when an appropriate card status
2105    event is received.  The config() and release() entry points are
2106    used to configure or release a socket, in response to card
2107    insertion and ejection events.  They are invoked from the dummy
2108    event handler.
2109 */
2110
2111 static void labpc_config(dev_link_t *link);
2112 static void labpc_release(u_long arg);
2113 static int labpc_event(event_t event, int priority,
2114                        event_callback_args_t *args);
2115
2116 /*
2117    The attach() and detach() entry points are used to create and destroy
2118    "instances" of the driver, where each instance represents everything
2119    needed to manage one actual PCMCIA card.
2120 */
2121
2122 static dev_link_t *labpc_cs_attach(void);
2123 static void labpc_cs_detach(dev_link_t *);
2124
2125 /*
2126    You'll also need to prototype all the functions that will actually
2127    be used to talk to your device.  See 'memory_cs' for a good example
2128    of a fully self-sufficient driver; the other drivers rely more or
2129    less on other parts of the kernel.
2130 */
2131
2132 /*
2133    The dev_info variable is the "key" that is used to match up this
2134    device driver with appropriate cards, through the card configuration
2135    database.
2136 */
2137
2138 static dev_info_t dev_info = "daqcard-1200";
2139
2140 /*
2141    A dev_link_t structure has fields for most things that are needed
2142    to keep track of a socket, but there will usually be some device
2143    specific information that also needs to be kept track of.  The
2144    'priv' pointer in a dev_link_t structure can be used to point to
2145    a device-specific private data structure, like this.
2146
2147    To simplify the data structure handling, we actually include the
2148    dev_link_t structure in the device's private data structure.
2149
2150    A driver needs to provide a dev_node_t structure for each device
2151    on a card.  In some cases, there is only one device per card (for
2152    example, ethernet cards, modems).  In other cases, there may be
2153    many actual or logical devices (SCSI adapters, memory cards with
2154    multiple partitions).  The dev_node_t structures need to be kept
2155    in a linked list starting at the 'dev' field of a dev_link_t
2156    structure.  We allocate them in the card's private data structure,
2157    because they generally shouldn't be allocated dynamically.
2158
2159    In this case, we also provide a flag to indicate if a device is
2160    "stopped" due to a power management event, or card ejection.  The
2161    device IO routines can use a flag like this to throttle IO to a
2162    card that is not ready to accept it.
2163
2164    The bus_operations pointer is used on platforms for which we need
2165    to use special socket-specific versions of normal IO primitives
2166    (inb, outb, readb, writeb, etc) for card IO.
2167 */
2168
2169 typedef struct local_info_t {
2170     dev_link_t          link;
2171     dev_node_t          node;
2172     int                 stop;
2173     struct bus_operations *bus;
2174 } local_info_t;
2175
2176 /*====================================================================*/
2177
2178 static void cs_error(client_handle_t handle, int func, int ret)
2179 {
2180     error_info_t err = { func, ret };
2181     CardServices(ReportError, handle, &err);
2182 }
2183
2184 /*======================================================================
2185
2186     labpc_cs_attach() creates an "instance" of the driver, allocating
2187     local data structures for one device.  The device is registered
2188     with Card Services.
2189
2190     The dev_link structure is initialized, but we don't actually
2191     configure the card at this point -- we wait until we receive a
2192     card insertion event.
2193
2194 ======================================================================*/
2195
2196 static dev_link_t *labpc_cs_attach(void)
2197 {
2198     local_info_t *local;
2199     dev_link_t *link;
2200     client_reg_t client_reg;
2201     int ret, i;
2202
2203     DEBUG(0, "labpc_cs_attach()\n");
2204
2205     /* Allocate space for private device-specific data */
2206     local = kmalloc(sizeof(local_info_t), GFP_KERNEL);
2207     if (!local) return NULL;
2208     memset(local, 0, sizeof(local_info_t));
2209     link = &local->link; link->priv = local;
2210
2211     /* Initialize the dev_link_t structure */
2212     link->release.function = &labpc_release;
2213     link->release.data = (u_long)link;
2214
2215     /* Interrupt setup */
2216     link->irq.Attributes = IRQ_TYPE_EXCLUSIVE;
2217     link->irq.IRQInfo1 = IRQ_INFO2_VALID|IRQ_LEVEL_ID;
2218     if (irq_list[0] == -1)
2219                 link->irq.IRQInfo2 = irq_mask;
2220     else for (i = 0; i < 4; i++)
2221             link->irq.IRQInfo2 |= 1 << irq_list[i];
2222     link->irq.Handler = NULL;
2223
2224     /*
2225       General socket configuration defaults can go here.  In this
2226       client, we assume very little, and rely on the CIS for almost
2227       everything.  In most clients, many details (i.e., number, sizes,
2228       and attributes of IO windows) are fixed by the nature of the
2229       device, and can be hard-wired here.
2230     */
2231     link->conf.Attributes = 0;
2232     link->conf.Vcc = 50;
2233     link->conf.IntType = INT_MEMORY_AND_IO;
2234
2235     /* Register with Card Services */
2236     link->next = pcmcia_dev_list;
2237     pcmcia_dev_list = link;
2238     client_reg.dev_info = &dev_info;
2239     client_reg.Attributes = INFO_IO_CLIENT | INFO_CARD_SHARE;
2240     client_reg.EventMask =
2241         CS_EVENT_CARD_INSERTION | CS_EVENT_CARD_REMOVAL |
2242         CS_EVENT_RESET_PHYSICAL | CS_EVENT_CARD_RESET |
2243         CS_EVENT_PM_SUSPEND | CS_EVENT_PM_RESUME;
2244     client_reg.event_handler = &labpc_event;
2245     client_reg.Version = 0x0210;
2246     client_reg.event_callback_args.client_data = link;
2247     ret = CardServices(RegisterClient, &link->handle, &client_reg);
2248     if (ret != CS_SUCCESS) {
2249         cs_error(link->handle, RegisterClient, ret);
2250         labpc_cs_detach(link);
2251         return NULL;
2252     }
2253
2254     return link;
2255 } /* labpc_cs_attach */
2256
2257 /*======================================================================
2258
2259     This deletes a driver "instance".  The device is de-registered
2260     with Card Services.  If it has been released, all local data
2261     structures are freed.  Otherwise, the structures will be freed
2262     when the device is released.
2263
2264 ======================================================================*/
2265
2266 static void labpc_cs_detach(dev_link_t *link)
2267 {
2268     dev_link_t **linkp;
2269
2270     DEBUG(0, "labpc_cs_detach(0x%p)\n", link);
2271
2272     /* Locate device structure */
2273     for (linkp = &pcmcia_dev_list; *linkp; linkp = &(*linkp)->next)
2274         if (*linkp == link) break;
2275     if (*linkp == NULL)
2276         return;
2277
2278     /*
2279        If the device is currently configured and active, we won't
2280        actually delete it yet.  Instead, it is marked so that when
2281        the release() function is called, that will trigger a proper
2282        detach().
2283     */
2284     if (link->state & DEV_CONFIG) {
2285 #ifdef PCMCIA_DEBUG
2286         printk(KERN_DEBUG "ni_labpc: detach postponed, '%s' "
2287                "still locked\n", link->dev->dev_name);
2288 #endif
2289         link->state |= DEV_STALE_LINK;
2290         return;
2291     }
2292
2293     /* Break the link with Card Services */
2294     if (link->handle)
2295         CardServices(DeregisterClient, link->handle);
2296
2297     /* Unlink device structure, and free it */
2298     *linkp = link->next;
2299     /* This points to the parent local_info_t struct */
2300     kfree(link->priv);
2301
2302 } /* labpc_cs_detach */
2303
2304 /*======================================================================
2305
2306     labpc_config() is scheduled to run after a CARD_INSERTION event
2307     is received, to configure the PCMCIA socket, and to make the
2308     device available to the system.
2309
2310 ======================================================================*/
2311
2312 #define CS_CHECK(fn, args...) \
2313 while ((last_ret=CardServices(last_fn=(fn),args))!=0) goto cs_failed
2314
2315 #define CFG_CHECK(fn, args...) \
2316 if (CardServices(fn, args) != 0) goto next_entry
2317
2318 static void labpc_config(dev_link_t *link)
2319 {
2320     client_handle_t handle = link->handle;
2321     local_info_t *dev = link->priv;
2322     tuple_t tuple;
2323     cisparse_t parse;
2324     int last_fn, last_ret;
2325     u_char buf[64];
2326     config_info_t conf;
2327     win_req_t req;
2328     memreq_t map;
2329     cistpl_cftable_entry_t dflt = { 0 };
2330
2331     DEBUG(0, "labpc_config(0x%p)\n", link);
2332
2333     /*
2334        This reads the card's CONFIG tuple to find its configuration
2335        registers.
2336     */
2337     tuple.DesiredTuple = CISTPL_CONFIG;
2338     tuple.Attributes = 0;
2339     tuple.TupleData = buf;
2340     tuple.TupleDataMax = sizeof(buf);
2341     tuple.TupleOffset = 0;
2342     CS_CHECK(GetFirstTuple, handle, &tuple);
2343     CS_CHECK(GetTupleData, handle, &tuple);
2344     CS_CHECK(ParseTuple, handle, &tuple, &parse);
2345     link->conf.ConfigBase = parse.config.base;
2346     link->conf.Present = parse.config.rmask[0];
2347
2348     /* Configure card */
2349     link->state |= DEV_CONFIG;
2350
2351     /* Look up the current Vcc */
2352     CS_CHECK(GetConfigurationInfo, handle, &conf);
2353     link->conf.Vcc = conf.Vcc;
2354
2355     /*
2356       In this loop, we scan the CIS for configuration table entries,
2357       each of which describes a valid card configuration, including
2358       voltage, IO window, memory window, and interrupt settings.
2359
2360       We make no assumptions about the card to be configured: we use
2361       just the information available in the CIS.  In an ideal world,
2362       this would work for any PCMCIA card, but it requires a complete
2363       and accurate CIS.  In practice, a driver usually "knows" most of
2364       these things without consulting the CIS, and most client drivers
2365       will only use the CIS to fill in implementation-defined details.
2366     */
2367     tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
2368     CS_CHECK(GetFirstTuple, handle, &tuple);
2369     while (1) {
2370         cistpl_cftable_entry_t *cfg = &(parse.cftable_entry);
2371         CFG_CHECK(GetTupleData, handle, &tuple);
2372         CFG_CHECK(ParseTuple, handle, &tuple, &parse);
2373
2374         if (cfg->flags & CISTPL_CFTABLE_DEFAULT) dflt = *cfg;
2375         if (cfg->index == 0) goto next_entry;
2376         link->conf.ConfigIndex = cfg->index;
2377
2378         /* Does this card need audio output? */
2379         if (cfg->flags & CISTPL_CFTABLE_AUDIO) {
2380                 link->conf.Attributes |= CONF_ENABLE_SPKR;
2381                 link->conf.Status = CCSR_AUDIO_ENA;
2382         }
2383
2384         /* Use power settings for Vcc and Vpp if present */
2385         /*  Note that the CIS values need to be rescaled */
2386         if (cfg->vcc.present & (1<<CISTPL_POWER_VNOM)) {
2387             if (conf.Vcc != cfg->vcc.param[CISTPL_POWER_VNOM]/10000)
2388                 goto next_entry;
2389         } else if (dflt.vcc.present & (1<<CISTPL_POWER_VNOM)) {
2390             if (conf.Vcc != dflt.vcc.param[CISTPL_POWER_VNOM]/10000)
2391                 goto next_entry;
2392         }
2393
2394         if (cfg->vpp1.present & (1<<CISTPL_POWER_VNOM))
2395             link->conf.Vpp1 = link->conf.Vpp2 =
2396                 cfg->vpp1.param[CISTPL_POWER_VNOM]/10000;
2397         else if (dflt.vpp1.present & (1<<CISTPL_POWER_VNOM))
2398             link->conf.Vpp1 = link->conf.Vpp2 =
2399                 dflt.vpp1.param[CISTPL_POWER_VNOM]/10000;
2400
2401         /* Do we need to allocate an interrupt? */
2402         if (cfg->irq.IRQInfo1 || dflt.irq.IRQInfo1)
2403             link->conf.Attributes |= CONF_ENABLE_IRQ;
2404
2405         /* IO window settings */
2406         link->io.NumPorts1 = link->io.NumPorts2 = 0;
2407         if ((cfg->io.nwin > 0) || (dflt.io.nwin > 0)) {
2408             cistpl_io_t *io = (cfg->io.nwin) ? &cfg->io : &dflt.io;
2409                 link->io.Attributes1 = IO_DATA_PATH_WIDTH_8;
2410             link->io.IOAddrLines = io->flags & CISTPL_IO_LINES_MASK;
2411             link->io.BasePort1 = io->win[0].base;
2412             link->io.NumPorts1 = io->win[0].len;
2413             if (io->nwin > 1) {
2414                 link->io.Attributes2 = link->io.Attributes1;
2415                 link->io.BasePort2 = io->win[1].base;
2416                 link->io.NumPorts2 = io->win[1].len;
2417             }
2418             /* This reserves IO space but doesn't actually enable it */
2419             CFG_CHECK(RequestIO, link->handle, &link->io);
2420         }
2421
2422         /*
2423           Now set up a common memory window, if needed.  There is room
2424           in the dev_link_t structure for one memory window handle,
2425           but if the base addresses need to be saved, or if multiple
2426           windows are needed, the info should go in the private data
2427           structure for this device.
2428
2429           Note that the memory window base is a physical address, and
2430           needs to be mapped to virtual space with ioremap() before it
2431           is used.
2432         */
2433         if ((cfg->mem.nwin > 0) || (dflt.mem.nwin > 0)) {
2434             cistpl_mem_t *mem =
2435                 (cfg->mem.nwin) ? &cfg->mem : &dflt.mem;
2436             req.Attributes = WIN_DATA_WIDTH_16|WIN_MEMORY_TYPE_CM;
2437             req.Attributes |= WIN_ENABLE;
2438             req.Base = mem->win[0].host_addr;
2439             req.Size = mem->win[0].len;
2440             if (req.Size < 0x1000)
2441                 req.Size = 0x1000;
2442             req.AccessSpeed = 0;
2443             link->win = (window_handle_t)link->handle;
2444             CFG_CHECK(RequestWindow, &link->win, &req);
2445             map.Page = 0; map.CardOffset = mem->win[0].card_addr;
2446             CFG_CHECK(MapMemPage, link->win, &map);
2447         }
2448         /* If we got this far, we're cool! */
2449         break;
2450
2451     next_entry:
2452         if (link->io.NumPorts1)
2453             CardServices(ReleaseIO, link->handle, &link->io);
2454         CS_CHECK(GetNextTuple, handle, &tuple);
2455     }
2456
2457     /*
2458        Allocate an interrupt line.  Note that this does not assign a
2459        handler to the interrupt, unless the 'Handler' member of the
2460        irq structure is initialized.
2461     */
2462     if (link->conf.Attributes & CONF_ENABLE_IRQ)
2463         CS_CHECK(RequestIRQ, link->handle, &link->irq);
2464
2465     /*
2466        This actually configures the PCMCIA socket -- setting up
2467        the I/O windows and the interrupt mapping, and putting the
2468        card and host interface into "Memory and IO" mode.
2469     */
2470     CS_CHECK(RequestConfiguration, link->handle, &link->conf);
2471
2472     /*
2473       At this point, the dev_node_t structure(s) need to be
2474       initialized and arranged in a linked list at link->dev.
2475     */
2476     sprintf(dev->node.dev_name, "daqcard-1200");
2477     dev->node.major = dev->node.minor = 0;
2478     link->dev = &dev->node;
2479
2480     /* Finally, report what we've done */
2481     printk(KERN_INFO "%s: index 0x%02x: Vcc %d.%d",
2482            dev->node.dev_name, link->conf.ConfigIndex,
2483            link->conf.Vcc/10, link->conf.Vcc%10);
2484     if (link->conf.Vpp1)
2485         printk(", Vpp %d.%d", link->conf.Vpp1/10, link->conf.Vpp1%10);
2486     if (link->conf.Attributes & CONF_ENABLE_IRQ)
2487         printk(", irq %d", link->irq.AssignedIRQ);
2488     if (link->io.NumPorts1)
2489         printk(", io 0x%04x-0x%04x", link->io.BasePort1,
2490                link->io.BasePort1+link->io.NumPorts1-1);
2491     if (link->io.NumPorts2)
2492         printk(" & 0x%04x-0x%04x", link->io.BasePort2,
2493                link->io.BasePort2+link->io.NumPorts2-1);
2494     if (link->win)
2495         printk(", mem 0x%06lx-0x%06lx", req.Base,
2496                req.Base+req.Size-1);
2497     printk("\n");
2498
2499     link->state &= ~DEV_CONFIG_PENDING;
2500     return;
2501
2502 cs_failed:
2503     cs_error(link->handle, last_fn, last_ret);
2504     labpc_release((u_long)link);
2505
2506 } /* labpc_config */
2507
2508 /*======================================================================
2509
2510     After a card is removed, labpc_release() will unregister the
2511     device, and release the PCMCIA configuration.  If the device is
2512     still open, this will be postponed until it is closed.
2513
2514 ======================================================================*/
2515
2516 static void labpc_release(u_long arg)
2517 {
2518     dev_link_t *link = (dev_link_t *)arg;
2519
2520     DEBUG(0, "labpc_release(0x%p)\n", link);
2521
2522     /*
2523        If the device is currently in use, we won't release until it
2524        is actually closed, because until then, we can't be sure that
2525        no one will try to access the device or its data structures.
2526     */
2527     if (link->open) {
2528         DEBUG(1, "ni_labpc: release postponed, '%s' still open\n",
2529               link->dev->dev_name);
2530         link->state |= DEV_STALE_CONFIG;
2531         return;
2532     }
2533
2534     /* Unlink the device chain */
2535     link->dev = NULL;
2536
2537     /*
2538       In a normal driver, additional code may be needed to release
2539       other kernel data structures associated with this device.
2540     */
2541
2542     /* Don't bother checking to see if these succeed or not */
2543     if (link->win)
2544         CardServices(ReleaseWindow, link->win);
2545     CardServices(ReleaseConfiguration, link->handle);
2546     if (link->io.NumPorts1)
2547         CardServices(ReleaseIO, link->handle, &link->io);
2548     if (link->irq.AssignedIRQ)
2549         CardServices(ReleaseIRQ, link->handle, &link->irq);
2550     link->state &= ~DEV_CONFIG;
2551
2552     if (link->state & DEV_STALE_LINK)
2553         labpc_cs_detach(link);
2554
2555 } /* labpc_release */
2556
2557 /*======================================================================
2558
2559     The card status event handler.  Mostly, this schedules other
2560     stuff to run after an event is received.
2561
2562     When a CARD_REMOVAL event is received, we immediately set a
2563     private flag to block future accesses to this device.  All the
2564     functions that actually access the device should check this flag
2565     to make sure the card is still present.
2566
2567 ======================================================================*/
2568
2569 static int labpc_event(event_t event, int priority,
2570                        event_callback_args_t *args)
2571 {
2572     dev_link_t *link = args->client_data;
2573     local_info_t *dev = link->priv;
2574
2575     DEBUG(1, "labpc_event(0x%06x)\n", event);
2576
2577     switch (event) {
2578     case CS_EVENT_CARD_REMOVAL:
2579         link->state &= ~DEV_PRESENT;
2580         if (link->state & DEV_CONFIG) {
2581             ((local_info_t *)link->priv)->stop = 1;
2582             mod_timer(&link->release, jiffies + HZ/20);
2583         }
2584         break;
2585     case CS_EVENT_CARD_INSERTION:
2586         link->state |= DEV_PRESENT | DEV_CONFIG_PENDING;
2587         dev->bus = args->bus;
2588         labpc_config(link);
2589         break;
2590     case CS_EVENT_PM_SUSPEND:
2591         link->state |= DEV_SUSPEND;
2592         /* Fall through... */
2593     case CS_EVENT_RESET_PHYSICAL:
2594         /* Mark the device as stopped, to block IO until later */
2595         dev->stop = 1;
2596         if (link->state & DEV_CONFIG)
2597             CardServices(ReleaseConfiguration, link->handle);
2598         break;
2599     case CS_EVENT_PM_RESUME:
2600         link->state &= ~DEV_SUSPEND;
2601         /* Fall through... */
2602     case CS_EVENT_CARD_RESET:
2603         if (link->state & DEV_CONFIG)
2604             CardServices(RequestConfiguration, link->handle, &link->conf);
2605         dev->stop = 0;
2606         /*
2607           In a normal driver, additional code may go here to restore
2608           the device state and restart IO.
2609         */
2610         break;
2611     }
2612     return 0;
2613 } /* labpc_event */
2614
2615 /*====================================================================*/
2616
2617 static int __init init_labpc_cs(void)
2618 {
2619     servinfo_t serv;
2620     DEBUG(0, "%s\n", version);
2621     CardServices(GetCardServicesInfo, &serv);
2622     if (serv.Revision != CS_RELEASE_CODE) {
2623         printk(KERN_NOTICE "ni_labpc: Card Services release "
2624                "does not match!\n");
2625         return -1;
2626     }
2627     register_pccard_driver(&dev_info, &labpc_cs_attach, &labpc_cs_detach);
2628     return 0;
2629 }
2630
2631 static void __exit exit_labpc_cs(void)
2632 {
2633     DEBUG(0, "ni_labpc: unloading\n");
2634     unregister_pccard_driver(&dev_info);
2635     while (pcmcia_dev_list != NULL) {
2636         del_timer(&pcmcia_dev_list->release);
2637         if (pcmcia_dev_list->state & DEV_CONFIG)
2638             labpc_release((u_long)pcmcia_dev_list);
2639         labpc_cs_detach(pcmcia_dev_list);
2640     }
2641 }
2642
2643 int init_module(void)
2644 {
2645         int ret;
2646
2647         ret = init_labpc_cs();
2648         if(ret < 0)
2649                 return ret;
2650
2651         return comedi_driver_register(&driver_labpc);
2652 }
2653
2654 void cleanup_module(void)
2655 {
2656         exit_labpc_cs();
2657         comedi_driver_unregister(&driver_labpc);
2658 }
2659
2660 #else
2661 COMEDI_INITCLEANUP(driver_labpc);
2662
2663 #endif // CONFIG_PCMCIA