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