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