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