[PATCH] pcmcia: request CIS via firmware interface
[safe/jmp/linux-2.6] / drivers / pcmcia / ds.c
1 /*
2  * ds.c -- 16-bit PCMCIA core support
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License version 2 as
6  * published by the Free Software Foundation.
7  *
8  * The initial developer of the original code is David A. Hinds
9  * <dahinds@users.sourceforge.net>.  Portions created by David A. Hinds
10  * are Copyright (C) 1999 David A. Hinds.  All Rights Reserved.
11  *
12  * (C) 1999             David A. Hinds
13  * (C) 2003 - 2004      Dominik Brodowski
14  */
15
16 #include <linux/config.h>
17 #include <linux/module.h>
18 #include <linux/moduleparam.h>
19 #include <linux/init.h>
20 #include <linux/kernel.h>
21 #include <linux/major.h>
22 #include <linux/string.h>
23 #include <linux/errno.h>
24 #include <linux/slab.h>
25 #include <linux/mm.h>
26 #include <linux/fcntl.h>
27 #include <linux/sched.h>
28 #include <linux/smp_lock.h>
29 #include <linux/timer.h>
30 #include <linux/ioctl.h>
31 #include <linux/proc_fs.h>
32 #include <linux/poll.h>
33 #include <linux/pci.h>
34 #include <linux/list.h>
35 #include <linux/delay.h>
36 #include <linux/kref.h>
37 #include <linux/workqueue.h>
38 #include <linux/crc32.h>
39 #include <linux/firmware.h>
40
41 #include <asm/atomic.h>
42
43 #define IN_CARD_SERVICES
44 #include <pcmcia/version.h>
45 #include <pcmcia/cs_types.h>
46 #include <pcmcia/cs.h>
47 #include <pcmcia/bulkmem.h>
48 #include <pcmcia/cistpl.h>
49 #include <pcmcia/ds.h>
50 #include <pcmcia/ss.h>
51
52 #include "cs_internal.h"
53
54 /*====================================================================*/
55
56 /* Module parameters */
57
58 MODULE_AUTHOR("David Hinds <dahinds@users.sourceforge.net>");
59 MODULE_DESCRIPTION("PCMCIA Driver Services");
60 MODULE_LICENSE("GPL");
61
62 #ifdef DEBUG
63 int ds_pc_debug;
64
65 module_param_named(pc_debug, ds_pc_debug, int, 0644);
66
67 #define ds_dbg(lvl, fmt, arg...) do {                           \
68         if (ds_pc_debug > (lvl))                                        \
69                 printk(KERN_DEBUG "ds: " fmt , ## arg);         \
70 } while (0)
71 #else
72 #define ds_dbg(lvl, fmt, arg...) do { } while (0)
73 #endif
74
75 /*====================================================================*/
76
77 /* Device user information */
78 #define MAX_EVENTS      32
79 #define USER_MAGIC      0x7ea4
80 #define CHECK_USER(u) \
81     (((u) == NULL) || ((u)->user_magic != USER_MAGIC))
82 typedef struct user_info_t {
83     u_int               user_magic;
84     int                 event_head, event_tail;
85     event_t             event[MAX_EVENTS];
86     struct user_info_t  *next;
87     struct pcmcia_bus_socket *socket;
88 } user_info_t;
89
90 /* Socket state information */
91 struct pcmcia_bus_socket {
92         struct kref             refcount;
93         struct pcmcia_callback  callback;
94         int                     state;
95         user_info_t             *user;
96         wait_queue_head_t       queue;
97         struct pcmcia_socket    *parent;
98
99         /* the PCMCIA devices connected to this socket (normally one, more
100          * for multifunction devices: */
101         struct list_head        devices_list;
102         u8                      device_count; /* the number of devices, used
103                                                * only internally and subject
104                                                * to incorrectness and change */
105
106         u8                      device_add_pending;
107         struct work_struct      device_add;
108 };
109 static spinlock_t pcmcia_dev_list_lock;
110
111 #define DS_SOCKET_PRESENT               0x01
112 #define DS_SOCKET_BUSY                  0x02
113 #define DS_SOCKET_REMOVAL_PENDING       0x10
114 #define DS_SOCKET_DEAD                  0x80
115
116 /*====================================================================*/
117
118 static int major_dev = -1;
119
120 static int unbind_request(struct pcmcia_bus_socket *s);
121
122 /*====================================================================*/
123
124 /* code which was in cs.c before */
125
126 /* String tables for error messages */
127
128 typedef struct lookup_t {
129     int key;
130     char *msg;
131 } lookup_t;
132
133 static const lookup_t error_table[] = {
134     { CS_SUCCESS,               "Operation succeeded" },
135     { CS_BAD_ADAPTER,           "Bad adapter" },
136     { CS_BAD_ATTRIBUTE,         "Bad attribute", },
137     { CS_BAD_BASE,              "Bad base address" },
138     { CS_BAD_EDC,               "Bad EDC" },
139     { CS_BAD_IRQ,               "Bad IRQ" },
140     { CS_BAD_OFFSET,            "Bad offset" },
141     { CS_BAD_PAGE,              "Bad page number" },
142     { CS_READ_FAILURE,          "Read failure" },
143     { CS_BAD_SIZE,              "Bad size" },
144     { CS_BAD_SOCKET,            "Bad socket" },
145     { CS_BAD_TYPE,              "Bad type" },
146     { CS_BAD_VCC,               "Bad Vcc" },
147     { CS_BAD_VPP,               "Bad Vpp" },
148     { CS_BAD_WINDOW,            "Bad window" },
149     { CS_WRITE_FAILURE,         "Write failure" },
150     { CS_NO_CARD,               "No card present" },
151     { CS_UNSUPPORTED_FUNCTION,  "Usupported function" },
152     { CS_UNSUPPORTED_MODE,      "Unsupported mode" },
153     { CS_BAD_SPEED,             "Bad speed" },
154     { CS_BUSY,                  "Resource busy" },
155     { CS_GENERAL_FAILURE,       "General failure" },
156     { CS_WRITE_PROTECTED,       "Write protected" },
157     { CS_BAD_ARG_LENGTH,        "Bad argument length" },
158     { CS_BAD_ARGS,              "Bad arguments" },
159     { CS_CONFIGURATION_LOCKED,  "Configuration locked" },
160     { CS_IN_USE,                "Resource in use" },
161     { CS_NO_MORE_ITEMS,         "No more items" },
162     { CS_OUT_OF_RESOURCE,       "Out of resource" },
163     { CS_BAD_HANDLE,            "Bad handle" },
164     { CS_BAD_TUPLE,             "Bad CIS tuple" }
165 };
166
167
168 static const lookup_t service_table[] = {
169     { AccessConfigurationRegister,      "AccessConfigurationRegister" },
170     { AddSocketServices,                "AddSocketServices" },
171     { AdjustResourceInfo,               "AdjustResourceInfo" },
172     { CheckEraseQueue,                  "CheckEraseQueue" },
173     { CloseMemory,                      "CloseMemory" },
174     { DeregisterClient,                 "DeregisterClient" },
175     { DeregisterEraseQueue,             "DeregisterEraseQueue" },
176     { GetCardServicesInfo,              "GetCardServicesInfo" },
177     { GetClientInfo,                    "GetClientInfo" },
178     { GetConfigurationInfo,             "GetConfigurationInfo" },
179     { GetEventMask,                     "GetEventMask" },
180     { GetFirstClient,                   "GetFirstClient" },
181     { GetFirstRegion,                   "GetFirstRegion" },
182     { GetFirstTuple,                    "GetFirstTuple" },
183     { GetNextClient,                    "GetNextClient" },
184     { GetNextRegion,                    "GetNextRegion" },
185     { GetNextTuple,                     "GetNextTuple" },
186     { GetStatus,                        "GetStatus" },
187     { GetTupleData,                     "GetTupleData" },
188     { MapMemPage,                       "MapMemPage" },
189     { ModifyConfiguration,              "ModifyConfiguration" },
190     { ModifyWindow,                     "ModifyWindow" },
191     { OpenMemory,                       "OpenMemory" },
192     { ParseTuple,                       "ParseTuple" },
193     { ReadMemory,                       "ReadMemory" },
194     { RegisterClient,                   "RegisterClient" },
195     { RegisterEraseQueue,               "RegisterEraseQueue" },
196     { RegisterMTD,                      "RegisterMTD" },
197     { ReleaseConfiguration,             "ReleaseConfiguration" },
198     { ReleaseIO,                        "ReleaseIO" },
199     { ReleaseIRQ,                       "ReleaseIRQ" },
200     { ReleaseWindow,                    "ReleaseWindow" },
201     { RequestConfiguration,             "RequestConfiguration" },
202     { RequestIO,                        "RequestIO" },
203     { RequestIRQ,                       "RequestIRQ" },
204     { RequestSocketMask,                "RequestSocketMask" },
205     { RequestWindow,                    "RequestWindow" },
206     { ResetCard,                        "ResetCard" },
207     { SetEventMask,                     "SetEventMask" },
208     { ValidateCIS,                      "ValidateCIS" },
209     { WriteMemory,                      "WriteMemory" },
210     { BindDevice,                       "BindDevice" },
211     { BindMTD,                          "BindMTD" },
212     { ReportError,                      "ReportError" },
213     { SuspendCard,                      "SuspendCard" },
214     { ResumeCard,                       "ResumeCard" },
215     { EjectCard,                        "EjectCard" },
216     { InsertCard,                       "InsertCard" },
217     { ReplaceCIS,                       "ReplaceCIS" }
218 };
219
220
221 int pcmcia_report_error(client_handle_t handle, error_info_t *err)
222 {
223         int i;
224         char *serv;
225
226         if (CHECK_HANDLE(handle))
227                 printk(KERN_NOTICE);
228         else {
229                 struct pcmcia_device *p_dev = handle_to_pdev(handle);
230                 printk(KERN_NOTICE "%s: ", p_dev->dev.bus_id);
231         }
232
233         for (i = 0; i < ARRAY_SIZE(service_table); i++)
234                 if (service_table[i].key == err->func)
235                         break;
236         if (i < ARRAY_SIZE(service_table))
237                 serv = service_table[i].msg;
238         else
239                 serv = "Unknown service number";
240
241         for (i = 0; i < ARRAY_SIZE(error_table); i++)
242                 if (error_table[i].key == err->retcode)
243                         break;
244         if (i < ARRAY_SIZE(error_table))
245                 printk("%s: %s\n", serv, error_table[i].msg);
246         else
247                 printk("%s: Unknown error code %#x\n", serv, err->retcode);
248
249         return CS_SUCCESS;
250 } /* report_error */
251 EXPORT_SYMBOL(pcmcia_report_error);
252
253 /* end of code which was in cs.c before */
254
255 /*======================================================================*/
256
257 void cs_error(client_handle_t handle, int func, int ret)
258 {
259         error_info_t err = { func, ret };
260         pcmcia_report_error(handle, &err);
261 }
262 EXPORT_SYMBOL(cs_error);
263
264 #ifdef CONFIG_PCMCIA_DEBUG
265
266
267 static void pcmcia_check_driver(struct pcmcia_driver *p_drv)
268 {
269         struct pcmcia_device_id *did = p_drv->id_table;
270         unsigned int i;
271         u32 hash;
272
273         while (did && did->match_flags) {
274                 for (i=0; i<4; i++) {
275                         if (!did->prod_id[i])
276                                 continue;
277
278                         hash = crc32(0, did->prod_id[i], strlen(did->prod_id[i]));
279                         if (hash == did->prod_id_hash[i])
280                                 continue;
281
282                         printk(KERN_DEBUG "pcmcia: %s: invalid hash for "
283                                "product string \"%s\": is 0x%x, should "
284                                "be 0x%x\n", p_drv->drv.name, did->prod_id[i],
285                                did->prod_id_hash[i], hash);
286                 }
287                 did++;
288         }
289
290         return;
291 }
292
293 #else
294 static inline void pcmcia_check_driver(struct pcmcia_driver *p_drv) {
295         return;
296 }
297 #endif
298
299
300 #ifdef CONFIG_PCMCIA_LOAD_CIS
301
302 /**
303  * pcmcia_load_firmware - load CIS from userspace if device-provided is broken
304  * @dev - the pcmcia device which needs a CIS override
305  * @filename - requested filename in /lib/firmware/cis/
306  *
307  * This uses the in-kernel firmware loading mechanism to use a "fake CIS" if
308  * the one provided by the card is broken. The firmware files reside in
309  * /lib/firmware/cis/ in userspace.
310  */
311 static int pcmcia_load_firmware(struct pcmcia_device *dev, char * filename)
312 {
313         struct pcmcia_socket *s = dev->socket;
314         const struct firmware *fw;
315         char path[20];
316         int ret=-ENOMEM;
317         cisdump_t *cis;
318
319         if (!filename)
320                 return -EINVAL;
321
322         ds_dbg(1, "trying to load firmware %s\n", filename);
323
324         if (strlen(filename) > 14)
325                 return -EINVAL;
326
327         snprintf(path, 20, "%s", filename);
328
329         if (request_firmware(&fw, path, &dev->dev) == 0) {
330                 if (fw->size >= CISTPL_MAX_CIS_SIZE)
331                         goto release;
332
333                 cis = kmalloc(sizeof(cisdump_t), GFP_KERNEL);
334                 if (!cis)
335                         goto release;
336
337                 memset(cis, 0, sizeof(cisdump_t));
338
339                 cis->Length = fw->size + 1;
340                 memcpy(cis->Data, fw->data, fw->size);
341
342                 if (!pcmcia_replace_cis(s, cis))
343                         ret = 0;
344         }
345  release:
346         release_firmware(fw);
347
348         return (ret);
349 }
350
351 #else /* !CONFIG_PCMCIA_LOAD_CIS */
352
353 static inline int pcmcia_load_firmware(struct pcmcia_device *dev, char * filename)
354 {
355         return -ENODEV;
356 }
357
358 #endif
359
360
361 /*======================================================================*/
362
363 static struct pcmcia_driver * get_pcmcia_driver (dev_info_t *dev_info);
364 static struct pcmcia_bus_socket * get_socket_info_by_nr(unsigned int nr);
365
366 static void pcmcia_release_bus_socket(struct kref *refcount)
367 {
368         struct pcmcia_bus_socket *s = container_of(refcount, struct pcmcia_bus_socket, refcount);
369         pcmcia_put_socket(s->parent);
370         kfree(s);
371 }
372
373 static void pcmcia_put_bus_socket(struct pcmcia_bus_socket *s)
374 {
375         kref_put(&s->refcount, pcmcia_release_bus_socket);
376 }
377
378 static struct pcmcia_bus_socket *pcmcia_get_bus_socket(struct pcmcia_bus_socket *s)
379 {
380         kref_get(&s->refcount);
381         return (s);
382 }
383
384 /**
385  * pcmcia_register_driver - register a PCMCIA driver with the bus core
386  *
387  * Registers a PCMCIA driver with the PCMCIA bus core.
388  */
389 static int pcmcia_device_probe(struct device *dev);
390 static int pcmcia_device_remove(struct device * dev);
391
392 int pcmcia_register_driver(struct pcmcia_driver *driver)
393 {
394         if (!driver)
395                 return -EINVAL;
396
397         pcmcia_check_driver(driver);
398
399         /* initialize common fields */
400         driver->drv.bus = &pcmcia_bus_type;
401         driver->drv.owner = driver->owner;
402         driver->drv.probe = pcmcia_device_probe;
403         driver->drv.remove = pcmcia_device_remove;
404
405         return driver_register(&driver->drv);
406 }
407 EXPORT_SYMBOL(pcmcia_register_driver);
408
409 /**
410  * pcmcia_unregister_driver - unregister a PCMCIA driver with the bus core
411  */
412 void pcmcia_unregister_driver(struct pcmcia_driver *driver)
413 {
414         driver_unregister(&driver->drv);
415 }
416 EXPORT_SYMBOL(pcmcia_unregister_driver);
417
418 #ifdef CONFIG_PROC_FS
419 static struct proc_dir_entry *proc_pccard = NULL;
420
421 static int proc_read_drivers_callback(struct device_driver *driver, void *d)
422 {
423         char **p = d;
424         struct pcmcia_driver *p_drv = container_of(driver,
425                                                    struct pcmcia_driver, drv);
426
427         *p += sprintf(*p, "%-24.24s 1 %d\n", p_drv->drv.name,
428 #ifdef CONFIG_MODULE_UNLOAD
429                       (p_drv->owner) ? module_refcount(p_drv->owner) : 1
430 #else
431                       1
432 #endif
433         );
434         d = (void *) p;
435
436         return 0;
437 }
438
439 static int proc_read_drivers(char *buf, char **start, off_t pos,
440                              int count, int *eof, void *data)
441 {
442         char *p = buf;
443
444         bus_for_each_drv(&pcmcia_bus_type, NULL, 
445                          (void *) &p, proc_read_drivers_callback);
446
447         return (p - buf);
448 }
449 #endif
450
451 /* pcmcia_device handling */
452
453 static struct pcmcia_device * pcmcia_get_dev(struct pcmcia_device *p_dev)
454 {
455         struct device *tmp_dev;
456         tmp_dev = get_device(&p_dev->dev);
457         if (!tmp_dev)
458                 return NULL;
459         return to_pcmcia_dev(tmp_dev);
460 }
461
462 static void pcmcia_put_dev(struct pcmcia_device *p_dev)
463 {
464         if (p_dev)
465                 put_device(&p_dev->dev);
466 }
467
468 static void pcmcia_release_dev(struct device *dev)
469 {
470         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);
471         ds_dbg(1, "releasing dev %p\n", p_dev);
472         pcmcia_put_bus_socket(p_dev->socket->pcmcia);
473         kfree(p_dev);
474 }
475
476
477 static int pcmcia_device_probe(struct device * dev)
478 {
479         struct pcmcia_device *p_dev;
480         struct pcmcia_driver *p_drv;
481         int ret = 0;
482
483         dev = get_device(dev);
484         if (!dev)
485                 return -ENODEV;
486
487         p_dev = to_pcmcia_dev(dev);
488         p_drv = to_pcmcia_drv(dev->driver);
489
490         if (!try_module_get(p_drv->owner)) {
491                 ret = -EINVAL;
492                 goto put_dev;
493         }
494
495         if (p_drv->attach) {
496                 p_dev->instance = p_drv->attach();
497                 if ((!p_dev->instance) || (p_dev->client.state & CLIENT_UNBOUND)) {
498                         printk(KERN_NOTICE "ds: unable to create instance "
499                                "of '%s'!\n", p_drv->drv.name);
500                         ret = -EINVAL;
501                 }
502         }
503
504         if (ret)
505                 module_put(p_drv->owner);
506  put_dev:
507         if ((ret) || !(p_drv->attach))
508                 put_device(dev);
509         return (ret);
510 }
511
512
513 static int pcmcia_device_remove(struct device * dev)
514 {
515         struct pcmcia_device *p_dev;
516         struct pcmcia_driver *p_drv;
517
518         /* detach the "instance" */
519         p_dev = to_pcmcia_dev(dev);
520         p_drv = to_pcmcia_drv(dev->driver);
521
522         if (p_drv) {
523                 if ((p_drv->detach) && (p_dev->instance)) {
524                         p_drv->detach(p_dev->instance);
525                         /* from pcmcia_probe_device */
526                         put_device(&p_dev->dev);
527                 }
528                 module_put(p_drv->owner);
529         }
530
531         return 0;
532 }
533
534
535
536 /*
537  * pcmcia_device_query -- determine information about a pcmcia device
538  */
539 static int pcmcia_device_query(struct pcmcia_device *p_dev)
540 {
541         cistpl_manfid_t manf_id;
542         cistpl_funcid_t func_id;
543         cistpl_vers_1_t vers1;
544         unsigned int i;
545
546         if (!pccard_read_tuple(p_dev->socket, p_dev->func,
547                                CISTPL_MANFID, &manf_id)) {
548                 p_dev->manf_id = manf_id.manf;
549                 p_dev->card_id = manf_id.card;
550                 p_dev->has_manf_id = 1;
551                 p_dev->has_card_id = 1;
552         }
553
554         if (!pccard_read_tuple(p_dev->socket, p_dev->func,
555                                CISTPL_FUNCID, &func_id)) {
556                 p_dev->func_id = func_id.func;
557                 p_dev->has_func_id = 1;
558         } else {
559                 /* rule of thumb: cards with no FUNCID, but with
560                  * common memory device geometry information, are
561                  * probably memory cards (from pcmcia-cs) */
562                 cistpl_device_geo_t devgeo;
563                 if (!pccard_read_tuple(p_dev->socket, p_dev->func,
564                                       CISTPL_DEVICE_GEO, &devgeo)) {
565                         ds_dbg(0, "mem device geometry probably means "
566                                "FUNCID_MEMORY\n");
567                         p_dev->func_id = CISTPL_FUNCID_MEMORY;
568                         p_dev->has_func_id = 1;
569                 }
570         }
571
572         if (!pccard_read_tuple(p_dev->socket, p_dev->func, CISTPL_VERS_1,
573                                &vers1)) {
574                 for (i=0; i < vers1.ns; i++) {
575                         char *tmp;
576                         unsigned int length;
577
578                         tmp = vers1.str + vers1.ofs[i];
579
580                         length = strlen(tmp) + 1;
581                         if ((length < 3) || (length > 255))
582                                 continue;
583
584                         p_dev->prod_id[i] = kmalloc(sizeof(char) * length,
585                                                     GFP_KERNEL);
586                         if (!p_dev->prod_id[i])
587                                 continue;
588
589                         p_dev->prod_id[i] = strncpy(p_dev->prod_id[i],
590                                                     tmp, length);
591                 }
592         }
593
594         return 0;
595 }
596
597
598 /* device_add_lock is needed to avoid double registration by cardmgr and kernel.
599  * Serializes pcmcia_device_add; will most likely be removed in future.
600  *
601  * While it has the caveat that adding new PCMCIA devices inside(!) device_register()
602  * won't work, this doesn't matter much at the moment: the driver core doesn't
603  * support it either.
604  */
605 static DECLARE_MUTEX(device_add_lock);
606
607 static struct pcmcia_device * pcmcia_device_add(struct pcmcia_bus_socket *s, unsigned int function)
608 {
609         struct pcmcia_device *p_dev;
610         unsigned long flags;
611
612         s = pcmcia_get_bus_socket(s);
613         if (!s)
614                 return NULL;
615
616         down(&device_add_lock);
617
618         /* max of 2 devices per card */
619         if (s->device_count == 2)
620                 goto err_put;
621
622         p_dev = kmalloc(sizeof(struct pcmcia_device), GFP_KERNEL);
623         if (!p_dev)
624                 goto err_put;
625         memset(p_dev, 0, sizeof(struct pcmcia_device));
626
627         p_dev->socket = s->parent;
628         p_dev->device_no = (s->device_count++);
629         p_dev->func   = function;
630
631         p_dev->dev.bus = &pcmcia_bus_type;
632         p_dev->dev.parent = s->parent->dev.dev;
633         p_dev->dev.release = pcmcia_release_dev;
634         sprintf (p_dev->dev.bus_id, "%d.%d", p_dev->socket->sock, p_dev->device_no);
635
636         /* compat */
637         p_dev->client.client_magic = CLIENT_MAGIC;
638         p_dev->client.Socket = s->parent;
639         p_dev->client.Function = function;
640         p_dev->client.state = CLIENT_UNBOUND;
641
642         /* Add to the list in pcmcia_bus_socket */
643         spin_lock_irqsave(&pcmcia_dev_list_lock, flags);
644         list_add_tail(&p_dev->socket_device_list, &s->devices_list);
645         spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
646
647         pcmcia_device_query(p_dev);
648
649         if (device_register(&p_dev->dev)) {
650                 spin_lock_irqsave(&pcmcia_dev_list_lock, flags);
651                 list_del(&p_dev->socket_device_list);
652                 spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
653
654                 goto err_free;
655        }
656
657         up(&device_add_lock);
658
659         return p_dev;
660
661  err_free:
662         kfree(p_dev);
663         s->device_count--;
664  err_put:
665         up(&device_add_lock);
666         pcmcia_put_bus_socket(s);
667
668         return NULL;
669 }
670
671
672 static int pcmcia_card_add(struct pcmcia_socket *s)
673 {
674         cisinfo_t cisinfo;
675         cistpl_longlink_mfc_t mfc;
676         unsigned int no_funcs, i;
677         int ret = 0;
678
679         if (!(s->resource_setup_done))
680                 return -EAGAIN; /* try again, but later... */
681
682         pcmcia_validate_mem(s);
683         ret = pccard_validate_cis(s, BIND_FN_ALL, &cisinfo);
684         if (ret || !cisinfo.Chains) {
685                 ds_dbg(0, "invalid CIS or invalid resources\n");
686                 return -ENODEV;
687         }
688
689         if (!pccard_read_tuple(s, BIND_FN_ALL, CISTPL_LONGLINK_MFC, &mfc))
690                 no_funcs = mfc.nfn;
691         else
692                 no_funcs = 1;
693
694         /* this doesn't handle multifunction devices on one pcmcia function
695          * yet. */
696         for (i=0; i < no_funcs; i++)
697                 pcmcia_device_add(s->pcmcia, i);
698
699         return (ret);
700 }
701
702
703 static void pcmcia_delayed_add_pseudo_device(void *data)
704 {
705         struct pcmcia_bus_socket *s = data;
706         pcmcia_device_add(s, 0);
707         s->device_add_pending = 0;
708 }
709
710 static inline void pcmcia_add_pseudo_device(struct pcmcia_bus_socket *s)
711 {
712         if (!s->device_add_pending) {
713                 schedule_work(&s->device_add);
714                 s->device_add_pending = 1;
715         }
716         return;
717 }
718
719 static void pcmcia_bus_rescan(void)
720 {
721         /* must be called with skt_sem held */
722         bus_rescan_devices(&pcmcia_bus_type);
723 }
724
725 static inline int pcmcia_devmatch(struct pcmcia_device *dev,
726                                   struct pcmcia_device_id *did)
727 {
728         if (did->match_flags & PCMCIA_DEV_ID_MATCH_MANF_ID) {
729                 if ((!dev->has_manf_id) || (dev->manf_id != did->manf_id))
730                         return 0;
731         }
732
733         if (did->match_flags & PCMCIA_DEV_ID_MATCH_CARD_ID) {
734                 if ((!dev->has_card_id) || (dev->card_id != did->card_id))
735                         return 0;
736         }
737
738         if (did->match_flags & PCMCIA_DEV_ID_MATCH_FUNCTION) {
739                 if (dev->func != did->function)
740                         return 0;
741         }
742
743         if (did->match_flags & PCMCIA_DEV_ID_MATCH_PROD_ID1) {
744                 if (!dev->prod_id[0])
745                         return 0;
746                 if (strcmp(did->prod_id[0], dev->prod_id[0]))
747                         return 0;
748         }
749
750         if (did->match_flags & PCMCIA_DEV_ID_MATCH_PROD_ID2) {
751                 if (!dev->prod_id[1])
752                         return 0;
753                 if (strcmp(did->prod_id[1], dev->prod_id[1]))
754                         return 0;
755         }
756
757         if (did->match_flags & PCMCIA_DEV_ID_MATCH_PROD_ID3) {
758                 if (!dev->prod_id[2])
759                         return 0;
760                 if (strcmp(did->prod_id[2], dev->prod_id[2]))
761                         return 0;
762         }
763
764         if (did->match_flags & PCMCIA_DEV_ID_MATCH_PROD_ID4) {
765                 if (!dev->prod_id[3])
766                         return 0;
767                 if (strcmp(did->prod_id[3], dev->prod_id[3]))
768                         return 0;
769         }
770
771         if (did->match_flags & PCMCIA_DEV_ID_MATCH_DEVICE_NO) {
772                 /* handle pseudo multifunction devices:
773                  * there are at most two pseudo multifunction devices.
774                  * if we're matching against the first, schedule a
775                  * call which will then check whether there are two
776                  * pseudo devices, and if not, add the second one.
777                  */
778                 if (dev->device_no == 0)
779                         pcmcia_add_pseudo_device(dev->socket->pcmcia);
780
781                 if (dev->device_no != did->device_no)
782                         return 0;
783         }
784
785         if (did->match_flags & PCMCIA_DEV_ID_MATCH_FUNC_ID) {
786                 if ((!dev->has_func_id) || (dev->func_id != did->func_id))
787                         return 0;
788
789                 /* if this is a pseudo-multi-function device,
790                  * we need explicit matches */
791                 if (did->match_flags & PCMCIA_DEV_ID_MATCH_DEVICE_NO)
792                         return 0;
793                 if (dev->device_no)
794                         return 0;
795
796                 /* also, FUNC_ID matching needs to be activated by userspace
797                  * after it has re-checked that there is no possible module
798                  * with a prod_id/manf_id/card_id match.
799                  */
800                 if (!dev->allow_func_id_match)
801                         return 0;
802         }
803
804         if (did->match_flags & PCMCIA_DEV_ID_MATCH_FAKE_CIS) {
805                 if (!dev->socket->fake_cis)
806                         pcmcia_load_firmware(dev, did->cisfile);
807
808                 if (!dev->socket->fake_cis)
809                         return 0;
810         }
811
812         if (did->match_flags & PCMCIA_DEV_ID_MATCH_ANONYMOUS) {
813                 int i;
814                 for (i=0; i<4; i++)
815                         if (dev->prod_id[i])
816                                 return 0;
817                 if (dev->has_manf_id || dev->has_card_id || dev->has_func_id)
818                         return 0;
819         }
820
821         dev->dev.driver_data = (void *) did;
822
823         return 1;
824 }
825
826
827 static int pcmcia_bus_match(struct device * dev, struct device_driver * drv) {
828         struct pcmcia_device * p_dev = to_pcmcia_dev(dev);
829         struct pcmcia_driver * p_drv = to_pcmcia_drv(drv);
830         struct pcmcia_device_id *did = p_drv->id_table;
831
832         /* matching by cardmgr */
833         if (p_dev->cardmgr == p_drv)
834                 return 1;
835
836         while (did && did->match_flags) {
837                 if (pcmcia_devmatch(p_dev, did))
838                         return 1;
839                 did++;
840         }
841
842         return 0;
843 }
844
845 #ifdef CONFIG_HOTPLUG
846
847 static int pcmcia_bus_hotplug(struct device *dev, char **envp, int num_envp,
848                               char *buffer, int buffer_size)
849 {
850         struct pcmcia_device *p_dev;
851         int i, length = 0;
852         u32 hash[4] = { 0, 0, 0, 0};
853
854         if (!dev)
855                 return -ENODEV;
856
857         p_dev = to_pcmcia_dev(dev);
858
859         /* calculate hashes */
860         for (i=0; i<4; i++) {
861                 if (!p_dev->prod_id[i])
862                         continue;
863                 hash[i] = crc32(0, p_dev->prod_id[i], strlen(p_dev->prod_id[i]));
864         }
865
866         i = 0;
867
868         if (add_hotplug_env_var(envp, num_envp, &i,
869                                 buffer, buffer_size, &length,
870                                 "SOCKET_NO=%u",
871                                 p_dev->socket->sock))
872                 return -ENOMEM;
873
874         if (add_hotplug_env_var(envp, num_envp, &i,
875                                 buffer, buffer_size, &length,
876                                 "DEVICE_NO=%02X",
877                                 p_dev->device_no))
878                 return -ENOMEM;
879
880         if (add_hotplug_env_var(envp, num_envp, &i,
881                                 buffer, buffer_size, &length,
882                                 "MODALIAS=pcmcia:m%04Xc%04Xf%02Xfn%02Xpfn%02X"
883                                 "pa%08Xpb%08Xpc%08Xpd%08X",
884                                 p_dev->has_manf_id ? p_dev->manf_id : 0,
885                                 p_dev->has_card_id ? p_dev->card_id : 0,
886                                 p_dev->has_func_id ? p_dev->func_id : 0,
887                                 p_dev->func,
888                                 p_dev->device_no,
889                                 hash[0],
890                                 hash[1],
891                                 hash[2],
892                                 hash[3]))
893                 return -ENOMEM;
894
895         envp[i] = NULL;
896
897         return 0;
898 }
899
900 #else
901
902 static int pcmcia_bus_hotplug(struct device *dev, char **envp, int num_envp,
903                               char *buffer, int buffer_size)
904 {
905         return -ENODEV;
906 }
907
908 #endif
909
910 /************************ per-device sysfs output ***************************/
911
912 #define pcmcia_device_attr(field, test, format)                         \
913 static ssize_t field##_show (struct device *dev, struct device_attribute *attr, char *buf)              \
914 {                                                                       \
915         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);               \
916         return p_dev->test ? sprintf (buf, format, p_dev->field) : -ENODEV; \
917 }
918
919 #define pcmcia_device_stringattr(name, field)                                   \
920 static ssize_t name##_show (struct device *dev, struct device_attribute *attr, char *buf)               \
921 {                                                                       \
922         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);               \
923         return p_dev->field ? sprintf (buf, "%s\n", p_dev->field) : -ENODEV; \
924 }
925
926 pcmcia_device_attr(func, socket, "0x%02x\n");
927 pcmcia_device_attr(func_id, has_func_id, "0x%02x\n");
928 pcmcia_device_attr(manf_id, has_manf_id, "0x%04x\n");
929 pcmcia_device_attr(card_id, has_card_id, "0x%04x\n");
930 pcmcia_device_stringattr(prod_id1, prod_id[0]);
931 pcmcia_device_stringattr(prod_id2, prod_id[1]);
932 pcmcia_device_stringattr(prod_id3, prod_id[2]);
933 pcmcia_device_stringattr(prod_id4, prod_id[3]);
934
935
936 static ssize_t pcmcia_store_allow_func_id_match (struct device * dev, struct device_attribute *attr,
937                                                  const char * buf, size_t count)
938 {
939         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);
940         if (!count)
941                 return -EINVAL;
942
943         down(&p_dev->socket->skt_sem);
944         p_dev->allow_func_id_match = 1;
945         up(&p_dev->socket->skt_sem);
946
947         bus_rescan_devices(&pcmcia_bus_type);
948
949         return count;
950 }
951
952 static struct device_attribute pcmcia_dev_attrs[] = {
953         __ATTR(function, 0444, func_show, NULL),
954         __ATTR_RO(func_id),
955         __ATTR_RO(manf_id),
956         __ATTR_RO(card_id),
957         __ATTR_RO(prod_id1),
958         __ATTR_RO(prod_id2),
959         __ATTR_RO(prod_id3),
960         __ATTR_RO(prod_id4),
961         __ATTR(allow_func_id_match, 0200, NULL, pcmcia_store_allow_func_id_match),
962         __ATTR_NULL,
963 };
964
965
966 /*======================================================================
967
968     These manage a ring buffer of events pending for one user process
969     
970 ======================================================================*/
971
972 static int queue_empty(user_info_t *user)
973 {
974     return (user->event_head == user->event_tail);
975 }
976
977 static event_t get_queued_event(user_info_t *user)
978 {
979     user->event_tail = (user->event_tail+1) % MAX_EVENTS;
980     return user->event[user->event_tail];
981 }
982
983 static void queue_event(user_info_t *user, event_t event)
984 {
985     user->event_head = (user->event_head+1) % MAX_EVENTS;
986     if (user->event_head == user->event_tail)
987         user->event_tail = (user->event_tail+1) % MAX_EVENTS;
988     user->event[user->event_head] = event;
989 }
990
991 static void handle_event(struct pcmcia_bus_socket *s, event_t event)
992 {
993     user_info_t *user;
994     for (user = s->user; user; user = user->next)
995         queue_event(user, event);
996     wake_up_interruptible(&s->queue);
997 }
998
999
1000 /*======================================================================
1001
1002     The card status event handler.
1003     
1004 ======================================================================*/
1005
1006 struct send_event_data {
1007         struct pcmcia_socket *skt;
1008         event_t event;
1009         int priority;
1010 };
1011
1012 static int send_event_callback(struct device *dev, void * _data)
1013 {
1014         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);
1015         struct send_event_data *data = _data;
1016
1017         /* we get called for all sockets, but may only pass the event
1018          * for drivers _on the affected socket_ */
1019         if (p_dev->socket != data->skt)
1020                 return 0;
1021
1022         if (p_dev->client.state & (CLIENT_UNBOUND|CLIENT_STALE))
1023                 return 0;
1024
1025         if (p_dev->client.EventMask & data->event)
1026                 return EVENT(&p_dev->client, data->event, data->priority);
1027
1028         return 0;
1029 }
1030
1031 static int send_event(struct pcmcia_socket *s, event_t event, int priority)
1032 {
1033         int ret = 0;
1034         struct send_event_data private;
1035         struct pcmcia_bus_socket *skt = pcmcia_get_bus_socket(s->pcmcia);
1036
1037         if (!skt)
1038                 return 0;
1039
1040         private.skt = s;
1041         private.event = event;
1042         private.priority = priority;
1043
1044         ret = bus_for_each_dev(&pcmcia_bus_type, NULL, &private, send_event_callback);
1045
1046         pcmcia_put_bus_socket(skt);
1047         return ret;
1048 } /* send_event */
1049
1050
1051 /* Normally, the event is passed to individual drivers after
1052  * informing userspace. Only for CS_EVENT_CARD_REMOVAL this
1053  * is inversed to maintain historic compatibility.
1054  */
1055
1056 static int ds_event(struct pcmcia_socket *skt, event_t event, int priority)
1057 {
1058         struct pcmcia_bus_socket *s = skt->pcmcia;
1059         int ret = 0;
1060
1061         ds_dbg(1, "ds_event(0x%06x, %d, 0x%p)\n",
1062                event, priority, s);
1063     
1064         switch (event) {
1065
1066         case CS_EVENT_CARD_REMOVAL:
1067                 s->state &= ~DS_SOCKET_PRESENT;
1068                 send_event(skt, event, priority);
1069                 unbind_request(s);
1070                 handle_event(s, event);
1071                 break;
1072         
1073         case CS_EVENT_CARD_INSERTION:
1074                 s->state |= DS_SOCKET_PRESENT;
1075                 pcmcia_card_add(skt);
1076                 handle_event(s, event);
1077                 break;
1078
1079         case CS_EVENT_EJECTION_REQUEST:
1080                 ret = send_event(skt, event, priority);
1081                 break;
1082
1083         default:
1084                 handle_event(s, event);
1085                 send_event(skt, event, priority);
1086                 break;
1087     }
1088
1089     return 0;
1090 } /* ds_event */
1091
1092
1093 /*======================================================================
1094
1095     bind_request() and bind_device() are merged by now. Register_client()
1096     is called right at the end of bind_request(), during the driver's
1097     ->attach() call. Individual descriptions:
1098
1099     bind_request() connects a socket to a particular client driver.
1100     It looks up the specified device ID in the list of registered
1101     drivers, binds it to the socket, and tries to create an instance
1102     of the device.  unbind_request() deletes a driver instance.
1103     
1104     Bind_device() associates a device driver with a particular socket.
1105     It is normally called by Driver Services after it has identified
1106     a newly inserted card.  An instance of that driver will then be
1107     eligible to register as a client of this socket.
1108
1109     Register_client() uses the dev_info_t handle to match the
1110     caller with a socket.  The driver must have already been bound
1111     to a socket with bind_device() -- in fact, bind_device()
1112     allocates the client structure that will be used.
1113
1114 ======================================================================*/
1115
1116 static int bind_request(struct pcmcia_bus_socket *s, bind_info_t *bind_info)
1117 {
1118         struct pcmcia_driver *p_drv;
1119         struct pcmcia_device *p_dev;
1120         int ret = 0;
1121         unsigned long flags;
1122
1123         s = pcmcia_get_bus_socket(s);
1124         if (!s)
1125                 return -EINVAL;
1126
1127         ds_dbg(2, "bind_request(%d, '%s')\n", s->parent->sock,
1128                (char *)bind_info->dev_info);
1129
1130         p_drv = get_pcmcia_driver(&bind_info->dev_info);
1131         if (!p_drv) {
1132                 ret = -EINVAL;
1133                 goto err_put;
1134         }
1135
1136         if (!try_module_get(p_drv->owner)) {
1137                 ret = -EINVAL;
1138                 goto err_put_driver;
1139         }
1140
1141         spin_lock_irqsave(&pcmcia_dev_list_lock, flags);
1142         list_for_each_entry(p_dev, &s->devices_list, socket_device_list) {
1143                 if (p_dev->func == bind_info->function) {
1144                         if ((p_dev->dev.driver == &p_drv->drv)) {
1145                                 if (p_dev->cardmgr) {
1146                                         /* if there's already a device
1147                                          * registered, and it was registered
1148                                          * by userspace before, we need to
1149                                          * return the "instance". */
1150                                         spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
1151                                         bind_info->instance = p_dev->instance;
1152                                         ret = -EBUSY;
1153                                         goto err_put_module;
1154                                 } else {
1155                                         /* the correct driver managed to bind
1156                                          * itself magically to the correct
1157                                          * device. */
1158                                         spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
1159                                         p_dev->cardmgr = p_drv;
1160                                         ret = 0;
1161                                         goto err_put_module;
1162                                 }
1163                         } else if (!p_dev->dev.driver) {
1164                                 /* there's already a device available where
1165                                  * no device has been bound to yet. So we don't
1166                                  * need to register a device! */
1167                                 spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
1168                                 goto rescan;
1169                         }
1170                 }
1171         }
1172         spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
1173
1174         p_dev = pcmcia_device_add(s, bind_info->function);
1175         if (!p_dev) {
1176                 ret = -EIO;
1177                 goto err_put_module;
1178         }
1179
1180 rescan:
1181         p_dev->cardmgr = p_drv;
1182
1183         /* if a driver is already running, we can abort */
1184         if (p_dev->dev.driver)
1185                 goto err_put_module;
1186
1187         /*
1188          * Prevent this racing with a card insertion.
1189          */
1190         down(&s->parent->skt_sem);
1191         bus_rescan_devices(&pcmcia_bus_type);
1192         up(&s->parent->skt_sem);
1193
1194         /* check whether the driver indeed matched. I don't care if this
1195          * is racy or not, because it can only happen on cardmgr access
1196          * paths...
1197          */
1198         if (!(p_dev->dev.driver == &p_drv->drv))
1199                 p_dev->cardmgr = NULL;
1200
1201  err_put_module:
1202         module_put(p_drv->owner);
1203  err_put_driver:
1204         put_driver(&p_drv->drv);
1205  err_put:
1206         pcmcia_put_bus_socket(s);
1207
1208         return (ret);
1209 } /* bind_request */
1210
1211
1212 int pcmcia_register_client(client_handle_t *handle, client_reg_t *req)
1213 {
1214         client_t *client = NULL;
1215         struct pcmcia_socket *s;
1216         struct pcmcia_bus_socket *skt = NULL;
1217         struct pcmcia_device *p_dev = NULL;
1218
1219         /* Look for unbound client with matching dev_info */
1220         down_read(&pcmcia_socket_list_rwsem);
1221         list_for_each_entry(s, &pcmcia_socket_list, socket_list) {
1222                 unsigned long flags;
1223
1224                 if (s->state & SOCKET_CARDBUS)
1225                         continue;
1226
1227                 skt = s->pcmcia;
1228                 if (!skt)
1229                         continue;
1230                 skt = pcmcia_get_bus_socket(skt);
1231                 if (!skt)
1232                         continue;
1233                 spin_lock_irqsave(&pcmcia_dev_list_lock, flags);
1234                 list_for_each_entry(p_dev, &skt->devices_list, socket_device_list) {
1235                         struct pcmcia_driver *p_drv;
1236                         p_dev = pcmcia_get_dev(p_dev);
1237                         if (!p_dev)
1238                                 continue;
1239                         if (!(p_dev->client.state & CLIENT_UNBOUND) ||
1240                             (!p_dev->dev.driver)) {
1241                                 pcmcia_put_dev(p_dev);
1242                                 continue;
1243                         }
1244                         p_drv = to_pcmcia_drv(p_dev->dev.driver);
1245                         if (!strncmp(p_drv->drv.name, (char *)req->dev_info, DEV_NAME_LEN)) {
1246                                 client = &p_dev->client;
1247                                 spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
1248                                 goto found;
1249                         }
1250                         pcmcia_put_dev(p_dev);
1251                 }
1252                 spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
1253                 pcmcia_put_bus_socket(skt);
1254         }
1255  found:
1256         up_read(&pcmcia_socket_list_rwsem);
1257         if (!p_dev || !client)
1258                 return -ENODEV;
1259
1260         pcmcia_put_bus_socket(skt); /* safe, as we already hold a reference from bind_device */
1261
1262         *handle = client;
1263         client->state &= ~CLIENT_UNBOUND;
1264         client->Socket = s;
1265         client->EventMask = req->EventMask;
1266         client->event_handler = req->event_handler;
1267         client->event_callback_args = req->event_callback_args;
1268         client->event_callback_args.client_handle = client;
1269
1270         if (s->state & SOCKET_CARDBUS)
1271                 client->state |= CLIENT_CARDBUS;
1272
1273         if ((!(s->state & SOCKET_CARDBUS)) && (s->functions == 0) &&
1274             (client->Function != BIND_FN_ALL)) {
1275                 cistpl_longlink_mfc_t mfc;
1276                 if (pccard_read_tuple(s, client->Function, CISTPL_LONGLINK_MFC, &mfc)
1277                     == CS_SUCCESS)
1278                         s->functions = mfc.nfn;
1279                 else
1280                         s->functions = 1;
1281                 s->config = kmalloc(sizeof(config_t) * s->functions,
1282                                     GFP_KERNEL);
1283                 if (!s->config)
1284                         goto out_no_resource;
1285                 memset(s->config, 0, sizeof(config_t) * s->functions);
1286         }
1287
1288         ds_dbg(1, "register_client(): client 0x%p, dev %s\n",
1289                client, p_dev->dev.bus_id);
1290         if (client->EventMask & CS_EVENT_REGISTRATION_COMPLETE)
1291                 EVENT(client, CS_EVENT_REGISTRATION_COMPLETE, CS_EVENT_PRI_LOW);
1292
1293         if ((s->state & (SOCKET_PRESENT|SOCKET_CARDBUS)) == SOCKET_PRESENT) {
1294                 if (client->EventMask & CS_EVENT_CARD_INSERTION)
1295                         EVENT(client, CS_EVENT_CARD_INSERTION, CS_EVENT_PRI_LOW);
1296         }
1297
1298         return CS_SUCCESS;
1299
1300  out_no_resource:
1301         pcmcia_put_dev(p_dev);
1302         return CS_OUT_OF_RESOURCE;
1303 } /* register_client */
1304 EXPORT_SYMBOL(pcmcia_register_client);
1305
1306
1307 /*====================================================================*/
1308
1309 extern struct pci_bus *pcmcia_lookup_bus(struct pcmcia_socket *s);
1310
1311 static int get_device_info(struct pcmcia_bus_socket *s, bind_info_t *bind_info, int first)
1312 {
1313         dev_node_t *node;
1314         struct pcmcia_device *p_dev;
1315         unsigned long flags;
1316         int ret = 0;
1317
1318 #ifdef CONFIG_CARDBUS
1319         /*
1320          * Some unbelievably ugly code to associate the PCI cardbus
1321          * device and its driver with the PCMCIA "bind" information.
1322          */
1323         {
1324                 struct pci_bus *bus;
1325
1326                 bus = pcmcia_lookup_bus(s->parent);
1327                 if (bus) {
1328                         struct list_head *list;
1329                         struct pci_dev *dev = NULL;
1330
1331                         list = bus->devices.next;
1332                         while (list != &bus->devices) {
1333                                 struct pci_dev *pdev = pci_dev_b(list);
1334                                 list = list->next;
1335
1336                                 if (first) {
1337                                         dev = pdev;
1338                                         break;
1339                                 }
1340
1341                                 /* Try to handle "next" here some way? */
1342                         }
1343                         if (dev && dev->driver) {
1344                                 strlcpy(bind_info->name, dev->driver->name, DEV_NAME_LEN);
1345                                 bind_info->major = 0;
1346                                 bind_info->minor = 0;
1347                                 bind_info->next = NULL;
1348                                 return 0;
1349                         }
1350                 }
1351         }
1352 #endif
1353
1354         spin_lock_irqsave(&pcmcia_dev_list_lock, flags);
1355         list_for_each_entry(p_dev, &s->devices_list, socket_device_list) {
1356                 if (p_dev->func == bind_info->function) {
1357                         p_dev = pcmcia_get_dev(p_dev);
1358                         if (!p_dev)
1359                                 continue;
1360                         goto found;
1361                 }
1362         }
1363         spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
1364         return -ENODEV;
1365
1366  found:
1367         spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
1368
1369         if ((!p_dev->instance) ||
1370             (p_dev->instance->state & DEV_CONFIG_PENDING)) {
1371                 ret = -EAGAIN;
1372                 goto err_put;
1373         }
1374
1375         if (first)
1376                 node = p_dev->instance->dev;
1377         else
1378                 for (node = p_dev->instance->dev; node; node = node->next)
1379                         if (node == bind_info->next)
1380                                 break;
1381         if (!node) {
1382                 ret = -ENODEV;
1383                 goto err_put;
1384         }
1385
1386         strlcpy(bind_info->name, node->dev_name, DEV_NAME_LEN);
1387         bind_info->major = node->major;
1388         bind_info->minor = node->minor;
1389         bind_info->next = node->next;
1390
1391  err_put:
1392         pcmcia_put_dev(p_dev);
1393         return (ret);
1394 } /* get_device_info */
1395
1396 /*====================================================================*/
1397
1398 /* unbind _all_ devices attached to a given pcmcia_bus_socket. The
1399  * drivers have been called with EVENT_CARD_REMOVAL before.
1400  */
1401 static int unbind_request(struct pcmcia_bus_socket *s)
1402 {
1403         struct pcmcia_device    *p_dev;
1404         unsigned long           flags;
1405
1406         ds_dbg(2, "unbind_request(%d)\n", s->parent->sock);
1407
1408         s->device_count = 0;
1409
1410         for (;;) {
1411                 /* unregister all pcmcia_devices registered with this socket*/
1412                 spin_lock_irqsave(&pcmcia_dev_list_lock, flags);
1413                 if (list_empty(&s->devices_list)) {
1414                         spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
1415                         return 0;
1416                 }
1417                 p_dev = list_entry((&s->devices_list)->next, struct pcmcia_device, socket_device_list);
1418                 list_del(&p_dev->socket_device_list);
1419                 p_dev->client.state |= CLIENT_STALE;
1420                 spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
1421
1422                 device_unregister(&p_dev->dev);
1423         }
1424
1425         return 0;
1426 } /* unbind_request */
1427
1428 int pcmcia_deregister_client(client_handle_t handle)
1429 {
1430         struct pcmcia_socket *s;
1431         int i;
1432         struct pcmcia_device *p_dev = handle_to_pdev(handle);
1433
1434         if (CHECK_HANDLE(handle))
1435                 return CS_BAD_HANDLE;
1436
1437         s = SOCKET(handle);
1438         ds_dbg(1, "deregister_client(%p)\n", handle);
1439
1440         if (handle->state & (CLIENT_IRQ_REQ|CLIENT_IO_REQ|CLIENT_CONFIG_LOCKED))
1441                 goto warn_out;
1442         for (i = 0; i < MAX_WIN; i++)
1443                 if (handle->state & CLIENT_WIN_REQ(i))
1444                         goto warn_out;
1445
1446         if (handle->state & CLIENT_STALE) {
1447                 handle->client_magic = 0;
1448                 handle->state &= ~CLIENT_STALE;
1449                 pcmcia_put_dev(p_dev);
1450         } else {
1451                 handle->state = CLIENT_UNBOUND;
1452                 handle->event_handler = NULL;
1453         }
1454
1455         return CS_SUCCESS;
1456  warn_out:
1457         printk(KERN_WARNING "ds: deregister_client was called too early.\n");
1458         return CS_IN_USE;
1459 } /* deregister_client */
1460 EXPORT_SYMBOL(pcmcia_deregister_client);
1461
1462
1463 /*======================================================================
1464
1465     The user-mode PC Card device interface
1466
1467 ======================================================================*/
1468
1469 static int ds_open(struct inode *inode, struct file *file)
1470 {
1471     socket_t i = iminor(inode);
1472     struct pcmcia_bus_socket *s;
1473     user_info_t *user;
1474
1475     ds_dbg(0, "ds_open(socket %d)\n", i);
1476
1477     s = get_socket_info_by_nr(i);
1478     if (!s)
1479             return -ENODEV;
1480     s = pcmcia_get_bus_socket(s);
1481     if (!s)
1482             return -ENODEV;
1483
1484     if ((file->f_flags & O_ACCMODE) != O_RDONLY) {
1485             if (s->state & DS_SOCKET_BUSY) {
1486                     pcmcia_put_bus_socket(s);
1487                     return -EBUSY;
1488             }
1489         else
1490             s->state |= DS_SOCKET_BUSY;
1491     }
1492     
1493     user = kmalloc(sizeof(user_info_t), GFP_KERNEL);
1494     if (!user) {
1495             pcmcia_put_bus_socket(s);
1496             return -ENOMEM;
1497     }
1498     user->event_tail = user->event_head = 0;
1499     user->next = s->user;
1500     user->user_magic = USER_MAGIC;
1501     user->socket = s;
1502     s->user = user;
1503     file->private_data = user;
1504     
1505     if (s->state & DS_SOCKET_PRESENT)
1506         queue_event(user, CS_EVENT_CARD_INSERTION);
1507     return 0;
1508 } /* ds_open */
1509
1510 /*====================================================================*/
1511
1512 static int ds_release(struct inode *inode, struct file *file)
1513 {
1514     struct pcmcia_bus_socket *s;
1515     user_info_t *user, **link;
1516
1517     ds_dbg(0, "ds_release(socket %d)\n", iminor(inode));
1518
1519     user = file->private_data;
1520     if (CHECK_USER(user))
1521         goto out;
1522
1523     s = user->socket;
1524
1525     /* Unlink user data structure */
1526     if ((file->f_flags & O_ACCMODE) != O_RDONLY) {
1527         s->state &= ~DS_SOCKET_BUSY;
1528     }
1529     file->private_data = NULL;
1530     for (link = &s->user; *link; link = &(*link)->next)
1531         if (*link == user) break;
1532     if (link == NULL)
1533         goto out;
1534     *link = user->next;
1535     user->user_magic = 0;
1536     kfree(user);
1537     pcmcia_put_bus_socket(s);
1538 out:
1539     return 0;
1540 } /* ds_release */
1541
1542 /*====================================================================*/
1543
1544 static ssize_t ds_read(struct file *file, char __user *buf,
1545                        size_t count, loff_t *ppos)
1546 {
1547     struct pcmcia_bus_socket *s;
1548     user_info_t *user;
1549     int ret;
1550
1551     ds_dbg(2, "ds_read(socket %d)\n", iminor(file->f_dentry->d_inode));
1552     
1553     if (count < 4)
1554         return -EINVAL;
1555
1556     user = file->private_data;
1557     if (CHECK_USER(user))
1558         return -EIO;
1559     
1560     s = user->socket;
1561     if (s->state & DS_SOCKET_DEAD)
1562         return -EIO;
1563
1564     ret = wait_event_interruptible(s->queue, !queue_empty(user));
1565     if (ret == 0)
1566         ret = put_user(get_queued_event(user), (int __user *)buf) ? -EFAULT : 4;
1567
1568     return ret;
1569 } /* ds_read */
1570
1571 /*====================================================================*/
1572
1573 static ssize_t ds_write(struct file *file, const char __user *buf,
1574                         size_t count, loff_t *ppos)
1575 {
1576     ds_dbg(2, "ds_write(socket %d)\n", iminor(file->f_dentry->d_inode));
1577
1578     if (count != 4)
1579         return -EINVAL;
1580     if ((file->f_flags & O_ACCMODE) == O_RDONLY)
1581         return -EBADF;
1582
1583     return -EIO;
1584 } /* ds_write */
1585
1586 /*====================================================================*/
1587
1588 /* No kernel lock - fine */
1589 static u_int ds_poll(struct file *file, poll_table *wait)
1590 {
1591     struct pcmcia_bus_socket *s;
1592     user_info_t *user;
1593
1594     ds_dbg(2, "ds_poll(socket %d)\n", iminor(file->f_dentry->d_inode));
1595     
1596     user = file->private_data;
1597     if (CHECK_USER(user))
1598         return POLLERR;
1599     s = user->socket;
1600     /*
1601      * We don't check for a dead socket here since that
1602      * will send cardmgr into an endless spin.
1603      */
1604     poll_wait(file, &s->queue, wait);
1605     if (!queue_empty(user))
1606         return POLLIN | POLLRDNORM;
1607     return 0;
1608 } /* ds_poll */
1609
1610 /*====================================================================*/
1611
1612 extern int pcmcia_adjust_resource_info(adjust_t *adj);
1613
1614 static int ds_ioctl(struct inode * inode, struct file * file,
1615                     u_int cmd, u_long arg)
1616 {
1617     struct pcmcia_bus_socket *s;
1618     void __user *uarg = (char __user *)arg;
1619     u_int size;
1620     int ret, err;
1621     ds_ioctl_arg_t *buf;
1622     user_info_t *user;
1623
1624     ds_dbg(2, "ds_ioctl(socket %d, %#x, %#lx)\n", iminor(inode), cmd, arg);
1625     
1626     user = file->private_data;
1627     if (CHECK_USER(user))
1628         return -EIO;
1629
1630     s = user->socket;
1631     if (s->state & DS_SOCKET_DEAD)
1632         return -EIO;
1633     
1634     size = (cmd & IOCSIZE_MASK) >> IOCSIZE_SHIFT;
1635     if (size > sizeof(ds_ioctl_arg_t)) return -EINVAL;
1636
1637     /* Permission check */
1638     if (!(cmd & IOC_OUT) && !capable(CAP_SYS_ADMIN))
1639         return -EPERM;
1640         
1641     if (cmd & IOC_IN) {
1642         if (!access_ok(VERIFY_READ, uarg, size)) {
1643             ds_dbg(3, "ds_ioctl(): verify_read = %d\n", -EFAULT);
1644             return -EFAULT;
1645         }
1646     }
1647     if (cmd & IOC_OUT) {
1648         if (!access_ok(VERIFY_WRITE, uarg, size)) {
1649             ds_dbg(3, "ds_ioctl(): verify_write = %d\n", -EFAULT);
1650             return -EFAULT;
1651         }
1652     }
1653     buf = kmalloc(sizeof(ds_ioctl_arg_t), GFP_KERNEL);
1654     if (!buf)
1655         return -ENOMEM;
1656     
1657     err = ret = 0;
1658     
1659     if (cmd & IOC_IN) __copy_from_user((char *)buf, uarg, size);
1660     
1661     switch (cmd) {
1662     case DS_ADJUST_RESOURCE_INFO:
1663         ret = pcmcia_adjust_resource_info(&buf->adjust);
1664         break;
1665     case DS_GET_CARD_SERVICES_INFO:
1666         ret = pcmcia_get_card_services_info(&buf->servinfo);
1667         break;
1668     case DS_GET_CONFIGURATION_INFO:
1669         if (buf->config.Function &&
1670            (buf->config.Function >= s->parent->functions))
1671             ret = CS_BAD_ARGS;
1672         else
1673             ret = pccard_get_configuration_info(s->parent,
1674                         buf->config.Function, &buf->config);
1675         break;
1676     case DS_GET_FIRST_TUPLE:
1677         down(&s->parent->skt_sem);
1678         pcmcia_validate_mem(s->parent);
1679         up(&s->parent->skt_sem);
1680         ret = pccard_get_first_tuple(s->parent, BIND_FN_ALL, &buf->tuple);
1681         break;
1682     case DS_GET_NEXT_TUPLE:
1683         ret = pccard_get_next_tuple(s->parent, BIND_FN_ALL, &buf->tuple);
1684         break;
1685     case DS_GET_TUPLE_DATA:
1686         buf->tuple.TupleData = buf->tuple_parse.data;
1687         buf->tuple.TupleDataMax = sizeof(buf->tuple_parse.data);
1688         ret = pccard_get_tuple_data(s->parent, &buf->tuple);
1689         break;
1690     case DS_PARSE_TUPLE:
1691         buf->tuple.TupleData = buf->tuple_parse.data;
1692         ret = pccard_parse_tuple(&buf->tuple, &buf->tuple_parse.parse);
1693         break;
1694     case DS_RESET_CARD:
1695         ret = pccard_reset_card(s->parent);
1696         break;
1697     case DS_GET_STATUS:
1698         if (buf->status.Function &&
1699            (buf->status.Function >= s->parent->functions))
1700             ret = CS_BAD_ARGS;
1701         else
1702         ret = pccard_get_status(s->parent, buf->status.Function, &buf->status);
1703         break;
1704     case DS_VALIDATE_CIS:
1705         down(&s->parent->skt_sem);
1706         pcmcia_validate_mem(s->parent);
1707         up(&s->parent->skt_sem);
1708         ret = pccard_validate_cis(s->parent, BIND_FN_ALL, &buf->cisinfo);
1709         break;
1710     case DS_SUSPEND_CARD:
1711         ret = pcmcia_suspend_card(s->parent);
1712         break;
1713     case DS_RESUME_CARD:
1714         ret = pcmcia_resume_card(s->parent);
1715         break;
1716     case DS_EJECT_CARD:
1717         err = pcmcia_eject_card(s->parent);
1718         break;
1719     case DS_INSERT_CARD:
1720         err = pcmcia_insert_card(s->parent);
1721         break;
1722     case DS_ACCESS_CONFIGURATION_REGISTER:
1723         if ((buf->conf_reg.Action == CS_WRITE) && !capable(CAP_SYS_ADMIN)) {
1724             err = -EPERM;
1725             goto free_out;
1726         }
1727         if (buf->conf_reg.Function &&
1728            (buf->conf_reg.Function >= s->parent->functions))
1729             ret = CS_BAD_ARGS;
1730         else
1731             ret = pccard_access_configuration_register(s->parent,
1732                         buf->conf_reg.Function, &buf->conf_reg);
1733         break;
1734     case DS_GET_FIRST_REGION:
1735     case DS_GET_NEXT_REGION:
1736     case DS_BIND_MTD:
1737         if (!capable(CAP_SYS_ADMIN)) {
1738                 err = -EPERM;
1739                 goto free_out;
1740         } else {
1741                 static int printed = 0;
1742                 if (!printed) {
1743                         printk(KERN_WARNING "2.6. kernels use pcmciamtd instead of memory_cs.c and do not require special\n");
1744                         printk(KERN_WARNING "MTD handling any more.\n");
1745                         printed++;
1746                 }
1747         }
1748         err = -EINVAL;
1749         goto free_out;
1750         break;
1751     case DS_GET_FIRST_WINDOW:
1752         ret = pcmcia_get_window(s->parent, &buf->win_info.handle, 0,
1753                         &buf->win_info.window);
1754         break;
1755     case DS_GET_NEXT_WINDOW:
1756         ret = pcmcia_get_window(s->parent, &buf->win_info.handle,
1757                         buf->win_info.handle->index + 1, &buf->win_info.window);
1758         break;
1759     case DS_GET_MEM_PAGE:
1760         ret = pcmcia_get_mem_page(buf->win_info.handle,
1761                            &buf->win_info.map);
1762         break;
1763     case DS_REPLACE_CIS:
1764         ret = pcmcia_replace_cis(s->parent, &buf->cisdump);
1765         break;
1766     case DS_BIND_REQUEST:
1767         if (!capable(CAP_SYS_ADMIN)) {
1768                 err = -EPERM;
1769                 goto free_out;
1770         }
1771         err = bind_request(s, &buf->bind_info);
1772         break;
1773     case DS_GET_DEVICE_INFO:
1774         err = get_device_info(s, &buf->bind_info, 1);
1775         break;
1776     case DS_GET_NEXT_DEVICE:
1777         err = get_device_info(s, &buf->bind_info, 0);
1778         break;
1779     case DS_UNBIND_REQUEST:
1780         err = 0;
1781         break;
1782     default:
1783         err = -EINVAL;
1784     }
1785     
1786     if ((err == 0) && (ret != CS_SUCCESS)) {
1787         ds_dbg(2, "ds_ioctl: ret = %d\n", ret);
1788         switch (ret) {
1789         case CS_BAD_SOCKET: case CS_NO_CARD:
1790             err = -ENODEV; break;
1791         case CS_BAD_ARGS: case CS_BAD_ATTRIBUTE: case CS_BAD_IRQ:
1792         case CS_BAD_TUPLE:
1793             err = -EINVAL; break;
1794         case CS_IN_USE:
1795             err = -EBUSY; break;
1796         case CS_OUT_OF_RESOURCE:
1797             err = -ENOSPC; break;
1798         case CS_NO_MORE_ITEMS:
1799             err = -ENODATA; break;
1800         case CS_UNSUPPORTED_FUNCTION:
1801             err = -ENOSYS; break;
1802         default:
1803             err = -EIO; break;
1804         }
1805     }
1806
1807     if (cmd & IOC_OUT) {
1808         if (__copy_to_user(uarg, (char *)buf, size))
1809             err = -EFAULT;
1810     }
1811
1812 free_out:
1813     kfree(buf);
1814     return err;
1815 } /* ds_ioctl */
1816
1817 /*====================================================================*/
1818
1819 static struct file_operations ds_fops = {
1820         .owner          = THIS_MODULE,
1821         .open           = ds_open,
1822         .release        = ds_release,
1823         .ioctl          = ds_ioctl,
1824         .read           = ds_read,
1825         .write          = ds_write,
1826         .poll           = ds_poll,
1827 };
1828
1829 static int __devinit pcmcia_bus_add_socket(struct class_device *class_dev)
1830 {
1831         struct pcmcia_socket *socket = class_get_devdata(class_dev);
1832         struct pcmcia_bus_socket *s;
1833         int ret;
1834
1835         s = kmalloc(sizeof(struct pcmcia_bus_socket), GFP_KERNEL);
1836         if(!s)
1837                 return -ENOMEM;
1838         memset(s, 0, sizeof(struct pcmcia_bus_socket));
1839
1840         /* get reference to parent socket */
1841         s->parent = pcmcia_get_socket(socket);
1842         if (!s->parent) {
1843                 printk(KERN_ERR "PCMCIA obtaining reference to socket %p failed\n", socket);
1844                 kfree (s);
1845                 return -ENODEV;
1846         }
1847
1848         kref_init(&s->refcount);
1849     
1850         /*
1851          * Ugly. But we want to wait for the socket threads to have started up.
1852          * We really should let the drivers themselves drive some of this..
1853          */
1854         msleep(250);
1855
1856         init_waitqueue_head(&s->queue);
1857         INIT_LIST_HEAD(&s->devices_list);
1858         INIT_WORK(&s->device_add, pcmcia_delayed_add_pseudo_device, s);
1859
1860         /* Set up hotline to Card Services */
1861         s->callback.owner = THIS_MODULE;
1862         s->callback.event = &ds_event;
1863         s->callback.resources_done = &pcmcia_card_add;
1864         s->callback.replace_cis = &pcmcia_bus_rescan;
1865         socket->pcmcia = s;
1866
1867         ret = pccard_register_pcmcia(socket, &s->callback);
1868         if (ret) {
1869                 printk(KERN_ERR "PCMCIA registration PCCard core failed for socket %p\n", socket);
1870                 pcmcia_put_bus_socket(s);
1871                 socket->pcmcia = NULL;
1872                 return (ret);
1873         }
1874
1875         return 0;
1876 }
1877
1878
1879 static void pcmcia_bus_remove_socket(struct class_device *class_dev)
1880 {
1881         struct pcmcia_socket *socket = class_get_devdata(class_dev);
1882
1883         if (!socket || !socket->pcmcia)
1884                 return;
1885
1886         pccard_register_pcmcia(socket, NULL);
1887
1888         socket->pcmcia->state |= DS_SOCKET_DEAD;
1889         pcmcia_put_bus_socket(socket->pcmcia);
1890         socket->pcmcia = NULL;
1891
1892         return;
1893 }
1894
1895
1896 /* the pcmcia_bus_interface is used to handle pcmcia socket devices */
1897 static struct class_interface pcmcia_bus_interface = {
1898         .class = &pcmcia_socket_class,
1899         .add = &pcmcia_bus_add_socket,
1900         .remove = &pcmcia_bus_remove_socket,
1901 };
1902
1903
1904 struct bus_type pcmcia_bus_type = {
1905         .name = "pcmcia",
1906         .hotplug = pcmcia_bus_hotplug,
1907         .match = pcmcia_bus_match,
1908         .dev_attrs = pcmcia_dev_attrs,
1909 };
1910 EXPORT_SYMBOL(pcmcia_bus_type);
1911
1912
1913 static int __init init_pcmcia_bus(void)
1914 {
1915         int i;
1916
1917         spin_lock_init(&pcmcia_dev_list_lock);
1918
1919         bus_register(&pcmcia_bus_type);
1920         class_interface_register(&pcmcia_bus_interface);
1921
1922         /* Set up character device for user mode clients */
1923         i = register_chrdev(0, "pcmcia", &ds_fops);
1924         if (i < 0)
1925                 printk(KERN_NOTICE "unable to find a free device # for "
1926                        "Driver Services (error=%d)\n", i);
1927         else
1928                 major_dev = i;
1929
1930 #ifdef CONFIG_PROC_FS
1931         proc_pccard = proc_mkdir("pccard", proc_bus);
1932         if (proc_pccard)
1933                 create_proc_read_entry("drivers",0,proc_pccard,proc_read_drivers,NULL);
1934 #endif
1935
1936         return 0;
1937 }
1938 fs_initcall(init_pcmcia_bus); /* one level after subsys_initcall so that 
1939                                * pcmcia_socket_class is already registered */
1940
1941
1942 static void __exit exit_pcmcia_bus(void)
1943 {
1944         class_interface_unregister(&pcmcia_bus_interface);
1945
1946 #ifdef CONFIG_PROC_FS
1947         if (proc_pccard) {
1948                 remove_proc_entry("drivers", proc_pccard);
1949                 remove_proc_entry("pccard", proc_bus);
1950         }
1951 #endif
1952         if (major_dev != -1)
1953                 unregister_chrdev(major_dev, "pcmcia");
1954
1955         bus_unregister(&pcmcia_bus_type);
1956 }
1957 module_exit(exit_pcmcia_bus);
1958
1959
1960
1961 /* helpers for backwards-compatible functions */
1962
1963 static struct pcmcia_bus_socket * get_socket_info_by_nr(unsigned int nr)
1964 {
1965         struct pcmcia_socket * s = pcmcia_get_socket_by_nr(nr);
1966         if (s && s->pcmcia)
1967                 return s->pcmcia;
1968         else
1969                 return NULL;
1970 }
1971
1972 /* backwards-compatible accessing of driver --- by name! */
1973
1974 static struct pcmcia_driver * get_pcmcia_driver (dev_info_t *dev_info)
1975 {
1976         struct device_driver *drv;
1977         struct pcmcia_driver *p_drv;
1978
1979         drv = driver_find((char *) dev_info, &pcmcia_bus_type);
1980         if (!drv)
1981                 return NULL;
1982
1983         p_drv = container_of(drv, struct pcmcia_driver, drv);
1984
1985         return (p_drv);
1986 }
1987
1988 MODULE_ALIAS("ds");