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