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