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