[PATCH] pcmcia: allow for four multifunction subdevices
[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 - 2006      Dominik Brodowski
14  */
15
16 #include <linux/kernel.h>
17 #include <linux/module.h>
18 #include <linux/init.h>
19 #include <linux/errno.h>
20 #include <linux/list.h>
21 #include <linux/delay.h>
22 #include <linux/workqueue.h>
23 #include <linux/crc32.h>
24 #include <linux/firmware.h>
25 #include <linux/kref.h>
26
27 #define IN_CARD_SERVICES
28 #include <pcmcia/cs_types.h>
29 #include <pcmcia/cs.h>
30 #include <pcmcia/cistpl.h>
31 #include <pcmcia/ds.h>
32 #include <pcmcia/ss.h>
33
34 #include "cs_internal.h"
35 #include "ds_internal.h"
36
37 /*====================================================================*/
38
39 /* Module parameters */
40
41 MODULE_AUTHOR("David Hinds <dahinds@users.sourceforge.net>");
42 MODULE_DESCRIPTION("PCMCIA Driver Services");
43 MODULE_LICENSE("GPL");
44
45 #ifdef DEBUG
46 int ds_pc_debug;
47
48 module_param_named(pc_debug, ds_pc_debug, int, 0644);
49
50 #define ds_dbg(lvl, fmt, arg...) do {                           \
51         if (ds_pc_debug > (lvl))                                        \
52                 printk(KERN_DEBUG "ds: " fmt , ## arg);         \
53 } while (0)
54 #else
55 #define ds_dbg(lvl, fmt, arg...) do { } while (0)
56 #endif
57
58 spinlock_t pcmcia_dev_list_lock;
59
60 /*====================================================================*/
61
62 /* code which was in cs.c before */
63
64 /* String tables for error messages */
65
66 typedef struct lookup_t {
67     int key;
68     char *msg;
69 } lookup_t;
70
71 static const lookup_t error_table[] = {
72     { CS_SUCCESS,               "Operation succeeded" },
73     { CS_BAD_ADAPTER,           "Bad adapter" },
74     { CS_BAD_ATTRIBUTE,         "Bad attribute", },
75     { CS_BAD_BASE,              "Bad base address" },
76     { CS_BAD_EDC,               "Bad EDC" },
77     { CS_BAD_IRQ,               "Bad IRQ" },
78     { CS_BAD_OFFSET,            "Bad offset" },
79     { CS_BAD_PAGE,              "Bad page number" },
80     { CS_READ_FAILURE,          "Read failure" },
81     { CS_BAD_SIZE,              "Bad size" },
82     { CS_BAD_SOCKET,            "Bad socket" },
83     { CS_BAD_TYPE,              "Bad type" },
84     { CS_BAD_VCC,               "Bad Vcc" },
85     { CS_BAD_VPP,               "Bad Vpp" },
86     { CS_BAD_WINDOW,            "Bad window" },
87     { CS_WRITE_FAILURE,         "Write failure" },
88     { CS_NO_CARD,               "No card present" },
89     { CS_UNSUPPORTED_FUNCTION,  "Usupported function" },
90     { CS_UNSUPPORTED_MODE,      "Unsupported mode" },
91     { CS_BAD_SPEED,             "Bad speed" },
92     { CS_BUSY,                  "Resource busy" },
93     { CS_GENERAL_FAILURE,       "General failure" },
94     { CS_WRITE_PROTECTED,       "Write protected" },
95     { CS_BAD_ARG_LENGTH,        "Bad argument length" },
96     { CS_BAD_ARGS,              "Bad arguments" },
97     { CS_CONFIGURATION_LOCKED,  "Configuration locked" },
98     { CS_IN_USE,                "Resource in use" },
99     { CS_NO_MORE_ITEMS,         "No more items" },
100     { CS_OUT_OF_RESOURCE,       "Out of resource" },
101     { CS_BAD_HANDLE,            "Bad handle" },
102     { CS_BAD_TUPLE,             "Bad CIS tuple" }
103 };
104
105
106 static const lookup_t service_table[] = {
107     { AccessConfigurationRegister,      "AccessConfigurationRegister" },
108     { AddSocketServices,                "AddSocketServices" },
109     { AdjustResourceInfo,               "AdjustResourceInfo" },
110     { CheckEraseQueue,                  "CheckEraseQueue" },
111     { CloseMemory,                      "CloseMemory" },
112     { DeregisterClient,                 "DeregisterClient" },
113     { DeregisterEraseQueue,             "DeregisterEraseQueue" },
114     { GetCardServicesInfo,              "GetCardServicesInfo" },
115     { GetClientInfo,                    "GetClientInfo" },
116     { GetConfigurationInfo,             "GetConfigurationInfo" },
117     { GetEventMask,                     "GetEventMask" },
118     { GetFirstClient,                   "GetFirstClient" },
119     { GetFirstRegion,                   "GetFirstRegion" },
120     { GetFirstTuple,                    "GetFirstTuple" },
121     { GetNextClient,                    "GetNextClient" },
122     { GetNextRegion,                    "GetNextRegion" },
123     { GetNextTuple,                     "GetNextTuple" },
124     { GetStatus,                        "GetStatus" },
125     { GetTupleData,                     "GetTupleData" },
126     { MapMemPage,                       "MapMemPage" },
127     { ModifyConfiguration,              "ModifyConfiguration" },
128     { ModifyWindow,                     "ModifyWindow" },
129     { OpenMemory,                       "OpenMemory" },
130     { ParseTuple,                       "ParseTuple" },
131     { ReadMemory,                       "ReadMemory" },
132     { RegisterClient,                   "RegisterClient" },
133     { RegisterEraseQueue,               "RegisterEraseQueue" },
134     { RegisterMTD,                      "RegisterMTD" },
135     { ReleaseConfiguration,             "ReleaseConfiguration" },
136     { ReleaseIO,                        "ReleaseIO" },
137     { ReleaseIRQ,                       "ReleaseIRQ" },
138     { ReleaseWindow,                    "ReleaseWindow" },
139     { RequestConfiguration,             "RequestConfiguration" },
140     { RequestIO,                        "RequestIO" },
141     { RequestIRQ,                       "RequestIRQ" },
142     { RequestSocketMask,                "RequestSocketMask" },
143     { RequestWindow,                    "RequestWindow" },
144     { ResetCard,                        "ResetCard" },
145     { SetEventMask,                     "SetEventMask" },
146     { ValidateCIS,                      "ValidateCIS" },
147     { WriteMemory,                      "WriteMemory" },
148     { BindDevice,                       "BindDevice" },
149     { BindMTD,                          "BindMTD" },
150     { ReportError,                      "ReportError" },
151     { SuspendCard,                      "SuspendCard" },
152     { ResumeCard,                       "ResumeCard" },
153     { EjectCard,                        "EjectCard" },
154     { InsertCard,                       "InsertCard" },
155     { ReplaceCIS,                       "ReplaceCIS" }
156 };
157
158
159 static int pcmcia_report_error(struct pcmcia_device *p_dev, error_info_t *err)
160 {
161         int i;
162         char *serv;
163
164         if (!p_dev)
165                 printk(KERN_NOTICE);
166         else
167                 printk(KERN_NOTICE "%s: ", p_dev->dev.bus_id);
168
169         for (i = 0; i < ARRAY_SIZE(service_table); i++)
170                 if (service_table[i].key == err->func)
171                         break;
172         if (i < ARRAY_SIZE(service_table))
173                 serv = service_table[i].msg;
174         else
175                 serv = "Unknown service number";
176
177         for (i = 0; i < ARRAY_SIZE(error_table); i++)
178                 if (error_table[i].key == err->retcode)
179                         break;
180         if (i < ARRAY_SIZE(error_table))
181                 printk("%s: %s\n", serv, error_table[i].msg);
182         else
183                 printk("%s: Unknown error code %#x\n", serv, err->retcode);
184
185         return CS_SUCCESS;
186 } /* report_error */
187
188 /* end of code which was in cs.c before */
189
190 /*======================================================================*/
191
192 void cs_error(struct pcmcia_device *p_dev, int func, int ret)
193 {
194         error_info_t err = { func, ret };
195         pcmcia_report_error(p_dev, &err);
196 }
197 EXPORT_SYMBOL(cs_error);
198
199
200 static void pcmcia_check_driver(struct pcmcia_driver *p_drv)
201 {
202         struct pcmcia_device_id *did = p_drv->id_table;
203         unsigned int i;
204         u32 hash;
205
206         if (!p_drv->probe || !p_drv->remove)
207                 printk(KERN_DEBUG "pcmcia: %s lacks a requisite callback "
208                        "function\n", p_drv->drv.name);
209
210         while (did && did->match_flags) {
211                 for (i=0; i<4; i++) {
212                         if (!did->prod_id[i])
213                                 continue;
214
215                         hash = crc32(0, did->prod_id[i], strlen(did->prod_id[i]));
216                         if (hash == did->prod_id_hash[i])
217                                 continue;
218
219                         printk(KERN_DEBUG "pcmcia: %s: invalid hash for "
220                                "product string \"%s\": is 0x%x, should "
221                                "be 0x%x\n", p_drv->drv.name, did->prod_id[i],
222                                did->prod_id_hash[i], hash);
223                         printk(KERN_DEBUG "pcmcia: see "
224                                 "Documentation/pcmcia/devicetable.txt for "
225                                 "details\n");
226                 }
227                 did++;
228         }
229
230         return;
231 }
232
233
234 /*======================================================================*/
235
236
237 /**
238  * pcmcia_register_driver - register a PCMCIA driver with the bus core
239  *
240  * Registers a PCMCIA driver with the PCMCIA bus core.
241  */
242 int pcmcia_register_driver(struct pcmcia_driver *driver)
243 {
244         if (!driver)
245                 return -EINVAL;
246
247         pcmcia_check_driver(driver);
248
249         /* initialize common fields */
250         driver->drv.bus = &pcmcia_bus_type;
251         driver->drv.owner = driver->owner;
252
253         return driver_register(&driver->drv);
254 }
255 EXPORT_SYMBOL(pcmcia_register_driver);
256
257 /**
258  * pcmcia_unregister_driver - unregister a PCMCIA driver with the bus core
259  */
260 void pcmcia_unregister_driver(struct pcmcia_driver *driver)
261 {
262         driver_unregister(&driver->drv);
263 }
264 EXPORT_SYMBOL(pcmcia_unregister_driver);
265
266
267 /* pcmcia_device handling */
268
269 struct pcmcia_device * pcmcia_get_dev(struct pcmcia_device *p_dev)
270 {
271         struct device *tmp_dev;
272         tmp_dev = get_device(&p_dev->dev);
273         if (!tmp_dev)
274                 return NULL;
275         return to_pcmcia_dev(tmp_dev);
276 }
277
278 void pcmcia_put_dev(struct pcmcia_device *p_dev)
279 {
280         if (p_dev)
281                 put_device(&p_dev->dev);
282 }
283
284 static void pcmcia_release_function(struct kref *ref)
285 {
286         struct config_t *c = container_of(ref, struct config_t, ref);
287         kfree(c);
288 }
289
290 static void pcmcia_release_dev(struct device *dev)
291 {
292         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);
293         ds_dbg(1, "releasing dev %p\n", p_dev);
294         pcmcia_put_socket(p_dev->socket);
295         kfree(p_dev->devname);
296         kref_put(&p_dev->function_config->ref, pcmcia_release_function);
297         kfree(p_dev);
298 }
299
300 static void pcmcia_add_device_later(struct pcmcia_socket *s, int mfc)
301 {
302         if (!s->pcmcia_state.device_add_pending) {
303                 s->pcmcia_state.device_add_pending = 1;
304                 s->pcmcia_state.mfc_pfc = mfc;
305                 schedule_work(&s->device_add);
306         }
307         return;
308 }
309
310 static int pcmcia_device_probe(struct device * dev)
311 {
312         struct pcmcia_device *p_dev;
313         struct pcmcia_driver *p_drv;
314         struct pcmcia_device_id *did;
315         struct pcmcia_socket *s;
316         int ret = 0;
317
318         dev = get_device(dev);
319         if (!dev)
320                 return -ENODEV;
321
322         p_dev = to_pcmcia_dev(dev);
323         p_drv = to_pcmcia_drv(dev->driver);
324         s = p_dev->socket;
325
326         if ((!p_drv->probe) || (!p_dev->function_config) ||
327             (!try_module_get(p_drv->owner))) {
328                 ret = -EINVAL;
329                 goto put_dev;
330         }
331
332         ret = p_drv->probe(p_dev);
333         if (ret)
334                 goto put_module;
335
336         /* handle pseudo multifunction devices:
337          * there are at most two pseudo multifunction devices.
338          * if we're matching against the first, schedule a
339          * call which will then check whether there are two
340          * pseudo devices, and if not, add the second one.
341          */
342         did = p_dev->dev.driver_data;
343         if (did && (did->match_flags & PCMCIA_DEV_ID_MATCH_DEVICE_NO) &&
344             (p_dev->socket->device_count == 1) && (p_dev->device_no == 0))
345                 pcmcia_add_device_later(p_dev->socket, 0);
346
347  put_module:
348         if (ret)
349                 module_put(p_drv->owner);
350  put_dev:
351         if (ret)
352                 put_device(dev);
353         return (ret);
354 }
355
356
357 /*
358  * Removes a PCMCIA card from the device tree and socket list.
359  */
360 static void pcmcia_card_remove(struct pcmcia_socket *s, struct pcmcia_device *leftover)
361 {
362         struct pcmcia_device    *p_dev;
363         struct pcmcia_device    *tmp;
364         unsigned long           flags;
365
366         ds_dbg(2, "unbind_request(%d)\n", s->sock);
367
368
369         if (!leftover)
370                 s->device_count = 0;
371         else
372                 s->device_count = 1;
373
374         /* unregister all pcmcia_devices registered with this socket, except leftover */
375         list_for_each_entry_safe(p_dev, tmp, &s->devices_list, socket_device_list) {
376                 if (p_dev == leftover)
377                         continue;
378
379                 spin_lock_irqsave(&pcmcia_dev_list_lock, flags);
380                 list_del(&p_dev->socket_device_list);
381                 p_dev->_removed=1;
382                 spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
383
384                 device_unregister(&p_dev->dev);
385         }
386
387         return;
388 }
389
390 static int pcmcia_device_remove(struct device * dev)
391 {
392         struct pcmcia_device *p_dev;
393         struct pcmcia_driver *p_drv;
394         struct pcmcia_device_id *did;
395         int i;
396
397         p_dev = to_pcmcia_dev(dev);
398         p_drv = to_pcmcia_drv(dev->driver);
399
400         /* If we're removing the primary module driving a
401          * pseudo multi-function card, we need to unbind
402          * all devices
403          */
404         did = p_dev->dev.driver_data;
405         if (did && (did->match_flags & PCMCIA_DEV_ID_MATCH_DEVICE_NO) &&
406             (p_dev->socket->device_count != 0) &&
407             (p_dev->device_no == 0))
408                 pcmcia_card_remove(p_dev->socket, p_dev);
409
410         /* detach the "instance" */
411         if (!p_drv)
412                 return 0;
413
414         if (p_drv->remove)
415                 p_drv->remove(p_dev);
416
417         p_dev->dev_node = NULL;
418
419         /* check for proper unloading */
420         if (p_dev->_irq || p_dev->_io || p_dev->_locked)
421                 printk(KERN_INFO "pcmcia: driver %s did not release config properly\n",
422                        p_drv->drv.name);
423
424         for (i = 0; i < MAX_WIN; i++)
425                 if (p_dev->_win & CLIENT_WIN_REQ(i))
426                         printk(KERN_INFO "pcmcia: driver %s did not release windows properly\n",
427                                p_drv->drv.name);
428
429         /* references from pcmcia_probe_device */
430         pcmcia_put_dev(p_dev);
431         module_put(p_drv->owner);
432
433         return 0;
434 }
435
436
437 /*
438  * pcmcia_device_query -- determine information about a pcmcia device
439  */
440 static int pcmcia_device_query(struct pcmcia_device *p_dev)
441 {
442         cistpl_manfid_t manf_id;
443         cistpl_funcid_t func_id;
444         cistpl_vers_1_t *vers1;
445         unsigned int i;
446
447         vers1 = kmalloc(sizeof(*vers1), GFP_KERNEL);
448         if (!vers1)
449                 return -ENOMEM;
450
451         if (!pccard_read_tuple(p_dev->socket, p_dev->func,
452                                CISTPL_MANFID, &manf_id)) {
453                 p_dev->manf_id = manf_id.manf;
454                 p_dev->card_id = manf_id.card;
455                 p_dev->has_manf_id = 1;
456                 p_dev->has_card_id = 1;
457         }
458
459         if (!pccard_read_tuple(p_dev->socket, p_dev->func,
460                                CISTPL_FUNCID, &func_id)) {
461                 p_dev->func_id = func_id.func;
462                 p_dev->has_func_id = 1;
463         } else {
464                 /* rule of thumb: cards with no FUNCID, but with
465                  * common memory device geometry information, are
466                  * probably memory cards (from pcmcia-cs) */
467                 cistpl_device_geo_t *devgeo;
468
469                 devgeo = kmalloc(sizeof(*devgeo), GFP_KERNEL);
470                 if (!devgeo) {
471                         kfree(vers1);
472                         return -ENOMEM;
473                 }
474                 if (!pccard_read_tuple(p_dev->socket, p_dev->func,
475                                       CISTPL_DEVICE_GEO, devgeo)) {
476                         ds_dbg(0, "mem device geometry probably means "
477                                "FUNCID_MEMORY\n");
478                         p_dev->func_id = CISTPL_FUNCID_MEMORY;
479                         p_dev->has_func_id = 1;
480                 }
481                 kfree(devgeo);
482         }
483
484         if (!pccard_read_tuple(p_dev->socket, p_dev->func, CISTPL_VERS_1,
485                                vers1)) {
486                 for (i=0; i < vers1->ns; i++) {
487                         char *tmp;
488                         unsigned int length;
489
490                         tmp = vers1->str + vers1->ofs[i];
491
492                         length = strlen(tmp) + 1;
493                         if ((length < 2) || (length > 255))
494                                 continue;
495
496                         p_dev->prod_id[i] = kmalloc(sizeof(char) * length,
497                                                     GFP_KERNEL);
498                         if (!p_dev->prod_id[i])
499                                 continue;
500
501                         p_dev->prod_id[i] = strncpy(p_dev->prod_id[i],
502                                                     tmp, length);
503                 }
504         }
505
506         kfree(vers1);
507         return 0;
508 }
509
510
511 /* device_add_lock is needed to avoid double registration by cardmgr and kernel.
512  * Serializes pcmcia_device_add; will most likely be removed in future.
513  *
514  * While it has the caveat that adding new PCMCIA devices inside(!) device_register()
515  * won't work, this doesn't matter much at the moment: the driver core doesn't
516  * support it either.
517  */
518 static DEFINE_MUTEX(device_add_lock);
519
520 struct pcmcia_device * pcmcia_device_add(struct pcmcia_socket *s, unsigned int function)
521 {
522         struct pcmcia_device *p_dev, *tmp_dev;
523         unsigned long flags;
524         int bus_id_len;
525
526         s = pcmcia_get_socket(s);
527         if (!s)
528                 return NULL;
529
530         mutex_lock(&device_add_lock);
531
532         /* max of 4 devices per card */
533         if (s->device_count == 4)
534                 goto err_put;
535
536         p_dev = kzalloc(sizeof(struct pcmcia_device), GFP_KERNEL);
537         if (!p_dev)
538                 goto err_put;
539
540         p_dev->socket = s;
541         p_dev->device_no = (s->device_count++);
542         p_dev->func   = function;
543
544         p_dev->dev.bus = &pcmcia_bus_type;
545         p_dev->dev.parent = s->dev.dev;
546         p_dev->dev.release = pcmcia_release_dev;
547         bus_id_len = sprintf (p_dev->dev.bus_id, "%d.%d", p_dev->socket->sock, p_dev->device_no);
548
549         p_dev->devname = kmalloc(6 + bus_id_len + 1, GFP_KERNEL);
550         if (!p_dev->devname)
551                 goto err_free;
552         sprintf (p_dev->devname, "pcmcia%s", p_dev->dev.bus_id);
553
554         /* compat */
555         spin_lock_irqsave(&pcmcia_dev_list_lock, flags);
556
557         /*
558          * p_dev->function_config must be the same for all card functions.
559          * Note that this is serialized by the device_add_lock, so that
560          * only one such struct will be created.
561          */
562         list_for_each_entry(tmp_dev, &s->devices_list, socket_device_list)
563                 if (p_dev->func == tmp_dev->func) {
564                         p_dev->function_config = tmp_dev->function_config;
565                         kref_get(&p_dev->function_config->ref);
566                 }
567
568         /* Add to the list in pcmcia_bus_socket */
569         list_add(&p_dev->socket_device_list, &s->devices_list);
570
571         spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
572
573         if (!p_dev->function_config) {
574                 p_dev->function_config = kzalloc(sizeof(struct config_t),
575                                                  GFP_KERNEL);
576                 if (!p_dev->function_config)
577                         goto err_unreg;
578                 kref_init(&p_dev->function_config->ref);
579         }
580
581         printk(KERN_NOTICE "pcmcia: registering new device %s\n",
582                p_dev->devname);
583
584         pcmcia_device_query(p_dev);
585
586         if (device_register(&p_dev->dev))
587                 goto err_unreg;
588
589         mutex_unlock(&device_add_lock);
590
591         return p_dev;
592
593  err_unreg:
594         spin_lock_irqsave(&pcmcia_dev_list_lock, flags);
595         list_del(&p_dev->socket_device_list);
596         spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
597
598  err_free:
599         kfree(p_dev->devname);
600         kfree(p_dev);
601         s->device_count--;
602  err_put:
603         mutex_unlock(&device_add_lock);
604         pcmcia_put_socket(s);
605
606         return NULL;
607 }
608
609
610 static int pcmcia_card_add(struct pcmcia_socket *s)
611 {
612         cisinfo_t cisinfo;
613         cistpl_longlink_mfc_t mfc;
614         unsigned int no_funcs, i;
615         int ret = 0;
616
617         if (!(s->resource_setup_done))
618                 return -EAGAIN; /* try again, but later... */
619
620         if (pcmcia_validate_mem(s))
621                 return -EAGAIN; /* try again, but later... */
622
623         ret = pccard_validate_cis(s, BIND_FN_ALL, &cisinfo);
624         if (ret || !cisinfo.Chains) {
625                 ds_dbg(0, "invalid CIS or invalid resources\n");
626                 return -ENODEV;
627         }
628
629         if (!pccard_read_tuple(s, BIND_FN_ALL, CISTPL_LONGLINK_MFC, &mfc))
630                 no_funcs = mfc.nfn;
631         else
632                 no_funcs = 1;
633         s->functions = no_funcs;
634
635         for (i=0; i < no_funcs; i++)
636                 pcmcia_device_add(s, i);
637
638         return (ret);
639 }
640
641
642 static void pcmcia_delayed_add_device(void *data)
643 {
644         struct pcmcia_socket *s = data;
645         pcmcia_device_add(s, s->pcmcia_state.mfc_pfc);
646         s->pcmcia_state.device_add_pending = 0;
647         s->pcmcia_state.mfc_pfc = 0;
648 }
649
650 static int pcmcia_requery(struct device *dev, void * _data)
651 {
652         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);
653         if (!p_dev->dev.driver)
654                 pcmcia_device_query(p_dev);
655
656         return 0;
657 }
658
659 static void pcmcia_bus_rescan(struct pcmcia_socket *skt, int new_cis)
660 {
661         int no_devices = 0;
662         int ret = 0;
663         unsigned long flags;
664
665         /* must be called with skt_mutex held */
666         spin_lock_irqsave(&pcmcia_dev_list_lock, flags);
667         if (list_empty(&skt->devices_list))
668                 no_devices = 1;
669         spin_unlock_irqrestore(&pcmcia_dev_list_lock, flags);
670
671         /* If this is because of a CIS override, start over */
672         if (new_cis && !no_devices)
673                 pcmcia_card_remove(skt, NULL);
674
675         /* if no devices were added for this socket yet because of
676          * missing resource information or other trouble, we need to
677          * do this now. */
678         if (no_devices || new_cis) {
679                 ret = pcmcia_card_add(skt);
680                 if (ret)
681                         return;
682         }
683
684         /* some device information might have changed because of a CIS
685          * update or because we can finally read it correctly... so
686          * determine it again, overwriting old values if necessary. */
687         bus_for_each_dev(&pcmcia_bus_type, NULL, NULL, pcmcia_requery);
688
689         /* we re-scan all devices, not just the ones connected to this
690          * socket. This does not matter, though. */
691         ret = bus_rescan_devices(&pcmcia_bus_type);
692         if (ret)
693                 printk(KERN_INFO "pcmcia: bus_rescan_devices failed\n");
694 }
695
696 #ifdef CONFIG_PCMCIA_LOAD_CIS
697
698 /**
699  * pcmcia_load_firmware - load CIS from userspace if device-provided is broken
700  * @dev - the pcmcia device which needs a CIS override
701  * @filename - requested filename in /lib/firmware/
702  *
703  * This uses the in-kernel firmware loading mechanism to use a "fake CIS" if
704  * the one provided by the card is broken. The firmware files reside in
705  * /lib/firmware/ in userspace.
706  */
707 static int pcmcia_load_firmware(struct pcmcia_device *dev, char * filename)
708 {
709         struct pcmcia_socket *s = dev->socket;
710         const struct firmware *fw;
711         char path[20];
712         int ret = -ENOMEM;
713         int no_funcs;
714         int old_funcs;
715         cisdump_t *cis;
716         cistpl_longlink_mfc_t mfc;
717
718         if (!filename)
719                 return -EINVAL;
720
721         ds_dbg(1, "trying to load firmware %s\n", filename);
722
723         if (strlen(filename) > 14)
724                 return -EINVAL;
725
726         snprintf(path, 20, "%s", filename);
727
728         if (request_firmware(&fw, path, &dev->dev) == 0) {
729                 if (fw->size >= CISTPL_MAX_CIS_SIZE)
730                         goto release;
731
732                 cis = kzalloc(sizeof(cisdump_t), GFP_KERNEL);
733                 if (!cis)
734                         goto release;
735
736                 cis->Length = fw->size + 1;
737                 memcpy(cis->Data, fw->data, fw->size);
738
739                 if (!pcmcia_replace_cis(s, cis))
740                         ret = 0;
741
742                 /* update information */
743                 pcmcia_device_query(dev);
744
745                 /* does this cis override add or remove functions? */
746                 old_funcs = s->functions;
747
748                 if (!pccard_read_tuple(s, BIND_FN_ALL, CISTPL_LONGLINK_MFC, &mfc))
749                         no_funcs = mfc.nfn;
750                 else
751                         no_funcs = 1;
752                 s->functions = no_funcs;
753
754                 if (old_funcs > no_funcs)
755                         pcmcia_card_remove(s, dev);
756                 else if (no_funcs > old_funcs)
757                         pcmcia_add_device_later(s, 1);
758         }
759  release:
760         release_firmware(fw);
761
762         return (ret);
763 }
764
765 #else /* !CONFIG_PCMCIA_LOAD_CIS */
766
767 static inline int pcmcia_load_firmware(struct pcmcia_device *dev, char * filename)
768 {
769         return -ENODEV;
770 }
771
772 #endif
773
774
775 static inline int pcmcia_devmatch(struct pcmcia_device *dev,
776                                   struct pcmcia_device_id *did)
777 {
778         if (did->match_flags & PCMCIA_DEV_ID_MATCH_MANF_ID) {
779                 if ((!dev->has_manf_id) || (dev->manf_id != did->manf_id))
780                         return 0;
781         }
782
783         if (did->match_flags & PCMCIA_DEV_ID_MATCH_CARD_ID) {
784                 if ((!dev->has_card_id) || (dev->card_id != did->card_id))
785                         return 0;
786         }
787
788         if (did->match_flags & PCMCIA_DEV_ID_MATCH_FUNCTION) {
789                 if (dev->func != did->function)
790                         return 0;
791         }
792
793         if (did->match_flags & PCMCIA_DEV_ID_MATCH_PROD_ID1) {
794                 if (!dev->prod_id[0])
795                         return 0;
796                 if (strcmp(did->prod_id[0], dev->prod_id[0]))
797                         return 0;
798         }
799
800         if (did->match_flags & PCMCIA_DEV_ID_MATCH_PROD_ID2) {
801                 if (!dev->prod_id[1])
802                         return 0;
803                 if (strcmp(did->prod_id[1], dev->prod_id[1]))
804                         return 0;
805         }
806
807         if (did->match_flags & PCMCIA_DEV_ID_MATCH_PROD_ID3) {
808                 if (!dev->prod_id[2])
809                         return 0;
810                 if (strcmp(did->prod_id[2], dev->prod_id[2]))
811                         return 0;
812         }
813
814         if (did->match_flags & PCMCIA_DEV_ID_MATCH_PROD_ID4) {
815                 if (!dev->prod_id[3])
816                         return 0;
817                 if (strcmp(did->prod_id[3], dev->prod_id[3]))
818                         return 0;
819         }
820
821         if (did->match_flags & PCMCIA_DEV_ID_MATCH_DEVICE_NO) {
822                 if (dev->device_no != did->device_no)
823                         return 0;
824         }
825
826         if (did->match_flags & PCMCIA_DEV_ID_MATCH_FUNC_ID) {
827                 if ((!dev->has_func_id) || (dev->func_id != did->func_id))
828                         return 0;
829
830                 /* if this is a pseudo-multi-function device,
831                  * we need explicit matches */
832                 if (did->match_flags & PCMCIA_DEV_ID_MATCH_DEVICE_NO)
833                         return 0;
834                 if (dev->device_no)
835                         return 0;
836
837                 /* also, FUNC_ID matching needs to be activated by userspace
838                  * after it has re-checked that there is no possible module
839                  * with a prod_id/manf_id/card_id match.
840                  */
841                 if (!dev->allow_func_id_match)
842                         return 0;
843         }
844
845         if (did->match_flags & PCMCIA_DEV_ID_MATCH_FAKE_CIS) {
846                 if (!dev->socket->fake_cis)
847                         pcmcia_load_firmware(dev, did->cisfile);
848
849                 if (!dev->socket->fake_cis)
850                         return 0;
851         }
852
853         if (did->match_flags & PCMCIA_DEV_ID_MATCH_ANONYMOUS) {
854                 int i;
855                 for (i=0; i<4; i++)
856                         if (dev->prod_id[i])
857                                 return 0;
858                 if (dev->has_manf_id || dev->has_card_id || dev->has_func_id)
859                         return 0;
860         }
861
862         dev->dev.driver_data = (void *) did;
863
864         return 1;
865 }
866
867
868 static int pcmcia_bus_match(struct device * dev, struct device_driver * drv) {
869         struct pcmcia_device * p_dev = to_pcmcia_dev(dev);
870         struct pcmcia_driver * p_drv = to_pcmcia_drv(drv);
871         struct pcmcia_device_id *did = p_drv->id_table;
872
873 #ifdef CONFIG_PCMCIA_IOCTL
874         /* matching by cardmgr */
875         if (p_dev->cardmgr == p_drv)
876                 return 1;
877 #endif
878
879         while (did && did->match_flags) {
880                 if (pcmcia_devmatch(p_dev, did))
881                         return 1;
882                 did++;
883         }
884
885         return 0;
886 }
887
888 #ifdef CONFIG_HOTPLUG
889
890 static int pcmcia_bus_uevent(struct device *dev, char **envp, int num_envp,
891                              char *buffer, int buffer_size)
892 {
893         struct pcmcia_device *p_dev;
894         int i, length = 0;
895         u32 hash[4] = { 0, 0, 0, 0};
896
897         if (!dev)
898                 return -ENODEV;
899
900         p_dev = to_pcmcia_dev(dev);
901
902         /* calculate hashes */
903         for (i=0; i<4; i++) {
904                 if (!p_dev->prod_id[i])
905                         continue;
906                 hash[i] = crc32(0, p_dev->prod_id[i], strlen(p_dev->prod_id[i]));
907         }
908
909         i = 0;
910
911         if (add_uevent_var(envp, num_envp, &i,
912                            buffer, buffer_size, &length,
913                            "SOCKET_NO=%u",
914                            p_dev->socket->sock))
915                 return -ENOMEM;
916
917         if (add_uevent_var(envp, num_envp, &i,
918                            buffer, buffer_size, &length,
919                            "DEVICE_NO=%02X",
920                            p_dev->device_no))
921                 return -ENOMEM;
922
923         if (add_uevent_var(envp, num_envp, &i,
924                            buffer, buffer_size, &length,
925                            "MODALIAS=pcmcia:m%04Xc%04Xf%02Xfn%02Xpfn%02X"
926                            "pa%08Xpb%08Xpc%08Xpd%08X",
927                            p_dev->has_manf_id ? p_dev->manf_id : 0,
928                            p_dev->has_card_id ? p_dev->card_id : 0,
929                            p_dev->has_func_id ? p_dev->func_id : 0,
930                            p_dev->func,
931                            p_dev->device_no,
932                            hash[0],
933                            hash[1],
934                            hash[2],
935                            hash[3]))
936                 return -ENOMEM;
937
938         envp[i] = NULL;
939
940         return 0;
941 }
942
943 #else
944
945 static int pcmcia_bus_uevent(struct device *dev, char **envp, int num_envp,
946                               char *buffer, int buffer_size)
947 {
948         return -ENODEV;
949 }
950
951 #endif
952
953 /************************ per-device sysfs output ***************************/
954
955 #define pcmcia_device_attr(field, test, format)                         \
956 static ssize_t field##_show (struct device *dev, struct device_attribute *attr, char *buf)              \
957 {                                                                       \
958         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);               \
959         return p_dev->test ? sprintf (buf, format, p_dev->field) : -ENODEV; \
960 }
961
962 #define pcmcia_device_stringattr(name, field)                                   \
963 static ssize_t name##_show (struct device *dev, struct device_attribute *attr, char *buf)               \
964 {                                                                       \
965         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);               \
966         return p_dev->field ? sprintf (buf, "%s\n", p_dev->field) : -ENODEV; \
967 }
968
969 pcmcia_device_attr(func, socket, "0x%02x\n");
970 pcmcia_device_attr(func_id, has_func_id, "0x%02x\n");
971 pcmcia_device_attr(manf_id, has_manf_id, "0x%04x\n");
972 pcmcia_device_attr(card_id, has_card_id, "0x%04x\n");
973 pcmcia_device_stringattr(prod_id1, prod_id[0]);
974 pcmcia_device_stringattr(prod_id2, prod_id[1]);
975 pcmcia_device_stringattr(prod_id3, prod_id[2]);
976 pcmcia_device_stringattr(prod_id4, prod_id[3]);
977
978
979 static ssize_t pcmcia_show_pm_state(struct device *dev, struct device_attribute *attr, char *buf)
980 {
981         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);
982
983         if (p_dev->suspended)
984                 return sprintf(buf, "off\n");
985         else
986                 return sprintf(buf, "on\n");
987 }
988
989 static ssize_t pcmcia_store_pm_state(struct device *dev, struct device_attribute *attr,
990                                      const char *buf, size_t count)
991 {
992         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);
993         int ret = 0;
994
995         if (!count)
996                 return -EINVAL;
997
998         if ((!p_dev->suspended) && !strncmp(buf, "off", 3))
999                 ret = dpm_runtime_suspend(dev, PMSG_SUSPEND);
1000         else if (p_dev->suspended && !strncmp(buf, "on", 2))
1001                 dpm_runtime_resume(dev);
1002
1003         return ret ? ret : count;
1004 }
1005
1006
1007 static ssize_t modalias_show(struct device *dev, struct device_attribute *attr, char *buf)
1008 {
1009         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);
1010         int i;
1011         u32 hash[4] = { 0, 0, 0, 0};
1012
1013         /* calculate hashes */
1014         for (i=0; i<4; i++) {
1015                 if (!p_dev->prod_id[i])
1016                         continue;
1017                 hash[i] = crc32(0,p_dev->prod_id[i],strlen(p_dev->prod_id[i]));
1018         }
1019         return sprintf(buf, "pcmcia:m%04Xc%04Xf%02Xfn%02Xpfn%02X"
1020                                 "pa%08Xpb%08Xpc%08Xpd%08X\n",
1021                                 p_dev->has_manf_id ? p_dev->manf_id : 0,
1022                                 p_dev->has_card_id ? p_dev->card_id : 0,
1023                                 p_dev->has_func_id ? p_dev->func_id : 0,
1024                                 p_dev->func, p_dev->device_no,
1025                                 hash[0], hash[1], hash[2], hash[3]);
1026 }
1027
1028 static ssize_t pcmcia_store_allow_func_id_match(struct device *dev,
1029                 struct device_attribute *attr, const char *buf, size_t count)
1030 {
1031         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);
1032         int ret;
1033
1034         if (!count)
1035                 return -EINVAL;
1036
1037         mutex_lock(&p_dev->socket->skt_mutex);
1038         p_dev->allow_func_id_match = 1;
1039         mutex_unlock(&p_dev->socket->skt_mutex);
1040
1041         ret = bus_rescan_devices(&pcmcia_bus_type);
1042         if (ret)
1043                 printk(KERN_INFO "pcmcia: bus_rescan_devices failed after "
1044                        "allowing func_id matches\n");
1045
1046         return count;
1047 }
1048
1049 static struct device_attribute pcmcia_dev_attrs[] = {
1050         __ATTR(function, 0444, func_show, NULL),
1051         __ATTR(pm_state, 0644, pcmcia_show_pm_state, pcmcia_store_pm_state),
1052         __ATTR_RO(func_id),
1053         __ATTR_RO(manf_id),
1054         __ATTR_RO(card_id),
1055         __ATTR_RO(prod_id1),
1056         __ATTR_RO(prod_id2),
1057         __ATTR_RO(prod_id3),
1058         __ATTR_RO(prod_id4),
1059         __ATTR_RO(modalias),
1060         __ATTR(allow_func_id_match, 0200, NULL, pcmcia_store_allow_func_id_match),
1061         __ATTR_NULL,
1062 };
1063
1064 /* PM support, also needed for reset */
1065
1066 static int pcmcia_dev_suspend(struct device * dev, pm_message_t state)
1067 {
1068         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);
1069         struct pcmcia_driver *p_drv = NULL;
1070         int ret = 0;
1071
1072         if (dev->driver)
1073                 p_drv = to_pcmcia_drv(dev->driver);
1074
1075         if (!p_drv)
1076                 goto out;
1077
1078         if (p_drv->suspend) {
1079                 ret = p_drv->suspend(p_dev);
1080                 if (ret)
1081                         goto out;
1082         }
1083
1084         if (p_dev->device_no == p_dev->func)
1085                 pcmcia_release_configuration(p_dev);
1086
1087  out:
1088         if (!ret)
1089                 p_dev->suspended = 1;
1090         return ret;
1091 }
1092
1093
1094 static int pcmcia_dev_resume(struct device * dev)
1095 {
1096         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);
1097         struct pcmcia_driver *p_drv = NULL;
1098         int ret = 0;
1099
1100         if (dev->driver)
1101                 p_drv = to_pcmcia_drv(dev->driver);
1102
1103         if (!p_drv)
1104                 goto out;
1105
1106         if (p_dev->device_no == p_dev->func) {
1107                 ret = pcmcia_request_configuration(p_dev, &p_dev->conf);
1108                 if (ret)
1109                         goto out;
1110         }
1111
1112         if (p_drv->resume)
1113                 ret = p_drv->resume(p_dev);
1114
1115  out:
1116         if (!ret)
1117                 p_dev->suspended = 0;
1118         return ret;
1119 }
1120
1121
1122 static int pcmcia_bus_suspend_callback(struct device *dev, void * _data)
1123 {
1124         struct pcmcia_socket *skt = _data;
1125         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);
1126
1127         if (p_dev->socket != skt)
1128                 return 0;
1129
1130         return dpm_runtime_suspend(dev, PMSG_SUSPEND);
1131 }
1132
1133 static int pcmcia_bus_resume_callback(struct device *dev, void * _data)
1134 {
1135         struct pcmcia_socket *skt = _data;
1136         struct pcmcia_device *p_dev = to_pcmcia_dev(dev);
1137
1138         if (p_dev->socket != skt)
1139                 return 0;
1140
1141         dpm_runtime_resume(dev);
1142
1143         return 0;
1144 }
1145
1146 static int pcmcia_bus_resume(struct pcmcia_socket *skt)
1147 {
1148         bus_for_each_dev(&pcmcia_bus_type, NULL, skt, pcmcia_bus_resume_callback);
1149         return 0;
1150 }
1151
1152 static int pcmcia_bus_suspend(struct pcmcia_socket *skt)
1153 {
1154         if (bus_for_each_dev(&pcmcia_bus_type, NULL, skt,
1155                              pcmcia_bus_suspend_callback)) {
1156                 pcmcia_bus_resume(skt);
1157                 return -EIO;
1158         }
1159         return 0;
1160 }
1161
1162
1163 /*======================================================================
1164
1165     The card status event handler.
1166     
1167 ======================================================================*/
1168
1169 /* Normally, the event is passed to individual drivers after
1170  * informing userspace. Only for CS_EVENT_CARD_REMOVAL this
1171  * is inversed to maintain historic compatibility.
1172  */
1173
1174 static int ds_event(struct pcmcia_socket *skt, event_t event, int priority)
1175 {
1176         struct pcmcia_socket *s = pcmcia_get_socket(skt);
1177
1178         if (!s) {
1179                 printk(KERN_ERR "PCMCIA obtaining reference to socket %p " \
1180                         "failed, event 0x%x lost!\n", skt, event);
1181                 return -ENODEV;
1182         }
1183
1184         ds_dbg(1, "ds_event(0x%06x, %d, 0x%p)\n",
1185                event, priority, skt);
1186
1187         switch (event) {
1188         case CS_EVENT_CARD_REMOVAL:
1189                 s->pcmcia_state.present = 0;
1190                 pcmcia_card_remove(skt, NULL);
1191                 handle_event(skt, event);
1192                 break;
1193
1194         case CS_EVENT_CARD_INSERTION:
1195                 s->pcmcia_state.present = 1;
1196                 pcmcia_card_add(skt);
1197                 handle_event(skt, event);
1198                 break;
1199
1200         case CS_EVENT_EJECTION_REQUEST:
1201                 break;
1202
1203         case CS_EVENT_PM_SUSPEND:
1204         case CS_EVENT_PM_RESUME:
1205         case CS_EVENT_RESET_PHYSICAL:
1206         case CS_EVENT_CARD_RESET:
1207         default:
1208                 handle_event(skt, event);
1209                 break;
1210     }
1211
1212     pcmcia_put_socket(s);
1213
1214     return 0;
1215 } /* ds_event */
1216
1217
1218 struct pcmcia_device * pcmcia_dev_present(struct pcmcia_device *_p_dev)
1219 {
1220         struct pcmcia_device *p_dev;
1221         struct pcmcia_device *ret = NULL;
1222
1223         p_dev = pcmcia_get_dev(_p_dev);
1224         if (!p_dev)
1225                 return NULL;
1226
1227         if (!p_dev->socket->pcmcia_state.present)
1228                 goto out;
1229
1230         if (p_dev->_removed)
1231                 goto out;
1232
1233         if (p_dev->suspended)
1234                 goto out;
1235
1236         ret = p_dev;
1237  out:
1238         pcmcia_put_dev(p_dev);
1239         return ret;
1240 }
1241 EXPORT_SYMBOL(pcmcia_dev_present);
1242
1243
1244 static struct pcmcia_callback pcmcia_bus_callback = {
1245         .owner = THIS_MODULE,
1246         .event = ds_event,
1247         .requery = pcmcia_bus_rescan,
1248         .suspend = pcmcia_bus_suspend,
1249         .resume = pcmcia_bus_resume,
1250 };
1251
1252 static int __devinit pcmcia_bus_add_socket(struct class_device *class_dev,
1253                                            struct class_interface *class_intf)
1254 {
1255         struct pcmcia_socket *socket = class_get_devdata(class_dev);
1256         int ret;
1257
1258         socket = pcmcia_get_socket(socket);
1259         if (!socket) {
1260                 printk(KERN_ERR "PCMCIA obtaining reference to socket %p failed\n", socket);
1261                 return -ENODEV;
1262         }
1263
1264         /*
1265          * Ugly. But we want to wait for the socket threads to have started up.
1266          * We really should let the drivers themselves drive some of this..
1267          */
1268         msleep(250);
1269
1270 #ifdef CONFIG_PCMCIA_IOCTL
1271         init_waitqueue_head(&socket->queue);
1272 #endif
1273         INIT_LIST_HEAD(&socket->devices_list);
1274         INIT_WORK(&socket->device_add, pcmcia_delayed_add_device, socket);
1275         memset(&socket->pcmcia_state, 0, sizeof(u8));
1276         socket->device_count = 0;
1277
1278         ret = pccard_register_pcmcia(socket, &pcmcia_bus_callback);
1279         if (ret) {
1280                 printk(KERN_ERR "PCMCIA registration PCCard core failed for socket %p\n", socket);
1281                 pcmcia_put_socket(socket);
1282                 return (ret);
1283         }
1284
1285         return 0;
1286 }
1287
1288 static void pcmcia_bus_remove_socket(struct class_device *class_dev,
1289                                      struct class_interface *class_intf)
1290 {
1291         struct pcmcia_socket *socket = class_get_devdata(class_dev);
1292
1293         if (!socket)
1294                 return;
1295
1296         socket->pcmcia_state.dead = 1;
1297         pccard_register_pcmcia(socket, NULL);
1298
1299         /* unregister any unbound devices */
1300         mutex_lock(&socket->skt_mutex);
1301         pcmcia_card_remove(socket, NULL);
1302         mutex_unlock(&socket->skt_mutex);
1303
1304         pcmcia_put_socket(socket);
1305
1306         return;
1307 }
1308
1309
1310 /* the pcmcia_bus_interface is used to handle pcmcia socket devices */
1311 static struct class_interface pcmcia_bus_interface = {
1312         .class = &pcmcia_socket_class,
1313         .add = &pcmcia_bus_add_socket,
1314         .remove = &pcmcia_bus_remove_socket,
1315 };
1316
1317
1318 struct bus_type pcmcia_bus_type = {
1319         .name = "pcmcia",
1320         .uevent = pcmcia_bus_uevent,
1321         .match = pcmcia_bus_match,
1322         .dev_attrs = pcmcia_dev_attrs,
1323         .probe = pcmcia_device_probe,
1324         .remove = pcmcia_device_remove,
1325         .suspend = pcmcia_dev_suspend,
1326         .resume = pcmcia_dev_resume,
1327 };
1328
1329
1330 static int __init init_pcmcia_bus(void)
1331 {
1332         int ret;
1333
1334         spin_lock_init(&pcmcia_dev_list_lock);
1335
1336         ret = bus_register(&pcmcia_bus_type);
1337         if (ret < 0) {
1338                 printk(KERN_WARNING "pcmcia: bus_register error: %d\n", ret);
1339                 return ret;
1340         }
1341         ret = class_interface_register(&pcmcia_bus_interface);
1342         if (ret < 0) {
1343                 printk(KERN_WARNING
1344                         "pcmcia: class_interface_register error: %d\n", ret);
1345                 bus_unregister(&pcmcia_bus_type);
1346                 return ret;
1347         }
1348
1349         pcmcia_setup_ioctl();
1350
1351         return 0;
1352 }
1353 fs_initcall(init_pcmcia_bus); /* one level after subsys_initcall so that 
1354                                * pcmcia_socket_class is already registered */
1355
1356
1357 static void __exit exit_pcmcia_bus(void)
1358 {
1359         pcmcia_cleanup_ioctl();
1360
1361         class_interface_unregister(&pcmcia_bus_interface);
1362
1363         bus_unregister(&pcmcia_bus_type);
1364 }
1365 module_exit(exit_pcmcia_bus);
1366
1367
1368 MODULE_ALIAS("ds");