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