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