Global change from ds@stm.lbl.gov to ds@schleef.org
[comedi.git] / comedi / drivers / quatech_daqp_cs.c
1 /*======================================================================
2
3     Quatech DAQP PCMCIA data capture cards COMEDI client driver
4     Copyright (C) 2000 Brent Baccala <baccala@freesoft.org>
5     The DAQP interface code in this file is released into the public domain.
6
7     COMEDI - Linux Control and Measurement Device Interface
8     Copyright (C) 1998 David A. Schleef <ds@schleef.org>
9
10     daqp_cs.c 1.00
11
12
13
14     Documentation for the DAQP PCMCIA cards can be found on Quatech's site:
15
16                 ftp://ftp.quatech.com/Manuals/daqp-208.pdf
17
18     This manual is for both the DAQP-208 and the DAQP-308.
19
20     This code presently doesn't do D/A conversion; only A/D.
21     Also, I've had problems getting interrupts to work reliably,
22     the driver currently polls the card.
23
24     Multiple DAPQ cards are handled and can be independently attached
25     by specifying a numeric argument to comedi_config.  Cards are
26     numbered sequentially from 0 in the order they are inserted/detected.
27
28 ======================================================================*/
29
30 /*
31 Driver: quatech_daqp_cs.o
32 Description: Quatech DAQP PCMCIA data capture cards
33 Author: Brent Baccala <baccala@freesoft.org>
34 Status: unkown
35 Devices: [Quatech] DAQP-208 (daqp), DAQP-308
36 */
37
38 //#include <pcmcia/config.h>
39 //#include <pcmcia/k_compat.h>
40
41 #include <linux/kernel.h>
42 #include <linux/module.h>
43 #include <linux/init.h>
44 #include <linux/sched.h>
45 #include <linux/ptrace.h>
46 #include <linux/slab.h>
47 #include <linux/string.h>
48 #include <linux/timer.h>
49 #include <asm/io.h>
50 #include <asm/system.h>
51
52 #include <pcmcia/version.h>
53 #include <pcmcia/cs_types.h>
54 #include <pcmcia/cs.h>
55 #include <pcmcia/cistpl.h>
56 #include <pcmcia/cisreg.h>
57 #include <pcmcia/ds.h>
58
59 #include <linux/comedidev.h>
60
61 /*
62    All the PCMCIA modules use PCMCIA_DEBUG to control debugging.  If
63    you do not define PCMCIA_DEBUG at all, all the debug code will be
64    left out.  If you compile with PCMCIA_DEBUG=0, the debug code will
65    be present but disabled -- but it can then be enabled for specific
66    modules at load time with a 'pc_debug=#' option to insmod.
67 */
68 #ifdef PCMCIA_DEBUG
69 static int pc_debug = PCMCIA_DEBUG;
70 MODULE_PARM(pc_debug, "i");
71 #define DEBUG(n, args...) if (pc_debug>(n)) printk(KERN_DEBUG args)
72 static char *version =
73 "daqp_cs.c 1.00 2000/10/02 (Brent Baccala)";
74 #else
75 #define DEBUG(n, args...)
76 #endif
77
78 /* Maximum number of separate DAQP devices we'll allow */
79 #define MAX_DEV         4
80
81 /* I can't get my DAQP-308 to reliably generate interrupts, so I poll it */
82 /* #define USE_INTERRUPTS */
83
84 /*
85    A dev_link_t structure has fields for most things that are needed
86    to keep track of a socket, but there will usually be some device
87    specific information that also needs to be kept track of.  The
88    'priv' pointer in a dev_link_t structure can be used to point to
89    a device-specific private data structure, like this.
90
91    To simplify the data structure handling, we actually include the
92    dev_link_t structure in the device's private data structure.
93
94    A driver needs to provide a dev_node_t structure for each device
95    on a card.  In some cases, there is only one device per card (for
96    example, ethernet cards, modems).  In other cases, there may be
97    many actual or logical devices (SCSI adapters, memory cards with
98    multiple partitions).  The dev_node_t structures need to be kept
99    in a linked list starting at the 'dev' field of a dev_link_t
100    structure.  We allocate them in the card's private data structure,
101    because they generally shouldn't be allocated dynamically.
102
103    We also provide an index into the dev_table
104 */
105    
106 typedef struct local_info_t {
107     dev_link_t          link;
108     dev_node_t          node;
109     int                 stop;
110     int                 table_index;
111     wait_queue_head_t   endofscan;
112 } local_info_t;
113
114 /* A list of "instances" of the device. */
115
116 static local_info_t *dev_table[MAX_DEV] = { NULL, /* ... */ };
117
118
119 /* this is COMEDI's private data structure unique to this hardware driver.
120    Not to be confused with PCMCIA's local_info_t (above).
121 */
122
123 typedef struct {
124
125         int devnum;
126
127 } daqp_private;
128
129 #define devpriv ((daqp_private *)dev->private)
130
131 /*====================================================================*/
132
133 /* Parameters that can be set with 'insmod' */
134
135 /* The old way: bit map of interrupts to choose from */
136 /* This means pick from 15, 14, 12, 11, 10, 9, 7, 5, 4, and 3 */
137 static u_int irq_mask = 0xdeb8;
138 /* Newer, simpler way of listing specific interrupts */
139 static int irq_list[4] = { -1 };
140
141 MODULE_PARM(irq_mask, "i");
142 MODULE_PARM(irq_list, "1-4i");
143
144 /*====================================================================*/
145
146 /* The DAQP communicates with the system through a 16 byte I/O window. */
147
148 #define DAQP_FIFO_SIZE          4096
149
150 #define DAQP_FIFO               0
151 #define DAQP_SCANLIST           1
152 #define DAQP_CONTROL            2
153 #define DAQP_STATUS             2
154 #define DAQP_DIGITAL_IO         3
155 #define DAQP_PACER_LOW          4
156 #define DAQP_PACER_MID          5
157 #define DAQP_PACER_HIGH         6
158 #define DAQP_COMMAND            7
159 #define DAQP_DA                 8
160 #define DAQP_TIMER              10
161 #define DAQP_AUX                15
162
163 #define DAQP_SCANLIST_DIFFERENTIAL      0x4000
164 #define DAQP_SCANLIST_GAIN(x)           ((x)<<12)
165 #define DAQP_SCANLIST_CHANNEL(x)        ((x)<<8)
166 #define DAQP_SCANLIST_START             0x0080
167 #define DAQP_SCANLIST_EXT_GAIN(x)       ((x)<<4)
168 #define DAQP_SCANLIST_EXT_CHANNEL(x)    (x)
169
170 #define DAQP_CONTROL_PACER_100kHz       0xc0
171 #define DAQP_CONTROL_PACER_1MHz         0x80
172 #define DAQP_CONTROL_PACER_5MHz         0x40
173 #define DAQP_CONTROL_PACER_EXTERNAL     0x00
174 #define DAQP_CONTORL_EXPANSION          0x20
175 #define DAQP_CONTROL_EOS_INT_ENABLE     0x10
176 #define DAQP_CONTROL_FIFO_INT_ENABLE    0x08
177 #define DAQP_CONTROL_TRIGGER_ONESHOT    0x00
178 #define DAQP_CONTROL_TRIGGER_CONTINUOUS 0x04
179 #define DAQP_CONTROL_TRIGGER_INTERNAL   0x00
180 #define DAQP_CONTROL_TRIGGER_EXTERNAL   0x02
181 #define DAQP_CONTROL_TRIGGER_RISING     0x00
182 #define DAQP_CONTROL_TRIGGER_FALLING    0x01
183
184 #define DAQP_STATUS_IDLE                0x80
185 #define DAQP_STATUS_RUNNING             0x40
186 #define DAQP_STATUS_DATA_LOST           0x20
187 #define DAQP_STATUS_END_OF_SCAN         0x10
188 #define DAQP_STATUS_FIFO_THRESHOLD      0x08
189 #define DAQP_STATUS_FIFO_FULL           0x04
190 #define DAQP_STATUS_FIFO_NEARFULL       0x02
191 #define DAQP_STATUS_FIFO_EMPTY          0x01
192
193 #define DAQP_COMMAND_ARM                0x80
194 #define DAQP_COMMAND_RSTF               0x40
195 #define DAQP_COMMAND_RSTQ               0x20
196 #define DAQP_COMMAND_STOP               0x10
197 #define DAQP_COMMAND_LATCH              0x08
198 #define DAQP_COMMAND_100kHz             0x00
199 #define DAQP_COMMAND_50kHz              0x02
200 #define DAQP_COMMAND_25kHz              0x04
201 #define DAQP_COMMAND_FIFO_DATA          0x01
202 #define DAQP_COMMAND_FIFO_PROGRAM       0x00
203
204 #define DAQP_AUX_TRIGGER_TTL            0x00
205 #define DAQP_AUX_TRIGGER_ANALOG         0x80
206 #define DAQP_AUX_TRIGGER_PRETRIGGER     0x40
207 #define DAQP_AUX_TIMER_INT_ENABLE       0x20
208 #define DAQP_AUX_TIMER_RELOAD           0x00
209 #define DAQP_AUX_TIMER_PAUSE            0x08
210 #define DAQP_AUX_TIMER_GO               0x10
211 #define DAQP_AUX_TIMER_GO_EXTERNAL      0x18
212 #define DAQP_AUX_TIMER_EXTERNAL_SRC     0x04
213 #define DAQP_AUX_TIMER_INTERNAL_SRC     0x00
214 #define DAQP_AUX_DA_DIRECT              0x00
215 #define DAQP_AUX_DA_OVERFLOW            0x01
216 #define DAQP_AUX_DA_EXTERNAL            0x02
217 #define DAQP_AUX_DA_PACER               0x03
218
219 #define DAQP_AUX_RUNNING                0x80
220 #define DAQP_AUX_TRIGGERED              0x40
221 #define DAQP_AUX_DA_BUFFER              0x20
222 #define DAQP_AUX_TIMER_OVERFLOW         0x10
223 #define DAQP_AUX_CONVERSION             0x08
224 #define DAQP_AUX_DATA_LOST              0x04
225 #define DAQP_AUX_FIFO_NEARFULL          0x02
226 #define DAQP_AUX_FIFO_EMPTY             0x01
227
228 static comedi_lrange range_daqp_ai = { 4, {
229         BIP_RANGE( 10 ),
230         BIP_RANGE( 5 ),
231         BIP_RANGE( 2.5 ),
232         BIP_RANGE( 1.25 )
233 }};
234
235 /*====================================================================*/
236
237 /* comedi interface code */
238
239 static int daqp_attach(comedi_device *dev,comedi_devconfig *it);
240 static int daqp_detach(comedi_device *dev);
241 static comedi_driver driver_daqp={
242         driver_name:    "daqp",
243         module:         THIS_MODULE,
244         attach:         daqp_attach,
245         detach:         daqp_detach,
246 };
247
248
249 static void daqp_dump(comedi_device *dev)
250 {
251         printk("DAQP: status %02x; aux status %02x\n",
252                inb(dev->iobase + DAQP_STATUS), inb(dev->iobase + DAQP_AUX));
253 }
254
255 static int daqp_ai_insn_read(comedi_device *dev,comedi_subdevice *s,
256         comedi_insn *insn,lsampl_t *data)
257 {
258         local_info_t *local;
259         int i;
260         int v;
261         int counter=10000;
262 #ifdef USE_INTERRUPTS
263         int threshold;
264         int flags;
265         int timeout;
266 #endif
267
268         if (!dev_table[devpriv->devnum] || dev_table[devpriv->devnum]->stop) {
269                 return -EIO;
270         } else {
271                 local = dev_table[devpriv->devnum];
272         }
273
274         /* Stop any running conversion */
275         outb(DAQP_COMMAND_STOP,
276              dev->iobase+DAQP_COMMAND);
277
278         outb(0, dev->iobase+DAQP_AUX);
279
280         /* Reset scan list queue */
281         outb(DAQP_COMMAND_RSTQ,
282              dev->iobase+DAQP_COMMAND);
283
284         /* Program one scan list entry */
285
286         v = DAQP_SCANLIST_CHANNEL(CR_CHAN(insn->chanspec))
287                 | DAQP_SCANLIST_GAIN(CR_RANGE(insn->chanspec));
288
289         if (CR_AREF(insn->chanspec) == AREF_DIFF) {
290                 v |= DAQP_SCANLIST_DIFFERENTIAL;
291         }
292
293         v |= DAQP_SCANLIST_START;
294
295         outb(v & 0xff, dev->iobase + DAQP_SCANLIST);
296         outb(v >> 8, dev->iobase + DAQP_SCANLIST);
297
298         /* Reset data FIFO (see page 28 of DAQP User's Manual) */
299         outb(DAQP_COMMAND_RSTF,
300              dev->iobase + DAQP_COMMAND);
301
302 #ifdef USE_INTERRUPTS
303         /* Set FIFO threshold */
304         // threshold = DAQP_FIFO_SIZE - 2*it->n_chan;
305         threshold = DAQP_FIFO_SIZE - 1;
306         outb(0, dev->iobase + DAQP_FIFO);
307         outb(0, dev->iobase + DAQP_FIFO);
308         outb(threshold & 0xff, dev->iobase + DAQP_FIFO);
309         outb(threshold >> 8, dev->iobase + DAQP_FIFO);
310 #endif
311
312         /* Set trigger */
313         v = DAQP_CONTROL_TRIGGER_ONESHOT | DAQP_CONTROL_TRIGGER_INTERNAL
314           | DAQP_CONTROL_PACER_100kHz;
315 #ifdef USE_INTERRUPTS
316         v |= DAQP_CONTROL_FIFO_INT_ENABLE;
317 #endif
318         outb(v, dev->iobase + DAQP_CONTROL);
319
320 #ifdef USE_INTERRUPTS
321         save_flags(flags);
322         cli();
323 #endif
324
325         /* Start conversion */
326         outb(DAQP_COMMAND_ARM | DAQP_COMMAND_FIFO_DATA,
327              dev->iobase + DAQP_COMMAND);
328
329 #ifdef USE_INTERRUPTS
330         timeout = sleep_on_timeout(&local->endofscan, 1*HZ);
331
332         restore_flags(flags);
333
334         printk("timeout: %d\n", timeout);
335 #endif
336
337         i=0;
338
339         /* Wait for data in FIFO */
340         while (--counter
341                && (inb(dev->iobase + DAQP_STATUS)
342                    & DAQP_STATUS_FIFO_EMPTY));
343
344         if (!counter) {
345                 printk("DAQP FIFO never got data!\n");
346                 daqp_dump(dev);
347                 return -EIO;
348         } else {
349                 data[i] = inb(dev->iobase + DAQP_FIFO);
350                 data[i] |= inb(dev->iobase + DAQP_FIFO) << 8;
351                 data[i] ^= 0x8000;
352         }
353
354         /* XXX wrong, but I don't know how to fix it --ds */
355         return 1;
356 }
357
358 static void daqp_interrupt(int irq, void * dev_id, struct pt_regs *regs)
359 {
360         local_info_t *local = (local_info_t *)dev_id;
361
362         if (local == NULL) {
363                 printk(KERN_WARNING "daqp_interrupt(): irq %d for unknown device.\n",
364                        irq);
365                 return;
366         }
367
368         wake_up(&local->endofscan);
369
370         printk("daqp_interrupt()\n");
371 }
372
373 /* daqp_attach is called via comedi_config to attach a comedi device
374  * to a /dev/comedi*.  Note that this is different from daqp_cs_attach()
375  * which is called by the pcmcia subsystem to attach the PCMCIA card
376  * when it is inserted.
377  */
378
379 static int daqp_attach(comedi_device *dev, comedi_devconfig *it)
380 {
381         int ret;
382         comedi_subdevice *s;
383
384         if (it->options[0] < 0 || it->options[0] >= MAX_DEV
385             || ! dev_table[it->options[0]]) {
386           printk("comedi%d: No such daqp device %d\n",
387                  dev->minor, it->options[0]);
388           return -EIO;
389         }
390
391         /* Probably should pull this out of PCMCIA CIS tuples */
392         dev->board_name = "Quatech DAQP";
393
394         dev->iobase=dev_table[it->options[0]]->link.io.BasePort1;
395
396         if((ret=alloc_private(dev,sizeof(daqp_private))) < 0)
397                 return ret;
398         devpriv->devnum = it->options[0];
399
400         dev->n_subdevices=1;
401         if((ret=alloc_subdevices(dev))<0)
402                 return ret;
403
404         printk("comedi%d: attaching daqp%d (io 0x%04x)\n",
405                dev->minor, it->options[0], dev->iobase);
406
407         s=dev->subdevices+0;
408         s->type=COMEDI_SUBD_AI;
409         s->subdev_flags=SDF_READABLE;
410         s->n_chan=8;
411         s->maxdata=0xffff;
412         s->range_table=&range_daqp_ai;
413         s->insn_read=daqp_ai_insn_read;
414
415         return 1;
416 }
417
418
419 /* daqp_detach (called from comedi_comdig) does nothing. If the PCMCIA
420  * card is removed, daqp_cs_detach() is called by the pcmcia subsystem.
421  */
422
423 static int daqp_detach(comedi_device *dev)
424 {
425         printk("comedi%d: detaching daqp\n",dev->minor);
426         
427         return 0;
428 }
429
430 /*====================================================================
431
432     PCMCIA interface code
433
434     The rest of the code in this file is based on dummy_cs.c v1.24
435     from the Linux pcmcia_cs distribution v3.1.8 and is subject
436     to the following license agreement.
437
438     The remaining contents of this file are subject to the Mozilla Public
439     License Version 1.1 (the "License"); you may not use this file
440     except in compliance with the License. You may obtain a copy of
441     the License at http://www.mozilla.org/MPL/
442
443     Software distributed under the License is distributed on an "AS
444     IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
445     implied. See the License for the specific language governing
446     rights and limitations under the License.
447
448     The initial developer of the original code is David A. Hinds
449     <dhinds@pcmcia.sourceforge.org>.  Portions created by David A. Hinds
450     are Copyright (C) 1999 David A. Hinds.  All Rights Reserved.
451
452     Alternatively, the contents of this file may be used under the
453     terms of the GNU Public License version 2 (the "GPL"), in which
454     case the provisions of the GPL are applicable instead of the
455     above.  If you wish to allow the use of your version of this file
456     only under the terms of the GPL and not to allow others to use
457     your version of this file under the MPL, indicate your decision
458     by deleting the provisions above and replace them with the notice
459     and other provisions required by the GPL.  If you do not delete
460     the provisions above, a recipient may use your version of this
461     file under either the MPL or the GPL.
462     
463 ======================================================================*/
464
465 /*
466    The event() function is this driver's Card Services event handler.
467    It will be called by Card Services when an appropriate card status
468    event is received.  The config() and release() entry points are
469    used to configure or release a socket, in response to card
470    insertion and ejection events.
471 */
472
473 static void daqp_cs_config(dev_link_t *link);
474 static void daqp_cs_release(u_long arg);
475 static int daqp_cs_event(event_t event, int priority,
476                        event_callback_args_t *args);
477
478 /*
479    The attach() and detach() entry points are used to create and destroy
480    "instances" of the driver, where each instance represents everything
481    needed to manage one actual PCMCIA card.
482 */
483
484 static dev_link_t *daqp_cs_attach(void);
485 static void daqp_cs_detach(dev_link_t *);
486
487 /*
488    The dev_info variable is the "key" that is used to match up this
489    device driver with appropriate cards, through the card configuration
490    database.
491 */
492
493 static dev_info_t dev_info = "daqp_cs";
494
495 /*====================================================================*/
496
497 static void cs_error(client_handle_t handle, int func, int ret)
498 {
499     error_info_t err = { func, ret };
500     CardServices(ReportError, handle, &err);
501 }
502
503 /*======================================================================
504
505     daqp_cs_attach() creates an "instance" of the driver, allocating
506     local data structures for one device.  The device is registered
507     with Card Services.
508
509     The dev_link structure is initialized, but we don't actually
510     configure the card at this point -- we wait until we receive a
511     card insertion event.
512     
513 ======================================================================*/
514
515 static dev_link_t *daqp_cs_attach(void)
516 {
517     local_info_t *local;
518     dev_link_t *link;
519     client_reg_t client_reg;
520     int ret, i;
521     
522     DEBUG(0, "daqp_cs_attach()\n");
523
524     for (i = 0; i < MAX_DEV; i++)
525       if (dev_table[i] == NULL) break;
526     if (i == MAX_DEV) {
527       printk(KERN_NOTICE "daqp_cs: no devices available\n");
528       return NULL;
529     }
530     
531     /* Allocate space for private device-specific data */
532     local = kmalloc(sizeof(local_info_t), GFP_KERNEL);
533     if (!local) return NULL;
534     memset(local, 0, sizeof(local_info_t));
535
536     local->table_index = i;
537     dev_table[i] = local;
538     link = &local->link;
539     link->priv = local;
540
541     init_waitqueue_head(&local->endofscan);
542
543     /* Initialize the dev_link_t structure */
544     link->release.function = &daqp_cs_release;
545     link->release.data = (u_long)link;
546
547     /* Interrupt setup */
548     link->irq.Attributes = IRQ_TYPE_EXCLUSIVE | IRQ_HANDLE_PRESENT;
549     link->irq.IRQInfo1 = IRQ_INFO2_VALID|IRQ_LEVEL_ID;
550     if (irq_list[0] == -1)
551         link->irq.IRQInfo2 = irq_mask;
552     else
553         for (i = 0; i < 4; i++)
554             link->irq.IRQInfo2 |= 1 << irq_list[i];
555     link->irq.Handler = daqp_interrupt;
556     link->irq.Instance = local;
557     
558     /*
559       General socket configuration defaults can go here.  In this
560       client, we assume very little, and rely on the CIS for almost
561       everything.  In most clients, many details (i.e., number, sizes,
562       and attributes of IO windows) are fixed by the nature of the
563       device, and can be hard-wired here.
564     */
565     link->conf.Attributes = 0;
566     link->conf.Vcc = 50;
567     link->conf.IntType = INT_MEMORY_AND_IO;
568
569     /* Register with Card Services */
570     client_reg.dev_info = &dev_info;
571     client_reg.Attributes = INFO_IO_CLIENT | INFO_CARD_SHARE;
572     client_reg.EventMask =
573         CS_EVENT_CARD_INSERTION | CS_EVENT_CARD_REMOVAL |
574         CS_EVENT_RESET_PHYSICAL | CS_EVENT_CARD_RESET |
575         CS_EVENT_PM_SUSPEND | CS_EVENT_PM_RESUME;
576     client_reg.event_handler = &daqp_cs_event;
577     client_reg.Version = 0x0210;
578     client_reg.event_callback_args.client_data = link;
579     ret = CardServices(RegisterClient, &link->handle, &client_reg);
580     if (ret != CS_SUCCESS) {
581         cs_error(link->handle, RegisterClient, ret);
582         daqp_cs_detach(link);
583         return NULL;
584     }
585
586     return link;
587 } /* daqp_cs_attach */
588
589 /*======================================================================
590
591     This deletes a driver "instance".  The device is de-registered
592     with Card Services.  If it has been released, all local data
593     structures are freed.  Otherwise, the structures will be freed
594     when the device is released.
595
596 ======================================================================*/
597
598 static void daqp_cs_detach(dev_link_t *link)
599 {
600     local_info_t *dev = link->priv;
601
602     DEBUG(0, "daqp_cs_detach(0x%p)\n", link);
603     
604     /*
605        If the device is currently configured and active, we won't
606        actually delete it yet.  Instead, it is marked so that when
607        the release() function is called, that will trigger a proper
608        detach().
609     */
610     if (link->state & DEV_CONFIG) {
611 #ifdef PCMCIA_DEBUG
612         printk(KERN_DEBUG "daqp_cs: detach postponed, '%s' "
613                "still locked\n", link->dev->dev_name);
614 #endif
615         link->state |= DEV_STALE_LINK;
616         return;
617     }
618
619     /* Break the link with Card Services */
620     if (link->handle)
621         CardServices(DeregisterClient, link->handle);
622     
623     /* Unlink device structure, and free it */
624     dev_table[dev->table_index] = NULL;
625     kfree(dev);
626     
627 } /* daqp_cs_detach */
628
629 /*======================================================================
630
631     daqp_cs_config() is scheduled to run after a CARD_INSERTION event
632     is received, to configure the PCMCIA socket, and to make the
633     device available to the system.
634     
635 ======================================================================*/
636
637 #define CS_CHECK(fn, args...) \
638 while ((last_ret=CardServices(last_fn=(fn),args))!=0) goto cs_failed
639
640 #define CFG_CHECK(fn, args...) \
641 if (CardServices(fn, args) != 0) goto next_entry
642
643 static void daqp_cs_config(dev_link_t *link)
644 {
645     client_handle_t handle = link->handle;
646     local_info_t *dev = link->priv;
647     tuple_t tuple;
648     cisparse_t parse;
649     int last_fn, last_ret;
650     u_char buf[64];
651     config_info_t conf;
652     
653     DEBUG(0, "daqp_cs_config(0x%p)\n", link);
654
655     /*
656        This reads the card's CONFIG tuple to find its configuration
657        registers.
658     */
659     tuple.DesiredTuple = CISTPL_CONFIG;
660     tuple.Attributes = 0;
661     tuple.TupleData = buf;
662     tuple.TupleDataMax = sizeof(buf);
663     tuple.TupleOffset = 0;
664     CS_CHECK(GetFirstTuple, handle, &tuple);
665     CS_CHECK(GetTupleData, handle, &tuple);
666     CS_CHECK(ParseTuple, handle, &tuple, &parse);
667     link->conf.ConfigBase = parse.config.base;
668     link->conf.Present = parse.config.rmask[0];
669     
670     /* Configure card */
671     link->state |= DEV_CONFIG;
672
673     /* Look up the current Vcc */
674     CS_CHECK(GetConfigurationInfo, handle, &conf);
675     link->conf.Vcc = conf.Vcc;
676
677     /*
678       In this loop, we scan the CIS for configuration table entries,
679       each of which describes a valid card configuration, including
680       voltage, IO window, memory window, and interrupt settings.
681
682       We make no assumptions about the card to be configured: we use
683       just the information available in the CIS.  In an ideal world,
684       this would work for any PCMCIA card, but it requires a complete
685       and accurate CIS.  In practice, a driver usually "knows" most of
686       these things without consulting the CIS, and most client drivers
687       will only use the CIS to fill in implementation-defined details.
688     */
689     tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
690     CS_CHECK(GetFirstTuple, handle, &tuple);
691     while (1) {
692         cistpl_cftable_entry_t dflt = { 0 };
693         cistpl_cftable_entry_t *cfg = &(parse.cftable_entry);
694         CFG_CHECK(GetTupleData, handle, &tuple);
695         CFG_CHECK(ParseTuple, handle, &tuple, &parse);
696
697         if (cfg->flags & CISTPL_CFTABLE_DEFAULT) dflt = *cfg;
698         if (cfg->index == 0) goto next_entry;
699         link->conf.ConfigIndex = cfg->index;
700         
701         /* Use power settings for Vcc and Vpp if present */
702         /*  Note that the CIS values need to be rescaled */
703         if (cfg->vcc.present & (1<<CISTPL_POWER_VNOM)) {
704             if (conf.Vcc != cfg->vcc.param[CISTPL_POWER_VNOM]/10000)
705                 goto next_entry;
706         } else if (dflt.vcc.present & (1<<CISTPL_POWER_VNOM)) {
707             if (conf.Vcc != dflt.vcc.param[CISTPL_POWER_VNOM]/10000)
708                 goto next_entry;
709         }
710             
711         if (cfg->vpp1.present & (1<<CISTPL_POWER_VNOM))
712             link->conf.Vpp1 = link->conf.Vpp2 =
713                 cfg->vpp1.param[CISTPL_POWER_VNOM]/10000;
714         else if (dflt.vpp1.present & (1<<CISTPL_POWER_VNOM))
715             link->conf.Vpp1 = link->conf.Vpp2 =
716                 dflt.vpp1.param[CISTPL_POWER_VNOM]/10000;
717         
718         /* Do we need to allocate an interrupt? */
719         if (cfg->irq.IRQInfo1 || dflt.irq.IRQInfo1)
720             link->conf.Attributes |= CONF_ENABLE_IRQ;
721         
722         /* IO window settings */
723         link->io.NumPorts1 = link->io.NumPorts2 = 0;
724         if ((cfg->io.nwin > 0) || (dflt.io.nwin > 0)) {
725             cistpl_io_t *io = (cfg->io.nwin) ? &cfg->io : &dflt.io;
726             link->io.Attributes1 = IO_DATA_PATH_WIDTH_AUTO;
727             if (!(io->flags & CISTPL_IO_8BIT))
728                 link->io.Attributes1 = IO_DATA_PATH_WIDTH_16;
729             if (!(io->flags & CISTPL_IO_16BIT))
730                 link->io.Attributes1 = IO_DATA_PATH_WIDTH_8;
731             link->io.IOAddrLines = io->flags & CISTPL_IO_LINES_MASK;
732             link->io.BasePort1 = io->win[0].base;
733             link->io.NumPorts1 = io->win[0].len;
734             if (io->nwin > 1) {
735                 link->io.Attributes2 = link->io.Attributes1;
736                 link->io.BasePort2 = io->win[1].base;
737                 link->io.NumPorts2 = io->win[1].len;
738             }
739         }
740
741         /* This reserves IO space but doesn't actually enable it */
742         CFG_CHECK(RequestIO, link->handle, &link->io);
743
744         /* If we got this far, we're cool! */
745         break;
746         
747     next_entry:
748         CS_CHECK(GetNextTuple, handle, &tuple);
749     }
750     
751     /*
752        Allocate an interrupt line.  Note that this does not assign a
753        handler to the interrupt, unless the 'Handler' member of the
754        irq structure is initialized.
755     */
756     if (link->conf.Attributes & CONF_ENABLE_IRQ)
757         CS_CHECK(RequestIRQ, link->handle, &link->irq);
758         
759     /*
760        This actually configures the PCMCIA socket -- setting up
761        the I/O windows and the interrupt mapping, and putting the
762        card and host interface into "Memory and IO" mode.
763     */
764     CS_CHECK(RequestConfiguration, link->handle, &link->conf);
765
766     /*
767       At this point, the dev_node_t structure(s) need to be
768       initialized and arranged in a linked list at link->dev.
769     */
770     sprintf(dev->node.dev_name, "daqp%d", dev->table_index);
771     dev->node.major = dev->node.minor = 0;
772     link->dev = &dev->node;
773
774     /* Finally, report what we've done */
775     printk(KERN_INFO "%s: index 0x%02x: Vcc %d.%d",
776            dev->node.dev_name, link->conf.ConfigIndex,
777            link->conf.Vcc/10, link->conf.Vcc%10);
778     if (link->conf.Vpp1)
779         printk(", Vpp %d.%d", link->conf.Vpp1/10, link->conf.Vpp1%10);
780     if (link->conf.Attributes & CONF_ENABLE_IRQ)
781         printk(", irq %d", link->irq.AssignedIRQ);
782     if (link->io.NumPorts1)
783         printk(", io 0x%04x-0x%04x", link->io.BasePort1,
784                link->io.BasePort1+link->io.NumPorts1-1);
785     if (link->io.NumPorts2)
786         printk(" & 0x%04x-0x%04x", link->io.BasePort2,
787                link->io.BasePort2+link->io.NumPorts2-1);
788     printk("\n");
789     
790     link->state &= ~DEV_CONFIG_PENDING;
791     return;
792
793 cs_failed:
794     cs_error(link->handle, last_fn, last_ret);
795     daqp_cs_release((u_long)link);
796
797 } /* daqp_cs_config */
798
799 /*======================================================================
800
801     After a card is removed, daqp_cs_release() will unregister the
802     device, and release the PCMCIA configuration.  If the device is
803     still open, this will be postponed until it is closed.
804     
805 ======================================================================*/
806
807 static void daqp_cs_release(u_long arg)
808 {
809     dev_link_t *link = (dev_link_t *)arg;
810
811     DEBUG(0, "daqp_cs_release(0x%p)\n", link);
812
813     /*
814        If the device is currently in use, we won't release until it
815        is actually closed, because until then, we can't be sure that
816        no one will try to access the device or its data structures.
817     */
818     if (link->open) {
819         DEBUG(1, "daqp_cs: release postponed, '%s' still open\n",
820               link->dev->dev_name);
821         link->state |= DEV_STALE_CONFIG;
822         return;
823     }
824
825     /* Unlink the device chain */
826     link->dev = NULL;
827
828     /*
829       In a normal driver, additional code may be needed to release
830       other kernel data structures associated with this device. 
831     */
832     
833     /* Don't bother checking to see if these succeed or not */
834
835     CardServices(ReleaseConfiguration, link->handle);
836     if (link->io.NumPorts1)
837         CardServices(ReleaseIO, link->handle, &link->io);
838     if (link->irq.AssignedIRQ)
839         CardServices(ReleaseIRQ, link->handle, &link->irq);
840     link->state &= ~DEV_CONFIG;
841     
842     if (link->state & DEV_STALE_LINK)
843         daqp_cs_detach(link);
844     
845 } /* daqp_cs_release */
846
847 /*======================================================================
848
849     The card status event handler.  Mostly, this schedules other
850     stuff to run after an event is received.
851
852     When a CARD_REMOVAL event is received, we immediately set a
853     private flag to block future accesses to this device.  All the
854     functions that actually access the device should check this flag
855     to make sure the card is still present.
856     
857 ======================================================================*/
858
859 static int daqp_cs_event(event_t event, int priority,
860                        event_callback_args_t *args)
861 {
862     dev_link_t *link = args->client_data;
863     local_info_t *dev = link->priv;
864     
865     DEBUG(1, "daqp_cs_event(0x%06x)\n", event);
866     
867     switch (event) {
868     case CS_EVENT_CARD_REMOVAL:
869         link->state &= ~DEV_PRESENT;
870         if (link->state & DEV_CONFIG) {
871             dev->stop = 1;
872             link->release.expires = jiffies + HZ/20;
873             add_timer(&link->release);
874         }
875         break;
876     case CS_EVENT_CARD_INSERTION:
877         link->state |= DEV_PRESENT | DEV_CONFIG_PENDING;
878         daqp_cs_config(link);
879         break;
880     case CS_EVENT_PM_SUSPEND:
881         link->state |= DEV_SUSPEND;
882         /* Fall through... */
883     case CS_EVENT_RESET_PHYSICAL:
884         /* Mark the device as stopped, to block IO until later */
885         dev->stop = 1;
886         if (link->state & DEV_CONFIG)
887             CardServices(ReleaseConfiguration, link->handle);
888         break;
889     case CS_EVENT_PM_RESUME:
890         link->state &= ~DEV_SUSPEND;
891         /* Fall through... */
892     case CS_EVENT_CARD_RESET:
893         if (link->state & DEV_CONFIG)
894             CardServices(RequestConfiguration, link->handle, &link->conf);
895         dev->stop = 0;
896         break;
897     }
898     return 0;
899 } /* daqp_cs_event */
900
901 /*====================================================================*/
902
903 #ifdef MODULE
904
905 int init_module(void)
906 {
907     servinfo_t serv;
908     DEBUG(0, "%s\n", version);
909     CardServices(GetCardServicesInfo, &serv);
910     if (serv.Revision != CS_RELEASE_CODE) {
911         printk(KERN_NOTICE "daqp_cs: Card Services release "
912                "does not match!\n");
913         return -1;
914     }
915     register_pccard_driver(&dev_info, &daqp_cs_attach, &daqp_cs_detach);
916     comedi_driver_register(&driver_daqp);
917     return 0;
918 }
919
920 void cleanup_module(void)
921 {
922     int i;
923
924     DEBUG(0, "daqp_cs: unloading\n");
925     comedi_driver_unregister(&driver_daqp);
926     unregister_pccard_driver(&dev_info);
927     for (i=0; i < MAX_DEV; i++) {
928       if (dev_table[i]) {
929         if (dev_table[i]->link.state & DEV_CONFIG) {
930           daqp_cs_release((u_long)(&dev_table[i]->link));
931         }
932         daqp_cs_detach(&dev_table[i]->link);
933       }
934     }
935 }
936
937 #endif