vserver 1.9.5.x5
[linux-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, u32 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 rssi;
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 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 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 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 #include <linux/crypto.h>
1129 #endif
1130
1131 struct airo_info {
1132         struct net_device_stats stats;
1133         struct net_device             *dev;
1134         /* Note, we can have MAX_FIDS outstanding.  FIDs are 16-bits, so we
1135            use the high bit to mark whether it is in use. */
1136 #define MAX_FIDS 6
1137 #define MPI_MAX_FIDS 1
1138         int                           fids[MAX_FIDS];
1139         ConfigRid config;
1140         char keyindex; // Used with auto wep
1141         char defindex; // Used with auto wep
1142         struct proc_dir_entry *proc_entry;
1143         spinlock_t aux_lock;
1144         unsigned long flags;
1145 #define FLAG_PROMISC    8       /* IFF_PROMISC 0x100 - include/linux/if.h */
1146 #define FLAG_RADIO_OFF  0       /* User disabling of MAC */
1147 #define FLAG_RADIO_DOWN 1       /* ifup/ifdown disabling of MAC */
1148 #define FLAG_RADIO_MASK 0x03
1149 #define FLAG_ENABLED    2
1150 #define FLAG_ADHOC      3       /* Needed by MIC */
1151 #define FLAG_MIC_CAPABLE 4
1152 #define FLAG_UPDATE_MULTI 5
1153 #define FLAG_UPDATE_UNI 6
1154 #define FLAG_802_11     7
1155 #define FLAG_PENDING_XMIT 9
1156 #define FLAG_PENDING_XMIT11 10
1157 #define FLAG_MPI        11
1158 #define FLAG_REGISTERED 12
1159 #define FLAG_COMMIT     13
1160 #define FLAG_RESET      14
1161 #define FLAG_FLASHING   15
1162 #define JOB_MASK        0x1ff0000
1163 #define JOB_DIE         16
1164 #define JOB_XMIT        17
1165 #define JOB_XMIT11      18
1166 #define JOB_STATS       19
1167 #define JOB_PROMISC     20
1168 #define JOB_MIC         21
1169 #define JOB_EVENT       22
1170 #define JOB_AUTOWEP     23
1171 #define JOB_WSTATS      24
1172         int (*bap_read)(struct airo_info*, u16 *pu16Dst, int bytelen,
1173                         int whichbap);
1174         unsigned short *flash;
1175         tdsRssiEntry *rssi;
1176         struct task_struct *task;
1177         struct semaphore sem;
1178         pid_t thr_pid;
1179         wait_queue_head_t thr_wait;
1180         struct completion thr_exited;
1181         unsigned long expires;
1182         struct {
1183                 struct sk_buff *skb;
1184                 int fid;
1185         } xmit, xmit11;
1186         struct net_device *wifidev;
1187 #ifdef WIRELESS_EXT
1188         struct iw_statistics    wstats;         // wireless stats
1189         unsigned long           scan_timestamp; /* Time started to scan */
1190         struct iw_spy_data      spy_data;
1191         struct iw_public_data   wireless_data;
1192 #endif /* WIRELESS_EXT */
1193 #ifdef MICSUPPORT
1194         /* MIC stuff */
1195         struct crypto_tfm       *tfm;
1196         mic_module              mod[2];
1197         mic_statistics          micstats;
1198 #endif
1199         HostRxDesc rxfids[MPI_MAX_FIDS]; // rx/tx/config MPI350 descriptors
1200         HostTxDesc txfids[MPI_MAX_FIDS];
1201         HostRidDesc config_desc;
1202         unsigned long ridbus; // phys addr of config_desc
1203         struct sk_buff_head txq;// tx queue used by mpi350 code
1204         struct pci_dev          *pci;
1205         unsigned char           __iomem *pcimem;
1206         unsigned char           __iomem *pciaux;
1207         unsigned char           *shared;
1208         dma_addr_t              shared_dma;
1209         int                     power;
1210         SsidRid                 *SSID;
1211         APListRid               *APList;
1212 #define PCI_SHARED_LEN          2*MPI_MAX_FIDS*PKTSIZE+RIDSIZE
1213         char                    proc_name[IFNAMSIZ];
1214 };
1215
1216 static inline int bap_read(struct airo_info *ai, u16 *pu16Dst, int bytelen,
1217                            int whichbap) {
1218         return ai->bap_read(ai, pu16Dst, bytelen, whichbap);
1219 }
1220
1221 static int setup_proc_entry( struct net_device *dev,
1222                              struct airo_info *apriv );
1223 static int takedown_proc_entry( struct net_device *dev,
1224                                 struct airo_info *apriv );
1225
1226 #ifdef MICSUPPORT
1227 /***********************************************************************
1228  *                              MIC ROUTINES                           *
1229  ***********************************************************************
1230  */
1231
1232 static int RxSeqValid (struct airo_info *ai,miccntx *context,int mcast,u32 micSeq);
1233 static void MoveWindow(miccntx *context, u32 micSeq);
1234 void emmh32_setseed(emmh32_context *context, u8 *pkey, int keylen, struct crypto_tfm *);
1235 void emmh32_init(emmh32_context *context);
1236 void emmh32_update(emmh32_context *context, u8 *pOctets, int len);
1237 void emmh32_final(emmh32_context *context, u8 digest[4]);
1238
1239 /* micinit - Initialize mic seed */
1240
1241 static void micinit(struct airo_info *ai)
1242 {
1243         MICRid mic_rid;
1244
1245         clear_bit(JOB_MIC, &ai->flags);
1246         PC4500_readrid(ai, RID_MIC, &mic_rid, sizeof(mic_rid), 0);
1247         up(&ai->sem);
1248
1249         ai->micstats.enabled = (mic_rid.state & 0x00FF) ? 1 : 0;
1250
1251         if (ai->micstats.enabled) {
1252                 /* Key must be valid and different */
1253                 if (mic_rid.multicastValid && (!ai->mod[0].mCtx.valid ||
1254                     (memcmp (ai->mod[0].mCtx.key, mic_rid.multicast,
1255                              sizeof(ai->mod[0].mCtx.key)) != 0))) {
1256                         /* Age current mic Context */
1257                         memcpy(&ai->mod[1].mCtx,&ai->mod[0].mCtx,sizeof(miccntx));
1258                         /* Initialize new context */
1259                         memcpy(&ai->mod[0].mCtx.key,mic_rid.multicast,sizeof(mic_rid.multicast));
1260                         ai->mod[0].mCtx.window  = 33; //Window always points to the middle
1261                         ai->mod[0].mCtx.rx      = 0;  //Rx Sequence numbers
1262                         ai->mod[0].mCtx.tx      = 0;  //Tx sequence numbers
1263                         ai->mod[0].mCtx.valid   = 1;  //Key is now valid
1264   
1265                         /* Give key to mic seed */
1266                         emmh32_setseed(&ai->mod[0].mCtx.seed,mic_rid.multicast,sizeof(mic_rid.multicast), ai->tfm);
1267                 }
1268
1269                 /* Key must be valid and different */
1270                 if (mic_rid.unicastValid && (!ai->mod[0].uCtx.valid || 
1271                     (memcmp(ai->mod[0].uCtx.key, mic_rid.unicast,
1272                             sizeof(ai->mod[0].uCtx.key)) != 0))) {
1273                         /* Age current mic Context */
1274                         memcpy(&ai->mod[1].uCtx,&ai->mod[0].uCtx,sizeof(miccntx));
1275                         /* Initialize new context */
1276                         memcpy(&ai->mod[0].uCtx.key,mic_rid.unicast,sizeof(mic_rid.unicast));
1277         
1278                         ai->mod[0].uCtx.window  = 33; //Window always points to the middle
1279                         ai->mod[0].uCtx.rx      = 0;  //Rx Sequence numbers
1280                         ai->mod[0].uCtx.tx      = 0;  //Tx sequence numbers
1281                         ai->mod[0].uCtx.valid   = 1;  //Key is now valid
1282         
1283                         //Give key to mic seed
1284                         emmh32_setseed(&ai->mod[0].uCtx.seed, mic_rid.unicast, sizeof(mic_rid.unicast), ai->tfm);
1285                 }
1286         } else {
1287       /* So next time we have a valid key and mic is enabled, we will update
1288        * the sequence number if the key is the same as before.
1289        */
1290                 ai->mod[0].uCtx.valid = 0;
1291                 ai->mod[0].mCtx.valid = 0;
1292         }
1293 }
1294
1295 /* micsetup - Get ready for business */
1296
1297 static int micsetup(struct airo_info *ai) {
1298         int i;
1299
1300         if (ai->tfm == NULL)
1301                 ai->tfm = crypto_alloc_tfm("aes", 0);
1302
1303         if (ai->tfm == NULL) {
1304                 printk(KERN_ERR "airo: failed to load transform for AES\n");
1305                 return ERROR;
1306         }
1307
1308         for (i=0; i < NUM_MODULES; i++) {
1309                 memset(&ai->mod[i].mCtx,0,sizeof(miccntx));
1310                 memset(&ai->mod[i].uCtx,0,sizeof(miccntx));
1311         }
1312         return SUCCESS;
1313 }
1314
1315 char micsnap[]= {0xAA,0xAA,0x03,0x00,0x40,0x96,0x00,0x02};
1316
1317 /*===========================================================================
1318  * Description: Mic a packet
1319  *    
1320  *      Inputs: etherHead * pointer to an 802.3 frame
1321  *    
1322  *     Returns: BOOLEAN if successful, otherwise false.
1323  *             PacketTxLen will be updated with the mic'd packets size.
1324  *
1325  *    Caveats: It is assumed that the frame buffer will already
1326  *             be big enough to hold the largets mic message possible.
1327  *            (No memory allocation is done here).
1328  *  
1329  *    Author: sbraneky (10/15/01)
1330  *    Merciless hacks by rwilcher (1/14/02)
1331  */
1332
1333 static int encapsulate(struct airo_info *ai ,etherHead *frame, MICBuffer *mic, int payLen)
1334 {
1335         miccntx   *context;
1336
1337         // Determine correct context
1338         // If not adhoc, always use unicast key
1339
1340         if (test_bit(FLAG_ADHOC, &ai->flags) && (frame->da[0] & 0x1))
1341                 context = &ai->mod[0].mCtx;
1342         else
1343                 context = &ai->mod[0].uCtx;
1344   
1345         if (!context->valid)
1346                 return ERROR;
1347
1348         mic->typelen = htons(payLen + 16); //Length of Mic'd packet
1349
1350         memcpy(&mic->u.snap, micsnap, sizeof(micsnap)); // Add Snap
1351
1352         // Add Tx sequence
1353         mic->seq = htonl(context->tx);
1354         context->tx += 2;
1355
1356         emmh32_init(&context->seed); // Mic the packet
1357         emmh32_update(&context->seed,frame->da,ETH_ALEN * 2); // DA,SA
1358         emmh32_update(&context->seed,(u8*)&mic->typelen,10); // Type/Length and Snap
1359         emmh32_update(&context->seed,(u8*)&mic->seq,sizeof(mic->seq)); //SEQ
1360         emmh32_update(&context->seed,frame->da + ETH_ALEN * 2,payLen); //payload
1361         emmh32_final(&context->seed, (u8*)&mic->mic);
1362
1363         /*    New Type/length ?????????? */
1364         mic->typelen = 0; //Let NIC know it could be an oversized packet
1365         return SUCCESS;
1366 }
1367
1368 typedef enum {
1369     NONE,
1370     NOMIC,
1371     NOMICPLUMMED,
1372     SEQUENCE,
1373     INCORRECTMIC,
1374 } mic_error;
1375
1376 /*===========================================================================
1377  *  Description: Decapsulates a MIC'd packet and returns the 802.3 packet
1378  *               (removes the MIC stuff) if packet is a valid packet.
1379  *      
1380  *       Inputs: etherHead  pointer to the 802.3 packet             
1381  *     
1382  *      Returns: BOOLEAN - TRUE if packet should be dropped otherwise FALSE
1383  *     
1384  *      Author: sbraneky (10/15/01)
1385  *    Merciless hacks by rwilcher (1/14/02)
1386  *---------------------------------------------------------------------------
1387  */
1388
1389 static int decapsulate(struct airo_info *ai, MICBuffer *mic, etherHead *eth, u16 payLen)
1390 {
1391         int      i;
1392         u32      micSEQ;
1393         miccntx  *context;
1394         u8       digest[4];
1395         mic_error micError = NONE;
1396
1397         // Check if the packet is a Mic'd packet
1398
1399         if (!ai->micstats.enabled) {
1400                 //No Mic set or Mic OFF but we received a MIC'd packet.
1401                 if (memcmp ((u8*)eth + 14, micsnap, sizeof(micsnap)) == 0) {
1402                         ai->micstats.rxMICPlummed++;
1403                         return ERROR;
1404                 }
1405                 return SUCCESS;
1406         }
1407
1408         if (ntohs(mic->typelen) == 0x888E)
1409                 return SUCCESS;
1410
1411         if (memcmp (mic->u.snap, micsnap, sizeof(micsnap)) != 0) {
1412             // Mic enabled but packet isn't Mic'd
1413                 ai->micstats.rxMICPlummed++;
1414                 return ERROR;
1415         }
1416
1417         micSEQ = ntohl(mic->seq);            //store SEQ as CPU order
1418
1419         //At this point we a have a mic'd packet and mic is enabled
1420         //Now do the mic error checking.
1421
1422         //Receive seq must be odd
1423         if ( (micSEQ & 1) == 0 ) {
1424                 ai->micstats.rxWrongSequence++;
1425                 return ERROR;
1426         }
1427
1428         for (i = 0; i < NUM_MODULES; i++) {
1429                 int mcast = eth->da[0] & 1;
1430                 //Determine proper context 
1431                 context = mcast ? &ai->mod[i].mCtx : &ai->mod[i].uCtx;
1432         
1433                 //Make sure context is valid
1434                 if (!context->valid) {
1435                         if (i == 0)
1436                                 micError = NOMICPLUMMED;
1437                         continue;                
1438                 }
1439                 //DeMic it 
1440
1441                 if (!mic->typelen)
1442                         mic->typelen = htons(payLen + sizeof(MICBuffer) - 2);
1443         
1444                 emmh32_init(&context->seed);
1445                 emmh32_update(&context->seed, eth->da, ETH_ALEN*2); 
1446                 emmh32_update(&context->seed, (u8 *)&mic->typelen, sizeof(mic->typelen)+sizeof(mic->u.snap)); 
1447                 emmh32_update(&context->seed, (u8 *)&mic->seq,sizeof(mic->seq));        
1448                 emmh32_update(&context->seed, eth->da + ETH_ALEN*2,payLen);     
1449                 //Calculate MIC
1450                 emmh32_final(&context->seed, digest);
1451         
1452                 if (memcmp(digest, &mic->mic, 4)) { //Make sure the mics match
1453                   //Invalid Mic
1454                         if (i == 0)
1455                                 micError = INCORRECTMIC;
1456                         continue;
1457                 }
1458
1459                 //Check Sequence number if mics pass
1460                 if (RxSeqValid(ai, context, mcast, micSEQ) == SUCCESS) {
1461                         ai->micstats.rxSuccess++;
1462                         return SUCCESS;
1463                 }
1464                 if (i == 0)
1465                         micError = SEQUENCE;
1466         }
1467
1468         // Update statistics
1469         switch (micError) {
1470                 case NOMICPLUMMED: ai->micstats.rxMICPlummed++;   break;
1471                 case SEQUENCE:    ai->micstats.rxWrongSequence++; break;
1472                 case INCORRECTMIC: ai->micstats.rxIncorrectMIC++; break;
1473                 case NONE:  break;
1474                 case NOMIC: break;
1475         }
1476         return ERROR;
1477 }
1478
1479 /*===========================================================================
1480  * Description:  Checks the Rx Seq number to make sure it is valid
1481  *               and hasn't already been received
1482  *   
1483  *     Inputs: miccntx - mic context to check seq against
1484  *             micSeq  - the Mic seq number
1485  *   
1486  *    Returns: TRUE if valid otherwise FALSE. 
1487  *
1488  *    Author: sbraneky (10/15/01)
1489  *    Merciless hacks by rwilcher (1/14/02)
1490  *---------------------------------------------------------------------------
1491  */
1492
1493 static int RxSeqValid (struct airo_info *ai,miccntx *context,int mcast,u32 micSeq)
1494 {
1495         u32 seq,index;
1496
1497         //Allow for the ap being rebooted - if it is then use the next 
1498         //sequence number of the current sequence number - might go backwards
1499
1500         if (mcast) {
1501                 if (test_bit(FLAG_UPDATE_MULTI, &ai->flags)) {
1502                         clear_bit (FLAG_UPDATE_MULTI, &ai->flags);
1503                         context->window = (micSeq > 33) ? micSeq : 33;
1504                         context->rx     = 0;        // Reset rx
1505                 }
1506         } else if (test_bit(FLAG_UPDATE_UNI, &ai->flags)) {
1507                 clear_bit (FLAG_UPDATE_UNI, &ai->flags);
1508                 context->window = (micSeq > 33) ? micSeq : 33; // Move window
1509                 context->rx     = 0;        // Reset rx
1510         }
1511
1512         //Make sequence number relative to START of window
1513         seq = micSeq - (context->window - 33);
1514
1515         //Too old of a SEQ number to check.
1516         if ((s32)seq < 0)
1517                 return ERROR;
1518     
1519         if ( seq > 64 ) {
1520                 //Window is infinite forward
1521                 MoveWindow(context,micSeq);
1522                 return SUCCESS;
1523         }
1524
1525         // We are in the window. Now check the context rx bit to see if it was already sent
1526         seq >>= 1;         //divide by 2 because we only have odd numbers
1527         index = 1 << seq;  //Get an index number
1528
1529         if (!(context->rx & index)) {
1530                 //micSEQ falls inside the window.
1531                 //Add seqence number to the list of received numbers.
1532                 context->rx |= index;
1533
1534                 MoveWindow(context,micSeq);
1535
1536                 return SUCCESS;
1537         }
1538         return ERROR;
1539 }
1540
1541 static void MoveWindow(miccntx *context, u32 micSeq)
1542 {
1543         u32 shift;
1544
1545         //Move window if seq greater than the middle of the window
1546         if (micSeq > context->window) {
1547                 shift = (micSeq - context->window) >> 1;
1548     
1549                     //Shift out old
1550                 if (shift < 32)
1551                         context->rx >>= shift;
1552                 else
1553                         context->rx = 0;
1554
1555                 context->window = micSeq;      //Move window
1556         }
1557 }
1558
1559 /*==============================================*/
1560 /*========== EMMH ROUTINES  ====================*/
1561 /*==============================================*/
1562
1563 /* mic accumulate */
1564 #define MIC_ACCUM(val)  \
1565         context->accum += (u64)(val) * context->coeff[coeff_position++];
1566
1567 static unsigned char aes_counter[16];
1568
1569 /* expand the key to fill the MMH coefficient array */
1570 void emmh32_setseed(emmh32_context *context, u8 *pkey, int keylen, struct crypto_tfm *tfm)
1571 {
1572   /* take the keying material, expand if necessary, truncate at 16-bytes */
1573   /* run through AES counter mode to generate context->coeff[] */
1574   
1575         int i,j;
1576         u32 counter;
1577         u8 *cipher, plain[16];
1578         struct scatterlist sg[1];
1579
1580         crypto_cipher_setkey(tfm, pkey, 16);
1581         counter = 0;
1582         for (i = 0; i < (sizeof(context->coeff)/sizeof(context->coeff[0])); ) {
1583                 aes_counter[15] = (u8)(counter >> 0);
1584                 aes_counter[14] = (u8)(counter >> 8);
1585                 aes_counter[13] = (u8)(counter >> 16);
1586                 aes_counter[12] = (u8)(counter >> 24);
1587                 counter++;
1588                 memcpy (plain, aes_counter, 16);
1589                 sg[0].page = virt_to_page(plain);
1590                 sg[0].offset = ((long) plain & ~PAGE_MASK);
1591                 sg[0].length = 16;
1592                 crypto_cipher_encrypt(tfm, sg, sg, 16);
1593                 cipher = kmap(sg[0].page) + sg[0].offset;
1594                 for (j=0; (j<16) && (i< (sizeof(context->coeff)/sizeof(context->coeff[0]))); ) {
1595                         context->coeff[i++] = ntohl(*(u32 *)&cipher[j]);
1596                         j += 4;
1597                 }
1598         }
1599 }
1600
1601 /* prepare for calculation of a new mic */
1602 void emmh32_init(emmh32_context *context)
1603 {
1604         /* prepare for new mic calculation */
1605         context->accum = 0;
1606         context->position = 0;
1607 }
1608
1609 /* add some bytes to the mic calculation */
1610 void emmh32_update(emmh32_context *context, u8 *pOctets, int len)
1611 {
1612         int     coeff_position, byte_position;
1613   
1614         if (len == 0) return;
1615   
1616         coeff_position = context->position >> 2;
1617   
1618         /* deal with partial 32-bit word left over from last update */
1619         byte_position = context->position & 3;
1620         if (byte_position) {
1621                 /* have a partial word in part to deal with */
1622                 do {
1623                         if (len == 0) return;
1624                         context->part.d8[byte_position++] = *pOctets++;
1625                         context->position++;
1626                         len--;
1627                 } while (byte_position < 4);
1628                 MIC_ACCUM(htonl(context->part.d32));
1629         }
1630
1631         /* deal with full 32-bit words */
1632         while (len >= 4) {
1633                 MIC_ACCUM(htonl(*(u32 *)pOctets));
1634                 context->position += 4;
1635                 pOctets += 4;
1636                 len -= 4;
1637         }
1638
1639         /* deal with partial 32-bit word that will be left over from this update */
1640         byte_position = 0;
1641         while (len > 0) {
1642                 context->part.d8[byte_position++] = *pOctets++;
1643                 context->position++;
1644                 len--;
1645         }
1646 }
1647
1648 /* mask used to zero empty bytes for final partial word */
1649 static u32 mask32[4] = { 0x00000000L, 0xFF000000L, 0xFFFF0000L, 0xFFFFFF00L };
1650
1651 /* calculate the mic */
1652 void emmh32_final(emmh32_context *context, u8 digest[4])
1653 {
1654         int     coeff_position, byte_position;
1655         u32     val;
1656   
1657         u64 sum, utmp;
1658         s64 stmp;
1659
1660         coeff_position = context->position >> 2;
1661   
1662         /* deal with partial 32-bit word left over from last update */
1663         byte_position = context->position & 3;
1664         if (byte_position) {
1665                 /* have a partial word in part to deal with */
1666                 val = htonl(context->part.d32);
1667                 MIC_ACCUM(val & mask32[byte_position]); /* zero empty bytes */
1668         }
1669
1670         /* reduce the accumulated u64 to a 32-bit MIC */
1671         sum = context->accum;
1672         stmp = (sum  & 0xffffffffLL) - ((sum >> 32)  * 15);
1673         utmp = (stmp & 0xffffffffLL) - ((stmp >> 32) * 15);
1674         sum = utmp & 0xffffffffLL;
1675         if (utmp > 0x10000000fLL)
1676                 sum -= 15;
1677
1678         val = (u32)sum;
1679         digest[0] = (val>>24) & 0xFF;
1680         digest[1] = (val>>16) & 0xFF;
1681         digest[2] = (val>>8) & 0xFF;
1682         digest[3] = val & 0xFF;
1683 }
1684 #endif
1685
1686 static int readBSSListRid(struct airo_info *ai, int first,
1687                       BSSListRid *list) {
1688         int rc;
1689                         Cmd cmd;
1690                         Resp rsp;
1691
1692         if (first == 1) {
1693                         if (ai->flags & FLAG_RADIO_MASK) return -ENETDOWN;
1694                         memset(&cmd, 0, sizeof(cmd));
1695                         cmd.cmd=CMD_LISTBSS;
1696                         if (down_interruptible(&ai->sem))
1697                                 return -ERESTARTSYS;
1698                         issuecommand(ai, &cmd, &rsp);
1699                         up(&ai->sem);
1700                         /* Let the command take effect */
1701                         set_current_state (TASK_INTERRUPTIBLE);
1702                         ai->task = current;
1703                         schedule_timeout (3*HZ);
1704                         ai->task = NULL;
1705                 }
1706         rc = PC4500_readrid(ai, first ? RID_BSSLISTFIRST : RID_BSSLISTNEXT,
1707                             list, sizeof(*list), 1);
1708
1709         list->len = le16_to_cpu(list->len);
1710         list->index = le16_to_cpu(list->index);
1711         list->radioType = le16_to_cpu(list->radioType);
1712         list->cap = le16_to_cpu(list->cap);
1713         list->beaconInterval = le16_to_cpu(list->beaconInterval);
1714         list->fh.dwell = le16_to_cpu(list->fh.dwell);
1715         list->dsChannel = le16_to_cpu(list->dsChannel);
1716         list->atimWindow = le16_to_cpu(list->atimWindow);
1717         return rc;
1718 }
1719
1720 static int readWepKeyRid(struct airo_info*ai, WepKeyRid *wkr, int temp, int lock) {
1721         int rc = PC4500_readrid(ai, temp ? RID_WEP_TEMP : RID_WEP_PERM,
1722                                 wkr, sizeof(*wkr), lock);
1723
1724         wkr->len = le16_to_cpu(wkr->len);
1725         wkr->kindex = le16_to_cpu(wkr->kindex);
1726         wkr->klen = le16_to_cpu(wkr->klen);
1727         return rc;
1728 }
1729 /* In the writeXXXRid routines we copy the rids so that we don't screwup
1730  * the originals when we endian them... */
1731 static int writeWepKeyRid(struct airo_info*ai, WepKeyRid *pwkr, int perm, int lock) {
1732         int rc;
1733         WepKeyRid wkr = *pwkr;
1734
1735         wkr.len = cpu_to_le16(wkr.len);
1736         wkr.kindex = cpu_to_le16(wkr.kindex);
1737         wkr.klen = cpu_to_le16(wkr.klen);
1738         rc = PC4500_writerid(ai, RID_WEP_TEMP, &wkr, sizeof(wkr), lock);
1739         if (rc!=SUCCESS) printk(KERN_ERR "airo:  WEP_TEMP set %x\n", rc);
1740         if (perm) {
1741                 rc = PC4500_writerid(ai, RID_WEP_PERM, &wkr, sizeof(wkr), lock);
1742                 if (rc!=SUCCESS) {
1743                         printk(KERN_ERR "airo:  WEP_PERM set %x\n", rc);
1744                 }
1745         }
1746         return rc;
1747 }
1748
1749 static int readSsidRid(struct airo_info*ai, SsidRid *ssidr) {
1750         int i;
1751         int rc = PC4500_readrid(ai, RID_SSID, ssidr, sizeof(*ssidr), 1);
1752
1753         ssidr->len = le16_to_cpu(ssidr->len);
1754         for(i = 0; i < 3; i++) {
1755                 ssidr->ssids[i].len = le16_to_cpu(ssidr->ssids[i].len);
1756         }
1757         return rc;
1758 }
1759 static int writeSsidRid(struct airo_info*ai, SsidRid *pssidr, int lock) {
1760         int rc;
1761         int i;
1762         SsidRid ssidr = *pssidr;
1763
1764         ssidr.len = cpu_to_le16(ssidr.len);
1765         for(i = 0; i < 3; i++) {
1766                 ssidr.ssids[i].len = cpu_to_le16(ssidr.ssids[i].len);
1767         }
1768         rc = PC4500_writerid(ai, RID_SSID, &ssidr, sizeof(ssidr), lock);
1769         return rc;
1770 }
1771 static int readConfigRid(struct airo_info*ai, int lock) {
1772         int rc;
1773         u16 *s;
1774         ConfigRid cfg;
1775
1776         if (ai->config.len)
1777                 return SUCCESS;
1778
1779         rc = PC4500_readrid(ai, RID_ACTUALCONFIG, &cfg, sizeof(cfg), lock);
1780         if (rc != SUCCESS)
1781                 return rc;
1782
1783         for(s = &cfg.len; s <= &cfg.rtsThres; s++) *s = le16_to_cpu(*s);
1784
1785         for(s = &cfg.shortRetryLimit; s <= &cfg.radioType; s++)
1786                 *s = le16_to_cpu(*s);
1787
1788         for(s = &cfg.txPower; s <= &cfg.radioSpecific; s++)
1789                 *s = le16_to_cpu(*s);
1790
1791         for(s = &cfg.arlThreshold; s <= &cfg._reserved4[0]; s++)
1792                 *s = cpu_to_le16(*s);
1793
1794         for(s = &cfg.autoWake; s <= &cfg.autoWake; s++)
1795                 *s = cpu_to_le16(*s);
1796
1797         ai->config = cfg;
1798         return SUCCESS;
1799 }
1800 static inline void checkThrottle(struct airo_info *ai) {
1801         int i;
1802 /* Old hardware had a limit on encryption speed */
1803         if (ai->config.authType != AUTH_OPEN && maxencrypt) {
1804                 for(i=0; i<8; i++) {
1805                         if (ai->config.rates[i] > maxencrypt) {
1806                                 ai->config.rates[i] = 0;
1807                         }
1808                 }
1809         }
1810 }
1811 static int writeConfigRid(struct airo_info*ai, int lock) {
1812         u16 *s;
1813         ConfigRid cfgr;
1814
1815         if (!test_bit (FLAG_COMMIT, &ai->flags))
1816                 return SUCCESS;
1817
1818         clear_bit (FLAG_COMMIT, &ai->flags);
1819         clear_bit (FLAG_RESET, &ai->flags);
1820         checkThrottle(ai);
1821         cfgr = ai->config;
1822
1823         if ((cfgr.opmode & 0xFF) == MODE_STA_IBSS)
1824                 set_bit(FLAG_ADHOC, &ai->flags);
1825         else
1826                 clear_bit(FLAG_ADHOC, &ai->flags);
1827
1828         for(s = &cfgr.len; s <= &cfgr.rtsThres; s++) *s = cpu_to_le16(*s);
1829
1830         for(s = &cfgr.shortRetryLimit; s <= &cfgr.radioType; s++)
1831                 *s = cpu_to_le16(*s);
1832
1833         for(s = &cfgr.txPower; s <= &cfgr.radioSpecific; s++)
1834                 *s = cpu_to_le16(*s);
1835
1836         for(s = &cfgr.arlThreshold; s <= &cfgr._reserved4[0]; s++)
1837                 *s = cpu_to_le16(*s);
1838
1839         for(s = &cfgr.autoWake; s <= &cfgr.autoWake; s++)
1840                 *s = cpu_to_le16(*s);
1841
1842         return PC4500_writerid( ai, RID_CONFIG, &cfgr, sizeof(cfgr), lock);
1843 }
1844 static int readStatusRid(struct airo_info*ai, StatusRid *statr, int lock) {
1845         int rc = PC4500_readrid(ai, RID_STATUS, statr, sizeof(*statr), lock);
1846         u16 *s;
1847
1848         statr->len = le16_to_cpu(statr->len);
1849         for(s = &statr->mode; s <= &statr->SSIDlen; s++) *s = le16_to_cpu(*s);
1850
1851         for(s = &statr->beaconPeriod; s <= &statr->shortPreamble; s++)
1852                 *s = le16_to_cpu(*s);
1853         statr->load = le16_to_cpu(statr->load);
1854         statr->assocStatus = le16_to_cpu(statr->assocStatus);
1855         return rc;
1856 }
1857 static int readAPListRid(struct airo_info*ai, APListRid *aplr) {
1858         int rc =  PC4500_readrid(ai, RID_APLIST, aplr, sizeof(*aplr), 1);
1859         aplr->len = le16_to_cpu(aplr->len);
1860         return rc;
1861 }
1862 static int writeAPListRid(struct airo_info*ai, APListRid *aplr, int lock) {
1863         int rc;
1864         aplr->len = cpu_to_le16(aplr->len);
1865         rc = PC4500_writerid(ai, RID_APLIST, aplr, sizeof(*aplr), lock);
1866         return rc;
1867 }
1868 static int readCapabilityRid(struct airo_info*ai, CapabilityRid *capr, int lock) {
1869         int rc = PC4500_readrid(ai, RID_CAPABILITIES, capr, sizeof(*capr), lock);
1870         u16 *s;
1871
1872         capr->len = le16_to_cpu(capr->len);
1873         capr->prodNum = le16_to_cpu(capr->prodNum);
1874         capr->radioType = le16_to_cpu(capr->radioType);
1875         capr->country = le16_to_cpu(capr->country);
1876         for(s = &capr->txPowerLevels[0]; s <= &capr->requiredHard; s++)
1877                 *s = le16_to_cpu(*s);
1878         return rc;
1879 }
1880 static int readStatsRid(struct airo_info*ai, StatsRid *sr, int rid, int lock) {
1881         int rc = PC4500_readrid(ai, rid, sr, sizeof(*sr), lock);
1882         u32 *i;
1883
1884         sr->len = le16_to_cpu(sr->len);
1885         for(i = &sr->vals[0]; i <= &sr->vals[99]; i++) *i = le32_to_cpu(*i);
1886         return rc;
1887 }
1888
1889 static int airo_open(struct net_device *dev) {
1890         struct airo_info *info = dev->priv;
1891         Resp rsp;
1892
1893         if (test_bit(FLAG_FLASHING, &info->flags))
1894                 return -EIO;
1895
1896         /* Make sure the card is configured.
1897          * Wireless Extensions may postpone config changes until the card
1898          * is open (to pipeline changes and speed-up card setup). If
1899          * those changes are not yet commited, do it now - Jean II */
1900         if (test_bit (FLAG_COMMIT, &info->flags)) {
1901                 disable_MAC(info, 1);
1902                 writeConfigRid(info, 1);
1903         }
1904
1905         if (info->wifidev != dev) {
1906                 /* Power on the MAC controller (which may have been disabled) */
1907                 clear_bit(FLAG_RADIO_DOWN, &info->flags);
1908                 enable_interrupts(info);
1909         }
1910         enable_MAC(info, &rsp, 1);
1911
1912         netif_start_queue(dev);
1913         return 0;
1914 }
1915
1916 static int mpi_start_xmit(struct sk_buff *skb, struct net_device *dev) {
1917         int npacks, pending;
1918         unsigned long flags;
1919         struct airo_info *ai = dev->priv;
1920
1921         if (!skb) {
1922                 printk(KERN_ERR "airo: %s: skb==NULL\n",__FUNCTION__);
1923                 return 0;
1924         }
1925         npacks = skb_queue_len (&ai->txq);
1926
1927         if (npacks >= MAXTXQ - 1) {
1928                 netif_stop_queue (dev);
1929                 if (npacks > MAXTXQ) {
1930                         ai->stats.tx_fifo_errors++;
1931                         return 1;
1932                 }
1933                 skb_queue_tail (&ai->txq, skb);
1934                 return 0;
1935         }
1936
1937         spin_lock_irqsave(&ai->aux_lock, flags);
1938         skb_queue_tail (&ai->txq, skb);
1939         pending = test_bit(FLAG_PENDING_XMIT, &ai->flags);
1940         spin_unlock_irqrestore(&ai->aux_lock,flags);
1941         netif_wake_queue (dev);
1942
1943         if (pending == 0) {
1944                 set_bit(FLAG_PENDING_XMIT, &ai->flags);
1945                 mpi_send_packet (dev);
1946         }
1947         return 0;
1948 }
1949
1950 /*
1951  * @mpi_send_packet
1952  *
1953  * Attempt to transmit a packet. Can be called from interrupt
1954  * or transmit . return number of packets we tried to send
1955  */
1956
1957 static int mpi_send_packet (struct net_device *dev)
1958 {
1959         struct sk_buff *skb;
1960         unsigned char *buffer;
1961         s16 len, *payloadLen;
1962         struct airo_info *ai = dev->priv;
1963         u8 *sendbuf;
1964
1965         /* get a packet to send */
1966
1967         if ((skb = skb_dequeue(&ai->txq)) == 0) {
1968                 printk (KERN_ERR
1969                         "airo: %s: Dequeue'd zero in send_packet()\n",
1970                         __FUNCTION__);
1971                 return 0;
1972         }
1973
1974         /* check min length*/
1975         len = ETH_ZLEN < skb->len ? skb->len : ETH_ZLEN;
1976         buffer = skb->data;
1977
1978         ai->txfids[0].tx_desc.offset = 0;
1979         ai->txfids[0].tx_desc.valid = 1;
1980         ai->txfids[0].tx_desc.eoc = 1;
1981         ai->txfids[0].tx_desc.len =len+sizeof(WifiHdr);
1982
1983 /*
1984  * Magic, the cards firmware needs a length count (2 bytes) in the host buffer
1985  * right after  TXFID_HDR.The TXFID_HDR contains the status short so payloadlen
1986  * is immediatly after it. ------------------------------------------------
1987  *                         |TXFIDHDR+STATUS|PAYLOADLEN|802.3HDR|PACKETDATA|
1988  *                         ------------------------------------------------
1989  */
1990
1991         memcpy((char *)ai->txfids[0].virtual_host_addr,
1992                 (char *)&wifictlhdr8023, sizeof(wifictlhdr8023));
1993
1994         payloadLen = (s16 *)(ai->txfids[0].virtual_host_addr +
1995                 sizeof(wifictlhdr8023));
1996         sendbuf = ai->txfids[0].virtual_host_addr +
1997                 sizeof(wifictlhdr8023) + 2 ;
1998
1999         /*
2000          * Firmware automaticly puts 802 header on so
2001          * we don't need to account for it in the length
2002          */
2003 #ifdef MICSUPPORT
2004         if (test_bit(FLAG_MIC_CAPABLE, &ai->flags) && ai->micstats.enabled &&
2005                 (ntohs(((u16 *)buffer)[6]) != 0x888E)) {
2006                 MICBuffer pMic;
2007
2008                 if (encapsulate(ai, (etherHead *)buffer, &pMic, len - sizeof(etherHead)) != SUCCESS)
2009                         return ERROR;
2010
2011                 *payloadLen = cpu_to_le16(len-sizeof(etherHead)+sizeof(pMic));
2012                 ai->txfids[0].tx_desc.len += sizeof(pMic);
2013                 /* copy data into airo dma buffer */
2014                 memcpy (sendbuf, buffer, sizeof(etherHead));
2015                 buffer += sizeof(etherHead);
2016                 sendbuf += sizeof(etherHead);
2017                 memcpy (sendbuf, &pMic, sizeof(pMic));
2018                 sendbuf += sizeof(pMic);
2019                 memcpy (sendbuf, buffer, len - sizeof(etherHead));
2020         } else
2021 #endif
2022         {
2023                 *payloadLen = cpu_to_le16(len - sizeof(etherHead));
2024
2025                 dev->trans_start = jiffies;
2026
2027                 /* copy data into airo dma buffer */
2028                 memcpy(sendbuf, buffer, len);
2029         }
2030
2031         memcpy_toio(ai->txfids[0].card_ram_off,
2032                 &ai->txfids[0].tx_desc, sizeof(TxFid));
2033
2034         OUT4500(ai, EVACK, 8);
2035
2036         dev_kfree_skb_any(skb);
2037         return 1;
2038 }
2039
2040 static void get_tx_error(struct airo_info *ai, u32 fid)
2041 {
2042         u16 status;
2043
2044         if (fid < 0)
2045                 status = ((WifiCtlHdr *)ai->txfids[0].virtual_host_addr)->ctlhdr.status;
2046         else {
2047                 if (bap_setup(ai, ai->fids[fid] & 0xffff, 4, BAP0) != SUCCESS)
2048                         return;
2049                 bap_read(ai, &status, 2, BAP0);
2050         }
2051         if (le16_to_cpu(status) & 2) /* Too many retries */
2052                 ai->stats.tx_aborted_errors++;
2053         if (le16_to_cpu(status) & 4) /* Transmit lifetime exceeded */
2054                 ai->stats.tx_heartbeat_errors++;
2055         if (le16_to_cpu(status) & 8) /* Aid fail */
2056                 { }
2057         if (le16_to_cpu(status) & 0x10) /* MAC disabled */
2058                 ai->stats.tx_carrier_errors++;
2059         if (le16_to_cpu(status) & 0x20) /* Association lost */
2060                 { }
2061         /* We produce a TXDROP event only for retry or lifetime
2062          * exceeded, because that's the only status that really mean
2063          * that this particular node went away.
2064          * Other errors means that *we* screwed up. - Jean II */
2065         if ((le16_to_cpu(status) & 2) ||
2066              (le16_to_cpu(status) & 4)) {
2067                 union iwreq_data        wrqu;
2068                 char junk[0x18];
2069
2070                 /* Faster to skip over useless data than to do
2071                  * another bap_setup(). We are at offset 0x6 and
2072                  * need to go to 0x18 and read 6 bytes - Jean II */
2073                 bap_read(ai, (u16 *) junk, 0x18, BAP0);
2074
2075                 /* Copy 802.11 dest address.
2076                  * We use the 802.11 header because the frame may
2077                  * not be 802.3 or may be mangled...
2078                  * In Ad-Hoc mode, it will be the node address.
2079                  * In managed mode, it will be most likely the AP addr
2080                  * User space will figure out how to convert it to
2081                  * whatever it needs (IP address or else).
2082                  * - Jean II */
2083                 memcpy(wrqu.addr.sa_data, junk + 0x12, ETH_ALEN);
2084                 wrqu.addr.sa_family = ARPHRD_ETHER;
2085
2086                 /* Send event to user space */
2087                 wireless_send_event(ai->dev, IWEVTXDROP, &wrqu, NULL);
2088         }
2089 }
2090
2091 static void airo_end_xmit(struct net_device *dev) {
2092         u16 status;
2093         int i;
2094         struct airo_info *priv = dev->priv;
2095         struct sk_buff *skb = priv->xmit.skb;
2096         int fid = priv->xmit.fid;
2097         u32 *fids = priv->fids;
2098
2099         clear_bit(JOB_XMIT, &priv->flags);
2100         clear_bit(FLAG_PENDING_XMIT, &priv->flags);
2101         status = transmit_802_3_packet (priv, fids[fid], skb->data);
2102         up(&priv->sem);
2103
2104         i = 0;
2105         if ( status == SUCCESS ) {
2106                 dev->trans_start = jiffies;
2107                 for (; i < MAX_FIDS / 2 && (priv->fids[i] & 0xffff0000); i++);
2108         } else {
2109                 priv->fids[fid] &= 0xffff;
2110                 priv->stats.tx_window_errors++;
2111         }
2112         if (i < MAX_FIDS / 2)
2113                 netif_wake_queue(dev);
2114         dev_kfree_skb(skb);
2115 }
2116
2117 static int airo_start_xmit(struct sk_buff *skb, struct net_device *dev) {
2118         s16 len;
2119         int i, j;
2120         struct airo_info *priv = dev->priv;
2121         u32 *fids = priv->fids;
2122
2123         if ( skb == NULL ) {
2124                 printk( KERN_ERR "airo:  skb == NULL!!!\n" );
2125                 return 0;
2126         }
2127
2128         /* Find a vacant FID */
2129         for( i = 0; i < MAX_FIDS / 2 && (fids[i] & 0xffff0000); i++ );
2130         for( j = i + 1; j < MAX_FIDS / 2 && (fids[j] & 0xffff0000); j++ );
2131
2132         if ( j >= MAX_FIDS / 2 ) {
2133                 netif_stop_queue(dev);
2134
2135                 if (i == MAX_FIDS / 2) {
2136                         priv->stats.tx_fifo_errors++;
2137                         return 1;
2138                 }
2139         }
2140         /* check min length*/
2141         len = ETH_ZLEN < skb->len ? skb->len : ETH_ZLEN;
2142         /* Mark fid as used & save length for later */
2143         fids[i] |= (len << 16);
2144         priv->xmit.skb = skb;
2145         priv->xmit.fid = i;
2146         if (down_trylock(&priv->sem) != 0) {
2147                 set_bit(FLAG_PENDING_XMIT, &priv->flags);
2148                 netif_stop_queue(dev);
2149                 set_bit(JOB_XMIT, &priv->flags);
2150                 wake_up_interruptible(&priv->thr_wait);
2151         } else
2152                 airo_end_xmit(dev);
2153         return 0;
2154 }
2155
2156 static void airo_end_xmit11(struct net_device *dev) {
2157         u16 status;
2158         int i;
2159         struct airo_info *priv = dev->priv;
2160         struct sk_buff *skb = priv->xmit11.skb;
2161         int fid = priv->xmit11.fid;
2162         u32 *fids = priv->fids;
2163
2164         clear_bit(JOB_XMIT11, &priv->flags);
2165         clear_bit(FLAG_PENDING_XMIT11, &priv->flags);
2166         status = transmit_802_11_packet (priv, fids[fid], skb->data);
2167         up(&priv->sem);
2168
2169         i = MAX_FIDS / 2;
2170         if ( status == SUCCESS ) {
2171                 dev->trans_start = jiffies;
2172                 for (; i < MAX_FIDS && (priv->fids[i] & 0xffff0000); i++);
2173         } else {
2174                 priv->fids[fid] &= 0xffff;
2175                 priv->stats.tx_window_errors++;
2176         }
2177         if (i < MAX_FIDS)
2178                 netif_wake_queue(dev);
2179         dev_kfree_skb(skb);
2180 }
2181
2182 static int airo_start_xmit11(struct sk_buff *skb, struct net_device *dev) {
2183         s16 len;
2184         int i, j;
2185         struct airo_info *priv = dev->priv;
2186         u32 *fids = priv->fids;
2187
2188         if (test_bit(FLAG_MPI, &priv->flags)) {
2189                 /* Not implemented yet for MPI350 */
2190                 netif_stop_queue(dev);
2191                 return -ENETDOWN;
2192         }
2193
2194         if ( skb == NULL ) {
2195                 printk( KERN_ERR "airo:  skb == NULL!!!\n" );
2196                 return 0;
2197         }
2198
2199         /* Find a vacant FID */
2200         for( i = MAX_FIDS / 2; i < MAX_FIDS && (fids[i] & 0xffff0000); i++ );
2201         for( j = i + 1; j < MAX_FIDS && (fids[j] & 0xffff0000); j++ );
2202
2203         if ( j >= MAX_FIDS ) {
2204                 netif_stop_queue(dev);
2205
2206                 if (i == MAX_FIDS) {
2207                         priv->stats.tx_fifo_errors++;
2208                         return 1;
2209                 }
2210         }
2211         /* check min length*/
2212         len = ETH_ZLEN < skb->len ? skb->len : ETH_ZLEN;
2213         /* Mark fid as used & save length for later */
2214         fids[i] |= (len << 16);
2215         priv->xmit11.skb = skb;
2216         priv->xmit11.fid = i;
2217         if (down_trylock(&priv->sem) != 0) {
2218                 set_bit(FLAG_PENDING_XMIT11, &priv->flags);
2219                 netif_stop_queue(dev);
2220                 set_bit(JOB_XMIT11, &priv->flags);
2221                 wake_up_interruptible(&priv->thr_wait);
2222         } else
2223                 airo_end_xmit11(dev);
2224         return 0;
2225 }
2226
2227 static void airo_read_stats(struct airo_info *ai) {
2228         StatsRid stats_rid;
2229         u32 *vals = stats_rid.vals;
2230
2231         clear_bit(JOB_STATS, &ai->flags);
2232         if (ai->power) {
2233                 up(&ai->sem);
2234                 return;
2235         }
2236         readStatsRid(ai, &stats_rid, RID_STATS, 0);
2237         up(&ai->sem);
2238
2239         ai->stats.rx_packets = vals[43] + vals[44] + vals[45];
2240         ai->stats.tx_packets = vals[39] + vals[40] + vals[41];
2241         ai->stats.rx_bytes = vals[92];
2242         ai->stats.tx_bytes = vals[91];
2243         ai->stats.rx_errors = vals[0] + vals[2] + vals[3] + vals[4];
2244         ai->stats.tx_errors = vals[42] + ai->stats.tx_fifo_errors;
2245         ai->stats.multicast = vals[43];
2246         ai->stats.collisions = vals[89];
2247
2248         /* detailed rx_errors: */
2249         ai->stats.rx_length_errors = vals[3];
2250         ai->stats.rx_crc_errors = vals[4];
2251         ai->stats.rx_frame_errors = vals[2];
2252         ai->stats.rx_fifo_errors = vals[0];
2253 }
2254
2255 struct net_device_stats *airo_get_stats(struct net_device *dev)
2256 {
2257         struct airo_info *local =  dev->priv;
2258
2259         if (!test_bit(JOB_STATS, &local->flags)) {
2260                 /* Get stats out of the card if available */
2261                 if (down_trylock(&local->sem) != 0) {
2262                         set_bit(JOB_STATS, &local->flags);
2263                         wake_up_interruptible(&local->thr_wait);
2264                 } else
2265                         airo_read_stats(local);
2266         }
2267
2268         return &local->stats;
2269 }
2270
2271 static void airo_set_promisc(struct airo_info *ai) {
2272         Cmd cmd;
2273         Resp rsp;
2274
2275         memset(&cmd, 0, sizeof(cmd));
2276         cmd.cmd=CMD_SETMODE;
2277         clear_bit(JOB_PROMISC, &ai->flags);
2278         cmd.parm0=(ai->flags&IFF_PROMISC) ? PROMISC : NOPROMISC;
2279         issuecommand(ai, &cmd, &rsp);
2280         up(&ai->sem);
2281 }
2282
2283 static void airo_set_multicast_list(struct net_device *dev) {
2284         struct airo_info *ai = dev->priv;
2285
2286         if ((dev->flags ^ ai->flags) & IFF_PROMISC) {
2287                 change_bit(FLAG_PROMISC, &ai->flags);
2288                 if (down_trylock(&ai->sem) != 0) {
2289                         set_bit(JOB_PROMISC, &ai->flags);
2290                         wake_up_interruptible(&ai->thr_wait);
2291                 } else
2292                         airo_set_promisc(ai);
2293         }
2294
2295         if ((dev->flags&IFF_ALLMULTI)||dev->mc_count>0) {
2296                 /* Turn on multicast.  (Should be already setup...) */
2297         }
2298 }
2299
2300 static int airo_set_mac_address(struct net_device *dev, void *p)
2301 {
2302         struct airo_info *ai = dev->priv;
2303         struct sockaddr *addr = p;
2304         Resp rsp;
2305
2306         readConfigRid(ai, 1);
2307         memcpy (ai->config.macAddr, addr->sa_data, dev->addr_len);
2308         set_bit (FLAG_COMMIT, &ai->flags);
2309         disable_MAC(ai, 1);
2310         writeConfigRid (ai, 1);
2311         enable_MAC(ai, &rsp, 1);
2312         memcpy (ai->dev->dev_addr, addr->sa_data, dev->addr_len);
2313         if (ai->wifidev)
2314                 memcpy (ai->wifidev->dev_addr, addr->sa_data, dev->addr_len);
2315         return 0;
2316 }
2317
2318 static int airo_change_mtu(struct net_device *dev, int new_mtu)
2319 {
2320         if ((new_mtu < 68) || (new_mtu > 2400))
2321                 return -EINVAL;
2322         dev->mtu = new_mtu;
2323         return 0;
2324 }
2325
2326
2327 static int airo_close(struct net_device *dev) {
2328         struct airo_info *ai = dev->priv;
2329
2330         netif_stop_queue(dev);
2331
2332         if (ai->wifidev != dev) {
2333 #ifdef POWER_ON_DOWN
2334                 /* Shut power to the card. The idea is that the user can save
2335                  * power when he doesn't need the card with "ifconfig down".
2336                  * That's the method that is most friendly towards the network
2337                  * stack (i.e. the network stack won't try to broadcast
2338                  * anything on the interface and routes are gone. Jean II */
2339                 set_bit(FLAG_RADIO_DOWN, &ai->flags);
2340                 disable_MAC(ai, 1);
2341 #endif
2342                 disable_interrupts( ai );
2343         }
2344         return 0;
2345 }
2346
2347 static void del_airo_dev( struct net_device *dev );
2348
2349 void stop_airo_card( struct net_device *dev, int freeres )
2350 {
2351         struct airo_info *ai = dev->priv;
2352
2353         set_bit(FLAG_RADIO_DOWN, &ai->flags);
2354         disable_MAC(ai, 1);
2355         disable_interrupts(ai);
2356         free_irq( dev->irq, dev );
2357         takedown_proc_entry( dev, ai );
2358         if (test_bit(FLAG_REGISTERED, &ai->flags)) {
2359                 unregister_netdev( dev );
2360                 if (ai->wifidev) {
2361                         unregister_netdev(ai->wifidev);
2362                         free_netdev(ai->wifidev);
2363                         ai->wifidev = NULL;
2364                 }
2365                 clear_bit(FLAG_REGISTERED, &ai->flags);
2366         }
2367         set_bit(JOB_DIE, &ai->flags);
2368         kill_proc(ai->thr_pid, SIGTERM, 1);
2369         wait_for_completion(&ai->thr_exited);
2370
2371         /*
2372          * Clean out tx queue
2373          */
2374         if (test_bit(FLAG_MPI, &ai->flags) && skb_queue_len (&ai->txq) > 0) {
2375                 struct sk_buff *skb = NULL;
2376                 for (;(skb = skb_dequeue(&ai->txq));)
2377                         dev_kfree_skb(skb);
2378         }
2379
2380         if (ai->flash)
2381                 kfree(ai->flash);
2382         if (ai->rssi)
2383                 kfree(ai->rssi);
2384         if (ai->APList)
2385                 kfree(ai->APList);
2386         if (ai->SSID)
2387                 kfree(ai->SSID);
2388         if (freeres) {
2389                 /* PCMCIA frees this stuff, so only for PCI and ISA */
2390                 release_region( dev->base_addr, 64 );
2391                 if (test_bit(FLAG_MPI, &ai->flags)) {
2392                         if (ai->pci)
2393                                 mpi_unmap_card(ai->pci);
2394                         if (ai->pcimem)
2395                                 iounmap(ai->pcimem);
2396                         if (ai->pciaux)
2397                                 iounmap(ai->pciaux);
2398                         pci_free_consistent(ai->pci, PCI_SHARED_LEN,
2399                                 ai->shared, ai->shared_dma);
2400                 }
2401         }
2402 #ifdef MICSUPPORT
2403         if (ai->tfm)
2404                 crypto_free_tfm(ai->tfm);
2405 #endif
2406         del_airo_dev( dev );
2407         free_netdev( dev );
2408 }
2409
2410 EXPORT_SYMBOL(stop_airo_card);
2411
2412 static int add_airo_dev( struct net_device *dev );
2413
2414 int wll_header_parse(struct sk_buff *skb, unsigned char *haddr)
2415 {
2416         memcpy(haddr, skb->mac.raw + 10, ETH_ALEN);
2417         return ETH_ALEN;
2418 }
2419
2420 static void mpi_unmap_card(struct pci_dev *pci)
2421 {
2422         unsigned long mem_start = pci_resource_start(pci, 1);
2423         unsigned long mem_len = pci_resource_len(pci, 1);
2424         unsigned long aux_start = pci_resource_start(pci, 2);
2425         unsigned long aux_len = AUXMEMSIZE;
2426
2427         release_mem_region(aux_start, aux_len);
2428         release_mem_region(mem_start, mem_len);
2429 }
2430
2431 /*************************************************************
2432  *  This routine assumes that descriptors have been setup .
2433  *  Run at insmod time or after reset  when the decriptors
2434  *  have been initialized . Returns 0 if all is well nz
2435  *  otherwise . Does not allocate memory but sets up card
2436  *  using previously allocated descriptors.
2437  */
2438 static int mpi_init_descriptors (struct airo_info *ai)
2439 {
2440         Cmd cmd;
2441         Resp rsp;
2442         int i;
2443         int rc = SUCCESS;
2444
2445         /* Alloc  card RX descriptors */
2446         netif_stop_queue(ai->dev);
2447
2448         memset(&rsp,0,sizeof(rsp));
2449         memset(&cmd,0,sizeof(cmd));
2450
2451         cmd.cmd = CMD_ALLOCATEAUX;
2452         cmd.parm0 = FID_RX;
2453         cmd.parm1 = (ai->rxfids[0].card_ram_off - ai->pciaux);
2454         cmd.parm2 = MPI_MAX_FIDS;
2455         rc=issuecommand(ai, &cmd, &rsp);
2456         if (rc != SUCCESS) {
2457                 printk(KERN_ERR "airo:  Couldn't allocate RX FID\n");
2458                 return rc;
2459         }
2460
2461         for (i=0; i<MPI_MAX_FIDS; i++) {
2462                 memcpy_toio(ai->rxfids[i].card_ram_off,
2463                         &ai->rxfids[i].rx_desc, sizeof(RxFid));
2464         }
2465
2466         /* Alloc card TX descriptors */
2467
2468         memset(&rsp,0,sizeof(rsp));
2469         memset(&cmd,0,sizeof(cmd));
2470
2471         cmd.cmd = CMD_ALLOCATEAUX;
2472         cmd.parm0 = FID_TX;
2473         cmd.parm1 = (ai->txfids[0].card_ram_off - ai->pciaux);
2474         cmd.parm2 = MPI_MAX_FIDS;
2475
2476         for (i=0; i<MPI_MAX_FIDS; i++) {
2477                 ai->txfids[i].tx_desc.valid = 1;
2478                 memcpy_toio(ai->txfids[i].card_ram_off,
2479                         &ai->txfids[i].tx_desc, sizeof(TxFid));
2480         }
2481         ai->txfids[i-1].tx_desc.eoc = 1; /* Last descriptor has EOC set */
2482
2483         rc=issuecommand(ai, &cmd, &rsp);
2484         if (rc != SUCCESS) {
2485                 printk(KERN_ERR "airo:  Couldn't allocate TX FID\n");
2486                 return rc;
2487         }
2488
2489         /* Alloc card Rid descriptor */
2490         memset(&rsp,0,sizeof(rsp));
2491         memset(&cmd,0,sizeof(cmd));
2492
2493         cmd.cmd = CMD_ALLOCATEAUX;
2494         cmd.parm0 = RID_RW;
2495         cmd.parm1 = (ai->config_desc.card_ram_off - ai->pciaux);
2496         cmd.parm2 = 1; /* Magic number... */
2497         rc=issuecommand(ai, &cmd, &rsp);
2498         if (rc != SUCCESS) {
2499                 printk(KERN_ERR "airo:  Couldn't allocate RID\n");
2500                 return rc;
2501         }
2502
2503         memcpy_toio(ai->config_desc.card_ram_off,
2504                 &ai->config_desc.rid_desc, sizeof(Rid));
2505
2506         return rc;
2507 }
2508
2509 /*
2510  * We are setting up three things here:
2511  * 1) Map AUX memory for descriptors: Rid, TxFid, or RxFid.
2512  * 2) Map PCI memory for issueing commands.
2513  * 3) Allocate memory (shared) to send and receive ethernet frames.
2514  */
2515 static int mpi_map_card(struct airo_info *ai, struct pci_dev *pci,
2516                     const char *name)
2517 {
2518         unsigned long mem_start, mem_len, aux_start, aux_len;
2519         int rc = -1;
2520         int i;
2521         unsigned char *busaddroff,*vpackoff;
2522         unsigned char __iomem *pciaddroff;
2523
2524         mem_start = pci_resource_start(pci, 1);
2525         mem_len = pci_resource_len(pci, 1);
2526         aux_start = pci_resource_start(pci, 2);
2527         aux_len = AUXMEMSIZE;
2528
2529         if (!request_mem_region(mem_start, mem_len, name)) {
2530                 printk(KERN_ERR "airo: Couldn't get region %x[%x] for %s\n",
2531                        (int)mem_start, (int)mem_len, name);
2532                 goto out;
2533         }
2534         if (!request_mem_region(aux_start, aux_len, name)) {
2535                 printk(KERN_ERR "airo: Couldn't get region %x[%x] for %s\n",
2536                        (int)aux_start, (int)aux_len, name);
2537                 goto free_region1;
2538         }
2539
2540         ai->pcimem = ioremap(mem_start, mem_len);
2541         if (!ai->pcimem) {
2542                 printk(KERN_ERR "airo: Couldn't map region %x[%x] for %s\n",
2543                        (int)mem_start, (int)mem_len, name);
2544                 goto free_region2;
2545         }
2546         ai->pciaux = ioremap(aux_start, aux_len);
2547         if (!ai->pciaux) {
2548                 printk(KERN_ERR "airo: Couldn't map region %x[%x] for %s\n",
2549                        (int)aux_start, (int)aux_len, name);
2550                 goto free_memmap;
2551         }
2552
2553         /* Reserve PKTSIZE for each fid and 2K for the Rids */
2554         ai->shared = pci_alloc_consistent(pci, PCI_SHARED_LEN, &ai->shared_dma);
2555         if (!ai->shared) {
2556                 printk(KERN_ERR "airo: Couldn't alloc_consistent %d\n",
2557                        PCI_SHARED_LEN);
2558                 goto free_auxmap;
2559         }
2560
2561         /*
2562          * Setup descriptor RX, TX, CONFIG
2563          */
2564         busaddroff = (unsigned char *)ai->shared_dma;
2565         pciaddroff = ai->pciaux + AUX_OFFSET;
2566         vpackoff   = ai->shared;
2567
2568         /* RX descriptor setup */
2569         for(i = 0; i < MPI_MAX_FIDS; i++) {
2570                 ai->rxfids[i].pending = 0;
2571                 ai->rxfids[i].card_ram_off = pciaddroff;
2572                 ai->rxfids[i].virtual_host_addr = vpackoff;
2573                 ai->rxfids[i].rx_desc.host_addr = (dma_addr_t) busaddroff;
2574                 ai->rxfids[i].rx_desc.valid = 1;
2575                 ai->rxfids[i].rx_desc.len = PKTSIZE;
2576                 ai->rxfids[i].rx_desc.rdy = 0;
2577
2578                 pciaddroff += sizeof(RxFid);
2579                 busaddroff += PKTSIZE;
2580                 vpackoff   += PKTSIZE;
2581         }
2582
2583         /* TX descriptor setup */
2584         for(i = 0; i < MPI_MAX_FIDS; i++) {
2585                 ai->txfids[i].card_ram_off = pciaddroff;
2586                 ai->txfids[i].virtual_host_addr = vpackoff;
2587                 ai->txfids[i].tx_desc.valid = 1;
2588                 ai->txfids[i].tx_desc.host_addr = (dma_addr_t) busaddroff;
2589                 memcpy(ai->txfids[i].virtual_host_addr,
2590                         &wifictlhdr8023, sizeof(wifictlhdr8023));
2591
2592                 pciaddroff += sizeof(TxFid);
2593                 busaddroff += PKTSIZE;
2594                 vpackoff   += PKTSIZE;
2595         }
2596         ai->txfids[i-1].tx_desc.eoc = 1; /* Last descriptor has EOC set */
2597
2598         /* Rid descriptor setup */
2599         ai->config_desc.card_ram_off = pciaddroff;
2600         ai->config_desc.virtual_host_addr = vpackoff;
2601         ai->config_desc.rid_desc.host_addr = (dma_addr_t) busaddroff;
2602         ai->ridbus = (dma_addr_t)busaddroff;
2603         ai->config_desc.rid_desc.rid = 0;
2604         ai->config_desc.rid_desc.len = RIDSIZE;
2605         ai->config_desc.rid_desc.valid = 1;
2606         pciaddroff += sizeof(Rid);
2607         busaddroff += RIDSIZE;
2608         vpackoff   += RIDSIZE;
2609
2610         /* Tell card about descriptors */
2611         if (mpi_init_descriptors (ai) != SUCCESS)
2612                 goto free_shared;
2613
2614         return 0;
2615  free_shared:
2616         pci_free_consistent(pci, PCI_SHARED_LEN, ai->shared, ai->shared_dma);
2617  free_auxmap:
2618         iounmap(ai->pciaux);
2619  free_memmap:
2620         iounmap(ai->pcimem);
2621  free_region2:
2622         release_mem_region(aux_start, aux_len);
2623  free_region1:
2624         release_mem_region(mem_start, mem_len);
2625  out:
2626         return rc;
2627 }
2628
2629 static void wifi_setup(struct net_device *dev)
2630 {
2631         dev->hard_header        = NULL;
2632         dev->rebuild_header     = NULL;
2633         dev->hard_header_cache  = NULL;
2634         dev->header_cache_update= NULL;
2635
2636         dev->hard_header_parse  = wll_header_parse;
2637         dev->hard_start_xmit = &airo_start_xmit11;
2638         dev->get_stats = &airo_get_stats;
2639         dev->set_mac_address = &airo_set_mac_address;
2640         dev->do_ioctl = &airo_ioctl;
2641 #ifdef WIRELESS_EXT
2642         dev->wireless_handlers = &airo_handler_def;
2643 #endif /* WIRELESS_EXT */
2644         dev->change_mtu = &airo_change_mtu;
2645         dev->open = &airo_open;
2646         dev->stop = &airo_close;
2647
2648         dev->type               = ARPHRD_IEEE80211;
2649         dev->hard_header_len    = ETH_HLEN;
2650         dev->mtu                = 2312;
2651         dev->addr_len           = ETH_ALEN;
2652         dev->tx_queue_len       = 100; 
2653
2654         memset(dev->broadcast,0xFF, ETH_ALEN);
2655
2656         dev->flags              = IFF_BROADCAST|IFF_MULTICAST;
2657 }
2658
2659 static struct net_device *init_wifidev(struct airo_info *ai,
2660                                         struct net_device *ethdev)
2661 {
2662         int err;
2663         struct net_device *dev = alloc_netdev(0, "wifi%d", wifi_setup);
2664         if (!dev)
2665                 return NULL;
2666         dev->priv = ethdev->priv;
2667         dev->irq = ethdev->irq;
2668         dev->base_addr = ethdev->base_addr;
2669 #ifdef WIRELESS_EXT
2670         dev->wireless_data = ethdev->wireless_data;
2671 #endif /* WIRELESS_EXT */
2672         memcpy(dev->dev_addr, ethdev->dev_addr, dev->addr_len);
2673         err = register_netdev(dev);
2674         if (err<0) {
2675                 free_netdev(dev);
2676                 return NULL;
2677         }
2678         return dev;
2679 }
2680
2681 int reset_card( struct net_device *dev , int lock) {
2682         struct airo_info *ai = dev->priv;
2683
2684         if (lock && down_interruptible(&ai->sem))
2685                 return -1;
2686         waitbusy (ai);
2687         OUT4500(ai,COMMAND,CMD_SOFTRESET);
2688         set_current_state (TASK_UNINTERRUPTIBLE);
2689         schedule_timeout (HZ/5);
2690         waitbusy (ai);
2691         set_current_state (TASK_UNINTERRUPTIBLE);
2692         schedule_timeout (HZ/5);
2693         if (lock)
2694                 up(&ai->sem);
2695         return 0;
2696 }
2697
2698 struct net_device *_init_airo_card( unsigned short irq, int port,
2699                                     int is_pcmcia, struct pci_dev *pci,
2700                                     struct device *dmdev )
2701 {
2702         struct net_device *dev;
2703         struct airo_info *ai;
2704         int i, rc;
2705
2706         /* Create the network device object. */
2707         dev = alloc_etherdev(sizeof(*ai));
2708         if (!dev) {
2709                 printk(KERN_ERR "airo:  Couldn't alloc_etherdev\n");
2710                 return NULL;
2711         }
2712         if (dev_alloc_name(dev, dev->name) < 0) {
2713                 printk(KERN_ERR "airo:  Couldn't get name!\n");
2714                 goto err_out_free;
2715         }
2716
2717         ai = dev->priv;
2718         ai->wifidev = NULL;
2719         ai->flags = 0;
2720         if (pci && (pci->device == 0x5000 || pci->device == 0xa504)) {
2721                 printk(KERN_DEBUG "airo: Found an MPI350 card\n");
2722                 set_bit(FLAG_MPI, &ai->flags);
2723         }
2724         ai->dev = dev;
2725         spin_lock_init(&ai->aux_lock);
2726         sema_init(&ai->sem, 1);
2727         ai->config.len = 0;
2728         ai->pci = pci;
2729         init_waitqueue_head (&ai->thr_wait);
2730         init_completion (&ai->thr_exited);
2731         ai->thr_pid = kernel_thread(airo_thread, dev, CLONE_FS | CLONE_FILES);
2732         if (ai->thr_pid < 0)
2733                 goto err_out_free;
2734 #ifdef MICSUPPORT
2735         ai->tfm = NULL;
2736 #endif
2737         rc = add_airo_dev( dev );
2738         if (rc)
2739                 goto err_out_thr;
2740
2741         /* The Airo-specific entries in the device structure. */
2742         if (test_bit(FLAG_MPI,&ai->flags)) {
2743                 skb_queue_head_init (&ai->txq);
2744                 dev->hard_start_xmit = &mpi_start_xmit;
2745         } else
2746                 dev->hard_start_xmit = &airo_start_xmit;
2747         dev->get_stats = &airo_get_stats;
2748         dev->set_multicast_list = &airo_set_multicast_list;
2749         dev->set_mac_address = &airo_set_mac_address;
2750         dev->do_ioctl = &airo_ioctl;
2751 #ifdef WIRELESS_EXT
2752         dev->wireless_handlers = &airo_handler_def;
2753         ai->wireless_data.spy_data = &ai->spy_data;
2754         dev->wireless_data = &ai->wireless_data;
2755 #endif /* WIRELESS_EXT */
2756         dev->change_mtu = &airo_change_mtu;
2757         dev->open = &airo_open;
2758         dev->stop = &airo_close;
2759         dev->irq = irq;
2760         dev->base_addr = port;
2761
2762         SET_NETDEV_DEV(dev, dmdev);
2763
2764
2765         if (test_bit(FLAG_MPI,&ai->flags))
2766                 reset_card (dev, 1);
2767
2768         rc = request_irq( dev->irq, airo_interrupt, SA_SHIRQ, dev->name, dev );
2769         if (rc) {
2770                 printk(KERN_ERR "airo: register interrupt %d failed, rc %d\n", irq, rc );
2771                 goto err_out_unlink;
2772         }
2773         if (!is_pcmcia) {
2774                 if (!request_region( dev->base_addr, 64, dev->name )) {
2775                         rc = -EBUSY;
2776                         printk(KERN_ERR "airo: Couldn't request region\n");
2777                         goto err_out_irq;
2778                 }
2779         }
2780
2781         if (test_bit(FLAG_MPI,&ai->flags)) {
2782                 if (mpi_map_card(ai, pci, dev->name)) {
2783                         printk(KERN_ERR "airo: Could not map memory\n");
2784                         goto err_out_res;
2785                 }
2786         }
2787
2788         if (probe) {
2789                 if ( setup_card( ai, dev->dev_addr, 1 ) != SUCCESS ) {
2790                         printk( KERN_ERR "airo: MAC could not be enabled\n" );
2791                         rc = -EIO;
2792                         goto err_out_map;
2793                 }
2794         } else if (!test_bit(FLAG_MPI,&ai->flags)) {
2795                 ai->bap_read = fast_bap_read;
2796                 set_bit(FLAG_FLASHING, &ai->flags);
2797         }
2798
2799         rc = register_netdev(dev);
2800         if (rc) {
2801                 printk(KERN_ERR "airo: Couldn't register_netdev\n");
2802                 goto err_out_map;
2803         }
2804         ai->wifidev = init_wifidev(ai, dev);
2805
2806         set_bit(FLAG_REGISTERED,&ai->flags);
2807         printk( KERN_INFO "airo: MAC enabled %s %x:%x:%x:%x:%x:%x\n",
2808                 dev->name,
2809                 dev->dev_addr[0], dev->dev_addr[1], dev->dev_addr[2],
2810                 dev->dev_addr[3], dev->dev_addr[4], dev->dev_addr[5] );
2811
2812         /* Allocate the transmit buffers */
2813         if (probe && !test_bit(FLAG_MPI,&ai->flags))
2814                 for( i = 0; i < MAX_FIDS; i++ )
2815                         ai->fids[i] = transmit_allocate(ai,2312,i>=MAX_FIDS/2);
2816
2817         setup_proc_entry( dev, dev->priv ); /* XXX check for failure */
2818         netif_start_queue(dev);
2819         SET_MODULE_OWNER(dev);
2820         return dev;
2821
2822 err_out_map:
2823         if (test_bit(FLAG_MPI,&ai->flags) && pci) {
2824                 pci_free_consistent(pci, PCI_SHARED_LEN, ai->shared, ai->shared_dma);
2825                 iounmap(ai->pciaux);
2826                 iounmap(ai->pcimem);
2827                 mpi_unmap_card(ai->pci);
2828         }
2829 err_out_res:
2830         if (!is_pcmcia)
2831                 release_region( dev->base_addr, 64 );
2832 err_out_irq:
2833         free_irq(dev->irq, dev);
2834 err_out_unlink:
2835         del_airo_dev(dev);
2836 err_out_thr:
2837         set_bit(JOB_DIE, &ai->flags);
2838         kill_proc(ai->thr_pid, SIGTERM, 1);
2839         wait_for_completion(&ai->thr_exited);
2840 err_out_free:
2841         free_netdev(dev);
2842         return NULL;
2843 }
2844
2845 struct net_device *init_airo_card( unsigned short irq, int port, int is_pcmcia,
2846                                   struct device *dmdev)
2847 {
2848         return _init_airo_card ( irq, port, is_pcmcia, NULL, dmdev);
2849 }
2850
2851 EXPORT_SYMBOL(init_airo_card);
2852
2853 static int waitbusy (struct airo_info *ai) {
2854         int delay = 0;
2855         while ((IN4500 (ai, COMMAND) & COMMAND_BUSY) & (delay < 10000)) {
2856                 udelay (10);
2857                 if ((++delay % 20) == 0)
2858                         OUT4500(ai, EVACK, EV_CLEARCOMMANDBUSY);
2859         }
2860         return delay < 10000;
2861 }
2862
2863 int reset_airo_card( struct net_device *dev )
2864 {
2865         int i;
2866         struct airo_info *ai = dev->priv;
2867
2868         if (reset_card (dev, 1))
2869                 return -1;
2870
2871         if ( setup_card(ai, dev->dev_addr, 1 ) != SUCCESS ) {
2872                 printk( KERN_ERR "airo: MAC could not be enabled\n" );
2873                 return -1;
2874         }
2875         printk( KERN_INFO "airo: MAC enabled %s %x:%x:%x:%x:%x:%x\n", dev->name,
2876                         dev->dev_addr[0], dev->dev_addr[1], dev->dev_addr[2],
2877                         dev->dev_addr[3], dev->dev_addr[4], dev->dev_addr[5]);
2878         /* Allocate the transmit buffers if needed */
2879         if (!test_bit(FLAG_MPI,&ai->flags))
2880                 for( i = 0; i < MAX_FIDS; i++ )
2881                         ai->fids[i] = transmit_allocate (ai,2312,i>=MAX_FIDS/2);
2882
2883         enable_interrupts( ai );
2884         netif_wake_queue(dev);
2885         return 0;
2886 }
2887
2888 EXPORT_SYMBOL(reset_airo_card);
2889
2890 static void airo_send_event(struct net_device *dev) {
2891         struct airo_info *ai = dev->priv;
2892         union iwreq_data wrqu;
2893         StatusRid status_rid;
2894
2895         clear_bit(JOB_EVENT, &ai->flags);
2896         PC4500_readrid(ai, RID_STATUS, &status_rid, sizeof(status_rid), 0);
2897         up(&ai->sem);
2898         wrqu.data.length = 0;
2899         wrqu.data.flags = 0;
2900         memcpy(wrqu.ap_addr.sa_data, status_rid.bssid[0], ETH_ALEN);
2901         wrqu.ap_addr.sa_family = ARPHRD_ETHER;
2902
2903         /* Send event to user space */
2904         wireless_send_event(dev, SIOCGIWAP, &wrqu, NULL);
2905 }
2906
2907 static int airo_thread(void *data) {
2908         struct net_device *dev = data;
2909         struct airo_info *ai = dev->priv;
2910         int locked;
2911         
2912         daemonize("%s", dev->name);
2913         allow_signal(SIGTERM);
2914
2915         while(1) {
2916                 if (signal_pending(current))
2917                         flush_signals(current);
2918
2919                 /* make swsusp happy with our thread */
2920                 try_to_freeze(PF_FREEZE);
2921
2922                 if (test_bit(JOB_DIE, &ai->flags))
2923                         break;
2924
2925                 if (ai->flags & JOB_MASK) {
2926                         locked = down_interruptible(&ai->sem);
2927                 } else {
2928                         wait_queue_t wait;
2929
2930                         init_waitqueue_entry(&wait, current);
2931                         add_wait_queue(&ai->thr_wait, &wait);
2932                         for (;;) {
2933                                 set_current_state(TASK_INTERRUPTIBLE);
2934                                 if (ai->flags & JOB_MASK)
2935                                         break;
2936                                 if (ai->expires) {
2937                                         if (time_after_eq(jiffies,ai->expires)){
2938                                                 set_bit(JOB_AUTOWEP,&ai->flags);
2939                                                 break;
2940                                         }
2941                                         if (!signal_pending(current)) {
2942                                                 schedule_timeout(ai->expires - jiffies);
2943                                                 continue;
2944                                         }
2945                                 } else if (!signal_pending(current)) {
2946                                         schedule();
2947                                         continue;
2948                                 }
2949                                 break;
2950                         }
2951                         current->state = TASK_RUNNING;
2952                         remove_wait_queue(&ai->thr_wait, &wait);
2953                         locked = 1;
2954                 }
2955
2956                 if (locked)
2957                         continue;
2958
2959                 if (test_bit(JOB_DIE, &ai->flags)) {
2960                         up(&ai->sem);
2961                         break;
2962                 }
2963
2964                 if (ai->power || test_bit(FLAG_FLASHING, &ai->flags)) {
2965                         up(&ai->sem);
2966                         continue;
2967                 }
2968
2969                 if (test_bit(JOB_XMIT, &ai->flags))
2970                         airo_end_xmit(dev);
2971                 else if (test_bit(JOB_XMIT11, &ai->flags))
2972                         airo_end_xmit11(dev);
2973                 else if (test_bit(JOB_STATS, &ai->flags))
2974                         airo_read_stats(ai);
2975                 else if (test_bit(JOB_WSTATS, &ai->flags))
2976                         airo_read_wireless_stats(ai);
2977                 else if (test_bit(JOB_PROMISC, &ai->flags))
2978                         airo_set_promisc(ai);
2979 #ifdef MICSUPPORT
2980                 else if (test_bit(JOB_MIC, &ai->flags))
2981                         micinit(ai);
2982 #endif
2983                 else if (test_bit(JOB_EVENT, &ai->flags))
2984                         airo_send_event(dev);
2985                 else if (test_bit(JOB_AUTOWEP, &ai->flags))
2986                         timer_func(dev);
2987         }
2988         complete_and_exit (&ai->thr_exited, 0);
2989 }
2990
2991 static irqreturn_t airo_interrupt ( int irq, void* dev_id, struct pt_regs *regs) {
2992         struct net_device *dev = (struct net_device *)dev_id;
2993         u16 status;
2994         u16 fid;
2995         struct airo_info *apriv = dev->priv;
2996         u16 savedInterrupts = 0;
2997         int handled = 0;
2998
2999         if (!netif_device_present(dev))
3000                 return IRQ_NONE;
3001
3002         for (;;) {
3003                 status = IN4500( apriv, EVSTAT );
3004                 if ( !(status & STATUS_INTS) || status == 0xffff ) break;
3005
3006                 handled = 1;
3007
3008                 if ( status & EV_AWAKE ) {
3009                         OUT4500( apriv, EVACK, EV_AWAKE );
3010                         OUT4500( apriv, EVACK, EV_AWAKE );
3011                 }
3012
3013                 if (!savedInterrupts) {
3014                         savedInterrupts = IN4500( apriv, EVINTEN );
3015                         OUT4500( apriv, EVINTEN, 0 );
3016                 }
3017
3018                 if ( status & EV_MIC ) {
3019                         OUT4500( apriv, EVACK, EV_MIC );
3020 #ifdef MICSUPPORT
3021                         if (test_bit(FLAG_MIC_CAPABLE, &apriv->flags)) {
3022                                 set_bit(JOB_MIC, &apriv->flags);
3023                                 wake_up_interruptible(&apriv->thr_wait);
3024                         }
3025 #endif
3026                 }
3027                 if ( status & EV_LINK ) {
3028                         union iwreq_data        wrqu;
3029                         /* The link status has changed, if you want to put a
3030                            monitor hook in, do it here.  (Remember that
3031                            interrupts are still disabled!)
3032                         */
3033                         u16 newStatus = IN4500(apriv, LINKSTAT);
3034                         OUT4500( apriv, EVACK, EV_LINK);
3035                         /* Here is what newStatus means: */
3036 #define NOBEACON 0x8000 /* Loss of sync - missed beacons */
3037 #define MAXRETRIES 0x8001 /* Loss of sync - max retries */
3038 #define MAXARL 0x8002 /* Loss of sync - average retry level exceeded*/
3039 #define FORCELOSS 0x8003 /* Loss of sync - host request */
3040 #define TSFSYNC 0x8004 /* Loss of sync - TSF synchronization */
3041 #define DEAUTH 0x8100 /* Deauthentication (low byte is reason code) */
3042 #define DISASS 0x8200 /* Disassociation (low byte is reason code) */
3043 #define ASSFAIL 0x8400 /* Association failure (low byte is reason
3044                           code) */
3045 #define AUTHFAIL 0x0300 /* Authentication failure (low byte is reason
3046                            code) */
3047 #define ASSOCIATED 0x0400 /* Assocatied */
3048 #define RC_RESERVED 0 /* Reserved return code */
3049 #define RC_NOREASON 1 /* Unspecified reason */
3050 #define RC_AUTHINV 2 /* Previous authentication invalid */
3051 #define RC_DEAUTH 3 /* Deauthenticated because sending station is
3052                        leaving */
3053 #define RC_NOACT 4 /* Disassociated due to inactivity */
3054 #define RC_MAXLOAD 5 /* Disassociated because AP is unable to handle
3055                         all currently associated stations */
3056 #define RC_BADCLASS2 6 /* Class 2 frame received from
3057                           non-Authenticated station */
3058 #define RC_BADCLASS3 7 /* Class 3 frame received from
3059                           non-Associated station */
3060 #define RC_STATLEAVE 8 /* Disassociated because sending station is
3061                           leaving BSS */
3062 #define RC_NOAUTH 9 /* Station requesting (Re)Association is not
3063                        Authenticated with the responding station */
3064                         if (newStatus != ASSOCIATED) {
3065                                 if (auto_wep && !apriv->expires) {
3066                                         apriv->expires = RUN_AT(3*HZ);
3067                                         wake_up_interruptible(&apriv->thr_wait);
3068                                 }
3069                         } else {
3070                                 struct task_struct *task = apriv->task;
3071                                 if (auto_wep)
3072                                         apriv->expires = 0;
3073                                 if (task)
3074                                         wake_up_process (task);
3075                                 set_bit(FLAG_UPDATE_UNI, &apriv->flags);
3076                                 set_bit(FLAG_UPDATE_MULTI, &apriv->flags);
3077                         }
3078                         /* Question : is ASSOCIATED the only status
3079                          * that is valid ? We want to catch handover
3080                          * and reassociations as valid status
3081                          * Jean II */
3082                         if(newStatus == ASSOCIATED) {
3083                                 if (apriv->scan_timestamp) {
3084                                         /* Send an empty event to user space.
3085                                          * We don't send the received data on
3086                                          * the event because it would require
3087                                          * us to do complex transcoding, and
3088                                          * we want to minimise the work done in
3089                                          * the irq handler. Use a request to
3090                                          * extract the data - Jean II */
3091                                         wrqu.data.length = 0;
3092                                         wrqu.data.flags = 0;
3093                                         wireless_send_event(dev, SIOCGIWSCAN, &wrqu, NULL);
3094                                         apriv->scan_timestamp = 0;
3095                                 }
3096                                 if (down_trylock(&apriv->sem) != 0) {
3097                                         set_bit(JOB_EVENT, &apriv->flags);
3098                                         wake_up_interruptible(&apriv->thr_wait);
3099                                 } else
3100                                         airo_send_event(dev);
3101                         } else {
3102                                 memset(wrqu.ap_addr.sa_data, '\0', ETH_ALEN);
3103                                 wrqu.ap_addr.sa_family = ARPHRD_ETHER;
3104
3105                                 /* Send event to user space */
3106                                 wireless_send_event(dev, SIOCGIWAP, &wrqu,NULL);
3107                         }
3108                 }
3109
3110                 /* Check to see if there is something to receive */
3111                 if ( status & EV_RX  ) {
3112                         struct sk_buff *skb = NULL;
3113                         u16 fc, len, hdrlen = 0;
3114 #pragma pack(1)
3115                         struct {
3116                                 u16 status, len;
3117                                 u8 rssi[2];
3118                                 u8 rate;
3119                                 u8 freq;
3120                                 u16 tmp[4];
3121                         } hdr;
3122 #pragma pack()
3123                         u16 gap;
3124                         u16 tmpbuf[4];
3125                         u16 *buffer;
3126
3127                         if (test_bit(FLAG_MPI,&apriv->flags)) {
3128                                 if (test_bit(FLAG_802_11, &apriv->flags))
3129                                         mpi_receive_802_11(apriv);
3130                                 else
3131                                         mpi_receive_802_3(apriv);
3132                                 OUT4500(apriv, EVACK, EV_RX);
3133                                 goto exitrx;
3134                         }
3135
3136                         fid = IN4500( apriv, RXFID );
3137
3138                         /* Get the packet length */
3139                         if (test_bit(FLAG_802_11, &apriv->flags)) {
3140                                 bap_setup (apriv, fid, 4, BAP0);
3141                                 bap_read (apriv, (u16*)&hdr, sizeof(hdr), BAP0);
3142                                 /* Bad CRC. Ignore packet */
3143                                 if (le16_to_cpu(hdr.status) & 2)
3144                                         hdr.len = 0;
3145                                 if (apriv->wifidev == NULL)
3146                                         hdr.len = 0;
3147                         } else {
3148                                 bap_setup (apriv, fid, 0x36, BAP0);
3149                                 bap_read (apriv, (u16*)&hdr.len, 2, BAP0);
3150                         }
3151                         len = le16_to_cpu(hdr.len);
3152
3153                         if (len > 2312) {
3154                                 printk( KERN_ERR "airo: Bad size %d\n", len );
3155                                 goto badrx;
3156                         }
3157                         if (len == 0)
3158                                 goto badrx;
3159
3160                         if (test_bit(FLAG_802_11, &apriv->flags)) {
3161                                 bap_read (apriv, (u16*)&fc, sizeof(fc), BAP0);
3162                                 fc = le16_to_cpu(fc);
3163                                 switch (fc & 0xc) {
3164                                         case 4:
3165                                                 if ((fc & 0xe0) == 0xc0)
3166                                                         hdrlen = 10;
3167                                                 else
3168                                                         hdrlen = 16;
3169                                                 break;
3170                                         case 8:
3171                                                 if ((fc&0x300)==0x300){
3172                                                         hdrlen = 30;
3173                                                         break;
3174                                                 }
3175                                         default:
3176                                                 hdrlen = 24;
3177                                 }
3178                         } else
3179                                 hdrlen = ETH_ALEN * 2;
3180
3181                         skb = dev_alloc_skb( len + hdrlen + 2 + 2 );
3182                         if ( !skb ) {
3183                                 apriv->stats.rx_dropped++;
3184                                 goto badrx;
3185                         }
3186                         skb_reserve(skb, 2); /* This way the IP header is aligned */
3187                         buffer = (u16*)skb_put (skb, len + hdrlen);
3188                         if (test_bit(FLAG_802_11, &apriv->flags)) {
3189                                 buffer[0] = fc;
3190                                 bap_read (apriv, buffer + 1, hdrlen - 2, BAP0);
3191                                 if (hdrlen == 24)
3192                                         bap_read (apriv, tmpbuf, 6, BAP0);
3193
3194                                 bap_read (apriv, &gap, sizeof(gap), BAP0);
3195                                 gap = le16_to_cpu(gap);
3196                                 if (gap) {
3197                                         if (gap <= 8)
3198                                                 bap_read (apriv, tmpbuf, gap, BAP0);
3199                                         else
3200                                                 printk(KERN_ERR "airo: gaplen too big. Problems will follow...\n");
3201                                 }
3202                                 bap_read (apriv, buffer + hdrlen/2, len, BAP0);
3203                         } else {
3204 #ifdef MICSUPPORT
3205                                 MICBuffer micbuf;
3206 #endif
3207                                 bap_read (apriv, buffer, ETH_ALEN*2, BAP0);
3208 #ifdef MICSUPPORT
3209                                 if (apriv->micstats.enabled) {
3210                                         bap_read (apriv,(u16*)&micbuf,sizeof(micbuf),BAP0);
3211                                         if (ntohs(micbuf.typelen) > 0x05DC)
3212                                                 bap_setup (apriv, fid, 0x44, BAP0);
3213                                         else {
3214                                                 if (len <= sizeof(micbuf))
3215                                                         goto badmic;
3216
3217                                                 len -= sizeof(micbuf);
3218                                                 skb_trim (skb, len + hdrlen);
3219                                         }
3220                                 }
3221 #endif
3222                                 bap_read(apriv,buffer+ETH_ALEN,len,BAP0);
3223 #ifdef MICSUPPORT
3224                                 if (decapsulate(apriv,&micbuf,(etherHead*)buffer,len)) {
3225 badmic:
3226                                         dev_kfree_skb_irq (skb);
3227 #else
3228                                 if (0) {
3229 #endif
3230 badrx:
3231                                         OUT4500( apriv, EVACK, EV_RX);
3232                                         goto exitrx;
3233                                 }
3234                         }
3235 #ifdef WIRELESS_SPY
3236                         if (apriv->spy_data.spy_number > 0) {
3237                                 char *sa;
3238                                 struct iw_quality wstats;
3239                                 /* Prepare spy data : addr + qual */
3240                                 if (!test_bit(FLAG_802_11, &apriv->flags)) {
3241                                         sa = (char*)buffer + 6;
3242                                         bap_setup (apriv, fid, 8, BAP0);
3243                                         bap_read (apriv, (u16*)hdr.rssi, 2, BAP0);
3244                                 } else
3245                                         sa = (char*)buffer + 10;
3246                                 wstats.qual = hdr.rssi[0];
3247                                 if (apriv->rssi)
3248                                         wstats.level = 0x100 - apriv->rssi[hdr.rssi[1]].rssidBm;
3249                                 else
3250                                         wstats.level = (hdr.rssi[1] + 321) / 2;
3251                                 wstats.updated = 3;     
3252                                 /* Update spy records */
3253                                 wireless_spy_update(dev, sa, &wstats);
3254                         }
3255 #endif /* WIRELESS_SPY */
3256                         OUT4500( apriv, EVACK, EV_RX);
3257
3258                         if (test_bit(FLAG_802_11, &apriv->flags)) {
3259                                 skb->mac.raw = skb->data;
3260                                 skb->pkt_type = PACKET_OTHERHOST;
3261                                 skb->dev = apriv->wifidev;
3262                                 skb->protocol = htons(ETH_P_802_2);
3263                         } else {
3264                                 skb->dev = dev;
3265                                 skb->protocol = eth_type_trans(skb,dev);
3266                         }
3267                         skb->dev->last_rx = jiffies;
3268                         skb->ip_summed = CHECKSUM_NONE;
3269
3270                         netif_rx( skb );
3271                 }
3272 exitrx:
3273
3274                 /* Check to see if a packet has been transmitted */
3275                 if (  status & ( EV_TX|EV_TXCPY|EV_TXEXC ) ) {
3276                         int i;
3277                         int len = 0;
3278                         int index = -1;
3279
3280                         if (test_bit(FLAG_MPI,&apriv->flags)) {
3281                                 unsigned long flags;
3282
3283                                 if (status & EV_TXEXC)
3284                                         get_tx_error(apriv, -1);
3285                                 spin_lock_irqsave(&apriv->aux_lock, flags);
3286                                 if (skb_queue_len (&apriv->txq)) {
3287                                         spin_unlock_irqrestore(&apriv->aux_lock,flags);
3288                                         mpi_send_packet (dev);
3289                                 } else {
3290                                         clear_bit(FLAG_PENDING_XMIT, &apriv->flags);
3291                                         spin_unlock_irqrestore(&apriv->aux_lock,flags);
3292                                         netif_wake_queue (dev);
3293                                 }
3294                                 OUT4500( apriv, EVACK,
3295                                         status & (EV_TX|EV_TXCPY|EV_TXEXC));
3296                                 goto exittx;
3297                         }
3298
3299                         fid = IN4500(apriv, TXCOMPLFID);
3300
3301                         for( i = 0; i < MAX_FIDS; i++ ) {
3302                                 if ( ( apriv->fids[i] & 0xffff ) == fid ) {
3303                                         len = apriv->fids[i] >> 16;
3304                                         index = i;
3305                                 }
3306                         }
3307                         if (index != -1) {
3308                                 if (status & EV_TXEXC)
3309                                         get_tx_error(apriv, index);
3310                                 OUT4500( apriv, EVACK, status & (EV_TX | EV_TXEXC));
3311                                 /* Set up to be used again */
3312                                 apriv->fids[index] &= 0xffff;
3313                                 if (index < MAX_FIDS / 2) {
3314                                         if (!test_bit(FLAG_PENDING_XMIT, &apriv->flags))
3315                                                 netif_wake_queue(dev);
3316                                 } else {
3317                                         if (!test_bit(FLAG_PENDING_XMIT11, &apriv->flags))
3318                                                 netif_wake_queue(apriv->wifidev);
3319                                 }
3320                         } else {
3321                                 OUT4500( apriv, EVACK, status & (EV_TX | EV_TXCPY | EV_TXEXC));
3322                                 printk( KERN_ERR "airo: Unallocated FID was used to xmit\n" );
3323                         }
3324                 }
3325 exittx:
3326                 if ( status & ~STATUS_INTS & ~IGNORE_INTS )
3327                         printk( KERN_WARNING "airo: Got weird status %x\n",
3328                                 status & ~STATUS_INTS & ~IGNORE_INTS );
3329         }
3330
3331         if (savedInterrupts)
3332                 OUT4500( apriv, EVINTEN, savedInterrupts );
3333
3334         /* done.. */
3335         return IRQ_RETVAL(handled);
3336 }
3337
3338 /*
3339  *  Routines to talk to the card
3340  */
3341
3342 /*
3343  *  This was originally written for the 4500, hence the name
3344  *  NOTE:  If use with 8bit mode and SMP bad things will happen!
3345  *         Why would some one do 8 bit IO in an SMP machine?!?
3346  */
3347 static void OUT4500( struct airo_info *ai, u16 reg, u16 val ) {
3348         if (test_bit(FLAG_MPI,&ai->flags))
3349                 reg <<= 1;
3350         if ( !do8bitIO )
3351                 outw( val, ai->dev->base_addr + reg );
3352         else {
3353                 outb( val & 0xff, ai->dev->base_addr + reg );
3354                 outb( val >> 8, ai->dev->base_addr + reg + 1 );
3355         }
3356 }
3357
3358 static u16 IN4500( struct airo_info *ai, u16 reg ) {
3359         unsigned short rc;
3360
3361         if (test_bit(FLAG_MPI,&ai->flags))
3362                 reg <<= 1;
3363         if ( !do8bitIO )
3364                 rc = inw( ai->dev->base_addr + reg );
3365         else {
3366                 rc = inb( ai->dev->base_addr + reg );
3367                 rc += ((int)inb( ai->dev->base_addr + reg + 1 )) << 8;
3368         }
3369         return rc;
3370 }
3371
3372 static int enable_MAC( struct airo_info *ai, Resp *rsp, int lock ) {
3373         int rc;
3374         Cmd cmd;
3375
3376         /* FLAG_RADIO_OFF : Radio disabled via /proc or Wireless Extensions
3377          * FLAG_RADIO_DOWN : Radio disabled via "ifconfig ethX down"
3378          * Note : we could try to use !netif_running(dev) in enable_MAC()
3379          * instead of this flag, but I don't trust it *within* the
3380          * open/close functions, and testing both flags together is
3381          * "cheaper" - Jean II */
3382         if (ai->flags & FLAG_RADIO_MASK) return SUCCESS;
3383
3384         if (lock && down_interruptible(&ai->sem))
3385                 return -ERESTARTSYS;
3386
3387         if (!test_bit(FLAG_ENABLED, &ai->flags)) {
3388                 memset(&cmd, 0, sizeof(cmd));
3389                 cmd.cmd = MAC_ENABLE;
3390                 rc = issuecommand(ai, &cmd, rsp);
3391                 if (rc == SUCCESS)
3392                         set_bit(FLAG_ENABLED, &ai->flags);
3393         } else
3394                 rc = SUCCESS;
3395
3396         if (lock)
3397             up(&ai->sem);
3398
3399         if (rc)
3400                 printk(KERN_ERR "%s: Cannot enable MAC, err=%d\n",
3401                         __FUNCTION__,rc);
3402         return rc;
3403 }
3404
3405 static void disable_MAC( struct airo_info *ai, int lock ) {
3406         Cmd cmd;
3407         Resp rsp;
3408
3409         if (lock && down_interruptible(&ai->sem))
3410                 return;
3411
3412         if (test_bit(FLAG_ENABLED, &ai->flags)) {
3413                 memset(&cmd, 0, sizeof(cmd));
3414                 cmd.cmd = MAC_DISABLE; // disable in case already enabled
3415                 issuecommand(ai, &cmd, &rsp);
3416                 clear_bit(FLAG_ENABLED, &ai->flags);
3417         }
3418         if (lock)
3419                 up(&ai->sem);
3420 }
3421
3422 static void enable_interrupts( struct airo_info *ai ) {
3423         /* Enable the interrupts */
3424         OUT4500( ai, EVINTEN, STATUS_INTS );
3425 }
3426
3427 static void disable_interrupts( struct airo_info *ai ) {
3428         OUT4500( ai, EVINTEN, 0 );
3429 }
3430
3431 static void mpi_receive_802_3(struct airo_info *ai)
3432 {
3433         RxFid rxd;
3434         int len = 0;
3435         struct sk_buff *skb;
3436         char *buffer;
3437 #ifdef MICSUPPORT
3438         int off = 0;
3439         MICBuffer micbuf;
3440 #endif
3441
3442         memcpy_fromio(&rxd, ai->rxfids[0].card_ram_off, sizeof(rxd));
3443         /* Make sure we got something */
3444         if (rxd.rdy && rxd.valid == 0) {
3445                 len = rxd.len + 12;
3446                 if (len < 12 && len > 2048)
3447                         goto badrx;
3448
3449                 skb = dev_alloc_skb(len);
3450                 if (!skb) {
3451                         ai->stats.rx_dropped++;
3452                         goto badrx;
3453                 }
3454                 buffer = skb_put(skb,len);
3455 #ifdef MICSUPPORT
3456                 memcpy(buffer, ai->rxfids[0].virtual_host_addr, ETH_ALEN * 2);
3457                 if (ai->micstats.enabled) {
3458                         memcpy(&micbuf,
3459                                 ai->rxfids[0].virtual_host_addr + ETH_ALEN * 2,
3460                                 sizeof(micbuf));
3461                         if (ntohs(micbuf.typelen) <= 0x05DC) {
3462                                 if (len <= sizeof(micbuf) + ETH_ALEN * 2)
3463                                         goto badmic;
3464
3465                                 off = sizeof(micbuf);
3466                                 skb_trim (skb, len - off);
3467                         }
3468                 }
3469                 memcpy(buffer + ETH_ALEN * 2,
3470                         ai->rxfids[0].virtual_host_addr + ETH_ALEN * 2 + off,
3471                         len - ETH_ALEN * 2 - off);
3472                 if (decapsulate (ai, &micbuf, (etherHead*)buffer, len - off - ETH_ALEN * 2)) {
3473 badmic:
3474                         dev_kfree_skb_irq (skb);
3475                         goto badrx;
3476                 }
3477 #else
3478                 memcpy(buffer, ai->rxfids[0].virtual_host_addr, len);
3479 #endif
3480 #ifdef WIRELESS_SPY
3481                 if (ai->spy_data.spy_number > 0) {
3482                         char *sa;
3483                         struct iw_quality wstats;
3484                         /* Prepare spy data : addr + qual */
3485                         sa = buffer + ETH_ALEN;
3486                         wstats.qual = 0; /* XXX Where do I get that info from ??? */
3487                         wstats.level = 0;
3488                         wstats.updated = 0;
3489                         /* Update spy records */
3490                         wireless_spy_update(ai->dev, sa, &wstats);
3491                 }
3492 #endif /* WIRELESS_SPY */
3493
3494                 skb->dev = ai->dev;
3495                 skb->ip_summed = CHECKSUM_NONE;
3496                 skb->protocol = eth_type_trans(skb, ai->dev);
3497                 skb->dev->last_rx = jiffies;
3498                 netif_rx(skb);
3499         }
3500 badrx:
3501         if (rxd.valid == 0) {
3502                 rxd.valid = 1;
3503                 rxd.rdy = 0;
3504                 rxd.len = PKTSIZE;
3505                 memcpy_toio(ai->rxfids[0].card_ram_off, &rxd, sizeof(rxd));
3506         }
3507 }
3508
3509 void mpi_receive_802_11 (struct airo_info *ai)
3510 {
3511         RxFid rxd;
3512         struct sk_buff *skb = NULL;
3513         u16 fc, len, hdrlen = 0;
3514 #pragma pack(1)
3515         struct {
3516                 u16 status, len;
3517                 u8 rssi[2];
3518                 u8 rate;
3519                 u8 freq;
3520                 u16 tmp[4];
3521         } hdr;
3522 #pragma pack()
3523         u16 gap;
3524         u16 *buffer;
3525         char *ptr = ai->rxfids[0].virtual_host_addr+4;
3526
3527         memcpy_fromio(&rxd, ai->rxfids[0].card_ram_off, sizeof(rxd));
3528         memcpy ((char *)&hdr, ptr, sizeof(hdr));
3529         ptr += sizeof(hdr);
3530         /* Bad CRC. Ignore packet */
3531         if (le16_to_cpu(hdr.status) & 2)
3532                 hdr.len = 0;
3533         if (ai->wifidev == NULL)
3534                 hdr.len = 0;
3535         len = le16_to_cpu(hdr.len);
3536         if (len > 2312) {
3537                 printk( KERN_ERR "airo: Bad size %d\n", len );
3538                 goto badrx;
3539         }
3540         if (len == 0)
3541                 goto badrx;
3542
3543         memcpy ((char *)&fc, ptr, sizeof(fc));
3544         fc = le16_to_cpu(fc);
3545         switch (fc & 0xc) {
3546                 case 4:
3547                         if ((fc & 0xe0) == 0xc0)
3548                                 hdrlen = 10;
3549                         else
3550                                 hdrlen = 16;
3551                         break;
3552                 case 8:
3553                         if ((fc&0x300)==0x300){
3554                                 hdrlen = 30;
3555                                 break;
3556                         }
3557                 default:
3558                         hdrlen = 24;
3559         }
3560
3561         skb = dev_alloc_skb( len + hdrlen + 2 );
3562         if ( !skb ) {
3563                 ai->stats.rx_dropped++;
3564                 goto badrx;
3565         }
3566         buffer = (u16*)skb_put (skb, len + hdrlen);
3567         memcpy ((char *)buffer, ptr, hdrlen);
3568         ptr += hdrlen;
3569         if (hdrlen == 24)
3570                 ptr += 6;
3571         memcpy ((char *)&gap, ptr, sizeof(gap));
3572         ptr += sizeof(gap);
3573         gap = le16_to_cpu(gap);
3574         if (gap) {
3575                 if (gap <= 8)
3576                         ptr += gap;
3577                 else
3578                         printk(KERN_ERR
3579                             "airo: gaplen too big. Problems will follow...\n");
3580         }
3581         memcpy ((char *)buffer + hdrlen, ptr, len);
3582         ptr += len;
3583 #ifdef IW_WIRELESS_SPY    /* defined in iw_handler.h */
3584         if (ai->spy_data.spy_number > 0) {
3585                 char *sa;
3586                 struct iw_quality wstats;
3587                 /* Prepare spy data : addr + qual */
3588                 sa = (char*)buffer + 10;
3589                 wstats.qual = hdr.rssi[0];
3590                 if (ai->rssi)
3591                         wstats.level = 0x100 - ai->rssi[hdr.rssi[1]].rssidBm;
3592                 else
3593                         wstats.level = (hdr.rssi[1] + 321) / 2;
3594                 wstats.updated = 3;
3595                 /* Update spy records */
3596                 wireless_spy_update(ai->dev, sa, &wstats);
3597         }
3598 #endif /* IW_WIRELESS_SPY */
3599         skb->mac.raw = skb->data;
3600         skb->pkt_type = PACKET_OTHERHOST;
3601         skb->dev = ai->wifidev;
3602         skb->protocol = htons(ETH_P_802_2);
3603         skb->dev->last_rx = jiffies;
3604         skb->ip_summed = CHECKSUM_NONE;
3605         netif_rx( skb );
3606 badrx:
3607         if (rxd.valid == 0) {
3608                 rxd.valid = 1;
3609                 rxd.rdy = 0;
3610                 rxd.len = PKTSIZE;
3611                 memcpy_toio(ai->rxfids[0].card_ram_off, &rxd, sizeof(rxd));
3612         }
3613 }
3614
3615 static u16 setup_card(struct airo_info *ai, u8 *mac, int lock)
3616 {
3617         Cmd cmd;
3618         Resp rsp;
3619         int status;
3620         int i;
3621         SsidRid mySsid;
3622         u16 lastindex;
3623         WepKeyRid wkr;
3624         int rc;
3625
3626         memset( &mySsid, 0, sizeof( mySsid ) );
3627         if (ai->flash) {
3628                 kfree (ai->flash);
3629                 ai->flash = NULL;
3630         }
3631
3632         /* The NOP is the first step in getting the card going */
3633         cmd.cmd = NOP;
3634         cmd.parm0 = cmd.parm1 = cmd.parm2 = 0;
3635         if (lock && down_interruptible(&ai->sem))
3636                 return ERROR;
3637         if ( issuecommand( ai, &cmd, &rsp ) != SUCCESS ) {
3638                 if (lock)
3639                         up(&ai->sem);
3640                 return ERROR;
3641         }
3642         disable_MAC( ai, 0);
3643
3644         // Let's figure out if we need to use the AUX port
3645         if (!test_bit(FLAG_MPI,&ai->flags)) {
3646                 cmd.cmd = CMD_ENABLEAUX;
3647                 if (issuecommand(ai, &cmd, &rsp) != SUCCESS) {
3648                         if (lock)
3649                                 up(&ai->sem);
3650                         printk(KERN_ERR "airo: Error checking for AUX port\n");
3651                         return ERROR;
3652                 }
3653                 if (!aux_bap || rsp.status & 0xff00) {
3654                         ai->bap_read = fast_bap_read;
3655                         printk(KERN_DEBUG "airo: Doing fast bap_reads\n");
3656                 } else {
3657                         ai->bap_read = aux_bap_read;
3658                         printk(KERN_DEBUG "airo: Doing AUX bap_reads\n");
3659                 }
3660         }
3661         if (lock)
3662                 up(&ai->sem);
3663         if (ai->config.len == 0) {
3664                 tdsRssiRid rssi_rid;
3665                 CapabilityRid cap_rid;
3666
3667                 if (ai->APList) {
3668                         kfree(ai->APList);
3669                         ai->APList = NULL;
3670                 }
3671                 if (ai->SSID) {
3672                         kfree(ai->SSID);
3673                         ai->SSID = NULL;
3674                 }
3675                 // general configuration (read/modify/write)
3676                 status = readConfigRid(ai, lock);
3677                 if ( status != SUCCESS ) return ERROR;
3678
3679                 status = readCapabilityRid(ai, &cap_rid, lock);
3680                 if ( status != SUCCESS ) return ERROR;
3681
3682                 status = PC4500_readrid(ai,RID_RSSI,&rssi_rid,sizeof(rssi_rid),lock);
3683                 if ( status == SUCCESS ) {
3684                         if (ai->rssi || (ai->rssi = kmalloc(512, GFP_KERNEL)) != NULL)
3685                                 memcpy(ai->rssi, (u8*)&rssi_rid + 2, 512);
3686                 }
3687                 else {
3688                         if (ai->rssi) {
3689                                 kfree(ai->rssi);
3690                                 ai->rssi = NULL;
3691                         }
3692                         if (cap_rid.softCap & 8)
3693                                 ai->config.rmode |= RXMODE_NORMALIZED_RSSI;
3694                         else
3695                                 printk(KERN_WARNING "airo: unknown received signal level scale\n");
3696                 }
3697                 ai->config.opmode = adhoc ? MODE_STA_IBSS : MODE_STA_ESS;
3698                 ai->config.authType = AUTH_OPEN;
3699                 ai->config.modulation = MOD_CCK;
3700
3701 #ifdef MICSUPPORT
3702                 if ((cap_rid.len>=sizeof(cap_rid)) && (cap_rid.extSoftCap&1) &&
3703                     (micsetup(ai) == SUCCESS)) {
3704                         ai->config.opmode |= MODE_MIC;
3705                         set_bit(FLAG_MIC_CAPABLE, &ai->flags);
3706                 }
3707 #endif
3708
3709                 /* Save off the MAC */
3710                 for( i = 0; i < ETH_ALEN; i++ ) {
3711                         mac[i] = ai->config.macAddr[i];
3712                 }
3713
3714                 /* Check to see if there are any insmod configured
3715                    rates to add */
3716                 if ( rates[0] ) {
3717                         int i = 0;
3718                         memset(ai->config.rates,0,sizeof(ai->config.rates));
3719                         for( i = 0; i < 8 && rates[i]; i++ ) {
3720                                 ai->config.rates[i] = rates[i];
3721                         }
3722                 }
3723                 if ( basic_rate > 0 ) {
3724                         int i;
3725                         for( i = 0; i < 8; i++ ) {
3726                                 if ( ai->config.rates[i] == basic_rate ||
3727                                      !ai->config.rates ) {
3728                                         ai->config.rates[i] = basic_rate | 0x80;
3729                                         break;
3730                                 }
3731                         }
3732                 }
3733                 set_bit (FLAG_COMMIT, &ai->flags);
3734         }
3735
3736         /* Setup the SSIDs if present */
3737         if ( ssids[0] ) {
3738                 int i;
3739                 for( i = 0; i < 3 && ssids[i]; i++ ) {
3740                         mySsid.ssids[i].len = strlen(ssids[i]);
3741                         if ( mySsid.ssids[i].len > 32 )
3742                                 mySsid.ssids[i].len = 32;
3743                         memcpy(mySsid.ssids[i].ssid, ssids[i],
3744                                mySsid.ssids[i].len);
3745                 }
3746                 mySsid.len = sizeof(mySsid);
3747         }
3748
3749         status = writeConfigRid(ai, lock);
3750         if ( status != SUCCESS ) return ERROR;
3751
3752         /* Set up the SSID list */
3753         if ( ssids[0] ) {
3754                 status = writeSsidRid(ai, &mySsid, lock);
3755                 if ( status != SUCCESS ) return ERROR;
3756         }
3757
3758         status = enable_MAC(ai, &rsp, lock);
3759         if ( status != SUCCESS || (rsp.status & 0xFF00) != 0) {
3760                 printk( KERN_ERR "airo: Bad MAC enable reason = %x, rid = %x, offset = %d\n", rsp.rsp0, rsp.rsp1, rsp.rsp2 );
3761                 return ERROR;
3762         }
3763
3764         /* Grab the initial wep key, we gotta save it for auto_wep */
3765         rc = readWepKeyRid(ai, &wkr, 1, lock);
3766         if (rc == SUCCESS) do {
3767                 lastindex = wkr.kindex;
3768                 if (wkr.kindex == 0xffff) {
3769                         ai->defindex = wkr.mac[0];
3770                 }
3771                 rc = readWepKeyRid(ai, &wkr, 0, lock);
3772         } while(lastindex != wkr.kindex);
3773
3774         if (auto_wep) {
3775                 ai->expires = RUN_AT(3*HZ);
3776                 wake_up_interruptible(&ai->thr_wait);
3777         }
3778
3779         return SUCCESS;
3780 }
3781
3782 static u16 issuecommand(struct airo_info *ai, Cmd *pCmd, Resp *pRsp) {
3783         // Im really paranoid about letting it run forever!
3784         int max_tries = 600000;
3785
3786         if (IN4500(ai, EVSTAT) & EV_CMD)
3787                 OUT4500(ai, EVACK, EV_CMD);
3788
3789         OUT4500(ai, PARAM0, pCmd->parm0);
3790         OUT4500(ai, PARAM1, pCmd->parm1);
3791         OUT4500(ai, PARAM2, pCmd->parm2);
3792         OUT4500(ai, COMMAND, pCmd->cmd);
3793
3794         while (max_tries-- && (IN4500(ai, EVSTAT) & EV_CMD) == 0) {
3795                 if ((IN4500(ai, COMMAND)) == pCmd->cmd)
3796                         // PC4500 didn't notice command, try again
3797                         OUT4500(ai, COMMAND, pCmd->cmd);
3798                 if (!in_atomic() && (max_tries & 255) == 0)
3799                         schedule();
3800         }
3801
3802         if ( max_tries == -1 ) {
3803                 printk( KERN_ERR
3804                         "airo: Max tries exceeded when issueing command\n" );
3805                 if (IN4500(ai, COMMAND) & COMMAND_BUSY)
3806                         OUT4500(ai, EVACK, EV_CLEARCOMMANDBUSY);
3807                 return ERROR;
3808         }
3809
3810         // command completed
3811         pRsp->status = IN4500(ai, STATUS);
3812         pRsp->rsp0 = IN4500(ai, RESP0);
3813         pRsp->rsp1 = IN4500(ai, RESP1);
3814         pRsp->rsp2 = IN4500(ai, RESP2);
3815         if ((pRsp->status & 0xff00)!=0 && pCmd->cmd != CMD_SOFTRESET) {
3816                 printk (KERN_ERR "airo: cmd= %x\n", pCmd->cmd);
3817                 printk (KERN_ERR "airo: status= %x\n", pRsp->status);
3818                 printk (KERN_ERR "airo: Rsp0= %x\n", pRsp->rsp0);
3819                 printk (KERN_ERR "airo: Rsp1= %x\n", pRsp->rsp1);
3820                 printk (KERN_ERR "airo: Rsp2= %x\n", pRsp->rsp2);
3821         }
3822
3823         // clear stuck command busy if necessary
3824         if (IN4500(ai, COMMAND) & COMMAND_BUSY) {
3825                 OUT4500(ai, EVACK, EV_CLEARCOMMANDBUSY);
3826         }
3827         // acknowledge processing the status/response
3828         OUT4500(ai, EVACK, EV_CMD);
3829
3830         return SUCCESS;
3831 }
3832
3833 /* Sets up the bap to start exchange data.  whichbap should
3834  * be one of the BAP0 or BAP1 defines.  Locks should be held before
3835  * calling! */
3836 static int bap_setup(struct airo_info *ai, u16 rid, u16 offset, int whichbap )
3837 {
3838         int timeout = 50;
3839         int max_tries = 3;
3840
3841         OUT4500(ai, SELECT0+whichbap, rid);
3842         OUT4500(ai, OFFSET0+whichbap, offset);
3843         while (1) {
3844                 int status = IN4500(ai, OFFSET0+whichbap);
3845                 if (status & BAP_BUSY) {
3846                         /* This isn't really a timeout, but its kinda
3847                            close */
3848                         if (timeout--) {
3849                                 continue;
3850                         }
3851                 } else if ( status & BAP_ERR ) {
3852                         /* invalid rid or offset */
3853                         printk( KERN_ERR "airo: BAP error %x %d\n",
3854                                 status, whichbap );
3855                         return ERROR;
3856                 } else if (status & BAP_DONE) { // success
3857                         return SUCCESS;
3858                 }
3859                 if ( !(max_tries--) ) {
3860                         printk( KERN_ERR
3861                                 "airo: BAP setup error too many retries\n" );
3862                         return ERROR;
3863                 }
3864                 // -- PC4500 missed it, try again
3865                 OUT4500(ai, SELECT0+whichbap, rid);
3866                 OUT4500(ai, OFFSET0+whichbap, offset);
3867                 timeout = 50;
3868         }
3869 }
3870
3871 /* should only be called by aux_bap_read.  This aux function and the
3872    following use concepts not documented in the developers guide.  I
3873    got them from a patch given to my by Aironet */
3874 static u16 aux_setup(struct airo_info *ai, u16 page,
3875                      u16 offset, u16 *len)
3876 {
3877         u16 next;
3878
3879         OUT4500(ai, AUXPAGE, page);
3880         OUT4500(ai, AUXOFF, 0);
3881         next = IN4500(ai, AUXDATA);
3882         *len = IN4500(ai, AUXDATA)&0xff;
3883         if (offset != 4) OUT4500(ai, AUXOFF, offset);
3884         return next;
3885 }
3886
3887 /* requires call to bap_setup() first */
3888 static int aux_bap_read(struct airo_info *ai, u16 *pu16Dst,
3889                         int bytelen, int whichbap)
3890 {
3891         u16 len;
3892         u16 page;
3893         u16 offset;
3894         u16 next;
3895         int words;
3896         int i;
3897         unsigned long flags;
3898
3899         spin_lock_irqsave(&ai->aux_lock, flags);
3900         page = IN4500(ai, SWS0+whichbap);
3901         offset = IN4500(ai, SWS2+whichbap);
3902         next = aux_setup(ai, page, offset, &len);
3903         words = (bytelen+1)>>1;
3904
3905         for (i=0; i<words;) {
3906                 int count;
3907                 count = (len>>1) < (words-i) ? (len>>1) : (words-i);
3908                 if ( !do8bitIO )
3909                         insw( ai->dev->base_addr+DATA0+whichbap,
3910                               pu16Dst+i,count );
3911                 else
3912                         insb( ai->dev->base_addr+DATA0+whichbap,
3913                               pu16Dst+i, count << 1 );
3914                 i += count;
3915                 if (i<words) {
3916                         next = aux_setup(ai, next, 4, &len);
3917                 }
3918         }
3919         spin_unlock_irqrestore(&ai->aux_lock, flags);
3920         return SUCCESS;
3921 }
3922
3923
3924 /* requires call to bap_setup() first */
3925 static int fast_bap_read(struct airo_info *ai, u16 *pu16Dst,
3926                          int bytelen, int whichbap)
3927 {
3928         bytelen = (bytelen + 1) & (~1); // round up to even value
3929         if ( !do8bitIO )
3930                 insw( ai->dev->base_addr+DATA0+whichbap, pu16Dst, bytelen>>1 );
3931         else
3932                 insb( ai->dev->base_addr+DATA0+whichbap, pu16Dst, bytelen );
3933         return SUCCESS;
3934 }
3935
3936 /* requires call to bap_setup() first */
3937 static int bap_write(struct airo_info *ai, const u16 *pu16Src,
3938                      int bytelen, int whichbap)
3939 {
3940         bytelen = (bytelen + 1) & (~1); // round up to even value
3941         if ( !do8bitIO )
3942                 outsw( ai->dev->base_addr+DATA0+whichbap,
3943                        pu16Src, bytelen>>1 );
3944         else
3945                 outsb( ai->dev->base_addr+DATA0+whichbap, pu16Src, bytelen );
3946         return SUCCESS;
3947 }
3948
3949 static int PC4500_accessrid(struct airo_info *ai, u16 rid, u16 accmd)
3950 {
3951         Cmd cmd; /* for issuing commands */
3952         Resp rsp; /* response from commands */
3953         u16 status;
3954
3955         memset(&cmd, 0, sizeof(cmd));
3956         cmd.cmd = accmd;
3957         cmd.parm0 = rid;
3958         status = issuecommand(ai, &cmd, &rsp);
3959         if (status != 0) return status;
3960         if ( (rsp.status & 0x7F00) != 0) {
3961                 return (accmd << 8) + (rsp.rsp0 & 0xFF);
3962         }
3963         return 0;
3964 }
3965
3966 /*  Note, that we are using BAP1 which is also used by transmit, so
3967  *  we must get a lock. */
3968 static int PC4500_readrid(struct airo_info *ai, u16 rid, void *pBuf, int len, int lock)
3969 {
3970         u16 status;
3971         int rc = SUCCESS;
3972
3973         if (lock) {
3974                 if (down_interruptible(&ai->sem))
3975                         return ERROR;
3976         }
3977         if (test_bit(FLAG_MPI,&ai->flags)) {
3978                 Cmd cmd;
3979                 Resp rsp;
3980
3981                 memset(&cmd, 0, sizeof(cmd));
3982                 memset(&rsp, 0, sizeof(rsp));
3983                 ai->config_desc.rid_desc.valid = 1;
3984                 ai->config_desc.rid_desc.len = RIDSIZE;
3985                 ai->config_desc.rid_desc.rid = 0;
3986                 ai->config_desc.rid_desc.host_addr = ai->ridbus;
3987
3988                 cmd.cmd = CMD_ACCESS;
3989                 cmd.parm0 = rid;
3990
3991                 memcpy_toio(ai->config_desc.card_ram_off,
3992                         &ai->config_desc.rid_desc, sizeof(Rid));
3993
3994                 rc = issuecommand(ai, &cmd, &rsp);
3995
3996                 if (rsp.status & 0x7f00)
3997                         rc = rsp.rsp0;
3998                 if (!rc)
3999                         memcpy(pBuf, ai->config_desc.virtual_host_addr, len);
4000                 goto done;
4001         } else {
4002                 if ((status = PC4500_accessrid(ai, rid, CMD_ACCESS))!=SUCCESS) {
4003                         rc = status;
4004                         goto done;
4005                 }
4006                 if (bap_setup(ai, rid, 0, BAP1) != SUCCESS) {
4007                         rc = ERROR;
4008                         goto done;
4009                 }
4010                 // read the rid length field
4011                 bap_read(ai, pBuf, 2, BAP1);
4012                 // length for remaining part of rid
4013                 len = min(len, (int)le16_to_cpu(*(u16*)pBuf)) - 2;
4014
4015                 if ( len <= 2 ) {
4016                         printk( KERN_ERR
4017                         "airo: Rid %x has a length of %d which is too short\n",
4018                                 (int)rid, (int)len );
4019                         rc = ERROR;
4020                         goto done;
4021                 }
4022                 // read remainder of the rid
4023                 rc = bap_read(ai, ((u16*)pBuf)+1, len, BAP1);
4024         }
4025 done:
4026         if (lock)
4027                 up(&ai->sem);
4028         return rc;
4029 }
4030
4031 /*  Note, that we are using BAP1 which is also used by transmit, so
4032  *  make sure this isnt called when a transmit is happening */
4033 static int PC4500_writerid(struct airo_info *ai, u16 rid,
4034                            const void *pBuf, int len, int lock)
4035 {
4036         u16 status;
4037         int rc = SUCCESS;
4038
4039         *(u16*)pBuf = cpu_to_le16((u16)len);
4040
4041         if (lock) {
4042                 if (down_interruptible(&ai->sem))
4043                         return ERROR;
4044         }
4045         if (test_bit(FLAG_MPI,&ai->flags)) {
4046                 Cmd cmd;
4047                 Resp rsp;
4048
4049                 if (test_bit(FLAG_ENABLED, &ai->flags))
4050                         printk(KERN_ERR
4051                                 "%s: MAC should be disabled (rid=%04x)\n",
4052                                 __FUNCTION__, rid);
4053                 memset(&cmd, 0, sizeof(cmd));
4054                 memset(&rsp, 0, sizeof(rsp));
4055
4056                 ai->config_desc.rid_desc.valid = 1;
4057                 ai->config_desc.rid_desc.len = *((u16 *)pBuf);
4058                 ai->config_desc.rid_desc.rid = 0;
4059
4060                 cmd.cmd = CMD_WRITERID;
4061                 cmd.parm0 = rid;
4062
4063                 memcpy_toio(ai->config_desc.card_ram_off,
4064                         &ai->config_desc.rid_desc, sizeof(Rid));
4065
4066                 if (len < 4 || len > 2047) {
4067                         printk(KERN_ERR "%s: len=%d\n",__FUNCTION__,len);
4068                         rc = -1;
4069                 } else {
4070                         memcpy((char *)ai->config_desc.virtual_host_addr,
4071                                 pBuf, len);
4072
4073                         rc = issuecommand(ai, &cmd, &rsp);
4074                         if ((rc & 0xff00) != 0) {
4075                                 printk(KERN_ERR "%s: Write rid Error %d\n",
4076                                         __FUNCTION__,rc);
4077                                 printk(KERN_ERR "%s: Cmd=%04x\n",
4078                                                 __FUNCTION__,cmd.cmd);
4079                         }
4080
4081                         if ((rsp.status & 0x7f00))
4082                                 rc = rsp.rsp0;
4083                 }
4084         } else {
4085                 // --- first access so that we can write the rid data
4086                 if ( (status = PC4500_accessrid(ai, rid, CMD_ACCESS)) != 0) {
4087                         rc = status;
4088                         goto done;
4089                 }
4090                 // --- now write the rid data
4091                 if (bap_setup(ai, rid, 0, BAP1) != SUCCESS) {
4092                         rc = ERROR;
4093                         goto done;
4094                 }
4095                 bap_write(ai, pBuf, len, BAP1);
4096                 // ---now commit the rid data
4097                 rc = PC4500_accessrid(ai, rid, 0x100|CMD_ACCESS);
4098         }
4099 done:
4100         if (lock)
4101                 up(&ai->sem);
4102         return rc;
4103 }
4104
4105 /* Allocates a FID to be used for transmitting packets.  We only use
4106    one for now. */
4107 static u16 transmit_allocate(struct airo_info *ai, int lenPayload, int raw)
4108 {
4109         unsigned int loop = 3000;
4110         Cmd cmd;
4111         Resp rsp;
4112         u16 txFid;
4113         u16 txControl;
4114
4115         cmd.cmd = CMD_ALLOCATETX;
4116         cmd.parm0 = lenPayload;
4117         if (down_interruptible(&ai->sem))
4118                 return ERROR;
4119         if (issuecommand(ai, &cmd, &rsp) != SUCCESS) {
4120                 txFid = ERROR;
4121                 goto done;
4122         }
4123         if ( (rsp.status & 0xFF00) != 0) {
4124                 txFid = ERROR;
4125                 goto done;
4126         }
4127         /* wait for the allocate event/indication
4128          * It makes me kind of nervous that this can just sit here and spin,
4129          * but in practice it only loops like four times. */
4130         while (((IN4500(ai, EVSTAT) & EV_ALLOC) == 0) && --loop);
4131         if (!loop) {
4132                 txFid = ERROR;
4133                 goto done;
4134         }
4135
4136         // get the allocated fid and acknowledge
4137         txFid = IN4500(ai, TXALLOCFID);
4138         OUT4500(ai, EVACK, EV_ALLOC);
4139
4140         /*  The CARD is pretty cool since it converts the ethernet packet
4141          *  into 802.11.  Also note that we don't release the FID since we
4142          *  will be using the same one over and over again. */
4143         /*  We only have to setup the control once since we are not
4144          *  releasing the fid. */
4145         if (raw)
4146                 txControl = cpu_to_le16(TXCTL_TXOK | TXCTL_TXEX | TXCTL_802_11
4147                         | TXCTL_ETHERNET | TXCTL_NORELEASE);
4148         else
4149                 txControl = cpu_to_le16(TXCTL_TXOK | TXCTL_TXEX | TXCTL_802_3
4150                         | TXCTL_ETHERNET | TXCTL_NORELEASE);
4151         if (bap_setup(ai, txFid, 0x0008, BAP1) != SUCCESS)
4152                 txFid = ERROR;
4153         else
4154                 bap_write(ai, &txControl, sizeof(txControl), BAP1);
4155
4156 done:
4157         up(&ai->sem);
4158
4159         return txFid;
4160 }
4161
4162 /* In general BAP1 is dedicated to transmiting packets.  However,
4163    since we need a BAP when accessing RIDs, we also use BAP1 for that.
4164    Make sure the BAP1 spinlock is held when this is called. */
4165 static int transmit_802_3_packet(struct airo_info *ai, int len, char *pPacket)
4166 {
4167         u16 payloadLen;
4168         Cmd cmd;
4169         Resp rsp;
4170         int miclen = 0;
4171         u16 txFid = len;
4172         MICBuffer pMic;
4173
4174         len >>= 16;
4175
4176         if (len <= ETH_ALEN * 2) {
4177                 printk( KERN_WARNING "Short packet %d\n", len );
4178                 return ERROR;
4179         }
4180         len -= ETH_ALEN * 2;
4181
4182 #ifdef MICSUPPORT
4183         if (test_bit(FLAG_MIC_CAPABLE, &ai->flags) && ai->micstats.enabled && 
4184             (ntohs(((u16 *)pPacket)[6]) != 0x888E)) {
4185                 if (encapsulate(ai,(etherHead *)pPacket,&pMic,len) != SUCCESS)
4186                         return ERROR;
4187                 miclen = sizeof(pMic);
4188         }
4189 #endif
4190
4191         // packet is destination[6], source[6], payload[len-12]
4192         // write the payload length and dst/src/payload
4193         if (bap_setup(ai, txFid, 0x0036, BAP1) != SUCCESS) return ERROR;
4194         /* The hardware addresses aren't counted as part of the payload, so
4195          * we have to subtract the 12 bytes for the addresses off */
4196         payloadLen = cpu_to_le16(len + miclen);
4197         bap_write(ai, &payloadLen, sizeof(payloadLen),BAP1);
4198         bap_write(ai, (const u16*)pPacket, sizeof(etherHead), BAP1);
4199         if (miclen)
4200                 bap_write(ai, (const u16*)&pMic, miclen, BAP1);
4201         bap_write(ai, (const u16*)(pPacket + sizeof(etherHead)), len, BAP1);
4202         // issue the transmit command
4203         memset( &cmd, 0, sizeof( cmd ) );
4204         cmd.cmd = CMD_TRANSMIT;
4205         cmd.parm0 = txFid;
4206         if (issuecommand(ai, &cmd, &rsp) != SUCCESS) return ERROR;
4207         if ( (rsp.status & 0xFF00) != 0) return ERROR;
4208         return SUCCESS;
4209 }
4210
4211 static int transmit_802_11_packet(struct airo_info *ai, int len, char *pPacket)
4212 {
4213         u16 fc, payloadLen;
4214         Cmd cmd;
4215         Resp rsp;
4216         int hdrlen;
4217         struct {
4218                 u8 addr4[ETH_ALEN];
4219                 u16 gaplen;
4220                 u8 gap[6];
4221         } gap;
4222         u16 txFid = len;
4223         len >>= 16;
4224         gap.gaplen = 6;
4225
4226         fc = le16_to_cpu(*(const u16*)pPacket);
4227         switch (fc & 0xc) {
4228                 case 4:
4229                         if ((fc & 0xe0) == 0xc0)
4230                                 hdrlen = 10;
4231                         else
4232                                 hdrlen = 16;
4233                         break;
4234                 case 8:
4235                         if ((fc&0x300)==0x300){
4236                                 hdrlen = 30;
4237                                 break;
4238                         }
4239                 default:
4240                         hdrlen = 24;
4241         }
4242
4243         if (len < hdrlen) {
4244                 printk( KERN_WARNING "Short packet %d\n", len );
4245                 return ERROR;
4246         }
4247
4248         /* packet is 802.11 header +  payload
4249          * write the payload length and dst/src/payload */
4250         if (bap_setup(ai, txFid, 6, BAP1) != SUCCESS) return ERROR;
4251         /* The 802.11 header aren't counted as part of the payload, so
4252          * we have to subtract the header bytes off */
4253         payloadLen = cpu_to_le16(len-hdrlen);
4254         bap_write(ai, &payloadLen, sizeof(payloadLen),BAP1);
4255         if (bap_setup(ai, txFid, 0x0014, BAP1) != SUCCESS) return ERROR;
4256         bap_write(ai, (const u16*)pPacket, hdrlen, BAP1);
4257         bap_write(ai, hdrlen == 30 ?
4258                 (const u16*)&gap.gaplen : (const u16*)&gap, 38 - hdrlen, BAP1);
4259
4260         bap_write(ai, (const u16*)(pPacket + hdrlen), len - hdrlen, BAP1);
4261         // issue the transmit command
4262         memset( &cmd, 0, sizeof( cmd ) );
4263         cmd.cmd = CMD_TRANSMIT;
4264         cmd.parm0 = txFid;
4265         if (issuecommand(ai, &cmd, &rsp) != SUCCESS) return ERROR;
4266         if ( (rsp.status & 0xFF00) != 0) return ERROR;
4267         return SUCCESS;
4268 }
4269
4270 /*
4271  *  This is the proc_fs routines.  It is a bit messier than I would
4272  *  like!  Feel free to clean it up!
4273  */
4274
4275 static ssize_t proc_read( struct file *file,
4276                           char __user *buffer,
4277                           size_t len,
4278                           loff_t *offset);
4279
4280 static ssize_t proc_write( struct file *file,
4281                            const char __user *buffer,
4282                            size_t len,
4283                            loff_t *offset );
4284 static int proc_close( struct inode *inode, struct file *file );
4285
4286 static int proc_stats_open( struct inode *inode, struct file *file );
4287 static int proc_statsdelta_open( struct inode *inode, struct file *file );
4288 static int proc_status_open( struct inode *inode, struct file *file );
4289 static int proc_SSID_open( struct inode *inode, struct file *file );
4290 static int proc_APList_open( struct inode *inode, struct file *file );
4291 static int proc_BSSList_open( struct inode *inode, struct file *file );
4292 static int proc_config_open( struct inode *inode, struct file *file );
4293 static int proc_wepkey_open( struct inode *inode, struct file *file );
4294
4295 static struct file_operations proc_statsdelta_ops = {
4296         .read           = proc_read,
4297         .open           = proc_statsdelta_open,
4298         .release        = proc_close
4299 };
4300
4301 static struct file_operations proc_stats_ops = {
4302         .read           = proc_read,
4303         .open           = proc_stats_open,
4304         .release        = proc_close
4305 };
4306
4307 static struct file_operations proc_status_ops = {
4308         .read           = proc_read,
4309         .open           = proc_status_open,
4310         .release        = proc_close
4311 };
4312
4313 static struct file_operations proc_SSID_ops = {
4314         .read           = proc_read,
4315         .write          = proc_write,
4316         .open           = proc_SSID_open,
4317         .release        = proc_close
4318 };
4319
4320 static struct file_operations proc_BSSList_ops = {
4321         .read           = proc_read,
4322         .write          = proc_write,
4323         .open           = proc_BSSList_open,
4324         .release        = proc_close
4325 };
4326
4327 static struct file_operations proc_APList_ops = {
4328         .read           = proc_read,
4329         .write          = proc_write,
4330         .open           = proc_APList_open,
4331         .release        = proc_close
4332 };
4333
4334 static struct file_operations proc_config_ops = {
4335         .read           = proc_read,
4336         .write          = proc_write,
4337         .open           = proc_config_open,
4338         .release        = proc_close
4339 };
4340
4341 static struct file_operations proc_wepkey_ops = {
4342         .read           = proc_read,
4343         .write          = proc_write,
4344         .open           = proc_wepkey_open,
4345         .release        = proc_close
4346 };
4347
4348 static struct proc_dir_entry *airo_entry;
4349
4350 struct proc_data {
4351         int release_buffer;
4352         int readlen;
4353         char *rbuffer;
4354         int writelen;
4355         int maxwritelen;
4356         char *wbuffer;
4357         void (*on_close) (struct inode *, struct file *);
4358 };
4359
4360 #ifndef SETPROC_OPS
4361 #define SETPROC_OPS(entry, ops) (entry)->proc_fops = &(ops)
4362 #endif
4363
4364 static int setup_proc_entry( struct net_device *dev,
4365                              struct airo_info *apriv ) {
4366         struct proc_dir_entry *entry;
4367         /* First setup the device directory */
4368         strcpy(apriv->proc_name,dev->name);
4369         apriv->proc_entry = create_proc_entry(apriv->proc_name,
4370                                               S_IFDIR|airo_perm,
4371                                               airo_entry);
4372         apriv->proc_entry->uid = proc_uid;
4373         apriv->proc_entry->gid = proc_gid;
4374         apriv->proc_entry->owner = THIS_MODULE;
4375
4376         /* Setup the StatsDelta */
4377         entry = create_proc_entry("StatsDelta",
4378                                   S_IFREG | (S_IRUGO&proc_perm),
4379                                   apriv->proc_entry);
4380         entry->uid = proc_uid;
4381         entry->gid = proc_gid;
4382         entry->data = dev;
4383         entry->owner = THIS_MODULE;
4384         SETPROC_OPS(entry, proc_statsdelta_ops);
4385
4386         /* Setup the Stats */
4387         entry = create_proc_entry("Stats",
4388                                   S_IFREG | (S_IRUGO&proc_perm),
4389                                   apriv->proc_entry);
4390         entry->uid = proc_uid;
4391         entry->gid = proc_gid;
4392         entry->data = dev;
4393         entry->owner = THIS_MODULE;
4394         SETPROC_OPS(entry, proc_stats_ops);
4395
4396         /* Setup the Status */
4397         entry = create_proc_entry("Status",
4398                                   S_IFREG | (S_IRUGO&proc_perm),
4399                                   apriv->proc_entry);
4400         entry->uid = proc_uid;
4401         entry->gid = proc_gid;
4402         entry->data = dev;
4403         entry->owner = THIS_MODULE;
4404         SETPROC_OPS(entry, proc_status_ops);
4405
4406         /* Setup the Config */
4407         entry = create_proc_entry("Config",
4408                                   S_IFREG | proc_perm,
4409                                   apriv->proc_entry);
4410         entry->uid = proc_uid;
4411         entry->gid = proc_gid;
4412         entry->data = dev;
4413         entry->owner = THIS_MODULE;
4414         SETPROC_OPS(entry, proc_config_ops);
4415
4416         /* Setup the SSID */
4417         entry = create_proc_entry("SSID",
4418                                   S_IFREG | proc_perm,
4419                                   apriv->proc_entry);
4420         entry->uid = proc_uid;
4421         entry->gid = proc_gid;
4422         entry->data = dev;
4423         entry->owner = THIS_MODULE;
4424         SETPROC_OPS(entry, proc_SSID_ops);
4425
4426         /* Setup the APList */
4427         entry = create_proc_entry("APList",
4428                                   S_IFREG | proc_perm,
4429                                   apriv->proc_entry);
4430         entry->uid = proc_uid;
4431         entry->gid = proc_gid;
4432         entry->data = dev;
4433         entry->owner = THIS_MODULE;
4434         SETPROC_OPS(entry, proc_APList_ops);
4435
4436         /* Setup the BSSList */
4437         entry = create_proc_entry("BSSList",
4438                                   S_IFREG | proc_perm,
4439                                   apriv->proc_entry);
4440         entry->uid = proc_uid;
4441         entry->gid = proc_gid;
4442         entry->data = dev;
4443         entry->owner = THIS_MODULE;
4444         SETPROC_OPS(entry, proc_BSSList_ops);
4445
4446         /* Setup the WepKey */
4447         entry = create_proc_entry("WepKey",
4448                                   S_IFREG | proc_perm,
4449                                   apriv->proc_entry);
4450         entry->uid = proc_uid;
4451         entry->gid = proc_gid;
4452         entry->data = dev;
4453         entry->owner = THIS_MODULE;
4454         SETPROC_OPS(entry, proc_wepkey_ops);
4455
4456         return 0;
4457 }
4458
4459 static int takedown_proc_entry( struct net_device *dev,
4460                                 struct airo_info *apriv ) {
4461         if ( !apriv->proc_entry->namelen ) return 0;
4462         remove_proc_entry("Stats",apriv->proc_entry);
4463         remove_proc_entry("StatsDelta",apriv->proc_entry);
4464         remove_proc_entry("Status",apriv->proc_entry);
4465         remove_proc_entry("Config",apriv->proc_entry);
4466         remove_proc_entry("SSID",apriv->proc_entry);
4467         remove_proc_entry("APList",apriv->proc_entry);
4468         remove_proc_entry("BSSList",apriv->proc_entry);
4469         remove_proc_entry("WepKey",apriv->proc_entry);
4470         remove_proc_entry(apriv->proc_name,airo_entry);
4471         return 0;
4472 }
4473
4474 /*
4475  *  What we want from the proc_fs is to be able to efficiently read
4476  *  and write the configuration.  To do this, we want to read the
4477  *  configuration when the file is opened and write it when the file is
4478  *  closed.  So basically we allocate a read buffer at open and fill it
4479  *  with data, and allocate a write buffer and read it at close.
4480  */
4481
4482 /*
4483  *  The read routine is generic, it relies on the preallocated rbuffer
4484  *  to supply the data.
4485  */
4486 static ssize_t proc_read( struct file *file,
4487                           char __user *buffer,
4488                           size_t len,
4489                           loff_t *offset )
4490 {
4491         loff_t pos = *offset;
4492         struct proc_data *priv = (struct proc_data*)file->private_data;
4493
4494         if (!priv->rbuffer)
4495                 return -EINVAL;
4496
4497         if (pos < 0)
4498                 return -EINVAL;
4499         if (pos >= priv->readlen)
4500                 return 0;
4501         if (len > priv->readlen - pos)
4502                 len = priv->readlen - pos;
4503         if (copy_to_user(buffer, priv->rbuffer + pos, len))
4504                 return -EFAULT;
4505         *offset = pos + len;
4506         return len;
4507 }
4508
4509 /*
4510  *  The write routine is generic, it fills in a preallocated rbuffer
4511  *  to supply the data.
4512  */
4513 static ssize_t proc_write( struct file *file,
4514                            const char __user *buffer,
4515                            size_t len,
4516                            loff_t *offset )
4517 {
4518         loff_t pos = *offset;
4519         struct proc_data *priv = (struct proc_data*)file->private_data;
4520
4521         if (!priv->wbuffer)
4522                 return -EINVAL;
4523
4524         if (pos < 0)
4525                 return -EINVAL;
4526         if (pos >= priv->maxwritelen)
4527                 return 0;
4528         if (len > priv->maxwritelen - pos)
4529                 len = priv->maxwritelen - pos;
4530         if (copy_from_user(priv->wbuffer + pos, buffer, len))
4531                 return -EFAULT;
4532         if ( pos + len > priv->writelen )
4533                 priv->writelen = len + file->f_pos;
4534         *offset = pos + len;
4535         return len;
4536 }
4537
4538 static int proc_status_open( struct inode *inode, struct file *file ) {
4539         struct proc_data *data;
4540         struct proc_dir_entry *dp = PDE(inode);
4541         struct net_device *dev = dp->data;
4542         struct airo_info *apriv = dev->priv;
4543         CapabilityRid cap_rid;
4544         StatusRid status_rid;
4545         int i;
4546
4547         if ((file->private_data = kmalloc(sizeof(struct proc_data ), GFP_KERNEL)) == NULL)
4548                 return -ENOMEM;
4549         memset(file->private_data, 0, sizeof(struct proc_data));
4550         data = (struct proc_data *)file->private_data;
4551         if ((data->rbuffer = kmalloc( 2048, GFP_KERNEL )) == NULL) {
4552                 kfree (file->private_data);
4553                 return -ENOMEM;
4554         }
4555
4556         readStatusRid(apriv, &status_rid, 1);
4557         readCapabilityRid(apriv, &cap_rid, 1);
4558
4559         i = sprintf(data->rbuffer, "Status: %s%s%s%s%s%s%s%s%s\n",
4560                     status_rid.mode & 1 ? "CFG ": "",
4561                     status_rid.mode & 2 ? "ACT ": "",
4562                     status_rid.mode & 0x10 ? "SYN ": "",
4563                     status_rid.mode & 0x20 ? "LNK ": "",
4564                     status_rid.mode & 0x40 ? "LEAP ": "",
4565                     status_rid.mode & 0x80 ? "PRIV ": "",
4566                     status_rid.mode & 0x100 ? "KEY ": "",
4567                     status_rid.mode & 0x200 ? "WEP ": "",
4568                     status_rid.mode & 0x8000 ? "ERR ": "");
4569         sprintf( data->rbuffer+i, "Mode: %x\n"
4570                  "Signal Strength: %d\n"
4571                  "Signal Quality: %d\n"
4572                  "SSID: %-.*s\n"
4573                  "AP: %-.16s\n"
4574                  "Freq: %d\n"
4575                  "BitRate: %dmbs\n"
4576                  "Driver Version: %s\n"
4577                  "Device: %s\nManufacturer: %s\nFirmware Version: %s\n"
4578                  "Radio type: %x\nCountry: %x\nHardware Version: %x\n"
4579                  "Software Version: %x\nSoftware Subversion: %x\n"
4580                  "Boot block version: %x\n",
4581                  (int)status_rid.mode,
4582                  (int)status_rid.normalizedSignalStrength,
4583                  (int)status_rid.signalQuality,
4584                  (int)status_rid.SSIDlen,
4585                  status_rid.SSID,
4586                  status_rid.apName,
4587                  (int)status_rid.channel,
4588                  (int)status_rid.currentXmitRate/2,
4589                  version,
4590                  cap_rid.prodName,
4591                  cap_rid.manName,
4592                  cap_rid.prodVer,
4593                  cap_rid.radioType,
4594                  cap_rid.country,
4595                  cap_rid.hardVer,
4596                  (int)cap_rid.softVer,
4597                  (int)cap_rid.softSubVer,
4598                  (int)cap_rid.bootBlockVer );
4599         data->readlen = strlen( data->rbuffer );
4600         return 0;
4601 }
4602
4603 static int proc_stats_rid_open(struct inode*, struct file*, u16);
4604 static int proc_statsdelta_open( struct inode *inode,
4605                                  struct file *file ) {
4606         if (file->f_mode&FMODE_WRITE) {
4607                 return proc_stats_rid_open(inode, file, RID_STATSDELTACLEAR);
4608         }
4609         return proc_stats_rid_open(inode, file, RID_STATSDELTA);
4610 }
4611
4612 static int proc_stats_open( struct inode *inode, struct file *file ) {
4613         return proc_stats_rid_open(inode, file, RID_STATS);
4614 }
4615
4616 static int proc_stats_rid_open( struct inode *inode,
4617                                 struct file *file,
4618                                 u16 rid ) {
4619         struct proc_data *data;
4620         struct proc_dir_entry *dp = PDE(inode);
4621         struct net_device *dev = dp->data;
4622         struct airo_info *apriv = dev->priv;
4623         StatsRid stats;
4624         int i, j;
4625         u32 *vals = stats.vals;
4626
4627         if ((file->private_data = kmalloc(sizeof(struct proc_data ), GFP_KERNEL)) == NULL)
4628                 return -ENOMEM;
4629         memset(file->private_data, 0, sizeof(struct proc_data));
4630         data = (struct proc_data *)file->private_data;
4631         if ((data->rbuffer = kmalloc( 4096, GFP_KERNEL )) == NULL) {
4632                 kfree (file->private_data);
4633                 return -ENOMEM;
4634         }
4635
4636         readStatsRid(apriv, &stats, rid, 1);
4637
4638         j = 0;
4639         for(i=0; statsLabels[i]!=(char *)-1 &&
4640                     i*4<stats.len; i++){
4641                 if (!statsLabels[i]) continue;
4642                 if (j+strlen(statsLabels[i])+16>4096) {
4643                         printk(KERN_WARNING
4644                                "airo: Potentially disasterous buffer overflow averted!\n");
4645                         break;
4646                 }
4647                 j+=sprintf(data->rbuffer+j, "%s: %u\n", statsLabels[i], vals[i]);
4648         }
4649         if (i*4>=stats.len){
4650                 printk(KERN_WARNING
4651                        "airo: Got a short rid\n");
4652         }
4653         data->readlen = j;
4654         return 0;
4655 }
4656
4657 static int get_dec_u16( char *buffer, int *start, int limit ) {
4658         u16 value;
4659         int valid = 0;
4660         for( value = 0; buffer[*start] >= '0' &&
4661                      buffer[*start] <= '9' &&
4662                      *start < limit; (*start)++ ) {
4663                 valid = 1;
4664                 value *= 10;
4665                 value += buffer[*start] - '0';
4666         }
4667         if ( !valid ) return -1;
4668         return value;
4669 }
4670
4671 static int airo_config_commit(struct net_device *dev,
4672                               struct iw_request_info *info, void *zwrq,
4673                               char *extra);
4674
4675 static void proc_config_on_close( struct inode *inode, struct file *file ) {
4676         struct proc_data *data = file->private_data;
4677         struct proc_dir_entry *dp = PDE(inode);
4678         struct net_device *dev = dp->data;
4679         struct airo_info *ai = dev->priv;
4680         char *line;
4681
4682         if ( !data->writelen ) return;
4683
4684         readConfigRid(ai, 1);
4685         set_bit (FLAG_COMMIT, &ai->flags);
4686
4687         line = data->wbuffer;
4688         while( line[0] ) {
4689 /*** Mode processing */
4690                 if ( !strncmp( line, "Mode: ", 6 ) ) {
4691                         line += 6;
4692                         if ((ai->config.rmode & 0xff) >= RXMODE_RFMON)
4693                                         set_bit (FLAG_RESET, &ai->flags);
4694                         ai->config.rmode &= 0xfe00;
4695                         clear_bit (FLAG_802_11, &ai->flags);
4696                         ai->config.opmode &= 0xFF00;
4697                         ai->config.scanMode = SCANMODE_ACTIVE;
4698                         if ( line[0] == 'a' ) {
4699                                 ai->config.opmode |= 0;
4700                         } else {
4701                                 ai->config.opmode |= 1;
4702                                 if ( line[0] == 'r' ) {
4703                                         ai->config.rmode |= RXMODE_RFMON | RXMODE_DISABLE_802_3_HEADER;
4704                                         ai->config.scanMode = SCANMODE_PASSIVE;
4705                                         set_bit (FLAG_802_11, &ai->flags);
4706                                 } else if ( line[0] == 'y' ) {
4707                                         ai->config.rmode |= RXMODE_RFMON_ANYBSS | RXMODE_DISABLE_802_3_HEADER;
4708                                         ai->config.scanMode = SCANMODE_PASSIVE;
4709                                         set_bit (FLAG_802_11, &ai->flags);
4710                                 } else if ( line[0] == 'l' )
4711                                         ai->config.rmode |= RXMODE_LANMON;
4712                         }
4713                         set_bit (FLAG_COMMIT, &ai->flags);
4714                 }
4715
4716 /*** Radio status */
4717                 else if (!strncmp(line,"Radio: ", 7)) {
4718                         line += 7;
4719                         if (!strncmp(line,"off",3)) {
4720                                 set_bit (FLAG_RADIO_OFF, &ai->flags);
4721                         } else {
4722                                 clear_bit (FLAG_RADIO_OFF, &ai->flags);
4723                         }
4724                 }
4725 /*** NodeName processing */
4726                 else if ( !strncmp( line, "NodeName: ", 10 ) ) {
4727                         int j;
4728
4729                         line += 10;
4730                         memset( ai->config.nodeName, 0, 16 );
4731 /* Do the name, assume a space between the mode and node name */
4732                         for( j = 0; j < 16 && line[j] != '\n'; j++ ) {
4733                                 ai->config.nodeName[j] = line[j];
4734                         }
4735                         set_bit (FLAG_COMMIT, &ai->flags);
4736                 }
4737
4738 /*** PowerMode processing */
4739                 else if ( !strncmp( line, "PowerMode: ", 11 ) ) {
4740                         line += 11;
4741                         if ( !strncmp( line, "PSPCAM", 6 ) ) {
4742                                 ai->config.powerSaveMode = POWERSAVE_PSPCAM;
4743                                 set_bit (FLAG_COMMIT, &ai->flags);
4744                         } else if ( !strncmp( line, "PSP", 3 ) ) {
4745                                 ai->config.powerSaveMode = POWERSAVE_PSP;
4746                                 set_bit (FLAG_COMMIT, &ai->flags);
4747                         } else {
4748                                 ai->config.powerSaveMode = POWERSAVE_CAM;
4749                                 set_bit (FLAG_COMMIT, &ai->flags);
4750                         }
4751                 } else if ( !strncmp( line, "DataRates: ", 11 ) ) {
4752                         int v, i = 0, k = 0; /* i is index into line,
4753                                                 k is index to rates */
4754
4755                         line += 11;
4756                         while((v = get_dec_u16(line, &i, 3))!=-1) {
4757                                 ai->config.rates[k++] = (u8)v;
4758                                 line += i + 1;
4759                                 i = 0;
4760                         }
4761                         set_bit (FLAG_COMMIT, &ai->flags);
4762                 } else if ( !strncmp( line, "Channel: ", 9 ) ) {
4763                         int v, i = 0;
4764                         line += 9;
4765                         v = get_dec_u16(line, &i, i+3);
4766                         if ( v != -1 ) {
4767                                 ai->config.channelSet = (u16)v;
4768                                 set_bit (FLAG_COMMIT, &ai->flags);
4769                         }
4770                 } else if ( !strncmp( line, "XmitPower: ", 11 ) ) {
4771                         int v, i = 0;
4772                         line += 11;
4773                         v = get_dec_u16(line, &i, i+3);
4774                         if ( v != -1 ) {
4775                                 ai->config.txPower = (u16)v;
4776                                 set_bit (FLAG_COMMIT, &ai->flags);
4777                         }
4778                 } else if ( !strncmp( line, "WEP: ", 5 ) ) {
4779                         line += 5;
4780                         switch( line[0] ) {
4781                         case 's':
4782                                 ai->config.authType = (u16)AUTH_SHAREDKEY;
4783                                 break;
4784                         case 'e':
4785                                 ai->config.authType = (u16)AUTH_ENCRYPT;
4786                                 break;
4787                         default:
4788                                 ai->config.authType = (u16)AUTH_OPEN;
4789                                 break;
4790                         }
4791                         set_bit (FLAG_COMMIT, &ai->flags);
4792                 } else if ( !strncmp( line, "LongRetryLimit: ", 16 ) ) {
4793                         int v, i = 0;
4794
4795                         line += 16;
4796                         v = get_dec_u16(line, &i, 3);
4797                         v = (v<0) ? 0 : ((v>255) ? 255 : v);
4798                         ai->config.longRetryLimit = (u16)v;
4799                         set_bit (FLAG_COMMIT, &ai->flags);
4800                 } else if ( !strncmp( line, "ShortRetryLimit: ", 17 ) ) {
4801                         int v, i = 0;
4802
4803                         line += 17;
4804                         v = get_dec_u16(line, &i, 3);
4805                         v = (v<0) ? 0 : ((v>255) ? 255 : v);
4806                         ai->config.shortRetryLimit = (u16)v;
4807                         set_bit (FLAG_COMMIT, &ai->flags);
4808                 } else if ( !strncmp( line, "RTSThreshold: ", 14 ) ) {
4809                         int v, i = 0;
4810
4811                         line += 14;
4812                         v = get_dec_u16(line, &i, 4);
4813                         v = (v<0) ? 0 : ((v>2312) ? 2312 : v);
4814                         ai->config.rtsThres = (u16)v;
4815                         set_bit (FLAG_COMMIT, &ai->flags);
4816                 } else if ( !strncmp( line, "TXMSDULifetime: ", 16 ) ) {
4817                         int v, i = 0;
4818
4819                         line += 16;
4820                         v = get_dec_u16(line, &i, 5);
4821                         v = (v<0) ? 0 : v;
4822                         ai->config.txLifetime = (u16)v;
4823                         set_bit (FLAG_COMMIT, &ai->flags);
4824                 } else if ( !strncmp( line, "RXMSDULifetime: ", 16 ) ) {
4825                         int v, i = 0;
4826
4827                         line += 16;
4828                         v = get_dec_u16(line, &i, 5);
4829                         v = (v<0) ? 0 : v;
4830                         ai->config.rxLifetime = (u16)v;
4831                         set_bit (FLAG_COMMIT, &ai->flags);
4832                 } else if ( !strncmp( line, "TXDiversity: ", 13 ) ) {
4833                         ai->config.txDiversity =
4834                                 (line[13]=='l') ? 1 :
4835                                 ((line[13]=='r')? 2: 3);
4836                         set_bit (FLAG_COMMIT, &ai->flags);
4837                 } else if ( !strncmp( line, "RXDiversity: ", 13 ) ) {
4838                         ai->config.rxDiversity =
4839                                 (line[13]=='l') ? 1 :
4840                                 ((line[13]=='r')? 2: 3);
4841                         set_bit (FLAG_COMMIT, &ai->flags);
4842                 } else if ( !strncmp( line, "FragThreshold: ", 15 ) ) {
4843                         int v, i = 0;
4844
4845                         line += 15;
4846                         v = get_dec_u16(line, &i, 4);
4847                         v = (v<256) ? 256 : ((v>2312) ? 2312 : v);
4848                         v = v & 0xfffe; /* Make sure its even */
4849                         ai->config.fragThresh = (u16)v;
4850                         set_bit (FLAG_COMMIT, &ai->flags);
4851                 } else if (!strncmp(line, "Modulation: ", 12)) {
4852                         line += 12;
4853                         switch(*line) {
4854                         case 'd':  ai->config.modulation=MOD_DEFAULT; set_bit(FLAG_COMMIT, &ai->flags); break;
4855                         case 'c':  ai->config.modulation=MOD_CCK; set_bit(FLAG_COMMIT, &ai->flags); break;
4856                         case 'm':  ai->config.modulation=MOD_MOK; set_bit(FLAG_COMMIT, &ai->flags); break;
4857                         default:
4858                                 printk( KERN_WARNING "airo: Unknown modulation\n" );
4859                         }
4860                 } else if (!strncmp(line, "Preamble: ", 10)) {
4861                         line += 10;
4862                         switch(*line) {
4863                         case 'a': ai->config.preamble=PREAMBLE_AUTO; set_bit(FLAG_COMMIT, &ai->flags); break;
4864                         case 'l': ai->config.preamble=PREAMBLE_LONG; set_bit(FLAG_COMMIT, &ai->flags); break;
4865                         case 's': ai->config.preamble=PREAMBLE_SHORT; set_bit(FLAG_COMMIT, &ai->flags); break;
4866                         default: printk(KERN_WARNING "airo: Unknown preamble\n");
4867                         }
4868                 } else {
4869                         printk( KERN_WARNING "Couldn't figure out %s\n", line );
4870                 }
4871                 while( line[0] && line[0] != '\n' ) line++;
4872                 if ( line[0] ) line++;
4873         }
4874         airo_config_commit(dev, NULL, NULL, NULL);
4875 }
4876
4877 static char *get_rmode(u16 mode) {
4878         switch(mode&0xff) {
4879         case RXMODE_RFMON:  return "rfmon";
4880         case RXMODE_RFMON_ANYBSS:  return "yna (any) bss rfmon";
4881         case RXMODE_LANMON:  return "lanmon";
4882         }
4883         return "ESS";
4884 }
4885
4886 static int proc_config_open( struct inode *inode, struct file *file ) {
4887         struct proc_data *data;
4888         struct proc_dir_entry *dp = PDE(inode);
4889         struct net_device *dev = dp->data;
4890         struct airo_info *ai = dev->priv;
4891         int i;
4892
4893         if ((file->private_data = kmalloc(sizeof(struct proc_data ), GFP_KERNEL)) == NULL)
4894                 return -ENOMEM;
4895         memset(file->private_data, 0, sizeof(struct proc_data));
4896         data = (struct proc_data *)file->private_data;
4897         if ((data->rbuffer = kmalloc( 2048, GFP_KERNEL )) == NULL) {
4898                 kfree (file->private_data);
4899                 return -ENOMEM;
4900         }
4901         if ((data->wbuffer = kmalloc( 2048, GFP_KERNEL )) == NULL) {
4902                 kfree (data->rbuffer);
4903                 kfree (file->private_data);
4904                 return -ENOMEM;
4905         }
4906         memset( data->wbuffer, 0, 2048 );
4907         data->maxwritelen = 2048;
4908         data->on_close = proc_config_on_close;
4909
4910         readConfigRid(ai, 1);
4911
4912         i = sprintf( data->rbuffer,
4913                      "Mode: %s\n"
4914                      "Radio: %s\n"
4915                      "NodeName: %-16s\n"
4916                      "PowerMode: %s\n"
4917                      "DataRates: %d %d %d %d %d %d %d %d\n"
4918                      "Channel: %d\n"
4919                      "XmitPower: %d\n",
4920                      (ai->config.opmode & 0xFF) == 0 ? "adhoc" :
4921                      (ai->config.opmode & 0xFF) == 1 ? get_rmode(ai->config.rmode):
4922                      (ai->config.opmode & 0xFF) == 2 ? "AP" :
4923                      (ai->config.opmode & 0xFF) == 3 ? "AP RPTR" : "Error",
4924                      test_bit(FLAG_RADIO_OFF, &ai->flags) ? "off" : "on",
4925                      ai->config.nodeName,
4926                      ai->config.powerSaveMode == 0 ? "CAM" :
4927                      ai->config.powerSaveMode == 1 ? "PSP" :
4928                      ai->config.powerSaveMode == 2 ? "PSPCAM" : "Error",
4929                      (int)ai->config.rates[0],
4930                      (int)ai->config.rates[1],
4931                      (int)ai->config.rates[2],
4932                      (int)ai->config.rates[3],
4933                      (int)ai->config.rates[4],
4934                      (int)ai->config.rates[5],
4935                      (int)ai->config.rates[6],
4936                      (int)ai->config.rates[7],
4937                      (int)ai->config.channelSet,
4938                      (int)ai->config.txPower
4939                 );
4940         sprintf( data->rbuffer + i,
4941                  "LongRetryLimit: %d\n"
4942                  "ShortRetryLimit: %d\n"
4943                  "RTSThreshold: %d\n"
4944                  "TXMSDULifetime: %d\n"
4945                  "RXMSDULifetime: %d\n"
4946                  "TXDiversity: %s\n"
4947                  "RXDiversity: %s\n"
4948                  "FragThreshold: %d\n"
4949                  "WEP: %s\n"
4950                  "Modulation: %s\n"
4951                  "Preamble: %s\n",
4952                  (int)ai->config.longRetryLimit,
4953                  (int)ai->config.shortRetryLimit,
4954                  (int)ai->config.rtsThres,
4955                  (int)ai->config.txLifetime,
4956                  (int)ai->config.rxLifetime,
4957                  ai->config.txDiversity == 1 ? "left" :
4958                  ai->config.txDiversity == 2 ? "right" : "both",
4959                  ai->config.rxDiversity == 1 ? "left" :
4960                  ai->config.rxDiversity == 2 ? "right" : "both",
4961                  (int)ai->config.fragThresh,
4962                  ai->config.authType == AUTH_ENCRYPT ? "encrypt" :
4963                  ai->config.authType == AUTH_SHAREDKEY ? "shared" : "open",
4964                  ai->config.modulation == 0 ? "default" :
4965                  ai->config.modulation == MOD_CCK ? "cck" :
4966                  ai->config.modulation == MOD_MOK ? "mok" : "error",
4967                  ai->config.preamble == PREAMBLE_AUTO ? "auto" :
4968                  ai->config.preamble == PREAMBLE_LONG ? "long" :
4969                  ai->config.preamble == PREAMBLE_SHORT ? "short" : "error"
4970                 );
4971         data->readlen = strlen( data->rbuffer );
4972         return 0;
4973 }
4974
4975 static void proc_SSID_on_close( struct inode *inode, struct file *file ) {
4976         struct proc_data *data = (struct proc_data *)file->private_data;
4977         struct proc_dir_entry *dp = PDE(inode);
4978         struct net_device *dev = dp->data;
4979         struct airo_info *ai = dev->priv;
4980         SsidRid SSID_rid;
4981         Resp rsp;
4982         int i;
4983         int offset = 0;
4984
4985         if ( !data->writelen ) return;
4986
4987         memset( &SSID_rid, 0, sizeof( SSID_rid ) );
4988
4989         for( i = 0; i < 3; i++ ) {
4990                 int j;
4991                 for( j = 0; j+offset < data->writelen && j < 32 &&
4992                              data->wbuffer[offset+j] != '\n'; j++ ) {
4993                         SSID_rid.ssids[i].ssid[j] = data->wbuffer[offset+j];
4994                 }
4995                 if ( j == 0 ) break;
4996                 SSID_rid.ssids[i].len = j;
4997                 offset += j;
4998                 while( data->wbuffer[offset] != '\n' &&
4999                        offset < data->writelen ) offset++;
5000                 offset++;
5001         }
5002         if (i)
5003                 SSID_rid.len = sizeof(SSID_rid);
5004         disable_MAC(ai, 1);
5005         writeSsidRid(ai, &SSID_rid, 1);
5006         enable_MAC(ai, &rsp, 1);
5007 }
5008
5009 inline static u8 hexVal(char c) {
5010         if (c>='0' && c<='9') return c -= '0';
5011         if (c>='a' && c<='f') return c -= 'a'-10;
5012         if (c>='A' && c<='F') return c -= 'A'-10;
5013         return 0;
5014 }
5015
5016 static void proc_APList_on_close( struct inode *inode, struct file *file ) {
5017         struct proc_data *data = (struct proc_data *)file->private_data;
5018         struct proc_dir_entry *dp = PDE(inode);
5019         struct net_device *dev = dp->data;
5020         struct airo_info *ai = dev->priv;
5021         APListRid APList_rid;
5022         Resp rsp;
5023         int i;
5024
5025         if ( !data->writelen ) return;
5026
5027         memset( &APList_rid, 0, sizeof(APList_rid) );
5028         APList_rid.len = sizeof(APList_rid);
5029
5030         for( i = 0; i < 4 && data->writelen >= (i+1)*6*3; i++ ) {
5031                 int j;
5032                 for( j = 0; j < 6*3 && data->wbuffer[j+i*6*3]; j++ ) {
5033                         switch(j%3) {
5034                         case 0:
5035                                 APList_rid.ap[i][j/3]=
5036                                         hexVal(data->wbuffer[j+i*6*3])<<4;
5037                                 break;
5038                         case 1:
5039                                 APList_rid.ap[i][j/3]|=
5040                                         hexVal(data->wbuffer[j+i*6*3]);
5041                                 break;
5042                         }
5043                 }
5044         }
5045         disable_MAC(ai, 1);
5046         writeAPListRid(ai, &APList_rid, 1);
5047         enable_MAC(ai, &rsp, 1);
5048 }
5049
5050 /* This function wraps PC4500_writerid with a MAC disable */
5051 static int do_writerid( struct airo_info *ai, u16 rid, const void *rid_data,
5052                         int len, int dummy ) {
5053         int rc;
5054         Resp rsp;
5055
5056         disable_MAC(ai, 1);
5057         rc = PC4500_writerid(ai, rid, rid_data, len, 1);
5058         enable_MAC(ai, &rsp, 1);
5059         return rc;
5060 }
5061
5062 /* Returns the length of the key at the index.  If index == 0xffff
5063  * the index of the transmit key is returned.  If the key doesn't exist,
5064  * -1 will be returned.
5065  */
5066 static int get_wep_key(struct airo_info *ai, u16 index) {
5067         WepKeyRid wkr;
5068         int rc;
5069         u16 lastindex;
5070
5071         rc = readWepKeyRid(ai, &wkr, 1, 1);
5072         if (rc == SUCCESS) do {
5073                 lastindex = wkr.kindex;
5074                 if (wkr.kindex == index) {
5075                         if (index == 0xffff) {
5076                                 return wkr.mac[0];
5077                         }
5078                         return wkr.klen;
5079                 }
5080                 readWepKeyRid(ai, &wkr, 0, 1);
5081         } while(lastindex != wkr.kindex);
5082         return -1;
5083 }
5084
5085 static int set_wep_key(struct airo_info *ai, u16 index,
5086                        const char *key, u16 keylen, int perm, int lock ) {
5087         static const unsigned char macaddr[ETH_ALEN] = { 0x01, 0, 0, 0, 0, 0 };
5088         WepKeyRid wkr;
5089         Resp rsp;
5090
5091         memset(&wkr, 0, sizeof(wkr));
5092         if (keylen == 0) {
5093 // We are selecting which key to use
5094                 wkr.len = sizeof(wkr);
5095                 wkr.kindex = 0xffff;
5096                 wkr.mac[0] = (char)index;
5097                 if (perm) printk(KERN_INFO "Setting transmit key to %d\n", index);
5098                 if (perm) ai->defindex = (char)index;
5099         } else {
5100 // We are actually setting the key
5101                 wkr.len = sizeof(wkr);
5102                 wkr.kindex = index;
5103                 wkr.klen = keylen;
5104                 memcpy( wkr.key, key, keylen );
5105                 memcpy( wkr.mac, macaddr, ETH_ALEN );
5106                 printk(KERN_INFO "Setting key %d\n", index);
5107         }
5108
5109         disable_MAC(ai, lock);
5110         writeWepKeyRid(ai, &wkr, perm, lock);
5111         enable_MAC(ai, &rsp, lock);
5112         return 0;
5113 }
5114
5115 static void proc_wepkey_on_close( struct inode *inode, struct file *file ) {
5116         struct proc_data *data;
5117         struct proc_dir_entry *dp = PDE(inode);
5118         struct net_device *dev = dp->data;
5119         struct airo_info *ai = dev->priv;
5120         int i;
5121         char key[16];
5122         u16 index = 0;
5123         int j = 0;
5124
5125         memset(key, 0, sizeof(key));
5126
5127         data = (struct proc_data *)file->private_data;
5128         if ( !data->writelen ) return;
5129
5130         if (data->wbuffer[0] >= '0' && data->wbuffer[0] <= '3' &&
5131             (data->wbuffer[1] == ' ' || data->wbuffer[1] == '\n')) {
5132                 index = data->wbuffer[0] - '0';
5133                 if (data->wbuffer[1] == '\n') {
5134                         set_wep_key(ai, index, NULL, 0, 1, 1);
5135                         return;
5136                 }
5137                 j = 2;
5138         } else {
5139                 printk(KERN_ERR "airo:  WepKey passed invalid key index\n");
5140                 return;
5141         }
5142
5143         for( i = 0; i < 16*3 && data->wbuffer[i+j]; i++ ) {
5144                 switch(i%3) {
5145                 case 0:
5146                         key[i/3] = hexVal(data->wbuffer[i+j])<<4;
5147                         break;
5148                 case 1:
5149                         key[i/3] |= hexVal(data->wbuffer[i+j]);
5150                         break;
5151                 }
5152         }
5153         set_wep_key(ai, index, key, i/3, 1, 1);
5154 }
5155
5156 static int proc_wepkey_open( struct inode *inode, struct file *file ) {
5157         struct proc_data *data;
5158         struct proc_dir_entry *dp = PDE(inode);
5159         struct net_device *dev = dp->data;
5160         struct airo_info *ai = dev->priv;
5161         char *ptr;
5162         WepKeyRid wkr;
5163         u16 lastindex;
5164         int j=0;
5165         int rc;
5166
5167         if ((file->private_data = kmalloc(sizeof(struct proc_data ), GFP_KERNEL)) == NULL)
5168                 return -ENOMEM;
5169         memset(file->private_data, 0, sizeof(struct proc_data));
5170         memset(&wkr, 0, sizeof(wkr));
5171         data = (struct proc_data *)file->private_data;
5172         if ((data->rbuffer = kmalloc( 180, GFP_KERNEL )) == NULL) {
5173                 kfree (file->private_data);
5174                 return -ENOMEM;
5175         }
5176         memset(data->rbuffer, 0, 180);
5177         data->writelen = 0;
5178         data->maxwritelen = 80;
5179         if ((data->wbuffer = kmalloc( 80, GFP_KERNEL )) == NULL) {
5180                 kfree (data->rbuffer);
5181                 kfree (file->private_data);
5182                 return -ENOMEM;
5183         }
5184         memset( data->wbuffer, 0, 80 );
5185         data->on_close = proc_wepkey_on_close;
5186
5187         ptr = data->rbuffer;
5188         strcpy(ptr, "No wep keys\n");
5189         rc = readWepKeyRid(ai, &wkr, 1, 1);
5190         if (rc == SUCCESS) do {
5191                 lastindex = wkr.kindex;
5192                 if (wkr.kindex == 0xffff) {
5193                         j += sprintf(ptr+j, "Tx key = %d\n",
5194                                      (int)wkr.mac[0]);
5195                 } else {
5196                         j += sprintf(ptr+j, "Key %d set with length = %d\n",
5197                                      (int)wkr.kindex, (int)wkr.klen);
5198                 }
5199                 readWepKeyRid(ai, &wkr, 0, 1);
5200         } while((lastindex != wkr.kindex) && (j < 180-30));
5201
5202         data->readlen = strlen( data->rbuffer );
5203         return 0;
5204 }
5205
5206 static int proc_SSID_open( struct inode *inode, struct file *file ) {
5207         struct proc_data *data;
5208         struct proc_dir_entry *dp = PDE(inode);
5209         struct net_device *dev = dp->data;
5210         struct airo_info *ai = dev->priv;
5211         int i;
5212         char *ptr;
5213         SsidRid SSID_rid;
5214
5215         if ((file->private_data = kmalloc(sizeof(struct proc_data ), GFP_KERNEL)) == NULL)
5216                 return -ENOMEM;
5217         memset(file->private_data, 0, sizeof(struct proc_data));
5218         data = (struct proc_data *)file->private_data;
5219         if ((data->rbuffer = kmalloc( 104, GFP_KERNEL )) == NULL) {
5220                 kfree (file->private_data);
5221                 return -ENOMEM;
5222         }
5223         data->writelen = 0;
5224         data->maxwritelen = 33*3;
5225         if ((data->wbuffer = kmalloc( 33*3, GFP_KERNEL )) == NULL) {
5226                 kfree (data->rbuffer);
5227                 kfree (file->private_data);
5228                 return -ENOMEM;
5229         }
5230         memset( data->wbuffer, 0, 33*3 );
5231         data->on_close = proc_SSID_on_close;
5232
5233         readSsidRid(ai, &SSID_rid);
5234         ptr = data->rbuffer;
5235         for( i = 0; i < 3; i++ ) {
5236                 int j;
5237                 if ( !SSID_rid.ssids[i].len ) break;
5238                 for( j = 0; j < 32 &&
5239                              j < SSID_rid.ssids[i].len &&
5240                              SSID_rid.ssids[i].ssid[j]; j++ ) {
5241                         *ptr++ = SSID_rid.ssids[i].ssid[j];
5242                 }
5243                 *ptr++ = '\n';
5244         }
5245         *ptr = '\0';
5246         data->readlen = strlen( data->rbuffer );
5247         return 0;
5248 }
5249
5250 static int proc_APList_open( struct inode *inode, struct file *file ) {
5251         struct proc_data *data;
5252         struct proc_dir_entry *dp = PDE(inode);
5253         struct net_device *dev = dp->data;
5254         struct airo_info *ai = dev->priv;
5255         int i;
5256         char *ptr;
5257         APListRid APList_rid;
5258
5259         if ((file->private_data = kmalloc(sizeof(struct proc_data ), GFP_KERNEL)) == NULL)
5260                 return -ENOMEM;
5261         memset(file->private_data, 0, sizeof(struct proc_data));
5262         data = (struct proc_data *)file->private_data;
5263         if ((data->rbuffer = kmalloc( 104, GFP_KERNEL )) == NULL) {
5264                 kfree (file->private_data);
5265                 return -ENOMEM;
5266         }
5267         data->writelen = 0;
5268         data->maxwritelen = 4*6*3;
5269         if ((data->wbuffer = kmalloc( data->maxwritelen, GFP_KERNEL )) == NULL) {
5270                 kfree (data->rbuffer);
5271                 kfree (file->private_data);
5272                 return -ENOMEM;
5273         }
5274         memset( data->wbuffer, 0, data->maxwritelen );
5275         data->on_close = proc_APList_on_close;
5276
5277         readAPListRid(ai, &APList_rid);
5278         ptr = data->rbuffer;
5279         for( i = 0; i < 4; i++ ) {
5280 // We end when we find a zero MAC
5281                 if ( !*(int*)APList_rid.ap[i] &&
5282                      !*(int*)&APList_rid.ap[i][2]) break;
5283                 ptr += sprintf(ptr, "%02x:%02x:%02x:%02x:%02x:%02x\n",
5284                                (int)APList_rid.ap[i][0],
5285                                (int)APList_rid.ap[i][1],
5286                                (int)APList_rid.ap[i][2],
5287                                (int)APList_rid.ap[i][3],
5288                                (int)APList_rid.ap[i][4],
5289                                (int)APList_rid.ap[i][5]);
5290         }
5291         if (i==0) ptr += sprintf(ptr, "Not using specific APs\n");
5292
5293         *ptr = '\0';
5294         data->readlen = strlen( data->rbuffer );
5295         return 0;
5296 }
5297
5298 static int proc_BSSList_open( struct inode *inode, struct file *file ) {
5299         struct proc_data *data;
5300         struct proc_dir_entry *dp = PDE(inode);
5301         struct net_device *dev = dp->data;
5302         struct airo_info *ai = dev->priv;
5303         char *ptr;
5304         BSSListRid BSSList_rid;
5305         int rc;
5306         /* If doLoseSync is not 1, we won't do a Lose Sync */
5307         int doLoseSync = -1;
5308
5309         if ((file->private_data = kmalloc(sizeof(struct proc_data ), GFP_KERNEL)) == NULL)
5310                 return -ENOMEM;
5311         memset(file->private_data, 0, sizeof(struct proc_data));
5312         data = (struct proc_data *)file->private_data;
5313         if ((data->rbuffer = kmalloc( 1024, GFP_KERNEL )) == NULL) {
5314                 kfree (file->private_data);
5315                 return -ENOMEM;
5316         }
5317         data->writelen = 0;
5318         data->maxwritelen = 0;
5319         data->wbuffer = NULL;
5320         data->on_close = NULL;
5321
5322         if (file->f_mode & FMODE_WRITE) {
5323                 if (!(file->f_mode & FMODE_READ)) {
5324                         Cmd cmd;
5325                         Resp rsp;
5326
5327                         if (ai->flags & FLAG_RADIO_MASK) return -ENETDOWN;
5328                         memset(&cmd, 0, sizeof(cmd));
5329                         cmd.cmd=CMD_LISTBSS;
5330                         if (down_interruptible(&ai->sem))
5331                                 return -ERESTARTSYS;
5332                         issuecommand(ai, &cmd, &rsp);
5333                         up(&ai->sem);
5334                         data->readlen = 0;
5335                         return 0;
5336                 }
5337                 doLoseSync = 1;
5338         }
5339         ptr = data->rbuffer;
5340         /* There is a race condition here if there are concurrent opens.
5341            Since it is a rare condition, we'll just live with it, otherwise
5342            we have to add a spin lock... */
5343         rc = readBSSListRid(ai, doLoseSync, &BSSList_rid);
5344         while(rc == 0 && BSSList_rid.index != 0xffff) {
5345                 ptr += sprintf(ptr, "%02x:%02x:%02x:%02x:%02x:%02x %*s rssi = %d",
5346                                 (int)BSSList_rid.bssid[0],
5347                                 (int)BSSList_rid.bssid[1],
5348                                 (int)BSSList_rid.bssid[2],
5349                                 (int)BSSList_rid.bssid[3],
5350                                 (int)BSSList_rid.bssid[4],
5351                                 (int)BSSList_rid.bssid[5],
5352                                 (int)BSSList_rid.ssidLen,
5353                                 BSSList_rid.ssid,
5354                                 (int)BSSList_rid.rssi);
5355                 ptr += sprintf(ptr, " channel = %d %s %s %s %s\n",
5356                                 (int)BSSList_rid.dsChannel,
5357                                 BSSList_rid.cap & CAP_ESS ? "ESS" : "",
5358                                 BSSList_rid.cap & CAP_IBSS ? "adhoc" : "",
5359                                 BSSList_rid.cap & CAP_PRIVACY ? "wep" : "",
5360                                 BSSList_rid.cap & CAP_SHORTHDR ? "shorthdr" : "");
5361                 rc = readBSSListRid(ai, 0, &BSSList_rid);
5362         }
5363         *ptr = '\0';
5364         data->readlen = strlen( data->rbuffer );
5365         return 0;
5366 }
5367
5368 static int proc_close( struct inode *inode, struct file *file )
5369 {
5370         struct proc_data *data = (struct proc_data *)file->private_data;
5371         if ( data->on_close != NULL ) data->on_close( inode, file );
5372         if ( data->rbuffer ) kfree( data->rbuffer );
5373         if ( data->wbuffer ) kfree( data->wbuffer );
5374         kfree( data );
5375         return 0;
5376 }
5377
5378 static struct net_device_list {
5379         struct net_device *dev;
5380         struct net_device_list *next;
5381 } *airo_devices;
5382
5383 /* Since the card doesn't automatically switch to the right WEP mode,
5384    we will make it do it.  If the card isn't associated, every secs we
5385    will switch WEP modes to see if that will help.  If the card is
5386    associated we will check every minute to see if anything has
5387    changed. */
5388 static void timer_func( struct net_device *dev ) {
5389         struct airo_info *apriv = dev->priv;
5390         Resp rsp;
5391
5392 /* We don't have a link so try changing the authtype */
5393         readConfigRid(apriv, 0);
5394         disable_MAC(apriv, 0);
5395         switch(apriv->config.authType) {
5396                 case AUTH_ENCRYPT:
5397 /* So drop to OPEN */
5398                         apriv->config.authType = AUTH_OPEN;
5399                         break;
5400                 case AUTH_SHAREDKEY:
5401                         if (apriv->keyindex < auto_wep) {
5402                                 set_wep_key(apriv, apriv->keyindex, NULL, 0, 0, 0);
5403                                 apriv->config.authType = AUTH_SHAREDKEY;
5404                                 apriv->keyindex++;
5405                         } else {
5406                                 /* Drop to ENCRYPT */
5407                                 apriv->keyindex = 0;
5408                                 set_wep_key(apriv, apriv->defindex, NULL, 0, 0, 0);
5409                                 apriv->config.authType = AUTH_ENCRYPT;
5410                         }
5411                         break;
5412                 default:  /* We'll escalate to SHAREDKEY */
5413                         apriv->config.authType = AUTH_SHAREDKEY;
5414         }
5415         set_bit (FLAG_COMMIT, &apriv->flags);
5416         writeConfigRid(apriv, 0);
5417         enable_MAC(apriv, &rsp, 0);
5418         up(&apriv->sem);
5419
5420 /* Schedule check to see if the change worked */
5421         clear_bit(JOB_AUTOWEP, &apriv->flags);
5422         apriv->expires = RUN_AT(HZ*3);
5423 }
5424
5425 static int add_airo_dev( struct net_device *dev ) {
5426         struct net_device_list *node = kmalloc( sizeof( *node ), GFP_KERNEL );
5427         if ( !node )
5428                 return -ENOMEM;
5429
5430         node->dev = dev;
5431         node->next = airo_devices;
5432         airo_devices = node;
5433
5434         return 0;
5435 }
5436
5437 static void del_airo_dev( struct net_device *dev ) {
5438         struct net_device_list **p = &airo_devices;
5439         while( *p && ( (*p)->dev != dev ) )
5440                 p = &(*p)->next;
5441         if ( *p && (*p)->dev == dev )
5442                 *p = (*p)->next;
5443 }
5444
5445 #ifdef CONFIG_PCI
5446 static int __devinit airo_pci_probe(struct pci_dev *pdev,
5447                                     const struct pci_device_id *pent)
5448 {
5449         struct net_device *dev;
5450
5451         if (pci_enable_device(pdev))
5452                 return -ENODEV;
5453         pci_set_master(pdev);
5454
5455         if (pdev->device == 0x5000 || pdev->device == 0xa504)
5456                         dev = _init_airo_card(pdev->irq, pdev->resource[0].start, 0, pdev, &pdev->dev);
5457         else
5458                         dev = _init_airo_card(pdev->irq, pdev->resource[2].start, 0, pdev, &pdev->dev);
5459         if (!dev)
5460                 return -ENODEV;
5461
5462         pci_set_drvdata(pdev, dev);
5463         return 0;
5464 }
5465
5466 static void __devexit airo_pci_remove(struct pci_dev *pdev)
5467 {
5468 }
5469
5470 static int airo_pci_suspend(struct pci_dev *pdev, u32 state)
5471 {
5472         struct net_device *dev = pci_get_drvdata(pdev);
5473         struct airo_info *ai = dev->priv;
5474         Cmd cmd;
5475         Resp rsp;
5476
5477         if ((ai->APList == NULL) &&
5478                 (ai->APList = kmalloc(sizeof(APListRid), GFP_KERNEL)) == NULL)
5479                 return -ENOMEM;
5480         if ((ai->SSID == NULL) &&
5481                 (ai->SSID = kmalloc(sizeof(SsidRid), GFP_KERNEL)) == NULL)
5482                 return -ENOMEM;
5483         readAPListRid(ai, ai->APList);
5484         readSsidRid(ai, ai->SSID);
5485         memset(&cmd, 0, sizeof(cmd));
5486         /* the lock will be released at the end of the resume callback */
5487         if (down_interruptible(&ai->sem))
5488                 return -EAGAIN;
5489         disable_MAC(ai, 0);
5490         netif_device_detach(dev);
5491         ai->power = state;
5492         cmd.cmd=HOSTSLEEP;
5493         issuecommand(ai, &cmd, &rsp);
5494
5495         pci_enable_wake(pdev, state, 1);
5496         pci_save_state(pdev);
5497         return pci_set_power_state(pdev, state);
5498 }
5499
5500 static int airo_pci_resume(struct pci_dev *pdev)
5501 {
5502         struct net_device *dev = pci_get_drvdata(pdev);
5503         struct airo_info *ai = dev->priv;
5504         Resp rsp;
5505
5506         pci_set_power_state(pdev, 0);
5507         pci_restore_state(pdev);
5508         pci_enable_wake(pdev, ai->power, 0);
5509
5510         if (ai->power > 1) {
5511                 reset_card(dev, 0);
5512                 mpi_init_descriptors(ai);
5513                 setup_card(ai, dev->dev_addr, 0);
5514                 clear_bit(FLAG_RADIO_OFF, &ai->flags);
5515                 clear_bit(FLAG_PENDING_XMIT, &ai->flags);
5516         } else {
5517                 OUT4500(ai, EVACK, EV_AWAKEN);
5518                 OUT4500(ai, EVACK, EV_AWAKEN);
5519                 schedule_timeout(HZ/10);
5520         }
5521
5522         set_bit (FLAG_COMMIT, &ai->flags);
5523         disable_MAC(ai, 0);
5524         schedule_timeout (HZ/5);
5525         if (ai->SSID) {
5526                 writeSsidRid(ai, ai->SSID, 0);
5527                 kfree(ai->SSID);
5528                 ai->SSID = NULL;
5529         }
5530         if (ai->APList) {
5531                 writeAPListRid(ai, ai->APList, 0);
5532                 kfree(ai->APList);
5533                 ai->APList = NULL;
5534         }
5535         writeConfigRid(ai, 0);
5536         enable_MAC(ai, &rsp, 0);
5537         ai->power = 0;
5538         netif_device_attach(dev);
5539         netif_wake_queue(dev);
5540         enable_interrupts(ai);
5541         up(&ai->sem);
5542         return 0;
5543 }
5544 #endif
5545
5546 static int __init airo_init_module( void )
5547 {
5548         int i, have_isa_dev = 0;
5549
5550         airo_entry = create_proc_entry("aironet",
5551                                        S_IFDIR | airo_perm,
5552                                        proc_root_driver);
5553         airo_entry->uid = proc_uid;
5554         airo_entry->gid = proc_gid;
5555
5556         for( i = 0; i < 4 && io[i] && irq[i]; i++ ) {
5557                 printk( KERN_INFO
5558                         "airo:  Trying to configure ISA adapter at irq=%d io=0x%x\n",
5559                         irq[i], io[i] );
5560                 if (init_airo_card( irq[i], io[i], 0, NULL ))
5561                         have_isa_dev = 1;
5562         }
5563
5564 #ifdef CONFIG_PCI
5565         printk( KERN_INFO "airo:  Probing for PCI adapters\n" );
5566         pci_register_driver(&airo_driver);
5567         printk( KERN_INFO "airo:  Finished probing for PCI adapters\n" );
5568 #endif
5569
5570         /* Always exit with success, as we are a library module
5571          * as well as a driver module
5572          */
5573         return 0;
5574 }
5575
5576 static void __exit airo_cleanup_module( void )
5577 {
5578         while( airo_devices ) {
5579                 printk( KERN_INFO "airo: Unregistering %s\n", airo_devices->dev->name );
5580                 stop_airo_card( airo_devices->dev, 1 );
5581         }
5582 #ifdef CONFIG_PCI
5583         pci_unregister_driver(&airo_driver);
5584 #endif
5585         remove_proc_entry("aironet", proc_root_driver);
5586 }
5587
5588 #ifdef WIRELESS_EXT
5589 /*
5590  * Initial Wireless Extension code for Aironet driver by :
5591  *      Jean Tourrilhes <jt@hpl.hp.com> - HPL - 17 November 00
5592  * Conversion to new driver API by :
5593  *      Jean Tourrilhes <jt@hpl.hp.com> - HPL - 26 March 02
5594  * Javier also did a good amount of work here, adding some new extensions
5595  * and fixing my code. Let's just say that without him this code just
5596  * would not work at all... - Jean II
5597  */
5598
5599 static int airo_get_quality (StatusRid *status_rid, CapabilityRid *cap_rid)
5600 {
5601         int quality = 0;
5602
5603         if ((status_rid->mode & 0x3f) == 0x3f && (cap_rid->hardCap & 8)) {
5604                 if (memcmp(cap_rid->prodName, "350", 3))
5605                         if (status_rid->signalQuality > 0x20)
5606                                 quality = 0;
5607                         else
5608                                 quality = 0x20 - status_rid->signalQuality;
5609                 else
5610                         if (status_rid->signalQuality > 0xb0)
5611                                 quality = 0;
5612                         else if (status_rid->signalQuality < 0x10)
5613                                 quality = 0xa0;
5614                         else
5615                                 quality = 0xb0 - status_rid->signalQuality;
5616         }
5617         return quality;
5618 }
5619
5620 #define airo_get_max_quality(cap_rid) (memcmp((cap_rid)->prodName, "350", 3) ? 0x20 : 0xa0)
5621 #define airo_get_avg_quality(cap_rid) (memcmp((cap_rid)->prodName, "350", 3) ? 0x10 : 0x50);
5622
5623 /*------------------------------------------------------------------*/
5624 /*
5625  * Wireless Handler : get protocol name
5626  */
5627 static int airo_get_name(struct net_device *dev,
5628                          struct iw_request_info *info,
5629                          char *cwrq,
5630                          char *extra)
5631 {
5632         strcpy(cwrq, "IEEE 802.11-DS");
5633         return 0;
5634 }
5635
5636 /*------------------------------------------------------------------*/
5637 /*
5638  * Wireless Handler : set frequency
5639  */
5640 static int airo_set_freq(struct net_device *dev,
5641                          struct iw_request_info *info,
5642                          struct iw_freq *fwrq,
5643                          char *extra)
5644 {
5645         struct airo_info *local = dev->priv;
5646         int rc = -EINPROGRESS;          /* Call commit handler */
5647
5648         /* If setting by frequency, convert to a channel */
5649         if((fwrq->e == 1) &&
5650            (fwrq->m >= (int) 2.412e8) &&
5651            (fwrq->m <= (int) 2.487e8)) {
5652                 int f = fwrq->m / 100000;
5653                 int c = 0;
5654                 while((c < 14) && (f != frequency_list[c]))
5655                         c++;
5656                 /* Hack to fall through... */
5657                 fwrq->e = 0;
5658                 fwrq->m = c + 1;
5659         }
5660         /* Setting by channel number */
5661         if((fwrq->m > 1000) || (fwrq->e > 0))
5662                 rc = -EOPNOTSUPP;
5663         else {
5664                 int channel = fwrq->m;
5665                 /* We should do a better check than that,
5666                  * based on the card capability !!! */
5667                 if((channel < 1) || (channel > 16)) {
5668                         printk(KERN_DEBUG "%s: New channel value of %d is invalid!\n", dev->name, fwrq->m);
5669                         rc = -EINVAL;
5670                 } else {
5671                         readConfigRid(local, 1);
5672                         /* Yes ! We can set it !!! */
5673                         local->config.channelSet = (u16)(channel - 1);
5674                         set_bit (FLAG_COMMIT, &local->flags);
5675                 }
5676         }
5677         return rc;
5678 }
5679
5680 /*------------------------------------------------------------------*/
5681 /*
5682  * Wireless Handler : get frequency
5683  */
5684 static int airo_get_freq(struct net_device *dev,
5685                          struct iw_request_info *info,
5686                          struct iw_freq *fwrq,
5687                          char *extra)
5688 {
5689         struct airo_info *local = dev->priv;
5690         StatusRid status_rid;           /* Card status info */
5691
5692         readConfigRid(local, 1);
5693         if ((local->config.opmode & 0xFF) == MODE_STA_ESS)
5694                 status_rid.channel = local->config.channelSet;
5695         else
5696                 readStatusRid(local, &status_rid, 1);
5697
5698 #ifdef WEXT_USECHANNELS
5699         fwrq->m = ((int)status_rid.channel) + 1;
5700         fwrq->e = 0;
5701 #else
5702         {
5703                 int f = (int)status_rid.channel;
5704                 fwrq->m = frequency_list[f] * 100000;
5705                 fwrq->e = 1;
5706         }
5707 #endif
5708
5709         return 0;
5710 }
5711
5712 /*------------------------------------------------------------------*/
5713 /*
5714  * Wireless Handler : set ESSID
5715  */
5716 static int airo_set_essid(struct net_device *dev,
5717                           struct iw_request_info *info,
5718                           struct iw_point *dwrq,
5719                           char *extra)
5720 {
5721         struct airo_info *local = dev->priv;
5722         Resp rsp;
5723         SsidRid SSID_rid;               /* SSIDs */
5724
5725         /* Reload the list of current SSID */
5726         readSsidRid(local, &SSID_rid);
5727
5728         /* Check if we asked for `any' */
5729         if(dwrq->flags == 0) {
5730                 /* Just send an empty SSID list */
5731                 memset(&SSID_rid, 0, sizeof(SSID_rid));
5732         } else {
5733                 int     index = (dwrq->flags & IW_ENCODE_INDEX) - 1;
5734
5735                 /* Check the size of the string */
5736                 if(dwrq->length > IW_ESSID_MAX_SIZE+1) {
5737                         return -E2BIG ;
5738                 }
5739                 /* Check if index is valid */
5740                 if((index < 0) || (index >= 4)) {
5741                         return -EINVAL;
5742                 }
5743
5744                 /* Set the SSID */
5745                 memset(SSID_rid.ssids[index].ssid, 0,
5746                        sizeof(SSID_rid.ssids[index].ssid));
5747                 memcpy(SSID_rid.ssids[index].ssid, extra, dwrq->length);
5748                 SSID_rid.ssids[index].len = dwrq->length - 1;
5749         }
5750         SSID_rid.len = sizeof(SSID_rid);
5751         /* Write it to the card */
5752         disable_MAC(local, 1);
5753         writeSsidRid(local, &SSID_rid, 1);
5754         enable_MAC(local, &rsp, 1);
5755
5756         return 0;
5757 }
5758
5759 /*------------------------------------------------------------------*/
5760 /*
5761  * Wireless Handler : get ESSID
5762  */
5763 static int airo_get_essid(struct net_device *dev,
5764                           struct iw_request_info *info,
5765                           struct iw_point *dwrq,
5766                           char *extra)
5767 {
5768         struct airo_info *local = dev->priv;
5769         StatusRid status_rid;           /* Card status info */
5770
5771         readStatusRid(local, &status_rid, 1);
5772
5773         /* Note : if dwrq->flags != 0, we should
5774          * get the relevant SSID from the SSID list... */
5775
5776         /* Get the current SSID */
5777         memcpy(extra, status_rid.SSID, status_rid.SSIDlen);
5778         extra[status_rid.SSIDlen] = '\0';
5779         /* If none, we may want to get the one that was set */
5780
5781         /* Push it out ! */
5782         dwrq->length = status_rid.SSIDlen + 1;
5783         dwrq->flags = 1; /* active */
5784
5785         return 0;
5786 }
5787
5788 /*------------------------------------------------------------------*/
5789 /*
5790  * Wireless Handler : set AP address
5791  */
5792 static int airo_set_wap(struct net_device *dev,
5793                         struct iw_request_info *info,
5794                         struct sockaddr *awrq,
5795                         char *extra)
5796 {
5797         struct airo_info *local = dev->priv;
5798         Cmd cmd;
5799         Resp rsp;
5800         APListRid APList_rid;
5801         static const unsigned char bcast[ETH_ALEN] = { 255, 255, 255, 255, 255, 255 };
5802
5803         if (awrq->sa_family != ARPHRD_ETHER)
5804                 return -EINVAL;
5805         else if (!memcmp(bcast, awrq->sa_data, ETH_ALEN)) {
5806                 memset(&cmd, 0, sizeof(cmd));
5807                 cmd.cmd=CMD_LOSE_SYNC;
5808                 if (down_interruptible(&local->sem))
5809                         return -ERESTARTSYS;
5810                 issuecommand(local, &cmd, &rsp);
5811                 up(&local->sem);
5812         } else {
5813                 memset(&APList_rid, 0, sizeof(APList_rid));
5814                 APList_rid.len = sizeof(APList_rid);
5815                 memcpy(APList_rid.ap[0], awrq->sa_data, ETH_ALEN);
5816                 disable_MAC(local, 1);
5817                 writeAPListRid(local, &APList_rid, 1);
5818                 enable_MAC(local, &rsp, 1);
5819         }
5820         return 0;
5821 }
5822
5823 /*------------------------------------------------------------------*/
5824 /*
5825  * Wireless Handler : get AP address
5826  */
5827 static int airo_get_wap(struct net_device *dev,
5828                         struct iw_request_info *info,
5829                         struct sockaddr *awrq,
5830                         char *extra)
5831 {
5832         struct airo_info *local = dev->priv;
5833         StatusRid status_rid;           /* Card status info */
5834
5835         readStatusRid(local, &status_rid, 1);
5836
5837         /* Tentative. This seems to work, wow, I'm lucky !!! */
5838         memcpy(awrq->sa_data, status_rid.bssid[0], ETH_ALEN);
5839         awrq->sa_family = ARPHRD_ETHER;
5840
5841         return 0;
5842 }
5843
5844 /*------------------------------------------------------------------*/
5845 /*
5846  * Wireless Handler : set Nickname
5847  */
5848 static int airo_set_nick(struct net_device *dev,
5849                          struct iw_request_info *info,
5850                          struct iw_point *dwrq,
5851                          char *extra)
5852 {
5853         struct airo_info *local = dev->priv;
5854
5855         /* Check the size of the string */
5856         if(dwrq->length > 16 + 1) {
5857                 return -E2BIG;
5858         }
5859         readConfigRid(local, 1);
5860         memset(local->config.nodeName, 0, sizeof(local->config.nodeName));
5861         memcpy(local->config.nodeName, extra, dwrq->length);
5862         set_bit (FLAG_COMMIT, &local->flags);
5863
5864         return -EINPROGRESS;            /* Call commit handler */
5865 }
5866
5867 /*------------------------------------------------------------------*/
5868 /*
5869  * Wireless Handler : get Nickname
5870  */
5871 static int airo_get_nick(struct net_device *dev,
5872                          struct iw_request_info *info,
5873                          struct iw_point *dwrq,
5874                          char *extra)
5875 {
5876         struct airo_info *local = dev->priv;
5877
5878         readConfigRid(local, 1);
5879         strncpy(extra, local->config.nodeName, 16);
5880         extra[16] = '\0';
5881         dwrq->length = strlen(extra) + 1;
5882
5883         return 0;
5884 }
5885
5886 /*------------------------------------------------------------------*/
5887 /*
5888  * Wireless Handler : set Bit-Rate
5889  */
5890 static int airo_set_rate(struct net_device *dev,
5891                          struct iw_request_info *info,
5892                          struct iw_param *vwrq,
5893                          char *extra)
5894 {
5895         struct airo_info *local = dev->priv;
5896         CapabilityRid cap_rid;          /* Card capability info */
5897         u8      brate = 0;
5898         int     i;
5899
5900         /* First : get a valid bit rate value */
5901         readCapabilityRid(local, &cap_rid, 1);
5902
5903         /* Which type of value ? */
5904         if((vwrq->value < 8) && (vwrq->value >= 0)) {
5905                 /* Setting by rate index */
5906                 /* Find value in the magic rate table */
5907                 brate = cap_rid.supportedRates[vwrq->value];
5908         } else {
5909                 /* Setting by frequency value */
5910                 u8      normvalue = (u8) (vwrq->value/500000);
5911
5912                 /* Check if rate is valid */
5913                 for(i = 0 ; i < 8 ; i++) {
5914                         if(normvalue == cap_rid.supportedRates[i]) {
5915                                 brate = normvalue;
5916                                 break;
5917                         }
5918                 }
5919         }
5920         /* -1 designed the max rate (mostly auto mode) */
5921         if(vwrq->value == -1) {
5922                 /* Get the highest available rate */
5923                 for(i = 0 ; i < 8 ; i++) {
5924                         if(cap_rid.supportedRates[i] == 0)
5925                                 break;
5926                 }
5927                 if(i != 0)
5928                         brate = cap_rid.supportedRates[i - 1];
5929         }
5930         /* Check that it is valid */
5931         if(brate == 0) {
5932                 return -EINVAL;
5933         }
5934
5935         readConfigRid(local, 1);
5936         /* Now, check if we want a fixed or auto value */
5937         if(vwrq->fixed == 0) {
5938                 /* Fill all the rates up to this max rate */
5939                 memset(local->config.rates, 0, 8);
5940                 for(i = 0 ; i < 8 ; i++) {
5941                         local->config.rates[i] = cap_rid.supportedRates[i];
5942                         if(local->config.rates[i] == brate)
5943                                 break;
5944                 }
5945         } else {
5946                 /* Fixed mode */
5947                 /* One rate, fixed */
5948                 memset(local->config.rates, 0, 8);
5949                 local->config.rates[0] = brate;
5950         }
5951         set_bit (FLAG_COMMIT, &local->flags);
5952
5953         return -EINPROGRESS;            /* Call commit handler */
5954 }
5955
5956 /*------------------------------------------------------------------*/
5957 /*
5958  * Wireless Handler : get Bit-Rate
5959  */
5960 static int airo_get_rate(struct net_device *dev,
5961                          struct iw_request_info *info,
5962                          struct iw_param *vwrq,
5963                          char *extra)
5964 {
5965         struct airo_info *local = dev->priv;
5966         StatusRid status_rid;           /* Card status info */
5967
5968         readStatusRid(local, &status_rid, 1);
5969
5970         vwrq->value = status_rid.currentXmitRate * 500000;
5971         /* If more than one rate, set auto */
5972         readConfigRid(local, 1);
5973         vwrq->fixed = (local->config.rates[1] == 0);
5974
5975         return 0;
5976 }
5977
5978 /*------------------------------------------------------------------*/
5979 /*
5980  * Wireless Handler : set RTS threshold
5981  */
5982 static int airo_set_rts(struct net_device *dev,
5983                         struct iw_request_info *info,
5984                         struct iw_param *vwrq,
5985                         char *extra)
5986 {
5987         struct airo_info *local = dev->priv;
5988         int rthr = vwrq->value;
5989
5990         if(vwrq->disabled)
5991                 rthr = 2312;
5992         if((rthr < 0) || (rthr > 2312)) {
5993                 return -EINVAL;
5994         }
5995         readConfigRid(local, 1);
5996         local->config.rtsThres = rthr;
5997         set_bit (FLAG_COMMIT, &local->flags);
5998
5999         return -EINPROGRESS;            /* Call commit handler */
6000 }
6001
6002 /*------------------------------------------------------------------*/
6003 /*
6004  * Wireless Handler : get RTS threshold
6005  */
6006 static int airo_get_rts(struct net_device *dev,
6007                         struct iw_request_info *info,
6008                         struct iw_param *vwrq,
6009                         char *extra)
6010 {
6011         struct airo_info *local = dev->priv;
6012
6013         readConfigRid(local, 1);
6014         vwrq->value = local->config.rtsThres;
6015         vwrq->disabled = (vwrq->value >= 2312);
6016         vwrq->fixed = 1;
6017
6018         return 0;
6019 }
6020
6021 /*------------------------------------------------------------------*/
6022 /*
6023  * Wireless Handler : set Fragmentation threshold
6024  */
6025 static int airo_set_frag(struct net_device *dev,
6026                          struct iw_request_info *info,
6027                          struct iw_param *vwrq,
6028                          char *extra)
6029 {
6030         struct airo_info *local = dev->priv;
6031         int fthr = vwrq->value;
6032
6033         if(vwrq->disabled)
6034                 fthr = 2312;
6035         if((fthr < 256) || (fthr > 2312)) {
6036                 return -EINVAL;
6037         }
6038         fthr &= ~0x1;   /* Get an even value - is it really needed ??? */
6039         readConfigRid(local, 1);
6040         local->config.fragThresh = (u16)fthr;
6041         set_bit (FLAG_COMMIT, &local->flags);
6042
6043         return -EINPROGRESS;            /* Call commit handler */
6044 }
6045
6046 /*------------------------------------------------------------------*/
6047 /*
6048  * Wireless Handler : get Fragmentation threshold
6049  */
6050 static int airo_get_frag(struct net_device *dev,
6051                          struct iw_request_info *info,
6052                          struct iw_param *vwrq,
6053                          char *extra)
6054 {
6055         struct airo_info *local = dev->priv;
6056
6057         readConfigRid(local, 1);
6058         vwrq->value = local->config.fragThresh;
6059         vwrq->disabled = (vwrq->value >= 2312);
6060         vwrq->fixed = 1;
6061
6062         return 0;
6063 }
6064
6065 /*------------------------------------------------------------------*/
6066 /*
6067  * Wireless Handler : set Mode of Operation
6068  */
6069 static int airo_set_mode(struct net_device *dev,
6070                          struct iw_request_info *info,
6071                          __u32 *uwrq,
6072                          char *extra)
6073 {
6074         struct airo_info *local = dev->priv;
6075         int reset = 0;
6076
6077         readConfigRid(local, 1);
6078         if ((local->config.rmode & 0xff) >= RXMODE_RFMON)
6079                 reset = 1;
6080
6081         switch(*uwrq) {
6082                 case IW_MODE_ADHOC:
6083                         local->config.opmode &= 0xFF00;
6084                         local->config.opmode |= MODE_STA_IBSS;
6085                         local->config.rmode &= 0xfe00;
6086                         local->config.scanMode = SCANMODE_ACTIVE;
6087                         clear_bit (FLAG_802_11, &local->flags);
6088                         break;
6089                 case IW_MODE_INFRA:
6090                         local->config.opmode &= 0xFF00;
6091                         local->config.opmode |= MODE_STA_ESS;
6092                         local->config.rmode &= 0xfe00;
6093                         local->config.scanMode = SCANMODE_ACTIVE;
6094                         clear_bit (FLAG_802_11, &local->flags);
6095                         break;
6096                 case IW_MODE_MASTER:
6097                         local->config.opmode &= 0xFF00;
6098                         local->config.opmode |= MODE_AP;
6099                         local->config.rmode &= 0xfe00;
6100                         local->config.scanMode = SCANMODE_ACTIVE;
6101                         clear_bit (FLAG_802_11, &local->flags);
6102                         break;
6103                 case IW_MODE_REPEAT:
6104                         local->config.opmode &= 0xFF00;
6105                         local->config.opmode |= MODE_AP_RPTR;
6106                         local->config.rmode &= 0xfe00;
6107                         local->config.scanMode = SCANMODE_ACTIVE;
6108                         clear_bit (FLAG_802_11, &local->flags);
6109                         break;
6110                 case IW_MODE_MONITOR:
6111                         local->config.opmode &= 0xFF00;
6112                         local->config.opmode |= MODE_STA_ESS;
6113                         local->config.rmode &= 0xfe00;
6114                         local->config.rmode |= RXMODE_RFMON | RXMODE_DISABLE_802_3_HEADER;
6115                         local->config.scanMode = SCANMODE_PASSIVE;
6116                         set_bit (FLAG_802_11, &local->flags);
6117                         break;
6118                 default:
6119                         return -EINVAL;
6120         }
6121         if (reset)
6122                 set_bit (FLAG_RESET, &local->flags);
6123         set_bit (FLAG_COMMIT, &local->flags);
6124
6125         return -EINPROGRESS;            /* Call commit handler */
6126 }
6127
6128 /*------------------------------------------------------------------*/
6129 /*
6130  * Wireless Handler : get Mode of Operation
6131  */
6132 static int airo_get_mode(struct net_device *dev,
6133                          struct iw_request_info *info,
6134                          __u32 *uwrq,
6135                          char *extra)
6136 {
6137         struct airo_info *local = dev->priv;
6138
6139         readConfigRid(local, 1);
6140         /* If not managed, assume it's ad-hoc */
6141         switch (local->config.opmode & 0xFF) {
6142                 case MODE_STA_ESS:
6143                         *uwrq = IW_MODE_INFRA;
6144                         break;
6145                 case MODE_AP:
6146                         *uwrq = IW_MODE_MASTER;
6147                         break;
6148                 case MODE_AP_RPTR:
6149                         *uwrq = IW_MODE_REPEAT;
6150                         break;
6151                 default:
6152                         *uwrq = IW_MODE_ADHOC;
6153         }
6154
6155         return 0;
6156 }
6157
6158 /*------------------------------------------------------------------*/
6159 /*
6160  * Wireless Handler : set Encryption Key
6161  */
6162 static int airo_set_encode(struct net_device *dev,
6163                            struct iw_request_info *info,
6164                            struct iw_point *dwrq,
6165                            char *extra)
6166 {
6167         struct airo_info *local = dev->priv;
6168         CapabilityRid cap_rid;          /* Card capability info */
6169
6170         /* Is WEP supported ? */
6171         readCapabilityRid(local, &cap_rid, 1);
6172         /* Older firmware doesn't support this...
6173         if(!(cap_rid.softCap & 2)) {
6174                 return -EOPNOTSUPP;
6175         } */
6176         readConfigRid(local, 1);
6177
6178         /* Basic checking: do we have a key to set ?
6179          * Note : with the new API, it's impossible to get a NULL pointer.
6180          * Therefore, we need to check a key size == 0 instead.
6181          * New version of iwconfig properly set the IW_ENCODE_NOKEY flag
6182          * when no key is present (only change flags), but older versions
6183          * don't do it. - Jean II */
6184         if (dwrq->length > 0) {
6185                 wep_key_t key;
6186                 int index = (dwrq->flags & IW_ENCODE_INDEX) - 1;
6187                 int current_index = get_wep_key(local, 0xffff);
6188                 /* Check the size of the key */
6189                 if (dwrq->length > MAX_KEY_SIZE) {
6190                         return -EINVAL;
6191                 }
6192                 /* Check the index (none -> use current) */
6193                 if ((index < 0) || (index >= ((cap_rid.softCap & 0x80) ? 4:1)))
6194                         index = current_index;
6195                 /* Set the length */
6196                 if (dwrq->length > MIN_KEY_SIZE)
6197                         key.len = MAX_KEY_SIZE;
6198                 else
6199                         if (dwrq->length > 0)
6200                                 key.len = MIN_KEY_SIZE;
6201                         else
6202                                 /* Disable the key */
6203                                 key.len = 0;
6204                 /* Check if the key is not marked as invalid */
6205                 if(!(dwrq->flags & IW_ENCODE_NOKEY)) {
6206                         /* Cleanup */
6207                         memset(key.key, 0, MAX_KEY_SIZE);
6208                         /* Copy the key in the driver */
6209                         memcpy(key.key, extra, dwrq->length);
6210                         /* Send the key to the card */
6211                         set_wep_key(local, index, key.key, key.len, 1, 1);
6212                 }
6213                 /* WE specify that if a valid key is set, encryption
6214                  * should be enabled (user may turn it off later)
6215                  * This is also how "iwconfig ethX key on" works */
6216                 if((index == current_index) && (key.len > 0) &&
6217                    (local->config.authType == AUTH_OPEN)) {
6218                         local->config.authType = AUTH_ENCRYPT;
6219                         set_bit (FLAG_COMMIT, &local->flags);
6220                 }
6221         } else {
6222                 /* Do we want to just set the transmit key index ? */
6223                 int index = (dwrq->flags & IW_ENCODE_INDEX) - 1;
6224                 if ((index >= 0) && (index < ((cap_rid.softCap & 0x80)?4:1))) {
6225                         set_wep_key(local, index, NULL, 0, 1, 1);
6226                 } else
6227                         /* Don't complain if only change the mode */
6228                         if(!dwrq->flags & IW_ENCODE_MODE) {
6229                                 return -EINVAL;
6230                         }
6231         }
6232         /* Read the flags */
6233         if(dwrq->flags & IW_ENCODE_DISABLED)
6234                 local->config.authType = AUTH_OPEN;     // disable encryption
6235         if(dwrq->flags & IW_ENCODE_RESTRICTED)
6236                 local->config.authType = AUTH_SHAREDKEY;        // Only Both
6237         if(dwrq->flags & IW_ENCODE_OPEN)
6238                 local->config.authType = AUTH_ENCRYPT;  // Only Wep
6239         /* Commit the changes to flags if needed */
6240         if(dwrq->flags & IW_ENCODE_MODE)
6241                 set_bit (FLAG_COMMIT, &local->flags);
6242         return -EINPROGRESS;            /* Call commit handler */
6243 }
6244
6245 /*------------------------------------------------------------------*/
6246 /*
6247  * Wireless Handler : get Encryption Key
6248  */
6249 static int airo_get_encode(struct net_device *dev,
6250                            struct iw_request_info *info,
6251                            struct iw_point *dwrq,
6252                            char *extra)
6253 {
6254         struct airo_info *local = dev->priv;
6255         int index = (dwrq->flags & IW_ENCODE_INDEX) - 1;
6256         CapabilityRid cap_rid;          /* Card capability info */
6257
6258         /* Is it supported ? */
6259         readCapabilityRid(local, &cap_rid, 1);
6260         if(!(cap_rid.softCap & 2)) {
6261                 return -EOPNOTSUPP;
6262         }
6263         readConfigRid(local, 1);
6264         /* Check encryption mode */
6265         switch(local->config.authType)  {
6266                 case AUTH_ENCRYPT:
6267                         dwrq->flags = IW_ENCODE_OPEN;
6268                         break;
6269                 case AUTH_SHAREDKEY:
6270                         dwrq->flags = IW_ENCODE_RESTRICTED;
6271                         break;
6272                 default:
6273                 case AUTH_OPEN:
6274                         dwrq->flags = IW_ENCODE_DISABLED;
6275                         break;
6276         }
6277         /* We can't return the key, so set the proper flag and return zero */
6278         dwrq->flags |= IW_ENCODE_NOKEY;
6279         memset(extra, 0, 16);
6280
6281         /* Which key do we want ? -1 -> tx index */
6282         if ((index < 0) || (index >= ((cap_rid.softCap & 0x80) ? 4 : 1)))
6283                 index = get_wep_key(local, 0xffff);
6284         dwrq->flags |= index + 1;
6285         /* Copy the key to the user buffer */
6286         dwrq->length = get_wep_key(local, index);
6287         if (dwrq->length > 16) {
6288                 dwrq->length=0;
6289         }
6290         return 0;
6291 }
6292
6293 /*------------------------------------------------------------------*/
6294 /*
6295  * Wireless Handler : set Tx-Power
6296  */
6297 static int airo_set_txpow(struct net_device *dev,
6298                           struct iw_request_info *info,
6299                           struct iw_param *vwrq,
6300                           char *extra)
6301 {
6302         struct airo_info *local = dev->priv;
6303         CapabilityRid cap_rid;          /* Card capability info */
6304         int i;
6305         int rc = -EINVAL;
6306
6307         readCapabilityRid(local, &cap_rid, 1);
6308
6309         if (vwrq->disabled) {
6310                 set_bit (FLAG_RADIO_OFF, &local->flags);
6311                 set_bit (FLAG_COMMIT, &local->flags);
6312                 return -EINPROGRESS;            /* Call commit handler */
6313         }
6314         if (vwrq->flags != IW_TXPOW_MWATT) {
6315                 return -EINVAL;
6316         }
6317         clear_bit (FLAG_RADIO_OFF, &local->flags);
6318         for (i = 0; cap_rid.txPowerLevels[i] && (i < 8); i++)
6319                 if ((vwrq->value==cap_rid.txPowerLevels[i])) {
6320                         readConfigRid(local, 1);
6321                         local->config.txPower = vwrq->value;
6322                         set_bit (FLAG_COMMIT, &local->flags);
6323                         rc = -EINPROGRESS;      /* Call commit handler */
6324                         break;
6325                 }
6326         return rc;
6327 }
6328
6329 /*------------------------------------------------------------------*/
6330 /*
6331  * Wireless Handler : get Tx-Power
6332  */
6333 static int airo_get_txpow(struct net_device *dev,
6334                           struct iw_request_info *info,
6335                           struct iw_param *vwrq,
6336                           char *extra)
6337 {
6338         struct airo_info *local = dev->priv;
6339
6340         readConfigRid(local, 1);
6341         vwrq->value = local->config.txPower;
6342         vwrq->fixed = 1;        /* No power control */
6343         vwrq->disabled = test_bit(FLAG_RADIO_OFF, &local->flags);
6344         vwrq->flags = IW_TXPOW_MWATT;
6345
6346         return 0;
6347 }
6348
6349 /*------------------------------------------------------------------*/
6350 /*
6351  * Wireless Handler : set Retry limits
6352  */
6353 static int airo_set_retry(struct net_device *dev,
6354                           struct iw_request_info *info,
6355                           struct iw_param *vwrq,
6356                           char *extra)
6357 {
6358         struct airo_info *local = dev->priv;
6359         int rc = -EINVAL;
6360
6361         if(vwrq->disabled) {
6362                 return -EINVAL;
6363         }
6364         readConfigRid(local, 1);
6365         if(vwrq->flags & IW_RETRY_LIMIT) {
6366                 if(vwrq->flags & IW_RETRY_MAX)
6367                         local->config.longRetryLimit = vwrq->value;
6368                 else if (vwrq->flags & IW_RETRY_MIN)
6369                         local->config.shortRetryLimit = vwrq->value;
6370                 else {
6371                         /* No modifier : set both */
6372                         local->config.longRetryLimit = vwrq->value;
6373                         local->config.shortRetryLimit = vwrq->value;
6374                 }
6375                 set_bit (FLAG_COMMIT, &local->flags);
6376                 rc = -EINPROGRESS;              /* Call commit handler */
6377         }
6378         if(vwrq->flags & IW_RETRY_LIFETIME) {
6379                 local->config.txLifetime = vwrq->value / 1024;
6380                 set_bit (FLAG_COMMIT, &local->flags);
6381                 rc = -EINPROGRESS;              /* Call commit handler */
6382         }
6383         return rc;
6384 }
6385
6386 /*------------------------------------------------------------------*/
6387 /*
6388  * Wireless Handler : get Retry limits
6389  */
6390 static int airo_get_retry(struct net_device *dev,
6391                           struct iw_request_info *info,
6392                           struct iw_param *vwrq,
6393                           char *extra)
6394 {
6395         struct airo_info *local = dev->priv;
6396
6397         vwrq->disabled = 0;      /* Can't be disabled */
6398
6399         readConfigRid(local, 1);
6400         /* Note : by default, display the min retry number */
6401         if((vwrq->flags & IW_RETRY_TYPE) == IW_RETRY_LIFETIME) {
6402                 vwrq->flags = IW_RETRY_LIFETIME;
6403                 vwrq->value = (int)local->config.txLifetime * 1024;
6404         } else if((vwrq->flags & IW_RETRY_MAX)) {
6405                 vwrq->flags = IW_RETRY_LIMIT | IW_RETRY_MAX;
6406                 vwrq->value = (int)local->config.longRetryLimit;
6407         } else {
6408                 vwrq->flags = IW_RETRY_LIMIT;
6409                 vwrq->value = (int)local->config.shortRetryLimit;
6410                 if((int)local->config.shortRetryLimit != (int)local->config.longRetryLimit)
6411                         vwrq->flags |= IW_RETRY_MIN;
6412         }
6413
6414         return 0;
6415 }
6416
6417 /*------------------------------------------------------------------*/
6418 /*
6419  * Wireless Handler : get range info
6420  */
6421 static int airo_get_range(struct net_device *dev,
6422                           struct iw_request_info *info,
6423                           struct iw_point *dwrq,
6424                           char *extra)
6425 {
6426         struct airo_info *local = dev->priv;
6427         struct iw_range *range = (struct iw_range *) extra;
6428         CapabilityRid cap_rid;          /* Card capability info */
6429         int             i;
6430         int             k;
6431
6432         readCapabilityRid(local, &cap_rid, 1);
6433
6434         dwrq->length = sizeof(struct iw_range);
6435         memset(range, 0, sizeof(*range));
6436         range->min_nwid = 0x0000;
6437         range->max_nwid = 0x0000;
6438         range->num_channels = 14;
6439         /* Should be based on cap_rid.country to give only
6440          * what the current card support */
6441         k = 0;
6442         for(i = 0; i < 14; i++) {
6443                 range->freq[k].i = i + 1; /* List index */
6444                 range->freq[k].m = frequency_list[i] * 100000;
6445                 range->freq[k++].e = 1; /* Values in table in MHz -> * 10^5 * 10 */
6446         }
6447         range->num_frequency = k;
6448
6449         /* Hum... Should put the right values there */
6450         range->max_qual.qual = airo_get_max_quality(&cap_rid);
6451         range->max_qual.level = 0x100 - 120;    /* -120 dBm */
6452         range->max_qual.noise = 0;
6453         range->sensitivity = 65535;
6454
6455         for(i = 0 ; i < 8 ; i++) {
6456                 range->bitrate[i] = cap_rid.supportedRates[i] * 500000;
6457                 if(range->bitrate[i] == 0)
6458                         break;
6459         }
6460         range->num_bitrates = i;
6461
6462         /* Set an indication of the max TCP throughput
6463          * in bit/s that we can expect using this interface.
6464          * May be use for QoS stuff... Jean II */
6465         if(i > 2)
6466                 range->throughput = 5000 * 1000;
6467         else
6468                 range->throughput = 1500 * 1000;
6469
6470         range->min_rts = 0;
6471         range->max_rts = 2312;
6472         range->min_frag = 256;
6473         range->max_frag = 2312;
6474
6475         if(cap_rid.softCap & 2) {
6476                 // WEP: RC4 40 bits
6477                 range->encoding_size[0] = 5;
6478                 // RC4 ~128 bits
6479                 if (cap_rid.softCap & 0x100) {
6480                         range->encoding_size[1] = 13;
6481                         range->num_encoding_sizes = 2;
6482                 } else
6483                         range->num_encoding_sizes = 1;
6484                 range->max_encoding_tokens = (cap_rid.softCap & 0x80) ? 4 : 1;
6485         } else {
6486                 range->num_encoding_sizes = 0;
6487                 range->max_encoding_tokens = 0;
6488         }
6489         range->min_pmp = 0;
6490         range->max_pmp = 5000000;       /* 5 secs */
6491         range->min_pmt = 0;
6492         range->max_pmt = 65535 * 1024;  /* ??? */
6493         range->pmp_flags = IW_POWER_PERIOD;
6494         range->pmt_flags = IW_POWER_TIMEOUT;
6495         range->pm_capa = IW_POWER_PERIOD | IW_POWER_TIMEOUT | IW_POWER_ALL_R;
6496
6497         /* Transmit Power - values are in mW */
6498         for(i = 0 ; i < 8 ; i++) {
6499                 range->txpower[i] = cap_rid.txPowerLevels[i];
6500                 if(range->txpower[i] == 0)
6501                         break;
6502         }
6503         range->num_txpower = i;
6504         range->txpower_capa = IW_TXPOW_MWATT;
6505         range->we_version_source = 12;
6506         range->we_version_compiled = WIRELESS_EXT;
6507         range->retry_capa = IW_RETRY_LIMIT | IW_RETRY_LIFETIME;
6508         range->retry_flags = IW_RETRY_LIMIT;
6509         range->r_time_flags = IW_RETRY_LIFETIME;
6510         range->min_retry = 1;
6511         range->max_retry = 65535;
6512         range->min_r_time = 1024;
6513         range->max_r_time = 65535 * 1024;
6514         /* Experimental measurements - boundary 11/5.5 Mb/s */
6515         /* Note : with or without the (local->rssi), results
6516          * are somewhat different. - Jean II */
6517         range->avg_qual.qual = airo_get_avg_quality(&cap_rid);
6518         if (local->rssi)
6519                 range->avg_qual.level = 186;    /* -70 dBm */
6520         else
6521                 range->avg_qual.level = 176;    /* -80 dBm */
6522         range->avg_qual.noise = 0;
6523
6524         /* Event capability (kernel + driver) */
6525         range->event_capa[0] = (IW_EVENT_CAPA_K_0 |
6526                                 IW_EVENT_CAPA_MASK(SIOCGIWTHRSPY) |
6527                                 IW_EVENT_CAPA_MASK(SIOCGIWAP) |
6528                                 IW_EVENT_CAPA_MASK(SIOCGIWSCAN));
6529         range->event_capa[1] = IW_EVENT_CAPA_K_1;
6530         range->event_capa[4] = IW_EVENT_CAPA_MASK(IWEVTXDROP);
6531         return 0;
6532 }
6533
6534 /*------------------------------------------------------------------*/
6535 /*
6536  * Wireless Handler : set Power Management
6537  */
6538 static int airo_set_power(struct net_device *dev,
6539                           struct iw_request_info *info,
6540                           struct iw_param *vwrq,
6541                           char *extra)
6542 {
6543         struct airo_info *local = dev->priv;
6544
6545         readConfigRid(local, 1);
6546         if (vwrq->disabled) {
6547                 if ((local->config.rmode & 0xFF) >= RXMODE_RFMON) {
6548                         return -EINVAL;
6549                 }
6550                 local->config.powerSaveMode = POWERSAVE_CAM;
6551                 local->config.rmode &= 0xFF00;
6552                 local->config.rmode |= RXMODE_BC_MC_ADDR;
6553                 set_bit (FLAG_COMMIT, &local->flags);
6554                 return -EINPROGRESS;            /* Call commit handler */
6555         }
6556         if ((vwrq->flags & IW_POWER_TYPE) == IW_POWER_TIMEOUT) {
6557                 local->config.fastListenDelay = (vwrq->value + 500) / 1024;
6558                 local->config.powerSaveMode = POWERSAVE_PSPCAM;
6559                 set_bit (FLAG_COMMIT, &local->flags);
6560         } else if ((vwrq->flags & IW_POWER_TYPE) == IW_POWER_PERIOD) {
6561                 local->config.fastListenInterval = local->config.listenInterval = (vwrq->value + 500) / 1024;
6562                 local->config.powerSaveMode = POWERSAVE_PSPCAM;
6563                 set_bit (FLAG_COMMIT, &local->flags);
6564         }
6565         switch (vwrq->flags & IW_POWER_MODE) {
6566                 case IW_POWER_UNICAST_R:
6567                         if ((local->config.rmode & 0xFF) >= RXMODE_RFMON) {
6568                                 return -EINVAL;
6569                         }
6570                         local->config.rmode &= 0xFF00;
6571                         local->config.rmode |= RXMODE_ADDR;
6572                         set_bit (FLAG_COMMIT, &local->flags);
6573                         break;
6574                 case IW_POWER_ALL_R:
6575                         if ((local->config.rmode & 0xFF) >= RXMODE_RFMON) {
6576                                 return -EINVAL;
6577                         }
6578                         local->config.rmode &= 0xFF00;
6579                         local->config.rmode |= RXMODE_BC_MC_ADDR;
6580                         set_bit (FLAG_COMMIT, &local->flags);
6581                 case IW_POWER_ON:
6582                         break;
6583                 default:
6584                         return -EINVAL;
6585         }
6586         // Note : we may want to factor local->need_commit here
6587         // Note2 : may also want to factor RXMODE_RFMON test
6588         return -EINPROGRESS;            /* Call commit handler */
6589 }
6590
6591 /*------------------------------------------------------------------*/
6592 /*
6593  * Wireless Handler : get Power Management
6594  */
6595 static int airo_get_power(struct net_device *dev,
6596                           struct iw_request_info *info,
6597                           struct iw_param *vwrq,
6598                           char *extra)
6599 {
6600         struct airo_info *local = dev->priv;
6601         int mode;
6602
6603         readConfigRid(local, 1);
6604         mode = local->config.powerSaveMode;
6605         if ((vwrq->disabled = (mode == POWERSAVE_CAM)))
6606                 return 0;
6607         if ((vwrq->flags & IW_POWER_TYPE) == IW_POWER_TIMEOUT) {
6608                 vwrq->value = (int)local->config.fastListenDelay * 1024;
6609                 vwrq->flags = IW_POWER_TIMEOUT;
6610         } else {
6611                 vwrq->value = (int)local->config.fastListenInterval * 1024;
6612                 vwrq->flags = IW_POWER_PERIOD;
6613         }
6614         if ((local->config.rmode & 0xFF) == RXMODE_ADDR)
6615                 vwrq->flags |= IW_POWER_UNICAST_R;
6616         else
6617                 vwrq->flags |= IW_POWER_ALL_R;
6618
6619         return 0;
6620 }
6621
6622 /*------------------------------------------------------------------*/
6623 /*
6624  * Wireless Handler : set Sensitivity
6625  */
6626 static int airo_set_sens(struct net_device *dev,
6627                          struct iw_request_info *info,
6628                          struct iw_param *vwrq,
6629                          char *extra)
6630 {
6631         struct airo_info *local = dev->priv;
6632
6633         readConfigRid(local, 1);
6634         local->config.rssiThreshold = vwrq->disabled ? RSSI_DEFAULT : vwrq->value;
6635         set_bit (FLAG_COMMIT, &local->flags);
6636
6637         return -EINPROGRESS;            /* Call commit handler */
6638 }
6639
6640 /*------------------------------------------------------------------*/
6641 /*
6642  * Wireless Handler : get Sensitivity
6643  */
6644 static int airo_get_sens(struct net_device *dev,
6645                          struct iw_request_info *info,
6646                          struct iw_param *vwrq,
6647                          char *extra)
6648 {
6649         struct airo_info *local = dev->priv;
6650
6651         readConfigRid(local, 1);
6652         vwrq->value = local->config.rssiThreshold;
6653         vwrq->disabled = (vwrq->value == 0);
6654         vwrq->fixed = 1;
6655
6656         return 0;
6657 }
6658
6659 /*------------------------------------------------------------------*/
6660 /*
6661  * Wireless Handler : get AP List
6662  * Note : this is deprecated in favor of IWSCAN
6663  */
6664 static int airo_get_aplist(struct net_device *dev,
6665                            struct iw_request_info *info,
6666                            struct iw_point *dwrq,
6667                            char *extra)
6668 {
6669         struct airo_info *local = dev->priv;
6670         struct sockaddr *address = (struct sockaddr *) extra;
6671         struct iw_quality qual[IW_MAX_AP];
6672         BSSListRid BSSList;
6673         int i;
6674         int loseSync = capable(CAP_NET_ADMIN) ? 1: -1;
6675
6676         for (i = 0; i < IW_MAX_AP; i++) {
6677                 if (readBSSListRid(local, loseSync, &BSSList))
6678                         break;
6679                 loseSync = 0;
6680                 memcpy(address[i].sa_data, BSSList.bssid, ETH_ALEN);
6681                 address[i].sa_family = ARPHRD_ETHER;
6682                 if (local->rssi)
6683                         qual[i].level = 0x100 - local->rssi[BSSList.rssi].rssidBm;
6684                 else
6685                         qual[i].level = (BSSList.rssi + 321) / 2;
6686                 qual[i].qual = qual[i].noise = 0;
6687                 qual[i].updated = 2;
6688                 if (BSSList.index == 0xffff)
6689                         break;
6690         }
6691         if (!i) {
6692                 StatusRid status_rid;           /* Card status info */
6693                 readStatusRid(local, &status_rid, 1);
6694                 for (i = 0;
6695                      i < min(IW_MAX_AP, 4) &&
6696                              (status_rid.bssid[i][0]
6697                               & status_rid.bssid[i][1]
6698                               & status_rid.bssid[i][2]
6699                               & status_rid.bssid[i][3]
6700                               & status_rid.bssid[i][4]
6701                               & status_rid.bssid[i][5])!=0xff &&
6702                              (status_rid.bssid[i][0]
6703                               | status_rid.bssid[i][1]
6704                               | status_rid.bssid[i][2]
6705                               | status_rid.bssid[i][3]
6706                               | status_rid.bssid[i][4]
6707                               | status_rid.bssid[i][5]);
6708                      i++) {
6709                         memcpy(address[i].sa_data,
6710                                status_rid.bssid[i], ETH_ALEN);
6711                         address[i].sa_family = ARPHRD_ETHER;
6712                 }
6713         } else {
6714                 dwrq->flags = 1; /* Should be define'd */
6715                 memcpy(extra + sizeof(struct sockaddr)*i,
6716                        &qual,  sizeof(struct iw_quality)*i);
6717         }
6718         dwrq->length = i;
6719
6720         return 0;
6721 }
6722
6723 /*------------------------------------------------------------------*/
6724 /*
6725  * Wireless Handler : Initiate Scan
6726  */
6727 static int airo_set_scan(struct net_device *dev,
6728                          struct iw_request_info *info,
6729                          struct iw_param *vwrq,
6730                          char *extra)
6731 {
6732         struct airo_info *ai = dev->priv;
6733         Cmd cmd;
6734         Resp rsp;
6735
6736         /* Note : you may have realised that, as this is a SET operation,
6737          * this is privileged and therefore a normal user can't
6738          * perform scanning.
6739          * This is not an error, while the device perform scanning,
6740          * traffic doesn't flow, so it's a perfect DoS...
6741          * Jean II */
6742         if (ai->flags & FLAG_RADIO_MASK) return -ENETDOWN;
6743
6744         /* Initiate a scan command */
6745         memset(&cmd, 0, sizeof(cmd));
6746         cmd.cmd=CMD_LISTBSS;
6747         if (down_interruptible(&ai->sem))
6748                 return -ERESTARTSYS;
6749         issuecommand(ai, &cmd, &rsp);
6750         ai->scan_timestamp = jiffies;
6751         up(&ai->sem);
6752
6753         /* At this point, just return to the user. */
6754
6755         return 0;
6756 }
6757
6758 /*------------------------------------------------------------------*/
6759 /*
6760  * Translate scan data returned from the card to a card independent
6761  * format that the Wireless Tools will understand - Jean II
6762  */
6763 static inline char *airo_translate_scan(struct net_device *dev,
6764                                         char *current_ev,
6765                                         char *end_buf,
6766                                         BSSListRid *list)
6767 {
6768         struct airo_info *ai = dev->priv;
6769         struct iw_event         iwe;            /* Temporary buffer */
6770         u16                     capabilities;
6771         char *                  current_val;    /* For rates */
6772         int                     i;
6773
6774         /* First entry *MUST* be the AP MAC address */
6775         iwe.cmd = SIOCGIWAP;
6776         iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
6777         memcpy(iwe.u.ap_addr.sa_data, list->bssid, ETH_ALEN);
6778         current_ev = iwe_stream_add_event(current_ev, end_buf, &iwe, IW_EV_ADDR_LEN);
6779
6780         /* Other entries will be displayed in the order we give them */
6781
6782         /* Add the ESSID */
6783         iwe.u.data.length = list->ssidLen;
6784         if(iwe.u.data.length > 32)
6785                 iwe.u.data.length = 32;
6786         iwe.cmd = SIOCGIWESSID;
6787         iwe.u.data.flags = 1;
6788         current_ev = iwe_stream_add_point(current_ev, end_buf, &iwe, list->ssid);
6789
6790         /* Add mode */
6791         iwe.cmd = SIOCGIWMODE;
6792         capabilities = le16_to_cpu(list->cap);
6793         if(capabilities & (CAP_ESS | CAP_IBSS)) {
6794                 if(capabilities & CAP_ESS)
6795                         iwe.u.mode = IW_MODE_MASTER;
6796                 else
6797                         iwe.u.mode = IW_MODE_ADHOC;
6798                 current_ev = iwe_stream_add_event(current_ev, end_buf, &iwe, IW_EV_UINT_LEN);
6799         }
6800
6801         /* Add frequency */
6802         iwe.cmd = SIOCGIWFREQ;
6803         iwe.u.freq.m = le16_to_cpu(list->dsChannel);
6804         iwe.u.freq.m = frequency_list[iwe.u.freq.m] * 100000;
6805         iwe.u.freq.e = 1;
6806         current_ev = iwe_stream_add_event(current_ev, end_buf, &iwe, IW_EV_FREQ_LEN);
6807
6808         /* Add quality statistics */
6809         iwe.cmd = IWEVQUAL;
6810         if (ai->rssi)
6811                 iwe.u.qual.level = 0x100 - ai->rssi[list->rssi].rssidBm;
6812         else
6813                 iwe.u.qual.level = (list->rssi + 321) / 2;
6814         iwe.u.qual.noise = 0;
6815         iwe.u.qual.qual = 0;
6816         current_ev = iwe_stream_add_event(current_ev, end_buf, &iwe, IW_EV_QUAL_LEN);
6817
6818         /* Add encryption capability */
6819         iwe.cmd = SIOCGIWENCODE;
6820         if(capabilities & CAP_PRIVACY)
6821                 iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
6822         else
6823                 iwe.u.data.flags = IW_ENCODE_DISABLED;
6824         iwe.u.data.length = 0;
6825         current_ev = iwe_stream_add_point(current_ev, end_buf, &iwe, list->ssid);
6826
6827         /* Rate : stuffing multiple values in a single event require a bit
6828          * more of magic - Jean II */
6829         current_val = current_ev + IW_EV_LCP_LEN;
6830
6831         iwe.cmd = SIOCGIWRATE;
6832         /* Those two flags are ignored... */
6833         iwe.u.bitrate.fixed = iwe.u.bitrate.disabled = 0;
6834         /* Max 8 values */
6835         for(i = 0 ; i < 8 ; i++) {
6836                 /* NULL terminated */
6837                 if(list->rates[i] == 0)
6838                         break;
6839                 /* Bit rate given in 500 kb/s units (+ 0x80) */
6840                 iwe.u.bitrate.value = ((list->rates[i] & 0x7f) * 500000);
6841                 /* Add new value to event */
6842                 current_val = iwe_stream_add_value(current_ev, current_val, end_buf, &iwe, IW_EV_PARAM_LEN);
6843         }
6844         /* Check if we added any event */
6845         if((current_val - current_ev) > IW_EV_LCP_LEN)
6846                 current_ev = current_val;
6847
6848         /* The other data in the scan result are not really
6849          * interesting, so for now drop it - Jean II */
6850         return current_ev;
6851 }
6852
6853 /*------------------------------------------------------------------*/
6854 /*
6855  * Wireless Handler : Read Scan Results
6856  */
6857 static int airo_get_scan(struct net_device *dev,
6858                          struct iw_request_info *info,
6859                          struct iw_point *dwrq,
6860                          char *extra)
6861 {
6862         struct airo_info *ai = dev->priv;
6863         BSSListRid BSSList;
6864         int rc;
6865         char *current_ev = extra;
6866
6867         /* When we are associated again, the scan has surely finished.
6868          * Just in case, let's make sure enough time has elapsed since
6869          * we started the scan. - Javier */
6870         if(ai->scan_timestamp && time_before(jiffies,ai->scan_timestamp+3*HZ)) {
6871                 /* Important note : we don't want to block the caller
6872                  * until results are ready for various reasons.
6873                  * First, managing wait queues is complex and racy
6874                  * (there may be multiple simultaneous callers).
6875                  * Second, we grab some rtnetlink lock before comming
6876                  * here (in dev_ioctl()).
6877                  * Third, the caller can wait on the Wireless Event
6878                  * - Jean II */
6879                 return -EAGAIN;
6880         }
6881         ai->scan_timestamp = 0;
6882
6883         /* There's only a race with proc_BSSList_open(), but its
6884          * consequences are begnign. So I don't bother fixing it - Javier */
6885
6886         /* Try to read the first entry of the scan result */
6887         rc = PC4500_readrid(ai, RID_BSSLISTFIRST, &BSSList, sizeof(BSSList), 1);
6888         if((rc) || (BSSList.index == 0xffff)) {
6889                 /* Client error, no scan results...
6890                  * The caller need to restart the scan. */
6891                 return -ENODATA;
6892         }
6893
6894         /* Read and parse all entries */
6895         while((!rc) && (BSSList.index != 0xffff)) {
6896                 /* Translate to WE format this entry */
6897                 current_ev = airo_translate_scan(dev, current_ev,
6898                                                  extra + dwrq->length,
6899                                                  &BSSList);
6900
6901                 /* Check if there is space for one more entry */
6902                 if((extra + dwrq->length - current_ev) <= IW_EV_ADDR_LEN) {
6903                         /* Ask user space to try again with a bigger buffer */
6904                         return -E2BIG;
6905                 }
6906
6907                 /* Read next entry */
6908                 rc = PC4500_readrid(ai, RID_BSSLISTNEXT,
6909                                     &BSSList, sizeof(BSSList), 1);
6910         }
6911         /* Length of data */
6912         dwrq->length = (current_ev - extra);
6913         dwrq->flags = 0;        /* todo */
6914
6915         return 0;
6916 }
6917
6918 /*------------------------------------------------------------------*/
6919 /*
6920  * Commit handler : called after a bunch of SET operations
6921  */
6922 static int airo_config_commit(struct net_device *dev,
6923                               struct iw_request_info *info,     /* NULL */
6924                               void *zwrq,                       /* NULL */
6925                               char *extra)                      /* NULL */
6926 {
6927         struct airo_info *local = dev->priv;
6928         Resp rsp;
6929
6930         if (!test_bit (FLAG_COMMIT, &local->flags))
6931                 return 0;
6932
6933         /* Some of the "SET" function may have modified some of the
6934          * parameters. It's now time to commit them in the card */
6935         disable_MAC(local, 1);
6936         if (test_bit (FLAG_RESET, &local->flags)) {
6937                 APListRid APList_rid;
6938                 SsidRid SSID_rid;
6939
6940                 readAPListRid(local, &APList_rid);
6941                 readSsidRid(local, &SSID_rid);
6942                 if (test_bit(FLAG_MPI,&local->flags))
6943                         setup_card(local, dev->dev_addr, 1 );
6944                 else
6945                         reset_airo_card(dev);
6946                 disable_MAC(local, 1);
6947                 writeSsidRid(local, &SSID_rid, 1);
6948                 writeAPListRid(local, &APList_rid, 1);
6949         }
6950         if (down_interruptible(&local->sem))
6951                 return -ERESTARTSYS;
6952         writeConfigRid(local, 0);
6953         enable_MAC(local, &rsp, 0);
6954         if (test_bit (FLAG_RESET, &local->flags))
6955                 airo_set_promisc(local);
6956         else
6957                 up(&local->sem);
6958
6959         return 0;
6960 }
6961
6962 /*------------------------------------------------------------------*/
6963 /*
6964  * Structures to export the Wireless Handlers
6965  */
6966
6967 static const struct iw_priv_args airo_private_args[] = {
6968 /*{ cmd,         set_args,                            get_args, name } */
6969   { AIROIOCTL, IW_PRIV_TYPE_BYTE | IW_PRIV_SIZE_FIXED | sizeof (aironet_ioctl),
6970     IW_PRIV_TYPE_BYTE | 2047, "airoioctl" },
6971   { AIROIDIFC, IW_PRIV_TYPE_BYTE | IW_PRIV_SIZE_FIXED | sizeof (aironet_ioctl),
6972     IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "airoidifc" },
6973 };
6974
6975 static const iw_handler         airo_handler[] =
6976 {
6977         (iw_handler) airo_config_commit,        /* SIOCSIWCOMMIT */
6978         (iw_handler) airo_get_name,             /* SIOCGIWNAME */
6979         (iw_handler) NULL,                      /* SIOCSIWNWID */
6980         (iw_handler) NULL,                      /* SIOCGIWNWID */
6981         (iw_handler) airo_set_freq,             /* SIOCSIWFREQ */
6982         (iw_handler) airo_get_freq,             /* SIOCGIWFREQ */
6983         (iw_handler) airo_set_mode,             /* SIOCSIWMODE */
6984         (iw_handler) airo_get_mode,             /* SIOCGIWMODE */
6985         (iw_handler) airo_set_sens,             /* SIOCSIWSENS */
6986         (iw_handler) airo_get_sens,             /* SIOCGIWSENS */
6987         (iw_handler) NULL,                      /* SIOCSIWRANGE */
6988         (iw_handler) airo_get_range,            /* SIOCGIWRANGE */
6989         (iw_handler) NULL,                      /* SIOCSIWPRIV */
6990         (iw_handler) NULL,                      /* SIOCGIWPRIV */
6991         (iw_handler) NULL,                      /* SIOCSIWSTATS */
6992         (iw_handler) NULL,                      /* SIOCGIWSTATS */
6993         iw_handler_set_spy,                     /* SIOCSIWSPY */
6994         iw_handler_get_spy,                     /* SIOCGIWSPY */
6995         iw_handler_set_thrspy,                  /* SIOCSIWTHRSPY */
6996         iw_handler_get_thrspy,                  /* SIOCGIWTHRSPY */
6997         (iw_handler) airo_set_wap,              /* SIOCSIWAP */
6998         (iw_handler) airo_get_wap,              /* SIOCGIWAP */
6999         (iw_handler) NULL,                      /* -- hole -- */
7000         (iw_handler) airo_get_aplist,           /* SIOCGIWAPLIST */
7001         (iw_handler) airo_set_scan,             /* SIOCSIWSCAN */
7002         (iw_handler) airo_get_scan,             /* SIOCGIWSCAN */
7003         (iw_handler) airo_set_essid,            /* SIOCSIWESSID */
7004         (iw_handler) airo_get_essid,            /* SIOCGIWESSID */
7005         (iw_handler) airo_set_nick,             /* SIOCSIWNICKN */
7006         (iw_handler) airo_get_nick,             /* SIOCGIWNICKN */
7007         (iw_handler) NULL,                      /* -- hole -- */
7008         (iw_handler) NULL,                      /* -- hole -- */
7009         (iw_handler) airo_set_rate,             /* SIOCSIWRATE */
7010         (iw_handler) airo_get_rate,             /* SIOCGIWRATE */
7011         (iw_handler) airo_set_rts,              /* SIOCSIWRTS */
7012         (iw_handler) airo_get_rts,              /* SIOCGIWRTS */
7013         (iw_handler) airo_set_frag,             /* SIOCSIWFRAG */
7014         (iw_handler) airo_get_frag,             /* SIOCGIWFRAG */
7015         (iw_handler) airo_set_txpow,            /* SIOCSIWTXPOW */
7016         (iw_handler) airo_get_txpow,            /* SIOCGIWTXPOW */
7017         (iw_handler) airo_set_retry,            /* SIOCSIWRETRY */
7018         (iw_handler) airo_get_retry,            /* SIOCGIWRETRY */
7019         (iw_handler) airo_set_encode,           /* SIOCSIWENCODE */
7020         (iw_handler) airo_get_encode,           /* SIOCGIWENCODE */
7021         (iw_handler) airo_set_power,            /* SIOCSIWPOWER */
7022         (iw_handler) airo_get_power,            /* SIOCGIWPOWER */
7023 };
7024
7025 /* Note : don't describe AIROIDIFC and AIROOLDIDIFC in here.
7026  * We want to force the use of the ioctl code, because those can't be
7027  * won't work the iw_handler code (because they simultaneously read
7028  * and write data and iw_handler can't do that).
7029  * Note that it's perfectly legal to read/write on a single ioctl command,
7030  * you just can't use iwpriv and need to force it via the ioctl handler.
7031  * Jean II */
7032 static const iw_handler         airo_private_handler[] =
7033 {
7034         NULL,                           /* SIOCIWFIRSTPRIV */
7035 };
7036
7037 static const struct iw_handler_def      airo_handler_def =
7038 {
7039         .num_standard   = sizeof(airo_handler)/sizeof(iw_handler),
7040         .num_private    = sizeof(airo_private_handler)/sizeof(iw_handler),
7041         .num_private_args = sizeof(airo_private_args)/sizeof(struct iw_priv_args),
7042         .standard       = airo_handler,
7043         .private        = airo_private_handler,
7044         .private_args   = airo_private_args,
7045         .get_wireless_stats = airo_get_wireless_stats,
7046 };
7047
7048 #endif /* WIRELESS_EXT */
7049
7050 /*
7051  * This defines the configuration part of the Wireless Extensions
7052  * Note : irq and spinlock protection will occur in the subroutines
7053  *
7054  * TODO :
7055  *      o Check input value more carefully and fill correct values in range
7056  *      o Test and shakeout the bugs (if any)
7057  *
7058  * Jean II
7059  *
7060  * Javier Achirica did a great job of merging code from the unnamed CISCO
7061  * developer that added support for flashing the card.
7062  */
7063 static int airo_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
7064 {
7065         int rc = 0;
7066         struct airo_info *ai = (struct airo_info *)dev->priv;
7067
7068         if (ai->power)
7069                 return 0;
7070
7071         switch (cmd) {
7072 #ifdef CISCO_EXT
7073         case AIROIDIFC:
7074 #ifdef AIROOLDIDIFC
7075         case AIROOLDIDIFC:
7076 #endif
7077         {
7078                 int val = AIROMAGIC;
7079                 aironet_ioctl com;
7080                 if (copy_from_user(&com,rq->ifr_data,sizeof(com)))
7081                         rc = -EFAULT;
7082                 else if (copy_to_user(com.data,(char *)&val,sizeof(val)))
7083                         rc = -EFAULT;
7084         }
7085         break;
7086
7087         case AIROIOCTL:
7088 #ifdef AIROOLDIOCTL
7089         case AIROOLDIOCTL:
7090 #endif
7091                 /* Get the command struct and hand it off for evaluation by
7092                  * the proper subfunction
7093                  */
7094         {
7095                 aironet_ioctl com;
7096                 if (copy_from_user(&com,rq->ifr_data,sizeof(com))) {
7097                         rc = -EFAULT;
7098                         break;
7099                 }
7100
7101                 /* Separate R/W functions bracket legality here
7102                  */
7103                 if ( com.command == AIRORSWVERSION ) {
7104                         if (copy_to_user(com.data, swversion, sizeof(swversion)))
7105                                 rc = -EFAULT;
7106                         else
7107                                 rc = 0;
7108                 }
7109                 else if ( com.command <= AIRORRID)
7110                         rc = readrids(dev,&com);
7111                 else if ( com.command >= AIROPCAP && com.command <= (AIROPLEAPUSR+2) )
7112                         rc = writerids(dev,&com);
7113                 else if ( com.command >= AIROFLSHRST && com.command <= AIRORESTART )
7114                         rc = flashcard(dev,&com);
7115                 else
7116                         rc = -EINVAL;      /* Bad command in ioctl */
7117         }
7118         break;
7119 #endif /* CISCO_EXT */
7120
7121         // All other calls are currently unsupported
7122         default:
7123                 rc = -EOPNOTSUPP;
7124         }
7125         return rc;
7126 }
7127
7128 #ifdef WIRELESS_EXT
7129 /*
7130  * Get the Wireless stats out of the driver
7131  * Note : irq and spinlock protection will occur in the subroutines
7132  *
7133  * TODO :
7134  *      o Check if work in Ad-Hoc mode (otherwise, use SPY, as in wvlan_cs)
7135  *
7136  * Jean
7137  */
7138 static void airo_read_wireless_stats(struct airo_info *local)
7139 {
7140         StatusRid status_rid;
7141         StatsRid stats_rid;
7142         CapabilityRid cap_rid;
7143         u32 *vals = stats_rid.vals;
7144
7145         /* Get stats out of the card */
7146         clear_bit(JOB_WSTATS, &local->flags);
7147         if (local->power) {
7148                 up(&local->sem);
7149                 return;
7150         }
7151         readCapabilityRid(local, &cap_rid, 0);
7152         readStatusRid(local, &status_rid, 0);
7153         readStatsRid(local, &stats_rid, RID_STATS, 0);
7154         up(&local->sem);
7155
7156         /* The status */
7157         local->wstats.status = status_rid.mode;
7158
7159         /* Signal quality and co. But where is the noise level ??? */
7160         local->wstats.qual.qual = airo_get_quality(&status_rid, &cap_rid);
7161         if (local->rssi)
7162                 local->wstats.qual.level = 0x100 - local->rssi[status_rid.sigQuality].rssidBm;
7163         else
7164                 local->wstats.qual.level = (status_rid.normalizedSignalStrength + 321) / 2;
7165         if (status_rid.len >= 124) {
7166                 local->wstats.qual.noise = 256 - status_rid.noisedBm;
7167                 local->wstats.qual.updated = 7;
7168         } else {
7169                 local->wstats.qual.noise = 0;
7170                 local->wstats.qual.updated = 3;
7171         }
7172
7173         /* Packets discarded in the wireless adapter due to wireless
7174          * specific problems */
7175         local->wstats.discard.nwid = vals[56] + vals[57] + vals[58];/* SSID Mismatch */
7176         local->wstats.discard.code = vals[6];/* RxWepErr */
7177         local->wstats.discard.fragment = vals[30];
7178         local->wstats.discard.retries = vals[10];
7179         local->wstats.discard.misc = vals[1] + vals[32];
7180         local->wstats.miss.beacon = vals[34];
7181 }
7182
7183 struct iw_statistics *airo_get_wireless_stats(struct net_device *dev)
7184 {
7185         struct airo_info *local =  dev->priv;
7186
7187         if (!test_bit(JOB_WSTATS, &local->flags)) {
7188                 /* Get stats out of the card if available */
7189                 if (down_trylock(&local->sem) != 0) {
7190                         set_bit(JOB_WSTATS, &local->flags);
7191                         wake_up_interruptible(&local->thr_wait);
7192                 } else
7193                         airo_read_wireless_stats(local);
7194         }
7195
7196         return &local->wstats;
7197 }
7198 #endif /* WIRELESS_EXT */
7199
7200 #ifdef CISCO_EXT
7201 /*
7202  * This just translates from driver IOCTL codes to the command codes to
7203  * feed to the radio's host interface. Things can be added/deleted
7204  * as needed.  This represents the READ side of control I/O to
7205  * the card
7206  */
7207 static int readrids(struct net_device *dev, aironet_ioctl *comp) {
7208         unsigned short ridcode;
7209         unsigned char *iobuf;
7210         int len;
7211         struct airo_info *ai = dev->priv;
7212         Resp rsp;
7213
7214         if (test_bit(FLAG_FLASHING, &ai->flags))
7215                 return -EIO;
7216
7217         switch(comp->command)
7218         {
7219         case AIROGCAP:      ridcode = RID_CAPABILITIES; break;
7220         case AIROGCFG:      ridcode = RID_CONFIG;
7221                 if (test_bit(FLAG_COMMIT, &ai->flags)) {
7222                         disable_MAC (ai, 1);
7223                         writeConfigRid (ai, 1);
7224                         enable_MAC (ai, &rsp, 1);
7225                 }
7226                 break;
7227         case AIROGSLIST:    ridcode = RID_SSID;         break;
7228         case AIROGVLIST:    ridcode = RID_APLIST;       break;
7229         case AIROGDRVNAM:   ridcode = RID_DRVNAME;      break;
7230         case AIROGEHTENC:   ridcode = RID_ETHERENCAP;   break;
7231         case AIROGWEPKTMP:  ridcode = RID_WEP_TEMP;
7232                 /* Only super-user can read WEP keys */
7233                 if (!capable(CAP_NET_ADMIN))
7234                         return -EPERM;
7235                 break;
7236         case AIROGWEPKNV:   ridcode = RID_WEP_PERM;
7237                 /* Only super-user can read WEP keys */
7238                 if (!capable(CAP_NET_ADMIN))
7239                         return -EPERM;
7240                 break;
7241         case AIROGSTAT:     ridcode = RID_STATUS;       break;
7242         case AIROGSTATSD32: ridcode = RID_STATSDELTA;   break;
7243         case AIROGSTATSC32: ridcode = RID_STATS;        break;
7244 #ifdef MICSUPPORT
7245         case AIROGMICSTATS:
7246                 if (copy_to_user(comp->data, &ai->micstats,
7247                                  min((int)comp->len,(int)sizeof(ai->micstats))))
7248                         return -EFAULT;
7249                 return 0;
7250 #endif
7251         case AIRORRID:      ridcode = comp->ridnum;     break;
7252         default:
7253                 return -EINVAL;
7254                 break;
7255         }
7256
7257         if ((iobuf = kmalloc(RIDSIZE, GFP_KERNEL)) == NULL)
7258                 return -ENOMEM;
7259
7260         PC4500_readrid(ai,ridcode,iobuf,RIDSIZE, 1);
7261         /* get the count of bytes in the rid  docs say 1st 2 bytes is it.
7262          * then return it to the user
7263          * 9/22/2000 Honor user given length
7264          */
7265         len = comp->len;
7266
7267         if (copy_to_user(comp->data, iobuf, min(len, (int)RIDSIZE))) {
7268                 kfree (iobuf);
7269                 return -EFAULT;
7270         }
7271         kfree (iobuf);
7272         return 0;
7273 }
7274
7275 /*
7276  * Danger Will Robinson write the rids here
7277  */
7278
7279 static int writerids(struct net_device *dev, aironet_ioctl *comp) {
7280         struct airo_info *ai = dev->priv;
7281         int  ridcode;
7282 #ifdef MICSUPPORT
7283         int  enabled;
7284 #endif
7285         Resp      rsp;
7286         static int (* writer)(struct airo_info *, u16 rid, const void *, int, int);
7287         unsigned char *iobuf;
7288
7289         /* Only super-user can write RIDs */
7290         if (!capable(CAP_NET_ADMIN))
7291                 return -EPERM;
7292
7293         if (test_bit(FLAG_FLASHING, &ai->flags))
7294                 return -EIO;
7295
7296         ridcode = 0;
7297         writer = do_writerid;
7298
7299         switch(comp->command)
7300         {
7301         case AIROPSIDS:     ridcode = RID_SSID;         break;
7302         case AIROPCAP:      ridcode = RID_CAPABILITIES; break;
7303         case AIROPAPLIST:   ridcode = RID_APLIST;       break;
7304         case AIROPCFG: ai->config.len = 0;
7305                             clear_bit(FLAG_COMMIT, &ai->flags);
7306                             ridcode = RID_CONFIG;       break;
7307         case AIROPWEPKEYNV: ridcode = RID_WEP_PERM;     break;
7308         case AIROPLEAPUSR:  ridcode = RID_LEAPUSERNAME; break;
7309         case AIROPLEAPPWD:  ridcode = RID_LEAPPASSWORD; break;
7310         case AIROPWEPKEY:   ridcode = RID_WEP_TEMP; writer = PC4500_writerid;
7311                 break;
7312         case AIROPLEAPUSR+1: ridcode = 0xFF2A;          break;
7313         case AIROPLEAPUSR+2: ridcode = 0xFF2B;          break;
7314
7315                 /* this is not really a rid but a command given to the card
7316                  * same with MAC off
7317                  */
7318         case AIROPMACON:
7319                 if (enable_MAC(ai, &rsp, 1) != 0)
7320                         return -EIO;
7321                 return 0;
7322
7323                 /*
7324                  * Evidently this code in the airo driver does not get a symbol
7325                  * as disable_MAC. it's probably so short the compiler does not gen one.
7326                  */
7327         case AIROPMACOFF:
7328                 disable_MAC(ai, 1);
7329                 return 0;
7330
7331                 /* This command merely clears the counts does not actually store any data
7332                  * only reads rid. But as it changes the cards state, I put it in the
7333                  * writerid routines.
7334                  */
7335         case AIROPSTCLR:
7336                 if ((iobuf = kmalloc(RIDSIZE, GFP_KERNEL)) == NULL)
7337                         return -ENOMEM;
7338
7339                 PC4500_readrid(ai,RID_STATSDELTACLEAR,iobuf,RIDSIZE, 1);
7340
7341 #ifdef MICSUPPORT
7342                 enabled = ai->micstats.enabled;
7343                 memset(&ai->micstats,0,sizeof(ai->micstats));
7344                 ai->micstats.enabled = enabled;
7345 #endif
7346
7347                 if (copy_to_user(comp->data, iobuf,
7348                                  min((int)comp->len, (int)RIDSIZE))) {
7349                         kfree (iobuf);
7350                         return -EFAULT;
7351                 }
7352                 kfree (iobuf);
7353                 return 0;
7354
7355         default:
7356                 return -EOPNOTSUPP;     /* Blarg! */
7357         }
7358         if(comp->len > RIDSIZE)
7359                 return -EINVAL;
7360
7361         if ((iobuf = kmalloc(RIDSIZE, GFP_KERNEL)) == NULL)
7362                 return -ENOMEM;
7363
7364         if (copy_from_user(iobuf,comp->data,comp->len)) {
7365                 kfree (iobuf);
7366                 return -EFAULT;
7367         }
7368
7369         if (comp->command == AIROPCFG) {
7370                 ConfigRid *cfg = (ConfigRid *)iobuf;
7371
7372                 if (test_bit(FLAG_MIC_CAPABLE, &ai->flags))
7373                         cfg->opmode |= MODE_MIC;
7374
7375                 if ((cfg->opmode & 0xFF) == MODE_STA_IBSS)
7376                         set_bit (FLAG_ADHOC, &ai->flags);
7377                 else
7378                         clear_bit (FLAG_ADHOC, &ai->flags);
7379         }
7380
7381         if((*writer)(ai, ridcode, iobuf,comp->len,1)) {
7382                 kfree (iobuf);
7383                 return -EIO;
7384         }
7385         kfree (iobuf);
7386         return 0;
7387 }
7388
7389 /*****************************************************************************
7390  * Ancillary flash / mod functions much black magic lurkes here              *
7391  *****************************************************************************
7392  */
7393
7394 /*
7395  * Flash command switch table
7396  */
7397
7398 int flashcard(struct net_device *dev, aironet_ioctl *comp) {
7399         int z;
7400         int cmdreset(struct airo_info *);
7401         int setflashmode(struct airo_info *);
7402         int flashgchar(struct airo_info *,int,int);
7403         int flashpchar(struct airo_info *,int,int);
7404         int flashputbuf(struct airo_info *);
7405         int flashrestart(struct airo_info *,struct net_device *);
7406
7407         /* Only super-user can modify flash */
7408         if (!capable(CAP_NET_ADMIN))
7409                 return -EPERM;
7410
7411         switch(comp->command)
7412         {
7413         case AIROFLSHRST:
7414                 return cmdreset((struct airo_info *)dev->priv);
7415
7416         case AIROFLSHSTFL:
7417                 if (!((struct airo_info *)dev->priv)->flash &&
7418                         (((struct airo_info *)dev->priv)->flash = kmalloc (FLASHSIZE, GFP_KERNEL)) == NULL)
7419                         return -ENOMEM;
7420                 return setflashmode((struct airo_info *)dev->priv);
7421
7422         case AIROFLSHGCHR: /* Get char from aux */
7423                 if(comp->len != sizeof(int))
7424                         return -EINVAL;
7425                 if (copy_from_user(&z,comp->data,comp->len))
7426                         return -EFAULT;
7427                 return flashgchar((struct airo_info *)dev->priv,z,8000);
7428
7429         case AIROFLSHPCHR: /* Send char to card. */
7430                 if(comp->len != sizeof(int))
7431                         return -EINVAL;
7432                 if (copy_from_user(&z,comp->data,comp->len))
7433                         return -EFAULT;
7434                 return flashpchar((struct airo_info *)dev->priv,z,8000);
7435
7436         case AIROFLPUTBUF: /* Send 32k to card */
7437                 if (!((struct airo_info *)dev->priv)->flash)
7438                         return -ENOMEM;
7439                 if(comp->len > FLASHSIZE)
7440                         return -EINVAL;
7441                 if(copy_from_user(((struct airo_info *)dev->priv)->flash,comp->data,comp->len))
7442                         return -EFAULT;
7443
7444                 flashputbuf((struct airo_info *)dev->priv);
7445                 return 0;
7446
7447         case AIRORESTART:
7448                 if(flashrestart((struct airo_info *)dev->priv,dev))
7449                         return -EIO;
7450                 return 0;
7451         }
7452         return -EINVAL;
7453 }
7454
7455 #define FLASH_COMMAND  0x7e7e
7456
7457 /*
7458  * STEP 1)
7459  * Disable MAC and do soft reset on
7460  * card.
7461  */
7462
7463 int cmdreset(struct airo_info *ai) {
7464         disable_MAC(ai, 1);
7465
7466         if(!waitbusy (ai)){
7467                 printk(KERN_INFO "Waitbusy hang before RESET\n");
7468                 return -EBUSY;
7469         }
7470
7471         OUT4500(ai,COMMAND,CMD_SOFTRESET);
7472
7473         set_current_state (TASK_UNINTERRUPTIBLE);
7474         schedule_timeout (HZ);          /* WAS 600 12/7/00 */
7475
7476         if(!waitbusy (ai)){
7477                 printk(KERN_INFO "Waitbusy hang AFTER RESET\n");
7478                 return -EBUSY;
7479         }
7480         return 0;
7481 }
7482
7483 /* STEP 2)
7484  * Put the card in legendary flash
7485  * mode
7486  */
7487
7488 int setflashmode (struct airo_info *ai) {
7489         set_bit (FLAG_FLASHING, &ai->flags);
7490
7491         OUT4500(ai, SWS0, FLASH_COMMAND);
7492         OUT4500(ai, SWS1, FLASH_COMMAND);
7493         if (probe) {
7494                 OUT4500(ai, SWS0, FLASH_COMMAND);
7495                 OUT4500(ai, COMMAND,0x10);
7496         } else {
7497                 OUT4500(ai, SWS2, FLASH_COMMAND);
7498                 OUT4500(ai, SWS3, FLASH_COMMAND);
7499                 OUT4500(ai, COMMAND,0);
7500         }
7501         set_current_state (TASK_UNINTERRUPTIBLE);
7502         schedule_timeout (HZ/2); /* 500ms delay */
7503
7504         if(!waitbusy(ai)) {
7505                 clear_bit (FLAG_FLASHING, &ai->flags);
7506                 printk(KERN_INFO "Waitbusy hang after setflash mode\n");
7507                 return -EIO;
7508         }
7509         return 0;
7510 }
7511
7512 /* Put character to SWS0 wait for dwelltime
7513  * x 50us for  echo .
7514  */
7515
7516 int flashpchar(struct airo_info *ai,int byte,int dwelltime) {
7517         int echo;
7518         int waittime;
7519
7520         byte |= 0x8000;
7521
7522         if(dwelltime == 0 )
7523                 dwelltime = 200;
7524
7525         waittime=dwelltime;
7526
7527         /* Wait for busy bit d15 to go false indicating buffer empty */
7528         while ((IN4500 (ai, SWS0) & 0x8000) && waittime > 0) {
7529                 udelay (50);
7530                 waittime -= 50;
7531         }
7532
7533         /* timeout for busy clear wait */
7534         if(waittime <= 0 ){
7535                 printk(KERN_INFO "flash putchar busywait timeout! \n");
7536                 return -EBUSY;
7537         }
7538
7539         /* Port is clear now write byte and wait for it to echo back */
7540         do {
7541                 OUT4500(ai,SWS0,byte);
7542                 udelay(50);
7543                 dwelltime -= 50;
7544                 echo = IN4500(ai,SWS1);
7545         } while (dwelltime >= 0 && echo != byte);
7546
7547         OUT4500(ai,SWS1,0);
7548
7549         return (echo == byte) ? 0 : -EIO;
7550 }
7551
7552 /*
7553  * Get a character from the card matching matchbyte
7554  * Step 3)
7555  */
7556 int flashgchar(struct airo_info *ai,int matchbyte,int dwelltime){
7557         int           rchar;
7558         unsigned char rbyte=0;
7559
7560         do {
7561                 rchar = IN4500(ai,SWS1);
7562
7563                 if(dwelltime && !(0x8000 & rchar)){
7564                         dwelltime -= 10;
7565                         mdelay(10);
7566                         continue;
7567                 }
7568                 rbyte = 0xff & rchar;
7569
7570                 if( (rbyte == matchbyte) && (0x8000 & rchar) ){
7571                         OUT4500(ai,SWS1,0);
7572                         return 0;
7573                 }
7574                 if( rbyte == 0x81 || rbyte == 0x82 || rbyte == 0x83 || rbyte == 0x1a || 0xffff == rchar)
7575                         break;
7576                 OUT4500(ai,SWS1,0);
7577
7578         }while(dwelltime > 0);
7579         return -EIO;
7580 }
7581
7582 /*
7583  * Transfer 32k of firmware data from user buffer to our buffer and
7584  * send to the card
7585  */
7586
7587 int flashputbuf(struct airo_info *ai){
7588         int            nwords;
7589
7590         /* Write stuff */
7591         if (test_bit(FLAG_MPI,&ai->flags))
7592                 memcpy_toio(ai->pciaux + 0x8000, ai->flash, FLASHSIZE);
7593         else {
7594                 OUT4500(ai,AUXPAGE,0x100);
7595                 OUT4500(ai,AUXOFF,0);
7596
7597                 for(nwords=0;nwords != FLASHSIZE / 2;nwords++){
7598                         OUT4500(ai,AUXDATA,ai->flash[nwords] & 0xffff);
7599                 }
7600         }
7601         OUT4500(ai,SWS0,0x8000);
7602
7603         return 0;
7604 }
7605
7606 /*
7607  *
7608  */
7609 int flashrestart(struct airo_info *ai,struct net_device *dev){
7610         int    i,status;
7611
7612         set_current_state (TASK_UNINTERRUPTIBLE);
7613         schedule_timeout (HZ);          /* Added 12/7/00 */
7614         clear_bit (FLAG_FLASHING, &ai->flags);
7615         if (test_bit(FLAG_MPI, &ai->flags)) {
7616                 status = mpi_init_descriptors(ai);
7617                 if (status != SUCCESS)
7618                         return status;
7619         }
7620         status = setup_card(ai, dev->dev_addr, 1);
7621
7622         if (!test_bit(FLAG_MPI,&ai->flags))
7623                 for( i = 0; i < MAX_FIDS; i++ ) {
7624                         ai->fids[i] = transmit_allocate
7625                                 ( ai, 2312, i >= MAX_FIDS / 2 );
7626                 }
7627
7628         set_current_state (TASK_UNINTERRUPTIBLE);
7629         schedule_timeout (HZ);          /* Added 12/7/00 */
7630         return status;
7631 }
7632 #endif /* CISCO_EXT */
7633
7634 /*
7635     This program is free software; you can redistribute it and/or
7636     modify it under the terms of the GNU General Public License
7637     as published by the Free Software Foundation; either version 2
7638     of the License, or (at your option) any later version.
7639
7640     This program is distributed in the hope that it will be useful,
7641     but WITHOUT ANY WARRANTY; without even the implied warranty of
7642     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
7643     GNU General Public License for more details.
7644
7645     In addition:
7646
7647     Redistribution and use in source and binary forms, with or without
7648     modification, are permitted provided that the following conditions
7649     are met:
7650
7651     1. Redistributions of source code must retain the above copyright
7652        notice, this list of conditions and the following disclaimer.
7653     2. Redistributions in binary form must reproduce the above copyright
7654        notice, this list of conditions and the following disclaimer in the
7655        documentation and/or other materials provided with the distribution.
7656     3. The name of the author may not be used to endorse or promote
7657        products derived from this software without specific prior written
7658        permission.
7659
7660     THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
7661     IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
7662     WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
7663     ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
7664     INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
7665     (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
7666     SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
7667     HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
7668     STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
7669     IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
7670     POSSIBILITY OF SUCH DAMAGE.
7671 */
7672
7673 module_init(airo_init_module);
7674 module_exit(airo_cleanup_module);