Merge branch 'docs-next' of git://git.lwn.net/linux-2.6
[pandora-kernel.git] / drivers / staging / comedi / drivers / quatech_daqp_cs.c
1 /*======================================================================
2
3     comedi/drivers/quatech_daqp_cs.c
4
5     Quatech DAQP PCMCIA data capture cards COMEDI client driver
6     Copyright (C) 2000, 2003 Brent Baccala <baccala@freesoft.org>
7     The DAQP interface code in this file is released into the public domain.
8
9     COMEDI - Linux Control and Measurement Device Interface
10     Copyright (C) 1998 David A. Schleef <ds@schleef.org>
11     http://www.comedi.org/
12
13     quatech_daqp_cs.c 1.10
14
15     Documentation for the DAQP PCMCIA cards can be found on Quatech's site:
16
17                 ftp://ftp.quatech.com/Manuals/daqp-208.pdf
18
19     This manual is for both the DAQP-208 and the DAQP-308.
20
21     What works:
22
23         - A/D conversion
24             - 8 channels
25             - 4 gain ranges
26             - ground ref or differential
27             - single-shot and timed both supported
28         - D/A conversion, single-shot
29         - digital I/O
30
31     What doesn't:
32
33         - any kind of triggering - external or D/A channel 1
34         - the card's optional expansion board
35         - the card's timer (for anything other than A/D conversion)
36         - D/A update modes other than immediate (i.e, timed)
37         - fancier timing modes
38         - setting card's FIFO buffer thresholds to anything but default
39
40 ======================================================================*/
41
42 /*
43 Driver: quatech_daqp_cs
44 Description: Quatech DAQP PCMCIA data capture cards
45 Author: Brent Baccala <baccala@freesoft.org>
46 Status: works
47 Devices: [Quatech] DAQP-208 (daqp), DAQP-308
48 */
49
50 #include "../comedidev.h"
51
52 #include <pcmcia/cs_types.h>
53 #include <pcmcia/cs.h>
54 #include <pcmcia/cistpl.h>
55 #include <pcmcia/cisreg.h>
56 #include <pcmcia/ds.h>
57
58 /* Maximum number of separate DAQP devices we'll allow */
59 #define MAX_DEV         4
60
61 struct local_info_t {
62         struct pcmcia_device *link;
63         int stop;
64         int table_index;
65         char board_name[32];
66
67         enum { semaphore, buffer } interrupt_mode;
68
69         struct semaphore eos;
70
71         struct comedi_device *dev;
72         struct comedi_subdevice *s;
73         int count;
74 };
75
76 /* A list of "instances" of the device. */
77
78 static struct local_info_t *dev_table[MAX_DEV] = { NULL, /* ... */  };
79
80 /* The DAQP communicates with the system through a 16 byte I/O window. */
81
82 #define DAQP_FIFO_SIZE          4096
83
84 #define DAQP_FIFO               0
85 #define DAQP_SCANLIST           1
86 #define DAQP_CONTROL            2
87 #define DAQP_STATUS             2
88 #define DAQP_DIGITAL_IO         3
89 #define DAQP_PACER_LOW          4
90 #define DAQP_PACER_MID          5
91 #define DAQP_PACER_HIGH         6
92 #define DAQP_COMMAND            7
93 #define DAQP_DA                 8
94 #define DAQP_TIMER              10
95 #define DAQP_AUX                15
96
97 #define DAQP_SCANLIST_DIFFERENTIAL      0x4000
98 #define DAQP_SCANLIST_GAIN(x)           ((x)<<12)
99 #define DAQP_SCANLIST_CHANNEL(x)        ((x)<<8)
100 #define DAQP_SCANLIST_START             0x0080
101 #define DAQP_SCANLIST_EXT_GAIN(x)       ((x)<<4)
102 #define DAQP_SCANLIST_EXT_CHANNEL(x)    (x)
103
104 #define DAQP_CONTROL_PACER_100kHz       0xc0
105 #define DAQP_CONTROL_PACER_1MHz         0x80
106 #define DAQP_CONTROL_PACER_5MHz         0x40
107 #define DAQP_CONTROL_PACER_EXTERNAL     0x00
108 #define DAQP_CONTORL_EXPANSION          0x20
109 #define DAQP_CONTROL_EOS_INT_ENABLE     0x10
110 #define DAQP_CONTROL_FIFO_INT_ENABLE    0x08
111 #define DAQP_CONTROL_TRIGGER_ONESHOT    0x00
112 #define DAQP_CONTROL_TRIGGER_CONTINUOUS 0x04
113 #define DAQP_CONTROL_TRIGGER_INTERNAL   0x00
114 #define DAQP_CONTROL_TRIGGER_EXTERNAL   0x02
115 #define DAQP_CONTROL_TRIGGER_RISING     0x00
116 #define DAQP_CONTROL_TRIGGER_FALLING    0x01
117
118 #define DAQP_STATUS_IDLE                0x80
119 #define DAQP_STATUS_RUNNING             0x40
120 #define DAQP_STATUS_EVENTS              0x38
121 #define DAQP_STATUS_DATA_LOST           0x20
122 #define DAQP_STATUS_END_OF_SCAN         0x10
123 #define DAQP_STATUS_FIFO_THRESHOLD      0x08
124 #define DAQP_STATUS_FIFO_FULL           0x04
125 #define DAQP_STATUS_FIFO_NEARFULL       0x02
126 #define DAQP_STATUS_FIFO_EMPTY          0x01
127
128 #define DAQP_COMMAND_ARM                0x80
129 #define DAQP_COMMAND_RSTF               0x40
130 #define DAQP_COMMAND_RSTQ               0x20
131 #define DAQP_COMMAND_STOP               0x10
132 #define DAQP_COMMAND_LATCH              0x08
133 #define DAQP_COMMAND_100kHz             0x00
134 #define DAQP_COMMAND_50kHz              0x02
135 #define DAQP_COMMAND_25kHz              0x04
136 #define DAQP_COMMAND_FIFO_DATA          0x01
137 #define DAQP_COMMAND_FIFO_PROGRAM       0x00
138
139 #define DAQP_AUX_TRIGGER_TTL            0x00
140 #define DAQP_AUX_TRIGGER_ANALOG         0x80
141 #define DAQP_AUX_TRIGGER_PRETRIGGER     0x40
142 #define DAQP_AUX_TIMER_INT_ENABLE       0x20
143 #define DAQP_AUX_TIMER_RELOAD           0x00
144 #define DAQP_AUX_TIMER_PAUSE            0x08
145 #define DAQP_AUX_TIMER_GO               0x10
146 #define DAQP_AUX_TIMER_GO_EXTERNAL      0x18
147 #define DAQP_AUX_TIMER_EXTERNAL_SRC     0x04
148 #define DAQP_AUX_TIMER_INTERNAL_SRC     0x00
149 #define DAQP_AUX_DA_DIRECT              0x00
150 #define DAQP_AUX_DA_OVERFLOW            0x01
151 #define DAQP_AUX_DA_EXTERNAL            0x02
152 #define DAQP_AUX_DA_PACER               0x03
153
154 #define DAQP_AUX_RUNNING                0x80
155 #define DAQP_AUX_TRIGGERED              0x40
156 #define DAQP_AUX_DA_BUFFER              0x20
157 #define DAQP_AUX_TIMER_OVERFLOW         0x10
158 #define DAQP_AUX_CONVERSION             0x08
159 #define DAQP_AUX_DATA_LOST              0x04
160 #define DAQP_AUX_FIFO_NEARFULL          0x02
161 #define DAQP_AUX_FIFO_EMPTY             0x01
162
163 /* These range structures tell COMEDI how the sample values map to
164  * voltages.  The A/D converter has four        .ranges = +/- 10V through
165  * +/- 1.25V, and the D/A converter has only    .one = +/- 5V.
166  */
167
168 static const struct comedi_lrange range_daqp_ai = { 4, {
169                                                         BIP_RANGE(10),
170                                                         BIP_RANGE(5),
171                                                         BIP_RANGE(2.5),
172                                                         BIP_RANGE(1.25)
173                                                         }
174 };
175
176 static const struct comedi_lrange range_daqp_ao = { 1, {BIP_RANGE(5)} };
177
178 /*====================================================================*/
179
180 /* comedi interface code */
181
182 static int daqp_attach(struct comedi_device *dev, struct comedi_devconfig *it);
183 static int daqp_detach(struct comedi_device *dev);
184 static struct comedi_driver driver_daqp = {
185         .driver_name = "quatech_daqp_cs",
186         .module = THIS_MODULE,
187         .attach = daqp_attach,
188         .detach = daqp_detach,
189 };
190
191 #ifdef DAQP_DEBUG
192
193 static void daqp_dump(struct comedi_device *dev)
194 {
195         printk("DAQP: status %02x; aux status %02x\n",
196                inb(dev->iobase + DAQP_STATUS), inb(dev->iobase + DAQP_AUX));
197 }
198
199 static void hex_dump(char *str, void *ptr, int len)
200 {
201         unsigned char *cptr = ptr;
202         int i;
203
204         printk(str);
205
206         for (i = 0; i < len; i++) {
207                 if (i % 16 == 0) {
208                         printk("\n0x%08x:", (unsigned int)cptr);
209                 }
210                 printk(" %02x", *(cptr++));
211         }
212         printk("\n");
213 }
214
215 #endif
216
217 /* Cancel a running acquisition */
218
219 static int daqp_ai_cancel(struct comedi_device *dev, struct comedi_subdevice *s)
220 {
221         struct local_info_t *local = (struct local_info_t *)s->private;
222
223         if (local->stop) {
224                 return -EIO;
225         }
226
227         outb(DAQP_COMMAND_STOP, dev->iobase + DAQP_COMMAND);
228
229         /* flush any linguring data in FIFO - superfluous here */
230         /* outb(DAQP_COMMAND_RSTF, dev->iobase+DAQP_COMMAND); */
231
232         local->interrupt_mode = semaphore;
233
234         return 0;
235 }
236
237 /* Interrupt handler
238  *
239  * Operates in one of two modes.  If local->interrupt_mode is
240  * 'semaphore', just signal the local->eos semaphore and return
241  * (one-shot mode).  Otherwise (continuous mode), read data in from
242  * the card, transfer it to the buffer provided by the higher-level
243  * comedi kernel module, and signal various comedi callback routines,
244  * which run pretty quick.
245  */
246
247 static void daqp_interrupt(int irq, void *dev_id)
248 {
249         struct local_info_t *local = (struct local_info_t *)dev_id;
250         struct comedi_device *dev;
251         struct comedi_subdevice *s;
252         int loop_limit = 10000;
253         int status;
254
255         if (local == NULL) {
256                 printk(KERN_WARNING
257                        "daqp_interrupt(): irq %d for unknown device.\n", irq);
258                 return;
259         }
260
261         dev = local->dev;
262         if (dev == NULL) {
263                 printk(KERN_WARNING "daqp_interrupt(): NULL comedi_device.\n");
264                 return;
265         }
266
267         if (!dev->attached) {
268                 printk(KERN_WARNING
269                        "daqp_interrupt(): struct comedi_device not yet attached.\n");
270                 return;
271         }
272
273         s = local->s;
274         if (s == NULL) {
275                 printk(KERN_WARNING
276                        "daqp_interrupt(): NULL comedi_subdevice.\n");
277                 return;
278         }
279
280         if ((struct local_info_t *)s->private != local) {
281                 printk(KERN_WARNING
282                        "daqp_interrupt(): invalid comedi_subdevice.\n");
283                 return;
284         }
285
286         switch (local->interrupt_mode) {
287
288         case semaphore:
289
290                 up(&local->eos);
291                 break;
292
293         case buffer:
294
295                 while (!((status = inb(dev->iobase + DAQP_STATUS))
296                          & DAQP_STATUS_FIFO_EMPTY)) {
297
298                         short data;
299
300                         if (status & DAQP_STATUS_DATA_LOST) {
301                                 s->async->events |=
302                                     COMEDI_CB_EOA | COMEDI_CB_OVERFLOW;
303                                 printk("daqp: data lost\n");
304                                 daqp_ai_cancel(dev, s);
305                                 break;
306                         }
307
308                         data = inb(dev->iobase + DAQP_FIFO);
309                         data |= inb(dev->iobase + DAQP_FIFO) << 8;
310                         data ^= 0x8000;
311
312                         comedi_buf_put(s->async, data);
313
314                         /* If there's a limit, decrement it
315                          * and stop conversion if zero
316                          */
317
318                         if (local->count > 0) {
319                                 local->count--;
320                                 if (local->count == 0) {
321                                         daqp_ai_cancel(dev, s);
322                                         s->async->events |= COMEDI_CB_EOA;
323                                         break;
324                                 }
325                         }
326
327                         if ((loop_limit--) <= 0)
328                                 break;
329                 }
330
331                 if (loop_limit <= 0) {
332                         printk(KERN_WARNING
333                                "loop_limit reached in daqp_interrupt()\n");
334                         daqp_ai_cancel(dev, s);
335                         s->async->events |= COMEDI_CB_EOA | COMEDI_CB_ERROR;
336                 }
337
338                 s->async->events |= COMEDI_CB_BLOCK;
339
340                 comedi_event(dev, s);
341         }
342 }
343
344 /* One-shot analog data acquisition routine */
345
346 static int daqp_ai_insn_read(struct comedi_device *dev,
347                              struct comedi_subdevice *s,
348                              struct comedi_insn *insn, unsigned int *data)
349 {
350         struct local_info_t *local = (struct local_info_t *)s->private;
351         int i;
352         int v;
353         int counter = 10000;
354
355         if (local->stop) {
356                 return -EIO;
357         }
358
359         /* Stop any running conversion */
360         daqp_ai_cancel(dev, s);
361
362         outb(0, dev->iobase + DAQP_AUX);
363
364         /* Reset scan list queue */
365         outb(DAQP_COMMAND_RSTQ, dev->iobase + DAQP_COMMAND);
366
367         /* Program one scan list entry */
368
369         v = DAQP_SCANLIST_CHANNEL(CR_CHAN(insn->chanspec))
370             | DAQP_SCANLIST_GAIN(CR_RANGE(insn->chanspec));
371
372         if (CR_AREF(insn->chanspec) == AREF_DIFF) {
373                 v |= DAQP_SCANLIST_DIFFERENTIAL;
374         }
375
376         v |= DAQP_SCANLIST_START;
377
378         outb(v & 0xff, dev->iobase + DAQP_SCANLIST);
379         outb(v >> 8, dev->iobase + DAQP_SCANLIST);
380
381         /* Reset data FIFO (see page 28 of DAQP User's Manual) */
382
383         outb(DAQP_COMMAND_RSTF, dev->iobase + DAQP_COMMAND);
384
385         /* Set trigger */
386
387         v = DAQP_CONTROL_TRIGGER_ONESHOT | DAQP_CONTROL_TRIGGER_INTERNAL
388             | DAQP_CONTROL_PACER_100kHz | DAQP_CONTROL_EOS_INT_ENABLE;
389
390         outb(v, dev->iobase + DAQP_CONTROL);
391
392         /* Reset any pending interrupts (my card has a tendancy to require
393          * require multiple reads on the status register to achieve this)
394          */
395
396         while (--counter
397                && (inb(dev->iobase + DAQP_STATUS) & DAQP_STATUS_EVENTS)) ;
398         if (!counter) {
399                 printk("daqp: couldn't clear interrupts in status register\n");
400                 return -1;
401         }
402
403         /* Make sure semaphore is blocked */
404         sema_init(&local->eos, 0);
405         local->interrupt_mode = semaphore;
406         local->dev = dev;
407         local->s = s;
408
409         for (i = 0; i < insn->n; i++) {
410
411                 /* Start conversion */
412                 outb(DAQP_COMMAND_ARM | DAQP_COMMAND_FIFO_DATA,
413                      dev->iobase + DAQP_COMMAND);
414
415                 /* Wait for interrupt service routine to unblock semaphore */
416                 /* Maybe could use a timeout here, but it's interruptible */
417                 if (down_interruptible(&local->eos))
418                         return -EINTR;
419
420                 data[i] = inb(dev->iobase + DAQP_FIFO);
421                 data[i] |= inb(dev->iobase + DAQP_FIFO) << 8;
422                 data[i] ^= 0x8000;
423         }
424
425         return insn->n;
426 }
427
428 /* This function converts ns nanoseconds to a counter value suitable
429  * for programming the device.  We always use the DAQP's 5 MHz clock,
430  * which with its 24-bit counter, allows values up to 84 seconds.
431  * Also, the function adjusts ns so that it cooresponds to the actual
432  * time that the device will use.
433  */
434
435 static int daqp_ns_to_timer(unsigned int *ns, int round)
436 {
437         int timer;
438
439         timer = *ns / 200;
440         *ns = timer * 200;
441
442         return timer;
443 }
444
445 /* cmdtest tests a particular command to see if it is valid.
446  * Using the cmdtest ioctl, a user can create a valid cmd
447  * and then have it executed by the cmd ioctl.
448  *
449  * cmdtest returns 1,2,3,4 or 0, depending on which tests
450  * the command passes.
451  */
452
453 static int daqp_ai_cmdtest(struct comedi_device *dev,
454                            struct comedi_subdevice *s, struct comedi_cmd *cmd)
455 {
456         int err = 0;
457         int tmp;
458
459         /* step 1: make sure trigger sources are trivially valid */
460
461         tmp = cmd->start_src;
462         cmd->start_src &= TRIG_NOW;
463         if (!cmd->start_src || tmp != cmd->start_src)
464                 err++;
465
466         tmp = cmd->scan_begin_src;
467         cmd->scan_begin_src &= TRIG_TIMER | TRIG_FOLLOW;
468         if (!cmd->scan_begin_src || tmp != cmd->scan_begin_src)
469                 err++;
470
471         tmp = cmd->convert_src;
472         cmd->convert_src &= TRIG_TIMER | TRIG_NOW;
473         if (!cmd->convert_src || tmp != cmd->convert_src)
474                 err++;
475
476         tmp = cmd->scan_end_src;
477         cmd->scan_end_src &= TRIG_COUNT;
478         if (!cmd->scan_end_src || tmp != cmd->scan_end_src)
479                 err++;
480
481         tmp = cmd->stop_src;
482         cmd->stop_src &= TRIG_COUNT | TRIG_NONE;
483         if (!cmd->stop_src || tmp != cmd->stop_src)
484                 err++;
485
486         if (err)
487                 return 1;
488
489         /* step 2: make sure trigger sources are unique and mutually compatible */
490
491         /* note that mutual compatibility is not an issue here */
492         if (cmd->scan_begin_src != TRIG_TIMER &&
493             cmd->scan_begin_src != TRIG_FOLLOW)
494                 err++;
495         if (cmd->convert_src != TRIG_NOW && cmd->convert_src != TRIG_TIMER)
496                 err++;
497         if (cmd->scan_begin_src == TRIG_FOLLOW && cmd->convert_src == TRIG_NOW)
498                 err++;
499         if (cmd->stop_src != TRIG_COUNT && cmd->stop_src != TRIG_NONE)
500                 err++;
501
502         if (err)
503                 return 2;
504
505         /* step 3: make sure arguments are trivially compatible */
506
507         if (cmd->start_arg != 0) {
508                 cmd->start_arg = 0;
509                 err++;
510         }
511 #define MAX_SPEED       10000   /* 100 kHz - in nanoseconds */
512
513         if (cmd->scan_begin_src == TRIG_TIMER
514             && cmd->scan_begin_arg < MAX_SPEED) {
515                 cmd->scan_begin_arg = MAX_SPEED;
516                 err++;
517         }
518
519         /* If both scan_begin and convert are both timer values, the only
520          * way that can make sense is if the scan time is the number of
521          * conversions times the convert time
522          */
523
524         if (cmd->scan_begin_src == TRIG_TIMER && cmd->convert_src == TRIG_TIMER
525             && cmd->scan_begin_arg != cmd->convert_arg * cmd->scan_end_arg) {
526                 err++;
527         }
528
529         if (cmd->convert_src == TRIG_TIMER && cmd->convert_arg < MAX_SPEED) {
530                 cmd->convert_arg = MAX_SPEED;
531                 err++;
532         }
533
534         if (cmd->scan_end_arg != cmd->chanlist_len) {
535                 cmd->scan_end_arg = cmd->chanlist_len;
536                 err++;
537         }
538         if (cmd->stop_src == TRIG_COUNT) {
539                 if (cmd->stop_arg > 0x00ffffff) {
540                         cmd->stop_arg = 0x00ffffff;
541                         err++;
542                 }
543         } else {
544                 /* TRIG_NONE */
545                 if (cmd->stop_arg != 0) {
546                         cmd->stop_arg = 0;
547                         err++;
548                 }
549         }
550
551         if (err)
552                 return 3;
553
554         /* step 4: fix up any arguments */
555
556         if (cmd->scan_begin_src == TRIG_TIMER) {
557                 tmp = cmd->scan_begin_arg;
558                 daqp_ns_to_timer(&cmd->scan_begin_arg,
559                                  cmd->flags & TRIG_ROUND_MASK);
560                 if (tmp != cmd->scan_begin_arg)
561                         err++;
562         }
563
564         if (cmd->convert_src == TRIG_TIMER) {
565                 tmp = cmd->convert_arg;
566                 daqp_ns_to_timer(&cmd->convert_arg,
567                                  cmd->flags & TRIG_ROUND_MASK);
568                 if (tmp != cmd->convert_arg)
569                         err++;
570         }
571
572         if (err)
573                 return 4;
574
575         return 0;
576 }
577
578 static int daqp_ai_cmd(struct comedi_device *dev, struct comedi_subdevice *s)
579 {
580         struct local_info_t *local = (struct local_info_t *)s->private;
581         struct comedi_cmd *cmd = &s->async->cmd;
582         int counter = 100;
583         int scanlist_start_on_every_entry;
584         int threshold;
585
586         int i;
587         int v;
588
589         if (local->stop) {
590                 return -EIO;
591         }
592
593         /* Stop any running conversion */
594         daqp_ai_cancel(dev, s);
595
596         outb(0, dev->iobase + DAQP_AUX);
597
598         /* Reset scan list queue */
599         outb(DAQP_COMMAND_RSTQ, dev->iobase + DAQP_COMMAND);
600
601         /* Program pacer clock
602          *
603          * There's two modes we can operate in.  If convert_src is
604          * TRIG_TIMER, then convert_arg specifies the time between
605          * each conversion, so we program the pacer clock to that
606          * frequency and set the SCANLIST_START bit on every scanlist
607          * entry.  Otherwise, convert_src is TRIG_NOW, which means
608          * we want the fastest possible conversions, scan_begin_src
609          * is TRIG_TIMER, and scan_begin_arg specifies the time between
610          * each scan, so we program the pacer clock to this frequency
611          * and only set the SCANLIST_START bit on the first entry.
612          */
613
614         if (cmd->convert_src == TRIG_TIMER) {
615                 int counter = daqp_ns_to_timer(&cmd->convert_arg,
616                                                cmd->flags & TRIG_ROUND_MASK);
617                 outb(counter & 0xff, dev->iobase + DAQP_PACER_LOW);
618                 outb((counter >> 8) & 0xff, dev->iobase + DAQP_PACER_MID);
619                 outb((counter >> 16) & 0xff, dev->iobase + DAQP_PACER_HIGH);
620                 scanlist_start_on_every_entry = 1;
621         } else {
622                 int counter = daqp_ns_to_timer(&cmd->scan_begin_arg,
623                                                cmd->flags & TRIG_ROUND_MASK);
624                 outb(counter & 0xff, dev->iobase + DAQP_PACER_LOW);
625                 outb((counter >> 8) & 0xff, dev->iobase + DAQP_PACER_MID);
626                 outb((counter >> 16) & 0xff, dev->iobase + DAQP_PACER_HIGH);
627                 scanlist_start_on_every_entry = 0;
628         }
629
630         /* Program scan list */
631
632         for (i = 0; i < cmd->chanlist_len; i++) {
633
634                 int chanspec = cmd->chanlist[i];
635
636                 /* Program one scan list entry */
637
638                 v = DAQP_SCANLIST_CHANNEL(CR_CHAN(chanspec))
639                     | DAQP_SCANLIST_GAIN(CR_RANGE(chanspec));
640
641                 if (CR_AREF(chanspec) == AREF_DIFF) {
642                         v |= DAQP_SCANLIST_DIFFERENTIAL;
643                 }
644
645                 if (i == 0 || scanlist_start_on_every_entry) {
646                         v |= DAQP_SCANLIST_START;
647                 }
648
649                 outb(v & 0xff, dev->iobase + DAQP_SCANLIST);
650                 outb(v >> 8, dev->iobase + DAQP_SCANLIST);
651         }
652
653         /* Now it's time to program the FIFO threshold, basically the
654          * number of samples the card will buffer before it interrupts
655          * the CPU.
656          *
657          * If we don't have a stop count, then use half the size of
658          * the FIFO (the manufacturer's recommendation).  Consider
659          * that the FIFO can hold 2K samples (4K bytes).  With the
660          * threshold set at half the FIFO size, we have a margin of
661          * error of 1024 samples.  At the chip's maximum sample rate
662          * of 100,000 Hz, the CPU would have to delay interrupt
663          * service for a full 10 milliseconds in order to lose data
664          * here (as opposed to higher up in the kernel).  I've never
665          * seen it happen.  However, for slow sample rates it may
666          * buffer too much data and introduce too much delay for the
667          * user application.
668          *
669          * If we have a stop count, then things get more interesting.
670          * If the stop count is less than the FIFO size (actually
671          * three-quarters of the FIFO size - see below), we just use
672          * the stop count itself as the threshold, the card interrupts
673          * us when that many samples have been taken, and we kill the
674          * acquisition at that point and are done.  If the stop count
675          * is larger than that, then we divide it by 2 until it's less
676          * than three quarters of the FIFO size (we always leave the
677          * top quarter of the FIFO as protection against sluggish CPU
678          * interrupt response) and use that as the threshold.  So, if
679          * the stop count is 4000 samples, we divide by two twice to
680          * get 1000 samples, use that as the threshold, take four
681          * interrupts to get our 4000 samples and are done.
682          *
683          * The algorithm could be more clever.  For example, if 81000
684          * samples are requested, we could set the threshold to 1500
685          * samples and take 54 interrupts to get 81000.  But 54 isn't
686          * a power of two, so this algorithm won't find that option.
687          * Instead, it'll set the threshold at 1266 and take 64
688          * interrupts to get 81024 samples, of which the last 24 will
689          * be discarded... but we won't get the last interrupt until
690          * they've been collected.  To find the first option, the
691          * computer could look at the prime decomposition of the
692          * sample count (81000 = 3^4 * 5^3 * 2^3) and factor it into a
693          * threshold (1500 = 3 * 5^3 * 2^2) and an interrupt count (54
694          * = 3^3 * 2).  Hmmm... a one-line while loop or prime
695          * decomposition of integers... I'll leave it the way it is.
696          *
697          * I'll also note a mini-race condition before ignoring it in
698          * the code.  Let's say we're taking 4000 samples, as before.
699          * After 1000 samples, we get an interrupt.  But before that
700          * interrupt is completely serviced, another sample is taken
701          * and loaded into the FIFO.  Since the interrupt handler
702          * empties the FIFO before returning, it will read 1001 samples.
703          * If that happens four times, we'll end up taking 4004 samples,
704          * not 4000.  The interrupt handler will discard the extra four
705          * samples (by halting the acquisition with four samples still
706          * in the FIFO), but we will have to wait for them.
707          *
708          * In short, this code works pretty well, but for either of
709          * the two reasons noted, might end up waiting for a few more
710          * samples than actually requested.  Shouldn't make too much
711          * of a difference.
712          */
713
714         /* Save away the number of conversions we should perform, and
715          * compute the FIFO threshold (in bytes, not samples - that's
716          * why we multiple local->count by 2 = sizeof(sample))
717          */
718
719         if (cmd->stop_src == TRIG_COUNT) {
720                 local->count = cmd->stop_arg * cmd->scan_end_arg;
721                 threshold = 2 * local->count;
722                 while (threshold > DAQP_FIFO_SIZE * 3 / 4)
723                         threshold /= 2;
724         } else {
725                 local->count = -1;
726                 threshold = DAQP_FIFO_SIZE / 2;
727         }
728
729         /* Reset data FIFO (see page 28 of DAQP User's Manual) */
730
731         outb(DAQP_COMMAND_RSTF, dev->iobase + DAQP_COMMAND);
732
733         /* Set FIFO threshold.  First two bytes are near-empty
734          * threshold, which is unused; next two bytes are near-full
735          * threshold.  We computed the number of bytes we want in the
736          * FIFO when the interrupt is generated, what the card wants
737          * is actually the number of available bytes left in the FIFO
738          * when the interrupt is to happen.
739          */
740
741         outb(0x00, dev->iobase + DAQP_FIFO);
742         outb(0x00, dev->iobase + DAQP_FIFO);
743
744         outb((DAQP_FIFO_SIZE - threshold) & 0xff, dev->iobase + DAQP_FIFO);
745         outb((DAQP_FIFO_SIZE - threshold) >> 8, dev->iobase + DAQP_FIFO);
746
747         /* Set trigger */
748
749         v = DAQP_CONTROL_TRIGGER_CONTINUOUS | DAQP_CONTROL_TRIGGER_INTERNAL
750             | DAQP_CONTROL_PACER_5MHz | DAQP_CONTROL_FIFO_INT_ENABLE;
751
752         outb(v, dev->iobase + DAQP_CONTROL);
753
754         /* Reset any pending interrupts (my card has a tendancy to require
755          * require multiple reads on the status register to achieve this)
756          */
757
758         while (--counter
759                && (inb(dev->iobase + DAQP_STATUS) & DAQP_STATUS_EVENTS)) ;
760         if (!counter) {
761                 printk("daqp: couldn't clear interrupts in status register\n");
762                 return -1;
763         }
764
765         local->interrupt_mode = buffer;
766         local->dev = dev;
767         local->s = s;
768
769         /* Start conversion */
770         outb(DAQP_COMMAND_ARM | DAQP_COMMAND_FIFO_DATA,
771              dev->iobase + DAQP_COMMAND);
772
773         return 0;
774 }
775
776 /* Single-shot analog output routine */
777
778 static int daqp_ao_insn_write(struct comedi_device *dev,
779                               struct comedi_subdevice *s,
780                               struct comedi_insn *insn, unsigned int *data)
781 {
782         struct local_info_t *local = (struct local_info_t *)s->private;
783         int d;
784         unsigned int chan;
785
786         if (local->stop) {
787                 return -EIO;
788         }
789
790         chan = CR_CHAN(insn->chanspec);
791         d = data[0];
792         d &= 0x0fff;
793         d ^= 0x0800;            /* Flip the sign */
794         d |= chan << 12;
795
796         /* Make sure D/A update mode is direct update */
797         outb(0, dev->iobase + DAQP_AUX);
798
799         outw(d, dev->iobase + DAQP_DA);
800
801         return 1;
802 }
803
804 /* Digital input routine */
805
806 static int daqp_di_insn_read(struct comedi_device *dev,
807                              struct comedi_subdevice *s,
808                              struct comedi_insn *insn, unsigned int *data)
809 {
810         struct local_info_t *local = (struct local_info_t *)s->private;
811
812         if (local->stop) {
813                 return -EIO;
814         }
815
816         data[0] = inb(dev->iobase + DAQP_DIGITAL_IO);
817
818         return 1;
819 }
820
821 /* Digital output routine */
822
823 static int daqp_do_insn_write(struct comedi_device *dev,
824                               struct comedi_subdevice *s,
825                               struct comedi_insn *insn, unsigned int *data)
826 {
827         struct local_info_t *local = (struct local_info_t *)s->private;
828
829         if (local->stop) {
830                 return -EIO;
831         }
832
833         outw(data[0] & 0xf, dev->iobase + DAQP_DIGITAL_IO);
834
835         return 1;
836 }
837
838 /* daqp_attach is called via comedi_config to attach a comedi device
839  * to a /dev/comedi*.  Note that this is different from daqp_cs_attach()
840  * which is called by the pcmcia subsystem to attach the PCMCIA card
841  * when it is inserted.
842  */
843
844 static int daqp_attach(struct comedi_device *dev, struct comedi_devconfig *it)
845 {
846         int ret;
847         struct local_info_t *local = dev_table[it->options[0]];
848         struct comedi_subdevice *s;
849
850         if (it->options[0] < 0 || it->options[0] >= MAX_DEV || !local) {
851                 printk("comedi%d: No such daqp device %d\n",
852                        dev->minor, it->options[0]);
853                 return -EIO;
854         }
855
856         /* Typically brittle code that I don't completely understand,
857          * but "it works on my card".  The intent is to pull the model
858          * number of the card out the PCMCIA CIS and stash it away as
859          * the COMEDI board_name.  Looks like the third field in
860          * CISTPL_VERS_1 (offset 2) holds what we're looking for.  If
861          * it doesn't work, who cares, just leave it as "DAQP".
862          */
863
864         strcpy(local->board_name, "DAQP");
865         dev->board_name = local->board_name;
866         if (local->link->prod_id[2]) {
867                 if (strncmp(local->link->prod_id[2], "DAQP", 4) == 0) {
868                         strncpy(local->board_name, local->link->prod_id[2],
869                                 sizeof(local->board_name));
870                 }
871         }
872
873         dev->iobase = local->link->io.BasePort1;
874
875         ret = alloc_subdevices(dev, 4);
876         if (ret < 0)
877                 return ret;
878
879         printk("comedi%d: attaching daqp%d (io 0x%04lx)\n",
880                dev->minor, it->options[0], dev->iobase);
881
882         s = dev->subdevices + 0;
883         dev->read_subdev = s;
884         s->private = local;
885         s->type = COMEDI_SUBD_AI;
886         s->subdev_flags = SDF_READABLE | SDF_GROUND | SDF_DIFF | SDF_CMD_READ;
887         s->n_chan = 8;
888         s->len_chanlist = 2048;
889         s->maxdata = 0xffff;
890         s->range_table = &range_daqp_ai;
891         s->insn_read = daqp_ai_insn_read;
892         s->do_cmdtest = daqp_ai_cmdtest;
893         s->do_cmd = daqp_ai_cmd;
894         s->cancel = daqp_ai_cancel;
895
896         s = dev->subdevices + 1;
897         dev->write_subdev = s;
898         s->private = local;
899         s->type = COMEDI_SUBD_AO;
900         s->subdev_flags = SDF_WRITEABLE;
901         s->n_chan = 2;
902         s->len_chanlist = 1;
903         s->maxdata = 0x0fff;
904         s->range_table = &range_daqp_ao;
905         s->insn_write = daqp_ao_insn_write;
906
907         s = dev->subdevices + 2;
908         s->private = local;
909         s->type = COMEDI_SUBD_DI;
910         s->subdev_flags = SDF_READABLE;
911         s->n_chan = 1;
912         s->len_chanlist = 1;
913         s->insn_read = daqp_di_insn_read;
914
915         s = dev->subdevices + 3;
916         s->private = local;
917         s->type = COMEDI_SUBD_DO;
918         s->subdev_flags = SDF_WRITEABLE;
919         s->n_chan = 1;
920         s->len_chanlist = 1;
921         s->insn_write = daqp_do_insn_write;
922
923         return 1;
924 }
925
926 /* daqp_detach (called from comedi_comdig) does nothing. If the PCMCIA
927  * card is removed, daqp_cs_detach() is called by the pcmcia subsystem.
928  */
929
930 static int daqp_detach(struct comedi_device *dev)
931 {
932         printk("comedi%d: detaching daqp\n", dev->minor);
933
934         return 0;
935 }
936
937 /*====================================================================
938
939     PCMCIA interface code
940
941     The rest of the code in this file is based on dummy_cs.c v1.24
942     from the Linux pcmcia_cs distribution v3.1.8 and is subject
943     to the following license agreement.
944
945     The remaining contents of this file are subject to the Mozilla Public
946     License Version 1.1 (the "License"); you may not use this file
947     except in compliance with the License. You may obtain a copy of
948     the License at http://www.mozilla.org/MPL/
949
950     Software distributed under the License is distributed on an "AS
951     IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
952     implied. See the License for the specific language governing
953     rights and limitations under the License.
954
955     The initial developer of the original code is David A. Hinds
956     <dhinds@pcmcia.sourceforge.org>.  Portions created by David A. Hinds
957     are Copyright (C) 1999 David A. Hinds.  All Rights Reserved.
958
959     Alternatively, the contents of this file may be used under the
960     terms of the GNU Public License version 2 (the "GPL"), in which
961     case the provisions of the GPL are applicable instead of the
962     above.  If you wish to allow the use of your version of this file
963     only under the terms of the GPL and not to allow others to use
964     your version of this file under the MPL, indicate your decision
965     by deleting the provisions above and replace them with the notice
966     and other provisions required by the GPL.  If you do not delete
967     the provisions above, a recipient may use your version of this
968     file under either the MPL or the GPL.
969
970 ======================================================================*/
971
972 /*
973    The event() function is this driver's Card Services event handler.
974    It will be called by Card Services when an appropriate card status
975    event is received.  The config() and release() entry points are
976    used to configure or release a socket, in response to card
977    insertion and ejection events.
978
979    Kernel version 2.6.16 upwards uses suspend() and resume() functions
980    instead of an event() function.
981 */
982
983 static void daqp_cs_config(struct pcmcia_device *link);
984 static void daqp_cs_release(struct pcmcia_device *link);
985 static int daqp_cs_suspend(struct pcmcia_device *p_dev);
986 static int daqp_cs_resume(struct pcmcia_device *p_dev);
987
988 /*
989    The attach() and detach() entry points are used to create and destroy
990    "instances" of the driver, where each instance represents everything
991    needed to manage one actual PCMCIA card.
992 */
993
994 static int daqp_cs_attach(struct pcmcia_device *);
995 static void daqp_cs_detach(struct pcmcia_device *);
996
997 /*
998    The dev_info variable is the "key" that is used to match up this
999    device driver with appropriate cards, through the card configuration
1000    database.
1001 */
1002
1003 static const dev_info_t dev_info = "quatech_daqp_cs";
1004
1005 /*======================================================================
1006
1007     daqp_cs_attach() creates an "instance" of the driver, allocating
1008     local data structures for one device.  The device is registered
1009     with Card Services.
1010
1011     The dev_link structure is initialized, but we don't actually
1012     configure the card at this point -- we wait until we receive a
1013     card insertion event.
1014
1015 ======================================================================*/
1016
1017 static int daqp_cs_attach(struct pcmcia_device *link)
1018 {
1019         struct local_info_t *local;
1020         int i;
1021
1022         dev_dbg(&link->dev, "daqp_cs_attach()\n");
1023
1024         for (i = 0; i < MAX_DEV; i++)
1025                 if (dev_table[i] == NULL)
1026                         break;
1027         if (i == MAX_DEV) {
1028                 printk(KERN_NOTICE "daqp_cs: no devices available\n");
1029                 return -ENODEV;
1030         }
1031
1032         /* Allocate space for private device-specific data */
1033         local = kzalloc(sizeof(struct local_info_t), GFP_KERNEL);
1034         if (!local)
1035                 return -ENOMEM;
1036
1037         local->table_index = i;
1038         dev_table[i] = local;
1039         local->link = link;
1040         link->priv = local;
1041
1042         /*
1043            General socket configuration defaults can go here.  In this
1044            client, we assume very little, and rely on the CIS for almost
1045            everything.  In most clients, many details (i.e., number, sizes,
1046            and attributes of IO windows) are fixed by the nature of the
1047            device, and can be hard-wired here.
1048          */
1049         link->conf.Attributes = 0;
1050         link->conf.IntType = INT_MEMORY_AND_IO;
1051
1052         daqp_cs_config(link);
1053
1054         return 0;
1055 }                               /* daqp_cs_attach */
1056
1057 /*======================================================================
1058
1059     This deletes a driver "instance".  The device is de-registered
1060     with Card Services.  If it has been released, all local data
1061     structures are freed.  Otherwise, the structures will be freed
1062     when the device is released.
1063
1064 ======================================================================*/
1065
1066 static void daqp_cs_detach(struct pcmcia_device *link)
1067 {
1068         struct local_info_t *dev = link->priv;
1069
1070         dev_dbg(&link->dev, "daqp_cs_detach\n");
1071
1072         dev->stop = 1;
1073         daqp_cs_release(link);
1074
1075         /* Unlink device structure, and free it */
1076         dev_table[dev->table_index] = NULL;
1077         if (dev)
1078                 kfree(dev);
1079
1080 }                               /* daqp_cs_detach */
1081
1082 /*======================================================================
1083
1084     daqp_cs_config() is scheduled to run after a CARD_INSERTION event
1085     is received, to configure the PCMCIA socket, and to make the
1086     device available to the system.
1087
1088 ======================================================================*/
1089
1090
1091 static int daqp_pcmcia_config_loop(struct pcmcia_device *p_dev,
1092                                 cistpl_cftable_entry_t *cfg,
1093                                 cistpl_cftable_entry_t *dflt,
1094                                 unsigned int vcc,
1095                                 void *priv_data)
1096 {
1097         if (cfg->index == 0)
1098                 return -ENODEV;
1099
1100         /* Do we need to allocate an interrupt? */
1101         p_dev->conf.Attributes |= CONF_ENABLE_IRQ;
1102
1103         /* IO window settings */
1104         p_dev->io.NumPorts1 = p_dev->io.NumPorts2 = 0;
1105         if ((cfg->io.nwin > 0) || (dflt->io.nwin > 0)) {
1106                 cistpl_io_t *io = (cfg->io.nwin) ? &cfg->io : &dflt->io;
1107                 p_dev->io.Attributes1 = IO_DATA_PATH_WIDTH_AUTO;
1108                 if (!(io->flags & CISTPL_IO_8BIT))
1109                         p_dev->io.Attributes1 = IO_DATA_PATH_WIDTH_16;
1110                 if (!(io->flags & CISTPL_IO_16BIT))
1111                         p_dev->io.Attributes1 = IO_DATA_PATH_WIDTH_8;
1112                 p_dev->io.IOAddrLines = io->flags & CISTPL_IO_LINES_MASK;
1113                 p_dev->io.BasePort1 = io->win[0].base;
1114                 p_dev->io.NumPorts1 = io->win[0].len;
1115                 if (io->nwin > 1) {
1116                         p_dev->io.Attributes2 = p_dev->io.Attributes1;
1117                         p_dev->io.BasePort2 = io->win[1].base;
1118                         p_dev->io.NumPorts2 = io->win[1].len;
1119                 }
1120         }
1121
1122         /* This reserves IO space but doesn't actually enable it */
1123         return pcmcia_request_io(p_dev, &p_dev->io);
1124 }
1125
1126 static void daqp_cs_config(struct pcmcia_device *link)
1127 {
1128         int ret;
1129
1130         dev_dbg(&link->dev, "daqp_cs_config\n");
1131
1132         ret = pcmcia_loop_config(link, daqp_pcmcia_config_loop, NULL);
1133         if (ret) {
1134                 dev_warn(&link->dev, "no configuration found\n");
1135                 goto failed;
1136         }
1137
1138         ret = pcmcia_request_irq(link, daqp_interrupt);
1139         if (ret)
1140                 goto failed;
1141
1142         /*
1143            This actually configures the PCMCIA socket -- setting up
1144            the I/O windows and the interrupt mapping, and putting the
1145            card and host interface into "Memory and IO" mode.
1146          */
1147         ret = pcmcia_request_configuration(link, &link->conf);
1148         if (ret)
1149                 goto failed;
1150
1151         /* Finally, report what we've done */
1152         dev_info(&link->dev, "index 0x%02x", link->conf.ConfigIndex);
1153         if (link->conf.Attributes & CONF_ENABLE_IRQ)
1154                 printk(", irq %u", link->irq);
1155         if (link->io.NumPorts1)
1156                 printk(", io 0x%04x-0x%04x", link->io.BasePort1,
1157                        link->io.BasePort1 + link->io.NumPorts1 - 1);
1158         if (link->io.NumPorts2)
1159                 printk(" & 0x%04x-0x%04x", link->io.BasePort2,
1160                        link->io.BasePort2 + link->io.NumPorts2 - 1);
1161         printk("\n");
1162
1163         return;
1164
1165 failed:
1166         daqp_cs_release(link);
1167
1168 }                               /* daqp_cs_config */
1169
1170 static void daqp_cs_release(struct pcmcia_device *link)
1171 {
1172         dev_dbg(&link->dev, "daqp_cs_release\n");
1173
1174         pcmcia_disable_device(link);
1175 }                               /* daqp_cs_release */
1176
1177 /*======================================================================
1178
1179     The card status event handler.  Mostly, this schedules other
1180     stuff to run after an event is received.
1181
1182     When a CARD_REMOVAL event is received, we immediately set a
1183     private flag to block future accesses to this device.  All the
1184     functions that actually access the device should check this flag
1185     to make sure the card is still present.
1186
1187 ======================================================================*/
1188
1189 static int daqp_cs_suspend(struct pcmcia_device *link)
1190 {
1191         struct local_info_t *local = link->priv;
1192
1193         /* Mark the device as stopped, to block IO until later */
1194         local->stop = 1;
1195         return 0;
1196 }
1197
1198 static int daqp_cs_resume(struct pcmcia_device *link)
1199 {
1200         struct local_info_t *local = link->priv;
1201
1202         local->stop = 0;
1203
1204         return 0;
1205 }
1206
1207 /*====================================================================*/
1208
1209 #ifdef MODULE
1210
1211 static struct pcmcia_device_id daqp_cs_id_table[] = {
1212         PCMCIA_DEVICE_MANF_CARD(0x0137, 0x0027),
1213         PCMCIA_DEVICE_NULL
1214 };
1215
1216 MODULE_DEVICE_TABLE(pcmcia, daqp_cs_id_table);
1217
1218 struct pcmcia_driver daqp_cs_driver = {
1219         .probe = daqp_cs_attach,
1220         .remove = daqp_cs_detach,
1221         .suspend = daqp_cs_suspend,
1222         .resume = daqp_cs_resume,
1223         .id_table = daqp_cs_id_table,
1224         .owner = THIS_MODULE,
1225         .drv = {
1226                 .name = dev_info,
1227                 },
1228 };
1229
1230 int __init init_module(void)
1231 {
1232         pcmcia_register_driver(&daqp_cs_driver);
1233         comedi_driver_register(&driver_daqp);
1234         return 0;
1235 }
1236
1237 void __exit cleanup_module(void)
1238 {
1239         comedi_driver_unregister(&driver_daqp);
1240         pcmcia_unregister_driver(&daqp_cs_driver);
1241 }
1242
1243 #endif