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