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