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