[PATCH] drivers/net/s2io.c: make functions static
[linux-2.6] / drivers / net / wireless / atmel.c
1 /*** -*- linux-c -*- **********************************************************
2
3      Driver for Atmel at76c502 at76c504 and at76c506 wireless cards.
4
5         Copyright 2000-2001 ATMEL Corporation.
6         Copyright 2003-2004 Simon Kelley.
7
8     This code was developed from version 2.1.1 of the Atmel drivers, 
9     released by Atmel corp. under the GPL in December 2002. It also 
10     includes code from the Linux aironet drivers (C) Benjamin Reed, 
11     and the Linux PCMCIA package, (C) David Hinds and the Linux wireless
12     extensions, (C) Jean Tourrilhes.
13
14     The firmware module for reading the MAC address of the card comes from
15     net.russotto.AtmelMACFW, written by Matthew T. Russotto and copyright
16     by him. net.russotto.AtmelMACFW is used under the GPL license version 2.
17     This file contains the module in binary form and, under the terms
18     of the GPL, in source form. The source is located at the end of the file.
19
20     This program is free software; you can redistribute it and/or modify
21     it under the terms of the GNU General Public License as published by
22     the Free Software Foundation; either version 2 of the License, or
23     (at your option) any later version.
24
25     This software is distributed in the hope that it will be useful,
26     but WITHOUT ANY WARRANTY; without even the implied warranty of
27     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
28     GNU General Public License for more details.
29
30     You should have received a copy of the GNU General Public License
31     along with Atmel wireless lan drivers; if not, write to the Free Software
32     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
33
34     For all queries about this code, please contact the current author, 
35     Simon Kelley <simon@thekelleys.org.uk> and not Atmel Corporation.
36
37     Credit is due to HP UK and Cambridge Online Systems Ltd for supplying
38     hardware used during development of this driver.
39
40 ******************************************************************************/
41
42 #include <linux/config.h>
43 #include <linux/init.h>
44
45 #include <linux/kernel.h>
46 #include <linux/sched.h>
47 #include <linux/ptrace.h>
48 #include <linux/slab.h>
49 #include <linux/string.h>
50 #include <linux/ctype.h>
51 #include <linux/timer.h>
52 #include <asm/io.h>
53 #include <asm/system.h>
54 #include <asm/uaccess.h>
55 #include <linux/module.h>
56 #include <linux/netdevice.h>
57 #include <linux/etherdevice.h>
58 #include <linux/skbuff.h>
59 #include <linux/if_arp.h>
60 #include <linux/ioport.h>
61 #include <linux/fcntl.h>
62 #include <linux/delay.h>
63 #include <linux/wireless.h>
64 #include <net/iw_handler.h>
65 #include <linux/byteorder/generic.h>
66 #include <linux/crc32.h>
67 #include <linux/proc_fs.h>
68 #include <linux/device.h>
69 #include <linux/moduleparam.h>
70 #include <linux/firmware.h>
71 #include <net/ieee80211.h>
72 #include "atmel.h"
73
74 #define DRIVER_MAJOR 0
75 #define DRIVER_MINOR 96
76
77 MODULE_AUTHOR("Simon Kelley");
78 MODULE_DESCRIPTION("Support for Atmel at76c50x 802.11 wireless ethernet cards.");
79 MODULE_LICENSE("GPL");
80 MODULE_SUPPORTED_DEVICE("Atmel at76c50x wireless cards");
81
82 /* The name of the firmware file to be loaded 
83    over-rides any automatic selection */
84 static char *firmware = NULL;
85 module_param(firmware, charp, 0);
86
87 /* table of firmware file names */
88 static struct { 
89         AtmelFWType fw_type;
90         const char *fw_file;
91         const char *fw_file_ext;
92 } fw_table[] = {
93         { ATMEL_FW_TYPE_502,      "atmel_at76c502",      "bin" },
94         { ATMEL_FW_TYPE_502D,     "atmel_at76c502d",     "bin" },
95         { ATMEL_FW_TYPE_502E,     "atmel_at76c502e",     "bin" },
96         { ATMEL_FW_TYPE_502_3COM, "atmel_at76c502_3com", "bin" },
97         { ATMEL_FW_TYPE_504,      "atmel_at76c504",      "bin" },
98         { ATMEL_FW_TYPE_504_2958, "atmel_at76c504_2958", "bin" },
99         { ATMEL_FW_TYPE_504A_2958,"atmel_at76c504a_2958","bin" },
100         { ATMEL_FW_TYPE_506,      "atmel_at76c506",      "bin" },
101         { ATMEL_FW_TYPE_NONE,      NULL,                  NULL }
102 };
103
104 #define MAX_SSID_LENGTH 32
105 #define MGMT_JIFFIES (256 * HZ / 100)
106
107 #define MAX_BSS_ENTRIES 64      
108
109 /* registers */
110 #define GCR  0x00    //      (SIR0)  General Configuration Register        
111 #define BSR  0x02    //      (SIR1)  Bank Switching Select Register 
112 #define AR   0x04
113 #define DR   0x08
114 #define MR1  0x12    //      Mirror Register 1                  
115 #define MR2  0x14    //      Mirror Register 2  
116 #define MR3  0x16    //      Mirror Register 3  
117 #define MR4  0x18    //      Mirror Register 4   
118
119 #define GPR1                            0x0c
120 #define GPR2                            0x0e
121 #define GPR3                            0x10
122 //
123 // Constants for the GCR register.
124 //
125 #define GCR_REMAP     0x0400          // Remap internal SRAM to 0
126 #define GCR_SWRES     0x0080          // BIU reset (ARM and PAI are NOT reset) 
127 #define GCR_CORES     0x0060          // Core Reset (ARM and PAI are reset)
128 #define GCR_ENINT     0x0002          // Enable Interrupts    
129 #define GCR_ACKINT    0x0008          // Acknowledge Interrupts
130
131 #define BSS_SRAM      0x0200          // AMBA module selection --> SRAM
132 #define BSS_IRAM      0x0100          // AMBA module selection --> IRAM
133 //
134 // Constants for the MR registers.
135 //
136 #define MAC_INIT_COMPLETE       0x0001        // MAC init has been completed
137 #define MAC_BOOT_COMPLETE       0x0010        // MAC boot has been completed
138 #define MAC_INIT_OK             0x0002        // MAC boot has been completed
139
140 #define C80211_SUBTYPE_MGMT_ASS_REQUEST                 0x00
141 #define C80211_SUBTYPE_MGMT_ASS_RESPONSE                0x10
142 #define C80211_SUBTYPE_MGMT_REASS_REQUEST               0x20
143 #define C80211_SUBTYPE_MGMT_REASS_RESPONSE              0x30
144 #define C80211_SUBTYPE_MGMT_ProbeRequest                0x40
145 #define C80211_SUBTYPE_MGMT_ProbeResponse               0x50
146 #define C80211_SUBTYPE_MGMT_BEACON                      0x80
147 #define C80211_SUBTYPE_MGMT_ATIM                        0x90
148 #define C80211_SUBTYPE_MGMT_DISASSOSIATION              0xA0
149 #define C80211_SUBTYPE_MGMT_Authentication              0xB0
150 #define C80211_SUBTYPE_MGMT_Deauthentication    0xC0
151
152 #define C80211_MGMT_AAN_OPENSYSTEM              0x0000
153 #define C80211_MGMT_AAN_SHAREDKEY               0x0001
154
155 #define C80211_MGMT_CAPABILITY_ESS              0x0001  // see 802.11 p.58
156 #define C80211_MGMT_CAPABILITY_IBSS             0x0002  //      - " -
157 #define C80211_MGMT_CAPABILITY_CFPollable       0x0004  //      - " -
158 #define C80211_MGMT_CAPABILITY_CFPollRequest    0x0008  //      - " -
159 #define C80211_MGMT_CAPABILITY_Privacy          0x0010  //      - " -
160
161 #define C80211_MGMT_SC_Success                  0
162 #define C80211_MGMT_SC_Unspecified              1
163 #define C80211_MGMT_SC_SupportCapabilities      10
164 #define C80211_MGMT_SC_ReassDenied              11
165 #define C80211_MGMT_SC_AssDenied                12
166 #define C80211_MGMT_SC_AuthAlgNotSupported      13
167 #define C80211_MGMT_SC_AuthTransSeqNumError     14
168 #define C80211_MGMT_SC_AuthRejectChallenge      15
169 #define C80211_MGMT_SC_AuthRejectTimeout        16
170 #define C80211_MGMT_SC_AssDeniedHandleAP        17
171 #define C80211_MGMT_SC_AssDeniedBSSRate         18
172
173 #define C80211_MGMT_ElementID_SSID              0
174 #define C80211_MGMT_ElementID_SupportedRates    1
175 #define C80211_MGMT_ElementID_ChallengeText     16
176 #define C80211_MGMT_CAPABILITY_ShortPreamble    0x0020
177
178 #define MIB_MAX_DATA_BYTES    212
179 #define MIB_HEADER_SIZE       4    /* first four fields */
180
181 struct get_set_mib {
182         u8 type;
183         u8 size;
184         u8 index;
185         u8 reserved;
186         u8 data[MIB_MAX_DATA_BYTES];
187 };
188
189 struct rx_desc {
190         u32          Next;
191         u16          MsduPos;
192         u16          MsduSize;
193         
194         u8           State;
195         u8           Status;
196         u8           Rate;
197         u8           Rssi;
198         u8           LinkQuality;
199         u8           PreambleType;
200         u16          Duration;
201         u32          RxTime;
202
203 };
204
205 #define RX_DESC_FLAG_VALID       0x80
206 #define RX_DESC_FLAG_CONSUMED    0x40
207 #define RX_DESC_FLAG_IDLE        0x00
208
209 #define RX_STATUS_SUCCESS        0x00
210
211 #define RX_DESC_MSDU_POS_OFFSET      4
212 #define RX_DESC_MSDU_SIZE_OFFSET     6
213 #define RX_DESC_FLAGS_OFFSET         8
214 #define RX_DESC_STATUS_OFFSET        9
215 #define RX_DESC_RSSI_OFFSET          11
216 #define RX_DESC_LINK_QUALITY_OFFSET  12
217 #define RX_DESC_PREAMBLE_TYPE_OFFSET 13
218 #define RX_DESC_DURATION_OFFSET      14
219 #define RX_DESC_RX_TIME_OFFSET       16
220
221
222 struct tx_desc {
223         u32       NextDescriptor;
224         u16       TxStartOfFrame;
225         u16       TxLength;
226         
227         u8        TxState;
228         u8        TxStatus;
229         u8        RetryCount;
230         
231         u8        TxRate;
232
233         u8        KeyIndex;
234         u8        ChiperType;
235         u8        ChipreLength;
236         u8        Reserved1;
237
238         u8        Reserved;
239         u8        PacketType;
240         u16       HostTxLength;
241         
242 };
243
244
245 #define TX_DESC_NEXT_OFFSET          0
246 #define TX_DESC_POS_OFFSET           4
247 #define TX_DESC_SIZE_OFFSET          6
248 #define TX_DESC_FLAGS_OFFSET         8
249 #define TX_DESC_STATUS_OFFSET        9
250 #define TX_DESC_RETRY_OFFSET         10
251 #define TX_DESC_RATE_OFFSET          11
252 #define TX_DESC_KEY_INDEX_OFFSET     12
253 #define TX_DESC_CIPHER_TYPE_OFFSET   13
254 #define TX_DESC_CIPHER_LENGTH_OFFSET 14
255 #define TX_DESC_PACKET_TYPE_OFFSET   17
256 #define TX_DESC_HOST_LENGTH_OFFSET   18
257
258
259
260 ///////////////////////////////////////////////////////
261 // Host-MAC interface
262 ///////////////////////////////////////////////////////
263
264 #define TX_STATUS_SUCCESS       0x00
265
266 #define TX_FIRM_OWN             0x80
267 #define TX_DONE                 0x40
268
269
270 #define TX_ERROR                0x01
271
272 #define TX_PACKET_TYPE_DATA     0x01
273 #define TX_PACKET_TYPE_MGMT     0x02
274
275 #define ISR_EMPTY               0x00        // no bits set in ISR
276 #define ISR_TxCOMPLETE          0x01        // packet transmitted
277 #define ISR_RxCOMPLETE          0x02        // packet received
278 #define ISR_RxFRAMELOST         0x04        // Rx Frame lost
279 #define ISR_FATAL_ERROR         0x08        // Fatal error
280 #define ISR_COMMAND_COMPLETE    0x10        // command completed
281 #define ISR_OUT_OF_RANGE        0x20        // command completed
282 #define ISR_IBSS_MERGE          0x40        // (4.1.2.30): IBSS merge
283 #define ISR_GENERIC_IRQ         0x80                
284
285
286 #define Local_Mib_Type          0x01
287 #define Mac_Address_Mib_Type    0x02
288 #define Mac_Mib_Type            0x03
289 #define Statistics_Mib_Type     0x04
290 #define Mac_Mgmt_Mib_Type       0x05
291 #define Mac_Wep_Mib_Type        0x06
292 #define Phy_Mib_Type            0x07
293 #define Multi_Domain_MIB        0x08
294
295 #define MAC_MGMT_MIB_CUR_BSSID_POS            14
296 #define MAC_MIB_FRAG_THRESHOLD_POS            8
297 #define MAC_MIB_RTS_THRESHOLD_POS             10
298 #define MAC_MIB_SHORT_RETRY_POS               16
299 #define MAC_MIB_LONG_RETRY_POS                17
300 #define MAC_MIB_SHORT_RETRY_LIMIT_POS         16
301 #define MAC_MGMT_MIB_BEACON_PER_POS           0
302 #define MAC_MGMT_MIB_STATION_ID_POS           6
303 #define MAC_MGMT_MIB_CUR_PRIVACY_POS          11
304 #define MAC_MGMT_MIB_CUR_BSSID_POS            14
305 #define MAC_MGMT_MIB_PS_MODE_POS              53
306 #define MAC_MGMT_MIB_LISTEN_INTERVAL_POS      54
307 #define MAC_MGMT_MIB_MULTI_DOMAIN_IMPLEMENTED 56
308 #define MAC_MGMT_MIB_MULTI_DOMAIN_ENABLED     57
309 #define PHY_MIB_CHANNEL_POS                   14
310 #define PHY_MIB_RATE_SET_POS                  20
311 #define PHY_MIB_REG_DOMAIN_POS                26
312 #define LOCAL_MIB_AUTO_TX_RATE_POS            3
313 #define LOCAL_MIB_SSID_SIZE                   5
314 #define LOCAL_MIB_TX_PROMISCUOUS_POS          6
315 #define LOCAL_MIB_TX_MGMT_RATE_POS            7
316 #define LOCAL_MIB_TX_CONTROL_RATE_POS         8
317 #define LOCAL_MIB_PREAMBLE_TYPE               9
318 #define MAC_ADDR_MIB_MAC_ADDR_POS             0
319
320
321 #define         CMD_Set_MIB_Vars              0x01
322 #define         CMD_Get_MIB_Vars              0x02
323 #define         CMD_Scan                      0x03
324 #define         CMD_Join                      0x04
325 #define         CMD_Start                     0x05
326 #define         CMD_EnableRadio               0x06
327 #define         CMD_DisableRadio              0x07
328 #define         CMD_SiteSurvey                0x0B
329
330 #define         CMD_STATUS_IDLE                   0x00
331 #define         CMD_STATUS_COMPLETE               0x01
332 #define         CMD_STATUS_UNKNOWN                0x02
333 #define         CMD_STATUS_INVALID_PARAMETER      0x03
334 #define         CMD_STATUS_FUNCTION_NOT_SUPPORTED 0x04
335 #define         CMD_STATUS_TIME_OUT               0x07
336 #define         CMD_STATUS_IN_PROGRESS            0x08
337 #define         CMD_STATUS_REJECTED_RADIO_OFF     0x09
338 #define         CMD_STATUS_HOST_ERROR             0xFF
339 #define         CMD_STATUS_BUSY                   0xFE
340
341
342 #define CMD_BLOCK_COMMAND_OFFSET        0
343 #define CMD_BLOCK_STATUS_OFFSET         1
344 #define CMD_BLOCK_PARAMETERS_OFFSET     4
345
346 #define SCAN_OPTIONS_SITE_SURVEY        0x80
347
348 #define MGMT_FRAME_BODY_OFFSET          24
349 #define MAX_AUTHENTICATION_RETRIES      3
350 #define MAX_ASSOCIATION_RETRIES         3
351
352 #define AUTHENTICATION_RESPONSE_TIME_OUT  1000
353
354 #define MAX_WIRELESS_BODY  2316 /* mtu is 2312, CRC is 4 */
355 #define LOOP_RETRY_LIMIT   500000
356
357 #define ACTIVE_MODE     1
358 #define PS_MODE         2
359
360 #define MAX_ENCRYPTION_KEYS 4
361 #define MAX_ENCRYPTION_KEY_SIZE 40
362
363 ///////////////////////////////////////////////////////////////////////////
364 // 802.11 related definitions
365 ///////////////////////////////////////////////////////////////////////////
366
367 //
368 // Regulatory Domains
369 //
370
371 #define REG_DOMAIN_FCC          0x10    //Channels      1-11    USA
372 #define REG_DOMAIN_DOC          0x20    //Channel       1-11    Canada
373 #define REG_DOMAIN_ETSI         0x30    //Channel       1-13    Europe (ex Spain/France)
374 #define REG_DOMAIN_SPAIN        0x31    //Channel       10-11   Spain
375 #define REG_DOMAIN_FRANCE       0x32    //Channel       10-13   France
376 #define REG_DOMAIN_MKK          0x40    //Channel       14      Japan
377 #define REG_DOMAIN_MKK1         0x41    //Channel       1-14    Japan(MKK1)
378 #define REG_DOMAIN_ISRAEL       0x50    //Channel       3-9     ISRAEL
379
380 #define BSS_TYPE_AD_HOC         1
381 #define BSS_TYPE_INFRASTRUCTURE 2
382
383 #define SCAN_TYPE_ACTIVE        0
384 #define SCAN_TYPE_PASSIVE       1
385
386 #define LONG_PREAMBLE           0
387 #define SHORT_PREAMBLE          1
388 #define AUTO_PREAMBLE           2
389
390 #define DATA_FRAME_WS_HEADER_SIZE   30
391
392 /* promiscuous mode control */ 
393 #define PROM_MODE_OFF                   0x0
394 #define PROM_MODE_UNKNOWN               0x1
395 #define PROM_MODE_CRC_FAILED            0x2
396 #define PROM_MODE_DUPLICATED            0x4
397 #define PROM_MODE_MGMT                  0x8
398 #define PROM_MODE_CTRL                  0x10
399 #define PROM_MODE_BAD_PROTOCOL          0x20
400
401
402 #define IFACE_INT_STATUS_OFFSET         0
403 #define IFACE_INT_MASK_OFFSET           1
404 #define IFACE_LOCKOUT_HOST_OFFSET       2
405 #define IFACE_LOCKOUT_MAC_OFFSET        3
406 #define IFACE_FUNC_CTRL_OFFSET          28
407 #define IFACE_MAC_STAT_OFFSET           30
408 #define IFACE_GENERIC_INT_TYPE_OFFSET   32
409
410 #define CIPHER_SUITE_NONE     0 
411 #define CIPHER_SUITE_WEP_64   1
412 #define CIPHER_SUITE_TKIP     2
413 #define CIPHER_SUITE_AES      3
414 #define CIPHER_SUITE_CCX      4
415 #define CIPHER_SUITE_WEP_128  5
416
417 //
418 // IFACE MACROS & definitions
419 //
420 //
421
422 // FuncCtrl field: 
423 //
424 #define FUNC_CTRL_TxENABLE              0x10
425 #define FUNC_CTRL_RxENABLE              0x20
426 #define FUNC_CTRL_INIT_COMPLETE         0x01
427
428 /* A stub firmware image which reads the MAC address from NVRAM on the card.
429    For copyright information and source see the end of this file. */
430 static u8 mac_reader[] = {
431         0x06,0x00,0x00,0xea,0x04,0x00,0x00,0xea,0x03,0x00,0x00,0xea,0x02,0x00,0x00,0xea,
432         0x01,0x00,0x00,0xea,0x00,0x00,0x00,0xea,0xff,0xff,0xff,0xea,0xfe,0xff,0xff,0xea,
433         0xd3,0x00,0xa0,0xe3,0x00,0xf0,0x21,0xe1,0x0e,0x04,0xa0,0xe3,0x00,0x10,0xa0,0xe3,
434         0x81,0x11,0xa0,0xe1,0x00,0x10,0x81,0xe3,0x00,0x10,0x80,0xe5,0x1c,0x10,0x90,0xe5,
435         0x10,0x10,0xc1,0xe3,0x1c,0x10,0x80,0xe5,0x01,0x10,0xa0,0xe3,0x08,0x10,0x80,0xe5,
436         0x02,0x03,0xa0,0xe3,0x00,0x10,0xa0,0xe3,0xb0,0x10,0xc0,0xe1,0xb4,0x10,0xc0,0xe1,
437         0xb8,0x10,0xc0,0xe1,0xbc,0x10,0xc0,0xe1,0x56,0xdc,0xa0,0xe3,0x21,0x00,0x00,0xeb,
438         0x0a,0x00,0xa0,0xe3,0x1a,0x00,0x00,0xeb,0x10,0x00,0x00,0xeb,0x07,0x00,0x00,0xeb,
439         0x02,0x03,0xa0,0xe3,0x02,0x14,0xa0,0xe3,0xb4,0x10,0xc0,0xe1,0x4c,0x10,0x9f,0xe5,
440         0xbc,0x10,0xc0,0xe1,0x10,0x10,0xa0,0xe3,0xb8,0x10,0xc0,0xe1,0xfe,0xff,0xff,0xea,
441         0x00,0x40,0x2d,0xe9,0x00,0x20,0xa0,0xe3,0x02,0x3c,0xa0,0xe3,0x00,0x10,0xa0,0xe3,
442         0x28,0x00,0x9f,0xe5,0x37,0x00,0x00,0xeb,0x00,0x40,0xbd,0xe8,0x1e,0xff,0x2f,0xe1,
443         0x00,0x40,0x2d,0xe9,0x12,0x2e,0xa0,0xe3,0x06,0x30,0xa0,0xe3,0x00,0x10,0xa0,0xe3,
444         0x02,0x04,0xa0,0xe3,0x2f,0x00,0x00,0xeb,0x00,0x40,0xbd,0xe8,0x1e,0xff,0x2f,0xe1,
445         0x00,0x02,0x00,0x02,0x80,0x01,0x90,0xe0,0x01,0x00,0x00,0x0a,0x01,0x00,0x50,0xe2,
446         0xfc,0xff,0xff,0xea,0x1e,0xff,0x2f,0xe1,0x80,0x10,0xa0,0xe3,0xf3,0x06,0xa0,0xe3,
447         0x00,0x10,0x80,0xe5,0x00,0x10,0xa0,0xe3,0x00,0x10,0x80,0xe5,0x01,0x10,0xa0,0xe3,
448         0x04,0x10,0x80,0xe5,0x00,0x10,0x80,0xe5,0x0e,0x34,0xa0,0xe3,0x1c,0x10,0x93,0xe5,
449         0x02,0x1a,0x81,0xe3,0x1c,0x10,0x83,0xe5,0x58,0x11,0x9f,0xe5,0x30,0x10,0x80,0xe5,
450         0x54,0x11,0x9f,0xe5,0x34,0x10,0x80,0xe5,0x38,0x10,0x80,0xe5,0x3c,0x10,0x80,0xe5,
451         0x10,0x10,0x90,0xe5,0x08,0x00,0x90,0xe5,0x1e,0xff,0x2f,0xe1,0xf3,0x16,0xa0,0xe3,
452         0x08,0x00,0x91,0xe5,0x05,0x00,0xa0,0xe3,0x0c,0x00,0x81,0xe5,0x10,0x00,0x91,0xe5,
453         0x02,0x00,0x10,0xe3,0xfc,0xff,0xff,0x0a,0xff,0x00,0xa0,0xe3,0x0c,0x00,0x81,0xe5,
454         0x10,0x00,0x91,0xe5,0x02,0x00,0x10,0xe3,0xfc,0xff,0xff,0x0a,0x08,0x00,0x91,0xe5,
455         0x10,0x00,0x91,0xe5,0x01,0x00,0x10,0xe3,0xfc,0xff,0xff,0x0a,0x08,0x00,0x91,0xe5,
456         0xff,0x00,0x00,0xe2,0x1e,0xff,0x2f,0xe1,0x30,0x40,0x2d,0xe9,0x00,0x50,0xa0,0xe1,
457         0x03,0x40,0xa0,0xe1,0xa2,0x02,0xa0,0xe1,0x08,0x00,0x00,0xe2,0x03,0x00,0x80,0xe2,
458         0xd8,0x10,0x9f,0xe5,0x00,0x00,0xc1,0xe5,0x01,0x20,0xc1,0xe5,0xe2,0xff,0xff,0xeb,
459         0x01,0x00,0x10,0xe3,0xfc,0xff,0xff,0x1a,0x14,0x00,0xa0,0xe3,0xc4,0xff,0xff,0xeb,
460         0x04,0x20,0xa0,0xe1,0x05,0x10,0xa0,0xe1,0x02,0x00,0xa0,0xe3,0x01,0x00,0x00,0xeb,
461         0x30,0x40,0xbd,0xe8,0x1e,0xff,0x2f,0xe1,0x70,0x40,0x2d,0xe9,0xf3,0x46,0xa0,0xe3,
462         0x00,0x30,0xa0,0xe3,0x00,0x00,0x50,0xe3,0x08,0x00,0x00,0x9a,0x8c,0x50,0x9f,0xe5,
463         0x03,0x60,0xd5,0xe7,0x0c,0x60,0x84,0xe5,0x10,0x60,0x94,0xe5,0x02,0x00,0x16,0xe3,
464         0xfc,0xff,0xff,0x0a,0x01,0x30,0x83,0xe2,0x00,0x00,0x53,0xe1,0xf7,0xff,0xff,0x3a,
465         0xff,0x30,0xa0,0xe3,0x0c,0x30,0x84,0xe5,0x08,0x00,0x94,0xe5,0x10,0x00,0x94,0xe5,
466         0x01,0x00,0x10,0xe3,0xfc,0xff,0xff,0x0a,0x08,0x00,0x94,0xe5,0x00,0x00,0xa0,0xe3,
467         0x00,0x00,0x52,0xe3,0x0b,0x00,0x00,0x9a,0x10,0x50,0x94,0xe5,0x02,0x00,0x15,0xe3,
468         0xfc,0xff,0xff,0x0a,0x0c,0x30,0x84,0xe5,0x10,0x50,0x94,0xe5,0x01,0x00,0x15,0xe3,
469         0xfc,0xff,0xff,0x0a,0x08,0x50,0x94,0xe5,0x01,0x50,0xc1,0xe4,0x01,0x00,0x80,0xe2,
470         0x02,0x00,0x50,0xe1,0xf3,0xff,0xff,0x3a,0xc8,0x00,0xa0,0xe3,0x98,0xff,0xff,0xeb,
471         0x70,0x40,0xbd,0xe8,0x1e,0xff,0x2f,0xe1,0x01,0x0c,0x00,0x02,0x01,0x02,0x00,0x02,
472         0x00,0x01,0x00,0x02
473 };
474
475 struct atmel_private {
476         void *card; /* Bus dependent stucture varies for PCcard */
477         int (*present_callback)(void *); /* And callback which uses it */
478         char firmware_id[32];
479         AtmelFWType firmware_type;
480         u8 *firmware;
481         int firmware_length;
482         struct timer_list management_timer;
483         struct net_device *dev;
484         struct device *sys_dev;
485         struct iw_statistics wstats;
486         struct net_device_stats stats;  // device stats
487         spinlock_t irqlock, timerlock;  // spinlocks
488         enum { BUS_TYPE_PCCARD, BUS_TYPE_PCI } bus_type;
489         enum { 
490                 CARD_TYPE_PARALLEL_FLASH, 
491                 CARD_TYPE_SPI_FLASH,
492                 CARD_TYPE_EEPROM 
493         } card_type;
494         int do_rx_crc; /* If we need to CRC incoming packets */
495         int probe_crc; /* set if we don't yet know */
496         int crc_ok_cnt, crc_ko_cnt; /* counters for probing */
497         u16 rx_desc_head;
498         u16 tx_desc_free, tx_desc_head, tx_desc_tail, tx_desc_previous;
499         u16 tx_free_mem, tx_buff_head, tx_buff_tail;
500         
501         u16 frag_seq, frag_len, frag_no;
502         u8 frag_source[6]; 
503         
504         u8 wep_is_on, default_key, exclude_unencrypted, encryption_level;
505         u8 group_cipher_suite, pairwise_cipher_suite;
506         u8 wep_keys[MAX_ENCRYPTION_KEYS][MAX_ENCRYPTION_KEY_SIZE];
507         int wep_key_len[MAX_ENCRYPTION_KEYS]; 
508         int use_wpa, radio_on_broken; /* firmware dependent stuff. */
509
510         u16 host_info_base;
511         struct host_info_struct { 
512                 /* NB this is matched to the hardware, don't change. */
513                 u8 volatile int_status;
514                 u8 volatile int_mask;
515                 u8 volatile lockout_host;
516                 u8 volatile lockout_mac;
517
518                 u16 tx_buff_pos;
519                 u16 tx_buff_size;
520                 u16 tx_desc_pos;
521                 u16 tx_desc_count;
522
523                 u16 rx_buff_pos;
524                 u16 rx_buff_size;
525                 u16 rx_desc_pos;
526                 u16 rx_desc_count;
527                 
528                 u16 build_version;
529                 u16 command_pos;        
530                 
531                 u16 major_version;
532                 u16 minor_version;
533                 
534                 u16 func_ctrl;
535                 u16 mac_status;
536                 u16 generic_IRQ_type;
537                 u8  reserved[2];
538         } host_info;
539
540         enum { 
541                 STATION_STATE_SCANNING,
542                 STATION_STATE_JOINNING,
543                 STATION_STATE_AUTHENTICATING,
544                 STATION_STATE_ASSOCIATING,
545                 STATION_STATE_READY,
546                 STATION_STATE_REASSOCIATING,
547                 STATION_STATE_DOWN,
548                 STATION_STATE_MGMT_ERROR
549         } station_state;
550         
551         int operating_mode, power_mode;
552         time_t last_qual;
553         int beacons_this_sec;
554         int channel;
555         int reg_domain, config_reg_domain;
556         int tx_rate;
557         int auto_tx_rate;
558         int rts_threshold;
559         int frag_threshold;
560         int long_retry, short_retry;
561         int preamble;
562         int default_beacon_period, beacon_period, listen_interval;
563         int CurrentAuthentTransactionSeqNum, ExpectedAuthentTransactionSeqNum;  
564         int AuthenticationRequestRetryCnt, AssociationRequestRetryCnt, ReAssociationRequestRetryCnt;
565         enum {
566                 SITE_SURVEY_IDLE,
567                 SITE_SURVEY_IN_PROGRESS,
568                 SITE_SURVEY_COMPLETED 
569         } site_survey_state;
570         time_t last_survey;
571
572         int station_was_associated, station_is_associated;
573         int fast_scan;
574                                 
575         struct bss_info {
576                 int channel;
577                 int SSIDsize;
578                 int RSSI;
579                 int UsingWEP;
580                 int preamble;
581                 int beacon_period;
582                 int BSStype;
583                 u8 BSSID[6];
584                 u8 SSID[MAX_SSID_LENGTH];
585         } BSSinfo[MAX_BSS_ENTRIES];
586         int BSS_list_entries, current_BSS;
587         int connect_to_any_BSS; 
588         int SSID_size, new_SSID_size;
589         u8 CurrentBSSID[6], BSSID[6];
590         u8 SSID[MAX_SSID_LENGTH], new_SSID[MAX_SSID_LENGTH];
591         u64 last_beacon_timestamp;
592         u8 rx_buf[MAX_WIRELESS_BODY];
593         
594 };
595
596 static u8 atmel_basic_rates[4] = {0x82,0x84,0x0b,0x16};
597
598 static const struct {
599         int reg_domain;
600         int min, max;
601         char *name; 
602 } channel_table[] = { { REG_DOMAIN_FCC, 1, 11, "USA" },
603                       { REG_DOMAIN_DOC, 1, 11, "Canada" },
604                       { REG_DOMAIN_ETSI, 1, 13, "Europe" },
605                       { REG_DOMAIN_SPAIN, 10, 11, "Spain" },
606                       { REG_DOMAIN_FRANCE, 10, 13, "France" }, 
607                       { REG_DOMAIN_MKK, 14, 14, "MKK" },
608                       { REG_DOMAIN_MKK1, 1, 14, "MKK1" },
609                       { REG_DOMAIN_ISRAEL, 3, 9, "Israel"} };
610
611 static void build_wpa_mib(struct atmel_private *priv);
612 static int atmel_ioctl(struct net_device *dev, struct ifreq *rq, int cmd);
613 static void atmel_copy_to_card(struct net_device *dev, u16 dest, unsigned char *src, u16 len);
614 static void atmel_copy_to_host(struct net_device *dev, unsigned char *dest, u16 src, u16 len);
615 static void atmel_set_gcr(struct net_device *dev, u16 mask);
616 static void atmel_clear_gcr(struct net_device *dev, u16 mask);
617 static int atmel_lock_mac(struct atmel_private *priv);
618 static void atmel_wmem32(struct atmel_private *priv, u16 pos, u32 data);
619 static void atmel_command_irq(struct atmel_private *priv);
620 static int atmel_validate_channel(struct atmel_private *priv, int channel);
621 static void atmel_management_frame(struct atmel_private *priv, struct ieee80211_hdr_4addr *header, 
622                                    u16 frame_len, u8 rssi);
623 static void atmel_management_timer(u_long a);
624 static void atmel_send_command(struct atmel_private *priv, int command, void *cmd, int cmd_size);
625 static int atmel_send_command_wait(struct atmel_private *priv, int command, void *cmd, int cmd_size);
626 static void atmel_transmit_management_frame(struct atmel_private *priv, struct ieee80211_hdr_4addr *header,
627                                             u8 *body, int body_len);
628
629 static u8 atmel_get_mib8(struct atmel_private *priv, u8 type, u8 index);
630 static void atmel_set_mib8(struct atmel_private *priv, u8 type, u8 index, u8 data);
631 static void atmel_set_mib16(struct atmel_private *priv, u8 type, u8 index, u16 data);
632 static void atmel_set_mib(struct atmel_private *priv, u8 type, u8 index, u8 *data, int data_len);
633 static void atmel_get_mib(struct atmel_private *priv, u8 type, u8 index, u8 *data, int data_len);
634 static void atmel_scan(struct atmel_private *priv, int specific_ssid);
635 static void atmel_join_bss(struct atmel_private *priv, int bss_index);
636 static void atmel_smooth_qual(struct atmel_private *priv);
637 static void atmel_writeAR(struct net_device *dev, u16 data);
638 static int probe_atmel_card(struct net_device *dev);
639 static int reset_atmel_card(struct net_device *dev );
640 static void atmel_enter_state(struct atmel_private *priv, int new_state);
641 int atmel_open (struct net_device *dev);
642
643 static inline u16 atmel_hi(struct atmel_private *priv, u16 offset)
644 {
645         return priv->host_info_base + offset;
646 }
647
648 static inline u16 atmel_co(struct atmel_private *priv, u16 offset)
649 {
650         return priv->host_info.command_pos + offset;
651 }
652
653 static inline u16 atmel_rx(struct atmel_private *priv, u16 offset, u16  desc)
654 {
655         return priv->host_info.rx_desc_pos + (sizeof(struct rx_desc) * desc) + offset;
656 }
657
658 static inline u16 atmel_tx(struct atmel_private *priv, u16 offset, u16  desc)
659 {
660         return priv->host_info.tx_desc_pos + (sizeof(struct tx_desc) * desc) + offset;
661 }
662
663 static inline u8 atmel_read8(struct net_device *dev, u16 offset)
664 {
665         return inb(dev->base_addr + offset);
666 }
667
668 static inline void atmel_write8(struct net_device *dev, u16 offset, u8 data)
669 {
670         outb(data, dev->base_addr + offset);
671 }
672
673 static inline u16 atmel_read16(struct net_device *dev, u16 offset)
674 {
675         return inw(dev->base_addr + offset);
676 }
677
678 static inline void atmel_write16(struct net_device *dev, u16 offset, u16 data)
679 {
680         outw(data, dev->base_addr + offset);
681 }
682
683 static inline u8 atmel_rmem8(struct atmel_private *priv, u16 pos)
684 {
685         atmel_writeAR(priv->dev, pos);  
686         return atmel_read8(priv->dev, DR);
687 }
688
689 static inline void atmel_wmem8(struct atmel_private *priv, u16 pos, u16 data)
690 {
691         atmel_writeAR(priv->dev, pos);  
692         atmel_write8(priv->dev, DR, data);
693 }
694
695 static inline u16 atmel_rmem16(struct atmel_private *priv, u16 pos)
696 {
697         atmel_writeAR(priv->dev, pos);  
698         return atmel_read16(priv->dev, DR);
699 }
700
701 static inline void atmel_wmem16(struct atmel_private *priv, u16 pos, u16 data)
702 {
703         atmel_writeAR(priv->dev, pos);  
704         atmel_write16(priv->dev, DR, data);
705 }
706
707 static const struct iw_handler_def atmel_handler_def;
708
709 static void tx_done_irq(struct atmel_private *priv)
710 {
711         int i;
712
713         for (i = 0; 
714              atmel_rmem8(priv, atmel_tx(priv, TX_DESC_FLAGS_OFFSET, priv->tx_desc_head)) == TX_DONE &&
715                      i < priv->host_info.tx_desc_count;
716              i++) {
717                 
718                 u8 status = atmel_rmem8(priv, atmel_tx(priv, TX_DESC_STATUS_OFFSET, priv->tx_desc_head));
719                 u16 msdu_size = atmel_rmem16(priv, atmel_tx(priv, TX_DESC_SIZE_OFFSET, priv->tx_desc_head));
720                 u8 type = atmel_rmem8(priv, atmel_tx(priv, TX_DESC_PACKET_TYPE_OFFSET, priv->tx_desc_head));
721
722                 atmel_wmem8(priv, atmel_tx(priv, TX_DESC_FLAGS_OFFSET, priv->tx_desc_head), 0);
723
724                 priv->tx_free_mem += msdu_size;
725                 priv->tx_desc_free++;
726
727                 if (priv->tx_buff_head + msdu_size > (priv->host_info.tx_buff_pos + priv->host_info.tx_buff_size))
728                         priv->tx_buff_head = 0;
729                 else
730                         priv->tx_buff_head += msdu_size;
731                         
732                 if (priv->tx_desc_head < (priv->host_info.tx_desc_count - 1))
733                         priv->tx_desc_head++ ;                                  
734                 else
735                         priv->tx_desc_head = 0;
736                 
737                 if (type == TX_PACKET_TYPE_DATA) {
738                         if (status == TX_STATUS_SUCCESS)
739                                 priv->stats.tx_packets++;
740                         else 
741                                 priv->stats.tx_errors++;
742                         netif_wake_queue(priv->dev);
743                 }
744         }
745 }
746
747 static u16 find_tx_buff(struct atmel_private *priv, u16 len)
748 {
749         u16 bottom_free = priv->host_info.tx_buff_size - priv->tx_buff_tail;
750
751         if (priv->tx_desc_free == 3 || priv->tx_free_mem < len) 
752                 return 0;
753         
754         if (bottom_free >= len)
755                 return priv->host_info.tx_buff_pos + priv->tx_buff_tail;
756         
757         if (priv->tx_free_mem - bottom_free >= len) {
758                 priv->tx_buff_tail = 0;
759                 return priv->host_info.tx_buff_pos;
760         }
761         
762         return 0;
763 }
764
765 static void tx_update_descriptor(struct atmel_private *priv, int is_bcast, u16 len, u16 buff, u8 type)
766 {
767         atmel_wmem16(priv, atmel_tx(priv, TX_DESC_POS_OFFSET, priv->tx_desc_tail), buff);
768         atmel_wmem16(priv, atmel_tx(priv, TX_DESC_SIZE_OFFSET, priv->tx_desc_tail), len);
769         if (!priv->use_wpa)
770                 atmel_wmem16(priv, atmel_tx(priv, TX_DESC_HOST_LENGTH_OFFSET, priv->tx_desc_tail), len);
771         atmel_wmem8(priv, atmel_tx(priv, TX_DESC_PACKET_TYPE_OFFSET, priv->tx_desc_tail), type);
772         atmel_wmem8(priv, atmel_tx(priv, TX_DESC_RATE_OFFSET, priv->tx_desc_tail), priv->tx_rate);
773         atmel_wmem8(priv, atmel_tx(priv, TX_DESC_RETRY_OFFSET, priv->tx_desc_tail), 0);
774         if (priv->use_wpa) {
775                 int cipher_type, cipher_length;
776                 if (is_bcast) {
777                         cipher_type = priv->group_cipher_suite;
778                         if (cipher_type == CIPHER_SUITE_WEP_64 || 
779                             cipher_type == CIPHER_SUITE_WEP_128 )
780                                 cipher_length = 8;
781                         else if (cipher_type == CIPHER_SUITE_TKIP)
782                                 cipher_length = 12;
783                         else if (priv->pairwise_cipher_suite == CIPHER_SUITE_WEP_64 ||
784                                  priv->pairwise_cipher_suite == CIPHER_SUITE_WEP_128) {
785                                 cipher_type = priv->pairwise_cipher_suite;
786                                 cipher_length = 8;
787                         } else {
788                                 cipher_type = CIPHER_SUITE_NONE;
789                                 cipher_length = 0;
790                         }
791                 } else {
792                         cipher_type = priv->pairwise_cipher_suite;
793                         if (cipher_type == CIPHER_SUITE_WEP_64 || 
794                             cipher_type == CIPHER_SUITE_WEP_128 )
795                                 cipher_length = 8;
796                         else if (cipher_type == CIPHER_SUITE_TKIP)
797                                 cipher_length = 12;
798                         else if (priv->group_cipher_suite == CIPHER_SUITE_WEP_64 ||
799                                  priv->group_cipher_suite == CIPHER_SUITE_WEP_128) {
800                                 cipher_type = priv->group_cipher_suite;
801                                 cipher_length = 8;
802                         } else {
803                                 cipher_type = CIPHER_SUITE_NONE;
804                                 cipher_length = 0;
805                         }
806                 }
807                 
808                 atmel_wmem8(priv, atmel_tx(priv, TX_DESC_CIPHER_TYPE_OFFSET, priv->tx_desc_tail),
809                             cipher_type);       
810                 atmel_wmem8(priv, atmel_tx(priv, TX_DESC_CIPHER_LENGTH_OFFSET, priv->tx_desc_tail),
811                             cipher_length);
812         }
813         atmel_wmem32(priv, atmel_tx(priv, TX_DESC_NEXT_OFFSET, priv->tx_desc_tail), 0x80000000L);
814         atmel_wmem8(priv, atmel_tx(priv, TX_DESC_FLAGS_OFFSET, priv->tx_desc_tail), TX_FIRM_OWN);
815         if (priv->tx_desc_previous != priv->tx_desc_tail)
816                 atmel_wmem32(priv, atmel_tx(priv, TX_DESC_NEXT_OFFSET, priv->tx_desc_previous), 0);
817         priv->tx_desc_previous = priv->tx_desc_tail;
818         if (priv->tx_desc_tail < (priv->host_info.tx_desc_count -1 ))
819                 priv->tx_desc_tail++;
820         else
821                 priv->tx_desc_tail = 0;
822         priv->tx_desc_free--;
823         priv->tx_free_mem -= len;
824
825 }
826
827 static int start_tx (struct sk_buff *skb, struct net_device *dev)
828 {
829         struct atmel_private *priv = netdev_priv(dev);
830         struct ieee80211_hdr_4addr header;
831         unsigned long flags;
832         u16 buff, frame_ctl, len = (ETH_ZLEN < skb->len) ? skb->len : ETH_ZLEN;
833         u8 SNAP_RFC1024[6] = {0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00};
834  
835         if (priv->card && priv->present_callback && 
836             !(*priv->present_callback)(priv->card)) {
837                 priv->stats.tx_errors++;
838                 dev_kfree_skb(skb);
839                 return 0;
840         }
841         
842         if (priv->station_state != STATION_STATE_READY) {
843                 priv->stats.tx_errors++;
844                 dev_kfree_skb(skb);
845                 return 0;
846         }
847         
848         /* first ensure the timer func cannot run */
849         spin_lock_bh(&priv->timerlock); 
850         /* then stop the hardware ISR */
851         spin_lock_irqsave(&priv->irqlock, flags); 
852         /* nb doing the above in the opposite order will deadlock */
853         
854         /* The Wireless Header is 30 bytes. In the Ethernet packet we "cut" the
855            12 first bytes (containing DA/SA) and put them in the appropriate fields of
856            the Wireless Header. Thus the packet length is then the initial + 18 (+30-12) */
857         
858         if (!(buff = find_tx_buff(priv, len + 18))) {
859                 priv->stats.tx_dropped++;
860                 spin_unlock_irqrestore(&priv->irqlock, flags);
861                 spin_unlock_bh(&priv->timerlock);
862                 netif_stop_queue(dev);
863                 return 1;
864         }
865         
866         frame_ctl = IEEE80211_FTYPE_DATA;
867         header.duration_id = 0;
868         header.seq_ctl = 0;
869         if (priv->wep_is_on)
870                 frame_ctl |= IEEE80211_FCTL_PROTECTED;
871         if (priv->operating_mode == IW_MODE_ADHOC) {
872                 memcpy(&header.addr1, skb->data, 6);
873                 memcpy(&header.addr2, dev->dev_addr, 6);
874                 memcpy(&header.addr3, priv->BSSID, 6);
875         } else {
876                 frame_ctl |= IEEE80211_FCTL_TODS;
877                 memcpy(&header.addr1, priv->CurrentBSSID, 6);
878                 memcpy(&header.addr2, dev->dev_addr, 6);
879                 memcpy(&header.addr3, skb->data, 6);
880         }
881         
882         if (priv->use_wpa)
883                 memcpy(&header.addr4, SNAP_RFC1024, 6);
884
885         header.frame_ctl = cpu_to_le16(frame_ctl);
886         /* Copy the wireless header into the card */
887         atmel_copy_to_card(dev, buff, (unsigned char *)&header, DATA_FRAME_WS_HEADER_SIZE);
888         /* Copy the packet sans its 802.3 header addresses which have been replaced */
889         atmel_copy_to_card(dev, buff + DATA_FRAME_WS_HEADER_SIZE, skb->data + 12, len - 12);
890         priv->tx_buff_tail += len - 12 + DATA_FRAME_WS_HEADER_SIZE;
891         
892         /* low bit of first byte of destination tells us if broadcast */
893         tx_update_descriptor(priv, *(skb->data) & 0x01, len + 18, buff, TX_PACKET_TYPE_DATA);
894         dev->trans_start = jiffies;
895         priv->stats.tx_bytes += len;
896         
897         spin_unlock_irqrestore(&priv->irqlock, flags);
898         spin_unlock_bh(&priv->timerlock);
899         dev_kfree_skb(skb);
900         
901         return 0;       
902 }
903
904 static void atmel_transmit_management_frame(struct atmel_private *priv, 
905                                             struct ieee80211_hdr_4addr *header,
906                                             u8 *body, int body_len)
907 {
908         u16 buff;
909         int len =  MGMT_FRAME_BODY_OFFSET + body_len;
910         
911         if (!(buff = find_tx_buff(priv, len))) 
912                 return;
913
914         atmel_copy_to_card(priv->dev, buff, (u8 *)header, MGMT_FRAME_BODY_OFFSET);
915         atmel_copy_to_card(priv->dev, buff + MGMT_FRAME_BODY_OFFSET, body, body_len);
916         priv->tx_buff_tail += len;
917         tx_update_descriptor(priv, header->addr1[0] & 0x01, len, buff, TX_PACKET_TYPE_MGMT);
918 }
919         
920 static void fast_rx_path(struct atmel_private *priv, struct ieee80211_hdr_4addr *header, 
921                          u16 msdu_size, u16 rx_packet_loc, u32 crc)
922 {
923         /* fast path: unfragmented packet copy directly into skbuf */
924         u8 mac4[6]; 
925         struct sk_buff  *skb;
926         unsigned char *skbp;
927         
928         /* get the final, mac 4 header field, this tells us encapsulation */
929         atmel_copy_to_host(priv->dev, mac4, rx_packet_loc + 24, 6);
930         msdu_size -= 6;
931         
932         if (priv->do_rx_crc) {
933                 crc = crc32_le(crc, mac4, 6);
934                 msdu_size -= 4;
935         }
936         
937         if (!(skb = dev_alloc_skb(msdu_size + 14))) {
938                 priv->stats.rx_dropped++;
939                 return;
940         }
941
942         skb_reserve(skb, 2);
943         skbp = skb_put(skb, msdu_size + 12);
944         atmel_copy_to_host(priv->dev, skbp + 12, rx_packet_loc + 30, msdu_size);
945         
946         if (priv->do_rx_crc) {
947                 u32 netcrc;
948                 crc = crc32_le(crc, skbp + 12, msdu_size);
949                 atmel_copy_to_host(priv->dev, (void *)&netcrc, rx_packet_loc + 30 + msdu_size, 4);
950                 if ((crc ^ 0xffffffff) != netcrc) {
951                         priv->stats.rx_crc_errors++;
952                         dev_kfree_skb(skb);
953                         return;
954                 }
955         }
956         
957         memcpy(skbp, header->addr1, 6); /* destination address */
958         if (le16_to_cpu(header->frame_ctl) & IEEE80211_FCTL_FROMDS) 
959                 memcpy(&skbp[6], header->addr3, 6);
960         else
961                 memcpy(&skbp[6], header->addr2, 6); /* source address */
962         
963         priv->dev->last_rx=jiffies;
964         skb->dev = priv->dev;
965         skb->protocol = eth_type_trans(skb, priv->dev);
966         skb->ip_summed = CHECKSUM_NONE; 
967         netif_rx(skb);
968         priv->stats.rx_bytes += 12 + msdu_size;
969         priv->stats.rx_packets++;
970 }
971
972 /* Test to see if the packet in card memory at packet_loc has a valid CRC
973    It doesn't matter that this is slow: it is only used to proble the first few packets. */
974 static int probe_crc(struct atmel_private *priv, u16 packet_loc, u16 msdu_size)
975 {
976         int i = msdu_size - 4;
977         u32 netcrc, crc = 0xffffffff;
978
979         if (msdu_size < 4)
980                 return 0;
981
982         atmel_copy_to_host(priv->dev, (void *)&netcrc, packet_loc + i, 4);
983         
984         atmel_writeAR(priv->dev, packet_loc);
985         while (i--) {
986                 u8 octet = atmel_read8(priv->dev, DR);
987                 crc = crc32_le(crc, &octet, 1);
988         }
989
990         return (crc ^ 0xffffffff) == netcrc;
991 }
992
993 static void frag_rx_path(struct atmel_private *priv, struct ieee80211_hdr_4addr *header, 
994                          u16 msdu_size, u16 rx_packet_loc, u32 crc, u16 seq_no, u8 frag_no, int more_frags)
995 {
996         u8 mac4[6]; 
997         u8 source[6];
998         struct sk_buff *skb;
999
1000         if (le16_to_cpu(header->frame_ctl) & IEEE80211_FCTL_FROMDS) 
1001                 memcpy(source, header->addr3, 6);
1002         else
1003                 memcpy(source, header->addr2, 6); 
1004         
1005         rx_packet_loc += 24; /* skip header */
1006         
1007         if (priv->do_rx_crc)
1008                 msdu_size -= 4;
1009
1010         if (frag_no == 0) { /* first fragment */
1011                 atmel_copy_to_host(priv->dev, mac4, rx_packet_loc, 6);
1012                 msdu_size -= 6;
1013                 rx_packet_loc += 6;
1014
1015                 if (priv->do_rx_crc) 
1016                         crc = crc32_le(crc, mac4, 6);
1017                
1018                 priv->frag_seq = seq_no;
1019                 priv->frag_no = 1;
1020                 priv->frag_len = msdu_size;
1021                 memcpy(priv->frag_source, source, 6); 
1022                 memcpy(&priv->rx_buf[6], source, 6);
1023                 memcpy(priv->rx_buf, header->addr1, 6);
1024                                 
1025                 atmel_copy_to_host(priv->dev, &priv->rx_buf[12], rx_packet_loc, msdu_size);
1026
1027                 if (priv->do_rx_crc) {
1028                         u32 netcrc;
1029                         crc = crc32_le(crc, &priv->rx_buf[12], msdu_size);
1030                         atmel_copy_to_host(priv->dev, (void *)&netcrc, rx_packet_loc + msdu_size, 4);
1031                         if ((crc ^ 0xffffffff) != netcrc) {
1032                                 priv->stats.rx_crc_errors++;
1033                                 memset(priv->frag_source, 0xff, 6);
1034                         }
1035                 }
1036                 
1037         } else if (priv->frag_no == frag_no &&
1038                    priv->frag_seq == seq_no &&
1039                    memcmp(priv->frag_source, source, 6) == 0) {
1040                 
1041                 atmel_copy_to_host(priv->dev, &priv->rx_buf[12 + priv->frag_len], 
1042                                    rx_packet_loc, msdu_size);
1043                 if (priv->do_rx_crc) {
1044                         u32 netcrc;
1045                         crc = crc32_le(crc, 
1046                                        &priv->rx_buf[12 + priv->frag_len], 
1047                                        msdu_size);
1048                         atmel_copy_to_host(priv->dev, (void *)&netcrc, rx_packet_loc + msdu_size, 4);
1049                         if ((crc ^ 0xffffffff) != netcrc) {
1050                                 priv->stats.rx_crc_errors++;
1051                                 memset(priv->frag_source, 0xff, 6);
1052                                 more_frags = 1; /* don't send broken assembly */
1053                         }
1054                 }
1055                 
1056                 priv->frag_len += msdu_size;
1057                 priv->frag_no++;
1058
1059                 if (!more_frags) { /* last one */
1060                         memset(priv->frag_source, 0xff, 6);
1061                         if (!(skb = dev_alloc_skb(priv->frag_len + 14))) {
1062                                 priv->stats.rx_dropped++;
1063                         } else {
1064                                 skb_reserve(skb, 2);
1065                                 memcpy(skb_put(skb, priv->frag_len + 12), 
1066                                        priv->rx_buf,
1067                                        priv->frag_len + 12);
1068                                 priv->dev->last_rx = jiffies;
1069                                 skb->dev = priv->dev;
1070                                 skb->protocol = eth_type_trans(skb, priv->dev);
1071                                 skb->ip_summed = CHECKSUM_NONE; 
1072                                 netif_rx(skb);
1073                                 priv->stats.rx_bytes += priv->frag_len + 12;
1074                                 priv->stats.rx_packets++;
1075                         }
1076                 }
1077                 
1078         } else
1079                 priv->wstats.discard.fragment++;
1080 }
1081                 
1082 static void rx_done_irq(struct atmel_private *priv)
1083 {
1084         int i;
1085         struct ieee80211_hdr_4addr header;
1086         
1087         for (i = 0; 
1088              atmel_rmem8(priv, atmel_rx(priv, RX_DESC_FLAGS_OFFSET, priv->rx_desc_head)) == RX_DESC_FLAG_VALID &&
1089                      i < priv->host_info.rx_desc_count;
1090              i++) {
1091                                 
1092                 u16 msdu_size, rx_packet_loc, frame_ctl, seq_control;
1093                 u8 status = atmel_rmem8(priv, atmel_rx(priv, RX_DESC_STATUS_OFFSET, priv->rx_desc_head));
1094                 u32 crc = 0xffffffff;
1095                 
1096                 if (status != RX_STATUS_SUCCESS) {
1097                         if (status == 0xc1) /* determined by experiment */
1098                                 priv->wstats.discard.nwid++;
1099                         else
1100                                 priv->stats.rx_errors++; 
1101                         goto next;
1102                 }
1103
1104                 msdu_size = atmel_rmem16(priv, atmel_rx(priv, RX_DESC_MSDU_SIZE_OFFSET, priv->rx_desc_head));
1105                 rx_packet_loc = atmel_rmem16(priv, atmel_rx(priv, RX_DESC_MSDU_POS_OFFSET, priv->rx_desc_head));
1106                 
1107                 if (msdu_size < 30) {
1108                         priv->stats.rx_errors++; 
1109                         goto next;
1110                 }
1111                 
1112                 /* Get header as far as end of seq_ctl */
1113                 atmel_copy_to_host(priv->dev, (char *)&header, rx_packet_loc, 24);
1114                 frame_ctl = le16_to_cpu(header.frame_ctl);
1115                 seq_control = le16_to_cpu(header.seq_ctl);
1116
1117                 /* probe for CRC use here if needed  once five packets have arrived with
1118                    the same crc status, we assume we know what's happening and stop probing */
1119                 if (priv->probe_crc) {
1120                         if (!priv->wep_is_on || !(frame_ctl & IEEE80211_FCTL_PROTECTED)) {
1121                                 priv->do_rx_crc = probe_crc(priv, rx_packet_loc, msdu_size);
1122                         } else {
1123                                 priv->do_rx_crc = probe_crc(priv, rx_packet_loc + 24, msdu_size - 24);
1124                         }
1125                         if (priv->do_rx_crc) {
1126                                 if (priv->crc_ok_cnt++ > 5)
1127                                         priv->probe_crc = 0;
1128                         } else {
1129                                 if (priv->crc_ko_cnt++ > 5)
1130                                         priv->probe_crc = 0;
1131                         }
1132                 }
1133                     
1134                 /* don't CRC header when WEP in use */
1135                 if (priv->do_rx_crc && (!priv->wep_is_on || !(frame_ctl & IEEE80211_FCTL_PROTECTED))) {
1136                         crc = crc32_le(0xffffffff, (unsigned char *)&header, 24);
1137                 }
1138                 msdu_size -= 24; /* header */
1139
1140                 if ((frame_ctl & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_DATA) { 
1141                         
1142                         int more_fragments = frame_ctl & IEEE80211_FCTL_MOREFRAGS;
1143                         u8 packet_fragment_no = seq_control & IEEE80211_SCTL_FRAG;
1144                         u16 packet_sequence_no = (seq_control & IEEE80211_SCTL_SEQ) >> 4;
1145                         
1146                         if (!more_fragments && packet_fragment_no == 0 ) {
1147                                 fast_rx_path(priv, &header, msdu_size, rx_packet_loc, crc);
1148                         } else {
1149                                 frag_rx_path(priv, &header, msdu_size, rx_packet_loc, crc,
1150                                              packet_sequence_no, packet_fragment_no, more_fragments);
1151                         }
1152                 }
1153                 
1154                 if ((frame_ctl & IEEE80211_FCTL_FTYPE) == IEEE80211_FTYPE_MGMT) {
1155                         /* copy rest of packet into buffer */
1156                         atmel_copy_to_host(priv->dev, (unsigned char *)&priv->rx_buf, rx_packet_loc + 24, msdu_size);
1157                         
1158                         /* we use the same buffer for frag reassembly and control packets */
1159                         memset(priv->frag_source, 0xff, 6);
1160                         
1161                         if (priv->do_rx_crc) {
1162                                 /* last 4 octets is crc */
1163                                 msdu_size -= 4;
1164                                 crc = crc32_le(crc, (unsigned char *)&priv->rx_buf, msdu_size);
1165                                 if ((crc ^ 0xffffffff) != (*((u32 *)&priv->rx_buf[msdu_size]))) {
1166                                         priv->stats.rx_crc_errors++;
1167                                         goto next;
1168                                 }
1169                         }
1170
1171                         atmel_management_frame(priv, &header, msdu_size,
1172                                                atmel_rmem8(priv, atmel_rx(priv, RX_DESC_RSSI_OFFSET, priv->rx_desc_head)));
1173                 } 
1174
1175         next:
1176                 /* release descriptor */
1177                 atmel_wmem8(priv, atmel_rx(priv, RX_DESC_FLAGS_OFFSET, priv->rx_desc_head), RX_DESC_FLAG_CONSUMED);  
1178                 
1179                 if (priv->rx_desc_head < (priv->host_info.rx_desc_count - 1))
1180                         priv->rx_desc_head++;                                   
1181                 else
1182                         priv->rx_desc_head = 0;
1183         }
1184 }       
1185
1186 static irqreturn_t service_interrupt(int irq, void *dev_id, struct pt_regs *regs)
1187 {
1188         struct net_device *dev = (struct net_device *) dev_id;
1189         struct atmel_private *priv = netdev_priv(dev);
1190         u8 isr;
1191         int i = -1;
1192         static u8 irq_order[] = { 
1193                 ISR_OUT_OF_RANGE,
1194                 ISR_RxCOMPLETE,
1195                 ISR_TxCOMPLETE,
1196                 ISR_RxFRAMELOST,
1197                 ISR_FATAL_ERROR,
1198                 ISR_COMMAND_COMPLETE,
1199                 ISR_IBSS_MERGE,
1200                 ISR_GENERIC_IRQ
1201         };
1202                 
1203
1204         if (priv->card && priv->present_callback && 
1205             !(*priv->present_callback)(priv->card))
1206                 return IRQ_HANDLED;
1207
1208         /* In this state upper-level code assumes it can mess with
1209            the card unhampered by interrupts which may change register state.
1210            Note that even though the card shouldn't generate interrupts
1211            the inturrupt line may be shared. This allows card setup 
1212            to go on without disabling interrupts for a long time. */
1213         if (priv->station_state == STATION_STATE_DOWN)
1214                 return IRQ_NONE;
1215         
1216         atmel_clear_gcr(dev, GCR_ENINT); /* disable interrupts */
1217
1218         while (1) {
1219                 if (!atmel_lock_mac(priv)) {
1220                         /* failed to contact card */
1221                         printk(KERN_ALERT "%s: failed to contact MAC.\n", dev->name);
1222                         return IRQ_HANDLED;
1223                 }
1224                 
1225                 isr = atmel_rmem8(priv, atmel_hi(priv, IFACE_INT_STATUS_OFFSET));
1226                 atmel_wmem8(priv, atmel_hi(priv, IFACE_LOCKOUT_MAC_OFFSET), 0);
1227                 
1228                 if (!isr) {
1229                         atmel_set_gcr(dev, GCR_ENINT); /* enable interrupts */
1230                         return i == -1 ? IRQ_NONE : IRQ_HANDLED;
1231                 }
1232                 
1233                 atmel_set_gcr(dev, GCR_ACKINT); /* acknowledge interrupt */
1234                 
1235                 for (i = 0; i < sizeof(irq_order)/sizeof(u8); i++)
1236                         if (isr & irq_order[i])
1237                                 break;
1238                 
1239                 if (!atmel_lock_mac(priv)) {
1240                         /* failed to contact card */
1241                         printk(KERN_ALERT "%s: failed to contact MAC.\n", dev->name);
1242                         return IRQ_HANDLED;
1243                 }
1244                 
1245                 isr = atmel_rmem8(priv, atmel_hi(priv, IFACE_INT_STATUS_OFFSET));
1246                 isr ^= irq_order[i];
1247                 atmel_wmem8(priv, atmel_hi(priv, IFACE_INT_STATUS_OFFSET), isr);
1248                 atmel_wmem8(priv, atmel_hi(priv, IFACE_LOCKOUT_MAC_OFFSET), 0);
1249                 
1250                 switch (irq_order[i]) {
1251                         
1252                 case ISR_OUT_OF_RANGE: 
1253                         if (priv->operating_mode == IW_MODE_INFRA && 
1254                             priv->station_state == STATION_STATE_READY) {
1255                                 priv->station_is_associated = 0;
1256                                 atmel_scan(priv, 1);
1257                         }
1258                         break;
1259
1260                 case ISR_RxFRAMELOST:
1261                         priv->wstats.discard.misc++;
1262                         /* fall through */
1263                 case ISR_RxCOMPLETE:
1264                         rx_done_irq(priv); 
1265                         break;
1266                         
1267                 case ISR_TxCOMPLETE:
1268                         tx_done_irq(priv); 
1269                         break;
1270                         
1271                 case ISR_FATAL_ERROR:
1272                         printk(KERN_ALERT "%s: *** FATAL error interrupt ***\n", dev->name);
1273                         atmel_enter_state(priv, STATION_STATE_MGMT_ERROR);
1274                         break;
1275                         
1276                 case ISR_COMMAND_COMPLETE: 
1277                         atmel_command_irq(priv);
1278                         break;
1279
1280                 case ISR_IBSS_MERGE:
1281                         atmel_get_mib(priv, Mac_Mgmt_Mib_Type, MAC_MGMT_MIB_CUR_BSSID_POS, 
1282                                       priv->CurrentBSSID, 6);
1283                         /* The WPA stuff cares about the current AP address */
1284                         if (priv->use_wpa)
1285                                 build_wpa_mib(priv);
1286                         break;
1287                 case ISR_GENERIC_IRQ:
1288                         printk(KERN_INFO "%s: Generic_irq received.\n", dev->name);
1289                         break;
1290                 }
1291         }       
1292 }
1293
1294
1295 static struct net_device_stats *atmel_get_stats (struct net_device *dev)
1296 {
1297         struct atmel_private *priv = netdev_priv(dev);
1298         return &priv->stats;
1299 }
1300
1301 static struct iw_statistics *atmel_get_wireless_stats (struct net_device *dev)
1302 {
1303         struct atmel_private *priv = netdev_priv(dev);
1304
1305         /* update the link quality here in case we are seeing no beacons 
1306            at all to drive the process */
1307         atmel_smooth_qual(priv);
1308         
1309         priv->wstats.status = priv->station_state;
1310
1311         if (priv->operating_mode == IW_MODE_INFRA) {
1312                 if (priv->station_state != STATION_STATE_READY) {
1313                         priv->wstats.qual.qual = 0;
1314                         priv->wstats.qual.level = 0;
1315                         priv->wstats.qual.updated = (IW_QUAL_QUAL_INVALID
1316                                         | IW_QUAL_LEVEL_INVALID);
1317                 }
1318                 priv->wstats.qual.noise = 0;
1319                 priv->wstats.qual.updated |= IW_QUAL_NOISE_INVALID;
1320         } else {
1321                 /* Quality levels cannot be determined in ad-hoc mode,
1322                    because we can 'hear' more that one remote station. */
1323                 priv->wstats.qual.qual = 0;
1324                 priv->wstats.qual.level = 0;
1325                 priv->wstats.qual.noise = 0;
1326                 priv->wstats.qual.updated = IW_QUAL_QUAL_INVALID
1327                                         | IW_QUAL_LEVEL_INVALID
1328                                         | IW_QUAL_NOISE_INVALID;
1329                 priv->wstats.miss.beacon = 0;
1330         }
1331         
1332         return (&priv->wstats);
1333 }
1334
1335 static int atmel_change_mtu(struct net_device *dev, int new_mtu)
1336 {
1337         if ((new_mtu < 68) || (new_mtu > 2312))
1338                 return -EINVAL;
1339         dev->mtu = new_mtu;
1340         return 0;
1341 }
1342
1343 static int atmel_set_mac_address(struct net_device *dev, void *p)
1344 {
1345         struct sockaddr *addr = p;
1346         
1347         memcpy (dev->dev_addr, addr->sa_data, dev->addr_len);
1348         return atmel_open(dev);
1349 }
1350
1351 EXPORT_SYMBOL(atmel_open);
1352
1353 int atmel_open (struct net_device *dev)
1354 {
1355         struct atmel_private *priv = netdev_priv(dev);
1356         int i, channel;
1357
1358         /* any scheduled timer is no longer needed and might screw things up.. */
1359         del_timer_sync(&priv->management_timer);
1360         
1361         /* Interrupts will not touch the card once in this state... */
1362         priv->station_state = STATION_STATE_DOWN;
1363
1364         if (priv->new_SSID_size) {
1365                 memcpy(priv->SSID, priv->new_SSID, priv->new_SSID_size);
1366                 priv->SSID_size = priv->new_SSID_size;
1367                 priv->new_SSID_size = 0;
1368         }
1369         priv->BSS_list_entries = 0;
1370
1371         priv->AuthenticationRequestRetryCnt = 0;
1372         priv->AssociationRequestRetryCnt = 0;
1373         priv->ReAssociationRequestRetryCnt = 0;
1374         priv->CurrentAuthentTransactionSeqNum = 0x0001;
1375         priv->ExpectedAuthentTransactionSeqNum = 0x0002;
1376
1377         priv->site_survey_state = SITE_SURVEY_IDLE;
1378         priv->station_is_associated = 0;
1379
1380         if (!reset_atmel_card(dev)) 
1381                 return -EAGAIN;
1382
1383         if (priv->config_reg_domain) {
1384                 priv->reg_domain = priv->config_reg_domain;
1385                 atmel_set_mib8(priv, Phy_Mib_Type, PHY_MIB_REG_DOMAIN_POS, priv->reg_domain);
1386         } else {
1387                 priv->reg_domain = atmel_get_mib8(priv, Phy_Mib_Type, PHY_MIB_REG_DOMAIN_POS);
1388                 for (i = 0; i < sizeof(channel_table)/sizeof(channel_table[0]); i++)
1389                         if (priv->reg_domain == channel_table[i].reg_domain)
1390                                 break;
1391                 if (i == sizeof(channel_table)/sizeof(channel_table[0])) {
1392                         priv->reg_domain = REG_DOMAIN_MKK1;
1393                         printk(KERN_ALERT "%s: failed to get regulatory domain: assuming MKK1.\n", dev->name);
1394                 } 
1395         }
1396         
1397         if ((channel = atmel_validate_channel(priv, priv->channel)))
1398                 priv->channel = channel;
1399
1400         /* this moves station_state on.... */ 
1401         atmel_scan(priv, 1);    
1402
1403         atmel_set_gcr(priv->dev, GCR_ENINT); /* enable interrupts */
1404         return 0;
1405 }
1406
1407 static int atmel_close (struct net_device *dev)
1408 {
1409         struct atmel_private *priv = netdev_priv(dev);
1410                 
1411         atmel_enter_state(priv, STATION_STATE_DOWN);
1412         
1413         if (priv->bus_type == BUS_TYPE_PCCARD) 
1414                 atmel_write16(dev, GCR, 0x0060);
1415         atmel_write16(dev, GCR, 0x0040);
1416         return 0;
1417 }
1418
1419 static int atmel_validate_channel(struct atmel_private *priv, int channel)
1420 {
1421         /* check that channel is OK, if so return zero,
1422            else return suitable default channel */
1423         int i;
1424
1425         for (i = 0; i < sizeof(channel_table)/sizeof(channel_table[0]); i++)
1426                 if (priv->reg_domain == channel_table[i].reg_domain) {
1427                         if (channel >= channel_table[i].min &&
1428                             channel <= channel_table[i].max)
1429                                 return 0;
1430                         else
1431                                 return channel_table[i].min;
1432                 }
1433         return 0;
1434 }
1435
1436 static int atmel_proc_output (char *buf, struct atmel_private *priv)
1437 {
1438         int i;
1439         char *p = buf;
1440         char *s, *r, *c;
1441         
1442         p += sprintf(p, "Driver version:\t\t%d.%d\n", DRIVER_MAJOR, DRIVER_MINOR);
1443         
1444         if (priv->station_state != STATION_STATE_DOWN) {
1445                 p += sprintf(p, "Firmware version:\t%d.%d build %d\nFirmware location:\t", 
1446                              priv->host_info.major_version,
1447                              priv->host_info.minor_version,
1448                              priv->host_info.build_version);
1449                 
1450                 if (priv->card_type != CARD_TYPE_EEPROM) 
1451                         p += sprintf(p, "on card\n");
1452                 else if (priv->firmware) 
1453                         p += sprintf(p, "%s loaded by host\n", priv->firmware_id);
1454                 else
1455                         p += sprintf(p, "%s loaded by hotplug\n", priv->firmware_id);
1456                 
1457                 switch(priv->card_type) {
1458                 case CARD_TYPE_PARALLEL_FLASH: c = "Parallel flash"; break;
1459                 case CARD_TYPE_SPI_FLASH: c = "SPI flash\n"; break;
1460                 case CARD_TYPE_EEPROM: c = "EEPROM"; break;
1461                 default: c = "<unknown>";
1462                 }
1463
1464                 
1465                 r = "<unknown>";
1466                 for (i = 0; i < sizeof(channel_table)/sizeof(channel_table[0]); i++)
1467                         if (priv->reg_domain == channel_table[i].reg_domain)
1468                                 r = channel_table[i].name;
1469                 
1470                 p += sprintf(p, "MAC memory type:\t%s\n", c);
1471                 p += sprintf(p, "Regulatory domain:\t%s\n", r);
1472                 p += sprintf(p, "Host CRC checking:\t%s\n", 
1473                              priv->do_rx_crc ? "On" : "Off");
1474                 p += sprintf(p, "WPA-capable firmware:\t%s\n",
1475                              priv->use_wpa ? "Yes" : "No");
1476         }
1477         
1478         switch(priv->station_state) {
1479         case STATION_STATE_SCANNING: s = "Scanning"; break;
1480         case STATION_STATE_JOINNING: s = "Joining"; break;
1481         case STATION_STATE_AUTHENTICATING: s = "Authenticating"; break;
1482         case STATION_STATE_ASSOCIATING: s = "Associating"; break;
1483         case STATION_STATE_READY: s = "Ready"; break;
1484         case STATION_STATE_REASSOCIATING: s = "Reassociating"; break;
1485         case STATION_STATE_MGMT_ERROR: s = "Management error"; break;
1486         case STATION_STATE_DOWN: s = "Down"; break;
1487         default: s = "<unknown>";
1488         }
1489       
1490         p += sprintf(p, "Current state:\t\t%s\n", s);
1491         return  p - buf;
1492 }
1493
1494 static int atmel_read_proc(char *page, char **start, off_t off,
1495                            int count, int *eof, void *data)
1496 {
1497         struct atmel_private *priv = data;
1498         int len = atmel_proc_output (page, priv);
1499         if (len <= off+count) *eof = 1;
1500         *start = page + off;
1501         len -= off;
1502         if (len>count) len = count;
1503         if (len<0) len = 0;
1504         return len;
1505 }
1506
1507 struct net_device *init_atmel_card( unsigned short irq, int port, const AtmelFWType fw_type,  
1508                                     struct device *sys_dev, int (*card_present)(void *), void *card)
1509 {
1510         struct net_device *dev;
1511         struct atmel_private *priv;
1512         int rc;
1513
1514         /* Create the network device object. */
1515         dev = alloc_etherdev(sizeof(*priv));
1516         if (!dev) {
1517                 printk(KERN_ERR "atmel:  Couldn't alloc_etherdev\n");
1518                 return NULL;
1519         }
1520         if (dev_alloc_name(dev, dev->name) < 0) {
1521                 printk(KERN_ERR "atmel:  Couldn't get name!\n");
1522                 goto err_out_free;
1523         }
1524
1525         priv = netdev_priv(dev);
1526         priv->dev = dev;
1527         priv->sys_dev = sys_dev;
1528         priv->present_callback = card_present;
1529         priv->card = card;
1530         priv->firmware = NULL;
1531         priv->firmware_id[0] = '\0';
1532         priv->firmware_type = fw_type;
1533         if (firmware) /* module parameter */
1534                 strcpy(priv->firmware_id, firmware);
1535         priv->bus_type = card_present ? BUS_TYPE_PCCARD : BUS_TYPE_PCI;
1536         priv->station_state = STATION_STATE_DOWN;
1537         priv->do_rx_crc = 0;
1538         /* For PCMCIA cards, some chips need CRC, some don't
1539            so we have to probe. */
1540         if (priv->bus_type == BUS_TYPE_PCCARD) {
1541                 priv->probe_crc = 1;
1542                 priv->crc_ok_cnt = priv->crc_ko_cnt = 0;
1543         } else
1544                 priv->probe_crc = 0;
1545         memset(&priv->stats, 0, sizeof(priv->stats));
1546         memset(&priv->wstats, 0, sizeof(priv->wstats));
1547         priv->last_qual = jiffies;
1548         priv->last_beacon_timestamp = 0;
1549         memset(priv->frag_source, 0xff, sizeof(priv->frag_source));
1550         memset(priv->BSSID, 0, 6);
1551         priv->CurrentBSSID[0] = 0xFF; /* Initialize to something invalid.... */
1552         priv->station_was_associated = 0;
1553         
1554         priv->last_survey = jiffies;
1555         priv->preamble = LONG_PREAMBLE;
1556         priv->operating_mode = IW_MODE_INFRA;
1557         priv->connect_to_any_BSS = 0;
1558         priv->config_reg_domain = 0;
1559         priv->reg_domain = 0;
1560         priv->tx_rate = 3;
1561         priv->auto_tx_rate = 1;
1562         priv->channel = 4;
1563         priv->power_mode = 0;
1564         priv->SSID[0] = '\0';
1565         priv->SSID_size = 0;
1566         priv->new_SSID_size = 0;
1567         priv->frag_threshold = 2346;
1568         priv->rts_threshold = 2347;
1569         priv->short_retry = 7;
1570         priv->long_retry = 4;
1571
1572         priv->wep_is_on = 0;
1573         priv->default_key = 0;
1574         priv->encryption_level = 0;
1575         priv->exclude_unencrypted = 0;
1576         priv->group_cipher_suite = priv->pairwise_cipher_suite = CIPHER_SUITE_NONE;
1577         priv->use_wpa = 0;
1578         memset(priv->wep_keys, 0, sizeof(priv->wep_keys));
1579         memset(priv->wep_key_len, 0, sizeof(priv->wep_key_len));
1580
1581         priv->default_beacon_period = priv->beacon_period = 100;
1582         priv->listen_interval = 1;
1583
1584         init_timer(&priv->management_timer);
1585         spin_lock_init(&priv->irqlock);
1586         spin_lock_init(&priv->timerlock);
1587         priv->management_timer.function = atmel_management_timer;
1588         priv->management_timer.data = (unsigned long) dev;
1589         
1590         dev->open = atmel_open;
1591         dev->stop = atmel_close;
1592         dev->change_mtu = atmel_change_mtu;
1593         dev->set_mac_address = atmel_set_mac_address;
1594         dev->hard_start_xmit = start_tx;
1595         dev->get_stats = atmel_get_stats;
1596         dev->wireless_handlers = (struct iw_handler_def *)&atmel_handler_def;
1597         dev->do_ioctl = atmel_ioctl;
1598         dev->irq = irq;
1599         dev->base_addr = port;
1600         
1601         SET_NETDEV_DEV(dev, sys_dev);
1602         
1603         if ((rc = request_irq(dev->irq, service_interrupt, SA_SHIRQ, dev->name, dev))) {
1604                 printk(KERN_ERR "%s: register interrupt %d failed, rc %d\n", dev->name, irq, rc );
1605                 goto err_out_free;
1606         }
1607
1608         if (priv->bus_type == BUS_TYPE_PCI &&
1609             !request_region( dev->base_addr, 64, dev->name )) {
1610                 goto err_out_irq;
1611         }
1612         
1613         if (register_netdev(dev))
1614                 goto err_out_res;
1615         
1616         if (!probe_atmel_card(dev)){
1617                 unregister_netdev(dev);
1618                 goto err_out_res;
1619         }
1620         
1621         netif_carrier_off(dev);
1622         
1623         create_proc_read_entry ("driver/atmel", 0, NULL, atmel_read_proc, priv);        
1624         
1625         printk(KERN_INFO "%s: Atmel at76c50x wireless. Version %d.%d simon@thekelleys.org.uk\n",
1626                dev->name, DRIVER_MAJOR, DRIVER_MINOR);
1627         
1628         SET_MODULE_OWNER(dev);
1629         return dev;
1630         
1631  err_out_res:
1632         if (priv->bus_type == BUS_TYPE_PCI)
1633                 release_region( dev->base_addr, 64 );
1634  err_out_irq:
1635         free_irq(dev->irq, dev);
1636  err_out_free:
1637         free_netdev(dev);
1638         return NULL;
1639 }
1640
1641 EXPORT_SYMBOL(init_atmel_card);
1642
1643 void stop_atmel_card(struct net_device *dev, int freeres)
1644 {
1645         struct atmel_private *priv = netdev_priv(dev);
1646                 
1647         /* put a brick on it... */
1648         if (priv->bus_type == BUS_TYPE_PCCARD) 
1649                 atmel_write16(dev, GCR, 0x0060);
1650         atmel_write16(dev, GCR, 0x0040);
1651         
1652         del_timer_sync(&priv->management_timer);
1653         unregister_netdev(dev);
1654         remove_proc_entry("driver/atmel", NULL);
1655         free_irq(dev->irq, dev);
1656         kfree(priv->firmware);
1657         if (freeres) {
1658                 /* PCMCIA frees this stuff, so only for PCI */
1659                 release_region(dev->base_addr, 64);
1660         }
1661         free_netdev(dev);
1662 }
1663
1664 EXPORT_SYMBOL(stop_atmel_card);
1665
1666 static int atmel_set_essid(struct net_device *dev,
1667                            struct iw_request_info *info,
1668                            struct iw_point *dwrq,
1669                            char *extra)
1670 {
1671         struct atmel_private *priv = netdev_priv(dev);
1672
1673         /* Check if we asked for `any' */
1674         if(dwrq->flags == 0) {
1675                 priv->connect_to_any_BSS = 1;
1676         } else {
1677                 int index = (dwrq->flags & IW_ENCODE_INDEX) - 1;
1678
1679                 priv->connect_to_any_BSS = 0;
1680                 
1681                 /* Check the size of the string */
1682                 if (dwrq->length > MAX_SSID_LENGTH + 1)
1683                          return -E2BIG ;
1684                 if (index != 0)
1685                         return -EINVAL;
1686                 
1687                 memcpy(priv->new_SSID, extra, dwrq->length - 1);
1688                 priv->new_SSID_size = dwrq->length - 1;
1689         }
1690
1691         return -EINPROGRESS;
1692 }
1693
1694 static int atmel_get_essid(struct net_device *dev,
1695                            struct iw_request_info *info,
1696                            struct iw_point *dwrq,
1697                            char *extra)
1698 {
1699         struct atmel_private *priv = netdev_priv(dev);
1700
1701         /* Get the current SSID */
1702         if (priv->new_SSID_size != 0) {
1703                 memcpy(extra, priv->new_SSID, priv->new_SSID_size);
1704                 extra[priv->new_SSID_size] = '\0';
1705                 dwrq->length = priv->new_SSID_size + 1;
1706         } else {
1707                 memcpy(extra, priv->SSID, priv->SSID_size);
1708                 extra[priv->SSID_size] = '\0';
1709                 dwrq->length = priv->SSID_size + 1;
1710         }
1711         
1712         dwrq->flags = !priv->connect_to_any_BSS; /* active */
1713
1714         return 0;
1715 }
1716
1717 static int atmel_get_wap(struct net_device *dev,
1718                          struct iw_request_info *info,
1719                          struct sockaddr *awrq,
1720                          char *extra)
1721 {
1722         struct atmel_private *priv = netdev_priv(dev);
1723         memcpy(awrq->sa_data, priv->CurrentBSSID, 6);
1724         awrq->sa_family = ARPHRD_ETHER;
1725
1726         return 0;
1727 }
1728
1729 static int atmel_set_encode(struct net_device *dev,
1730                             struct iw_request_info *info,
1731                             struct iw_point *dwrq,
1732                             char *extra)
1733 {
1734         struct atmel_private *priv = netdev_priv(dev);
1735
1736         /* Basic checking: do we have a key to set ?
1737          * Note : with the new API, it's impossible to get a NULL pointer.
1738          * Therefore, we need to check a key size == 0 instead.
1739          * New version of iwconfig properly set the IW_ENCODE_NOKEY flag
1740          * when no key is present (only change flags), but older versions
1741          * don't do it. - Jean II */
1742         if (dwrq->length > 0) {
1743                 int index = (dwrq->flags & IW_ENCODE_INDEX) - 1;
1744                 int current_index = priv->default_key;
1745                 /* Check the size of the key */
1746                 if (dwrq->length > 13) {
1747                         return -EINVAL;
1748                 }
1749                 /* Check the index (none -> use current) */
1750                 if (index < 0 || index >= 4)
1751                         index = current_index;
1752                 else
1753                         priv->default_key = index;
1754                 /* Set the length */
1755                 if (dwrq->length > 5)
1756                         priv->wep_key_len[index] = 13;
1757                 else
1758                         if (dwrq->length > 0)
1759                                 priv->wep_key_len[index] = 5;
1760                         else
1761                                 /* Disable the key */
1762                                 priv->wep_key_len[index] = 0;
1763                 /* Check if the key is not marked as invalid */
1764                 if(!(dwrq->flags & IW_ENCODE_NOKEY)) {
1765                         /* Cleanup */
1766                         memset(priv->wep_keys[index], 0, 13);
1767                         /* Copy the key in the driver */
1768                         memcpy(priv->wep_keys[index], extra, dwrq->length);
1769                 }
1770                 /* WE specify that if a valid key is set, encryption
1771                  * should be enabled (user may turn it off later)
1772                  * This is also how "iwconfig ethX key on" works */
1773                 if (index == current_index && 
1774                     priv->wep_key_len[index] > 0) {
1775                         priv->wep_is_on = 1;
1776                         priv->exclude_unencrypted = 1;
1777                         if (priv->wep_key_len[index] > 5) {
1778                                 priv->pairwise_cipher_suite = CIPHER_SUITE_WEP_64;
1779                                 priv->encryption_level = 2;
1780                         } else {
1781                                 priv->pairwise_cipher_suite = CIPHER_SUITE_WEP_128;
1782                                 priv->encryption_level = 1;
1783                         }
1784                 }
1785         } else {
1786                 /* Do we want to just set the transmit key index ? */
1787                 int index = (dwrq->flags & IW_ENCODE_INDEX) - 1;
1788                 if ( index>=0 && index < 4 ) {
1789                         priv->default_key = index;
1790                 } else
1791                         /* Don't complain if only change the mode */
1792                         if(!dwrq->flags & IW_ENCODE_MODE) {
1793                                 return -EINVAL;
1794                         }
1795         }
1796         /* Read the flags */
1797         if(dwrq->flags & IW_ENCODE_DISABLED) {
1798                 priv->wep_is_on = 0;
1799                 priv->encryption_level = 0;     
1800                 priv->pairwise_cipher_suite = CIPHER_SUITE_NONE;
1801         } else {
1802                 priv->wep_is_on = 1;
1803                 if (priv->wep_key_len[priv->default_key] > 5) {
1804                         priv->pairwise_cipher_suite = CIPHER_SUITE_WEP_128;
1805                         priv->encryption_level = 2;
1806                 } else {
1807                         priv->pairwise_cipher_suite = CIPHER_SUITE_WEP_64;
1808                         priv->encryption_level = 1;
1809                 }
1810         }
1811         if(dwrq->flags & IW_ENCODE_RESTRICTED)
1812                 priv->exclude_unencrypted = 1;
1813         if(dwrq->flags & IW_ENCODE_OPEN)
1814                 priv->exclude_unencrypted = 0;
1815         
1816         return -EINPROGRESS;            /* Call commit handler */
1817 }
1818
1819
1820 static int atmel_get_encode(struct net_device *dev,
1821                             struct iw_request_info *info,
1822                             struct iw_point *dwrq,
1823                             char *extra)
1824 {
1825         struct atmel_private *priv = netdev_priv(dev);
1826         int index = (dwrq->flags & IW_ENCODE_INDEX) - 1;
1827         
1828         if (!priv->wep_is_on)
1829                 dwrq->flags = IW_ENCODE_DISABLED;
1830         else if (priv->exclude_unencrypted)
1831                 dwrq->flags = IW_ENCODE_RESTRICTED;
1832         else
1833                 dwrq->flags = IW_ENCODE_OPEN;
1834                 
1835                 /* Which key do we want ? -1 -> tx index */
1836         if (index < 0 || index >= 4)
1837                 index = priv->default_key;
1838         dwrq->flags |= index + 1;
1839         /* Copy the key to the user buffer */
1840         dwrq->length = priv->wep_key_len[index];
1841         if (dwrq->length > 16) {
1842                 dwrq->length=0;
1843         } else {
1844                 memset(extra, 0, 16);
1845                 memcpy(extra, priv->wep_keys[index], dwrq->length);
1846         }
1847         
1848         return 0;
1849 }
1850
1851 static int atmel_get_name(struct net_device *dev,
1852                           struct iw_request_info *info,
1853                           char *cwrq,
1854                           char *extra)
1855 {
1856         strcpy(cwrq, "IEEE 802.11-DS");
1857         return 0;
1858 }
1859
1860 static int atmel_set_rate(struct net_device *dev,
1861                           struct iw_request_info *info,
1862                           struct iw_param *vwrq,
1863                           char *extra)
1864 {
1865         struct atmel_private *priv = netdev_priv(dev);
1866         
1867         if (vwrq->fixed == 0) {
1868                 priv->tx_rate = 3;
1869                 priv->auto_tx_rate = 1;
1870         } else {
1871                 priv->auto_tx_rate = 0;
1872                 
1873                 /* Which type of value ? */
1874                 if((vwrq->value < 4) && (vwrq->value >= 0)) {
1875                         /* Setting by rate index */
1876                 priv->tx_rate = vwrq->value;
1877                 } else {
1878                 /* Setting by frequency value */
1879                         switch (vwrq->value) {
1880                         case  1000000: priv->tx_rate = 0; break;
1881                         case  2000000: priv->tx_rate = 1; break;
1882                         case  5500000: priv->tx_rate = 2; break;
1883                         case 11000000: priv->tx_rate = 3; break;
1884                         default: return -EINVAL;
1885                         }
1886                 }
1887         }
1888
1889         return -EINPROGRESS;
1890 }
1891
1892 static int atmel_set_mode(struct net_device *dev,
1893                           struct iw_request_info *info,
1894                           __u32 *uwrq,
1895                           char *extra)
1896 {
1897         struct atmel_private *priv = netdev_priv(dev);
1898
1899         if (*uwrq != IW_MODE_ADHOC && *uwrq != IW_MODE_INFRA)
1900                 return -EINVAL;
1901
1902         priv->operating_mode = *uwrq;
1903         return -EINPROGRESS;  
1904 }
1905
1906 static int atmel_get_mode(struct net_device *dev,
1907                           struct iw_request_info *info,
1908                           __u32 *uwrq,
1909                           char *extra)
1910 {
1911         struct atmel_private *priv = netdev_priv(dev);
1912         
1913         *uwrq = priv->operating_mode;
1914         return 0;
1915 }
1916
1917 static int atmel_get_rate(struct net_device *dev,
1918                          struct iw_request_info *info,
1919                          struct iw_param *vwrq,
1920                          char *extra)
1921 {
1922         struct atmel_private *priv = netdev_priv(dev);
1923
1924         if (priv->auto_tx_rate) {
1925                 vwrq->fixed = 0;
1926                 vwrq->value = 11000000;
1927         } else {
1928                 vwrq->fixed = 1;
1929                 switch(priv->tx_rate) {
1930                 case 0: vwrq->value =  1000000; break;
1931                 case 1: vwrq->value =  2000000; break;
1932                 case 2: vwrq->value =  5500000; break;
1933                 case 3: vwrq->value = 11000000; break;
1934                 }
1935         }
1936         return 0;
1937 }
1938
1939 static int atmel_set_power(struct net_device *dev,
1940                            struct iw_request_info *info,
1941                            struct iw_param *vwrq,
1942                            char *extra)
1943 {
1944         struct atmel_private *priv = netdev_priv(dev);
1945         priv->power_mode = vwrq->disabled ? 0 : 1;
1946         return -EINPROGRESS;
1947 }
1948
1949 static int atmel_get_power(struct net_device *dev,
1950                            struct iw_request_info *info,
1951                            struct iw_param *vwrq,
1952                            char *extra)
1953 {
1954         struct atmel_private *priv = netdev_priv(dev);
1955         vwrq->disabled = priv->power_mode ? 0 : 1;
1956         vwrq->flags = IW_POWER_ON;
1957         return 0;
1958 }
1959
1960 static int atmel_set_retry(struct net_device *dev,
1961                            struct iw_request_info *info,
1962                            struct iw_param *vwrq,
1963                            char *extra)
1964 {
1965         struct atmel_private *priv = netdev_priv(dev);
1966         
1967         if(!vwrq->disabled && (vwrq->flags & IW_RETRY_LIMIT)) {
1968                 if(vwrq->flags & IW_RETRY_MAX)
1969                         priv->long_retry = vwrq->value;
1970                 else if (vwrq->flags & IW_RETRY_MIN)
1971                         priv->short_retry = vwrq->value;
1972                 else {
1973                         /* No modifier : set both */
1974                         priv->long_retry = vwrq->value;
1975                         priv->short_retry = vwrq->value;
1976                 }
1977                 return -EINPROGRESS;            
1978         }
1979            
1980         return -EINVAL;
1981 }
1982
1983 static int atmel_get_retry(struct net_device *dev,
1984                            struct iw_request_info *info,
1985                            struct iw_param *vwrq,
1986                            char *extra)
1987 {
1988         struct atmel_private *priv = netdev_priv(dev);
1989
1990         vwrq->disabled = 0;      /* Can't be disabled */
1991
1992         /* Note : by default, display the min retry number */
1993         if((vwrq->flags & IW_RETRY_MAX)) {
1994                 vwrq->flags = IW_RETRY_LIMIT | IW_RETRY_MAX;
1995                 vwrq->value = priv->long_retry;
1996         } else {
1997                 vwrq->flags = IW_RETRY_LIMIT;
1998                 vwrq->value = priv->short_retry;
1999                 if(priv->long_retry != priv->short_retry)
2000                         vwrq->flags |= IW_RETRY_MIN;
2001         }
2002
2003         return 0;
2004 }
2005
2006 static int atmel_set_rts(struct net_device *dev,
2007                          struct iw_request_info *info,
2008                          struct iw_param *vwrq,
2009                          char *extra)
2010 {
2011         struct atmel_private *priv = netdev_priv(dev);
2012         int rthr = vwrq->value;
2013
2014         if(vwrq->disabled)
2015                 rthr = 2347;
2016         if((rthr < 0) || (rthr > 2347)) {
2017                 return -EINVAL;
2018         }
2019         priv->rts_threshold = rthr;
2020         
2021         return -EINPROGRESS;            /* Call commit handler */
2022 }
2023
2024 static int atmel_get_rts(struct net_device *dev,
2025                          struct iw_request_info *info,
2026                          struct iw_param *vwrq,
2027                          char *extra)
2028 {
2029         struct atmel_private *priv = netdev_priv(dev);
2030         
2031         vwrq->value = priv->rts_threshold;
2032         vwrq->disabled = (vwrq->value >= 2347);
2033         vwrq->fixed = 1;
2034
2035         return 0;
2036 }
2037
2038 static int atmel_set_frag(struct net_device *dev,
2039                           struct iw_request_info *info,
2040                           struct iw_param *vwrq,
2041                           char *extra)
2042 {
2043         struct atmel_private *priv = netdev_priv(dev);
2044         int fthr = vwrq->value;
2045
2046         if(vwrq->disabled)
2047                 fthr = 2346;
2048         if((fthr < 256) || (fthr > 2346)) {
2049                 return -EINVAL;
2050         }
2051         fthr &= ~0x1;   /* Get an even value - is it really needed ??? */
2052         priv->frag_threshold = fthr;
2053         
2054         return -EINPROGRESS;            /* Call commit handler */
2055 }
2056
2057 static int atmel_get_frag(struct net_device *dev,
2058                           struct iw_request_info *info,
2059                           struct iw_param *vwrq,
2060                           char *extra)
2061 {
2062         struct atmel_private *priv = netdev_priv(dev);
2063
2064         vwrq->value = priv->frag_threshold;
2065         vwrq->disabled = (vwrq->value >= 2346);
2066         vwrq->fixed = 1;
2067
2068         return 0;
2069 }
2070
2071 static const long frequency_list[] = { 2412, 2417, 2422, 2427, 2432, 2437, 2442,
2072                                 2447, 2452, 2457, 2462, 2467, 2472, 2484 };
2073
2074 static int atmel_set_freq(struct net_device *dev,
2075                           struct iw_request_info *info,
2076                           struct iw_freq *fwrq,
2077                           char *extra)
2078 {
2079         struct atmel_private *priv = netdev_priv(dev);
2080         int rc = -EINPROGRESS;          /* Call commit handler */
2081         
2082         /* If setting by frequency, convert to a channel */
2083         if((fwrq->e == 1) &&
2084            (fwrq->m >= (int) 241200000) &&
2085            (fwrq->m <= (int) 248700000)) {
2086                 int f = fwrq->m / 100000;
2087                 int c = 0;
2088                 while((c < 14) && (f != frequency_list[c]))
2089                         c++;
2090                 /* Hack to fall through... */
2091                 fwrq->e = 0;
2092                 fwrq->m = c + 1;
2093         }
2094         /* Setting by channel number */
2095         if((fwrq->m > 1000) || (fwrq->e > 0))
2096                 rc = -EOPNOTSUPP;
2097         else {
2098                 int channel = fwrq->m;
2099                 if (atmel_validate_channel(priv, channel) == 0) {
2100                         priv->channel = channel;
2101                 } else {
2102                         rc = -EINVAL;
2103                 } 
2104         }
2105         return rc;
2106 }
2107
2108 static int atmel_get_freq(struct net_device *dev,
2109                           struct iw_request_info *info,
2110                           struct iw_freq *fwrq,
2111                           char *extra)
2112 {
2113         struct atmel_private *priv = netdev_priv(dev);
2114
2115         fwrq->m = priv->channel;
2116         fwrq->e = 0;
2117         return 0;
2118 }
2119
2120 static int atmel_set_scan(struct net_device *dev,
2121                           struct iw_request_info *info,
2122                           struct iw_param *vwrq,
2123                           char *extra)
2124 {
2125         struct atmel_private *priv = netdev_priv(dev);
2126         unsigned long flags;
2127
2128         /* Note : you may have realised that, as this is a SET operation,
2129          * this is privileged and therefore a normal user can't
2130          * perform scanning.
2131          * This is not an error, while the device perform scanning,
2132          * traffic doesn't flow, so it's a perfect DoS...
2133          * Jean II */
2134         
2135         if (priv->station_state == STATION_STATE_DOWN)
2136                 return -EAGAIN;
2137
2138         /* Timeout old surveys. */
2139         if ((jiffies - priv->last_survey) > (20 * HZ))
2140                 priv->site_survey_state = SITE_SURVEY_IDLE;
2141         priv->last_survey = jiffies;
2142
2143         /* Initiate a scan command */
2144         if (priv->site_survey_state == SITE_SURVEY_IN_PROGRESS)
2145                 return -EBUSY;
2146                 
2147         del_timer_sync(&priv->management_timer);
2148         spin_lock_irqsave(&priv->irqlock, flags);
2149         
2150         priv->site_survey_state = SITE_SURVEY_IN_PROGRESS;
2151         priv->fast_scan = 0;
2152         atmel_scan(priv, 0);
2153         spin_unlock_irqrestore(&priv->irqlock, flags);
2154         
2155         return 0;
2156 }
2157
2158 static int atmel_get_scan(struct net_device *dev,
2159                           struct iw_request_info *info,
2160                           struct iw_point *dwrq,
2161                           char *extra)
2162 {
2163         struct atmel_private *priv = netdev_priv(dev);
2164         int i;
2165         char *current_ev = extra;
2166         struct iw_event iwe;
2167         
2168         if (priv->site_survey_state != SITE_SURVEY_COMPLETED)
2169                 return -EAGAIN;
2170         
2171         for(i=0; i<priv->BSS_list_entries; i++) { 
2172                 iwe.cmd = SIOCGIWAP;
2173                 iwe.u.ap_addr.sa_family = ARPHRD_ETHER;
2174                 memcpy(iwe.u.ap_addr.sa_data, priv->BSSinfo[i].BSSID, 6);
2175                 current_ev = iwe_stream_add_event(current_ev, extra + IW_SCAN_MAX_DATA, &iwe, IW_EV_ADDR_LEN);
2176
2177                 iwe.u.data.length =  priv->BSSinfo[i].SSIDsize;
2178                 if (iwe.u.data.length > 32)
2179                         iwe.u.data.length = 32;
2180                 iwe.cmd = SIOCGIWESSID;
2181                 iwe.u.data.flags = 1;
2182                 current_ev = iwe_stream_add_point(current_ev, extra + IW_SCAN_MAX_DATA, &iwe, priv->BSSinfo[i].SSID);
2183                 
2184                 iwe.cmd = SIOCGIWMODE;
2185                 iwe.u.mode = priv->BSSinfo[i].BSStype;
2186                 current_ev = iwe_stream_add_event(current_ev, extra + IW_SCAN_MAX_DATA, &iwe, IW_EV_UINT_LEN);
2187         
2188                 iwe.cmd = SIOCGIWFREQ;
2189                 iwe.u.freq.m = priv->BSSinfo[i].channel;
2190                 iwe.u.freq.e = 0;
2191                 current_ev = iwe_stream_add_event(current_ev, extra + IW_SCAN_MAX_DATA, &iwe, IW_EV_FREQ_LEN);
2192                 
2193                 iwe.cmd = SIOCGIWENCODE;
2194                 if (priv->BSSinfo[i].UsingWEP)
2195                         iwe.u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
2196                 else
2197                         iwe.u.data.flags = IW_ENCODE_DISABLED;
2198                 iwe.u.data.length = 0;
2199                 current_ev = iwe_stream_add_point(current_ev, extra + IW_SCAN_MAX_DATA, &iwe, NULL);
2200                 
2201         }
2202
2203         /* Length of data */
2204         dwrq->length = (current_ev - extra);
2205         dwrq->flags = 0;   
2206         
2207         return 0;
2208 }
2209
2210 static int atmel_get_range(struct net_device *dev,
2211                            struct iw_request_info *info,
2212                            struct iw_point *dwrq,
2213                            char *extra)
2214 {
2215         struct atmel_private *priv = netdev_priv(dev);
2216         struct iw_range *range = (struct iw_range *) extra;
2217         int k,i,j;
2218
2219         dwrq->length = sizeof(struct iw_range);
2220         memset(range, 0, sizeof(range));
2221         range->min_nwid = 0x0000;
2222         range->max_nwid = 0x0000;
2223         range->num_channels = 0;
2224         for (j = 0; j < sizeof(channel_table)/sizeof(channel_table[0]); j++)
2225                 if (priv->reg_domain == channel_table[j].reg_domain) {
2226                         range->num_channels = channel_table[j].max - channel_table[j].min + 1;
2227                         break;
2228                 }
2229         if (range->num_channels != 0) {
2230                 for(k = 0, i = channel_table[j].min; i <= channel_table[j].max; i++) {
2231                         range->freq[k].i = i; /* List index */
2232                         range->freq[k].m = frequency_list[i-1] * 100000;
2233                         range->freq[k++].e = 1; /* Values in table in MHz -> * 10^5 * 10 */
2234                 }
2235                 range->num_frequency = k;
2236         }
2237         
2238         range->max_qual.qual = 100;
2239         range->max_qual.level = 100;
2240         range->max_qual.noise = 0;
2241         range->max_qual.updated = IW_QUAL_NOISE_INVALID;
2242
2243         range->avg_qual.qual = 50;
2244         range->avg_qual.level = 50;
2245         range->avg_qual.noise = 0;
2246         range->avg_qual.updated = IW_QUAL_NOISE_INVALID;
2247
2248         range->sensitivity = 0;
2249
2250         range->bitrate[0] =  1000000;
2251         range->bitrate[1] =  2000000;
2252         range->bitrate[2] =  5500000;
2253         range->bitrate[3] = 11000000;
2254         range->num_bitrates = 4;
2255
2256         range->min_rts = 0;
2257         range->max_rts = 2347;
2258         range->min_frag = 256;
2259         range->max_frag = 2346;
2260
2261         range->encoding_size[0] = 5;
2262         range->encoding_size[1] = 13;
2263         range->num_encoding_sizes = 2;
2264         range->max_encoding_tokens = 4;
2265         
2266         range->pmp_flags = IW_POWER_ON;
2267         range->pmt_flags = IW_POWER_ON;
2268         range->pm_capa = 0;
2269         
2270         range->we_version_source = WIRELESS_EXT;
2271         range->we_version_compiled = WIRELESS_EXT;
2272         range->retry_capa = IW_RETRY_LIMIT ;
2273         range->retry_flags = IW_RETRY_LIMIT;
2274         range->r_time_flags = 0;
2275         range->min_retry = 1;
2276         range->max_retry = 65535;
2277
2278         return 0;
2279 }
2280
2281 static int atmel_set_wap(struct net_device *dev,
2282                          struct iw_request_info *info,
2283                          struct sockaddr *awrq,
2284                          char *extra)
2285 {
2286         struct atmel_private *priv = netdev_priv(dev);
2287         int i;
2288         static const u8 bcast[] = { 255, 255, 255, 255, 255, 255 };
2289         unsigned long flags;
2290
2291         if (awrq->sa_family != ARPHRD_ETHER)
2292                 return -EINVAL;
2293         
2294         if (memcmp(bcast, awrq->sa_data, 6) == 0) {
2295                 del_timer_sync(&priv->management_timer);
2296                 spin_lock_irqsave(&priv->irqlock, flags);
2297                 atmel_scan(priv, 1);
2298                 spin_unlock_irqrestore(&priv->irqlock, flags);
2299                 return 0;
2300         }
2301         
2302         for(i=0; i<priv->BSS_list_entries; i++) {
2303                 if (memcmp(priv->BSSinfo[i].BSSID, awrq->sa_data, 6) == 0) {
2304                         if (!priv->wep_is_on && priv->BSSinfo[i].UsingWEP) {
2305                                 return -EINVAL;
2306                         } else if  (priv->wep_is_on && !priv->BSSinfo[i].UsingWEP) {
2307                                 return -EINVAL;
2308                         } else {
2309                                 del_timer_sync(&priv->management_timer);
2310                                 spin_lock_irqsave(&priv->irqlock, flags);
2311                                 atmel_join_bss(priv, i);
2312                                 spin_unlock_irqrestore(&priv->irqlock, flags);
2313                                 return 0;
2314                         }
2315                 }
2316         }
2317                 
2318         return -EINVAL;
2319 }
2320         
2321 static int atmel_config_commit(struct net_device *dev,
2322                                struct iw_request_info *info,    /* NULL */
2323                                void *zwrq,                      /* NULL */
2324                                char *extra)                     /* NULL */
2325 {
2326         return atmel_open(dev);
2327 }
2328
2329 static const iw_handler         atmel_handler[] =
2330 {
2331         (iw_handler) atmel_config_commit,       /* SIOCSIWCOMMIT */
2332         (iw_handler) atmel_get_name,            /* SIOCGIWNAME */
2333         (iw_handler) NULL,                      /* SIOCSIWNWID */
2334         (iw_handler) NULL,                      /* SIOCGIWNWID */
2335         (iw_handler) atmel_set_freq,            /* SIOCSIWFREQ */
2336         (iw_handler) atmel_get_freq,            /* SIOCGIWFREQ */
2337         (iw_handler) atmel_set_mode,            /* SIOCSIWMODE */
2338         (iw_handler) atmel_get_mode,            /* SIOCGIWMODE */
2339         (iw_handler) NULL,                      /* SIOCSIWSENS */
2340         (iw_handler) NULL,                      /* SIOCGIWSENS */
2341         (iw_handler) NULL,                      /* SIOCSIWRANGE */
2342         (iw_handler) atmel_get_range,           /* SIOCGIWRANGE */
2343         (iw_handler) NULL,                      /* SIOCSIWPRIV */
2344         (iw_handler) NULL,                      /* SIOCGIWPRIV */
2345         (iw_handler) NULL,                      /* SIOCSIWSTATS */
2346         (iw_handler) NULL,                      /* SIOCGIWSTATS */
2347         (iw_handler) NULL,                      /* SIOCSIWSPY */
2348         (iw_handler) NULL,                      /* SIOCGIWSPY */
2349         (iw_handler) NULL,                      /* -- hole -- */
2350         (iw_handler) NULL,                      /* -- hole -- */
2351         (iw_handler) atmel_set_wap,             /* SIOCSIWAP */
2352         (iw_handler) atmel_get_wap,             /* SIOCGIWAP */
2353         (iw_handler) NULL,                      /* -- hole -- */
2354         (iw_handler) NULL,                      /* SIOCGIWAPLIST */
2355         (iw_handler) atmel_set_scan,            /* SIOCSIWSCAN */
2356         (iw_handler) atmel_get_scan,            /* SIOCGIWSCAN */
2357         (iw_handler) atmel_set_essid,           /* SIOCSIWESSID */
2358         (iw_handler) atmel_get_essid,           /* SIOCGIWESSID */
2359         (iw_handler) NULL,                      /* SIOCSIWNICKN */
2360         (iw_handler) NULL,                      /* SIOCGIWNICKN */
2361         (iw_handler) NULL,                      /* -- hole -- */
2362         (iw_handler) NULL,                      /* -- hole -- */
2363         (iw_handler) atmel_set_rate,            /* SIOCSIWRATE */
2364         (iw_handler) atmel_get_rate,            /* SIOCGIWRATE */
2365         (iw_handler) atmel_set_rts,             /* SIOCSIWRTS */
2366         (iw_handler) atmel_get_rts,             /* SIOCGIWRTS */
2367         (iw_handler) atmel_set_frag,            /* SIOCSIWFRAG */
2368         (iw_handler) atmel_get_frag,            /* SIOCGIWFRAG */
2369         (iw_handler) NULL,                      /* SIOCSIWTXPOW */
2370         (iw_handler) NULL,                      /* SIOCGIWTXPOW */
2371         (iw_handler) atmel_set_retry,           /* SIOCSIWRETRY */
2372         (iw_handler) atmel_get_retry,           /* SIOCGIWRETRY */
2373         (iw_handler) atmel_set_encode,          /* SIOCSIWENCODE */
2374         (iw_handler) atmel_get_encode,          /* SIOCGIWENCODE */
2375         (iw_handler) atmel_set_power,           /* SIOCSIWPOWER */
2376         (iw_handler) atmel_get_power,           /* SIOCGIWPOWER */
2377 };
2378
2379
2380 static const iw_handler         atmel_private_handler[] =
2381 {
2382         NULL,                           /* SIOCIWFIRSTPRIV */
2383 };
2384
2385 typedef struct atmel_priv_ioctl {
2386         char id[32];
2387         unsigned char __user *data;             
2388         unsigned short len;             
2389 } atmel_priv_ioctl;
2390
2391         
2392 #define ATMELFWL SIOCIWFIRSTPRIV
2393 #define ATMELIDIFC ATMELFWL + 1
2394 #define ATMELRD ATMELFWL + 2
2395 #define ATMELMAGIC 0x51807 
2396 #define REGDOMAINSZ 20
2397
2398 static const struct iw_priv_args atmel_private_args[] = {
2399 /*{ cmd,         set_args,                            get_args, name } */
2400   { ATMELFWL, IW_PRIV_TYPE_BYTE | IW_PRIV_SIZE_FIXED | sizeof (atmel_priv_ioctl), IW_PRIV_TYPE_NONE, "atmelfwl" },
2401   { ATMELIDIFC, IW_PRIV_TYPE_NONE, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "atmelidifc" },
2402   { ATMELRD, IW_PRIV_TYPE_CHAR | REGDOMAINSZ, IW_PRIV_TYPE_NONE, "regdomain" },
2403 };
2404
2405 static const struct iw_handler_def      atmel_handler_def =
2406 {
2407         .num_standard   = sizeof(atmel_handler)/sizeof(iw_handler),
2408         .num_private    = sizeof(atmel_private_handler)/sizeof(iw_handler), 
2409         .num_private_args = sizeof(atmel_private_args)/sizeof(struct iw_priv_args), 
2410         .standard       = (iw_handler *) atmel_handler,
2411         .private        = (iw_handler *) atmel_private_handler, 
2412         .private_args   = (struct iw_priv_args *) atmel_private_args,
2413         .get_wireless_stats = atmel_get_wireless_stats
2414 };
2415
2416 static int atmel_ioctl(struct net_device *dev, struct ifreq *rq, int cmd)
2417 {
2418         int i, rc = 0;
2419         struct atmel_private *priv = netdev_priv(dev);
2420         atmel_priv_ioctl com;
2421         struct iwreq *wrq = (struct iwreq *) rq;
2422         unsigned char *new_firmware;
2423         char domain[REGDOMAINSZ+1];
2424
2425         switch (cmd) {
2426         case ATMELIDIFC:
2427                 wrq->u.param.value = ATMELMAGIC;                
2428                 break;
2429         
2430         case ATMELFWL:
2431                 if (copy_from_user(&com, rq->ifr_data, sizeof(com))) {
2432                         rc = -EFAULT;
2433                         break;
2434                 }
2435
2436                 if (!capable(CAP_NET_ADMIN)) {
2437                         rc = -EPERM;
2438                         break;
2439                 }
2440
2441                 if (!(new_firmware = kmalloc(com.len, GFP_KERNEL))) {
2442                         rc = -ENOMEM;
2443                         break;
2444                 }
2445
2446                 if (copy_from_user(new_firmware, com.data, com.len)) {
2447                         kfree(new_firmware);
2448                         rc = -EFAULT;
2449                         break;
2450                 }
2451
2452                 kfree(priv->firmware);
2453                 
2454                 priv->firmware = new_firmware;
2455                 priv->firmware_length = com.len;
2456                 strncpy(priv->firmware_id, com.id, 31);
2457                 priv->firmware_id[31] = '\0';
2458                 break;
2459
2460         case ATMELRD:
2461                 if (copy_from_user(domain, rq->ifr_data, REGDOMAINSZ)) {
2462                         rc = -EFAULT;
2463                         break;
2464                 }
2465                 
2466                 if (!capable(CAP_NET_ADMIN)) {
2467                         rc = -EPERM;
2468                         break;
2469                 }
2470
2471                 domain[REGDOMAINSZ] = 0;
2472                 rc = -EINVAL;
2473                 for (i = 0; i < sizeof(channel_table)/sizeof(channel_table[0]); i++) {
2474                         /* strcasecmp doesn't exist in the library */
2475                         char *a = channel_table[i].name;
2476                         char *b = domain;
2477                         while (*a) {
2478                                 char c1 = *a++;
2479                                 char c2 = *b++;
2480                                 if (tolower(c1) != tolower(c2))
2481                                         break;
2482                         }
2483                         if (!*a && !*b) {
2484                                 priv->config_reg_domain = channel_table[i].reg_domain;
2485                                 rc = 0;
2486                         }
2487                 }
2488                 
2489                 if (rc == 0 &&  priv->station_state != STATION_STATE_DOWN)
2490                         rc = atmel_open(dev);
2491                 break;
2492                 
2493         default:
2494                 rc = -EOPNOTSUPP;
2495         }
2496         
2497         return rc;
2498 }
2499
2500 struct auth_body {
2501         u16 alg;
2502         u16 trans_seq;
2503         u16 status;
2504         u8 el_id;
2505         u8 chall_text_len;
2506         u8 chall_text[253];
2507 }; 
2508
2509 static void atmel_enter_state(struct atmel_private *priv, int new_state)
2510 {
2511         int old_state = priv->station_state;
2512                 
2513         if (new_state == old_state)
2514                 return;
2515         
2516         priv->station_state = new_state;
2517                 
2518         if (new_state == STATION_STATE_READY) {
2519                 netif_start_queue(priv->dev);
2520                 netif_carrier_on(priv->dev);
2521         }
2522
2523         if (old_state == STATION_STATE_READY) {
2524                 netif_carrier_off(priv->dev);
2525                 if (netif_running(priv->dev))
2526                         netif_stop_queue(priv->dev);
2527                 priv->last_beacon_timestamp = 0;
2528         }
2529 }
2530
2531 static void atmel_scan(struct atmel_private *priv, int specific_ssid)
2532 {
2533         struct {
2534                 u8 BSSID[6];
2535                 u8 SSID[MAX_SSID_LENGTH];
2536                 u8 scan_type;
2537                 u8 channel;
2538                 u16 BSS_type;
2539                 u16 min_channel_time;
2540                 u16 max_channel_time;
2541                 u8 options;
2542                 u8 SSID_size;
2543         } cmd;
2544         
2545         memset(cmd.BSSID, 0xff, 6);
2546
2547         if (priv->fast_scan) {
2548                 cmd.SSID_size = priv->SSID_size;
2549                 memcpy(cmd.SSID, priv->SSID, priv->SSID_size);
2550                 cmd.min_channel_time = cpu_to_le16(10);
2551                 cmd.max_channel_time = cpu_to_le16(50);
2552         } else {
2553                 priv->BSS_list_entries = 0;
2554                 cmd.SSID_size = 0;
2555                 cmd.min_channel_time = cpu_to_le16(10);
2556                 cmd.max_channel_time = cpu_to_le16(120);
2557         }
2558         
2559         cmd.options = 0;
2560         
2561         if (!specific_ssid)
2562                 cmd.options |= SCAN_OPTIONS_SITE_SURVEY;
2563         
2564         cmd.channel = (priv->channel & 0x7f); 
2565         cmd.scan_type = SCAN_TYPE_ACTIVE;
2566         cmd.BSS_type = cpu_to_le16(priv->operating_mode == IW_MODE_ADHOC ? 
2567                 BSS_TYPE_AD_HOC : BSS_TYPE_INFRASTRUCTURE);
2568         
2569         atmel_send_command(priv, CMD_Scan, &cmd, sizeof(cmd));
2570
2571         /* This must come after all hardware access to avoid being messed up
2572            by stuff happening in interrupt context after we leave STATE_DOWN */
2573         atmel_enter_state(priv, STATION_STATE_SCANNING);
2574 }
2575
2576 static void join(struct atmel_private *priv, int type)
2577 {
2578         struct {
2579                 u8 BSSID[6];
2580                 u8 SSID[MAX_SSID_LENGTH];
2581                 u8 BSS_type; /* this is a short in a scan command - weird */
2582                 u8 channel;
2583                 u16 timeout;
2584                 u8 SSID_size;
2585                 u8 reserved;
2586         } cmd;
2587
2588         cmd.SSID_size = priv->SSID_size;
2589         memcpy(cmd.SSID, priv->SSID, priv->SSID_size);
2590         memcpy(cmd.BSSID, priv->CurrentBSSID, 6);
2591         cmd.channel = (priv->channel & 0x7f);
2592         cmd.BSS_type = type;
2593         cmd.timeout = cpu_to_le16(2000);
2594
2595         atmel_send_command(priv, CMD_Join, &cmd, sizeof(cmd));
2596 }
2597
2598
2599 static void start(struct atmel_private *priv, int type)
2600 {
2601         struct {
2602                 u8 BSSID[6];
2603                 u8 SSID[MAX_SSID_LENGTH];
2604                 u8 BSS_type;                                
2605                 u8 channel;
2606                 u8 SSID_size;
2607                 u8 reserved[3];
2608         } cmd;
2609
2610         cmd.SSID_size = priv->SSID_size;
2611         memcpy(cmd.SSID, priv->SSID, priv->SSID_size);
2612         memcpy(cmd.BSSID, priv->BSSID, 6);
2613         cmd.BSS_type = type;
2614         cmd.channel = (priv->channel & 0x7f);
2615
2616         atmel_send_command(priv, CMD_Start, &cmd, sizeof(cmd)); 
2617 }
2618
2619 static void handle_beacon_probe(struct atmel_private *priv, u16 capability, u8 channel)
2620 {
2621         int rejoin = 0;
2622         int new = capability  & C80211_MGMT_CAPABILITY_ShortPreamble ? 
2623                 SHORT_PREAMBLE : LONG_PREAMBLE;
2624
2625         if (priv->preamble != new) {
2626                 priv->preamble = new;
2627                 rejoin = 1;
2628                 atmel_set_mib8(priv, Local_Mib_Type, LOCAL_MIB_PREAMBLE_TYPE, new);
2629         }
2630                 
2631         if (priv->channel != channel) {
2632                 priv->channel = channel;
2633                 rejoin = 1;
2634                 atmel_set_mib8(priv, Phy_Mib_Type, PHY_MIB_CHANNEL_POS, channel);
2635         }
2636         
2637         if (rejoin) {
2638                 priv->station_is_associated = 0;
2639                 atmel_enter_state(priv, STATION_STATE_JOINNING);
2640                 
2641                 if (priv->operating_mode == IW_MODE_INFRA)
2642                         join(priv, BSS_TYPE_INFRASTRUCTURE);
2643                 else 
2644                         join(priv, BSS_TYPE_AD_HOC);
2645         } 
2646 }
2647
2648  
2649 static void send_authentication_request(struct atmel_private *priv, u8 *challenge, int challenge_len)
2650 {
2651         struct ieee80211_hdr_4addr header;
2652         struct auth_body auth;
2653         
2654         header.frame_ctl = cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_AUTH); 
2655         header.duration_id      = cpu_to_le16(0x8000);  
2656         header.seq_ctl = 0;
2657         memcpy(header.addr1, priv->CurrentBSSID, 6);
2658         memcpy(header.addr2, priv->dev->dev_addr, 6);
2659         memcpy(header.addr3, priv->CurrentBSSID, 6);
2660         
2661         if (priv->wep_is_on) {
2662                 auth.alg = cpu_to_le16(C80211_MGMT_AAN_SHAREDKEY); 
2663                 /* no WEP for authentication frames with TrSeqNo 1 */
2664                 if (priv->CurrentAuthentTransactionSeqNum != 1)
2665                         header.frame_ctl |=  cpu_to_le16(IEEE80211_FCTL_PROTECTED);
2666         } else {
2667                 auth.alg = cpu_to_le16(C80211_MGMT_AAN_OPENSYSTEM);
2668         }
2669
2670         auth.status = 0;
2671         auth.trans_seq = cpu_to_le16(priv->CurrentAuthentTransactionSeqNum);
2672         priv->ExpectedAuthentTransactionSeqNum = priv->CurrentAuthentTransactionSeqNum+1; 
2673         priv->CurrentAuthentTransactionSeqNum += 2;
2674         
2675         if (challenge_len != 0) {
2676                 auth.el_id = 16; /* challenge_text */
2677                 auth.chall_text_len = challenge_len;
2678                 memcpy(auth.chall_text, challenge, challenge_len);
2679                 atmel_transmit_management_frame(priv, &header, (u8 *)&auth, 8 + challenge_len);
2680         } else {
2681                 atmel_transmit_management_frame(priv, &header, (u8 *)&auth, 6);
2682         }
2683 }
2684
2685 static void send_association_request(struct atmel_private *priv, int is_reassoc)
2686 {
2687         u8 *ssid_el_p;
2688         int bodysize;
2689         struct ieee80211_hdr_4addr header;
2690         struct ass_req_format {
2691                 u16 capability;
2692                 u16 listen_interval; 
2693                 u8 ap[6]; /* nothing after here directly accessible */
2694                 u8 ssid_el_id;
2695                 u8 ssid_len;
2696                 u8 ssid[MAX_SSID_LENGTH];
2697                 u8 sup_rates_el_id;
2698                 u8 sup_rates_len;
2699                 u8 rates[4];
2700         } body;
2701                 
2702         header.frame_ctl = cpu_to_le16(IEEE80211_FTYPE_MGMT | 
2703                 (is_reassoc ? IEEE80211_STYPE_REASSOC_REQ : IEEE80211_STYPE_ASSOC_REQ));
2704         header.duration_id = cpu_to_le16(0x8000);
2705         header.seq_ctl = 0;
2706
2707         memcpy(header.addr1, priv->CurrentBSSID, 6); 
2708         memcpy(header.addr2, priv->dev->dev_addr, 6);
2709         memcpy(header.addr3, priv->CurrentBSSID, 6); 
2710
2711         body.capability = cpu_to_le16(C80211_MGMT_CAPABILITY_ESS);
2712         if (priv->wep_is_on)
2713                 body.capability |= cpu_to_le16(C80211_MGMT_CAPABILITY_Privacy);
2714         if (priv->preamble == SHORT_PREAMBLE)
2715                 body.capability |= cpu_to_le16(C80211_MGMT_CAPABILITY_ShortPreamble);
2716
2717         body.listen_interval = cpu_to_le16(priv->listen_interval * priv->beacon_period);
2718         
2719         /* current AP address - only in reassoc frame */
2720         if (is_reassoc) {
2721                 memcpy(body.ap,  priv->CurrentBSSID, 6);
2722                 ssid_el_p = (u8 *)&body.ssid_el_id;
2723                 bodysize = 18 + priv->SSID_size;
2724         } else {
2725                 ssid_el_p = (u8 *)&body.ap[0];
2726                 bodysize = 12 + priv->SSID_size;
2727         }
2728                 
2729         ssid_el_p[0]= C80211_MGMT_ElementID_SSID;
2730         ssid_el_p[1] = priv->SSID_size;
2731         memcpy(ssid_el_p + 2, priv->SSID, priv->SSID_size);
2732         ssid_el_p[2 + priv->SSID_size] = C80211_MGMT_ElementID_SupportedRates;
2733         ssid_el_p[3 + priv->SSID_size] = 4; /* len of suported rates */
2734         memcpy(ssid_el_p + 4 + priv->SSID_size, atmel_basic_rates, 4);
2735
2736         atmel_transmit_management_frame(priv, &header, (void *)&body, bodysize);
2737 }
2738
2739 static int is_frame_from_current_bss(struct atmel_private *priv, struct ieee80211_hdr_4addr *header)
2740 {
2741         if (le16_to_cpu(header->frame_ctl) & IEEE80211_FCTL_FROMDS)
2742                 return memcmp(header->addr3, priv->CurrentBSSID, 6) == 0;
2743         else
2744                 return memcmp(header->addr2, priv->CurrentBSSID, 6) == 0;
2745 }
2746
2747 static int retrieve_bss(struct atmel_private *priv)
2748 {
2749         int i;
2750         int max_rssi = -128;
2751         int max_index = -1;
2752         
2753         if (priv->BSS_list_entries == 0)
2754                 return -1;
2755                         
2756         if (priv->connect_to_any_BSS) {
2757                 /* Select a BSS with the max-RSSI but of the same type and of the same WEP mode
2758                    and that it is not marked as 'bad' (i.e. we had previously failed to connect to
2759                    this BSS with the settings that we currently use) */
2760                 priv->current_BSS = 0;
2761                 for(i=0; i<priv->BSS_list_entries; i++) { 
2762                         if (priv->operating_mode == priv->BSSinfo[i].BSStype &&
2763                             ((!priv->wep_is_on && !priv->BSSinfo[i].UsingWEP) || 
2764                              (priv->wep_is_on && priv->BSSinfo[i].UsingWEP)) &&
2765                             !(priv->BSSinfo[i].channel & 0x80)) {
2766                                 max_rssi = priv->BSSinfo[i].RSSI;
2767                                 priv->current_BSS = max_index = i;
2768                         }
2769                         
2770                 }
2771                 return max_index;
2772         }
2773                 
2774         for(i=0; i<priv->BSS_list_entries; i++) {
2775                 if (priv->SSID_size == priv->BSSinfo[i].SSIDsize &&
2776                     memcmp(priv->SSID, priv->BSSinfo[i].SSID, priv->SSID_size) == 0 &&
2777                     priv->operating_mode == priv->BSSinfo[i].BSStype &&
2778                     atmel_validate_channel(priv, priv->BSSinfo[i].channel) == 0) {
2779                         if (priv->BSSinfo[i].RSSI >= max_rssi) {
2780                                 max_rssi = priv->BSSinfo[i].RSSI;
2781                                 max_index = i;
2782                         }
2783                 }
2784         }
2785         return max_index;
2786 }
2787
2788
2789 static void store_bss_info(struct atmel_private *priv, struct ieee80211_hdr_4addr *header,
2790                            u16 capability, u16 beacon_period, u8 channel, u8 rssi, 
2791                            u8 ssid_len, u8 *ssid, int is_beacon)
2792 {
2793         u8 *bss = capability & C80211_MGMT_CAPABILITY_ESS ? header->addr2 : header->addr3;
2794         int i, index;
2795                 
2796         for (index = -1, i = 0; i < priv->BSS_list_entries; i++) 
2797                 if (memcmp(bss, priv->BSSinfo[i].BSSID, 6) == 0) 
2798                         index = i;
2799
2800         /* If we process a probe and an entry from this BSS exists 
2801            we will update the BSS entry with the info from this BSS.
2802            If we process a beacon we will only update RSSI */
2803
2804         if (index == -1) {
2805                 if (priv->BSS_list_entries == MAX_BSS_ENTRIES)
2806                         return;
2807                 index = priv->BSS_list_entries++;
2808                 memcpy(priv->BSSinfo[index].BSSID, bss, 6);
2809                 priv->BSSinfo[index].RSSI = rssi;
2810         } else {
2811                 if (rssi > priv->BSSinfo[index].RSSI)
2812                         priv->BSSinfo[index].RSSI = rssi;
2813                 if (is_beacon)
2814                         return;
2815         }
2816
2817         priv->BSSinfo[index].channel = channel;
2818         priv->BSSinfo[index].beacon_period = beacon_period;
2819         priv->BSSinfo[index].UsingWEP = capability & C80211_MGMT_CAPABILITY_Privacy;
2820         memcpy(priv->BSSinfo[index].SSID, ssid, ssid_len);
2821         priv->BSSinfo[index].SSIDsize = ssid_len;
2822
2823         if (capability & C80211_MGMT_CAPABILITY_IBSS)
2824                 priv->BSSinfo[index].BSStype = IW_MODE_ADHOC;
2825         else if (capability & C80211_MGMT_CAPABILITY_ESS)
2826                 priv->BSSinfo[index].BSStype =IW_MODE_INFRA;
2827         
2828         priv->BSSinfo[index].preamble = capability  & C80211_MGMT_CAPABILITY_ShortPreamble ? 
2829                 SHORT_PREAMBLE : LONG_PREAMBLE;
2830 }
2831
2832 static void authenticate(struct atmel_private *priv, u16 frame_len)
2833 {
2834         struct auth_body *auth = (struct auth_body *)priv->rx_buf;
2835         u16 status = le16_to_cpu(auth->status);
2836         u16 trans_seq_no = le16_to_cpu(auth->trans_seq);
2837         
2838         if (status == C80211_MGMT_SC_Success && !priv->wep_is_on) { 
2839                 /* no WEP */
2840                 if (priv->station_was_associated) {
2841                         atmel_enter_state(priv, STATION_STATE_REASSOCIATING);
2842                         send_association_request(priv, 1);
2843                         return;
2844                 } else {
2845                         atmel_enter_state(priv, STATION_STATE_ASSOCIATING);
2846                         send_association_request(priv, 0);
2847                         return;
2848                 } 
2849         }
2850                 
2851         if (status == C80211_MGMT_SC_Success && priv->wep_is_on) { 
2852                 /* WEP */
2853                 if (trans_seq_no != priv->ExpectedAuthentTransactionSeqNum)
2854                         return;
2855                                 
2856                 if (trans_seq_no == 0x0002 &&
2857                     auth->el_id == C80211_MGMT_ElementID_ChallengeText) {
2858                         send_authentication_request(priv, auth->chall_text, auth->chall_text_len);
2859                         return;
2860                 }
2861                 
2862                 if (trans_seq_no == 0x0004) {
2863                         if(priv->station_was_associated) {
2864                                 atmel_enter_state(priv, STATION_STATE_REASSOCIATING);
2865                                 send_association_request(priv, 1);
2866                                 return;
2867                         } else {
2868                                 atmel_enter_state(priv, STATION_STATE_ASSOCIATING);
2869                                 send_association_request(priv, 0);
2870                                 return;
2871                         } 
2872                 }
2873         }                       
2874         
2875         if (status == C80211_MGMT_SC_AuthAlgNotSupported && priv->connect_to_any_BSS) {
2876                 int bss_index;
2877                 
2878                 priv->BSSinfo[(int)(priv->current_BSS)].channel |= 0x80;
2879                 
2880                 if ((bss_index  = retrieve_bss(priv)) != -1) {
2881                         atmel_join_bss(priv, bss_index);
2882                         return;
2883                 }
2884         }
2885         
2886         
2887         priv->AuthenticationRequestRetryCnt = 0;
2888         atmel_enter_state(priv,  STATION_STATE_MGMT_ERROR);
2889         priv->station_is_associated = 0;
2890 }
2891
2892 static void associate(struct atmel_private *priv, u16 frame_len, u16 subtype)
2893 {
2894         struct ass_resp_format {
2895                 u16 capability;
2896                 u16 status;
2897                 u16 ass_id;
2898                 u8 el_id;
2899                 u8 length;
2900                 u8 rates[4];
2901         } *ass_resp = (struct ass_resp_format *)priv->rx_buf;
2902         
2903         u16 status = le16_to_cpu(ass_resp->status);
2904         u16 ass_id = le16_to_cpu(ass_resp->ass_id);
2905         u16 rates_len = ass_resp->length > 4 ? 4 : ass_resp->length;
2906         
2907         if (frame_len < 8 + rates_len)
2908                 return;
2909         
2910         if (status == C80211_MGMT_SC_Success) {
2911                 if (subtype == C80211_SUBTYPE_MGMT_ASS_RESPONSE)
2912                         priv->AssociationRequestRetryCnt = 0;
2913                 else
2914                         priv->ReAssociationRequestRetryCnt = 0;
2915                 
2916                 atmel_set_mib16(priv, Mac_Mgmt_Mib_Type, MAC_MGMT_MIB_STATION_ID_POS, ass_id & 0x3fff);
2917                 atmel_set_mib(priv, Phy_Mib_Type, PHY_MIB_RATE_SET_POS, ass_resp->rates, rates_len);
2918                 if (priv->power_mode == 0) {
2919                         priv->listen_interval = 1;
2920                         atmel_set_mib8(priv, Mac_Mgmt_Mib_Type, MAC_MGMT_MIB_PS_MODE_POS,  ACTIVE_MODE);
2921                         atmel_set_mib16(priv, Mac_Mgmt_Mib_Type, MAC_MGMT_MIB_LISTEN_INTERVAL_POS, 1);
2922                 } else {
2923                         priv->listen_interval = 2;
2924                         atmel_set_mib8(priv, Mac_Mgmt_Mib_Type, MAC_MGMT_MIB_PS_MODE_POS,  PS_MODE);
2925                         atmel_set_mib16(priv, Mac_Mgmt_Mib_Type, MAC_MGMT_MIB_LISTEN_INTERVAL_POS, 2);
2926                 }
2927                 
2928                 priv->station_is_associated = 1;
2929                 priv->station_was_associated = 1;
2930                 atmel_enter_state(priv, STATION_STATE_READY);
2931                 return;
2932         }
2933         
2934         if (subtype == C80211_SUBTYPE_MGMT_ASS_RESPONSE &&
2935             status != C80211_MGMT_SC_AssDeniedBSSRate &&
2936             status != C80211_MGMT_SC_SupportCapabilities &&
2937             priv->AssociationRequestRetryCnt < MAX_ASSOCIATION_RETRIES) {
2938                 mod_timer(&priv->management_timer, jiffies + MGMT_JIFFIES);
2939                 priv->AssociationRequestRetryCnt++;
2940                 send_association_request(priv, 0);
2941                 return;
2942         }
2943                 
2944         if (subtype == C80211_SUBTYPE_MGMT_REASS_RESPONSE &&
2945             status != C80211_MGMT_SC_AssDeniedBSSRate &&
2946             status != C80211_MGMT_SC_SupportCapabilities &&
2947             priv->AssociationRequestRetryCnt < MAX_ASSOCIATION_RETRIES) {
2948                 mod_timer(&priv->management_timer, jiffies + MGMT_JIFFIES);
2949                 priv->ReAssociationRequestRetryCnt++;
2950                 send_association_request(priv, 1);
2951                 return;
2952         }
2953         
2954         atmel_enter_state(priv,  STATION_STATE_MGMT_ERROR);
2955         priv->station_is_associated = 0;
2956         
2957         if(priv->connect_to_any_BSS) {
2958                 int bss_index;
2959                 priv->BSSinfo[(int)(priv->current_BSS)].channel |= 0x80;
2960                 
2961                 if ((bss_index = retrieve_bss(priv)) != -1) 
2962                         atmel_join_bss(priv, bss_index);
2963                 
2964         }
2965 }
2966
2967 void atmel_join_bss(struct atmel_private *priv, int bss_index)
2968 {
2969         struct bss_info *bss =  &priv->BSSinfo[bss_index];
2970
2971         memcpy(priv->CurrentBSSID, bss->BSSID, 6);
2972         memcpy(priv->SSID, bss->SSID, priv->SSID_size = bss->SSIDsize);
2973
2974         /* The WPA stuff cares about the current AP address */
2975         if (priv->use_wpa)
2976                 build_wpa_mib(priv);
2977         
2978         /* When switching to AdHoc turn OFF Power Save if needed */
2979
2980         if (bss->BSStype == IW_MODE_ADHOC &&
2981             priv->operating_mode != IW_MODE_ADHOC &&
2982             priv->power_mode) {
2983                 priv->power_mode = 0;
2984                 priv->listen_interval = 1;
2985                 atmel_set_mib8(priv, Mac_Mgmt_Mib_Type, MAC_MGMT_MIB_PS_MODE_POS,  ACTIVE_MODE);
2986                 atmel_set_mib16(priv, Mac_Mgmt_Mib_Type, MAC_MGMT_MIB_LISTEN_INTERVAL_POS, 1);
2987         }
2988                 
2989         priv->operating_mode = bss->BSStype;
2990         priv->channel = bss->channel & 0x7f;    
2991         priv->beacon_period = bss->beacon_period;
2992         
2993         if (priv->preamble != bss->preamble) {
2994                 priv->preamble = bss->preamble;
2995                 atmel_set_mib8(priv, Local_Mib_Type, LOCAL_MIB_PREAMBLE_TYPE, bss->preamble);
2996         }
2997         
2998         if (!priv->wep_is_on && bss->UsingWEP) {
2999                 atmel_enter_state(priv, STATION_STATE_MGMT_ERROR);
3000                 priv->station_is_associated = 0;
3001                 return;
3002         }
3003                 
3004         if (priv->wep_is_on && !bss->UsingWEP) {
3005                 atmel_enter_state(priv, STATION_STATE_MGMT_ERROR);
3006                 priv->station_is_associated = 0;
3007                 return;
3008         }
3009
3010         atmel_enter_state(priv, STATION_STATE_JOINNING);
3011         
3012         if (priv->operating_mode == IW_MODE_INFRA)
3013                 join(priv, BSS_TYPE_INFRASTRUCTURE);
3014         else 
3015                 join(priv, BSS_TYPE_AD_HOC);
3016 }
3017
3018
3019 static void restart_search(struct atmel_private *priv)
3020 {
3021         int bss_index;
3022         
3023         if (!priv->connect_to_any_BSS) {
3024                 atmel_scan(priv, 1);
3025         } else {
3026                 priv->BSSinfo[(int)(priv->current_BSS)].channel |= 0x80;
3027                 
3028                 if ((bss_index = retrieve_bss(priv)) != -1) 
3029                         atmel_join_bss(priv, bss_index);
3030                 else
3031                         atmel_scan(priv, 0);
3032                 
3033         } 
3034 }       
3035
3036 static void smooth_rssi(struct atmel_private *priv, u8 rssi)
3037 {
3038         u8 old = priv->wstats.qual.level;
3039         u8 max_rssi = 42; /* 502-rmfd-revd max by experiment, default for now */
3040
3041         switch (priv->firmware_type) {
3042                 case ATMEL_FW_TYPE_502E:
3043                         max_rssi = 63; /* 502-rmfd-reve max by experiment */
3044                         break;
3045                 default:
3046                         break;
3047         }
3048
3049         rssi = rssi * 100 / max_rssi;
3050         if((rssi + old) % 2)
3051                 priv->wstats.qual.level =  ((rssi + old)/2) + 1;
3052         else
3053                 priv->wstats.qual.level =  ((rssi + old)/2);            
3054         priv->wstats.qual.updated |= IW_QUAL_LEVEL_UPDATED;
3055         priv->wstats.qual.updated &= ~IW_QUAL_LEVEL_INVALID;
3056 }
3057
3058 static void atmel_smooth_qual(struct atmel_private *priv)
3059 {
3060         unsigned long time_diff = (jiffies - priv->last_qual)/HZ;
3061         while (time_diff--) {
3062                 priv->last_qual += HZ;
3063                 priv->wstats.qual.qual = priv->wstats.qual.qual/2;
3064                 priv->wstats.qual.qual += 
3065                         priv->beacons_this_sec * priv->beacon_period * (priv->wstats.qual.level + 100) / 4000;
3066                 priv->beacons_this_sec = 0;
3067         }
3068         priv->wstats.qual.updated |= IW_QUAL_QUAL_UPDATED;
3069         priv->wstats.qual.updated &= ~IW_QUAL_QUAL_INVALID;
3070 }
3071
3072 /* deals with incoming managment frames. */
3073 static void atmel_management_frame(struct atmel_private *priv, struct ieee80211_hdr_4addr *header, 
3074                       u16 frame_len, u8 rssi)
3075 {
3076         u16 subtype;
3077         
3078         switch (subtype = le16_to_cpu(header->frame_ctl) & IEEE80211_FCTL_STYPE) {
3079         case C80211_SUBTYPE_MGMT_BEACON :
3080         case C80211_SUBTYPE_MGMT_ProbeResponse:
3081                 
3082                 /* beacon frame has multiple variable-length fields -
3083                    never let an engineer loose with a data structure design. */
3084                 {
3085                         struct beacon_format {
3086                                 u64 timestamp;
3087                                 u16 interval;
3088                                 u16 capability;
3089                                 u8 ssid_el_id;
3090                                 u8 ssid_length;
3091                                 /* ssid here */
3092                                 u8 rates_el_id;
3093                                 u8 rates_length;
3094                                 /* rates here */
3095                                 u8 ds_el_id;
3096                                 u8 ds_length;
3097                                 /* ds here */
3098                         } *beacon = (struct beacon_format *)priv->rx_buf;
3099                         
3100                         u8 channel, rates_length, ssid_length;
3101                         u64 timestamp = le64_to_cpu(beacon->timestamp);
3102                         u16 beacon_interval = le16_to_cpu(beacon->interval);
3103                         u16 capability = le16_to_cpu(beacon->capability);
3104                         u8 *beaconp = priv->rx_buf;
3105                         ssid_length = beacon->ssid_length;
3106                         /* this blows chunks. */
3107                         if (frame_len < 14 || frame_len < ssid_length + 15) 
3108                                 return;
3109                         rates_length = beaconp[beacon->ssid_length + 15];
3110                         if (frame_len < ssid_length + rates_length + 18)
3111                                 return;
3112                         if (ssid_length >  MAX_SSID_LENGTH)
3113                                 return;
3114                         channel = beaconp[ssid_length + rates_length + 18];
3115                        
3116                         if (priv->station_state == STATION_STATE_READY) {
3117                                 smooth_rssi(priv, rssi);
3118                                 if (is_frame_from_current_bss(priv, header)) { 
3119                                         priv->beacons_this_sec++;
3120                                         atmel_smooth_qual(priv);
3121                                         if (priv->last_beacon_timestamp) {
3122                                                 /* Note truncate this to 32 bits - kernel can't divide a long long */
3123                                                 u32 beacon_delay = timestamp - priv->last_beacon_timestamp;
3124                                                 int beacons = beacon_delay / (beacon_interval * 1000);
3125                                                 if (beacons > 1)
3126                                                         priv->wstats.miss.beacon += beacons - 1;
3127                                         }
3128                                         priv->last_beacon_timestamp = timestamp;
3129                                         handle_beacon_probe(priv, capability, channel);
3130                                 }
3131                         }
3132                         
3133                         if (priv->station_state == STATION_STATE_SCANNING ) 
3134                                 store_bss_info(priv, header, capability, beacon_interval, channel,
3135                                                rssi, ssid_length, &beacon->rates_el_id,
3136                                                subtype == C80211_SUBTYPE_MGMT_BEACON) ;
3137                 }
3138                 break;
3139                 
3140         case C80211_SUBTYPE_MGMT_Authentication:
3141
3142                 if (priv->station_state == STATION_STATE_AUTHENTICATING)
3143                         authenticate(priv, frame_len);
3144         
3145                 break;
3146                 
3147         case C80211_SUBTYPE_MGMT_ASS_RESPONSE:
3148         case C80211_SUBTYPE_MGMT_REASS_RESPONSE:
3149                 
3150                 if (priv->station_state == STATION_STATE_ASSOCIATING || 
3151                     priv->station_state == STATION_STATE_REASSOCIATING)
3152                         associate(priv, frame_len, subtype);
3153                 
3154                 break;
3155
3156         case C80211_SUBTYPE_MGMT_DISASSOSIATION:
3157                 if (priv->station_is_associated && 
3158                     priv->operating_mode == IW_MODE_INFRA && 
3159                     is_frame_from_current_bss(priv, header)) {
3160                         priv->station_was_associated = 0;
3161                         priv->station_is_associated = 0;
3162                         
3163                         atmel_enter_state(priv, STATION_STATE_JOINNING);
3164                         join(priv, BSS_TYPE_INFRASTRUCTURE);
3165                 }
3166                 
3167                 break;
3168
3169         case C80211_SUBTYPE_MGMT_Deauthentication:
3170                 if (priv->operating_mode == IW_MODE_INFRA &&
3171                     is_frame_from_current_bss(priv, header)) {
3172                         priv->station_was_associated = 0;
3173
3174                         atmel_enter_state(priv, STATION_STATE_JOINNING);
3175                         join(priv, BSS_TYPE_INFRASTRUCTURE);
3176                 }
3177                 
3178                 break;
3179         }
3180 }
3181
3182 /* run when timer expires */
3183 static void atmel_management_timer(u_long a)
3184 {
3185   struct net_device *dev = (struct net_device *) a;
3186   struct atmel_private *priv = netdev_priv(dev);
3187   unsigned long flags;
3188   
3189   /* Check if the card has been yanked. */
3190   if (priv->card && priv->present_callback && 
3191       !(*priv->present_callback)(priv->card))
3192           return;
3193   
3194   spin_lock_irqsave(&priv->irqlock, flags);
3195
3196   switch (priv->station_state) {
3197           
3198   case STATION_STATE_AUTHENTICATING:
3199           if (priv->AuthenticationRequestRetryCnt >= MAX_AUTHENTICATION_RETRIES) {
3200                   atmel_enter_state(priv, STATION_STATE_MGMT_ERROR);
3201                   priv->station_is_associated = 0;
3202                   priv->AuthenticationRequestRetryCnt = 0;
3203                   restart_search(priv);
3204           } else {
3205                   priv->AuthenticationRequestRetryCnt++;
3206                   priv->CurrentAuthentTransactionSeqNum = 0x0001;
3207                   mod_timer(&priv->management_timer, jiffies + MGMT_JIFFIES);
3208                   send_authentication_request(priv, NULL, 0);
3209           }
3210           
3211           break;
3212
3213   case STATION_STATE_ASSOCIATING:
3214           if (priv->AssociationRequestRetryCnt == MAX_ASSOCIATION_RETRIES) {
3215                   atmel_enter_state(priv, STATION_STATE_MGMT_ERROR);
3216                   priv->station_is_associated = 0;
3217                   priv->AssociationRequestRetryCnt = 0;
3218                   restart_search(priv);
3219           } else {
3220                   priv->AssociationRequestRetryCnt++;
3221                   mod_timer(&priv->management_timer, jiffies + MGMT_JIFFIES);
3222                   send_association_request(priv, 0);
3223           }
3224
3225           break;
3226                   
3227   case STATION_STATE_REASSOCIATING:     
3228           if (priv->ReAssociationRequestRetryCnt == MAX_ASSOCIATION_RETRIES) {
3229                   atmel_enter_state(priv, STATION_STATE_MGMT_ERROR);
3230                   priv->station_is_associated = 0;
3231                   priv->ReAssociationRequestRetryCnt = 0;
3232                   restart_search(priv);
3233           } else {
3234                   priv->ReAssociationRequestRetryCnt++;
3235                   mod_timer(&priv->management_timer, jiffies + MGMT_JIFFIES);
3236                   send_association_request(priv, 1);
3237           }
3238
3239           break;
3240   
3241   default:
3242           break;
3243   }
3244   
3245   spin_unlock_irqrestore(&priv->irqlock, flags);
3246 }
3247   
3248 static void atmel_command_irq(struct atmel_private *priv)
3249 {
3250         u8 status = atmel_rmem8(priv, atmel_co(priv, CMD_BLOCK_STATUS_OFFSET));
3251         u8 command = atmel_rmem8(priv, atmel_co(priv, CMD_BLOCK_COMMAND_OFFSET));
3252         int fast_scan;
3253         
3254         if (status == CMD_STATUS_IDLE || 
3255             status == CMD_STATUS_IN_PROGRESS)
3256                 return;
3257
3258         switch (command){
3259
3260         case CMD_Start:
3261                 if (status == CMD_STATUS_COMPLETE) {
3262                         priv->station_was_associated = priv->station_is_associated;
3263                         atmel_get_mib(priv, Mac_Mgmt_Mib_Type, MAC_MGMT_MIB_CUR_BSSID_POS,
3264                                       (u8 *)priv->CurrentBSSID, 6);
3265                         atmel_enter_state(priv, STATION_STATE_READY);
3266                 }                       
3267                 break;
3268                 
3269         case CMD_Scan:
3270                 fast_scan = priv->fast_scan;
3271                 priv->fast_scan = 0;
3272                 
3273                 if (status != CMD_STATUS_COMPLETE) {
3274                         atmel_scan(priv, 1);
3275                 } else {
3276                         int bss_index = retrieve_bss(priv);
3277                         if (bss_index != -1) {
3278                                 atmel_join_bss(priv, bss_index);
3279                         } else if (priv->operating_mode == IW_MODE_ADHOC && 
3280                                    priv->SSID_size != 0) {
3281                                 start(priv, BSS_TYPE_AD_HOC);
3282                         } else {
3283                                 priv->fast_scan = !fast_scan;
3284                                 atmel_scan(priv, 1);
3285                         }
3286                         priv->site_survey_state = SITE_SURVEY_COMPLETED;
3287                 }
3288                 break;
3289                 
3290         case CMD_SiteSurvey:
3291                 priv->fast_scan = 0;
3292                 
3293                 if (status != CMD_STATUS_COMPLETE)
3294                         return;
3295                 
3296                 priv->site_survey_state = SITE_SURVEY_COMPLETED;
3297                 if (priv->station_is_associated) {
3298                         atmel_enter_state(priv, STATION_STATE_READY);                           
3299                 } else {
3300                         atmel_scan(priv, 1);
3301                 }
3302                 break;
3303
3304         case CMD_Join:
3305                 if (status == CMD_STATUS_COMPLETE) {
3306                         if (priv->operating_mode == IW_MODE_ADHOC) {
3307                                 priv->station_was_associated = priv->station_is_associated;
3308                                 atmel_enter_state(priv, STATION_STATE_READY);
3309                         } else {
3310                                 priv->AuthenticationRequestRetryCnt = 0;
3311                                 atmel_enter_state(priv, STATION_STATE_AUTHENTICATING);
3312                                 
3313                                 mod_timer(&priv->management_timer, jiffies + MGMT_JIFFIES);
3314                                 priv->CurrentAuthentTransactionSeqNum = 0x0001;
3315                                 send_authentication_request(priv, NULL, 0);
3316                         }
3317                         return;
3318                 }
3319                 
3320                 atmel_scan(priv, 1);
3321                 
3322         }
3323 }
3324
3325 static int atmel_wakeup_firmware(struct atmel_private *priv)
3326 {
3327         struct host_info_struct *iface = &priv->host_info;
3328         u16 mr1, mr3;
3329         int i;
3330
3331         if (priv->card_type == CARD_TYPE_SPI_FLASH)
3332                 atmel_set_gcr(priv->dev, GCR_REMAP);
3333         
3334         /* wake up on-board processor */
3335         atmel_clear_gcr(priv->dev, 0x0040);
3336         atmel_write16(priv->dev, BSR, BSS_SRAM);
3337         
3338         if (priv->card_type == CARD_TYPE_SPI_FLASH)
3339                 mdelay(100);
3340
3341         /* and wait for it */
3342         for (i =  LOOP_RETRY_LIMIT; i; i--) {
3343                 mr1 = atmel_read16(priv->dev, MR1);
3344                 mr3 = atmel_read16(priv->dev, MR3);
3345                 
3346                 if (mr3 & MAC_BOOT_COMPLETE) 
3347                         break;
3348                 if (mr1 & MAC_BOOT_COMPLETE &&
3349                     priv->bus_type == BUS_TYPE_PCCARD)
3350                         break;
3351         }
3352
3353         if (i == 0) {
3354                 printk(KERN_ALERT "%s: MAC failed to boot.\n", priv->dev->name);
3355                 return 0;
3356         }
3357                 
3358         if ((priv->host_info_base = atmel_read16(priv->dev, MR2)) == 0xffff) {
3359                 printk(KERN_ALERT "%s: card missing.\n", priv->dev->name);
3360                 return 0;
3361         }
3362         
3363         /* now check for completion of MAC initialization through  
3364            the FunCtrl field of the IFACE, poll MR1 to detect completion of       
3365            MAC initialization, check completion status, set interrupt mask,  
3366            enables interrupts and calls Tx and Rx initialization functions */  
3367         
3368         atmel_wmem8(priv, atmel_hi(priv, IFACE_FUNC_CTRL_OFFSET), FUNC_CTRL_INIT_COMPLETE);
3369         
3370         for (i =  LOOP_RETRY_LIMIT; i; i--) {
3371                 mr1 = atmel_read16(priv->dev, MR1);
3372                 mr3 = atmel_read16(priv->dev, MR3);
3373                 
3374                 if (mr3 & MAC_INIT_COMPLETE) 
3375                         break;
3376                 if (mr1 & MAC_INIT_COMPLETE &&
3377                     priv->bus_type == BUS_TYPE_PCCARD)
3378                         break;
3379         }
3380         
3381         if (i == 0) {
3382                 printk(KERN_ALERT "%s: MAC failed to initialise.\n", priv->dev->name);
3383                 return 0;
3384         }
3385         
3386         /* Check for MAC_INIT_OK only on the register that the MAC_INIT_OK was set */
3387         if ((mr3 & MAC_INIT_COMPLETE) &&
3388             !(atmel_read16(priv->dev, MR3) & MAC_INIT_OK)) {
3389                 printk(KERN_ALERT "%s: MAC failed MR3 self-test.\n", priv->dev->name);
3390                 return 0;
3391         }
3392         if ((mr1 & MAC_INIT_COMPLETE) &&
3393             !(atmel_read16(priv->dev, MR1) & MAC_INIT_OK)) {
3394                 printk(KERN_ALERT "%s: MAC failed MR1 self-test.\n", priv->dev->name);
3395                 return 0;
3396         }
3397
3398         atmel_copy_to_host(priv->dev, (unsigned char *)iface, 
3399                            priv->host_info_base, sizeof(*iface));
3400         
3401         iface->tx_buff_pos = le16_to_cpu(iface->tx_buff_pos);
3402         iface->tx_buff_size = le16_to_cpu(iface->tx_buff_size);
3403         iface->tx_desc_pos = le16_to_cpu(iface->tx_desc_pos);
3404         iface->tx_desc_count = le16_to_cpu(iface->tx_desc_count);
3405         iface->rx_buff_pos = le16_to_cpu(iface->rx_buff_pos);
3406         iface->rx_buff_size = le16_to_cpu(iface->rx_buff_size);
3407         iface->rx_desc_pos = le16_to_cpu(iface->rx_desc_pos);
3408         iface->rx_desc_count = le16_to_cpu(iface->rx_desc_count);
3409         iface->build_version = le16_to_cpu(iface->build_version);
3410         iface->command_pos = le16_to_cpu(iface->command_pos);
3411         iface->major_version = le16_to_cpu(iface->major_version);
3412         iface->minor_version = le16_to_cpu(iface->minor_version);
3413         iface->func_ctrl = le16_to_cpu(iface->func_ctrl);
3414         iface->mac_status = le16_to_cpu(iface->mac_status);
3415
3416         return 1;
3417 }
3418
3419 /* determine type of memory and MAC address */
3420 static int probe_atmel_card(struct net_device *dev)
3421 {
3422         int rc = 0;
3423         struct atmel_private *priv = netdev_priv(dev);
3424          
3425         /* reset pccard */
3426         if (priv->bus_type == BUS_TYPE_PCCARD) 
3427                 atmel_write16(dev, GCR, 0x0060);
3428         
3429         atmel_write16(dev, GCR, 0x0040);
3430         mdelay(500);
3431         
3432         if (atmel_read16(dev, MR2) == 0) {
3433                 /* No stored firmware so load a small stub which just 
3434                    tells us the MAC address */
3435                 int i;
3436                 priv->card_type = CARD_TYPE_EEPROM;
3437                 atmel_write16(dev, BSR, BSS_IRAM);
3438                 atmel_copy_to_card(dev, 0, mac_reader, sizeof(mac_reader));
3439                 atmel_set_gcr(dev, GCR_REMAP);
3440                 atmel_clear_gcr(priv->dev, 0x0040);
3441                 atmel_write16(dev, BSR, BSS_SRAM);
3442                 for (i =  LOOP_RETRY_LIMIT; i; i--) 
3443                         if (atmel_read16(dev, MR3) & MAC_BOOT_COMPLETE)
3444                                 break;
3445                 if (i == 0) {
3446                         printk(KERN_ALERT "%s: MAC failed to boot MAC address reader.\n", dev->name);
3447                 } else {
3448                         atmel_copy_to_host(dev, dev->dev_addr, atmel_read16(dev, MR2), 6);
3449                         /* got address, now squash it again until the network
3450                            interface is opened */
3451                         if (priv->bus_type == BUS_TYPE_PCCARD) 
3452                                 atmel_write16(dev, GCR, 0x0060);
3453                         atmel_write16(dev, GCR, 0x0040);
3454                         rc = 1;
3455                 }
3456         } else if (atmel_read16(dev, MR4) == 0) {
3457                 /* Mac address easy in this case. */
3458                 priv->card_type = CARD_TYPE_PARALLEL_FLASH;
3459                 atmel_write16(dev,  BSR, 1);    
3460                 atmel_copy_to_host(dev, dev->dev_addr, 0xc000, 6);
3461                 atmel_write16(dev,  BSR, 0x200);
3462                 rc = 1;
3463         } else {
3464                 /* Standard firmware in flash, boot it up and ask
3465                    for the Mac Address */
3466                 priv->card_type = CARD_TYPE_SPI_FLASH;
3467                 if (atmel_wakeup_firmware(priv)) {
3468                         atmel_get_mib(priv, Mac_Address_Mib_Type, 0, dev->dev_addr, 6);
3469                         
3470                         /* got address, now squash it again until the network
3471                            interface is opened */
3472                         if (priv->bus_type == BUS_TYPE_PCCARD) 
3473                                 atmel_write16(dev, GCR, 0x0060);
3474                         atmel_write16(dev, GCR, 0x0040);
3475                         rc = 1;
3476                 }
3477         }
3478         
3479         if (rc) {
3480                 if (dev->dev_addr[0] == 0xFF) {
3481                         u8 default_mac[] = {0x00,0x04, 0x25, 0x00, 0x00, 0x00};
3482                         printk(KERN_ALERT "%s: *** Invalid MAC address. UPGRADE Firmware ****\n", dev->name);
3483                         memcpy(dev->dev_addr, default_mac, 6);
3484                 }
3485                 printk(KERN_INFO "%s: MAC address %.2x:%.2x:%.2x:%.2x:%.2x:%.2x\n",
3486                        dev->name,
3487                        dev->dev_addr[0], dev->dev_addr[1], dev->dev_addr[2],
3488                        dev->dev_addr[3], dev->dev_addr[4], dev->dev_addr[5] );
3489                 
3490         }
3491         
3492         return rc;
3493 }
3494
3495 static void build_wep_mib(struct atmel_private *priv)
3496 /* Move the encyption information on the MIB structure.
3497    This routine is for the pre-WPA firmware: later firmware has
3498    a different format MIB and a different routine. */
3499 {
3500         struct { /* NB this is matched to the hardware, don't change. */
3501                 u8 wep_is_on;                 
3502                 u8 default_key; /* 0..3 */
3503                 u8 reserved;
3504                 u8 exclude_unencrypted;
3505                 
3506                 u32 WEPICV_error_count;
3507                 u32 WEP_excluded_count;
3508                 
3509                 u8 wep_keys[MAX_ENCRYPTION_KEYS][13];
3510                 u8 encryption_level; /* 0, 1, 2 */
3511                 u8 reserved2[3]; 
3512         } mib;
3513         int i;
3514
3515         mib.wep_is_on = priv->wep_is_on;
3516         if (priv->wep_is_on) {
3517                 if (priv->wep_key_len[priv->default_key] > 5)
3518                         mib.encryption_level = 2;
3519                 else
3520                         mib.encryption_level = 1;       
3521         } else {
3522                 mib.encryption_level = 0;
3523         }
3524
3525         mib.default_key = priv->default_key;
3526         mib.exclude_unencrypted = priv->exclude_unencrypted;
3527         
3528         for(i = 0; i < MAX_ENCRYPTION_KEYS;  i++)
3529                 memcpy(mib.wep_keys[i], priv->wep_keys[i], 13);
3530                 
3531         atmel_set_mib(priv, Mac_Wep_Mib_Type, 0, (u8 *)&mib, sizeof(mib));
3532 }
3533
3534 static void build_wpa_mib(struct atmel_private *priv)
3535 {
3536         /* This is for the later (WPA enabled) firmware. */        
3537
3538         struct { /* NB this is matched to the hardware, don't change. */
3539                 u8 cipher_default_key_value[MAX_ENCRYPTION_KEYS][MAX_ENCRYPTION_KEY_SIZE];
3540                 u8 receiver_address[6];
3541                 u8 wep_is_on;                 
3542                 u8 default_key; /* 0..3 */
3543                 u8 group_key;
3544                 u8 exclude_unencrypted;
3545                 u8 encryption_type;
3546                 u8 reserved;
3547                 
3548                 u32 WEPICV_error_count;
3549                 u32 WEP_excluded_count;
3550                 
3551                 u8 key_RSC[4][8];
3552         } mib;
3553         
3554         int i;
3555
3556         mib.wep_is_on = priv->wep_is_on;
3557         mib.exclude_unencrypted = priv->exclude_unencrypted;
3558         memcpy(mib.receiver_address, priv->CurrentBSSID, 6);
3559         
3560         /* zero all the keys before adding in valid ones. */
3561         memset(mib.cipher_default_key_value, 0, sizeof(mib.cipher_default_key_value));
3562         
3563         if (priv->wep_is_on) {
3564                 /* There's a comment in the Atmel code to the effect that this is only valid
3565                    when still using WEP, it may need to be set to something to use WPA */
3566                 memset(mib.key_RSC, 0, sizeof(mib.key_RSC));
3567                 
3568                 mib.default_key = mib.group_key = 255;
3569                 for (i = 0; i < MAX_ENCRYPTION_KEYS; i++) {
3570                         if (priv->wep_key_len[i] > 0) {
3571                                 memcpy(mib.cipher_default_key_value[i], priv->wep_keys[i], MAX_ENCRYPTION_KEY_SIZE);
3572                                 if (i == priv->default_key) {
3573                                         mib.default_key = i;
3574                                         mib.cipher_default_key_value[i][MAX_ENCRYPTION_KEY_SIZE-1] = 7;
3575                                         mib.cipher_default_key_value[i][MAX_ENCRYPTION_KEY_SIZE-2] = priv->pairwise_cipher_suite; 
3576                                 } else {
3577                                         mib.group_key = i;
3578                                         priv->group_cipher_suite = priv->pairwise_cipher_suite;
3579                                         mib.cipher_default_key_value[i][MAX_ENCRYPTION_KEY_SIZE-1] = 1;
3580                                         mib.cipher_default_key_value[i][MAX_ENCRYPTION_KEY_SIZE-2] = priv->group_cipher_suite;  
3581                                 }
3582                         }
3583                 }
3584                 if (mib.default_key == 255)
3585                         mib.default_key = mib.group_key != 255 ? mib.group_key : 0;
3586                 if (mib.group_key == 255)
3587                         mib.group_key = mib.default_key;
3588                 
3589         }
3590         
3591         atmel_set_mib(priv, Mac_Wep_Mib_Type, 0, (u8 *)&mib, sizeof(mib));
3592 }
3593                                         
3594 static int reset_atmel_card(struct net_device *dev) 
3595 {
3596         /* do everything necessary to wake up the hardware, including
3597            waiting for the lightning strike and throwing the knife switch....
3598
3599            set all the Mib values which matter in the card to match 
3600            their settings in the atmel_private structure. Some of these
3601            can be altered on the fly, but many (WEP, infrastucture or ad-hoc)
3602            can only be changed by tearing down the world and coming back through
3603            here.
3604
3605            This routine is also responsible for initialising some 
3606            hardware-specific fields in the atmel_private structure, 
3607            including a copy of the firmware's hostinfo stucture
3608            which is the route into the rest of the firmare datastructures. */
3609
3610         struct atmel_private *priv = netdev_priv(dev);
3611         u8 configuration;
3612         
3613         /* data to add to the firmware names, in priority order
3614            this implemenents firmware versioning */
3615         
3616         static char *firmware_modifier[] = {
3617                 "-wpa",
3618                 "",
3619                 NULL
3620         };
3621                 
3622         /* reset pccard */
3623         if (priv->bus_type == BUS_TYPE_PCCARD) 
3624                 atmel_write16(priv->dev, GCR, 0x0060);
3625                 
3626         /* stop card , disable interrupts */
3627         atmel_write16(priv->dev, GCR, 0x0040);
3628                 
3629         if (priv->card_type == CARD_TYPE_EEPROM) {
3630                 /* copy in firmware if needed */
3631                 const struct firmware *fw_entry = NULL;
3632                 unsigned char *fw;
3633                 int len = priv->firmware_length;
3634                 if (!(fw = priv->firmware)) {
3635                         if (priv->firmware_type == ATMEL_FW_TYPE_NONE) {
3636                                 if (strlen(priv->firmware_id) == 0) {
3637                                         printk(KERN_INFO
3638                                                "%s: card type is unknown: assuming at76c502 firmware is OK.\n",
3639                                                dev->name);
3640                                         printk(KERN_INFO
3641                                                "%s: if not, use the firmware= module parameter.\n", 
3642                                                dev->name);
3643                                         strcpy(priv->firmware_id, "atmel_at76c502.bin");
3644                                 }
3645                                 if (request_firmware(&fw_entry, priv->firmware_id, priv->sys_dev) != 0) {
3646                                         printk(KERN_ALERT 
3647                                                "%s: firmware %s is missing, cannot continue.\n", 
3648                                                dev->name, priv->firmware_id);
3649                                         return 0;
3650                                 }
3651                         } else {
3652                                 int fw_index = 0;
3653                                 int success = 0;
3654
3655                                 /* get firmware filename entry based on firmware type ID */
3656                                 while (fw_table[fw_index].fw_type != priv->firmware_type
3657                                                 && fw_table[fw_index].fw_type != ATMEL_FW_TYPE_NONE)
3658                                         fw_index++;
3659                                 
3660                                 /* construct the actual firmware file name */
3661                                 if (fw_table[fw_index].fw_type != ATMEL_FW_TYPE_NONE) {
3662                                         int i;
3663                                         for (i = 0; firmware_modifier[i]; i++) {
3664                                                 snprintf(priv->firmware_id, 32, "%s%s.%s", fw_table[fw_index].fw_file,
3665                                                         firmware_modifier[i], fw_table[fw_index].fw_file_ext);
3666                                                 priv->firmware_id[31] = '\0';
3667                                                 if (request_firmware(&fw_entry, priv->firmware_id, priv->sys_dev) == 0) {
3668                                                         success = 1;
3669                                                         break;
3670                                                 }
3671                                         }
3672                                 }
3673                                 if (!success) {
3674                                         printk(KERN_ALERT 
3675                                                "%s: firmware %s is missing, cannot start.\n", 
3676                                                dev->name, priv->firmware_id);
3677                                         priv->firmware_id[0] = '\0';
3678                                         return 0;       
3679                                 }
3680                         }
3681                         
3682                         fw = fw_entry->data;
3683                         len = fw_entry->size;
3684                 }
3685                 
3686                 if (len <= 0x6000) {
3687                         atmel_write16(priv->dev, BSR, BSS_IRAM);
3688                         atmel_copy_to_card(priv->dev, 0, fw, len);
3689                         atmel_set_gcr(priv->dev, GCR_REMAP);
3690                 } else {
3691                         /* Remap */ 
3692                         atmel_set_gcr(priv->dev, GCR_REMAP);
3693                         atmel_write16(priv->dev, BSR, BSS_IRAM);
3694                         atmel_copy_to_card(priv->dev, 0, fw, 0x6000);
3695                         atmel_write16(priv->dev, BSR, 0x2ff);
3696                         atmel_copy_to_card(priv->dev, 0x8000, &fw[0x6000], len - 0x6000);
3697                 }
3698
3699                 if (fw_entry)
3700                         release_firmware(fw_entry);
3701         }
3702
3703         if (!atmel_wakeup_firmware(priv))
3704                 return 0;
3705
3706         /* Check the version and set the correct flag for wpa stuff,
3707            old and new firmware is incompatible.
3708            The pre-wpa 3com firmware reports major version 5,
3709            the wpa 3com firmware is major version 4 and doesn't need
3710            the 3com broken-ness filter. */
3711         priv->use_wpa = (priv->host_info.major_version == 4);
3712         priv->radio_on_broken = (priv->host_info.major_version == 5);
3713         
3714         /* unmask all irq sources */
3715         atmel_wmem8(priv, atmel_hi(priv, IFACE_INT_MASK_OFFSET), 0xff);
3716         
3717         /* int Tx system and enable Tx */
3718         atmel_wmem8(priv, atmel_tx(priv, TX_DESC_FLAGS_OFFSET, 0), 0);
3719         atmel_wmem32(priv, atmel_tx(priv, TX_DESC_NEXT_OFFSET, 0), 0x80000000L);
3720         atmel_wmem16(priv, atmel_tx(priv, TX_DESC_POS_OFFSET, 0), 0);
3721         atmel_wmem16(priv, atmel_tx(priv, TX_DESC_SIZE_OFFSET, 0), 0);
3722
3723         priv->tx_desc_free = priv->host_info.tx_desc_count;             
3724         priv->tx_desc_head = 0;                                                                 
3725         priv->tx_desc_tail = 0;                                                                 
3726         priv->tx_desc_previous = 0;
3727         priv->tx_free_mem = priv->host_info.tx_buff_size;
3728         priv->tx_buff_head = 0; 
3729         priv->tx_buff_tail = 0; 
3730                 
3731         configuration = atmel_rmem8(priv, atmel_hi(priv, IFACE_FUNC_CTRL_OFFSET)); 
3732         atmel_wmem8(priv, atmel_hi(priv, IFACE_FUNC_CTRL_OFFSET), 
3733                                    configuration | FUNC_CTRL_TxENABLE);
3734
3735         /* init Rx system and enable */
3736         priv->rx_desc_head = 0;
3737         
3738         configuration = atmel_rmem8(priv, atmel_hi(priv, IFACE_FUNC_CTRL_OFFSET)); 
3739         atmel_wmem8(priv, atmel_hi(priv, IFACE_FUNC_CTRL_OFFSET), 
3740                                    configuration | FUNC_CTRL_RxENABLE);
3741                         
3742         if (!priv->radio_on_broken) {
3743                 if (atmel_send_command_wait(priv, CMD_EnableRadio, NULL, 0) == 
3744                     CMD_STATUS_REJECTED_RADIO_OFF) {
3745                         printk(KERN_INFO 
3746                                "%s: cannot turn the radio on. (Hey radio, you're beautiful!)\n",
3747                                dev->name);
3748                         return 0;
3749                 }
3750         }
3751         
3752         /* set up enough MIB values to run. */
3753         atmel_set_mib8(priv, Local_Mib_Type, LOCAL_MIB_AUTO_TX_RATE_POS, priv->auto_tx_rate);
3754         atmel_set_mib8(priv, Local_Mib_Type,  LOCAL_MIB_TX_PROMISCUOUS_POS,  PROM_MODE_OFF);
3755         atmel_set_mib16(priv, Mac_Mib_Type, MAC_MIB_RTS_THRESHOLD_POS, priv->rts_threshold);
3756         atmel_set_mib16(priv, Mac_Mib_Type, MAC_MIB_FRAG_THRESHOLD_POS, priv->frag_threshold);
3757         atmel_set_mib8(priv, Mac_Mib_Type, MAC_MIB_SHORT_RETRY_POS, priv->short_retry);
3758         atmel_set_mib8(priv, Mac_Mib_Type, MAC_MIB_LONG_RETRY_POS, priv->long_retry);
3759         atmel_set_mib8(priv, Local_Mib_Type, LOCAL_MIB_PREAMBLE_TYPE, priv->preamble);
3760         atmel_set_mib(priv, Mac_Address_Mib_Type, MAC_ADDR_MIB_MAC_ADDR_POS, 
3761                       priv->dev->dev_addr, 6);
3762         atmel_set_mib8(priv, Mac_Mgmt_Mib_Type, MAC_MGMT_MIB_PS_MODE_POS, ACTIVE_MODE);
3763         atmel_set_mib16(priv, Mac_Mgmt_Mib_Type, MAC_MGMT_MIB_LISTEN_INTERVAL_POS, 1);
3764         atmel_set_mib16(priv, Mac_Mgmt_Mib_Type, MAC_MGMT_MIB_BEACON_PER_POS, priv->default_beacon_period);
3765         atmel_set_mib(priv, Phy_Mib_Type, PHY_MIB_RATE_SET_POS, atmel_basic_rates, 4);
3766         atmel_set_mib8(priv, Mac_Mgmt_Mib_Type, MAC_MGMT_MIB_CUR_PRIVACY_POS, priv->wep_is_on);
3767         if (priv->use_wpa)
3768                 build_wpa_mib(priv);
3769         else
3770                 build_wep_mib(priv);
3771         
3772         return 1;
3773 }
3774
3775 static void atmel_send_command(struct atmel_private *priv, int command, void *cmd, int cmd_size)
3776 {
3777         if (cmd)
3778                 atmel_copy_to_card(priv->dev, atmel_co(priv, CMD_BLOCK_PARAMETERS_OFFSET), 
3779                                    cmd, cmd_size);
3780         
3781         atmel_wmem8(priv, atmel_co(priv, CMD_BLOCK_COMMAND_OFFSET), command);
3782         atmel_wmem8(priv, atmel_co(priv, CMD_BLOCK_STATUS_OFFSET), 0);
3783 }
3784         
3785 static int atmel_send_command_wait(struct atmel_private *priv, int command, void *cmd, int cmd_size)
3786 {
3787         int i, status;
3788         
3789         atmel_send_command(priv, command, cmd, cmd_size);
3790         
3791         for (i = 5000; i; i--) {
3792                 status = atmel_rmem8(priv, atmel_co(priv, CMD_BLOCK_STATUS_OFFSET));
3793                 if (status != CMD_STATUS_IDLE && 
3794                     status != CMD_STATUS_IN_PROGRESS)
3795                         break;
3796                 udelay(20);
3797         }
3798         
3799         if (i == 0) {
3800                 printk(KERN_ALERT "%s: failed to contact MAC.\n", priv->dev->name);
3801                 status =  CMD_STATUS_HOST_ERROR;
3802         } else { 
3803                 if (command != CMD_EnableRadio)
3804                         status = CMD_STATUS_COMPLETE;
3805         }
3806         
3807         return status;
3808 }
3809
3810 static u8 atmel_get_mib8(struct atmel_private *priv, u8 type, u8 index)
3811 {
3812         struct get_set_mib m;
3813         m.type = type;
3814         m.size = 1;
3815         m.index = index;
3816
3817         atmel_send_command_wait(priv, CMD_Get_MIB_Vars, &m, MIB_HEADER_SIZE + 1);
3818         return atmel_rmem8(priv, atmel_co(priv, CMD_BLOCK_PARAMETERS_OFFSET + MIB_HEADER_SIZE));
3819 }
3820
3821 static void atmel_set_mib8(struct atmel_private *priv, u8 type, u8 index, u8 data)
3822 {
3823         struct get_set_mib m;
3824         m.type = type;
3825         m.size = 1;
3826         m.index = index;
3827         m.data[0] = data;
3828
3829         atmel_send_command_wait(priv, CMD_Set_MIB_Vars, &m, MIB_HEADER_SIZE + 1);
3830 }
3831
3832 static void atmel_set_mib16(struct atmel_private *priv, u8 type, u8 index, u16 data)
3833 {
3834         struct get_set_mib m;
3835         m.type = type;
3836         m.size = 2;
3837         m.index = index;
3838         m.data[0] = data;
3839         m.data[1] = data >> 8;
3840
3841         atmel_send_command_wait(priv, CMD_Set_MIB_Vars, &m, MIB_HEADER_SIZE + 2);
3842 }
3843
3844 static void atmel_set_mib(struct atmel_private *priv, u8 type, u8 index, u8 *data, int data_len)
3845 {
3846         struct get_set_mib m;
3847         m.type = type;
3848         m.size = data_len;
3849         m.index = index;
3850
3851         if (data_len > MIB_MAX_DATA_BYTES)
3852                 printk(KERN_ALERT "%s: MIB buffer too small.\n", priv->dev->name);
3853         
3854         memcpy(m.data, data, data_len);
3855         atmel_send_command_wait(priv, CMD_Set_MIB_Vars, &m, MIB_HEADER_SIZE + data_len);
3856 }
3857
3858 static void atmel_get_mib(struct atmel_private *priv, u8 type, u8 index, u8 *data, int data_len)
3859 {
3860         struct get_set_mib m;
3861         m.type = type;
3862         m.size = data_len;
3863         m.index = index;
3864         
3865         if (data_len > MIB_MAX_DATA_BYTES)
3866                 printk(KERN_ALERT "%s: MIB buffer too small.\n", priv->dev->name);
3867         
3868         atmel_send_command_wait(priv, CMD_Get_MIB_Vars, &m, MIB_HEADER_SIZE + data_len);
3869         atmel_copy_to_host(priv->dev, data, 
3870                            atmel_co(priv, CMD_BLOCK_PARAMETERS_OFFSET + MIB_HEADER_SIZE), data_len);
3871 }
3872
3873 static void atmel_writeAR(struct net_device *dev, u16 data)
3874 {
3875         int i;
3876         outw(data, dev->base_addr + AR);
3877         /* Address register appears to need some convincing..... */
3878         for (i = 0; data != inw(dev->base_addr + AR) && i<10; i++)
3879                 outw(data, dev->base_addr + AR);
3880 }
3881
3882 static void atmel_copy_to_card(struct net_device *dev, u16 dest, unsigned char *src, u16 len)
3883 {
3884         int i;
3885         atmel_writeAR(dev, dest);
3886         if (dest % 2) {
3887                 atmel_write8(dev, DR, *src);
3888                 src++; len--;
3889         }
3890         for (i = len; i > 1 ; i -= 2) {
3891                 u8 lb = *src++;
3892                 u8 hb = *src++;
3893                 atmel_write16(dev, DR, lb | (hb << 8));
3894         }
3895         if (i)
3896                 atmel_write8(dev, DR, *src);
3897 }
3898
3899 static void atmel_copy_to_host(struct net_device *dev, unsigned char *dest, u16 src, u16 len)
3900 {
3901         int i;
3902         atmel_writeAR(dev, src);
3903         if (src % 2) {
3904                 *dest = atmel_read8(dev, DR);
3905                 dest++; len--;
3906         }
3907         for (i = len; i > 1 ; i -= 2) {
3908                 u16 hw = atmel_read16(dev, DR);
3909                 *dest++ = hw;
3910                 *dest++ = hw >> 8;
3911         }
3912         if (i)
3913                 *dest = atmel_read8(dev, DR);
3914 }
3915
3916 static void atmel_set_gcr(struct net_device *dev, u16 mask)
3917 {
3918         outw(inw(dev->base_addr + GCR) | mask, dev->base_addr + GCR);
3919 }
3920
3921 static void atmel_clear_gcr(struct net_device *dev, u16 mask)
3922 {
3923         outw(inw(dev->base_addr + GCR) & ~mask, dev->base_addr + GCR);
3924 }
3925
3926 static int atmel_lock_mac(struct atmel_private *priv)
3927 {
3928         int i, j = 20;
3929  retry:
3930         for (i = 5000; i; i--) {
3931                 if (!atmel_rmem8(priv, atmel_hi(priv, IFACE_LOCKOUT_HOST_OFFSET)))
3932                         break;
3933                 udelay(20);
3934         }
3935         
3936         if (!i) return 0; /* timed out */
3937         
3938         atmel_wmem8(priv, atmel_hi(priv, IFACE_LOCKOUT_MAC_OFFSET), 1);
3939         if (atmel_rmem8(priv, atmel_hi(priv, IFACE_LOCKOUT_HOST_OFFSET))) {
3940                 atmel_wmem8(priv, atmel_hi(priv, IFACE_LOCKOUT_MAC_OFFSET), 0);
3941                 if (!j--) return 0; /* timed out */
3942                 goto retry;
3943         }
3944         
3945         return 1;
3946 }
3947
3948 static void atmel_wmem32(struct atmel_private *priv, u16 pos, u32 data)
3949 {
3950         atmel_writeAR(priv->dev, pos);  
3951         atmel_write16(priv->dev, DR, data); /* card is little-endian */
3952         atmel_write16(priv->dev, DR, data >> 16);
3953 }
3954
3955 /***************************************************************************/
3956 /* There follows the source form of the MAC address reading firmware       */
3957 /***************************************************************************/
3958 #if 0
3959
3960 /* Copyright 2003 Matthew T. Russotto                                      */
3961 /* But derived from the Atmel 76C502 firmware written by Atmel and         */
3962 /* included in "atmel wireless lan drivers" package                        */
3963 /**
3964     This file is part of net.russotto.AtmelMACFW, hereto referred to
3965     as AtmelMACFW
3966
3967     AtmelMACFW is free software; you can redistribute it and/or modify
3968     it under the terms of the GNU General Public License version 2
3969     as published by the Free Software Foundation.
3970
3971     AtmelMACFW is distributed in the hope that it will be useful,
3972     but WITHOUT ANY WARRANTY; without even the implied warranty of
3973     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
3974     GNU General Public License for more details.
3975
3976     You should have received a copy of the GNU General Public License
3977     along with AtmelMACFW; if not, write to the Free Software
3978     Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
3979
3980 ****************************************************************************/
3981 /* This firmware should work on the 76C502 RFMD, RFMD_D, and RFMD_E        */
3982 /* It will probably work on the 76C504 and 76C502 RFMD_3COM                */
3983 /* It only works on SPI EEPROM versions of the card.                       */
3984
3985 /* This firmware initializes the SPI controller and clock, reads the MAC   */
3986 /* address from the EEPROM into SRAM, and puts the SRAM offset of the MAC  */
3987 /* address in MR2, and sets MR3 to 0x10 to indicate it is done             */
3988 /* It also puts a complete copy of the EEPROM in SRAM with the offset in   */
3989 /* MR4, for investigational purposes (maybe we can determine chip type     */
3990 /* from that?)                                                             */
3991
3992         .org 0
3993     .set MRBASE, 0x8000000
3994         .set CPSR_INITIAL, 0xD3 /* IRQ/FIQ disabled, ARM mode, Supervisor state */
3995         .set CPSR_USER, 0xD1 /* IRQ/FIQ disabled, ARM mode, USER state */
3996         .set SRAM_BASE,  0x02000000
3997         .set SP_BASE,    0x0F300000
3998         .set UNK_BASE,   0x0F000000 /* Some internal device, but which one? */
3999         .set SPI_CGEN_BASE,  0x0E000000 /* Some internal device, but which one? */
4000         .set UNK3_BASE,  0x02014000 /* Some internal device, but which one? */
4001         .set STACK_BASE, 0x5600
4002         .set SP_SR, 0x10
4003         .set SP_TDRE, 2 /* status register bit -- TDR empty */
4004         .set SP_RDRF, 1 /* status register bit -- RDR full */
4005         .set SP_SWRST, 0x80
4006         .set SP_SPIEN, 0x1
4007         .set SP_CR, 0   /* control register */
4008         .set SP_MR, 4   /* mode register */
4009         .set SP_RDR, 0x08 /* Read Data Register */
4010         .set SP_TDR, 0x0C /* Transmit Data Register */
4011         .set SP_CSR0, 0x30 /* chip select registers */
4012         .set SP_CSR1, 0x34
4013         .set SP_CSR2, 0x38
4014         .set SP_CSR3, 0x3C
4015         .set NVRAM_CMD_RDSR, 5 /* read status register */
4016         .set NVRAM_CMD_READ, 3 /* read data */
4017         .set NVRAM_SR_RDY, 1 /* RDY bit.  This bit is inverted */
4018         .set SPI_8CLOCKS, 0xFF /* Writing this to the TDR doesn't do anything to the
4019                                   serial output, since SO is normally high.  But it
4020                                   does cause 8 clock cycles and thus 8 bits to be
4021                                   clocked in to the chip.  See Atmel's SPI
4022                                   controller (e.g. AT91M55800) timing and 4K 
4023                                   SPI EEPROM manuals */
4024                                  
4025         .set NVRAM_SCRATCH, 0x02000100  /* arbitrary area for scratchpad memory */
4026         .set NVRAM_IMAGE, 0x02000200
4027         .set NVRAM_LENGTH, 0x0200
4028         .set MAC_ADDRESS_MIB, SRAM_BASE
4029         .set MAC_ADDRESS_LENGTH, 6
4030         .set MAC_BOOT_FLAG, 0x10
4031         .set MR1, 0
4032         .set MR2, 4
4033         .set MR3, 8
4034         .set MR4, 0xC
4035 RESET_VECTOR:
4036         b RESET_HANDLER
4037 UNDEF_VECTOR:  
4038         b HALT1
4039 SWI_VECTOR:            
4040         b HALT1
4041 IABORT_VECTOR: 
4042         b HALT1
4043 DABORT_VECTOR:         
4044 RESERVED_VECTOR:    
4045         b HALT1
4046 IRQ_VECTOR:    
4047         b HALT1
4048 FIQ_VECTOR:    
4049         b HALT1
4050 HALT1:  b HALT1
4051 RESET_HANDLER:
4052         mov     r0, #CPSR_INITIAL
4053         msr     CPSR_c, r0      /* This is probably unnecessary */
4054                         
4055 /* I'm guessing this is initializing clock generator electronics for SPI */
4056         ldr     r0, =SPI_CGEN_BASE
4057         mov     r1, #0
4058         mov     r1, r1, lsl #3
4059         orr     r1,r1, #0
4060         str     r1, [r0]
4061         ldr     r1, [r0, #28]
4062         bic     r1, r1, #16
4063         str     r1, [r0, #28]
4064         mov     r1, #1
4065         str     r1, [r0, #8]
4066         
4067         ldr     r0, =MRBASE
4068         mov     r1, #0
4069         strh    r1, [r0, #MR1]
4070         strh    r1, [r0, #MR2]
4071         strh    r1, [r0, #MR3]
4072         strh    r1, [r0, #MR4]
4073
4074         mov     sp, #STACK_BASE
4075         bl      SP_INIT
4076         mov     r0, #10
4077         bl      DELAY9
4078         bl      GET_MAC_ADDR
4079         bl      GET_WHOLE_NVRAM
4080         ldr     r0, =MRBASE
4081         ldr     r1, =MAC_ADDRESS_MIB
4082         strh    r1, [r0, #MR2]
4083         ldr     r1, =NVRAM_IMAGE
4084         strh    r1, [r0, #MR4]
4085         mov     r1, #MAC_BOOT_FLAG
4086         strh    r1, [r0, #MR3]
4087 HALT2:  b HALT2
4088 .func Get_Whole_NVRAM, GET_WHOLE_NVRAM
4089 GET_WHOLE_NVRAM:
4090         stmdb   sp!, {lr}
4091         mov     r2, #0 /* 0th bytes of NVRAM */
4092         mov     r3, #NVRAM_LENGTH
4093         mov     r1, #0          /* not used in routine */
4094         ldr     r0, =NVRAM_IMAGE
4095         bl      NVRAM_XFER
4096         ldmia   sp!, {lr}
4097         bx      lr
4098 .endfunc
4099         
4100 .func Get_MAC_Addr, GET_MAC_ADDR
4101 GET_MAC_ADDR:
4102         stmdb   sp!, {lr}
4103         mov     r2, #0x120      /* address of MAC Address within NVRAM */
4104         mov     r3, #MAC_ADDRESS_LENGTH
4105         mov     r1, #0          /* not used in routine */
4106         ldr     r0, =MAC_ADDRESS_MIB
4107         bl      NVRAM_XFER
4108         ldmia   sp!, {lr}
4109         bx      lr
4110 .endfunc
4111 .ltorg
4112 .func Delay9, DELAY9
4113 DELAY9:
4114         adds    r0, r0, r0, LSL #3   /* r0 = r0 * 9 */
4115 DELAYLOOP:      
4116         beq     DELAY9_done
4117         subs    r0, r0, #1
4118         b       DELAYLOOP
4119 DELAY9_done:    
4120         bx      lr
4121 .endfunc        
4122
4123 .func SP_Init, SP_INIT
4124 SP_INIT:
4125         mov     r1, #SP_SWRST
4126         ldr     r0, =SP_BASE
4127         str     r1, [r0, #SP_CR] /* reset the SPI */
4128         mov     r1, #0
4129         str     r1, [r0, #SP_CR] /* release SPI from reset state */
4130         mov     r1, #SP_SPIEN
4131         str     r1, [r0, #SP_MR] /* set the SPI to MASTER mode*/
4132         str     r1, [r0, #SP_CR] /* enable the SPI */
4133
4134 /*  My guess would be this turns on the SPI clock */
4135         ldr     r3, =SPI_CGEN_BASE
4136         ldr     r1, [r3, #28]
4137         orr     r1, r1, #0x2000
4138         str     r1, [r3, #28]
4139
4140         ldr     r1, =0x2000c01
4141         str     r1, [r0, #SP_CSR0]
4142         ldr     r1, =0x2000201
4143         str     r1, [r0, #SP_CSR1]
4144         str     r1, [r0, #SP_CSR2]
4145         str     r1, [r0, #SP_CSR3]
4146         ldr     r1, [r0, #SP_SR]
4147         ldr     r0, [r0, #SP_RDR]
4148         bx      lr
4149 .endfunc
4150 .func NVRAM_Init, NVRAM_INIT    
4151 NVRAM_INIT:
4152         ldr     r1, =SP_BASE
4153         ldr     r0, [r1, #SP_RDR]
4154         mov     r0, #NVRAM_CMD_RDSR
4155         str     r0, [r1, #SP_TDR]
4156 SP_loop1:       
4157         ldr     r0, [r1, #SP_SR]
4158         tst     r0, #SP_TDRE
4159         beq     SP_loop1
4160
4161         mov     r0, #SPI_8CLOCKS
4162         str     r0, [r1, #SP_TDR] 
4163 SP_loop2:       
4164         ldr     r0, [r1, #SP_SR]
4165         tst     r0, #SP_TDRE
4166         beq     SP_loop2
4167
4168         ldr     r0, [r1, #SP_RDR]
4169 SP_loop3:       
4170         ldr     r0, [r1, #SP_SR]
4171         tst     r0, #SP_RDRF
4172         beq     SP_loop3
4173
4174         ldr     r0, [r1, #SP_RDR]
4175         and     r0, r0, #255
4176         bx      lr
4177 .endfunc
4178         
4179 .func NVRAM_Xfer, NVRAM_XFER
4180         /* r0 = dest address */
4181         /* r1 = not used */
4182         /* r2 = src address within NVRAM */
4183         /* r3 = length */
4184 NVRAM_XFER:
4185         stmdb   sp!, {r4, r5, lr}
4186         mov     r5, r0          /* save r0 (dest address) */
4187         mov     r4, r3          /* save r3 (length) */
4188         mov     r0, r2, LSR #5 /*  SPI memories put A8 in the command field */
4189         and     r0, r0, #8
4190         add     r0, r0, #NVRAM_CMD_READ 
4191         ldr     r1, =NVRAM_SCRATCH
4192         strb    r0, [r1, #0]    /* save command in NVRAM_SCRATCH[0] */
4193         strb    r2, [r1, #1]    /* save low byte of source address in NVRAM_SCRATCH[1] */
4194 _local1:        
4195         bl      NVRAM_INIT
4196         tst     r0, #NVRAM_SR_RDY
4197         bne     _local1
4198         mov     r0, #20
4199         bl      DELAY9
4200         mov     r2, r4          /* length */
4201         mov     r1, r5          /* dest address */
4202         mov     r0, #2          /* bytes to transfer in command */
4203         bl      NVRAM_XFER2
4204         ldmia   sp!, {r4, r5, lr}
4205         bx      lr
4206 .endfunc
4207
4208 .func NVRAM_Xfer2, NVRAM_XFER2
4209 NVRAM_XFER2:
4210         stmdb   sp!, {r4, r5, r6, lr}
4211         ldr     r4, =SP_BASE
4212         mov     r3, #0
4213         cmp     r0, #0
4214         bls     _local2
4215         ldr     r5, =NVRAM_SCRATCH
4216 _local4:        
4217         ldrb    r6, [r5, r3]
4218         str     r6, [r4, #SP_TDR]
4219 _local3:
4220         ldr     r6, [r4, #SP_SR]
4221         tst     r6, #SP_TDRE
4222         beq     _local3
4223         add     r3, r3, #1
4224         cmp     r3, r0 /* r0 is # of bytes to send out (command+addr) */
4225         blo     _local4
4226 _local2:
4227         mov     r3, #SPI_8CLOCKS
4228         str     r3, [r4, #SP_TDR]
4229         ldr     r0, [r4, #SP_RDR]
4230 _local5:        
4231         ldr     r0, [r4, #SP_SR]
4232         tst     r0, #SP_RDRF
4233         beq     _local5
4234         ldr     r0, [r4, #SP_RDR] /* what's this byte?  It's the byte read while writing the TDR -- nonsense, because the NVRAM doesn't read and write at the same time */
4235         mov     r0, #0
4236         cmp     r2, #0  /* r2 is # of bytes to copy in */
4237         bls     _local6
4238 _local7:        
4239         ldr     r5, [r4, #SP_SR]
4240         tst     r5, #SP_TDRE
4241         beq     _local7
4242         str     r3, [r4, #SP_TDR]  /* r3 has SPI_8CLOCKS */
4243 _local8:        
4244         ldr     r5, [r4, #SP_SR]
4245         tst     r5, #SP_RDRF
4246         beq     _local8
4247         ldr     r5, [r4, #SP_RDR] /* but didn't we read this byte above? */
4248         strb    r5, [r1], #1 /* postindexed */
4249         add     r0, r0, #1
4250         cmp     r0, r2
4251         blo     _local7 /* since we don't send another address, the NVRAM must be capable of sequential reads */
4252 _local6:
4253         mov     r0, #200
4254         bl      DELAY9
4255         ldmia   sp!, {r4, r5, r6, lr}
4256         bx      lr
4257 #endif