Merge branch 'release' of git://git.kernel.org/pub/scm/linux/kernel/git/lenb/linux...
[pandora-kernel.git] / drivers / char / pcmcia / cm4000_cs.c
1  /*
2   * A driver for the PCMCIA Smartcard Reader "Omnikey CardMan Mobile 4000"
3   *
4   * cm4000_cs.c support.linux@omnikey.com
5   *
6   * Tue Oct 23 11:32:43 GMT 2001 herp - cleaned up header files
7   * Sun Jan 20 10:11:15 MET 2002 herp - added modversion header files
8   * Thu Nov 14 16:34:11 GMT 2002 mh   - added PPS functionality
9   * Tue Nov 19 16:36:27 GMT 2002 mh   - added SUSPEND/RESUME functionailty
10   * Wed Jul 28 12:55:01 CEST 2004 mh  - kernel 2.6 adjustments
11   *
12   * current version: 2.4.0gm4
13   *
14   * (C) 2000,2001,2002,2003,2004 Omnikey AG
15   *
16   * (C) 2005-2006 Harald Welte <laforge@gnumonks.org>
17   *     - Adhere to Kernel CodingStyle
18   *     - Port to 2.6.13 "new" style PCMCIA
19   *     - Check for copy_{from,to}_user return values
20   *     - Use nonseekable_open()
21   *     - add class interface for udev device creation
22   *
23   * All rights reserved. Licensed under dual BSD/GPL license.
24   */
25
26 /* #define PCMCIA_DEBUG 6 */
27
28 #include <linux/kernel.h>
29 #include <linux/module.h>
30 #include <linux/slab.h>
31 #include <linux/init.h>
32 #include <linux/fs.h>
33 #include <linux/delay.h>
34 #include <asm/uaccess.h>
35 #include <asm/io.h>
36
37 #include <pcmcia/cs_types.h>
38 #include <pcmcia/cs.h>
39 #include <pcmcia/cistpl.h>
40 #include <pcmcia/cisreg.h>
41 #include <pcmcia/ciscode.h>
42 #include <pcmcia/ds.h>
43
44 #include <linux/cm4000_cs.h>
45
46 /* #define ATR_CSUM */
47
48 #ifdef PCMCIA_DEBUG
49 #define reader_to_dev(x)        (&handle_to_dev(x->p_dev->handle))
50 static int pc_debug = PCMCIA_DEBUG;
51 module_param(pc_debug, int, 0600);
52 #define DEBUGP(n, rdr, x, args...) do {                                 \
53         if (pc_debug >= (n))                                            \
54                 dev_printk(KERN_DEBUG, reader_to_dev(rdr), "%s:" x,     \
55                            __FUNCTION__ , ## args);                     \
56         } while (0)
57 #else
58 #define DEBUGP(n, rdr, x, args...)
59 #endif
60 static char *version = "cm4000_cs.c v2.4.0gm6 - All bugs added by Harald Welte";
61
62 #define T_1SEC          (HZ)
63 #define T_10MSEC        msecs_to_jiffies(10)
64 #define T_20MSEC        msecs_to_jiffies(20)
65 #define T_40MSEC        msecs_to_jiffies(40)
66 #define T_50MSEC        msecs_to_jiffies(50)
67 #define T_100MSEC       msecs_to_jiffies(100)
68 #define T_500MSEC       msecs_to_jiffies(500)
69
70 static void cm4000_release(struct pcmcia_device *link);
71
72 static int major;               /* major number we get from the kernel */
73
74 /* note: the first state has to have number 0 always */
75
76 #define M_FETCH_ATR     0
77 #define M_TIMEOUT_WAIT  1
78 #define M_READ_ATR_LEN  2
79 #define M_READ_ATR      3
80 #define M_ATR_PRESENT   4
81 #define M_BAD_CARD      5
82 #define M_CARDOFF       6
83
84 #define LOCK_IO                 0
85 #define LOCK_MONITOR            1
86
87 #define IS_AUTOPPS_ACT           6
88 #define IS_PROCBYTE_PRESENT      7
89 #define IS_INVREV                8
90 #define IS_ANY_T0                9
91 #define IS_ANY_T1               10
92 #define IS_ATR_PRESENT          11
93 #define IS_ATR_VALID            12
94 #define IS_CMM_ABSENT           13
95 #define IS_BAD_LENGTH           14
96 #define IS_BAD_CSUM             15
97 #define IS_BAD_CARD             16
98
99 #define REG_FLAGS0(x)           (x + 0)
100 #define REG_FLAGS1(x)           (x + 1)
101 #define REG_NUM_BYTES(x)        (x + 2)
102 #define REG_BUF_ADDR(x)         (x + 3)
103 #define REG_BUF_DATA(x)         (x + 4)
104 #define REG_NUM_SEND(x)         (x + 5)
105 #define REG_BAUDRATE(x)         (x + 6)
106 #define REG_STOPBITS(x)         (x + 7)
107
108 struct cm4000_dev {
109         struct pcmcia_device *p_dev;
110         dev_node_t node;                /* OS node (major,minor) */
111
112         unsigned char atr[MAX_ATR];
113         unsigned char rbuf[512];
114         unsigned char sbuf[512];
115
116         wait_queue_head_t devq;         /* when removing cardman must not be
117                                            zeroed! */
118
119         wait_queue_head_t ioq;          /* if IO is locked, wait on this Q */
120         wait_queue_head_t atrq;         /* wait for ATR valid */
121         wait_queue_head_t readq;        /* used by write to wake blk.read */
122
123         /* warning: do not move this fields.
124          * initialising to zero depends on it - see ZERO_DEV below.  */
125         unsigned char atr_csum;
126         unsigned char atr_len_retry;
127         unsigned short atr_len;
128         unsigned short rlen;    /* bytes avail. after write */
129         unsigned short rpos;    /* latest read pos. write zeroes */
130         unsigned char procbyte; /* T=0 procedure byte */
131         unsigned char mstate;   /* state of card monitor */
132         unsigned char cwarn;    /* slow down warning */
133         unsigned char flags0;   /* cardman IO-flags 0 */
134         unsigned char flags1;   /* cardman IO-flags 1 */
135         unsigned int mdelay;    /* variable monitor speeds, in jiffies */
136
137         unsigned int baudv;     /* baud value for speed */
138         unsigned char ta1;
139         unsigned char proto;    /* T=0, T=1, ... */
140         unsigned long flags;    /* lock+flags (MONITOR,IO,ATR) * for concurrent
141                                    access */
142
143         unsigned char pts[4];
144
145         struct timer_list timer;        /* used to keep monitor running */
146         int monitor_running;
147 };
148
149 #define ZERO_DEV(dev)                                           \
150         memset(&dev->atr_csum,0,                                \
151                 sizeof(struct cm4000_dev) -                     \
152                 offsetof(struct cm4000_dev, atr_csum))
153
154 static struct pcmcia_device *dev_table[CM4000_MAX_DEV];
155 static struct class *cmm_class;
156
157 /* This table doesn't use spaces after the comma between fields and thus
158  * violates CodingStyle.  However, I don't really think wrapping it around will
159  * make it any clearer to read -HW */
160 static unsigned char fi_di_table[10][14] = {
161 /*FI     00   01   02   03   04   05   06   07   08   09   10   11   12   13 */
162 /*DI */
163 /* 0 */ {0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11},
164 /* 1 */ {0x01,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x91,0x11,0x11,0x11,0x11},
165 /* 2 */ {0x02,0x12,0x22,0x32,0x11,0x11,0x11,0x11,0x11,0x92,0xA2,0xB2,0x11,0x11},
166 /* 3 */ {0x03,0x13,0x23,0x33,0x43,0x53,0x63,0x11,0x11,0x93,0xA3,0xB3,0xC3,0xD3},
167 /* 4 */ {0x04,0x14,0x24,0x34,0x44,0x54,0x64,0x11,0x11,0x94,0xA4,0xB4,0xC4,0xD4},
168 /* 5 */ {0x00,0x15,0x25,0x35,0x45,0x55,0x65,0x11,0x11,0x95,0xA5,0xB5,0xC5,0xD5},
169 /* 6 */ {0x06,0x16,0x26,0x36,0x46,0x56,0x66,0x11,0x11,0x96,0xA6,0xB6,0xC6,0xD6},
170 /* 7 */ {0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11,0x11},
171 /* 8 */ {0x08,0x11,0x28,0x38,0x48,0x58,0x68,0x11,0x11,0x98,0xA8,0xB8,0xC8,0xD8},
172 /* 9 */ {0x09,0x19,0x29,0x39,0x49,0x59,0x69,0x11,0x11,0x99,0xA9,0xB9,0xC9,0xD9}
173 };
174
175 #ifndef PCMCIA_DEBUG
176 #define xoutb   outb
177 #define xinb    inb
178 #else
179 static inline void xoutb(unsigned char val, unsigned short port)
180 {
181         if (pc_debug >= 7)
182                 printk(KERN_DEBUG "outb(val=%.2x,port=%.4x)\n", val, port);
183         outb(val, port);
184 }
185 static inline unsigned char xinb(unsigned short port)
186 {
187         unsigned char val;
188
189         val = inb(port);
190         if (pc_debug >= 7)
191                 printk(KERN_DEBUG "%.2x=inb(%.4x)\n", val, port);
192
193         return val;
194 }
195 #endif
196
197 #define b_0000  15
198 #define b_0001  14
199 #define b_0010  13
200 #define b_0011  12
201 #define b_0100  11
202 #define b_0101  10
203 #define b_0110  9
204 #define b_0111  8
205 #define b_1000  7
206 #define b_1001  6
207 #define b_1010  5
208 #define b_1011  4
209 #define b_1100  3
210 #define b_1101  2
211 #define b_1110  1
212 #define b_1111  0
213
214 static unsigned char irtab[16] = {
215         b_0000, b_1000, b_0100, b_1100,
216         b_0010, b_1010, b_0110, b_1110,
217         b_0001, b_1001, b_0101, b_1101,
218         b_0011, b_1011, b_0111, b_1111
219 };
220
221 static void str_invert_revert(unsigned char *b, int len)
222 {
223         int i;
224
225         for (i = 0; i < len; i++)
226                 b[i] = (irtab[b[i] & 0x0f] << 4) | irtab[b[i] >> 4];
227 }
228
229 static unsigned char invert_revert(unsigned char ch)
230 {
231         return (irtab[ch & 0x0f] << 4) | irtab[ch >> 4];
232 }
233
234 #define ATRLENCK(dev,pos) \
235         if (pos>=dev->atr_len || pos>=MAX_ATR) \
236                 goto return_0;
237
238 static unsigned int calc_baudv(unsigned char fidi)
239 {
240         unsigned int wcrcf, wbrcf, fi_rfu, di_rfu;
241
242         fi_rfu = 372;
243         di_rfu = 1;
244
245         /* FI */
246         switch ((fidi >> 4) & 0x0F) {
247         case 0x00:
248                 wcrcf = 372;
249                 break;
250         case 0x01:
251                 wcrcf = 372;
252                 break;
253         case 0x02:
254                 wcrcf = 558;
255                 break;
256         case 0x03:
257                 wcrcf = 744;
258                 break;
259         case 0x04:
260                 wcrcf = 1116;
261                 break;
262         case 0x05:
263                 wcrcf = 1488;
264                 break;
265         case 0x06:
266                 wcrcf = 1860;
267                 break;
268         case 0x07:
269                 wcrcf = fi_rfu;
270                 break;
271         case 0x08:
272                 wcrcf = fi_rfu;
273                 break;
274         case 0x09:
275                 wcrcf = 512;
276                 break;
277         case 0x0A:
278                 wcrcf = 768;
279                 break;
280         case 0x0B:
281                 wcrcf = 1024;
282                 break;
283         case 0x0C:
284                 wcrcf = 1536;
285                 break;
286         case 0x0D:
287                 wcrcf = 2048;
288                 break;
289         default:
290                 wcrcf = fi_rfu;
291                 break;
292         }
293
294         /* DI */
295         switch (fidi & 0x0F) {
296         case 0x00:
297                 wbrcf = di_rfu;
298                 break;
299         case 0x01:
300                 wbrcf = 1;
301                 break;
302         case 0x02:
303                 wbrcf = 2;
304                 break;
305         case 0x03:
306                 wbrcf = 4;
307                 break;
308         case 0x04:
309                 wbrcf = 8;
310                 break;
311         case 0x05:
312                 wbrcf = 16;
313                 break;
314         case 0x06:
315                 wbrcf = 32;
316                 break;
317         case 0x07:
318                 wbrcf = di_rfu;
319                 break;
320         case 0x08:
321                 wbrcf = 12;
322                 break;
323         case 0x09:
324                 wbrcf = 20;
325                 break;
326         default:
327                 wbrcf = di_rfu;
328                 break;
329         }
330
331         return (wcrcf / wbrcf);
332 }
333
334 static unsigned short io_read_num_rec_bytes(ioaddr_t iobase, unsigned short *s)
335 {
336         unsigned short tmp;
337
338         tmp = *s = 0;
339         do {
340                 *s = tmp;
341                 tmp = inb(REG_NUM_BYTES(iobase)) |
342                                 (inb(REG_FLAGS0(iobase)) & 4 ? 0x100 : 0);
343         } while (tmp != *s);
344
345         return *s;
346 }
347
348 static int parse_atr(struct cm4000_dev *dev)
349 {
350         unsigned char any_t1, any_t0;
351         unsigned char ch, ifno;
352         int ix, done;
353
354         DEBUGP(3, dev, "-> parse_atr: dev->atr_len = %i\n", dev->atr_len);
355
356         if (dev->atr_len < 3) {
357                 DEBUGP(5, dev, "parse_atr: atr_len < 3\n");
358                 return 0;
359         }
360
361         if (dev->atr[0] == 0x3f)
362                 set_bit(IS_INVREV, &dev->flags);
363         else
364                 clear_bit(IS_INVREV, &dev->flags);
365         ix = 1;
366         ifno = 1;
367         ch = dev->atr[1];
368         dev->proto = 0;         /* XXX PROTO */
369         any_t1 = any_t0 = done = 0;
370         dev->ta1 = 0x11;        /* defaults to 9600 baud */
371         do {
372                 if (ifno == 1 && (ch & 0x10)) {
373                         /* read first interface byte and TA1 is present */
374                         dev->ta1 = dev->atr[2];
375                         DEBUGP(5, dev, "Card says FiDi is 0x%.2x\n", dev->ta1);
376                         ifno++;
377                 } else if ((ifno == 2) && (ch & 0x10)) { /* TA(2) */
378                         dev->ta1 = 0x11;
379                         ifno++;
380                 }
381
382                 DEBUGP(5, dev, "Yi=%.2x\n", ch & 0xf0);
383                 ix += ((ch & 0x10) >> 4)        /* no of int.face chars */
384                     +((ch & 0x20) >> 5)
385                     + ((ch & 0x40) >> 6)
386                     + ((ch & 0x80) >> 7);
387                 /* ATRLENCK(dev,ix); */
388                 if (ch & 0x80) {        /* TDi */
389                         ch = dev->atr[ix];
390                         if ((ch & 0x0f)) {
391                                 any_t1 = 1;
392                                 DEBUGP(5, dev, "card is capable of T=1\n");
393                         } else {
394                                 any_t0 = 1;
395                                 DEBUGP(5, dev, "card is capable of T=0\n");
396                         }
397                 } else
398                         done = 1;
399         } while (!done);
400
401         DEBUGP(5, dev, "ix=%d noHist=%d any_t1=%d\n",
402               ix, dev->atr[1] & 15, any_t1);
403         if (ix + 1 + (dev->atr[1] & 0x0f) + any_t1 != dev->atr_len) {
404                 DEBUGP(5, dev, "length error\n");
405                 return 0;
406         }
407         if (any_t0)
408                 set_bit(IS_ANY_T0, &dev->flags);
409
410         if (any_t1) {           /* compute csum */
411                 dev->atr_csum = 0;
412 #ifdef ATR_CSUM
413                 for (i = 1; i < dev->atr_len; i++)
414                         dev->atr_csum ^= dev->atr[i];
415                 if (dev->atr_csum) {
416                         set_bit(IS_BAD_CSUM, &dev->flags);
417                         DEBUGP(5, dev, "bad checksum\n");
418                         goto return_0;
419                 }
420 #endif
421                 if (any_t0 == 0)
422                         dev->proto = 1; /* XXX PROTO */
423                 set_bit(IS_ANY_T1, &dev->flags);
424         }
425
426         return 1;
427 }
428
429 struct card_fixup {
430         char atr[12];
431         u_int8_t atr_len;
432         u_int8_t stopbits;
433 };
434
435 static struct card_fixup card_fixups[] = {
436         {       /* ACOS */
437                 .atr = { 0x3b, 0xb3, 0x11, 0x00, 0x00, 0x41, 0x01 },
438                 .atr_len = 7,
439                 .stopbits = 0x03,
440         },
441         {       /* Motorola */
442                 .atr = {0x3b, 0x76, 0x13, 0x00, 0x00, 0x80, 0x62, 0x07,
443                         0x41, 0x81, 0x81 },
444                 .atr_len = 11,
445                 .stopbits = 0x04,
446         },
447 };
448
449 static void set_cardparameter(struct cm4000_dev *dev)
450 {
451         int i;
452         ioaddr_t iobase = dev->p_dev->io.BasePort1;
453         u_int8_t stopbits = 0x02; /* ISO default */
454
455         DEBUGP(3, dev, "-> set_cardparameter\n");
456
457         dev->flags1 = dev->flags1 | (((dev->baudv - 1) & 0x0100) >> 8);
458         xoutb(dev->flags1, REG_FLAGS1(iobase));
459         DEBUGP(5, dev, "flags1 = 0x%02x\n", dev->flags1);
460
461         /* set baudrate */
462         xoutb((unsigned char)((dev->baudv - 1) & 0xFF), REG_BAUDRATE(iobase));
463
464         DEBUGP(5, dev, "baudv = %i -> write 0x%02x\n", dev->baudv,
465               ((dev->baudv - 1) & 0xFF));
466
467         /* set stopbits */
468         for (i = 0; i < ARRAY_SIZE(card_fixups); i++) {
469                 if (!memcmp(dev->atr, card_fixups[i].atr,
470                             card_fixups[i].atr_len))
471                         stopbits = card_fixups[i].stopbits;
472         }
473         xoutb(stopbits, REG_STOPBITS(iobase));
474
475         DEBUGP(3, dev, "<- set_cardparameter\n");
476 }
477
478 static int set_protocol(struct cm4000_dev *dev, struct ptsreq *ptsreq)
479 {
480
481         unsigned long tmp, i;
482         unsigned short num_bytes_read;
483         unsigned char pts_reply[4];
484         ssize_t rc;
485         ioaddr_t iobase = dev->p_dev->io.BasePort1;
486
487         rc = 0;
488
489         DEBUGP(3, dev, "-> set_protocol\n");
490         DEBUGP(5, dev, "ptsreq->Protocol = 0x%.8x, ptsreq->Flags=0x%.8x, "
491                  "ptsreq->pts1=0x%.2x, ptsreq->pts2=0x%.2x, "
492                  "ptsreq->pts3=0x%.2x\n", (unsigned int)ptsreq->protocol,
493                  (unsigned int)ptsreq->flags, ptsreq->pts1, ptsreq->pts2,
494                  ptsreq->pts3);
495
496         /* Fill PTS structure */
497         dev->pts[0] = 0xff;
498         dev->pts[1] = 0x00;
499         tmp = ptsreq->protocol;
500         while ((tmp = (tmp >> 1)) > 0)
501                 dev->pts[1]++;
502         dev->proto = dev->pts[1];       /* Set new protocol */
503         dev->pts[1] = (0x01 << 4) | (dev->pts[1]);
504
505         /* Correct Fi/Di according to CM4000 Fi/Di table */
506         DEBUGP(5, dev, "Ta(1) from ATR is 0x%.2x\n", dev->ta1);
507         /* set Fi/Di according to ATR TA(1) */
508         dev->pts[2] = fi_di_table[dev->ta1 & 0x0F][(dev->ta1 >> 4) & 0x0F];
509
510         /* Calculate PCK character */
511         dev->pts[3] = dev->pts[0] ^ dev->pts[1] ^ dev->pts[2];
512
513         DEBUGP(5, dev, "pts0=%.2x, pts1=%.2x, pts2=%.2x, pts3=%.2x\n",
514                dev->pts[0], dev->pts[1], dev->pts[2], dev->pts[3]);
515
516         /* check card convention */
517         if (test_bit(IS_INVREV, &dev->flags))
518                 str_invert_revert(dev->pts, 4);
519
520         /* reset SM */
521         xoutb(0x80, REG_FLAGS0(iobase));
522
523         /* Enable access to the message buffer */
524         DEBUGP(5, dev, "Enable access to the messages buffer\n");
525         dev->flags1 = 0x20      /* T_Active */
526             | (test_bit(IS_INVREV, &dev->flags) ? 0x02 : 0x00) /* inv parity */
527             | ((dev->baudv >> 8) & 0x01);       /* MSB-baud */
528         xoutb(dev->flags1, REG_FLAGS1(iobase));
529
530         DEBUGP(5, dev, "Enable message buffer -> flags1 = 0x%.2x\n",
531                dev->flags1);
532
533         /* write challenge to the buffer */
534         DEBUGP(5, dev, "Write challenge to buffer: ");
535         for (i = 0; i < 4; i++) {
536                 xoutb(i, REG_BUF_ADDR(iobase));
537                 xoutb(dev->pts[i], REG_BUF_DATA(iobase));       /* buf data */
538 #ifdef PCMCIA_DEBUG
539                 if (pc_debug >= 5)
540                         printk("0x%.2x ", dev->pts[i]);
541         }
542         if (pc_debug >= 5)
543                 printk("\n");
544 #else
545         }
546 #endif
547
548         /* set number of bytes to write */
549         DEBUGP(5, dev, "Set number of bytes to write\n");
550         xoutb(0x04, REG_NUM_SEND(iobase));
551
552         /* Trigger CARDMAN CONTROLLER */
553         xoutb(0x50, REG_FLAGS0(iobase));
554
555         /* Monitor progress */
556         /* wait for xmit done */
557         DEBUGP(5, dev, "Waiting for NumRecBytes getting valid\n");
558
559         for (i = 0; i < 100; i++) {
560                 if (inb(REG_FLAGS0(iobase)) & 0x08) {
561                         DEBUGP(5, dev, "NumRecBytes is valid\n");
562                         break;
563                 }
564                 mdelay(10);
565         }
566         if (i == 100) {
567                 DEBUGP(5, dev, "Timeout waiting for NumRecBytes getting "
568                        "valid\n");
569                 rc = -EIO;
570                 goto exit_setprotocol;
571         }
572
573         DEBUGP(5, dev, "Reading NumRecBytes\n");
574         for (i = 0; i < 100; i++) {
575                 io_read_num_rec_bytes(iobase, &num_bytes_read);
576                 if (num_bytes_read >= 4) {
577                         DEBUGP(2, dev, "NumRecBytes = %i\n", num_bytes_read);
578                         break;
579                 }
580                 mdelay(10);
581         }
582
583         /* check whether it is a short PTS reply? */
584         if (num_bytes_read == 3)
585                 i = 0;
586
587         if (i == 100) {
588                 DEBUGP(5, dev, "Timeout reading num_bytes_read\n");
589                 rc = -EIO;
590                 goto exit_setprotocol;
591         }
592
593         DEBUGP(5, dev, "Reset the CARDMAN CONTROLLER\n");
594         xoutb(0x80, REG_FLAGS0(iobase));
595
596         /* Read PPS reply */
597         DEBUGP(5, dev, "Read PPS reply\n");
598         for (i = 0; i < num_bytes_read; i++) {
599                 xoutb(i, REG_BUF_ADDR(iobase));
600                 pts_reply[i] = inb(REG_BUF_DATA(iobase));
601         }
602
603 #ifdef PCMCIA_DEBUG
604         DEBUGP(2, dev, "PTSreply: ");
605         for (i = 0; i < num_bytes_read; i++) {
606                 if (pc_debug >= 5)
607                         printk("0x%.2x ", pts_reply[i]);
608         }
609         printk("\n");
610 #endif  /* PCMCIA_DEBUG */
611
612         DEBUGP(5, dev, "Clear Tactive in Flags1\n");
613         xoutb(0x20, REG_FLAGS1(iobase));
614
615         /* Compare ptsreq and ptsreply */
616         if ((dev->pts[0] == pts_reply[0]) &&
617             (dev->pts[1] == pts_reply[1]) &&
618             (dev->pts[2] == pts_reply[2]) && (dev->pts[3] == pts_reply[3])) {
619                 /* setcardparameter according to PPS */
620                 dev->baudv = calc_baudv(dev->pts[2]);
621                 set_cardparameter(dev);
622         } else if ((dev->pts[0] == pts_reply[0]) &&
623                    ((dev->pts[1] & 0xef) == pts_reply[1]) &&
624                    ((pts_reply[0] ^ pts_reply[1]) == pts_reply[2])) {
625                 /* short PTS reply, set card parameter to default values */
626                 dev->baudv = calc_baudv(0x11);
627                 set_cardparameter(dev);
628         } else
629                 rc = -EIO;
630
631 exit_setprotocol:
632         DEBUGP(3, dev, "<- set_protocol\n");
633         return rc;
634 }
635
636 static int io_detect_cm4000(ioaddr_t iobase, struct cm4000_dev *dev)
637 {
638
639         /* note: statemachine is assumed to be reset */
640         if (inb(REG_FLAGS0(iobase)) & 8) {
641                 clear_bit(IS_ATR_VALID, &dev->flags);
642                 set_bit(IS_CMM_ABSENT, &dev->flags);
643                 return 0;       /* detect CMM = 1 -> failure */
644         }
645         /* xoutb(0x40, REG_FLAGS1(iobase)); detectCMM */
646         xoutb(dev->flags1 | 0x40, REG_FLAGS1(iobase));
647         if ((inb(REG_FLAGS0(iobase)) & 8) == 0) {
648                 clear_bit(IS_ATR_VALID, &dev->flags);
649                 set_bit(IS_CMM_ABSENT, &dev->flags);
650                 return 0;       /* detect CMM=0 -> failure */
651         }
652         /* clear detectCMM again by restoring original flags1 */
653         xoutb(dev->flags1, REG_FLAGS1(iobase));
654         return 1;
655 }
656
657 static void terminate_monitor(struct cm4000_dev *dev)
658 {
659
660         /* tell the monitor to stop and wait until
661          * it terminates.
662          */
663         DEBUGP(3, dev, "-> terminate_monitor\n");
664         wait_event_interruptible(dev->devq,
665                                  test_and_set_bit(LOCK_MONITOR,
666                                                   (void *)&dev->flags));
667
668         /* now, LOCK_MONITOR has been set.
669          * allow a last cycle in the monitor.
670          * the monitor will indicate that it has
671          * finished by clearing this bit.
672          */
673         DEBUGP(5, dev, "Now allow last cycle of monitor!\n");
674         while (test_bit(LOCK_MONITOR, (void *)&dev->flags))
675                 msleep(25);
676
677         DEBUGP(5, dev, "Delete timer\n");
678         del_timer_sync(&dev->timer);
679 #ifdef PCMCIA_DEBUG
680         dev->monitor_running = 0;
681 #endif
682
683         DEBUGP(3, dev, "<- terminate_monitor\n");
684 }
685
686 /*
687  * monitor the card every 50msec. as a side-effect, retrieve the
688  * atr once a card is inserted. another side-effect of retrieving the
689  * atr is that the card will be powered on, so there is no need to
690  * power on the card explictely from the application: the driver
691  * is already doing that for you.
692  */
693
694 static void monitor_card(unsigned long p)
695 {
696         struct cm4000_dev *dev = (struct cm4000_dev *) p;
697         ioaddr_t iobase = dev->p_dev->io.BasePort1;
698         unsigned short s;
699         struct ptsreq ptsreq;
700         int i, atrc;
701
702         DEBUGP(7, dev, "->  monitor_card\n");
703
704         /* if someone has set the lock for us: we're done! */
705         if (test_and_set_bit(LOCK_MONITOR, &dev->flags)) {
706                 DEBUGP(4, dev, "About to stop monitor\n");
707                 /* no */
708                 dev->rlen =
709                     dev->rpos =
710                     dev->atr_csum = dev->atr_len_retry = dev->cwarn = 0;
711                 dev->mstate = M_FETCH_ATR;
712                 clear_bit(LOCK_MONITOR, &dev->flags);
713                 /* close et al. are sleeping on devq, so wake it */
714                 wake_up_interruptible(&dev->devq);
715                 DEBUGP(2, dev, "<- monitor_card (we are done now)\n");
716                 return;
717         }
718
719         /* try to lock io: if it is already locked, just add another timer */
720         if (test_and_set_bit(LOCK_IO, (void *)&dev->flags)) {
721                 DEBUGP(4, dev, "Couldn't get IO lock\n");
722                 goto return_with_timer;
723         }
724
725         /* is a card/a reader inserted at all ? */
726         dev->flags0 = xinb(REG_FLAGS0(iobase));
727         DEBUGP(7, dev, "dev->flags0 = 0x%2x\n", dev->flags0);
728         DEBUGP(7, dev, "smartcard present: %s\n",
729                dev->flags0 & 1 ? "yes" : "no");
730         DEBUGP(7, dev, "cardman present: %s\n",
731                dev->flags0 == 0xff ? "no" : "yes");
732
733         if ((dev->flags0 & 1) == 0      /* no smartcard inserted */
734             || dev->flags0 == 0xff) {   /* no cardman inserted */
735                 /* no */
736                 dev->rlen =
737                     dev->rpos =
738                     dev->atr_csum = dev->atr_len_retry = dev->cwarn = 0;
739                 dev->mstate = M_FETCH_ATR;
740
741                 dev->flags &= 0x000000ff; /* only keep IO and MONITOR locks */
742
743                 if (dev->flags0 == 0xff) {
744                         DEBUGP(4, dev, "set IS_CMM_ABSENT bit\n");
745                         set_bit(IS_CMM_ABSENT, &dev->flags);
746                 } else if (test_bit(IS_CMM_ABSENT, &dev->flags)) {
747                         DEBUGP(4, dev, "clear IS_CMM_ABSENT bit "
748                                "(card is removed)\n");
749                         clear_bit(IS_CMM_ABSENT, &dev->flags);
750                 }
751
752                 goto release_io;
753         } else if ((dev->flags0 & 1) && test_bit(IS_CMM_ABSENT, &dev->flags)) {
754                 /* cardman and card present but cardman was absent before
755                  * (after suspend with inserted card) */
756                 DEBUGP(4, dev, "clear IS_CMM_ABSENT bit (card is inserted)\n");
757                 clear_bit(IS_CMM_ABSENT, &dev->flags);
758         }
759
760         if (test_bit(IS_ATR_VALID, &dev->flags) == 1) {
761                 DEBUGP(7, dev, "believe ATR is already valid (do nothing)\n");
762                 goto release_io;
763         }
764
765         switch (dev->mstate) {
766                 unsigned char flags0;
767         case M_CARDOFF:
768                 DEBUGP(4, dev, "M_CARDOFF\n");
769                 flags0 = inb(REG_FLAGS0(iobase));
770                 if (flags0 & 0x02) {
771                         /* wait until Flags0 indicate power is off */
772                         dev->mdelay = T_10MSEC;
773                 } else {
774                         /* Flags0 indicate power off and no card inserted now;
775                          * Reset CARDMAN CONTROLLER */
776                         xoutb(0x80, REG_FLAGS0(iobase));
777
778                         /* prepare for fetching ATR again: after card off ATR
779                          * is read again automatically */
780                         dev->rlen =
781                             dev->rpos =
782                             dev->atr_csum =
783                             dev->atr_len_retry = dev->cwarn = 0;
784                         dev->mstate = M_FETCH_ATR;
785
786                         /* minimal gap between CARDOFF and read ATR is 50msec */
787                         dev->mdelay = T_50MSEC;
788                 }
789                 break;
790         case M_FETCH_ATR:
791                 DEBUGP(4, dev, "M_FETCH_ATR\n");
792                 xoutb(0x80, REG_FLAGS0(iobase));
793                 DEBUGP(4, dev, "Reset BAUDV to 9600\n");
794                 dev->baudv = 0x173;     /* 9600 */
795                 xoutb(0x02, REG_STOPBITS(iobase));      /* stopbits=2 */
796                 xoutb(0x73, REG_BAUDRATE(iobase));      /* baud value */
797                 xoutb(0x21, REG_FLAGS1(iobase));        /* T_Active=1, baud
798                                                            value */
799                 /* warm start vs. power on: */
800                 xoutb(dev->flags0 & 2 ? 0x46 : 0x44, REG_FLAGS0(iobase));
801                 dev->mdelay = T_40MSEC;
802                 dev->mstate = M_TIMEOUT_WAIT;
803                 break;
804         case M_TIMEOUT_WAIT:
805                 DEBUGP(4, dev, "M_TIMEOUT_WAIT\n");
806                 /* numRecBytes */
807                 io_read_num_rec_bytes(iobase, &dev->atr_len);
808                 dev->mdelay = T_10MSEC;
809                 dev->mstate = M_READ_ATR_LEN;
810                 break;
811         case M_READ_ATR_LEN:
812                 DEBUGP(4, dev, "M_READ_ATR_LEN\n");
813                 /* infinite loop possible, since there is no timeout */
814
815 #define MAX_ATR_LEN_RETRY       100
816
817                 if (dev->atr_len == io_read_num_rec_bytes(iobase, &s)) {
818                         if (dev->atr_len_retry++ >= MAX_ATR_LEN_RETRY) {                                        /* + XX msec */
819                                 dev->mdelay = T_10MSEC;
820                                 dev->mstate = M_READ_ATR;
821                         }
822                 } else {
823                         dev->atr_len = s;
824                         dev->atr_len_retry = 0; /* set new timeout */
825                 }
826
827                 DEBUGP(4, dev, "Current ATR_LEN = %i\n", dev->atr_len);
828                 break;
829         case M_READ_ATR:
830                 DEBUGP(4, dev, "M_READ_ATR\n");
831                 xoutb(0x80, REG_FLAGS0(iobase));        /* reset SM */
832                 for (i = 0; i < dev->atr_len; i++) {
833                         xoutb(i, REG_BUF_ADDR(iobase));
834                         dev->atr[i] = inb(REG_BUF_DATA(iobase));
835                 }
836                 /* Deactivate T_Active flags */
837                 DEBUGP(4, dev, "Deactivate T_Active flags\n");
838                 dev->flags1 = 0x01;
839                 xoutb(dev->flags1, REG_FLAGS1(iobase));
840
841                 /* atr is present (which doesnt mean it's valid) */
842                 set_bit(IS_ATR_PRESENT, &dev->flags);
843                 if (dev->atr[0] == 0x03)
844                         str_invert_revert(dev->atr, dev->atr_len);
845                 atrc = parse_atr(dev);
846                 if (atrc == 0) {        /* atr invalid */
847                         dev->mdelay = 0;
848                         dev->mstate = M_BAD_CARD;
849                 } else {
850                         dev->mdelay = T_50MSEC;
851                         dev->mstate = M_ATR_PRESENT;
852                         set_bit(IS_ATR_VALID, &dev->flags);
853                 }
854
855                 if (test_bit(IS_ATR_VALID, &dev->flags) == 1) {
856                         DEBUGP(4, dev, "monitor_card: ATR valid\n");
857                         /* if ta1 == 0x11, no PPS necessary (default values) */
858                         /* do not do PPS with multi protocol cards */
859                         if ((test_bit(IS_AUTOPPS_ACT, &dev->flags) == 0) &&
860                             (dev->ta1 != 0x11) &&
861                             !(test_bit(IS_ANY_T0, &dev->flags) &&
862                             test_bit(IS_ANY_T1, &dev->flags))) {
863                                 DEBUGP(4, dev, "Perform AUTOPPS\n");
864                                 set_bit(IS_AUTOPPS_ACT, &dev->flags);
865                                 ptsreq.protocol = ptsreq.protocol =
866                                     (0x01 << dev->proto);
867                                 ptsreq.flags = 0x01;
868                                 ptsreq.pts1 = 0x00;
869                                 ptsreq.pts2 = 0x00;
870                                 ptsreq.pts3 = 0x00;
871                                 if (set_protocol(dev, &ptsreq) == 0) {
872                                         DEBUGP(4, dev, "AUTOPPS ret SUCC\n");
873                                         clear_bit(IS_AUTOPPS_ACT, &dev->flags);
874                                         wake_up_interruptible(&dev->atrq);
875                                 } else {
876                                         DEBUGP(4, dev, "AUTOPPS failed: "
877                                                "repower using defaults\n");
878                                         /* prepare for repowering  */
879                                         clear_bit(IS_ATR_PRESENT, &dev->flags);
880                                         clear_bit(IS_ATR_VALID, &dev->flags);
881                                         dev->rlen =
882                                             dev->rpos =
883                                             dev->atr_csum =
884                                             dev->atr_len_retry = dev->cwarn = 0;
885                                         dev->mstate = M_FETCH_ATR;
886
887                                         dev->mdelay = T_50MSEC;
888                                 }
889                         } else {
890                                 /* for cards which use slightly different
891                                  * params (extra guard time) */
892                                 set_cardparameter(dev);
893                                 if (test_bit(IS_AUTOPPS_ACT, &dev->flags) == 1)
894                                         DEBUGP(4, dev, "AUTOPPS already active "
895                                                "2nd try:use default values\n");
896                                 if (dev->ta1 == 0x11)
897                                         DEBUGP(4, dev, "No AUTOPPS necessary "
898                                                "TA(1)==0x11\n");
899                                 if (test_bit(IS_ANY_T0, &dev->flags)
900                                     && test_bit(IS_ANY_T1, &dev->flags))
901                                         DEBUGP(4, dev, "Do NOT perform AUTOPPS "
902                                                "with multiprotocol cards\n");
903                                 clear_bit(IS_AUTOPPS_ACT, &dev->flags);
904                                 wake_up_interruptible(&dev->atrq);
905                         }
906                 } else {
907                         DEBUGP(4, dev, "ATR invalid\n");
908                         wake_up_interruptible(&dev->atrq);
909                 }
910                 break;
911         case M_BAD_CARD:
912                 DEBUGP(4, dev, "M_BAD_CARD\n");
913                 /* slow down warning, but prompt immediately after insertion */
914                 if (dev->cwarn == 0 || dev->cwarn == 10) {
915                         set_bit(IS_BAD_CARD, &dev->flags);
916                         printk(KERN_WARNING MODULE_NAME ": device %s: ",
917                                dev->node.dev_name);
918                         if (test_bit(IS_BAD_CSUM, &dev->flags)) {
919                                 DEBUGP(4, dev, "ATR checksum (0x%.2x, should "
920                                        "be zero) failed\n", dev->atr_csum);
921                         }
922 #ifdef PCMCIA_DEBUG
923                         else if (test_bit(IS_BAD_LENGTH, &dev->flags)) {
924                                 DEBUGP(4, dev, "ATR length error\n");
925                         } else {
926                                 DEBUGP(4, dev, "card damaged or wrong way "
927                                         "inserted\n");
928                         }
929 #endif
930                         dev->cwarn = 0;
931                         wake_up_interruptible(&dev->atrq);      /* wake open */
932                 }
933                 dev->cwarn++;
934                 dev->mdelay = T_100MSEC;
935                 dev->mstate = M_FETCH_ATR;
936                 break;
937         default:
938                 DEBUGP(7, dev, "Unknown action\n");
939                 break;          /* nothing */
940         }
941
942 release_io:
943         DEBUGP(7, dev, "release_io\n");
944         clear_bit(LOCK_IO, &dev->flags);
945         wake_up_interruptible(&dev->ioq);       /* whoever needs IO */
946
947 return_with_timer:
948         DEBUGP(7, dev, "<- monitor_card (returns with timer)\n");
949         dev->timer.expires = jiffies + dev->mdelay;
950         add_timer(&dev->timer);
951         clear_bit(LOCK_MONITOR, &dev->flags);
952 }
953
954 /* Interface to userland (file_operations) */
955
956 static ssize_t cmm_read(struct file *filp, __user char *buf, size_t count,
957                         loff_t *ppos)
958 {
959         struct cm4000_dev *dev = filp->private_data;
960         ioaddr_t iobase = dev->p_dev->io.BasePort1;
961         ssize_t rc;
962         int i, j, k;
963
964         DEBUGP(2, dev, "-> cmm_read(%s,%d)\n", current->comm, current->pid);
965
966         if (count == 0)         /* according to manpage */
967                 return 0;
968
969         if (!pcmcia_dev_present(dev->p_dev) || /* device removed */
970             test_bit(IS_CMM_ABSENT, &dev->flags))
971                 return -ENODEV;
972
973         if (test_bit(IS_BAD_CSUM, &dev->flags))
974                 return -EIO;
975
976         /* also see the note about this in cmm_write */
977         if (wait_event_interruptible
978             (dev->atrq,
979              ((filp->f_flags & O_NONBLOCK)
980               || (test_bit(IS_ATR_PRESENT, (void *)&dev->flags) != 0)))) {
981                 if (filp->f_flags & O_NONBLOCK)
982                         return -EAGAIN;
983                 return -ERESTARTSYS;
984         }
985
986         if (test_bit(IS_ATR_VALID, &dev->flags) == 0)
987                 return -EIO;
988
989         /* this one implements blocking IO */
990         if (wait_event_interruptible
991             (dev->readq,
992              ((filp->f_flags & O_NONBLOCK) || (dev->rpos < dev->rlen)))) {
993                 if (filp->f_flags & O_NONBLOCK)
994                         return -EAGAIN;
995                 return -ERESTARTSYS;
996         }
997
998         /* lock io */
999         if (wait_event_interruptible
1000             (dev->ioq,
1001              ((filp->f_flags & O_NONBLOCK)
1002               || (test_and_set_bit(LOCK_IO, (void *)&dev->flags) == 0)))) {
1003                 if (filp->f_flags & O_NONBLOCK)
1004                         return -EAGAIN;
1005                 return -ERESTARTSYS;
1006         }
1007
1008         rc = 0;
1009         dev->flags0 = inb(REG_FLAGS0(iobase));
1010         if ((dev->flags0 & 1) == 0      /* no smartcard inserted */
1011             || dev->flags0 == 0xff) {   /* no cardman inserted */
1012                 clear_bit(IS_ATR_VALID, &dev->flags);
1013                 if (dev->flags0 & 1) {
1014                         set_bit(IS_CMM_ABSENT, &dev->flags);
1015                         rc = -ENODEV;
1016                 }
1017                 rc = -EIO;
1018                 goto release_io;
1019         }
1020
1021         DEBUGP(4, dev, "begin read answer\n");
1022         j = min(count, (size_t)(dev->rlen - dev->rpos));
1023         k = dev->rpos;
1024         if (k + j > 255)
1025                 j = 256 - k;
1026         DEBUGP(4, dev, "read1 j=%d\n", j);
1027         for (i = 0; i < j; i++) {
1028                 xoutb(k++, REG_BUF_ADDR(iobase));
1029                 dev->rbuf[i] = xinb(REG_BUF_DATA(iobase));
1030         }
1031         j = min(count, (size_t)(dev->rlen - dev->rpos));
1032         if (k + j > 255) {
1033                 DEBUGP(4, dev, "read2 j=%d\n", j);
1034                 dev->flags1 |= 0x10;    /* MSB buf addr set */
1035                 xoutb(dev->flags1, REG_FLAGS1(iobase));
1036                 for (; i < j; i++) {
1037                         xoutb(k++, REG_BUF_ADDR(iobase));
1038                         dev->rbuf[i] = xinb(REG_BUF_DATA(iobase));
1039                 }
1040         }
1041
1042         if (dev->proto == 0 && count > dev->rlen - dev->rpos) {
1043                 DEBUGP(4, dev, "T=0 and count > buffer\n");
1044                 dev->rbuf[i] = dev->rbuf[i - 1];
1045                 dev->rbuf[i - 1] = dev->procbyte;
1046                 j++;
1047         }
1048         count = j;
1049
1050         dev->rpos = dev->rlen + 1;
1051
1052         /* Clear T1Active */
1053         DEBUGP(4, dev, "Clear T1Active\n");
1054         dev->flags1 &= 0xdf;
1055         xoutb(dev->flags1, REG_FLAGS1(iobase));
1056
1057         xoutb(0, REG_FLAGS1(iobase));   /* clear detectCMM */
1058         /* last check before exit */
1059         if (!io_detect_cm4000(iobase, dev))
1060                 count = -ENODEV;
1061
1062         if (test_bit(IS_INVREV, &dev->flags) && count > 0)
1063                 str_invert_revert(dev->rbuf, count);
1064
1065         if (copy_to_user(buf, dev->rbuf, count))
1066                 return -EFAULT;
1067
1068 release_io:
1069         clear_bit(LOCK_IO, &dev->flags);
1070         wake_up_interruptible(&dev->ioq);
1071
1072         DEBUGP(2, dev, "<- cmm_read returns: rc = %Zi\n",
1073                (rc < 0 ? rc : count));
1074         return rc < 0 ? rc : count;
1075 }
1076
1077 static ssize_t cmm_write(struct file *filp, const char __user *buf,
1078                          size_t count, loff_t *ppos)
1079 {
1080         struct cm4000_dev *dev = (struct cm4000_dev *) filp->private_data;
1081         ioaddr_t iobase = dev->p_dev->io.BasePort1;
1082         unsigned short s;
1083         unsigned char tmp;
1084         unsigned char infolen;
1085         unsigned char sendT0;
1086         unsigned short nsend;
1087         unsigned short nr;
1088         ssize_t rc;
1089         int i;
1090
1091         DEBUGP(2, dev, "-> cmm_write(%s,%d)\n", current->comm, current->pid);
1092
1093         if (count == 0)         /* according to manpage */
1094                 return 0;
1095
1096         if (dev->proto == 0 && count < 4) {
1097                 /* T0 must have at least 4 bytes */
1098                 DEBUGP(4, dev, "T0 short write\n");
1099                 return -EIO;
1100         }
1101
1102         nr = count & 0x1ff;     /* max bytes to write */
1103
1104         sendT0 = dev->proto ? 0 : nr > 5 ? 0x08 : 0;
1105
1106         if (!pcmcia_dev_present(dev->p_dev) || /* device removed */
1107             test_bit(IS_CMM_ABSENT, &dev->flags))
1108                 return -ENODEV;
1109
1110         if (test_bit(IS_BAD_CSUM, &dev->flags)) {
1111                 DEBUGP(4, dev, "bad csum\n");
1112                 return -EIO;
1113         }
1114
1115         /*
1116          * wait for atr to become valid.
1117          * note: it is important to lock this code. if we dont, the monitor
1118          * could be run between test_bit and the the call the sleep on the
1119          * atr-queue.  if *then* the monitor detects atr valid, it will wake up
1120          * any process on the atr-queue, *but* since we have been interrupted,
1121          * we do not yet sleep on this queue. this would result in a missed
1122          * wake_up and the calling process would sleep forever (until
1123          * interrupted).  also, do *not* restore_flags before sleep_on, because
1124          * this could result in the same situation!
1125          */
1126         if (wait_event_interruptible
1127             (dev->atrq,
1128              ((filp->f_flags & O_NONBLOCK)
1129               || (test_bit(IS_ATR_PRESENT, (void *)&dev->flags) != 0)))) {
1130                 if (filp->f_flags & O_NONBLOCK)
1131                         return -EAGAIN;
1132                 return -ERESTARTSYS;
1133         }
1134
1135         if (test_bit(IS_ATR_VALID, &dev->flags) == 0) { /* invalid atr */
1136                 DEBUGP(4, dev, "invalid ATR\n");
1137                 return -EIO;
1138         }
1139
1140         /* lock io */
1141         if (wait_event_interruptible
1142             (dev->ioq,
1143              ((filp->f_flags & O_NONBLOCK)
1144               || (test_and_set_bit(LOCK_IO, (void *)&dev->flags) == 0)))) {
1145                 if (filp->f_flags & O_NONBLOCK)
1146                         return -EAGAIN;
1147                 return -ERESTARTSYS;
1148         }
1149
1150         if (copy_from_user(dev->sbuf, buf, ((count > 512) ? 512 : count)))
1151                 return -EFAULT;
1152
1153         rc = 0;
1154         dev->flags0 = inb(REG_FLAGS0(iobase));
1155         if ((dev->flags0 & 1) == 0      /* no smartcard inserted */
1156             || dev->flags0 == 0xff) {   /* no cardman inserted */
1157                 clear_bit(IS_ATR_VALID, &dev->flags);
1158                 if (dev->flags0 & 1) {
1159                         set_bit(IS_CMM_ABSENT, &dev->flags);
1160                         rc = -ENODEV;
1161                 } else {
1162                         DEBUGP(4, dev, "IO error\n");
1163                         rc = -EIO;
1164                 }
1165                 goto release_io;
1166         }
1167
1168         xoutb(0x80, REG_FLAGS0(iobase));        /* reset SM  */
1169
1170         if (!io_detect_cm4000(iobase, dev)) {
1171                 rc = -ENODEV;
1172                 goto release_io;
1173         }
1174
1175         /* reflect T=0 send/read mode in flags1 */
1176         dev->flags1 |= (sendT0);
1177
1178         set_cardparameter(dev);
1179
1180         /* dummy read, reset flag procedure received */
1181         tmp = inb(REG_FLAGS1(iobase));
1182
1183         dev->flags1 = 0x20      /* T_Active */
1184             | (sendT0)
1185             | (test_bit(IS_INVREV, &dev->flags) ? 2 : 0)/* inverse parity  */
1186             | (((dev->baudv - 1) & 0x0100) >> 8);       /* MSB-Baud */
1187         DEBUGP(1, dev, "set dev->flags1 = 0x%.2x\n", dev->flags1);
1188         xoutb(dev->flags1, REG_FLAGS1(iobase));
1189
1190         /* xmit data */
1191         DEBUGP(4, dev, "Xmit data\n");
1192         for (i = 0; i < nr; i++) {
1193                 if (i >= 256) {
1194                         dev->flags1 = 0x20      /* T_Active */
1195                             | (sendT0)  /* SendT0 */
1196                                 /* inverse parity: */
1197                             | (test_bit(IS_INVREV, &dev->flags) ? 2 : 0)
1198                             | (((dev->baudv - 1) & 0x0100) >> 8) /* MSB-Baud */
1199                             | 0x10;     /* set address high */
1200                         DEBUGP(4, dev, "dev->flags = 0x%.2x - set address "
1201                                "high\n", dev->flags1);
1202                         xoutb(dev->flags1, REG_FLAGS1(iobase));
1203                 }
1204                 if (test_bit(IS_INVREV, &dev->flags)) {
1205                         DEBUGP(4, dev, "Apply inverse convention for 0x%.2x "
1206                                 "-> 0x%.2x\n", (unsigned char)dev->sbuf[i],
1207                               invert_revert(dev->sbuf[i]));
1208                         xoutb(i, REG_BUF_ADDR(iobase));
1209                         xoutb(invert_revert(dev->sbuf[i]),
1210                               REG_BUF_DATA(iobase));
1211                 } else {
1212                         xoutb(i, REG_BUF_ADDR(iobase));
1213                         xoutb(dev->sbuf[i], REG_BUF_DATA(iobase));
1214                 }
1215         }
1216         DEBUGP(4, dev, "Xmit done\n");
1217
1218         if (dev->proto == 0) {
1219                 /* T=0 proto: 0 byte reply  */
1220                 if (nr == 4) {
1221                         DEBUGP(4, dev, "T=0 assumes 0 byte reply\n");
1222                         xoutb(i, REG_BUF_ADDR(iobase));
1223                         if (test_bit(IS_INVREV, &dev->flags))
1224                                 xoutb(0xff, REG_BUF_DATA(iobase));
1225                         else
1226                                 xoutb(0x00, REG_BUF_DATA(iobase));
1227                 }
1228
1229                 /* numSendBytes */
1230                 if (sendT0)
1231                         nsend = nr;
1232                 else {
1233                         if (nr == 4)
1234                                 nsend = 5;
1235                         else {
1236                                 nsend = 5 + (unsigned char)dev->sbuf[4];
1237                                 if (dev->sbuf[4] == 0)
1238                                         nsend += 0x100;
1239                         }
1240                 }
1241         } else
1242                 nsend = nr;
1243
1244         /* T0: output procedure byte */
1245         if (test_bit(IS_INVREV, &dev->flags)) {
1246                 DEBUGP(4, dev, "T=0 set Procedure byte (inverse-reverse) "
1247                        "0x%.2x\n", invert_revert(dev->sbuf[1]));
1248                 xoutb(invert_revert(dev->sbuf[1]), REG_NUM_BYTES(iobase));
1249         } else {
1250                 DEBUGP(4, dev, "T=0 set Procedure byte 0x%.2x\n", dev->sbuf[1]);
1251                 xoutb(dev->sbuf[1], REG_NUM_BYTES(iobase));
1252         }
1253
1254         DEBUGP(1, dev, "set NumSendBytes = 0x%.2x\n",
1255                (unsigned char)(nsend & 0xff));
1256         xoutb((unsigned char)(nsend & 0xff), REG_NUM_SEND(iobase));
1257
1258         DEBUGP(1, dev, "Trigger CARDMAN CONTROLLER (0x%.2x)\n",
1259                0x40     /* SM_Active */
1260               | (dev->flags0 & 2 ? 0 : 4)       /* power on if needed */
1261               |(dev->proto ? 0x10 : 0x08)       /* T=1/T=0 */
1262               |(nsend & 0x100) >> 8 /* MSB numSendBytes */ );
1263         xoutb(0x40              /* SM_Active */
1264               | (dev->flags0 & 2 ? 0 : 4)       /* power on if needed */
1265               |(dev->proto ? 0x10 : 0x08)       /* T=1/T=0 */
1266               |(nsend & 0x100) >> 8,    /* MSB numSendBytes */
1267               REG_FLAGS0(iobase));
1268
1269         /* wait for xmit done */
1270         if (dev->proto == 1) {
1271                 DEBUGP(4, dev, "Wait for xmit done\n");
1272                 for (i = 0; i < 1000; i++) {
1273                         if (inb(REG_FLAGS0(iobase)) & 0x08)
1274                                 break;
1275                         msleep_interruptible(10);
1276                 }
1277                 if (i == 1000) {
1278                         DEBUGP(4, dev, "timeout waiting for xmit done\n");
1279                         rc = -EIO;
1280                         goto release_io;
1281                 }
1282         }
1283
1284         /* T=1: wait for infoLen */
1285
1286         infolen = 0;
1287         if (dev->proto) {
1288                 /* wait until infoLen is valid */
1289                 for (i = 0; i < 6000; i++) {    /* max waiting time of 1 min */
1290                         io_read_num_rec_bytes(iobase, &s);
1291                         if (s >= 3) {
1292                                 infolen = inb(REG_FLAGS1(iobase));
1293                                 DEBUGP(4, dev, "infolen=%d\n", infolen);
1294                                 break;
1295                         }
1296                         msleep_interruptible(10);
1297                 }
1298                 if (i == 6000) {
1299                         DEBUGP(4, dev, "timeout waiting for infoLen\n");
1300                         rc = -EIO;
1301                         goto release_io;
1302                 }
1303         } else
1304                 clear_bit(IS_PROCBYTE_PRESENT, &dev->flags);
1305
1306         /* numRecBytes | bit9 of numRecytes */
1307         io_read_num_rec_bytes(iobase, &dev->rlen);
1308         for (i = 0; i < 600; i++) {     /* max waiting time of 2 sec */
1309                 if (dev->proto) {
1310                         if (dev->rlen >= infolen + 4)
1311                                 break;
1312                 }
1313                 msleep_interruptible(10);
1314                 /* numRecBytes | bit9 of numRecytes */
1315                 io_read_num_rec_bytes(iobase, &s);
1316                 if (s > dev->rlen) {
1317                         DEBUGP(1, dev, "NumRecBytes inc (reset timeout)\n");
1318                         i = 0;  /* reset timeout */
1319                         dev->rlen = s;
1320                 }
1321                 /* T=0: we are done when numRecBytes doesn't
1322                  *      increment any more and NoProcedureByte
1323                  *      is set and numRecBytes == bytes sent + 6
1324                  *      (header bytes + data + 1 for sw2)
1325                  *      except when the card replies an error
1326                  *      which means, no data will be sent back.
1327                  */
1328                 else if (dev->proto == 0) {
1329                         if ((inb(REG_BUF_ADDR(iobase)) & 0x80)) {
1330                                 /* no procedure byte received since last read */
1331                                 DEBUGP(1, dev, "NoProcedure byte set\n");
1332                                 /* i=0; */
1333                         } else {
1334                                 /* procedure byte received since last read */
1335                                 DEBUGP(1, dev, "NoProcedure byte unset "
1336                                         "(reset timeout)\n");
1337                                 dev->procbyte = inb(REG_FLAGS1(iobase));
1338                                 DEBUGP(1, dev, "Read procedure byte 0x%.2x\n",
1339                                       dev->procbyte);
1340                                 i = 0;  /* resettimeout */
1341                         }
1342                         if (inb(REG_FLAGS0(iobase)) & 0x08) {
1343                                 DEBUGP(1, dev, "T0Done flag (read reply)\n");
1344                                 break;
1345                         }
1346                 }
1347                 if (dev->proto)
1348                         infolen = inb(REG_FLAGS1(iobase));
1349         }
1350         if (i == 600) {
1351                 DEBUGP(1, dev, "timeout waiting for numRecBytes\n");
1352                 rc = -EIO;
1353                 goto release_io;
1354         } else {
1355                 if (dev->proto == 0) {
1356                         DEBUGP(1, dev, "Wait for T0Done bit to be  set\n");
1357                         for (i = 0; i < 1000; i++) {
1358                                 if (inb(REG_FLAGS0(iobase)) & 0x08)
1359                                         break;
1360                                 msleep_interruptible(10);
1361                         }
1362                         if (i == 1000) {
1363                                 DEBUGP(1, dev, "timeout waiting for T0Done\n");
1364                                 rc = -EIO;
1365                                 goto release_io;
1366                         }
1367
1368                         dev->procbyte = inb(REG_FLAGS1(iobase));
1369                         DEBUGP(4, dev, "Read procedure byte 0x%.2x\n",
1370                               dev->procbyte);
1371
1372                         io_read_num_rec_bytes(iobase, &dev->rlen);
1373                         DEBUGP(4, dev, "Read NumRecBytes = %i\n", dev->rlen);
1374
1375                 }
1376         }
1377         /* T=1: read offset=zero, T=0: read offset=after challenge */
1378         dev->rpos = dev->proto ? 0 : nr == 4 ? 5 : nr > dev->rlen ? 5 : nr;
1379         DEBUGP(4, dev, "dev->rlen = %i,  dev->rpos = %i, nr = %i\n",
1380               dev->rlen, dev->rpos, nr);
1381
1382 release_io:
1383         DEBUGP(4, dev, "Reset SM\n");
1384         xoutb(0x80, REG_FLAGS0(iobase));        /* reset SM */
1385
1386         if (rc < 0) {
1387                 DEBUGP(4, dev, "Write failed but clear T_Active\n");
1388                 dev->flags1 &= 0xdf;
1389                 xoutb(dev->flags1, REG_FLAGS1(iobase));
1390         }
1391
1392         clear_bit(LOCK_IO, &dev->flags);
1393         wake_up_interruptible(&dev->ioq);
1394         wake_up_interruptible(&dev->readq);     /* tell read we have data */
1395
1396         /* ITSEC E2: clear write buffer */
1397         memset((char *)dev->sbuf, 0, 512);
1398
1399         /* return error or actually written bytes */
1400         DEBUGP(2, dev, "<- cmm_write\n");
1401         return rc < 0 ? rc : nr;
1402 }
1403
1404 static void start_monitor(struct cm4000_dev *dev)
1405 {
1406         DEBUGP(3, dev, "-> start_monitor\n");
1407         if (!dev->monitor_running) {
1408                 DEBUGP(5, dev, "create, init and add timer\n");
1409                 init_timer(&dev->timer);
1410                 dev->monitor_running = 1;
1411                 dev->timer.expires = jiffies;
1412                 dev->timer.data = (unsigned long) dev;
1413                 dev->timer.function = monitor_card;
1414                 add_timer(&dev->timer);
1415         } else
1416                 DEBUGP(5, dev, "monitor already running\n");
1417         DEBUGP(3, dev, "<- start_monitor\n");
1418 }
1419
1420 static void stop_monitor(struct cm4000_dev *dev)
1421 {
1422         DEBUGP(3, dev, "-> stop_monitor\n");
1423         if (dev->monitor_running) {
1424                 DEBUGP(5, dev, "stopping monitor\n");
1425                 terminate_monitor(dev);
1426                 /* reset monitor SM */
1427                 clear_bit(IS_ATR_VALID, &dev->flags);
1428                 clear_bit(IS_ATR_PRESENT, &dev->flags);
1429         } else
1430                 DEBUGP(5, dev, "monitor already stopped\n");
1431         DEBUGP(3, dev, "<- stop_monitor\n");
1432 }
1433
1434 static int cmm_ioctl(struct inode *inode, struct file *filp, unsigned int cmd,
1435                      unsigned long arg)
1436 {
1437         struct cm4000_dev *dev = filp->private_data;
1438         ioaddr_t iobase = dev->p_dev->io.BasePort1;
1439         struct pcmcia_device *link;
1440         int size;
1441         int rc;
1442         void __user *argp = (void __user *)arg;
1443 #ifdef PCMCIA_DEBUG
1444         char *ioctl_names[CM_IOC_MAXNR + 1] = {
1445                 [_IOC_NR(CM_IOCGSTATUS)] "CM_IOCGSTATUS",
1446                 [_IOC_NR(CM_IOCGATR)] "CM_IOCGATR",
1447                 [_IOC_NR(CM_IOCARDOFF)] "CM_IOCARDOFF",
1448                 [_IOC_NR(CM_IOCSPTS)] "CM_IOCSPTS",
1449                 [_IOC_NR(CM_IOSDBGLVL)] "CM4000_DBGLVL",
1450         };
1451 #endif
1452         DEBUGP(3, dev, "cmm_ioctl(device=%d.%d) %s\n", imajor(inode),
1453                iminor(inode), ioctl_names[_IOC_NR(cmd)]);
1454
1455         link = dev_table[iminor(inode)];
1456         if (!pcmcia_dev_present(link)) {
1457                 DEBUGP(4, dev, "DEV_OK false\n");
1458                 return -ENODEV;
1459         }
1460
1461         if (test_bit(IS_CMM_ABSENT, &dev->flags)) {
1462                 DEBUGP(4, dev, "CMM_ABSENT flag set\n");
1463                 return -ENODEV;
1464         }
1465
1466         if (_IOC_TYPE(cmd) != CM_IOC_MAGIC) {
1467                 DEBUGP(4, dev, "ioctype mismatch\n");
1468                 return -EINVAL;
1469         }
1470         if (_IOC_NR(cmd) > CM_IOC_MAXNR) {
1471                 DEBUGP(4, dev, "iocnr mismatch\n");
1472                 return -EINVAL;
1473         }
1474         size = _IOC_SIZE(cmd);
1475         rc = 0;
1476         DEBUGP(4, dev, "iocdir=%.4x iocr=%.4x iocw=%.4x iocsize=%d cmd=%.4x\n",
1477               _IOC_DIR(cmd), _IOC_READ, _IOC_WRITE, size, cmd);
1478
1479         if (_IOC_DIR(cmd) & _IOC_READ) {
1480                 if (!access_ok(VERIFY_WRITE, argp, size))
1481                         return -EFAULT;
1482         }
1483         if (_IOC_DIR(cmd) & _IOC_WRITE) {
1484                 if (!access_ok(VERIFY_READ, argp, size))
1485                         return -EFAULT;
1486         }
1487
1488         switch (cmd) {
1489         case CM_IOCGSTATUS:
1490                 DEBUGP(4, dev, " ... in CM_IOCGSTATUS\n");
1491                 {
1492                         int status;
1493
1494                         /* clear other bits, but leave inserted & powered as
1495                          * they are */
1496                         status = dev->flags0 & 3;
1497                         if (test_bit(IS_ATR_PRESENT, &dev->flags))
1498                                 status |= CM_ATR_PRESENT;
1499                         if (test_bit(IS_ATR_VALID, &dev->flags))
1500                                 status |= CM_ATR_VALID;
1501                         if (test_bit(IS_CMM_ABSENT, &dev->flags))
1502                                 status |= CM_NO_READER;
1503                         if (test_bit(IS_BAD_CARD, &dev->flags))
1504                                 status |= CM_BAD_CARD;
1505                         if (copy_to_user(argp, &status, sizeof(int)))
1506                                 return -EFAULT;
1507                 }
1508                 return 0;
1509         case CM_IOCGATR:
1510                 DEBUGP(4, dev, "... in CM_IOCGATR\n");
1511                 {
1512                         struct atreq __user *atreq = argp;
1513                         int tmp;
1514                         /* allow nonblocking io and being interrupted */
1515                         if (wait_event_interruptible
1516                             (dev->atrq,
1517                              ((filp->f_flags & O_NONBLOCK)
1518                               || (test_bit(IS_ATR_PRESENT, (void *)&dev->flags)
1519                                   != 0)))) {
1520                                 if (filp->f_flags & O_NONBLOCK)
1521                                         return -EAGAIN;
1522                                 return -ERESTARTSYS;
1523                         }
1524
1525                         if (test_bit(IS_ATR_VALID, &dev->flags) == 0) {
1526                                 tmp = -1;
1527                                 if (copy_to_user(&(atreq->atr_len), &tmp,
1528                                                  sizeof(int)))
1529                                         return -EFAULT;
1530                         } else {
1531                                 if (copy_to_user(atreq->atr, dev->atr,
1532                                                  dev->atr_len))
1533                                         return -EFAULT;
1534
1535                                 tmp = dev->atr_len;
1536                                 if (copy_to_user(&(atreq->atr_len), &tmp, sizeof(int)))
1537                                         return -EFAULT;
1538                         }
1539                         return 0;
1540                 }
1541         case CM_IOCARDOFF:
1542
1543 #ifdef PCMCIA_DEBUG
1544                 DEBUGP(4, dev, "... in CM_IOCARDOFF\n");
1545                 if (dev->flags0 & 0x01) {
1546                         DEBUGP(4, dev, "    Card inserted\n");
1547                 } else {
1548                         DEBUGP(2, dev, "    No card inserted\n");
1549                 }
1550                 if (dev->flags0 & 0x02) {
1551                         DEBUGP(4, dev, "    Card powered\n");
1552                 } else {
1553                         DEBUGP(2, dev, "    Card not powered\n");
1554                 }
1555 #endif
1556
1557                 /* is a card inserted and powered? */
1558                 if ((dev->flags0 & 0x01) && (dev->flags0 & 0x02)) {
1559
1560                         /* get IO lock */
1561                         if (wait_event_interruptible
1562                             (dev->ioq,
1563                              ((filp->f_flags & O_NONBLOCK)
1564                               || (test_and_set_bit(LOCK_IO, (void *)&dev->flags)
1565                                   == 0)))) {
1566                                 if (filp->f_flags & O_NONBLOCK)
1567                                         return -EAGAIN;
1568                                 return -ERESTARTSYS;
1569                         }
1570                         /* Set Flags0 = 0x42 */
1571                         DEBUGP(4, dev, "Set Flags0=0x42 \n");
1572                         xoutb(0x42, REG_FLAGS0(iobase));
1573                         clear_bit(IS_ATR_PRESENT, &dev->flags);
1574                         clear_bit(IS_ATR_VALID, &dev->flags);
1575                         dev->mstate = M_CARDOFF;
1576                         clear_bit(LOCK_IO, &dev->flags);
1577                         if (wait_event_interruptible
1578                             (dev->atrq,
1579                              ((filp->f_flags & O_NONBLOCK)
1580                               || (test_bit(IS_ATR_VALID, (void *)&dev->flags) !=
1581                                   0)))) {
1582                                 if (filp->f_flags & O_NONBLOCK)
1583                                         return -EAGAIN;
1584                                 return -ERESTARTSYS;
1585                         }
1586                 }
1587                 /* release lock */
1588                 clear_bit(LOCK_IO, &dev->flags);
1589                 wake_up_interruptible(&dev->ioq);
1590
1591                 return 0;
1592         case CM_IOCSPTS:
1593                 {
1594                         struct ptsreq krnptsreq;
1595
1596                         if (copy_from_user(&krnptsreq, argp,
1597                                            sizeof(struct ptsreq)))
1598                                 return -EFAULT;
1599
1600                         rc = 0;
1601                         DEBUGP(4, dev, "... in CM_IOCSPTS\n");
1602                         /* wait for ATR to get valid */
1603                         if (wait_event_interruptible
1604                             (dev->atrq,
1605                              ((filp->f_flags & O_NONBLOCK)
1606                               || (test_bit(IS_ATR_PRESENT, (void *)&dev->flags)
1607                                   != 0)))) {
1608                                 if (filp->f_flags & O_NONBLOCK)
1609                                         return -EAGAIN;
1610                                 return -ERESTARTSYS;
1611                         }
1612                         /* get IO lock */
1613                         if (wait_event_interruptible
1614                             (dev->ioq,
1615                              ((filp->f_flags & O_NONBLOCK)
1616                               || (test_and_set_bit(LOCK_IO, (void *)&dev->flags)
1617                                   == 0)))) {
1618                                 if (filp->f_flags & O_NONBLOCK)
1619                                         return -EAGAIN;
1620                                 return -ERESTARTSYS;
1621                         }
1622
1623                         if ((rc = set_protocol(dev, &krnptsreq)) != 0) {
1624                                 /* auto power_on again */
1625                                 dev->mstate = M_FETCH_ATR;
1626                                 clear_bit(IS_ATR_VALID, &dev->flags);
1627                         }
1628                         /* release lock */
1629                         clear_bit(LOCK_IO, &dev->flags);
1630                         wake_up_interruptible(&dev->ioq);
1631
1632                 }
1633                 return rc;
1634 #ifdef PCMCIA_DEBUG
1635         case CM_IOSDBGLVL:      /* set debug log level */
1636                 {
1637                         int old_pc_debug = 0;
1638
1639                         old_pc_debug = pc_debug;
1640                         if (copy_from_user(&pc_debug, argp, sizeof(int)))
1641                                 return -EFAULT;
1642
1643                         if (old_pc_debug != pc_debug)
1644                                 DEBUGP(0, dev, "Changed debug log level "
1645                                        "to %i\n", pc_debug);
1646                 }
1647                 return rc;
1648 #endif
1649         default:
1650                 DEBUGP(4, dev, "... in default (unknown IOCTL code)\n");
1651                 return -EINVAL;
1652         }
1653 }
1654
1655 static int cmm_open(struct inode *inode, struct file *filp)
1656 {
1657         struct cm4000_dev *dev;
1658         struct pcmcia_device *link;
1659         int rc, minor = iminor(inode);
1660
1661         if (minor >= CM4000_MAX_DEV)
1662                 return -ENODEV;
1663
1664         link = dev_table[minor];
1665         if (link == NULL || !pcmcia_dev_present(link))
1666                 return -ENODEV;
1667
1668         if (link->open)
1669                 return -EBUSY;
1670
1671         dev = link->priv;
1672         filp->private_data = dev;
1673
1674         DEBUGP(2, dev, "-> cmm_open(device=%d.%d process=%s,%d)\n",
1675               imajor(inode), minor, current->comm, current->pid);
1676
1677         /* init device variables, they may be "polluted" after close
1678          * or, the device may never have been closed (i.e. open failed)
1679          */
1680
1681         ZERO_DEV(dev);
1682
1683         /* opening will always block since the
1684          * monitor will be started by open, which
1685          * means we have to wait for ATR becoming
1686          * vaild = block until valid (or card
1687          * inserted)
1688          */
1689         if (filp->f_flags & O_NONBLOCK)
1690                 return -EAGAIN;
1691
1692         dev->mdelay = T_50MSEC;
1693
1694         /* start monitoring the cardstatus */
1695         start_monitor(dev);
1696
1697         link->open = 1;         /* only one open per device */
1698         rc = 0;
1699
1700         DEBUGP(2, dev, "<- cmm_open\n");
1701         return nonseekable_open(inode, filp);
1702 }
1703
1704 static int cmm_close(struct inode *inode, struct file *filp)
1705 {
1706         struct cm4000_dev *dev;
1707         struct pcmcia_device *link;
1708         int minor = iminor(inode);
1709
1710         if (minor >= CM4000_MAX_DEV)
1711                 return -ENODEV;
1712
1713         link = dev_table[minor];
1714         if (link == NULL)
1715                 return -ENODEV;
1716
1717         dev = link->priv;
1718
1719         DEBUGP(2, dev, "-> cmm_close(maj/min=%d.%d)\n",
1720                imajor(inode), minor);
1721
1722         stop_monitor(dev);
1723
1724         ZERO_DEV(dev);
1725
1726         link->open = 0;         /* only one open per device */
1727         wake_up(&dev->devq);    /* socket removed? */
1728
1729         DEBUGP(2, dev, "cmm_close\n");
1730         return 0;
1731 }
1732
1733 static void cmm_cm4000_release(struct pcmcia_device * link)
1734 {
1735         struct cm4000_dev *dev = link->priv;
1736
1737         /* dont terminate the monitor, rather rely on
1738          * close doing that for us.
1739          */
1740         DEBUGP(3, dev, "-> cmm_cm4000_release\n");
1741         while (link->open) {
1742                 printk(KERN_INFO MODULE_NAME ": delaying release until "
1743                        "process has terminated\n");
1744                 /* note: don't interrupt us:
1745                  * close the applications which own
1746                  * the devices _first_ !
1747                  */
1748                 wait_event(dev->devq, (link->open == 0));
1749         }
1750         /* dev->devq=NULL;      this cannot be zeroed earlier */
1751         DEBUGP(3, dev, "<- cmm_cm4000_release\n");
1752         return;
1753 }
1754
1755 /*==== Interface to PCMCIA Layer =======================================*/
1756
1757 static int cm4000_config(struct pcmcia_device * link, int devno)
1758 {
1759         struct cm4000_dev *dev;
1760         tuple_t tuple;
1761         cisparse_t parse;
1762         u_char buf[64];
1763         int fail_fn, fail_rc;
1764         int rc;
1765
1766         /* read the config-tuples */
1767         tuple.DesiredTuple = CISTPL_CONFIG;
1768         tuple.Attributes = 0;
1769         tuple.TupleData = buf;
1770         tuple.TupleDataMax = sizeof(buf);
1771         tuple.TupleOffset = 0;
1772
1773         if ((fail_rc = pcmcia_get_first_tuple(link, &tuple)) != CS_SUCCESS) {
1774                 fail_fn = GetFirstTuple;
1775                 goto cs_failed;
1776         }
1777         if ((fail_rc = pcmcia_get_tuple_data(link, &tuple)) != CS_SUCCESS) {
1778                 fail_fn = GetTupleData;
1779                 goto cs_failed;
1780         }
1781         if ((fail_rc =
1782              pcmcia_parse_tuple(link, &tuple, &parse)) != CS_SUCCESS) {
1783                 fail_fn = ParseTuple;
1784                 goto cs_failed;
1785         }
1786
1787         link->conf.ConfigBase = parse.config.base;
1788         link->conf.Present = parse.config.rmask[0];
1789
1790         link->io.BasePort2 = 0;
1791         link->io.NumPorts2 = 0;
1792         link->io.Attributes2 = 0;
1793         tuple.DesiredTuple = CISTPL_CFTABLE_ENTRY;
1794         for (rc = pcmcia_get_first_tuple(link, &tuple);
1795              rc == CS_SUCCESS; rc = pcmcia_get_next_tuple(link, &tuple)) {
1796
1797                 rc = pcmcia_get_tuple_data(link, &tuple);
1798                 if (rc != CS_SUCCESS)
1799                         continue;
1800                 rc = pcmcia_parse_tuple(link, &tuple, &parse);
1801                 if (rc != CS_SUCCESS)
1802                         continue;
1803
1804                 link->conf.ConfigIndex = parse.cftable_entry.index;
1805
1806                 if (!parse.cftable_entry.io.nwin)
1807                         continue;
1808
1809                 /* Get the IOaddr */
1810                 link->io.BasePort1 = parse.cftable_entry.io.win[0].base;
1811                 link->io.NumPorts1 = parse.cftable_entry.io.win[0].len;
1812                 link->io.Attributes1 = IO_DATA_PATH_WIDTH_AUTO;
1813                 if (!(parse.cftable_entry.io.flags & CISTPL_IO_8BIT))
1814                         link->io.Attributes1 = IO_DATA_PATH_WIDTH_16;
1815                 if (!(parse.cftable_entry.io.flags & CISTPL_IO_16BIT))
1816                         link->io.Attributes1 = IO_DATA_PATH_WIDTH_8;
1817                 link->io.IOAddrLines = parse.cftable_entry.io.flags
1818                     & CISTPL_IO_LINES_MASK;
1819
1820                 rc = pcmcia_request_io(link, &link->io);
1821                 if (rc == CS_SUCCESS)
1822                         break;  /* we are done */
1823         }
1824         if (rc != CS_SUCCESS)
1825                 goto cs_release;
1826
1827         link->conf.IntType = 00000002;
1828
1829         if ((fail_rc =
1830              pcmcia_request_configuration(link, &link->conf)) != CS_SUCCESS) {
1831                 fail_fn = RequestConfiguration;
1832                 goto cs_release;
1833         }
1834
1835         dev = link->priv;
1836         sprintf(dev->node.dev_name, DEVICE_NAME "%d", devno);
1837         dev->node.major = major;
1838         dev->node.minor = devno;
1839         dev->node.next = NULL;
1840         link->dev_node = &dev->node;
1841
1842         return 0;
1843
1844 cs_failed:
1845         cs_error(link, fail_fn, fail_rc);
1846 cs_release:
1847         cm4000_release(link);
1848         return -ENODEV;
1849 }
1850
1851 static int cm4000_suspend(struct pcmcia_device *link)
1852 {
1853         struct cm4000_dev *dev;
1854
1855         dev = link->priv;
1856         stop_monitor(dev);
1857
1858         return 0;
1859 }
1860
1861 static int cm4000_resume(struct pcmcia_device *link)
1862 {
1863         struct cm4000_dev *dev;
1864
1865         dev = link->priv;
1866         if (link->open)
1867                 start_monitor(dev);
1868
1869         return 0;
1870 }
1871
1872 static void cm4000_release(struct pcmcia_device *link)
1873 {
1874         cmm_cm4000_release(link->priv); /* delay release until device closed */
1875         pcmcia_disable_device(link);
1876 }
1877
1878 static int cm4000_probe(struct pcmcia_device *link)
1879 {
1880         struct cm4000_dev *dev;
1881         int i, ret;
1882
1883         for (i = 0; i < CM4000_MAX_DEV; i++)
1884                 if (dev_table[i] == NULL)
1885                         break;
1886
1887         if (i == CM4000_MAX_DEV) {
1888                 printk(KERN_NOTICE MODULE_NAME ": all devices in use\n");
1889                 return -ENODEV;
1890         }
1891
1892         /* create a new cm4000_cs device */
1893         dev = kzalloc(sizeof(struct cm4000_dev), GFP_KERNEL);
1894         if (dev == NULL)
1895                 return -ENOMEM;
1896
1897         dev->p_dev = link;
1898         link->priv = dev;
1899         link->conf.IntType = INT_MEMORY_AND_IO;
1900         dev_table[i] = link;
1901
1902         init_waitqueue_head(&dev->devq);
1903         init_waitqueue_head(&dev->ioq);
1904         init_waitqueue_head(&dev->atrq);
1905         init_waitqueue_head(&dev->readq);
1906
1907         ret = cm4000_config(link, i);
1908         if (ret)
1909                 return ret;
1910
1911         class_device_create(cmm_class, NULL, MKDEV(major, i), NULL,
1912                             "cmm%d", i);
1913
1914         return 0;
1915 }
1916
1917 static void cm4000_detach(struct pcmcia_device *link)
1918 {
1919         struct cm4000_dev *dev = link->priv;
1920         int devno;
1921
1922         /* find device */
1923         for (devno = 0; devno < CM4000_MAX_DEV; devno++)
1924                 if (dev_table[devno] == link)
1925                         break;
1926         if (devno == CM4000_MAX_DEV)
1927                 return;
1928
1929         stop_monitor(dev);
1930
1931         cm4000_release(link);
1932
1933         dev_table[devno] = NULL;
1934         kfree(dev);
1935
1936         class_device_destroy(cmm_class, MKDEV(major, devno));
1937
1938         return;
1939 }
1940
1941 static const struct file_operations cm4000_fops = {
1942         .owner  = THIS_MODULE,
1943         .read   = cmm_read,
1944         .write  = cmm_write,
1945         .ioctl  = cmm_ioctl,
1946         .open   = cmm_open,
1947         .release= cmm_close,
1948 };
1949
1950 static struct pcmcia_device_id cm4000_ids[] = {
1951         PCMCIA_DEVICE_MANF_CARD(0x0223, 0x0002),
1952         PCMCIA_DEVICE_PROD_ID12("CardMan", "4000", 0x2FB368CA, 0xA2BD8C39),
1953         PCMCIA_DEVICE_NULL,
1954 };
1955 MODULE_DEVICE_TABLE(pcmcia, cm4000_ids);
1956
1957 static struct pcmcia_driver cm4000_driver = {
1958         .owner    = THIS_MODULE,
1959         .drv      = {
1960                 .name = "cm4000_cs",
1961                 },
1962         .probe    = cm4000_probe,
1963         .remove   = cm4000_detach,
1964         .suspend  = cm4000_suspend,
1965         .resume   = cm4000_resume,
1966         .id_table = cm4000_ids,
1967 };
1968
1969 static int __init cmm_init(void)
1970 {
1971         int rc;
1972
1973         printk(KERN_INFO "%s\n", version);
1974
1975         cmm_class = class_create(THIS_MODULE, "cardman_4000");
1976         if (!cmm_class)
1977                 return -1;
1978
1979         major = register_chrdev(0, DEVICE_NAME, &cm4000_fops);
1980         if (major < 0) {
1981                 printk(KERN_WARNING MODULE_NAME
1982                         ": could not get major number\n");
1983                 return -1;
1984         }
1985
1986         rc = pcmcia_register_driver(&cm4000_driver);
1987         if (rc < 0) {
1988                 unregister_chrdev(major, DEVICE_NAME);
1989                 return rc;
1990         }
1991
1992         return 0;
1993 }
1994
1995 static void __exit cmm_exit(void)
1996 {
1997         printk(KERN_INFO MODULE_NAME ": unloading\n");
1998         pcmcia_unregister_driver(&cm4000_driver);
1999         unregister_chrdev(major, DEVICE_NAME);
2000         class_destroy(cmm_class);
2001 };
2002
2003 module_init(cmm_init);
2004 module_exit(cmm_exit);
2005 MODULE_LICENSE("Dual BSD/GPL");