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