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