Merge master.kernel.org:/pub/scm/linux/kernel/git/davem/net-2.6
[sfrench/cifs-2.6.git] / drivers / net / wireless / airo.c
1 /*======================================================================
2
3     Aironet driver for 4500 and 4800 series cards
4
5     This code is released under both the GPL version 2 and BSD licenses.
6     Either license may be used.  The respective licenses are found at
7     the end of this file.
8
9     This code was developed by Benjamin Reed <breed@users.sourceforge.net>
10     including portions of which come from the Aironet PC4500
11     Developer's Reference Manual and used with permission.  Copyright
12     (C) 1999 Benjamin Reed.  All Rights Reserved.  Permission to use
13     code in the Developer's manual was granted for this driver by
14     Aironet.  Major code contributions were received from Javier Achirica
15     <achirica@users.sourceforge.net> and Jean Tourrilhes <jt@hpl.hp.com>.
16     Code was also integrated from the Cisco Aironet driver for Linux.
17     Support for MPI350 cards was added by Fabrice Bellet
18     <fabrice@bellet.info>.
19
20 ======================================================================*/
21
22 #include <linux/config.h>
23 #include <linux/init.h>
24
25 #include <linux/kernel.h>
26 #include <linux/module.h>
27 #include <linux/proc_fs.h>
28 #include <linux/smp_lock.h>
29
30 #include <linux/sched.h>
31 #include <linux/ptrace.h>
32 #include <linux/slab.h>
33 #include <linux/string.h>
34 #include <linux/timer.h>
35 #include <linux/interrupt.h>
36 #include <linux/in.h>
37 #include <linux/bitops.h>
38 #include <asm/io.h>
39 #include <asm/system.h>
40
41 #include <linux/netdevice.h>
42 #include <linux/etherdevice.h>
43 #include <linux/skbuff.h>
44 #include <linux/if_arp.h>
45 #include <linux/ioport.h>
46 #include <linux/pci.h>
47 #include <asm/uaccess.h>
48
49 #ifdef CONFIG_PCI
50 static struct pci_device_id card_ids[] = {
51         { 0x14b9, 1, PCI_ANY_ID, PCI_ANY_ID, },
52         { 0x14b9, 0x4500, PCI_ANY_ID, PCI_ANY_ID },
53         { 0x14b9, 0x4800, PCI_ANY_ID, PCI_ANY_ID, },
54         { 0x14b9, 0x0340, PCI_ANY_ID, PCI_ANY_ID, },
55         { 0x14b9, 0x0350, PCI_ANY_ID, PCI_ANY_ID, },
56         { 0x14b9, 0x5000, PCI_ANY_ID, PCI_ANY_ID, },
57         { 0x14b9, 0xa504, PCI_ANY_ID, PCI_ANY_ID, },
58         { 0, }
59 };
60 MODULE_DEVICE_TABLE(pci, card_ids);
61
62 static int airo_pci_probe(struct pci_dev *, const struct pci_device_id *);
63 static void airo_pci_remove(struct pci_dev *);
64 static int airo_pci_suspend(struct pci_dev *pdev, pm_message_t state);
65 static int airo_pci_resume(struct pci_dev *pdev);
66
67 static struct pci_driver airo_driver = {
68         .name     = "airo",
69         .id_table = card_ids,
70         .probe    = airo_pci_probe,
71         .remove   = __devexit_p(airo_pci_remove),
72         .suspend  = airo_pci_suspend,
73         .resume   = airo_pci_resume,
74 };
75 #endif /* CONFIG_PCI */
76
77 /* Include Wireless Extension definition and check version - Jean II */
78 #include <linux/wireless.h>
79 #define WIRELESS_SPY            // enable iwspy support
80 #include <net/iw_handler.h>     // New driver API
81
82 #define CISCO_EXT               // enable Cisco extensions
83 #ifdef CISCO_EXT
84 #include <linux/delay.h>
85 #endif
86
87 /* Support Cisco MIC feature */
88 #define MICSUPPORT
89
90 #if defined(MICSUPPORT) && !defined(CONFIG_CRYPTO)
91 #warning MIC support requires Crypto API
92 #undef MICSUPPORT
93 #endif
94
95 /* Hack to do some power saving */
96 #define POWER_ON_DOWN
97
98 /* As you can see this list is HUGH!
99    I really don't know what a lot of these counts are about, but they
100    are all here for completeness.  If the IGNLABEL macro is put in
101    infront of the label, that statistic will not be included in the list
102    of statistics in the /proc filesystem */
103
104 #define IGNLABEL(comment) NULL
105 static char *statsLabels[] = {
106         "RxOverrun",
107         IGNLABEL("RxPlcpCrcErr"),
108         IGNLABEL("RxPlcpFormatErr"),
109         IGNLABEL("RxPlcpLengthErr"),
110         "RxMacCrcErr",
111         "RxMacCrcOk",
112         "RxWepErr",
113         "RxWepOk",
114         "RetryLong",
115         "RetryShort",
116         "MaxRetries",
117         "NoAck",
118         "NoCts",
119         "RxAck",
120         "RxCts",
121         "TxAck",
122         "TxRts",
123         "TxCts",
124         "TxMc",
125         "TxBc",
126         "TxUcFrags",
127         "TxUcPackets",
128         "TxBeacon",
129         "RxBeacon",
130         "TxSinColl",
131         "TxMulColl",
132         "DefersNo",
133         "DefersProt",
134         "DefersEngy",
135         "DupFram",
136         "RxFragDisc",
137         "TxAged",
138         "RxAged",
139         "LostSync-MaxRetry",
140         "LostSync-MissedBeacons",
141         "LostSync-ArlExceeded",
142         "LostSync-Deauth",
143         "LostSync-Disassoced",
144         "LostSync-TsfTiming",
145         "HostTxMc",
146         "HostTxBc",
147         "HostTxUc",
148         "HostTxFail",
149         "HostRxMc",
150         "HostRxBc",
151         "HostRxUc",
152         "HostRxDiscard",
153         IGNLABEL("HmacTxMc"),
154         IGNLABEL("HmacTxBc"),
155         IGNLABEL("HmacTxUc"),
156         IGNLABEL("HmacTxFail"),
157         IGNLABEL("HmacRxMc"),
158         IGNLABEL("HmacRxBc"),
159         IGNLABEL("HmacRxUc"),
160         IGNLABEL("HmacRxDiscard"),
161         IGNLABEL("HmacRxAccepted"),
162         "SsidMismatch",
163         "ApMismatch",
164         "RatesMismatch",
165         "AuthReject",
166         "AuthTimeout",
167         "AssocReject",
168         "AssocTimeout",
169         IGNLABEL("ReasonOutsideTable"),
170         IGNLABEL("ReasonStatus1"),
171         IGNLABEL("ReasonStatus2"),
172         IGNLABEL("ReasonStatus3"),
173         IGNLABEL("ReasonStatus4"),
174         IGNLABEL("ReasonStatus5"),
175         IGNLABEL("ReasonStatus6"),
176         IGNLABEL("ReasonStatus7"),
177         IGNLABEL("ReasonStatus8"),
178         IGNLABEL("ReasonStatus9"),
179         IGNLABEL("ReasonStatus10"),
180         IGNLABEL("ReasonStatus11"),
181         IGNLABEL("ReasonStatus12"),
182         IGNLABEL("ReasonStatus13"),
183         IGNLABEL("ReasonStatus14"),
184         IGNLABEL("ReasonStatus15"),
185         IGNLABEL("ReasonStatus16"),
186         IGNLABEL("ReasonStatus17"),
187         IGNLABEL("ReasonStatus18"),
188         IGNLABEL("ReasonStatus19"),
189         "RxMan",
190         "TxMan",
191         "RxRefresh",
192         "TxRefresh",
193         "RxPoll",
194         "TxPoll",
195         "HostRetries",
196         "LostSync-HostReq",
197         "HostTxBytes",
198         "HostRxBytes",
199         "ElapsedUsec",
200         "ElapsedSec",
201         "LostSyncBetterAP",
202         "PrivacyMismatch",
203         "Jammed",
204         "DiscRxNotWepped",
205         "PhyEleMismatch",
206         (char*)-1 };
207 #ifndef RUN_AT
208 #define RUN_AT(x) (jiffies+(x))
209 #endif
210
211
212 /* These variables are for insmod, since it seems that the rates
213    can only be set in setup_card.  Rates should be a comma separated
214    (no spaces) list of rates (up to 8). */
215
216 static int rates[8];
217 static int basic_rate;
218 static char *ssids[3];
219
220 static int io[4];
221 static int irq[4];
222
223 static
224 int maxencrypt /* = 0 */; /* The highest rate that the card can encrypt at.
225                        0 means no limit.  For old cards this was 4 */
226
227 static int auto_wep /* = 0 */; /* If set, it tries to figure out the wep mode */
228 static int aux_bap /* = 0 */; /* Checks to see if the aux ports are needed to read
229                     the bap, needed on some older cards and buses. */
230 static int adhoc;
231
232 static int probe = 1;
233
234 static int proc_uid /* = 0 */;
235
236 static int proc_gid /* = 0 */;
237
238 static int airo_perm = 0555;
239
240 static int proc_perm = 0644;
241
242 MODULE_AUTHOR("Benjamin Reed");
243 MODULE_DESCRIPTION("Support for Cisco/Aironet 802.11 wireless ethernet \
244                    cards.  Direct support for ISA/PCI/MPI cards and support \
245                    for PCMCIA when used with airo_cs.");
246 MODULE_LICENSE("Dual BSD/GPL");
247 MODULE_SUPPORTED_DEVICE("Aironet 4500, 4800 and Cisco 340/350");
248 module_param_array(io, int, NULL, 0);
249 module_param_array(irq, int, NULL, 0);
250 module_param(basic_rate, int, 0);
251 module_param_array(rates, int, NULL, 0);
252 module_param_array(ssids, charp, NULL, 0);
253 module_param(auto_wep, int, 0);
254 MODULE_PARM_DESC(auto_wep, "If non-zero, the driver will keep looping through \
255 the authentication options until an association is made.  The value of \
256 auto_wep is number of the wep keys to check.  A value of 2 will try using \
257 the key at index 0 and index 1.");
258 module_param(aux_bap, int, 0);
259 MODULE_PARM_DESC(aux_bap, "If non-zero, the driver will switch into a mode \
260 than seems to work better for older cards with some older buses.  Before \
261 switching it checks that the switch is needed.");
262 module_param(maxencrypt, int, 0);
263 MODULE_PARM_DESC(maxencrypt, "The maximum speed that the card can do \
264 encryption.  Units are in 512kbs.  Zero (default) means there is no limit. \
265 Older cards used to be limited to 2mbs (4).");
266 module_param(adhoc, int, 0);
267 MODULE_PARM_DESC(adhoc, "If non-zero, the card will start in adhoc mode.");
268 module_param(probe, int, 0);
269 MODULE_PARM_DESC(probe, "If zero, the driver won't start the card.");
270
271 module_param(proc_uid, int, 0);
272 MODULE_PARM_DESC(proc_uid, "The uid that the /proc files will belong to.");
273 module_param(proc_gid, int, 0);
274 MODULE_PARM_DESC(proc_gid, "The gid that the /proc files will belong to.");
275 module_param(airo_perm, int, 0);
276 MODULE_PARM_DESC(airo_perm, "The permission bits of /proc/[driver/]aironet.");
277 module_param(proc_perm, int, 0);
278 MODULE_PARM_DESC(proc_perm, "The permission bits of the files in /proc");
279
280 /* This is a kind of sloppy hack to get this information to OUT4500 and
281    IN4500.  I would be extremely interested in the situation where this
282    doesn't work though!!! */
283 static int do8bitIO = 0;
284
285 /* Return codes */
286 #define SUCCESS 0
287 #define ERROR -1
288 #define NO_PACKET -2
289
290 /* Commands */
291 #define NOP2            0x0000
292 #define MAC_ENABLE      0x0001
293 #define MAC_DISABLE     0x0002
294 #define CMD_LOSE_SYNC   0x0003 /* Not sure what this does... */
295 #define CMD_SOFTRESET   0x0004
296 #define HOSTSLEEP       0x0005
297 #define CMD_MAGIC_PKT   0x0006
298 #define CMD_SETWAKEMASK 0x0007
299 #define CMD_READCFG     0x0008
300 #define CMD_SETMODE     0x0009
301 #define CMD_ALLOCATETX  0x000a
302 #define CMD_TRANSMIT    0x000b
303 #define CMD_DEALLOCATETX 0x000c
304 #define NOP             0x0010
305 #define CMD_WORKAROUND  0x0011
306 #define CMD_ALLOCATEAUX 0x0020
307 #define CMD_ACCESS      0x0021
308 #define CMD_PCIBAP      0x0022
309 #define CMD_PCIAUX      0x0023
310 #define CMD_ALLOCBUF    0x0028
311 #define CMD_GETTLV      0x0029
312 #define CMD_PUTTLV      0x002a
313 #define CMD_DELTLV      0x002b
314 #define CMD_FINDNEXTTLV 0x002c
315 #define CMD_PSPNODES    0x0030
316 #define CMD_SETCW       0x0031    
317 #define CMD_SETPCF      0x0032    
318 #define CMD_SETPHYREG   0x003e
319 #define CMD_TXTEST      0x003f
320 #define MAC_ENABLETX    0x0101
321 #define CMD_LISTBSS     0x0103
322 #define CMD_SAVECFG     0x0108
323 #define CMD_ENABLEAUX   0x0111
324 #define CMD_WRITERID    0x0121
325 #define CMD_USEPSPNODES 0x0130
326 #define MAC_ENABLERX    0x0201
327
328 /* Command errors */
329 #define ERROR_QUALIF 0x00
330 #define ERROR_ILLCMD 0x01
331 #define ERROR_ILLFMT 0x02
332 #define ERROR_INVFID 0x03
333 #define ERROR_INVRID 0x04
334 #define ERROR_LARGE 0x05
335 #define ERROR_NDISABL 0x06
336 #define ERROR_ALLOCBSY 0x07
337 #define ERROR_NORD 0x0B
338 #define ERROR_NOWR 0x0C
339 #define ERROR_INVFIDTX 0x0D
340 #define ERROR_TESTACT 0x0E
341 #define ERROR_TAGNFND 0x12
342 #define ERROR_DECODE 0x20
343 #define ERROR_DESCUNAV 0x21
344 #define ERROR_BADLEN 0x22
345 #define ERROR_MODE 0x80
346 #define ERROR_HOP 0x81
347 #define ERROR_BINTER 0x82
348 #define ERROR_RXMODE 0x83
349 #define ERROR_MACADDR 0x84
350 #define ERROR_RATES 0x85
351 #define ERROR_ORDER 0x86
352 #define ERROR_SCAN 0x87
353 #define ERROR_AUTH 0x88
354 #define ERROR_PSMODE 0x89
355 #define ERROR_RTYPE 0x8A
356 #define ERROR_DIVER 0x8B
357 #define ERROR_SSID 0x8C
358 #define ERROR_APLIST 0x8D
359 #define ERROR_AUTOWAKE 0x8E
360 #define ERROR_LEAP 0x8F
361
362 /* Registers */
363 #define COMMAND 0x00
364 #define PARAM0 0x02
365 #define PARAM1 0x04
366 #define PARAM2 0x06
367 #define STATUS 0x08
368 #define RESP0 0x0a
369 #define RESP1 0x0c
370 #define RESP2 0x0e
371 #define LINKSTAT 0x10
372 #define SELECT0 0x18
373 #define OFFSET0 0x1c
374 #define RXFID 0x20
375 #define TXALLOCFID 0x22
376 #define TXCOMPLFID 0x24
377 #define DATA0 0x36
378 #define EVSTAT 0x30
379 #define EVINTEN 0x32
380 #define EVACK 0x34
381 #define SWS0 0x28
382 #define SWS1 0x2a
383 #define SWS2 0x2c
384 #define SWS3 0x2e
385 #define AUXPAGE 0x3A
386 #define AUXOFF 0x3C
387 #define AUXDATA 0x3E
388
389 #define FID_TX 1
390 #define FID_RX 2
391 /* Offset into aux memory for descriptors */
392 #define AUX_OFFSET 0x800
393 /* Size of allocated packets */
394 #define PKTSIZE 1840
395 #define RIDSIZE 2048
396 /* Size of the transmit queue */
397 #define MAXTXQ 64
398
399 /* BAP selectors */
400 #define BAP0 0 // Used for receiving packets
401 #define BAP1 2 // Used for xmiting packets and working with RIDS
402
403 /* Flags */
404 #define COMMAND_BUSY 0x8000
405
406 #define BAP_BUSY 0x8000
407 #define BAP_ERR 0x4000
408 #define BAP_DONE 0x2000
409
410 #define PROMISC 0xffff
411 #define NOPROMISC 0x0000
412
413 #define EV_CMD 0x10
414 #define EV_CLEARCOMMANDBUSY 0x4000
415 #define EV_RX 0x01
416 #define EV_TX 0x02
417 #define EV_TXEXC 0x04
418 #define EV_ALLOC 0x08
419 #define EV_LINK 0x80
420 #define EV_AWAKE 0x100
421 #define EV_TXCPY 0x400
422 #define EV_UNKNOWN 0x800
423 #define EV_MIC 0x1000 /* Message Integrity Check Interrupt */
424 #define EV_AWAKEN 0x2000
425 #define STATUS_INTS (EV_AWAKE|EV_LINK|EV_TXEXC|EV_TX|EV_TXCPY|EV_RX|EV_MIC)
426
427 #ifdef CHECK_UNKNOWN_INTS
428 #define IGNORE_INTS ( EV_CMD | EV_UNKNOWN)
429 #else
430 #define IGNORE_INTS (~STATUS_INTS)
431 #endif
432
433 /* RID TYPES */
434 #define RID_RW 0x20
435
436 /* The RIDs */
437 #define RID_CAPABILITIES 0xFF00
438 #define RID_APINFO     0xFF01
439 #define RID_RADIOINFO  0xFF02
440 #define RID_UNKNOWN3   0xFF03
441 #define RID_RSSI       0xFF04
442 #define RID_CONFIG     0xFF10
443 #define RID_SSID       0xFF11
444 #define RID_APLIST     0xFF12
445 #define RID_DRVNAME    0xFF13
446 #define RID_ETHERENCAP 0xFF14
447 #define RID_WEP_TEMP   0xFF15
448 #define RID_WEP_PERM   0xFF16
449 #define RID_MODULATION 0xFF17
450 #define RID_OPTIONS    0xFF18
451 #define RID_ACTUALCONFIG 0xFF20 /*readonly*/
452 #define RID_FACTORYCONFIG 0xFF21
453 #define RID_UNKNOWN22  0xFF22
454 #define RID_LEAPUSERNAME 0xFF23
455 #define RID_LEAPPASSWORD 0xFF24
456 #define RID_STATUS     0xFF50
457 #define RID_BEACON_HST 0xFF51
458 #define RID_BUSY_HST   0xFF52
459 #define RID_RETRIES_HST 0xFF53
460 #define RID_UNKNOWN54  0xFF54
461 #define RID_UNKNOWN55  0xFF55
462 #define RID_UNKNOWN56  0xFF56
463 #define RID_MIC        0xFF57
464 #define RID_STATS16    0xFF60
465 #define RID_STATS16DELTA 0xFF61
466 #define RID_STATS16DELTACLEAR 0xFF62
467 #define RID_STATS      0xFF68
468 #define RID_STATSDELTA 0xFF69
469 #define RID_STATSDELTACLEAR 0xFF6A
470 #define RID_ECHOTEST_RID 0xFF70
471 #define RID_ECHOTEST_RESULTS 0xFF71
472 #define RID_BSSLISTFIRST 0xFF72
473 #define RID_BSSLISTNEXT  0xFF73
474
475 typedef struct {
476         u16 cmd;
477         u16 parm0;
478         u16 parm1;
479         u16 parm2;
480 } Cmd;
481
482 typedef struct {
483         u16 status;
484         u16 rsp0;
485         u16 rsp1;
486         u16 rsp2;
487 } Resp;
488
489 /*
490  * Rids and endian-ness:  The Rids will always be in cpu endian, since
491  * this all the patches from the big-endian guys end up doing that.
492  * so all rid access should use the read/writeXXXRid routines.
493  */
494
495 /* This is redundant for x86 archs, but it seems necessary for ARM */
496 #pragma pack(1)
497
498 /* This structure came from an email sent to me from an engineer at
499    aironet for inclusion into this driver */
500 typedef struct {
501         u16 len;
502         u16 kindex;
503         u8 mac[ETH_ALEN];
504         u16 klen;
505         u8 key[16];
506 } WepKeyRid;
507
508 /* These structures are from the Aironet's PC4500 Developers Manual */
509 typedef struct {
510         u16 len;
511         u8 ssid[32];
512 } Ssid;
513
514 typedef struct {
515         u16 len;
516         Ssid ssids[3];
517 } SsidRid;
518
519 typedef struct {
520         u16 len;
521         u16 modulation;
522 #define MOD_DEFAULT 0
523 #define MOD_CCK 1
524 #define MOD_MOK 2
525 } ModulationRid;
526
527 typedef struct {
528         u16 len; /* sizeof(ConfigRid) */
529         u16 opmode; /* operating mode */
530 #define MODE_STA_IBSS 0
531 #define MODE_STA_ESS 1
532 #define MODE_AP 2
533 #define MODE_AP_RPTR 3
534 #define MODE_ETHERNET_HOST (0<<8) /* rx payloads converted */
535 #define MODE_LLC_HOST (1<<8) /* rx payloads left as is */
536 #define MODE_AIRONET_EXTEND (1<<9) /* enable Aironet extenstions */
537 #define MODE_AP_INTERFACE (1<<10) /* enable ap interface extensions */
538 #define MODE_ANTENNA_ALIGN (1<<11) /* enable antenna alignment */
539 #define MODE_ETHER_LLC (1<<12) /* enable ethernet LLC */
540 #define MODE_LEAF_NODE (1<<13) /* enable leaf node bridge */
541 #define MODE_CF_POLLABLE (1<<14) /* enable CF pollable */
542 #define MODE_MIC (1<<15) /* enable MIC */
543         u16 rmode; /* receive mode */
544 #define RXMODE_BC_MC_ADDR 0
545 #define RXMODE_BC_ADDR 1 /* ignore multicasts */
546 #define RXMODE_ADDR 2 /* ignore multicast and broadcast */
547 #define RXMODE_RFMON 3 /* wireless monitor mode */
548 #define RXMODE_RFMON_ANYBSS 4
549 #define RXMODE_LANMON 5 /* lan style monitor -- data packets only */
550 #define RXMODE_DISABLE_802_3_HEADER (1<<8) /* disables 802.3 header on rx */
551 #define RXMODE_NORMALIZED_RSSI (1<<9) /* return normalized RSSI */
552         u16 fragThresh;
553         u16 rtsThres;
554         u8 macAddr[ETH_ALEN];
555         u8 rates[8];
556         u16 shortRetryLimit;
557         u16 longRetryLimit;
558         u16 txLifetime; /* in kusec */
559         u16 rxLifetime; /* in kusec */
560         u16 stationary;
561         u16 ordering;
562         u16 u16deviceType; /* for overriding device type */
563         u16 cfpRate;
564         u16 cfpDuration;
565         u16 _reserved1[3];
566         /*---------- Scanning/Associating ----------*/
567         u16 scanMode;
568 #define SCANMODE_ACTIVE 0
569 #define SCANMODE_PASSIVE 1
570 #define SCANMODE_AIROSCAN 2
571         u16 probeDelay; /* in kusec */
572         u16 probeEnergyTimeout; /* in kusec */
573         u16 probeResponseTimeout;
574         u16 beaconListenTimeout;
575         u16 joinNetTimeout;
576         u16 authTimeout;
577         u16 authType;
578 #define AUTH_OPEN 0x1
579 #define AUTH_ENCRYPT 0x101
580 #define AUTH_SHAREDKEY 0x102
581 #define AUTH_ALLOW_UNENCRYPTED 0x200
582         u16 associationTimeout;
583         u16 specifiedApTimeout;
584         u16 offlineScanInterval;
585         u16 offlineScanDuration;
586         u16 linkLossDelay;
587         u16 maxBeaconLostTime;
588         u16 refreshInterval;
589 #define DISABLE_REFRESH 0xFFFF
590         u16 _reserved1a[1];
591         /*---------- Power save operation ----------*/
592         u16 powerSaveMode;
593 #define POWERSAVE_CAM 0
594 #define POWERSAVE_PSP 1
595 #define POWERSAVE_PSPCAM 2
596         u16 sleepForDtims;
597         u16 listenInterval;
598         u16 fastListenInterval;
599         u16 listenDecay;
600         u16 fastListenDelay;
601         u16 _reserved2[2];
602         /*---------- Ap/Ibss config items ----------*/
603         u16 beaconPeriod;
604         u16 atimDuration;
605         u16 hopPeriod;
606         u16 channelSet;
607         u16 channel;
608         u16 dtimPeriod;
609         u16 bridgeDistance;
610         u16 radioID;
611         /*---------- Radio configuration ----------*/
612         u16 radioType;
613 #define RADIOTYPE_DEFAULT 0
614 #define RADIOTYPE_802_11 1
615 #define RADIOTYPE_LEGACY 2
616         u8 rxDiversity;
617         u8 txDiversity;
618         u16 txPower;
619 #define TXPOWER_DEFAULT 0
620         u16 rssiThreshold;
621 #define RSSI_DEFAULT 0
622         u16 modulation;
623 #define PREAMBLE_AUTO 0
624 #define PREAMBLE_LONG 1
625 #define PREAMBLE_SHORT 2
626         u16 preamble;
627         u16 homeProduct;
628         u16 radioSpecific;
629         /*---------- Aironet Extensions ----------*/
630         u8 nodeName[16];
631         u16 arlThreshold;
632         u16 arlDecay;
633         u16 arlDelay;
634         u16 _reserved4[1];
635         /*---------- Aironet Extensions ----------*/
636         u8 magicAction;
637 #define MAGIC_ACTION_STSCHG 1
638 #define MAGIC_ACTION_RESUME 2
639 #define MAGIC_IGNORE_MCAST (1<<8)
640 #define MAGIC_IGNORE_BCAST (1<<9)
641 #define MAGIC_SWITCH_TO_PSP (0<<10)
642 #define MAGIC_STAY_IN_CAM (1<<10)
643         u8 magicControl;
644         u16 autoWake;
645 } ConfigRid;
646
647 typedef struct {
648         u16 len;
649         u8 mac[ETH_ALEN];
650         u16 mode;
651         u16 errorCode;
652         u16 sigQuality;
653         u16 SSIDlen;
654         char SSID[32];
655         char apName[16];
656         u8 bssid[4][ETH_ALEN];
657         u16 beaconPeriod;
658         u16 dimPeriod;
659         u16 atimDuration;
660         u16 hopPeriod;
661         u16 channelSet;
662         u16 channel;
663         u16 hopsToBackbone;
664         u16 apTotalLoad;
665         u16 generatedLoad;
666         u16 accumulatedArl;
667         u16 signalQuality;
668         u16 currentXmitRate;
669         u16 apDevExtensions;
670         u16 normalizedSignalStrength;
671         u16 shortPreamble;
672         u8 apIP[4];
673         u8 noisePercent; /* Noise percent in last second */
674         u8 noisedBm; /* Noise dBm in last second */
675         u8 noiseAvePercent; /* Noise percent in last minute */
676         u8 noiseAvedBm; /* Noise dBm in last minute */
677         u8 noiseMaxPercent; /* Highest noise percent in last minute */
678         u8 noiseMaxdBm; /* Highest noise dbm in last minute */
679         u16 load;
680         u8 carrier[4];
681         u16 assocStatus;
682 #define STAT_NOPACKETS 0
683 #define STAT_NOCARRIERSET 10
684 #define STAT_GOTCARRIERSET 11
685 #define STAT_WRONGSSID 20
686 #define STAT_BADCHANNEL 25
687 #define STAT_BADBITRATES 30
688 #define STAT_BADPRIVACY 35
689 #define STAT_APFOUND 40
690 #define STAT_APREJECTED 50
691 #define STAT_AUTHENTICATING 60
692 #define STAT_DEAUTHENTICATED 61
693 #define STAT_AUTHTIMEOUT 62
694 #define STAT_ASSOCIATING 70
695 #define STAT_DEASSOCIATED 71
696 #define STAT_ASSOCTIMEOUT 72
697 #define STAT_NOTAIROAP 73
698 #define STAT_ASSOCIATED 80
699 #define STAT_LEAPING 90
700 #define STAT_LEAPFAILED 91
701 #define STAT_LEAPTIMEDOUT 92
702 #define STAT_LEAPCOMPLETE 93
703 } StatusRid;
704
705 typedef struct {
706         u16 len;
707         u16 spacer;
708         u32 vals[100];
709 } StatsRid;
710
711
712 typedef struct {
713         u16 len;
714         u8 ap[4][ETH_ALEN];
715 } APListRid;
716
717 typedef struct {
718         u16 len;
719         char oui[3];
720         char zero;
721         u16 prodNum;
722         char manName[32];
723         char prodName[16];
724         char prodVer[8];
725         char factoryAddr[ETH_ALEN];
726         char aironetAddr[ETH_ALEN];
727         u16 radioType;
728         u16 country;
729         char callid[ETH_ALEN];
730         char supportedRates[8];
731         char rxDiversity;
732         char txDiversity;
733         u16 txPowerLevels[8];
734         u16 hardVer;
735         u16 hardCap;
736         u16 tempRange;
737         u16 softVer;
738         u16 softSubVer;
739         u16 interfaceVer;
740         u16 softCap;
741         u16 bootBlockVer;
742         u16 requiredHard;
743         u16 extSoftCap;
744 } CapabilityRid;
745
746 typedef struct {
747   u16 len;
748   u16 index; /* First is 0 and 0xffff means end of list */
749 #define RADIO_FH 1 /* Frequency hopping radio type */
750 #define RADIO_DS 2 /* Direct sequence radio type */
751 #define RADIO_TMA 4 /* Proprietary radio used in old cards (2500) */
752   u16 radioType;
753   u8 bssid[ETH_ALEN]; /* Mac address of the BSS */
754   u8 zero;
755   u8 ssidLen;
756   u8 ssid[32];
757   u16 dBm;
758 #define CAP_ESS (1<<0)
759 #define CAP_IBSS (1<<1)
760 #define CAP_PRIVACY (1<<4)
761 #define CAP_SHORTHDR (1<<5)
762   u16 cap;
763   u16 beaconInterval;
764   u8 rates[8]; /* Same as rates for config rid */
765   struct { /* For frequency hopping only */
766     u16 dwell;
767     u8 hopSet;
768     u8 hopPattern;
769     u8 hopIndex;
770     u8 fill;
771   } fh;
772   u16 dsChannel;
773   u16 atimWindow;
774 } BSSListRid;
775
776 typedef struct {
777   u8 rssipct;
778   u8 rssidBm;
779 } tdsRssiEntry;
780
781 typedef struct {
782   u16 len;
783   tdsRssiEntry x[256];
784 } tdsRssiRid;
785
786 typedef struct {
787         u16 len;
788         u16 state;
789         u16 multicastValid;
790         u8  multicast[16];
791         u16 unicastValid;
792         u8  unicast[16];
793 } MICRid;
794
795 typedef struct {
796         u16 typelen;
797
798         union {
799             u8 snap[8];
800             struct {
801                 u8 dsap;
802                 u8 ssap;
803                 u8 control;
804                 u8 orgcode[3];
805                 u8 fieldtype[2];
806             } llc;
807         } u;
808         u32 mic;
809         u32 seq;
810 } MICBuffer;
811
812 typedef struct {
813         u8 da[ETH_ALEN];
814         u8 sa[ETH_ALEN];
815 } etherHead;
816
817 #pragma pack()
818
819 #define TXCTL_TXOK (1<<1) /* report if tx is ok */
820 #define TXCTL_TXEX (1<<2) /* report if tx fails */
821 #define TXCTL_802_3 (0<<3) /* 802.3 packet */
822 #define TXCTL_802_11 (1<<3) /* 802.11 mac packet */
823 #define TXCTL_ETHERNET (0<<4) /* payload has ethertype */
824 #define TXCTL_LLC (1<<4) /* payload is llc */
825 #define TXCTL_RELEASE (0<<5) /* release after completion */
826 #define TXCTL_NORELEASE (1<<5) /* on completion returns to host */
827
828 #define BUSY_FID 0x10000
829
830 #ifdef CISCO_EXT
831 #define AIROMAGIC       0xa55a
832 /* Warning : SIOCDEVPRIVATE may disapear during 2.5.X - Jean II */
833 #ifdef SIOCIWFIRSTPRIV
834 #ifdef SIOCDEVPRIVATE
835 #define AIROOLDIOCTL    SIOCDEVPRIVATE
836 #define AIROOLDIDIFC    AIROOLDIOCTL + 1
837 #endif /* SIOCDEVPRIVATE */
838 #else /* SIOCIWFIRSTPRIV */
839 #define SIOCIWFIRSTPRIV SIOCDEVPRIVATE
840 #endif /* SIOCIWFIRSTPRIV */
841 /* This may be wrong. When using the new SIOCIWFIRSTPRIV range, we probably
842  * should use only "GET" ioctls (last bit set to 1). "SET" ioctls are root
843  * only and don't return the modified struct ifreq to the application which
844  * is usually a problem. - Jean II */
845 #define AIROIOCTL       SIOCIWFIRSTPRIV
846 #define AIROIDIFC       AIROIOCTL + 1
847
848 /* Ioctl constants to be used in airo_ioctl.command */
849
850 #define AIROGCAP                0       // Capability rid
851 #define AIROGCFG                1       // USED A LOT
852 #define AIROGSLIST              2       // System ID list
853 #define AIROGVLIST              3       // List of specified AP's
854 #define AIROGDRVNAM             4       //  NOTUSED
855 #define AIROGEHTENC             5       // NOTUSED
856 #define AIROGWEPKTMP            6
857 #define AIROGWEPKNV             7
858 #define AIROGSTAT               8
859 #define AIROGSTATSC32           9
860 #define AIROGSTATSD32           10
861 #define AIROGMICRID             11
862 #define AIROGMICSTATS           12
863 #define AIROGFLAGS              13
864 #define AIROGID                 14
865 #define AIRORRID                15
866 #define AIRORSWVERSION          17
867
868 /* Leave gap of 40 commands after AIROGSTATSD32 for future */
869
870 #define AIROPCAP                AIROGSTATSD32 + 40
871 #define AIROPVLIST              AIROPCAP      + 1
872 #define AIROPSLIST              AIROPVLIST    + 1
873 #define AIROPCFG                AIROPSLIST    + 1
874 #define AIROPSIDS               AIROPCFG      + 1
875 #define AIROPAPLIST             AIROPSIDS     + 1
876 #define AIROPMACON              AIROPAPLIST   + 1       /* Enable mac  */
877 #define AIROPMACOFF             AIROPMACON    + 1       /* Disable mac */
878 #define AIROPSTCLR              AIROPMACOFF   + 1
879 #define AIROPWEPKEY             AIROPSTCLR    + 1
880 #define AIROPWEPKEYNV           AIROPWEPKEY   + 1
881 #define AIROPLEAPPWD            AIROPWEPKEYNV + 1
882 #define AIROPLEAPUSR            AIROPLEAPPWD  + 1
883
884 /* Flash codes */
885
886 #define AIROFLSHRST            AIROPWEPKEYNV  + 40
887 #define AIROFLSHGCHR           AIROFLSHRST    + 1
888 #define AIROFLSHSTFL           AIROFLSHGCHR   + 1
889 #define AIROFLSHPCHR           AIROFLSHSTFL   + 1
890 #define AIROFLPUTBUF           AIROFLSHPCHR   + 1
891 #define AIRORESTART            AIROFLPUTBUF   + 1
892
893 #define FLASHSIZE       32768
894 #define AUXMEMSIZE      (256 * 1024)
895
896 typedef struct aironet_ioctl {
897         unsigned short command;         // What to do
898         unsigned short len;             // Len of data
899         unsigned short ridnum;          // rid number
900         unsigned char __user *data;     // d-data
901 } aironet_ioctl;
902
903 static char swversion[] = "2.1";
904 #endif /* CISCO_EXT */
905
906 #define NUM_MODULES       2
907 #define MIC_MSGLEN_MAX    2400
908 #define EMMH32_MSGLEN_MAX MIC_MSGLEN_MAX
909
910 typedef struct {
911         u32   size;            // size
912         u8    enabled;         // MIC enabled or not
913         u32   rxSuccess;       // successful packets received
914         u32   rxIncorrectMIC;  // pkts dropped due to incorrect MIC comparison
915         u32   rxNotMICed;      // pkts dropped due to not being MIC'd
916         u32   rxMICPlummed;    // pkts dropped due to not having a MIC plummed
917         u32   rxWrongSequence; // pkts dropped due to sequence number violation
918         u32   reserve[32];
919 } mic_statistics;
920
921 typedef struct {
922         u32 coeff[((EMMH32_MSGLEN_MAX)+3)>>2];
923         u64 accum;      // accumulated mic, reduced to u32 in final()
924         int position;   // current position (byte offset) in message
925         union {
926                 u8  d8[4];
927                 u32 d32;
928         } part; // saves partial message word across update() calls
929 } emmh32_context;
930
931 typedef struct {
932         emmh32_context seed;        // Context - the seed
933         u32              rx;        // Received sequence number
934         u32              tx;        // Tx sequence number
935         u32              window;    // Start of window
936         u8               valid;     // Flag to say if context is valid or not
937         u8               key[16];
938 } miccntx;
939
940 typedef struct {
941         miccntx mCtx;           // Multicast context
942         miccntx uCtx;           // Unicast context
943 } mic_module;
944
945 typedef struct {
946         unsigned int  rid: 16;
947         unsigned int  len: 15;
948         unsigned int  valid: 1;
949         dma_addr_t host_addr;
950 } Rid;
951
952 typedef struct {
953         unsigned int  offset: 15;
954         unsigned int  eoc: 1;
955         unsigned int  len: 15;
956         unsigned int  valid: 1;
957         dma_addr_t host_addr;
958 } TxFid;
959
960 typedef struct {
961         unsigned int  ctl: 15;
962         unsigned int  rdy: 1;
963         unsigned int  len: 15;
964         unsigned int  valid: 1;
965         dma_addr_t host_addr;
966 } RxFid;
967
968 /*
969  * Host receive descriptor
970  */
971 typedef struct {
972         unsigned char __iomem *card_ram_off; /* offset into card memory of the
973                                                 desc */
974         RxFid         rx_desc;               /* card receive descriptor */
975         char          *virtual_host_addr;    /* virtual address of host receive
976                                                 buffer */
977         int           pending;
978 } HostRxDesc;
979
980 /*
981  * Host transmit descriptor
982  */
983 typedef struct {
984         unsigned char __iomem *card_ram_off;         /* offset into card memory of the
985                                                 desc */
986         TxFid         tx_desc;               /* card transmit descriptor */
987         char          *virtual_host_addr;    /* virtual address of host receive
988                                                 buffer */
989         int           pending;
990 } HostTxDesc;
991
992 /*
993  * Host RID descriptor
994  */
995 typedef struct {
996         unsigned char __iomem *card_ram_off;      /* offset into card memory of the
997                                              descriptor */
998         Rid           rid_desc;           /* card RID descriptor */
999         char          *virtual_host_addr; /* virtual address of host receive
1000                                              buffer */
1001 } HostRidDesc;
1002
1003 typedef struct {
1004         u16 sw0;
1005         u16 sw1;
1006         u16 status;
1007         u16 len;
1008 #define HOST_SET (1 << 0)
1009 #define HOST_INT_TX (1 << 1) /* Interrupt on successful TX */
1010 #define HOST_INT_TXERR (1 << 2) /* Interrupt on unseccessful TX */
1011 #define HOST_LCC_PAYLOAD (1 << 4) /* LLC payload, 0 = Ethertype */
1012 #define HOST_DONT_RLSE (1 << 5) /* Don't release buffer when done */
1013 #define HOST_DONT_RETRY (1 << 6) /* Don't retry trasmit */
1014 #define HOST_CLR_AID (1 << 7) /* clear AID failure */
1015 #define HOST_RTS (1 << 9) /* Force RTS use */
1016 #define HOST_SHORT (1 << 10) /* Do short preamble */
1017         u16 ctl;
1018         u16 aid;
1019         u16 retries;
1020         u16 fill;
1021 } TxCtlHdr;
1022
1023 typedef struct {
1024         u16 ctl;
1025         u16 duration;
1026         char addr1[6];
1027         char addr2[6];
1028         char addr3[6];
1029         u16 seq;
1030         char addr4[6];
1031 } WifiHdr;
1032
1033
1034 typedef struct {
1035         TxCtlHdr ctlhdr;
1036         u16 fill1;
1037         u16 fill2;
1038         WifiHdr wifihdr;
1039         u16 gaplen;
1040         u16 status;
1041 } WifiCtlHdr;
1042
1043 static WifiCtlHdr wifictlhdr8023 = {
1044         .ctlhdr = {
1045                 .ctl    = HOST_DONT_RLSE,
1046         }
1047 };
1048
1049 #ifdef WIRELESS_EXT
1050 // Frequency list (map channels to frequencies)
1051 static const long frequency_list[] = { 2412, 2417, 2422, 2427, 2432, 2437, 2442,
1052                                 2447, 2452, 2457, 2462, 2467, 2472, 2484 };
1053
1054 // A few details needed for WEP (Wireless Equivalent Privacy)
1055 #define MAX_KEY_SIZE 13                 // 128 (?) bits
1056 #define MIN_KEY_SIZE  5                 // 40 bits RC4 - WEP
1057 typedef struct wep_key_t {
1058         u16     len;
1059         u8      key[16];        /* 40-bit and 104-bit keys */
1060 } wep_key_t;
1061
1062 /* Backward compatibility */
1063 #ifndef IW_ENCODE_NOKEY
1064 #define IW_ENCODE_NOKEY         0x0800  /* Key is write only, so not present */
1065 #define IW_ENCODE_MODE  (IW_ENCODE_DISABLED | IW_ENCODE_RESTRICTED | IW_ENCODE_OPEN)
1066 #endif /* IW_ENCODE_NOKEY */
1067
1068 /* List of Wireless Handlers (new API) */
1069 static const struct iw_handler_def      airo_handler_def;
1070 #endif /* WIRELESS_EXT */
1071
1072 static const char version[] = "airo.c 0.6 (Ben Reed & Javier Achirica)";
1073
1074 struct airo_info;
1075
1076 static int get_dec_u16( char *buffer, int *start, int limit );
1077 static void OUT4500( struct airo_info *, u16 register, u16 value );
1078 static unsigned short IN4500( struct airo_info *, u16 register );
1079 static u16 setup_card(struct airo_info*, u8 *mac, int lock);
1080 static int enable_MAC( struct airo_info *ai, Resp *rsp, int lock );
1081 static void disable_MAC(struct airo_info *ai, int lock);
1082 static void enable_interrupts(struct airo_info*);
1083 static void disable_interrupts(struct airo_info*);
1084 static u16 issuecommand(struct airo_info*, Cmd *pCmd, Resp *pRsp);
1085 static int bap_setup(struct airo_info*, u16 rid, u16 offset, int whichbap);
1086 static int aux_bap_read(struct airo_info*, u16 *pu16Dst, int bytelen,
1087                         int whichbap);
1088 static int fast_bap_read(struct airo_info*, u16 *pu16Dst, int bytelen,
1089                          int whichbap);
1090 static int bap_write(struct airo_info*, const u16 *pu16Src, int bytelen,
1091                      int whichbap);
1092 static int PC4500_accessrid(struct airo_info*, u16 rid, u16 accmd);
1093 static int PC4500_readrid(struct airo_info*, u16 rid, void *pBuf, int len, int lock);
1094 static int PC4500_writerid(struct airo_info*, u16 rid, const void
1095                            *pBuf, int len, int lock);
1096 static int do_writerid( struct airo_info*, u16 rid, const void *rid_data,
1097                         int len, int dummy );
1098 static u16 transmit_allocate(struct airo_info*, int lenPayload, int raw);
1099 static int transmit_802_3_packet(struct airo_info*, int len, char *pPacket);
1100 static int transmit_802_11_packet(struct airo_info*, int len, char *pPacket);
1101
1102 static int mpi_send_packet (struct net_device *dev);
1103 static void mpi_unmap_card(struct pci_dev *pci);
1104 static void mpi_receive_802_3(struct airo_info *ai);
1105 static void mpi_receive_802_11(struct airo_info *ai);
1106 static int waitbusy (struct airo_info *ai);
1107
1108 static irqreturn_t airo_interrupt( int irq, void* dev_id, struct pt_regs
1109                             *regs);
1110 static int airo_thread(void *data);
1111 static void timer_func( struct net_device *dev );
1112 static int airo_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
1113 #ifdef WIRELESS_EXT
1114 static struct iw_statistics *airo_get_wireless_stats (struct net_device *dev);
1115 static void airo_read_wireless_stats (struct airo_info *local);
1116 #endif /* WIRELESS_EXT */
1117 #ifdef CISCO_EXT
1118 static int readrids(struct net_device *dev, aironet_ioctl *comp);
1119 static int writerids(struct net_device *dev, aironet_ioctl *comp);
1120 static int flashcard(struct net_device *dev, aironet_ioctl *comp);
1121 #endif /* CISCO_EXT */
1122 #ifdef MICSUPPORT
1123 static void micinit(struct airo_info *ai);
1124 static int micsetup(struct airo_info *ai);
1125 static int encapsulate(struct airo_info *ai, etherHead *pPacket, MICBuffer *buffer, int len);
1126 static int decapsulate(struct airo_info *ai, MICBuffer *mic, etherHead *pPacket, u16 payLen);
1127
1128 static u8 airo_rssi_to_dbm (tdsRssiEntry *rssi_rid, u8 rssi);
1129 static u8 airo_dbm_to_pct (tdsRssiEntry *rssi_rid, u8 dbm);
1130
1131 #include <linux/crypto.h>
1132 #endif
1133
1134 struct airo_info {
1135         struct net_device_stats stats;
1136         struct net_device             *dev;
1137         /* Note, we can have MAX_FIDS outstanding.  FIDs are 16-bits, so we
1138            use the high bit to mark whether it is in use. */
1139 #define MAX_FIDS 6
1140 #define MPI_MAX_FIDS 1
1141         int                           fids[MAX_FIDS];
1142         ConfigRid config;
1143         char keyindex; // Used with auto wep
1144         char defindex; // Used with auto wep
1145         struct proc_dir_entry *proc_entry;
1146         spinlock_t aux_lock;
1147         unsigned long flags;
1148 #define FLAG_PROMISC    8       /* IFF_PROMISC 0x100 - include/linux/if.h */
1149 #define FLAG_RADIO_OFF  0       /* User disabling of MAC */
1150 #define FLAG_RADIO_DOWN 1       /* ifup/ifdown disabling of MAC */
1151 #define FLAG_RADIO_MASK 0x03
1152 #define FLAG_ENABLED    2
1153 #define FLAG_ADHOC      3       /* Needed by MIC */
1154 #define FLAG_MIC_CAPABLE 4
1155 #define FLAG_UPDATE_MULTI 5
1156 #define FLAG_UPDATE_UNI 6
1157 #define FLAG_802_11     7
1158 #define FLAG_PENDING_XMIT 9
1159 #define FLAG_PENDING_XMIT11 10
1160 #define FLAG_MPI        11
1161 #define FLAG_REGISTERED 12
1162 #define FLAG_COMMIT     13
1163 #define FLAG_RESET      14
1164 #define FLAG_FLASHING   15
1165 #define JOB_MASK        0x1ff0000
1166 #define JOB_DIE         16
1167 #define JOB_XMIT        17
1168 #define JOB_XMIT11      18
1169 #define JOB_STATS       19
1170 #define JOB_PROMISC     20
1171 #define JOB_MIC         21
1172 #define JOB_EVENT       22
1173 #define JOB_AUTOWEP     23
1174 #define JOB_WSTATS      24
1175         int (*bap_read)(struct airo_info*, u16 *pu16Dst, int bytelen,
1176                         int whichbap);
1177         unsigned short *flash;
1178         tdsRssiEntry *rssi;
1179         struct task_struct *task;
1180         struct semaphore sem;
1181         pid_t thr_pid;
1182         wait_queue_head_t thr_wait;
1183         struct completion thr_exited;
1184         unsigned long expires;
1185         struct {
1186                 struct sk_buff *skb;
1187                 int fid;
1188         } xmit, xmit11;
1189         struct net_device *wifidev;
1190 #ifdef WIRELESS_EXT
1191         struct iw_statistics    wstats;         // wireless stats
1192         unsigned long           scan_timestamp; /* Time started to scan */
1193         struct iw_spy_data      spy_data;
1194         struct iw_public_data   wireless_data;
1195 #endif /* WIRELESS_EXT */
1196 #ifdef MICSUPPORT
1197         /* MIC stuff */
1198         struct crypto_tfm       *tfm;
1199         mic_module              mod[2];
1200         mic_statistics          micstats;
1201 #endif
1202         HostRxDesc rxfids[MPI_MAX_FIDS]; // rx/tx/config MPI350 descriptors
1203         HostTxDesc txfids[MPI_MAX_FIDS];
1204         HostRidDesc config_desc;
1205         unsigned long ridbus; // phys addr of config_desc
1206         struct sk_buff_head txq;// tx queue used by mpi350 code
1207         struct pci_dev          *pci;
1208         unsigned char           __iomem *pcimem;
1209         unsigned char           __iomem *pciaux;
1210         unsigned char           *shared;
1211         dma_addr_t              shared_dma;
1212         pm_message_t            power;
1213         SsidRid                 *SSID;
1214         APListRid               *APList;
1215 #define PCI_SHARED_LEN          2*MPI_MAX_FIDS*PKTSIZE+RIDSIZE
1216         char                    proc_name[IFNAMSIZ];
1217 };
1218
1219 static inline int bap_read(struct airo_info *ai, u16 *pu16Dst, int bytelen,
1220                            int whichbap) {
1221         return ai->bap_read(ai, pu16Dst, bytelen, whichbap);
1222 }
1223
1224 static int setup_proc_entry( struct net_device *dev,
1225                              struct airo_info *apriv );
1226 static int takedown_proc_entry( struct net_device *dev,
1227                                 struct airo_info *apriv );
1228
1229 static int cmdreset(struct airo_info *ai);
1230 static int setflashmode (struct airo_info *ai);
1231 static int flashgchar(struct airo_info *ai,int matchbyte,int dwelltime);
1232 static int flashputbuf(struct airo_info *ai);
1233 static int flashrestart(struct airo_info *ai,struct net_device *dev);
1234
1235 #ifdef MICSUPPORT
1236 /***********************************************************************
1237  *                              MIC ROUTINES                           *
1238  ***********************************************************************
1239  */
1240
1241 static int RxSeqValid (struct airo_info *ai,miccntx *context,int mcast,u32 micSeq);
1242 static void MoveWindow(miccntx *context, u32 micSeq);
1243 static void emmh32_setseed(emmh32_context *context, u8 *pkey, int keylen, struct crypto_tfm *);
1244 static void emmh32_init(emmh32_context *context);
1245 static void emmh32_update(emmh32_context *context, u8 *pOctets, int len);
1246 static void emmh32_final(emmh32_context *context, u8 digest[4]);
1247 static int flashpchar(struct airo_info *ai,int byte,int dwelltime);
1248
1249 /* micinit - Initialize mic seed */
1250
1251 static void micinit(struct airo_info *ai)
1252 {
1253         MICRid mic_rid;
1254
1255         clear_bit(JOB_MIC, &ai->flags);
1256         PC4500_readrid(ai, RID_MIC, &mic_rid, sizeof(mic_rid), 0);
1257         up(&ai->sem);
1258
1259         ai->micstats.enabled = (mic_rid.state & 0x00FF) ? 1 : 0;
1260
1261         if (ai->micstats.enabled) {
1262                 /* Key must be valid and different */
1263                 if (mic_rid.multicastValid && (!ai->mod[0].mCtx.valid ||
1264                     (memcmp (ai->mod[0].mCtx.key, mic_rid.multicast,
1265                              sizeof(ai->mod[0].mCtx.key)) != 0))) {
1266                         /* Age current mic Context */
1267                         memcpy(&ai->mod[1].mCtx,&ai->mod[0].mCtx,sizeof(miccntx));
1268                         /* Initialize new context */
1269                         memcpy(&ai->mod[0].mCtx.key,mic_rid.multicast,sizeof(mic_rid.multicast));
1270                         ai->mod[0].mCtx.window  = 33; //Window always points to the middle
1271                         ai->mod[0].mCtx.rx      = 0;  //Rx Sequence numbers
1272                         ai->mod[0].mCtx.tx      = 0;  //Tx sequence numbers
1273                         ai->mod[0].mCtx.valid   = 1;  //Key is now valid
1274   
1275                         /* Give key to mic seed */
1276                         emmh32_setseed(&ai->mod[0].mCtx.seed,mic_rid.multicast,sizeof(mic_rid.multicast), ai->tfm);
1277                 }
1278
1279                 /* Key must be valid and different */
1280                 if (mic_rid.unicastValid && (!ai->mod[0].uCtx.valid || 
1281                     (memcmp(ai->mod[0].uCtx.key, mic_rid.unicast,
1282                             sizeof(ai->mod[0].uCtx.key)) != 0))) {
1283                         /* Age current mic Context */
1284                         memcpy(&ai->mod[1].uCtx,&ai->mod[0].uCtx,sizeof(miccntx));
1285                         /* Initialize new context */
1286                         memcpy(&ai->mod[0].uCtx.key,mic_rid.unicast,sizeof(mic_rid.unicast));
1287         
1288                         ai->mod[0].uCtx.window  = 33; //Window always points to the middle
1289                         ai->mod[0].uCtx.rx      = 0;  //Rx Sequence numbers
1290                         ai->mod[0].uCtx.tx      = 0;  //Tx sequence numbers
1291                         ai->mod[0].uCtx.valid   = 1;  //Key is now valid
1292         
1293                         //Give key to mic seed
1294                         emmh32_setseed(&ai->mod[0].uCtx.seed, mic_rid.unicast, sizeof(mic_rid.unicast), ai->tfm);
1295                 }
1296         } else {
1297       /* So next time we have a valid key and mic is enabled, we will update
1298        * the sequence number if the key is the same as before.
1299        */
1300                 ai->mod[0].uCtx.valid = 0;
1301                 ai->mod[0].mCtx.valid = 0;
1302         }
1303 }
1304
1305 /* micsetup - Get ready for business */
1306
1307 static int micsetup(struct airo_info *ai) {
1308         int i;
1309
1310         if (ai->tfm == NULL)
1311                 ai->tfm = crypto_alloc_tfm("aes", CRYPTO_TFM_REQ_MAY_SLEEP);
1312
1313         if (ai->tfm == NULL) {
1314                 printk(KERN_ERR "airo: failed to load transform for AES\n");
1315                 return ERROR;
1316         }
1317
1318         for (i=0; i < NUM_MODULES; i++) {
1319                 memset(&ai->mod[i].mCtx,0,sizeof(miccntx));
1320                 memset(&ai->mod[i].uCtx,0,sizeof(miccntx));
1321         }
1322         return SUCCESS;
1323 }
1324
1325 static char micsnap[] = {0xAA,0xAA,0x03,0x00,0x40,0x96,0x00,0x02};
1326
1327 /*===========================================================================
1328  * Description: Mic a packet
1329  *    
1330  *      Inputs: etherHead * pointer to an 802.3 frame
1331  *    
1332  *     Returns: BOOLEAN if successful, otherwise false.
1333  *             PacketTxLen will be updated with the mic'd packets size.
1334  *
1335  *    Caveats: It is assumed that the frame buffer will already
1336  *             be big enough to hold the largets mic message possible.
1337  *            (No memory allocation is done here).
1338  *  
1339  *    Author: sbraneky (10/15/01)
1340  *    Merciless hacks by rwilcher (1/14/02)
1341  */
1342
1343 static int encapsulate(struct airo_info *ai ,etherHead *frame, MICBuffer *mic, int payLen)
1344 {
1345         miccntx   *context;
1346
1347         // Determine correct context
1348         // If not adhoc, always use unicast key
1349
1350         if (test_bit(FLAG_ADHOC, &ai->flags) && (frame->da[0] & 0x1))
1351                 context = &ai->mod[0].mCtx;
1352         else
1353                 context = &ai->mod[0].uCtx;
1354   
1355         if (!context->valid)
1356                 return ERROR;
1357
1358         mic->typelen = htons(payLen + 16); //Length of Mic'd packet
1359
1360         memcpy(&mic->u.snap, micsnap, sizeof(micsnap)); // Add Snap
1361
1362         // Add Tx sequence
1363         mic->seq = htonl(context->tx);
1364         context->tx += 2;
1365
1366         emmh32_init(&context->seed); // Mic the packet
1367         emmh32_update(&context->seed,frame->da,ETH_ALEN * 2); // DA,SA
1368         emmh32_update(&context->seed,(u8*)&mic->typelen,10); // Type/Length and Snap
1369         emmh32_update(&context->seed,(u8*)&mic->seq,sizeof(mic->seq)); //SEQ
1370         emmh32_update(&context->seed,frame->da + ETH_ALEN * 2,payLen); //payload
1371         emmh32_final(&context->seed, (u8*)&mic->mic);
1372
1373         /*    New Type/length ?????????? */
1374         mic->typelen = 0; //Let NIC know it could be an oversized packet
1375         return SUCCESS;
1376 }
1377
1378 typedef enum {
1379     NONE,
1380     NOMIC,
1381     NOMICPLUMMED,
1382     SEQUENCE,
1383     INCORRECTMIC,
1384 } mic_error;
1385
1386 /*===========================================================================
1387  *  Description: Decapsulates a MIC'd packet and returns the 802.3 packet
1388  *               (removes the MIC stuff) if packet is a valid packet.
1389  *      
1390  *       Inputs: etherHead  pointer to the 802.3 packet             
1391  *     
1392  *      Returns: BOOLEAN - TRUE if packet should be dropped otherwise FALSE
1393  *     
1394  *      Author: sbraneky (10/15/01)
1395  *    Merciless hacks by rwilcher (1/14/02)
1396  *---------------------------------------------------------------------------
1397  */
1398
1399 static int decapsulate(struct airo_info *ai, MICBuffer *mic, etherHead *eth, u16 payLen)
1400 {
1401         int      i;
1402         u32      micSEQ;
1403         miccntx  *context;
1404         u8       digest[4];
1405         mic_error micError = NONE;
1406
1407         // Check if the packet is a Mic'd packet
1408
1409         if (!ai->micstats.enabled) {
1410                 //No Mic set or Mic OFF but we received a MIC'd packet.
1411                 if (memcmp ((u8*)eth + 14, micsnap, sizeof(micsnap)) == 0) {
1412                         ai->micstats.rxMICPlummed++;
1413                         return ERROR;
1414                 }
1415                 return SUCCESS;
1416         }
1417
1418         if (ntohs(mic->typelen) == 0x888E)
1419                 return SUCCESS;
1420
1421         if (memcmp (mic->u.snap, micsnap, sizeof(micsnap)) != 0) {
1422             // Mic enabled but packet isn't Mic'd
1423                 ai->micstats.rxMICPlummed++;
1424                 return ERROR;
1425         }
1426
1427         micSEQ = ntohl(mic->seq);            //store SEQ as CPU order
1428
1429         //At this point we a have a mic'd packet and mic is enabled
1430         //Now do the mic error checking.
1431
1432         //Receive seq must be odd
1433         if ( (micSEQ & 1) == 0 ) {
1434                 ai->micstats.rxWrongSequence++;
1435                 return ERROR;
1436         }
1437
1438         for (i = 0; i < NUM_MODULES; i++) {
1439                 int mcast = eth->da[0] & 1;
1440                 //Determine proper context 
1441                 context = mcast ? &ai->mod[i].mCtx : &ai->mod[i].uCtx;
1442         
1443                 //Make sure context is valid
1444                 if (!context->valid) {
1445                         if (i == 0)
1446                                 micError = NOMICPLUMMED;
1447                         continue;                
1448                 }
1449                 //DeMic it 
1450
1451                 if (!mic->typelen)
1452                         mic->typelen = htons(payLen + sizeof(MICBuffer) - 2);
1453         
1454                 emmh32_init(&context->seed);
1455                 emmh32_update(&context->seed, eth->da, ETH_ALEN*2); 
1456                 emmh32_update(&context->seed, (u8 *)&mic->typelen, sizeof(mic->typelen)+sizeof(mic->u.snap)); 
1457                 emmh32_update(&context->seed, (u8 *)&mic->seq,sizeof(mic->seq));        
1458                 emmh32_update(&context->seed, eth->da + ETH_ALEN*2,payLen);     
1459                 //Calculate MIC
1460                 emmh32_final(&context->seed, digest);
1461         
1462                 if (memcmp(digest, &mic->mic, 4)) { //Make sure the mics match
1463                   //Invalid Mic
1464                         if (i == 0)
1465                                 micError = INCORRECTMIC;
1466                         continue;
1467                 }
1468
1469                 //Check Sequence number if mics pass
1470                 if (RxSeqValid(ai, context, mcast, micSEQ) == SUCCESS) {
1471                         ai->micstats.rxSuccess++;
1472                         return SUCCESS;
1473                 }
1474                 if (i == 0)
1475                         micError = SEQUENCE;
1476         }
1477
1478         // Update statistics
1479         switch (micError) {
1480                 case NOMICPLUMMED: ai->micstats.rxMICPlummed++;   break;
1481                 case SEQUENCE:    ai->micstats.rxWrongSequence++; break;
1482                 case INCORRECTMIC: ai->micstats.rxIncorrectMIC++; break;
1483                 case NONE:  break;
1484                 case NOMIC: break;
1485         }
1486         return ERROR;
1487 }
1488
1489 /*===========================================================================
1490  * Description:  Checks the Rx Seq number to make sure it is valid
1491  *               and hasn't already been received
1492  *   
1493  *     Inputs: miccntx - mic context to check seq against
1494  *             micSeq  - the Mic seq number
1495  *   
1496  *    Returns: TRUE if valid otherwise FALSE. 
1497  *
1498  *    Author: sbraneky (10/15/01)
1499  *    Merciless hacks by rwilcher (1/14/02)
1500  *---------------------------------------------------------------------------
1501  */
1502
1503 static int RxSeqValid (struct airo_info *ai,miccntx *context,int mcast,u32 micSeq)
1504 {
1505         u32 seq,index;
1506
1507         //Allow for the ap being rebooted - if it is then use the next 
1508         //sequence number of the current sequence number - might go backwards
1509
1510         if (mcast) {
1511                 if (test_bit(FLAG_UPDATE_MULTI, &ai->flags)) {
1512                         clear_bit (FLAG_UPDATE_MULTI, &ai->flags);
1513                         context->window = (micSeq > 33) ? micSeq : 33;
1514                         context->rx     = 0;        // Reset rx
1515                 }
1516         } else if (test_bit(FLAG_UPDATE_UNI, &ai->flags)) {
1517                 clear_bit (FLAG_UPDATE_UNI, &ai->flags);
1518                 context->window = (micSeq > 33) ? micSeq : 33; // Move window
1519                 context->rx     = 0;        // Reset rx
1520         }
1521
1522         //Make sequence number relative to START of window
1523         seq = micSeq - (context->window - 33);
1524
1525         //Too old of a SEQ number to check.
1526         if ((s32)seq < 0)
1527                 return ERROR;
1528     
1529         if ( seq > 64 ) {
1530                 //Window is infinite forward
1531                 MoveWindow(context,micSeq);
1532                 return SUCCESS;
1533         }
1534
1535         // We are in the window. Now check the context rx bit to see if it was already sent
1536         seq >>= 1;         //divide by 2 because we only have odd numbers
1537         index = 1 << seq;  //Get an index number
1538
1539         if (!(context->rx & index)) {
1540                 //micSEQ falls inside the window.
1541                 //Add seqence number to the list of received numbers.
1542                 context->rx |= index;
1543
1544                 MoveWindow(context,micSeq);
1545
1546                 return SUCCESS;
1547         }
1548         return ERROR;
1549 }
1550
1551 static void MoveWindow(miccntx *context, u32 micSeq)
1552 {
1553         u32 shift;
1554
1555         //Move window if seq greater than the middle of the window
1556         if (micSeq > context->window) {
1557                 shift = (micSeq - context->window) >> 1;
1558     
1559                     //Shift out old
1560                 if (shift < 32)
1561                         context->rx >>= shift;
1562                 else
1563                         context->rx = 0;
1564
1565                 context->window = micSeq;      //Move window
1566         }
1567 }
1568
1569 /*==============================================*/
1570 /*========== EMMH ROUTINES  ====================*/
1571 /*==============================================*/
1572
1573 /* mic accumulate */
1574 #define MIC_ACCUM(val)  \
1575         context->accum += (u64)(val) * context->coeff[coeff_position++];
1576
1577 static unsigned char aes_counter[16];
1578
1579 /* expand the key to fill the MMH coefficient array */
1580 static void emmh32_setseed(emmh32_context *context, u8 *pkey, int keylen, struct crypto_tfm *tfm)
1581 {
1582   /* take the keying material, expand if necessary, truncate at 16-bytes */
1583   /* run through AES counter mode to generate context->coeff[] */
1584   
1585         int i,j;
1586         u32 counter;
1587         u8 *cipher, plain[16];
1588         struct scatterlist sg[1];
1589
1590         crypto_cipher_setkey(tfm, pkey, 16);
1591         counter = 0;
1592         for (i = 0; i < (sizeof(context->coeff)/sizeof(context->coeff[0])); ) {
1593                 aes_counter[15] = (u8)(counter >> 0);
1594                 aes_counter[14] = (u8)(counter >> 8);
1595                 aes_counter[13] = (u8)(counter >> 16);
1596                 aes_counter[12] = (u8)(counter >> 24);
1597                 counter++;
1598                 memcpy (plain, aes_counter, 16);
1599                 sg[0].page = virt_to_page(plain);
1600                 sg[0].offset = ((long) plain & ~PAGE_MASK);
1601                 sg[0].length = 16;
1602                 crypto_cipher_encrypt(tfm, sg, sg, 16);
1603                 cipher = kmap(sg[0].page) + sg[0].offset;
1604                 for (j=0; (j<16) && (i< (sizeof(context->coeff)/sizeof(context->coeff[0]))); ) {
1605                         context->coeff[i++] = ntohl(*(u32 *)&cipher[j]);
1606                         j += 4;
1607                 }
1608         }
1609 }
1610
1611 /* prepare for calculation of a new mic */
1612 static void emmh32_init(emmh32_context *context)
1613 {
1614         /* prepare for new mic calculation */
1615         context->accum = 0;
1616         context->position = 0;
1617 }
1618
1619 /* add some bytes to the mic calculation */
1620 static void emmh32_update(emmh32_context *context, u8 *pOctets, int len)
1621 {
1622         int     coeff_position, byte_position;
1623   
1624         if (len == 0) return;
1625   
1626         coeff_position = context->position >> 2;
1627   
1628         /* deal with partial 32-bit word left over from last update */
1629         byte_position = context->position & 3;
1630         if (byte_position) {
1631                 /* have a partial word in part to deal with */
1632                 do {
1633                         if (len == 0) return;
1634                         context->part.d8[byte_position++] = *pOctets++;
1635                         context->position++;
1636                         len--;
1637                 } while (byte_position < 4);
1638                 MIC_ACCUM(htonl(context->part.d32));
1639         }
1640
1641         /* deal with full 32-bit words */
1642         while (len >= 4) {
1643                 MIC_ACCUM(htonl(*(u32 *)pOctets));
1644                 context->position += 4;
1645                 pOctets += 4;
1646                 len -= 4;
1647         }
1648
1649         /* deal with partial 32-bit word that will be left over from this update */
1650         byte_position = 0;
1651         while (len > 0) {
1652                 context->part.d8[byte_position++] = *pOctets++;
1653                 context->position++;
1654                 len--;
1655         }
1656 }
1657
1658 /* mask used to zero empty bytes for final partial word */
1659 static u32 mask32[4] = { 0x00000000L, 0xFF000000L, 0xFFFF0000L, 0xFFFFFF00L };
1660
1661 /* calculate the mic */
1662 static void emmh32_final(emmh32_context *context, u8 digest[4])
1663 {
1664         int     coeff_position, byte_position;
1665         u32     val;
1666   
1667         u64 sum, utmp;
1668         s64 stmp;
1669
1670         coeff_position = context->position >> 2;
1671   
1672         /* deal with partial 32-bit word left over from last update */
1673         byte_position = context->position & 3;
1674         if (byte_position) {
1675                 /* have a partial word in part to deal with */
1676                 val = htonl(context->part.d32);
1677                 MIC_ACCUM(val & mask32[byte_position]); /* zero empty bytes */
1678         }
1679
1680         /* reduce the accumulated u64 to a 32-bit MIC */
1681         sum = context->accum;
1682         stmp = (sum  & 0xffffffffLL) - ((sum >> 32)  * 15);
1683         utmp = (stmp & 0xffffffffLL) - ((stmp >> 32) * 15);
1684         sum = utmp & 0xffffffffLL;
1685         if (utmp > 0x10000000fLL)
1686                 sum -= 15;
1687
1688         val = (u32)sum;
1689         digest[0] = (val>>24) & 0xFF;
1690         digest[1] = (val>>16) & 0xFF;
1691         digest[2] = (val>>8) & 0xFF;
1692         digest[3] = val & 0xFF;
1693 }
1694 #endif
1695
1696 static int readBSSListRid(struct airo_info *ai, int first,
1697                       BSSListRid *list) {
1698         int rc;
1699                         Cmd cmd;
1700                         Resp rsp;
1701
1702         if (first == 1) {
1703                         if (ai->flags & FLAG_RADIO_MASK) return -ENETDOWN;
1704                         memset(&cmd, 0, sizeof(cmd));
1705                         cmd.cmd=CMD_LISTBSS;
1706                         if (down_interruptible(&ai->sem))
1707                                 return -ERESTARTSYS;
1708                         issuecommand(ai, &cmd, &rsp);
1709                         up(&ai->sem);
1710                         /* Let the command take effect */
1711                         ai->task = current;
1712                         ssleep(3);
1713                         ai->task = NULL;
1714                 }
1715         rc = PC4500_readrid(ai, first ? RID_BSSLISTFIRST : RID_BSSLISTNEXT,
1716                             list, sizeof(*list), 1);
1717
1718         list->len = le16_to_cpu(list->len);
1719         list->index = le16_to_cpu(list->index);
1720         list->radioType = le16_to_cpu(list->radioType);
1721         list->cap = le16_to_cpu(list->cap);
1722         list->beaconInterval = le16_to_cpu(list->beaconInterval);
1723         list->fh.dwell = le16_to_cpu(list->fh.dwell);
1724         list->dsChannel = le16_to_cpu(list->dsChannel);
1725         list->atimWindow = le16_to_cpu(list->atimWindow);
1726         list->dBm = le16_to_cpu(list->dBm);
1727         return rc;
1728 }
1729
1730 static int readWepKeyRid(struct airo_info*ai, WepKeyRid *wkr, int temp, int lock) {
1731         int rc = PC4500_readrid(ai, temp ? RID_WEP_TEMP : RID_WEP_PERM,
1732                                 wkr, sizeof(*wkr), lock);
1733
1734         wkr->len = le16_to_cpu(wkr->len);
1735         wkr->kindex = le16_to_cpu(wkr->kindex);
1736         wkr->klen = le16_to_cpu(wkr->klen);
1737         return rc;
1738 }
1739 /* In the writeXXXRid routines we copy the rids so that we don't screwup
1740  * the originals when we endian them... */
1741 static int writeWepKeyRid(struct airo_info*ai, WepKeyRid *pwkr, int perm, int lock) {
1742         int rc;
1743         WepKeyRid wkr = *pwkr;
1744
1745         wkr.len = cpu_to_le16(wkr.len);
1746         wkr.kindex = cpu_to_le16(wkr.kindex);
1747         wkr.klen = cpu_to_le16(wkr.klen);
1748         rc = PC4500_writerid(ai, RID_WEP_TEMP, &wkr, sizeof(wkr), lock);
1749         if (rc!=SUCCESS) printk(KERN_ERR "airo:  WEP_TEMP set %x\n", rc);
1750         if (perm) {
1751                 rc = PC4500_writerid(ai, RID_WEP_PERM, &wkr, sizeof(wkr), lock);
1752                 if (rc!=SUCCESS) {
1753                         printk(KERN_ERR "airo:  WEP_PERM set %x\n", rc);
1754                 }
1755         }
1756         return rc;
1757 }
1758
1759 static int readSsidRid(struct airo_info*ai, SsidRid *ssidr) {
1760         int i;
1761         int rc = PC4500_readrid(ai, RID_SSID, ssidr, sizeof(*ssidr), 1);
1762
1763         ssidr->len = le16_to_cpu(ssidr->len);
1764         for(i = 0; i < 3; i++) {
1765                 ssidr->ssids[i].len = le16_to_cpu(ssidr->ssids[i].len);
1766         }
1767         return rc;
1768 }
1769 static int writeSsidRid(struct airo_info*ai, SsidRid *pssidr, int lock) {
1770         int rc;
1771         int i;
1772         SsidRid ssidr = *pssidr;
1773
1774         ssidr.len = cpu_to_le16(ssidr.len);
1775         for(i = 0; i < 3; i++) {
1776                 ssidr.ssids[i].len = cpu_to_le16(ssidr.ssids[i].len);
1777         }
1778         rc = PC4500_writerid(ai, RID_SSID, &ssidr, sizeof(ssidr), lock);
1779         return rc;
1780 }
1781 static int readConfigRid(struct airo_info*ai, int lock) {
1782         int rc;
1783         u16 *s;
1784         ConfigRid cfg;
1785
1786         if (ai->config.len)
1787                 return SUCCESS;
1788
1789         rc = PC4500_readrid(ai, RID_ACTUALCONFIG, &cfg, sizeof(cfg), lock);
1790         if (rc != SUCCESS)
1791                 return rc;
1792
1793         for(s = &cfg.len; s <= &cfg.rtsThres; s++) *s = le16_to_cpu(*s);
1794
1795         for(s = &cfg.shortRetryLimit; s <= &cfg.radioType; s++)
1796                 *s = le16_to_cpu(*s);
1797
1798         for(s = &cfg.txPower; s <= &cfg.radioSpecific; s++)
1799                 *s = le16_to_cpu(*s);
1800
1801         for(s = &cfg.arlThreshold; s <= &cfg._reserved4[0]; s++)
1802                 *s = cpu_to_le16(*s);
1803
1804         for(s = &cfg.autoWake; s <= &cfg.autoWake; s++)
1805                 *s = cpu_to_le16(*s);
1806
1807         ai->config = cfg;
1808         return SUCCESS;
1809 }
1810 static inline void checkThrottle(struct airo_info *ai) {
1811         int i;
1812 /* Old hardware had a limit on encryption speed */
1813         if (ai->config.authType != AUTH_OPEN && maxencrypt) {
1814                 for(i=0; i<8; i++) {
1815                         if (ai->config.rates[i] > maxencrypt) {
1816                                 ai->config.rates[i] = 0;
1817                         }
1818                 }
1819         }
1820 }
1821 static int writeConfigRid(struct airo_info*ai, int lock) {
1822         u16 *s;
1823         ConfigRid cfgr;
1824
1825         if (!test_bit (FLAG_COMMIT, &ai->flags))
1826                 return SUCCESS;
1827
1828         clear_bit (FLAG_COMMIT, &ai->flags);
1829         clear_bit (FLAG_RESET, &ai->flags);
1830         checkThrottle(ai);
1831         cfgr = ai->config;
1832
1833         if ((cfgr.opmode & 0xFF) == MODE_STA_IBSS)
1834                 set_bit(FLAG_ADHOC, &ai->flags);
1835         else
1836                 clear_bit(FLAG_ADHOC, &ai->flags);
1837
1838         for(s = &cfgr.len; s <= &cfgr.rtsThres; s++) *s = cpu_to_le16(*s);
1839
1840         for(s = &cfgr.shortRetryLimit; s <= &cfgr.radioType; s++)
1841                 *s = cpu_to_le16(*s);
1842
1843         for(s = &cfgr.txPower; s <= &cfgr.radioSpecific; s++)
1844                 *s = cpu_to_le16(*s);
1845
1846         for(s = &cfgr.arlThreshold; s <= &cfgr._reserved4[0]; s++)
1847                 *s = cpu_to_le16(*s);
1848
1849         for(s = &cfgr.autoWake; s <= &cfgr.autoWake; s++)
1850                 *s = cpu_to_le16(*s);
1851
1852         return PC4500_writerid( ai, RID_CONFIG, &cfgr, sizeof(cfgr), lock);
1853 }
1854 static int readStatusRid(struct airo_info*ai, StatusRid *statr, int lock) {
1855         int rc = PC4500_readrid(ai, RID_STATUS, statr, sizeof(*statr), lock);
1856         u16 *s;
1857
1858         statr->len = le16_to_cpu(statr->len);
1859         for(s = &statr->mode; s <= &statr->SSIDlen; s++) *s = le16_to_cpu(*s);
1860
1861         for(s = &statr->beaconPeriod; s <= &statr->shortPreamble; s++)
1862                 *s = le16_to_cpu(*s);
1863         statr->load = le16_to_cpu(statr->load);
1864         statr->assocStatus = le16_to_cpu(statr->assocStatus);
1865         return rc;
1866 }
1867 static int readAPListRid(struct airo_info*ai, APListRid *aplr) {
1868         int rc =  PC4500_readrid(ai, RID_APLIST, aplr, sizeof(*aplr), 1);
1869         aplr->len = le16_to_cpu(aplr->len);
1870         return rc;
1871 }
1872 static int writeAPListRid(struct airo_info*ai, APListRid *aplr, int lock) {
1873         int rc;
1874         aplr->len = cpu_to_le16(aplr->len);
1875         rc = PC4500_writerid(ai, RID_APLIST, aplr, sizeof(*aplr), lock);
1876         return rc;
1877 }
1878 static int readCapabilityRid(struct airo_info*ai, CapabilityRid *capr, int lock) {
1879         int rc = PC4500_readrid(ai, RID_CAPABILITIES, capr, sizeof(*capr), lock);
1880         u16 *s;
1881
1882         capr->len = le16_to_cpu(capr->len);
1883         capr->prodNum = le16_to_cpu(capr->prodNum);
1884         capr->radioType = le16_to_cpu(capr->radioType);
1885         capr->country = le16_to_cpu(capr->country);
1886         for(s = &capr->txPowerLevels[0]; s <= &capr->requiredHard; s++)
1887                 *s = le16_to_cpu(*s);
1888         return rc;
1889 }
1890 static int readStatsRid(struct airo_info*ai, StatsRid *sr, int rid, int lock) {
1891         int rc = PC4500_readrid(ai, rid, sr, sizeof(*sr), lock);
1892         u32 *i;
1893
1894         sr->len = le16_to_cpu(sr->len);
1895         for(i = &sr->vals[0]; i <= &sr->vals[99]; i++) *i = le32_to_cpu(*i);
1896         return rc;
1897 }
1898
1899 static int airo_open(struct net_device *dev) {
1900         struct airo_info *info = dev->priv;
1901         Resp rsp;
1902
1903         if (test_bit(FLAG_FLASHING, &info->flags))
1904                 return -EIO;
1905
1906         /* Make sure the card is configured.
1907          * Wireless Extensions may postpone config changes until the card
1908          * is open (to pipeline changes and speed-up card setup). If
1909          * those changes are not yet commited, do it now - Jean II */
1910         if (test_bit (FLAG_COMMIT, &info->flags)) {
1911                 disable_MAC(info, 1);
1912                 writeConfigRid(info, 1);
1913         }
1914
1915         if (info->wifidev != dev) {
1916                 /* Power on the MAC controller (which may have been disabled) */
1917                 clear_bit(FLAG_RADIO_DOWN, &info->flags);
1918                 enable_interrupts(info);
1919         }
1920         enable_MAC(info, &rsp, 1);
1921
1922         netif_start_queue(dev);
1923         return 0;
1924 }
1925
1926 static int mpi_start_xmit(struct sk_buff *skb, struct net_device *dev) {
1927         int npacks, pending;
1928         unsigned long flags;
1929         struct airo_info *ai = dev->priv;
1930
1931         if (!skb) {
1932                 printk(KERN_ERR "airo: %s: skb==NULL\n",__FUNCTION__);
1933                 return 0;
1934         }
1935         npacks = skb_queue_len (&ai->txq);
1936
1937         if (npacks >= MAXTXQ - 1) {
1938                 netif_stop_queue (dev);
1939                 if (npacks > MAXTXQ) {
1940                         ai->stats.tx_fifo_errors++;
1941                         return 1;
1942                 }
1943                 skb_queue_tail (&ai->txq, skb);
1944                 return 0;
1945         }
1946
1947         spin_lock_irqsave(&ai->aux_lock, flags);
1948         skb_queue_tail (&ai->txq, skb);
1949         pending = test_bit(FLAG_PENDING_XMIT, &ai->flags);
1950         spin_unlock_irqrestore(&ai->aux_lock,flags);
1951         netif_wake_queue (dev);
1952
1953         if (pending == 0) {
1954                 set_bit(FLAG_PENDING_XMIT, &ai->flags);
1955                 mpi_send_packet (dev);
1956         }
1957         return 0;
1958 }
1959
1960 /*
1961  * @mpi_send_packet
1962  *
1963  * Attempt to transmit a packet. Can be called from interrupt
1964  * or transmit . return number of packets we tried to send
1965  */
1966
1967 static int mpi_send_packet (struct net_device *dev)
1968 {
1969         struct sk_buff *skb;
1970         unsigned char *buffer;
1971         s16 len, *payloadLen;
1972         struct airo_info *ai = dev->priv;
1973         u8 *sendbuf;
1974
1975         /* get a packet to send */
1976
1977         if ((skb = skb_dequeue(&ai->txq)) == 0) {
1978                 printk (KERN_ERR
1979                         "airo: %s: Dequeue'd zero in send_packet()\n",
1980                         __FUNCTION__);
1981                 return 0;
1982         }
1983
1984         /* check min length*/
1985         len = ETH_ZLEN < skb->len ? skb->len : ETH_ZLEN;
1986         buffer = skb->data;
1987
1988         ai->txfids[0].tx_desc.offset = 0;
1989         ai->txfids[0].tx_desc.valid = 1;
1990         ai->txfids[0].tx_desc.eoc = 1;
1991         ai->txfids[0].tx_desc.len =len+sizeof(WifiHdr);
1992
1993 /*
1994  * Magic, the cards firmware needs a length count (2 bytes) in the host buffer
1995  * right after  TXFID_HDR.The TXFID_HDR contains the status short so payloadlen
1996  * is immediatly after it. ------------------------------------------------
1997  *                         |TXFIDHDR+STATUS|PAYLOADLEN|802.3HDR|PACKETDATA|
1998  *                         ------------------------------------------------
1999  */
2000
2001         memcpy((char *)ai->txfids[0].virtual_host_addr,
2002                 (char *)&wifictlhdr8023, sizeof(wifictlhdr8023));
2003
2004         payloadLen = (s16 *)(ai->txfids[0].virtual_host_addr +
2005                 sizeof(wifictlhdr8023));
2006         sendbuf = ai->txfids[0].virtual_host_addr +
2007                 sizeof(wifictlhdr8023) + 2 ;
2008
2009         /*
2010          * Firmware automaticly puts 802 header on so
2011          * we don't need to account for it in the length
2012          */
2013 #ifdef MICSUPPORT
2014         if (test_bit(FLAG_MIC_CAPABLE, &ai->flags) && ai->micstats.enabled &&
2015                 (ntohs(((u16 *)buffer)[6]) != 0x888E)) {
2016                 MICBuffer pMic;
2017
2018                 if (encapsulate(ai, (etherHead *)buffer, &pMic, len - sizeof(etherHead)) != SUCCESS)
2019                         return ERROR;
2020
2021                 *payloadLen = cpu_to_le16(len-sizeof(etherHead)+sizeof(pMic));
2022                 ai->txfids[0].tx_desc.len += sizeof(pMic);
2023                 /* copy data into airo dma buffer */
2024                 memcpy (sendbuf, buffer, sizeof(etherHead));
2025                 buffer += sizeof(etherHead);
2026                 sendbuf += sizeof(etherHead);
2027                 memcpy (sendbuf, &pMic, sizeof(pMic));
2028                 sendbuf += sizeof(pMic);
2029                 memcpy (sendbuf, buffer, len - sizeof(etherHead));
2030         } else
2031 #endif
2032         {
2033                 *payloadLen = cpu_to_le16(len - sizeof(etherHead));
2034
2035                 dev->trans_start = jiffies;
2036
2037                 /* copy data into airo dma buffer */
2038                 memcpy(sendbuf, buffer, len);
2039         }
2040
2041         memcpy_toio(ai->txfids[0].card_ram_off,
2042                 &ai->txfids[0].tx_desc, sizeof(TxFid));
2043
2044         OUT4500(ai, EVACK, 8);
2045
2046         dev_kfree_skb_any(skb);
2047         return 1;
2048 }
2049
2050 static void get_tx_error(struct airo_info *ai, u32 fid)
2051 {
2052         u16 status;
2053
2054         if (fid < 0)
2055                 status = ((WifiCtlHdr *)ai->txfids[0].virtual_host_addr)->ctlhdr.status;
2056         else {
2057                 if (bap_setup(ai, ai->fids[fid] & 0xffff, 4, BAP0) != SUCCESS)
2058                         return;
2059                 bap_read(ai, &status, 2, BAP0);
2060         }
2061         if (le16_to_cpu(status) & 2) /* Too many retries */
2062                 ai->stats.tx_aborted_errors++;
2063         if (le16_to_cpu(status) & 4) /* Transmit lifetime exceeded */
2064                 ai->stats.tx_heartbeat_errors++;
2065         if (le16_to_cpu(status) & 8) /* Aid fail */
2066                 { }
2067         if (le16_to_cpu(status) & 0x10) /* MAC disabled */
2068                 ai->stats.tx_carrier_errors++;
2069         if (le16_to_cpu(status) & 0x20) /* Association lost */
2070                 { }
2071         /* We produce a TXDROP event only for retry or lifetime
2072          * exceeded, because that's the only status that really mean
2073          * that this particular node went away.
2074          * Other errors means that *we* screwed up. - Jean II */
2075         if ((le16_to_cpu(status) & 2) ||
2076              (le16_to_cpu(status) & 4)) {
2077                 union iwreq_data        wrqu;
2078                 char junk[0x18];
2079
2080                 /* Faster to skip over useless data than to do
2081                  * another bap_setup(). We are at offset 0x6 and
2082                  * need to go to 0x18 and read 6 bytes - Jean II */
2083                 bap_read(ai, (u16 *) junk, 0x18, BAP0);
2084
2085                 /* Copy 802.11 dest address.
2086                  * We use the 802.11 header because the frame may
2087                  * not be 802.3 or may be mangled...
2088                  * In Ad-Hoc mode, it will be the node address.
2089                  * In managed mode, it will be most likely the AP addr
2090                  * User space will figure out how to convert it to
2091                  * whatever it needs (IP address or else).
2092                  * - Jean II */
2093                 memcpy(wrqu.addr.sa_data, junk + 0x12, ETH_ALEN);
2094                 wrqu.addr.sa_family = ARPHRD_ETHER;
2095
2096                 /* Send event to user space */
2097                 wireless_send_event(ai->dev, IWEVTXDROP, &wrqu, NULL);
2098         }
2099 }
2100
2101 static void airo_end_xmit(struct net_device *dev) {
2102         u16 status;
2103         int i;
2104         struct airo_info *priv = dev->priv;
2105         struct sk_buff *skb = priv->xmit.skb;
2106         int fid = priv->xmit.fid;
2107         u32 *fids = priv->fids;
2108
2109         clear_bit(JOB_XMIT, &priv->flags);
2110         clear_bit(FLAG_PENDING_XMIT, &priv->flags);
2111         status = transmit_802_3_packet (priv, fids[fid], skb->data);
2112         up(&priv->sem);
2113
2114         i = 0;
2115         if ( status == SUCCESS ) {
2116                 dev->trans_start = jiffies;
2117                 for (; i < MAX_FIDS / 2 && (priv->fids[i] & 0xffff0000); i++);
2118         } else {
2119                 priv->fids[fid] &= 0xffff;
2120                 priv->stats.tx_window_errors++;
2121         }
2122         if (i < MAX_FIDS / 2)
2123                 netif_wake_queue(dev);
2124         dev_kfree_skb(skb);
2125 }
2126
2127 static int airo_start_xmit(struct sk_buff *skb, struct net_device *dev) {
2128         s16 len;
2129         int i, j;
2130         struct airo_info *priv = dev->priv;
2131         u32 *fids = priv->fids;
2132
2133         if ( skb == NULL ) {
2134                 printk( KERN_ERR "airo:  skb == NULL!!!\n" );
2135                 return 0;
2136         }
2137
2138         /* Find a vacant FID */
2139         for( i = 0; i < MAX_FIDS / 2 && (fids[i] & 0xffff0000); i++ );
2140         for( j = i + 1; j < MAX_FIDS / 2 && (fids[j] & 0xffff0000); j++ );
2141
2142         if ( j >= MAX_FIDS / 2 ) {
2143                 netif_stop_queue(dev);
2144
2145                 if (i == MAX_FIDS / 2) {
2146                         priv->stats.tx_fifo_errors++;
2147                         return 1;
2148                 }
2149         }
2150         /* check min length*/
2151         len = ETH_ZLEN < skb->len ? skb->len : ETH_ZLEN;
2152         /* Mark fid as used & save length for later */
2153         fids[i] |= (len << 16);
2154         priv->xmit.skb = skb;
2155         priv->xmit.fid = i;
2156         if (down_trylock(&priv->sem) != 0) {
2157                 set_bit(FLAG_PENDING_XMIT, &priv->flags);
2158                 netif_stop_queue(dev);
2159                 set_bit(JOB_XMIT, &priv->flags);
2160                 wake_up_interruptible(&priv->thr_wait);
2161         } else
2162                 airo_end_xmit(dev);
2163         return 0;
2164 }
2165
2166 static void airo_end_xmit11(struct net_device *dev) {
2167         u16 status;
2168         int i;
2169         struct airo_info *priv = dev->priv;
2170         struct sk_buff *skb = priv->xmit11.skb;
2171         int fid = priv->xmit11.fid;
2172         u32 *fids = priv->fids;
2173
2174         clear_bit(JOB_XMIT11, &priv->flags);
2175         clear_bit(FLAG_PENDING_XMIT11, &priv->flags);
2176         status = transmit_802_11_packet (priv, fids[fid], skb->data);
2177         up(&priv->sem);
2178
2179         i = MAX_FIDS / 2;
2180         if ( status == SUCCESS ) {
2181                 dev->trans_start = jiffies;
2182                 for (; i < MAX_FIDS && (priv->fids[i] & 0xffff0000); i++);
2183         } else {
2184                 priv->fids[fid] &= 0xffff;
2185                 priv->stats.tx_window_errors++;
2186         }
2187         if (i < MAX_FIDS)
2188                 netif_wake_queue(dev);
2189         dev_kfree_skb(skb);
2190 }
2191
2192 static int airo_start_xmit11(struct sk_buff *skb, struct net_device *dev) {
2193         s16 len;
2194         int i, j;
2195         struct airo_info *priv = dev->priv;
2196         u32 *fids = priv->fids;
2197
2198         if (test_bit(FLAG_MPI, &priv->flags)) {
2199                 /* Not implemented yet for MPI350 */
2200                 netif_stop_queue(dev);
2201                 return -ENETDOWN;
2202         }
2203
2204         if ( skb == NULL ) {
2205                 printk( KERN_ERR "airo:  skb == NULL!!!\n" );
2206                 return 0;
2207         }
2208
2209         /* Find a vacant FID */
2210         for( i = MAX_FIDS / 2; i < MAX_FIDS && (fids[i] & 0xffff0000); i++ );
2211         for( j = i + 1; j < MAX_FIDS && (fids[j] & 0xffff0000); j++ );
2212
2213         if ( j >= MAX_FIDS ) {
2214                 netif_stop_queue(dev);
2215
2216                 if (i == MAX_FIDS) {
2217                         priv->stats.tx_fifo_errors++;
2218                         return 1;
2219                 }
2220         }
2221         /* check min length*/
2222         len = ETH_ZLEN < skb->len ? skb->len : ETH_ZLEN;
2223         /* Mark fid as used & save length for later */
2224         fids[i] |= (len << 16);
2225         priv->xmit11.skb = skb;
2226         priv->xmit11.fid = i;
2227         if (down_trylock(&priv->sem) != 0) {
2228                 set_bit(FLAG_PENDING_XMIT11, &priv->flags);
2229                 netif_stop_queue(dev);
2230                 set_bit(JOB_XMIT11, &priv->flags);
2231                 wake_up_interruptible(&priv->thr_wait);
2232         } else
2233                 airo_end_xmit11(dev);
2234         return 0;
2235 }
2236
2237 static void airo_read_stats(struct airo_info *ai) {
2238         StatsRid stats_rid;
2239         u32 *vals = stats_rid.vals;
2240
2241         clear_bit(JOB_STATS, &ai->flags);
2242         if (ai->power.event) {
2243                 up(&ai->sem);
2244                 return;
2245         }
2246         readStatsRid(ai, &stats_rid, RID_STATS, 0);
2247         up(&ai->sem);
2248
2249         ai->stats.rx_packets = vals[43] + vals[44] + vals[45];
2250         ai->stats.tx_packets = vals[39] + vals[40] + vals[41];
2251         ai->stats.rx_bytes = vals[92];
2252         ai->stats.tx_bytes = vals[91];
2253         ai->stats.rx_errors = vals[0] + vals[2] + vals[3] + vals[4];
2254         ai->stats.tx_errors = vals[42] + ai->stats.tx_fifo_errors;
2255         ai->stats.multicast = vals[43];
2256         ai->stats.collisions = vals[89];
2257
2258         /* detailed rx_errors: */
2259         ai->stats.rx_length_errors = vals[3];
2260         ai->stats.rx_crc_errors = vals[4];
2261         ai->stats.rx_frame_errors = vals[2];
2262         ai->stats.rx_fifo_errors = vals[0];
2263 }
2264
2265 static struct net_device_stats *airo_get_stats(struct net_device *dev)
2266 {
2267         struct airo_info *local =  dev->priv;
2268
2269         if (!test_bit(JOB_STATS, &local->flags)) {
2270                 /* Get stats out of the card if available */
2271                 if (down_trylock(&local->sem) != 0) {
2272                         set_bit(JOB_STATS, &local->flags);
2273                         wake_up_interruptible(&local->thr_wait);
2274                 } else
2275                         airo_read_stats(local);
2276         }
2277
2278         return &local->stats;
2279 }
2280
2281 static void airo_set_promisc(struct airo_info *ai) {
2282         Cmd cmd;
2283         Resp rsp;
2284
2285         memset(&cmd, 0, sizeof(cmd));
2286         cmd.cmd=CMD_SETMODE;
2287         clear_bit(JOB_PROMISC, &ai->flags);
2288         cmd.parm0=(ai->flags&IFF_PROMISC) ? PROMISC : NOPROMISC;
2289         issuecommand(ai, &cmd, &rsp);
2290         up(&ai->sem);
2291 }
2292
2293 static void airo_set_multicast_list(struct net_device *dev) {
2294         struct airo_info *ai = dev->priv;
2295
2296         if ((dev->flags ^ ai->flags) & IFF_PROMISC) {
2297                 change_bit(FLAG_PROMISC, &ai->flags);
2298                 if (down_trylock(&ai->sem) != 0) {
2299                         set_bit(JOB_PROMISC, &ai->flags);
2300                         wake_up_interruptible(&ai->thr_wait);
2301                 } else
2302                         airo_set_promisc(ai);
2303         }
2304
2305         if ((dev->flags&IFF_ALLMULTI)||dev->mc_count>0) {
2306                 /* Turn on multicast.  (Should be already setup...) */
2307         }
2308 }
2309
2310 static int airo_set_mac_address(struct net_device *dev, void *p)
2311 {
2312         struct airo_info *ai = dev->priv;
2313         struct sockaddr *addr = p;
2314         Resp rsp;
2315
2316         readConfigRid(ai, 1);
2317         memcpy (ai->config.macAddr, addr->sa_data, dev->addr_len);
2318         set_bit (FLAG_COMMIT, &ai->flags);
2319         disable_MAC(ai, 1);
2320         writeConfigRid (ai, 1);
2321         enable_MAC(ai, &rsp, 1);
2322         memcpy (ai->dev->dev_addr, addr->sa_data, dev->addr_len);
2323         if (ai->wifidev)
2324                 memcpy (ai->wifidev->dev_addr, addr->sa_data, dev->addr_len);
2325         return 0;
2326 }
2327
2328 static int airo_change_mtu(struct net_device *dev, int new_mtu)
2329 {
2330         if ((new_mtu < 68) || (new_mtu > 2400))
2331                 return -EINVAL;
2332         dev->mtu = new_mtu;
2333         return 0;
2334 }
2335
2336
2337 static int airo_close(struct net_device *dev) {
2338         struct airo_info *ai = dev->priv;
2339
2340         netif_stop_queue(dev);
2341
2342         if (ai->wifidev != dev) {
2343 #ifdef POWER_ON_DOWN
2344                 /* Shut power to the card. The idea is that the user can save
2345                  * power when he doesn't need the card with "ifconfig down".
2346                  * That's the method that is most friendly towards the network
2347                  * stack (i.e. the network stack won't try to broadcast
2348                  * anything on the interface and routes are gone. Jean II */
2349                 set_bit(FLAG_RADIO_DOWN, &ai->flags);
2350                 disable_MAC(ai, 1);
2351 #endif
2352                 disable_interrupts( ai );
2353         }
2354         return 0;
2355 }
2356
2357 static void del_airo_dev( struct net_device *dev );
2358
2359 void stop_airo_card( struct net_device *dev, int freeres )
2360 {
2361         struct airo_info *ai = dev->priv;
2362
2363         set_bit(FLAG_RADIO_DOWN, &ai->flags);
2364         disable_MAC(ai, 1);
2365         disable_interrupts(ai);
2366         free_irq( dev->irq, dev );
2367         takedown_proc_entry( dev, ai );
2368         if (test_bit(FLAG_REGISTERED, &ai->flags)) {
2369                 unregister_netdev( dev );
2370                 if (ai->wifidev) {
2371                         unregister_netdev(ai->wifidev);
2372                         free_netdev(ai->wifidev);
2373                         ai->wifidev = NULL;
2374                 }
2375                 clear_bit(FLAG_REGISTERED, &ai->flags);
2376         }
2377         set_bit(JOB_DIE, &ai->flags);
2378         kill_proc(ai->thr_pid, SIGTERM, 1);
2379         wait_for_completion(&ai->thr_exited);
2380
2381         /*
2382          * Clean out tx queue
2383          */
2384         if (test_bit(FLAG_MPI, &ai->flags) && !skb_queue_empty(&ai->txq)) {
2385                 struct sk_buff *skb = NULL;
2386                 for (;(skb = skb_dequeue(&ai->txq));)
2387                         dev_kfree_skb(skb);
2388         }
2389
2390         if (ai->flash)
2391                 kfree(ai->flash);
2392         if (ai->rssi)
2393                 kfree(ai->rssi);
2394         if (ai->APList)
2395                 kfree(ai->APList);
2396         if (ai->SSID)
2397                 kfree(ai->SSID);
2398         if (freeres) {
2399                 /* PCMCIA frees this stuff, so only for PCI and ISA */
2400                 release_region( dev->base_addr, 64 );
2401                 if (test_bit(FLAG_MPI, &ai->flags)) {
2402                         if (ai->pci)
2403                                 mpi_unmap_card(ai->pci);
2404                         if (ai->pcimem)
2405                                 iounmap(ai->pcimem);
2406                         if (ai->pciaux)
2407                                 iounmap(ai->pciaux);
2408                         pci_free_consistent(ai->pci, PCI_SHARED_LEN,
2409                                 ai->shared, ai->shared_dma);
2410                 }
2411         }
2412 #ifdef MICSUPPORT
2413         crypto_free_tfm(ai->tfm);
2414 #endif
2415         del_airo_dev( dev );
2416         free_netdev( dev );
2417 }
2418
2419 EXPORT_SYMBOL(stop_airo_card);
2420
2421 static int add_airo_dev( struct net_device *dev );
2422
2423 static int wll_header_parse(struct sk_buff *skb, unsigned char *haddr)
2424 {
2425         memcpy(haddr, skb->mac.raw + 10, ETH_ALEN);
2426         return ETH_ALEN;
2427 }
2428
2429 static void mpi_unmap_card(struct pci_dev *pci)
2430 {
2431         unsigned long mem_start = pci_resource_start(pci, 1);
2432         unsigned long mem_len = pci_resource_len(pci, 1);
2433         unsigned long aux_start = pci_resource_start(pci, 2);
2434         unsigned long aux_len = AUXMEMSIZE;
2435
2436         release_mem_region(aux_start, aux_len);
2437         release_mem_region(mem_start, mem_len);
2438 }
2439
2440 /*************************************************************
2441  *  This routine assumes that descriptors have been setup .
2442  *  Run at insmod time or after reset  when the decriptors
2443  *  have been initialized . Returns 0 if all is well nz
2444  *  otherwise . Does not allocate memory but sets up card
2445  *  using previously allocated descriptors.
2446  */
2447 static int mpi_init_descriptors (struct airo_info *ai)
2448 {
2449         Cmd cmd;
2450         Resp rsp;
2451         int i;
2452         int rc = SUCCESS;
2453
2454         /* Alloc  card RX descriptors */
2455         netif_stop_queue(ai->dev);
2456
2457         memset(&rsp,0,sizeof(rsp));
2458         memset(&cmd,0,sizeof(cmd));
2459
2460         cmd.cmd = CMD_ALLOCATEAUX;
2461         cmd.parm0 = FID_RX;
2462         cmd.parm1 = (ai->rxfids[0].card_ram_off - ai->pciaux);
2463         cmd.parm2 = MPI_MAX_FIDS;
2464         rc=issuecommand(ai, &cmd, &rsp);
2465         if (rc != SUCCESS) {
2466                 printk(KERN_ERR "airo:  Couldn't allocate RX FID\n");
2467                 return rc;
2468         }
2469
2470         for (i=0; i<MPI_MAX_FIDS; i++) {
2471                 memcpy_toio(ai->rxfids[i].card_ram_off,
2472                         &ai->rxfids[i].rx_desc, sizeof(RxFid));
2473         }
2474
2475         /* Alloc card TX descriptors */
2476
2477         memset(&rsp,0,sizeof(rsp));
2478         memset(&cmd,0,sizeof(cmd));
2479
2480         cmd.cmd = CMD_ALLOCATEAUX;
2481         cmd.parm0 = FID_TX;
2482         cmd.parm1 = (ai->txfids[0].card_ram_off - ai->pciaux);
2483         cmd.parm2 = MPI_MAX_FIDS;
2484
2485         for (i=0; i<MPI_MAX_FIDS; i++) {
2486                 ai->txfids[i].tx_desc.valid = 1;
2487                 memcpy_toio(ai->txfids[i].card_ram_off,
2488                         &ai->txfids[i].tx_desc, sizeof(TxFid));
2489         }
2490         ai->txfids[i-1].tx_desc.eoc = 1; /* Last descriptor has EOC set */
2491
2492         rc=issuecommand(ai, &cmd, &rsp);
2493         if (rc != SUCCESS) {
2494                 printk(KERN_ERR "airo:  Couldn't allocate TX FID\n");
2495                 return rc;
2496         }
2497
2498         /* Alloc card Rid descriptor */
2499         memset(&rsp,0,sizeof(rsp));
2500         memset(&cmd,0,sizeof(cmd));
2501
2502         cmd.cmd = CMD_ALLOCATEAUX;
2503         cmd.parm0 = RID_RW;
2504         cmd.parm1 = (ai->config_desc.card_ram_off - ai->pciaux);
2505         cmd.parm2 = 1; /* Magic number... */
2506         rc=issuecommand(ai, &cmd, &rsp);
2507         if (rc != SUCCESS) {
2508                 printk(KERN_ERR "airo:  Couldn't allocate RID\n");
2509                 return rc;
2510         }
2511
2512         memcpy_toio(ai->config_desc.card_ram_off,
2513                 &ai->config_desc.rid_desc, sizeof(Rid));
2514
2515         return rc;
2516 }
2517
2518 /*
2519  * We are setting up three things here:
2520  * 1) Map AUX memory for descriptors: Rid, TxFid, or RxFid.
2521  * 2) Map PCI memory for issueing commands.
2522  * 3) Allocate memory (shared) to send and receive ethernet frames.
2523  */
2524 static int mpi_map_card(struct airo_info *ai, struct pci_dev *pci,
2525                     const char *name)
2526 {
2527         unsigned long mem_start, mem_len, aux_start, aux_len;
2528         int rc = -1;
2529         int i;
2530         unsigned char *busaddroff,*vpackoff;
2531         unsigned char __iomem *pciaddroff;
2532
2533         mem_start = pci_resource_start(pci, 1);
2534         mem_len = pci_resource_len(pci, 1);
2535         aux_start = pci_resource_start(pci, 2);
2536         aux_len = AUXMEMSIZE;
2537
2538         if (!request_mem_region(mem_start, mem_len, name)) {
2539                 printk(KERN_ERR "airo: Couldn't get region %x[%x] for %s\n",
2540                        (int)mem_start, (int)mem_len, name);
2541                 goto out;
2542         }
2543         if (!request_mem_region(aux_start, aux_len, name)) {
2544                 printk(KERN_ERR "airo: Couldn't get region %x[%x] for %s\n",
2545                        (int)aux_start, (int)aux_len, name);
2546                 goto free_region1;
2547         }
2548
2549         ai->pcimem = ioremap(mem_start, mem_len);
2550         if (!ai->pcimem) {
2551                 printk(KERN_ERR "airo: Couldn't map region %x[%x] for %s\n",
2552                        (int)mem_start, (int)mem_len, name);
2553                 goto free_region2;
2554         }
2555         ai->pciaux = ioremap(aux_start, aux_len);
2556         if (!ai->pciaux) {
2557                 printk(KERN_ERR "airo: Couldn't map region %x[%x] for %s\n",
2558                        (int)aux_start, (int)aux_len, name);
2559                 goto free_memmap;
2560         }
2561
2562         /* Reserve PKTSIZE for each fid and 2K for the Rids */
2563         ai->shared = pci_alloc_consistent(pci, PCI_SHARED_LEN, &ai->shared_dma);
2564         if (!ai->shared) {
2565                 printk(KERN_ERR "airo: Couldn't alloc_consistent %d\n",
2566                        PCI_SHARED_LEN);
2567                 goto free_auxmap;
2568         }
2569
2570         /*
2571          * Setup descriptor RX, TX, CONFIG
2572          */
2573         busaddroff = (unsigned char *)ai->shared_dma;
2574         pciaddroff = ai->pciaux + AUX_OFFSET;
2575         vpackoff   = ai->shared;
2576
2577         /* RX descriptor setup */
2578         for(i = 0; i < MPI_MAX_FIDS; i++) {
2579                 ai->rxfids[i].pending = 0;
2580                 ai->rxfids[i].card_ram_off = pciaddroff;
2581                 ai->rxfids[i].virtual_host_addr = vpackoff;
2582                 ai->rxfids[i].rx_desc.host_addr = (dma_addr_t) busaddroff;
2583                 ai->rxfids[i].rx_desc.valid = 1;
2584                 ai->rxfids[i].rx_desc.len = PKTSIZE;
2585                 ai->rxfids[i].rx_desc.rdy = 0;
2586
2587                 pciaddroff += sizeof(RxFid);
2588                 busaddroff += PKTSIZE;
2589                 vpackoff   += PKTSIZE;
2590         }
2591
2592         /* TX descriptor setup */
2593         for(i = 0; i < MPI_MAX_FIDS; i++) {
2594                 ai->txfids[i].card_ram_off = pciaddroff;
2595                 ai->txfids[i].virtual_host_addr = vpackoff;
2596                 ai->txfids[i].tx_desc.valid = 1;
2597                 ai->txfids[i].tx_desc.host_addr = (dma_addr_t) busaddroff;
2598                 memcpy(ai->txfids[i].virtual_host_addr,
2599                         &wifictlhdr8023, sizeof(wifictlhdr8023));
2600
2601                 pciaddroff += sizeof(TxFid);
2602                 busaddroff += PKTSIZE;
2603                 vpackoff   += PKTSIZE;
2604         }
2605         ai->txfids[i-1].tx_desc.eoc = 1; /* Last descriptor has EOC set */
2606
2607         /* Rid descriptor setup */
2608         ai->config_desc.card_ram_off = pciaddroff;
2609         ai->config_desc.virtual_host_addr = vpackoff;
2610         ai->config_desc.rid_desc.host_addr = (dma_addr_t) busaddroff;
2611         ai->ridbus = (dma_addr_t)busaddroff;
2612         ai->config_desc.rid_desc.rid = 0;
2613         ai->config_desc.rid_desc.len = RIDSIZE;
2614         ai->config_desc.rid_desc.valid = 1;
2615         pciaddroff += sizeof(Rid);
2616         busaddroff += RIDSIZE;
2617         vpackoff   += RIDSIZE;
2618
2619         /* Tell card about descriptors */
2620         if (mpi_init_descriptors (ai) != SUCCESS)
2621                 goto free_shared;
2622
2623         return 0;
2624  free_shared:
2625         pci_free_consistent(pci, PCI_SHARED_LEN, ai->shared, ai->shared_dma);
2626  free_auxmap:
2627         iounmap(ai->pciaux);
2628  free_memmap:
2629         iounmap(ai->pcimem);
2630  free_region2:
2631         release_mem_region(aux_start, aux_len);
2632  free_region1:
2633         release_mem_region(mem_start, mem_len);
2634  out:
2635         return rc;
2636 }
2637
2638 static void wifi_setup(struct net_device *dev)
2639 {
2640         dev->hard_header        = NULL;
2641         dev->rebuild_header     = NULL;
2642         dev->hard_header_cache  = NULL;
2643         dev->header_cache_update= NULL;
2644
2645         dev->hard_header_parse  = wll_header_parse;
2646         dev->hard_start_xmit = &airo_start_xmit11;
2647         dev->get_stats = &airo_get_stats;
2648         dev->set_mac_address = &airo_set_mac_address;
2649         dev->do_ioctl = &airo_ioctl;
2650 #ifdef WIRELESS_EXT
2651         dev->wireless_handlers = &airo_handler_def;
2652 #endif /* WIRELESS_EXT */
2653         dev->change_mtu = &airo_change_mtu;
2654         dev->open = &airo_open;
2655         dev->stop = &airo_close;
2656
2657         dev->type               = ARPHRD_IEEE80211;
2658         dev->hard_header_len    = ETH_HLEN;
2659         dev->mtu                = 2312;
2660         dev->addr_len           = ETH_ALEN;
2661         dev->tx_queue_len       = 100; 
2662
2663         memset(dev->broadcast,0xFF, ETH_ALEN);
2664
2665         dev->flags              = IFF_BROADCAST|IFF_MULTICAST;
2666 }
2667
2668 static struct net_device *init_wifidev(struct airo_info *ai,
2669                                         struct net_device *ethdev)
2670 {
2671         int err;
2672         struct net_device *dev = alloc_netdev(0, "wifi%d", wifi_setup);
2673         if (!dev)
2674                 return NULL;
2675         dev->priv = ethdev->priv;
2676         dev->irq = ethdev->irq;
2677         dev->base_addr = ethdev->base_addr;
2678 #ifdef WIRELESS_EXT
2679         dev->wireless_data = ethdev->wireless_data;
2680 #endif /* WIRELESS_EXT */
2681         memcpy(dev->dev_addr, ethdev->dev_addr, dev->addr_len);
2682         err = register_netdev(dev);
2683         if (err<0) {
2684                 free_netdev(dev);
2685                 return NULL;
2686         }
2687         return dev;
2688 }
2689
2690 static int reset_card( struct net_device *dev , int lock) {
2691         struct airo_info *ai = dev->priv;
2692
2693         if (lock && down_interruptible(&ai->sem))
2694                 return -1;
2695         waitbusy (ai);
2696         OUT4500(ai,COMMAND,CMD_SOFTRESET);
2697         msleep(200);
2698         waitbusy (ai);
2699         msleep(200);
2700         if (lock)
2701                 up(&ai->sem);
2702         return 0;
2703 }
2704
2705 static struct net_device *_init_airo_card( unsigned short irq, int port,
2706                                            int is_pcmcia, struct pci_dev *pci,
2707                                            struct device *dmdev )
2708 {
2709         struct net_device *dev;
2710         struct airo_info *ai;
2711         int i, rc;
2712
2713         /* Create the network device object. */
2714         dev = alloc_etherdev(sizeof(*ai));
2715         if (!dev) {
2716                 printk(KERN_ERR "airo:  Couldn't alloc_etherdev\n");
2717                 return NULL;
2718         }
2719         if (dev_alloc_name(dev, dev->name) < 0) {
2720                 printk(KERN_ERR "airo:  Couldn't get name!\n");
2721                 goto err_out_free;
2722         }
2723
2724         ai = dev->priv;
2725         ai->wifidev = NULL;
2726         ai->flags = 0;
2727         if (pci && (pci->device == 0x5000 || pci->device == 0xa504)) {
2728                 printk(KERN_DEBUG "airo: Found an MPI350 card\n");
2729                 set_bit(FLAG_MPI, &ai->flags);
2730         }
2731         ai->dev = dev;
2732         spin_lock_init(&ai->aux_lock);
2733         sema_init(&ai->sem, 1);
2734         ai->config.len = 0;
2735         ai->pci = pci;
2736         init_waitqueue_head (&ai->thr_wait);
2737         init_completion (&ai->thr_exited);
2738         ai->thr_pid = kernel_thread(airo_thread, dev, CLONE_FS | CLONE_FILES);
2739         if (ai->thr_pid < 0)
2740                 goto err_out_free;
2741 #ifdef MICSUPPORT
2742         ai->tfm = NULL;
2743 #endif
2744         rc = add_airo_dev( dev );
2745         if (rc)
2746                 goto err_out_thr;
2747
2748         /* The Airo-specific entries in the device structure. */
2749         if (test_bit(FLAG_MPI,&ai->flags)) {
2750                 skb_queue_head_init (&ai->txq);
2751                 dev->hard_start_xmit = &mpi_start_xmit;
2752         } else
2753                 dev->hard_start_xmit = &airo_start_xmit;
2754         dev->get_stats = &airo_get_stats;
2755         dev->set_multicast_list = &airo_set_multicast_list;
2756         dev->set_mac_address = &airo_set_mac_address;
2757         dev->do_ioctl = &airo_ioctl;
2758 #ifdef WIRELESS_EXT
2759         dev->wireless_handlers = &airo_handler_def;
2760         ai->wireless_data.spy_data = &ai->spy_data;
2761         dev->wireless_data = &ai->wireless_data;
2762 #endif /* WIRELESS_EXT */
2763         dev->change_mtu = &airo_change_mtu;
2764         dev->open = &airo_open;
2765         dev->stop = &airo_close;
2766         dev->irq = irq;
2767         dev->base_addr = port;
2768
2769         SET_NETDEV_DEV(dev, dmdev);
2770
2771
2772         if (test_bit(FLAG_MPI,&ai->flags))
2773                 reset_card (dev, 1);
2774
2775         rc = request_irq( dev->irq, airo_interrupt, SA_SHIRQ, dev->name, dev );
2776         if (rc) {
2777                 printk(KERN_ERR "airo: register interrupt %d failed, rc %d\n", irq, rc );
2778                 goto err_out_unlink;
2779         }
2780         if (!is_pcmcia) {
2781                 if (!request_region( dev->base_addr, 64, dev->name )) {
2782                         rc = -EBUSY;
2783                         printk(KERN_ERR "airo: Couldn't request region\n");
2784                         goto err_out_irq;
2785                 }
2786         }
2787
2788         if (test_bit(FLAG_MPI,&ai->flags)) {
2789                 if (mpi_map_card(ai, pci, dev->name)) {
2790                         printk(KERN_ERR "airo: Could not map memory\n");
2791                         goto err_out_res;
2792                 }
2793         }
2794
2795         if (probe) {
2796                 if ( setup_card( ai, dev->dev_addr, 1 ) != SUCCESS ) {
2797                         printk( KERN_ERR "airo: MAC could not be enabled\n" );
2798                         rc = -EIO;
2799                         goto err_out_map;
2800                 }
2801         } else if (!test_bit(FLAG_MPI,&ai->flags)) {
2802                 ai->bap_read = fast_bap_read;
2803                 set_bit(FLAG_FLASHING, &ai->flags);
2804         }
2805
2806         rc = register_netdev(dev);
2807         if (rc) {
2808                 printk(KERN_ERR "airo: Couldn't register_netdev\n");
2809                 goto err_out_map;
2810         }
2811         ai->wifidev = init_wifidev(ai, dev);
2812
2813         set_bit(FLAG_REGISTERED,&ai->flags);
2814         printk( KERN_INFO "airo: MAC enabled %s %x:%x:%x:%x:%x:%x\n",
2815                 dev->name,
2816                 dev->dev_addr[0], dev->dev_addr[1], dev->dev_addr[2],
2817                 dev->dev_addr[3], dev->dev_addr[4], dev->dev_addr[5] );
2818
2819         /* Allocate the transmit buffers */
2820         if (probe && !test_bit(FLAG_MPI,&ai->flags))
2821                 for( i = 0; i < MAX_FIDS; i++ )
2822                         ai->fids[i] = transmit_allocate(ai,2312,i>=MAX_FIDS/2);
2823
2824         setup_proc_entry( dev, dev->priv ); /* XXX check for failure */
2825         netif_start_queue(dev);
2826         SET_MODULE_OWNER(dev);
2827         return dev;
2828
2829 err_out_map:
2830         if (test_bit(FLAG_MPI,&ai->flags) && pci) {
2831                 pci_free_consistent(pci, PCI_SHARED_LEN, ai->shared, ai->shared_dma);
2832                 iounmap(ai->pciaux);
2833                 iounmap(ai->pcimem);
2834                 mpi_unmap_card(ai->pci);
2835         }
2836 err_out_res:
2837         if (!is_pcmcia)
2838                 release_region( dev->base_addr, 64 );
2839 err_out_irq:
2840         free_irq(dev->irq, dev);
2841 err_out_unlink:
2842         del_airo_dev(dev);
2843 err_out_thr:
2844         set_bit(JOB_DIE, &ai->flags);
2845         kill_proc(ai->thr_pid, SIGTERM, 1);
2846         wait_for_completion(&ai->thr_exited);
2847 err_out_free:
2848         free_netdev(dev);
2849         return NULL;
2850 }
2851
2852 struct net_device *init_airo_card( unsigned short irq, int port, int is_pcmcia,
2853                                   struct device *dmdev)
2854 {
2855         return _init_airo_card ( irq, port, is_pcmcia, NULL, dmdev);
2856 }
2857
2858 EXPORT_SYMBOL(init_airo_card);
2859
2860 static int waitbusy (struct airo_info *ai) {
2861         int delay = 0;
2862         while ((IN4500 (ai, COMMAND) & COMMAND_BUSY) & (delay < 10000)) {
2863                 udelay (10);
2864                 if ((++delay % 20) == 0)
2865                         OUT4500(ai, EVACK, EV_CLEARCOMMANDBUSY);
2866         }
2867         return delay < 10000;
2868 }
2869
2870 int reset_airo_card( struct net_device *dev )
2871 {
2872         int i;
2873         struct airo_info *ai = dev->priv;
2874
2875         if (reset_card (dev, 1))
2876                 return -1;
2877
2878         if ( setup_card(ai, dev->dev_addr, 1 ) != SUCCESS ) {
2879                 printk( KERN_ERR "airo: MAC could not be enabled\n" );
2880                 return -1;
2881         }
2882         printk( KERN_INFO "airo: MAC enabled %s %x:%x:%x:%x:%x:%x\n", dev->name,
2883                         dev->dev_addr[0], dev->dev_addr[1], dev->dev_addr[2],
2884                         dev->dev_addr[3], dev->dev_addr[4], dev->dev_addr[5]);
2885         /* Allocate the transmit buffers if needed */
2886         if (!test_bit(FLAG_MPI,&ai->flags))
2887                 for( i = 0; i < MAX_FIDS; i++ )
2888                         ai->fids[i] = transmit_allocate (ai,2312,i>=MAX_FIDS/2);
2889
2890         enable_interrupts( ai );
2891         netif_wake_queue(dev);
2892         return 0;
2893 }
2894
2895 EXPORT_SYMBOL(reset_airo_card);
2896
2897 static void airo_send_event(struct net_device *dev) {
2898         struct airo_info *ai = dev->priv;
2899         union iwreq_data wrqu;
2900         StatusRid status_rid;
2901
2902         clear_bit(JOB_EVENT, &ai->flags);
2903         PC4500_readrid(ai, RID_STATUS, &status_rid, sizeof(status_rid), 0);
2904         up(&ai->sem);
2905         wrqu.data.length = 0;
2906         wrqu.data.flags = 0;
2907         memcpy(wrqu.ap_addr.sa_data, status_rid.bssid[0], ETH_ALEN);
2908         wrqu.ap_addr.sa_family = ARPHRD_ETHER;
2909
2910         /* Send event to user space */
2911         wireless_send_event(dev, SIOCGIWAP, &wrqu, NULL);
2912 }
2913
2914 static int airo_thread(void *data) {
2915         struct net_device *dev = data;
2916         struct airo_info *ai = dev->priv;
2917         int locked;
2918         
2919         daemonize("%s", dev->name);
2920         allow_signal(SIGTERM);
2921
2922         while(1) {
2923                 if (signal_pending(current))
2924                         flush_signals(current);
2925
2926                 /* make swsusp happy with our thread */
2927                 try_to_freeze();
2928
2929                 if (test_bit(JOB_DIE, &ai->flags))
2930                         break;
2931
2932                 if (ai->flags & JOB_MASK) {
2933                         locked = down_interruptible(&ai->sem);
2934                 } else {
2935                         wait_queue_t wait;
2936
2937                         init_waitqueue_entry(&wait, current);
2938                         add_wait_queue(&ai->thr_wait, &wait);
2939                         for (;;) {
2940                                 set_current_state(TASK_INTERRUPTIBLE);
2941                                 if (ai->flags & JOB_MASK)
2942                                         break;
2943                                 if (ai->expires) {
2944                                         if (time_after_eq(jiffies,ai->expires)){
2945                                                 set_bit(JOB_AUTOWEP,&ai->flags);
2946                                                 break;
2947                                         }
2948                                         if (!signal_pending(current)) {
2949                                                 schedule_timeout(ai->expires - jiffies);
2950                                                 continue;
2951                                         }
2952                                 } else if (!signal_pending(current)) {
2953                                         schedule();
2954                                         continue;
2955                                 }
2956                                 break;
2957                         }
2958                         current->state = TASK_RUNNING;
2959                         remove_wait_queue(&ai->thr_wait, &wait);
2960                         locked = 1;
2961                 }
2962
2963                 if (locked)
2964                         continue;
2965
2966                 if (test_bit(JOB_DIE, &ai->flags)) {
2967                         up(&ai->sem);
2968                         break;
2969                 }
2970
2971                 if (ai->power.event || test_bit(FLAG_FLASHING, &ai->flags)) {
2972                         up(&ai->sem);
2973                         continue;
2974                 }
2975
2976                 if (test_bit(JOB_XMIT, &ai->flags))
2977                         airo_end_xmit(dev);
2978                 else if (test_bit(JOB_XMIT11, &ai->flags))
2979                         airo_end_xmit11(dev);
2980                 else if (test_bit(JOB_STATS, &ai->flags))
2981                         airo_read_stats(ai);
2982                 else if (test_bit(JOB_WSTATS, &ai->flags))
2983                         airo_read_wireless_stats(ai);
2984                 else if (test_bit(JOB_PROMISC, &ai->flags))
2985                         airo_set_promisc(ai);
2986 #ifdef MICSUPPORT
2987                 else if (test_bit(JOB_MIC, &ai->flags))
2988                         micinit(ai);
2989 #endif
2990                 else if (test_bit(JOB_EVENT, &ai->flags))
2991                         airo_send_event(dev);
2992                 else if (test_bit(JOB_AUTOWEP, &ai->flags))
2993                         timer_func(dev);
2994         }
2995         complete_and_exit (&ai->thr_exited, 0);
2996 }
2997
2998 static irqreturn_t airo_interrupt ( int irq, void* dev_id, struct pt_regs *regs) {
2999         struct net_device *dev = (struct net_device *)dev_id;
3000         u16 status;
3001         u16 fid;
3002         struct airo_info *apriv = dev->priv;
3003         u16 savedInterrupts = 0;
3004         int handled = 0;
3005
3006         if (!netif_device_present(dev))
3007                 return IRQ_NONE;
3008
3009         for (;;) {
3010                 status = IN4500( apriv, EVSTAT );
3011                 if ( !(status & STATUS_INTS) || status == 0xffff ) break;
3012
3013                 handled = 1;
3014
3015                 if ( status & EV_AWAKE ) {
3016                         OUT4500( apriv, EVACK, EV_AWAKE );
3017                         OUT4500( apriv, EVACK, EV_AWAKE );
3018                 }
3019
3020                 if (!savedInterrupts) {
3021                         savedInterrupts = IN4500( apriv, EVINTEN );
3022                         OUT4500( apriv, EVINTEN, 0 );
3023                 }
3024
3025                 if ( status & EV_MIC ) {
3026                         OUT4500( apriv, EVACK, EV_MIC );
3027 #ifdef MICSUPPORT
3028                         if (test_bit(FLAG_MIC_CAPABLE, &apriv->flags)) {
3029                                 set_bit(JOB_MIC, &apriv->flags);
3030                                 wake_up_interruptible(&apriv->thr_wait);
3031                         }
3032 #endif
3033                 }
3034                 if ( status & EV_LINK ) {
3035                         union iwreq_data        wrqu;
3036                         /* The link status has changed, if you want to put a
3037                            monitor hook in, do it here.  (Remember that
3038                            interrupts are still disabled!)
3039                         */
3040                         u16 newStatus = IN4500(apriv, LINKSTAT);
3041                         OUT4500( apriv, EVACK, EV_LINK);
3042                         /* Here is what newStatus means: */
3043 #define NOBEACON 0x8000 /* Loss of sync - missed beacons */
3044 #define MAXRETRIES 0x8001 /* Loss of sync - max retries */
3045 #define MAXARL 0x8002 /* Loss of sync - average retry level exceeded*/
3046 #define FORCELOSS 0x8003 /* Loss of sync - host request */
3047 #define TSFSYNC 0x8004 /* Loss of sync - TSF synchronization */
3048 #define DEAUTH 0x8100 /* Deauthentication (low byte is reason code) */
3049 #define DISASS 0x8200 /* Disassociation (low byte is reason code) */
3050 #define ASSFAIL 0x8400 /* Association failure (low byte is reason
3051                           code) */
3052 #define AUTHFAIL 0x0300 /* Authentication failure (low byte is reason
3053                            code) */
3054 #define ASSOCIATED 0x0400 /* Assocatied */
3055 #define RC_RESERVED 0 /* Reserved return code */
3056 #define RC_NOREASON 1 /* Unspecified reason */
3057 #define RC_AUTHINV 2 /* Previous authentication invalid */
3058 #define RC_DEAUTH 3 /* Deauthenticated because sending station is
3059                        leaving */
3060 #define RC_NOACT 4 /* Disassociated due to inactivity */
3061 #define RC_MAXLOAD 5 /* Disassociated because AP is unable to handle
3062                         all currently associated stations */
3063 #define RC_BADCLASS2 6 /* Class 2 frame received from
3064                           non-Authenticated station */
3065 #define RC_BADCLASS3 7 /* Class 3 frame received from
3066                           non-Associated station */
3067 #define RC_STATLEAVE 8 /* Disassociated because sending station is
3068                           leaving BSS */
3069 #define RC_NOAUTH 9 /* Station requesting (Re)Association is not
3070                        Authenticated with the responding station */
3071                         if (newStatus != ASSOCIATED) {
3072                                 if (auto_wep && !apriv->expires) {
3073                                         apriv->expires = RUN_AT(3*HZ);
3074                                         wake_up_interruptible(&apriv->thr_wait);
3075                                 }
3076                         } else {
3077                                 struct task_struct *task = apriv->task;
3078                                 if (auto_wep)
3079                                         apriv->expires = 0;
3080                                 if (task)
3081                                         wake_up_process (task);
3082                                 set_bit(FLAG_UPDATE_UNI, &apriv->flags);
3083                                 set_bit(FLAG_UPDATE_MULTI, &apriv->flags);
3084                         }
3085                         /* Question : is ASSOCIATED the only status
3086                          * that is valid ? We want to catch handover
3087                          * and reassociations as valid status
3088                          * Jean II */
3089                         if(newStatus == ASSOCIATED) {
3090                                 if (apriv->scan_timestamp) {
3091                                         /* Send an empty event to user space.
3092                                          * We don't send the received data on
3093                                          * the event because it would require
3094                                          * us to do complex transcoding, and
3095                                          * we want to minimise the work done in
3096                                          * the irq handler. Use a request to
3097                                          * extract the data - Jean II */
3098                                         wrqu.data.length = 0;
3099                                         wrqu.data.flags = 0;
3100                                         wireless_send_event(dev, SIOCGIWSCAN, &wrqu, NULL);
3101                                         apriv->scan_timestamp = 0;
3102                                 }
3103                                 if (down_trylock(&apriv->sem) != 0) {
3104                                         set_bit(JOB_EVENT, &apriv->flags);
3105                                         wake_up_interruptible(&apriv->thr_wait);
3106                                 } else
3107                                         airo_send_event(dev);
3108                         } else {
3109                                 memset(wrqu.ap_addr.sa_data, '\0', ETH_ALEN);
3110                                 wrqu.ap_addr.sa_family = ARPHRD_ETHER;
3111
3112                                 /* Send event to user space */
3113                                 wireless_send_event(dev, SIOCGIWAP, &wrqu,NULL);
3114                         }
3115                 }
3116
3117                 /* Check to see if there is something to receive */
3118                 if ( status & EV_RX  ) {
3119                         struct sk_buff *skb = NULL;
3120                         u16 fc, len, hdrlen = 0;
3121 #pragma pack(1)
3122                         struct {
3123                                 u16 status, len;
3124                                 u8 rssi[2];
3125                                 u8 rate;
3126                                 u8 freq;
3127                                 u16 tmp[4];
3128                         } hdr;
3129 #pragma pack()
3130                         u16 gap;
3131                         u16 tmpbuf[4];
3132                         u16 *buffer;
3133
3134                         if (test_bit(FLAG_MPI,&apriv->flags)) {
3135                                 if (test_bit(FLAG_802_11, &apriv->flags))
3136                                         mpi_receive_802_11(apriv);
3137                                 else
3138                                         mpi_receive_802_3(apriv);
3139                                 OUT4500(apriv, EVACK, EV_RX);
3140                                 goto exitrx;
3141                         }
3142
3143                         fid = IN4500( apriv, RXFID );
3144
3145                         /* Get the packet length */
3146                         if (test_bit(FLAG_802_11, &apriv->flags)) {
3147                                 bap_setup (apriv, fid, 4, BAP0);
3148                                 bap_read (apriv, (u16*)&hdr, sizeof(hdr), BAP0);
3149                                 /* Bad CRC. Ignore packet */
3150                                 if (le16_to_cpu(hdr.status) & 2)
3151                                         hdr.len = 0;
3152                                 if (apriv->wifidev == NULL)
3153                                         hdr.len = 0;
3154                         } else {
3155                                 bap_setup (apriv, fid, 0x36, BAP0);
3156                                 bap_read (apriv, (u16*)&hdr.len, 2, BAP0);
3157                         }
3158                         len = le16_to_cpu(hdr.len);
3159
3160                         if (len > 2312) {
3161                                 printk( KERN_ERR "airo: Bad size %d\n", len );
3162                                 goto badrx;
3163                         }
3164                         if (len == 0)
3165                                 goto badrx;
3166
3167                         if (test_bit(FLAG_802_11, &apriv->flags)) {
3168                                 bap_read (apriv, (u16*)&fc, sizeof(fc), BAP0);
3169                                 fc = le16_to_cpu(fc);
3170                                 switch (fc & 0xc) {
3171                                         case 4:
3172                                                 if ((fc & 0xe0) == 0xc0)
3173                                                         hdrlen = 10;
3174                                                 else
3175                                                         hdrlen = 16;
3176                                                 break;
3177                                         case 8:
3178                                                 if ((fc&0x300)==0x300){
3179                                                         hdrlen = 30;
3180                                                         break;
3181                                                 }
3182                                         default:
3183                                                 hdrlen = 24;
3184                                 }
3185                         } else
3186                                 hdrlen = ETH_ALEN * 2;
3187
3188                         skb = dev_alloc_skb( len + hdrlen + 2 + 2 );
3189                         if ( !skb ) {
3190                                 apriv->stats.rx_dropped++;
3191                                 goto badrx;
3192                         }
3193                         skb_reserve(skb, 2); /* This way the IP header is aligned */
3194                         buffer = (u16*)skb_put (skb, len + hdrlen);
3195                         if (test_bit(FLAG_802_11, &apriv->flags)) {
3196                                 buffer[0] = fc;
3197                                 bap_read (apriv, buffer + 1, hdrlen - 2, BAP0);
3198                                 if (hdrlen == 24)
3199                                         bap_read (apriv, tmpbuf, 6, BAP0);
3200
3201                                 bap_read (apriv, &gap, sizeof(gap), BAP0);
3202                                 gap = le16_to_cpu(gap);
3203                                 if (gap) {
3204                                         if (gap <= 8)
3205                                                 bap_read (apriv, tmpbuf, gap, BAP0);
3206                                         else
3207                                                 printk(KERN_ERR "airo: gaplen too big. Problems will follow...\n");
3208                                 }
3209                                 bap_read (apriv, buffer + hdrlen/2, len, BAP0);
3210                         } else {
3211 #ifdef MICSUPPORT
3212                                 MICBuffer micbuf;
3213 #endif
3214                                 bap_read (apriv, buffer, ETH_ALEN*2, BAP0);
3215 #ifdef MICSUPPORT
3216                                 if (apriv->micstats.enabled) {
3217                                         bap_read (apriv,(u16*)&micbuf,sizeof(micbuf),BAP0);
3218                                         if (ntohs(micbuf.typelen) > 0x05DC)