]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - drivers/staging/at76_usb/at76_usb.c
Merge branch 'for-linus' of git://git.o-hand.com/linux-rpurdie-leds
[linux-2.6-omap-h63xx.git] / drivers / staging / at76_usb / at76_usb.c
1 /*
2  * at76c503/at76c505 USB driver
3  *
4  * Copyright (c) 2002 - 2003 Oliver Kurth
5  * Copyright (c) 2004 Joerg Albert <joerg.albert@gmx.de>
6  * Copyright (c) 2004 Nick Jones
7  * Copyright (c) 2004 Balint Seeber <n0_5p4m_p13453@hotmail.com>
8  * Copyright (c) 2007 Guido Guenther <agx@sigxcpu.org>
9  *
10  * This program is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU General Public License as
12  * published by the Free Software Foundation; either version 2 of
13  * the License, or (at your option) any later version.
14  *
15  * This file is part of the Berlios driver for WLAN USB devices based on the
16  * Atmel AT76C503A/505/505A.
17  *
18  * Some iw_handler code was taken from airo.c, (C) 1999 Benjamin Reed
19  */
20
21 #include <linux/init.h>
22 #include <linux/kernel.h>
23 #include <linux/sched.h>
24 #include <linux/errno.h>
25 #include <linux/slab.h>
26 #include <linux/module.h>
27 #include <linux/spinlock.h>
28 #include <linux/list.h>
29 #include <linux/usb.h>
30 #include <linux/netdevice.h>
31 #include <linux/if_arp.h>
32 #include <linux/etherdevice.h>
33 #include <linux/ethtool.h>
34 #include <linux/wireless.h>
35 #include <net/iw_handler.h>
36 #include <net/ieee80211_radiotap.h>
37 #include <linux/firmware.h>
38 #include <linux/leds.h>
39 #include <net/ieee80211.h>
40
41 #include "at76_usb.h"
42
43 /* Version information */
44 #define DRIVER_NAME "at76_usb"
45 #define DRIVER_VERSION  "0.17"
46 #define DRIVER_DESC "Atmel at76x USB Wireless LAN Driver"
47
48 /* at76_debug bits */
49 #define DBG_PROGRESS            0x00000001      /* authentication/accociation */
50 #define DBG_BSS_TABLE           0x00000002      /* show BSS table after scans */
51 #define DBG_IOCTL               0x00000004      /* ioctl calls / settings */
52 #define DBG_MAC_STATE           0x00000008      /* MAC state transitions */
53 #define DBG_TX_DATA             0x00000010      /* tx header */
54 #define DBG_TX_DATA_CONTENT     0x00000020      /* tx content */
55 #define DBG_TX_MGMT             0x00000040      /* tx management */
56 #define DBG_RX_DATA             0x00000080      /* rx data header */
57 #define DBG_RX_DATA_CONTENT     0x00000100      /* rx data content */
58 #define DBG_RX_MGMT             0x00000200      /* rx mgmt frame headers */
59 #define DBG_RX_BEACON           0x00000400      /* rx beacon */
60 #define DBG_RX_CTRL             0x00000800      /* rx control */
61 #define DBG_RX_MGMT_CONTENT     0x00001000      /* rx mgmt content */
62 #define DBG_RX_FRAGS            0x00002000      /* rx data fragment handling */
63 #define DBG_DEVSTART            0x00004000      /* fw download, device start */
64 #define DBG_URB                 0x00008000      /* rx urb status, ... */
65 #define DBG_RX_ATMEL_HDR        0x00010000      /* Atmel-specific Rx headers */
66 #define DBG_PROC_ENTRY          0x00020000      /* procedure entries/exits */
67 #define DBG_PM                  0x00040000      /* power management settings */
68 #define DBG_BSS_MATCH           0x00080000      /* BSS match failures */
69 #define DBG_PARAMS              0x00100000      /* show configured parameters */
70 #define DBG_WAIT_COMPLETE       0x00200000      /* command completion */
71 #define DBG_RX_FRAGS_SKB        0x00400000      /* skb header of Rx fragments */
72 #define DBG_BSS_TABLE_RM        0x00800000      /* purging bss table entries */
73 #define DBG_MONITOR_MODE        0x01000000      /* monitor mode */
74 #define DBG_MIB                 0x02000000      /* dump all MIBs on startup */
75 #define DBG_MGMT_TIMER          0x04000000      /* dump mgmt_timer ops */
76 #define DBG_WE_EVENTS           0x08000000      /* dump wireless events */
77 #define DBG_FW                  0x10000000      /* firmware download */
78 #define DBG_DFU                 0x20000000      /* device firmware upgrade */
79
80 #define DBG_DEFAULTS            0
81
82 /* Use our own dbg macro */
83 #define at76_dbg(bits, format, arg...) \
84         do { \
85                 if (at76_debug & (bits)) \
86                 printk(KERN_DEBUG DRIVER_NAME ": " format "\n" , ## arg); \
87         } while (0)
88
89 static int at76_debug = DBG_DEFAULTS;
90
91 /* Protect against concurrent firmware loading and parsing */
92 static struct mutex fw_mutex;
93
94 static struct fwentry firmwares[] = {
95         [0] = {""},
96         [BOARD_503_ISL3861] = {"atmel_at76c503-i3861.bin"},
97         [BOARD_503_ISL3863] = {"atmel_at76c503-i3863.bin"},
98         [BOARD_503] = {"atmel_at76c503-rfmd.bin"},
99         [BOARD_503_ACC] = {"atmel_at76c503-rfmd-acc.bin"},
100         [BOARD_505] = {"atmel_at76c505-rfmd.bin"},
101         [BOARD_505_2958] = {"atmel_at76c505-rfmd2958.bin"},
102         [BOARD_505A] = {"atmel_at76c505a-rfmd2958.bin"},
103         [BOARD_505AMX] = {"atmel_at76c505amx-rfmd.bin"},
104 };
105
106 #define USB_DEVICE_DATA(__ops)  .driver_info = (kernel_ulong_t)(__ops)
107
108 static struct usb_device_id dev_table[] = {
109         /*
110          * at76c503-i3861
111          */
112         /* Generic AT76C503/3861 device */
113         {USB_DEVICE(0x03eb, 0x7603), USB_DEVICE_DATA(BOARD_503_ISL3861)},
114         /* Linksys WUSB11 v2.1/v2.6 */
115         {USB_DEVICE(0x066b, 0x2211), USB_DEVICE_DATA(BOARD_503_ISL3861)},
116         /* Netgear MA101 rev. A */
117         {USB_DEVICE(0x0864, 0x4100), USB_DEVICE_DATA(BOARD_503_ISL3861)},
118         /* Tekram U300C / Allnet ALL0193 */
119         {USB_DEVICE(0x0b3b, 0x1612), USB_DEVICE_DATA(BOARD_503_ISL3861)},
120         /* HP HN210W J7801A */
121         {USB_DEVICE(0x03f0, 0x011c), USB_DEVICE_DATA(BOARD_503_ISL3861)},
122         /* Sitecom/Z-Com/Zyxel M4Y-750 */
123         {USB_DEVICE(0x0cde, 0x0001), USB_DEVICE_DATA(BOARD_503_ISL3861)},
124         /* Dynalink/Askey WLL013 (intersil) */
125         {USB_DEVICE(0x069a, 0x0320), USB_DEVICE_DATA(BOARD_503_ISL3861)},
126         /* EZ connect 11Mpbs Wireless USB Adapter SMC2662W v1 */
127         {USB_DEVICE(0x0d5c, 0xa001), USB_DEVICE_DATA(BOARD_503_ISL3861)},
128         /* BenQ AWL300 */
129         {USB_DEVICE(0x04a5, 0x9000), USB_DEVICE_DATA(BOARD_503_ISL3861)},
130         /* Addtron AWU-120, Compex WLU11 */
131         {USB_DEVICE(0x05dd, 0xff31), USB_DEVICE_DATA(BOARD_503_ISL3861)},
132         /* Intel AP310 AnyPoint II USB */
133         {USB_DEVICE(0x8086, 0x0200), USB_DEVICE_DATA(BOARD_503_ISL3861)},
134         /* Dynalink L11U */
135         {USB_DEVICE(0x0d8e, 0x7100), USB_DEVICE_DATA(BOARD_503_ISL3861)},
136         /* Arescom WL-210, FCC id 07J-GL2411USB */
137         {USB_DEVICE(0x0d8e, 0x7110), USB_DEVICE_DATA(BOARD_503_ISL3861)},
138         /* I-O DATA WN-B11/USB */
139         {USB_DEVICE(0x04bb, 0x0919), USB_DEVICE_DATA(BOARD_503_ISL3861)},
140         /* BT Voyager 1010 */
141         {USB_DEVICE(0x069a, 0x0821), USB_DEVICE_DATA(BOARD_503_ISL3861)},
142         /*
143          * at76c503-i3863
144          */
145         /* Generic AT76C503/3863 device */
146         {USB_DEVICE(0x03eb, 0x7604), USB_DEVICE_DATA(BOARD_503_ISL3863)},
147         /* Samsung SWL-2100U */
148         {USB_DEVICE(0x055d, 0xa000), USB_DEVICE_DATA(BOARD_503_ISL3863)},
149         /*
150          * at76c503-rfmd
151          */
152         /* Generic AT76C503/RFMD device */
153         {USB_DEVICE(0x03eb, 0x7605), USB_DEVICE_DATA(BOARD_503)},
154         /* Dynalink/Askey WLL013 (rfmd) */
155         {USB_DEVICE(0x069a, 0x0321), USB_DEVICE_DATA(BOARD_503)},
156         /* Linksys WUSB11 v2.6 */
157         {USB_DEVICE(0x077b, 0x2219), USB_DEVICE_DATA(BOARD_503)},
158         /* Network Everywhere NWU11B */
159         {USB_DEVICE(0x077b, 0x2227), USB_DEVICE_DATA(BOARD_503)},
160         /* Netgear MA101 rev. B */
161         {USB_DEVICE(0x0864, 0x4102), USB_DEVICE_DATA(BOARD_503)},
162         /* D-Link DWL-120 rev. E */
163         {USB_DEVICE(0x2001, 0x3200), USB_DEVICE_DATA(BOARD_503)},
164         /* Actiontec 802UAT1, HWU01150-01UK */
165         {USB_DEVICE(0x1668, 0x7605), USB_DEVICE_DATA(BOARD_503)},
166         /* AirVast W-Buddie WN210 */
167         {USB_DEVICE(0x03eb, 0x4102), USB_DEVICE_DATA(BOARD_503)},
168         /* Dick Smith Electronics XH1153 802.11b USB adapter */
169         {USB_DEVICE(0x1371, 0x5743), USB_DEVICE_DATA(BOARD_503)},
170         /* CNet CNUSB611 */
171         {USB_DEVICE(0x1371, 0x0001), USB_DEVICE_DATA(BOARD_503)},
172         /* FiberLine FL-WL200U */
173         {USB_DEVICE(0x1371, 0x0002), USB_DEVICE_DATA(BOARD_503)},
174         /* BenQ AWL400 USB stick */
175         {USB_DEVICE(0x04a5, 0x9001), USB_DEVICE_DATA(BOARD_503)},
176         /* 3Com 3CRSHEW696 */
177         {USB_DEVICE(0x0506, 0x0a01), USB_DEVICE_DATA(BOARD_503)},
178         /* Siemens Santis ADSL WLAN USB adapter WLL 013 */
179         {USB_DEVICE(0x0681, 0x001b), USB_DEVICE_DATA(BOARD_503)},
180         /* Belkin F5D6050, version 2 */
181         {USB_DEVICE(0x050d, 0x0050), USB_DEVICE_DATA(BOARD_503)},
182         /* iBlitzz, BWU613 (not *B or *SB) */
183         {USB_DEVICE(0x07b8, 0xb000), USB_DEVICE_DATA(BOARD_503)},
184         /* Gigabyte GN-WLBM101 */
185         {USB_DEVICE(0x1044, 0x8003), USB_DEVICE_DATA(BOARD_503)},
186         /* Planex GW-US11S */
187         {USB_DEVICE(0x2019, 0x3220), USB_DEVICE_DATA(BOARD_503)},
188         /* Internal WLAN adapter in h5[4,5]xx series iPAQs */
189         {USB_DEVICE(0x049f, 0x0032), USB_DEVICE_DATA(BOARD_503)},
190         /* Corega Wireless LAN USB-11 mini */
191         {USB_DEVICE(0x07aa, 0x0011), USB_DEVICE_DATA(BOARD_503)},
192         /* Corega Wireless LAN USB-11 mini2 */
193         {USB_DEVICE(0x07aa, 0x0018), USB_DEVICE_DATA(BOARD_503)},
194         /* Uniden PCW100 */
195         {USB_DEVICE(0x05dd, 0xff35), USB_DEVICE_DATA(BOARD_503)},
196         /*
197          * at76c503-rfmd-acc
198          */
199         /* SMC2664W */
200         {USB_DEVICE(0x083a, 0x3501), USB_DEVICE_DATA(BOARD_503_ACC)},
201         /* Belkin F5D6050, SMC2662W v2, SMC2662W-AR */
202         {USB_DEVICE(0x0d5c, 0xa002), USB_DEVICE_DATA(BOARD_503_ACC)},
203         /*
204          * at76c505-rfmd
205          */
206         /* Generic AT76C505/RFMD */
207         {USB_DEVICE(0x03eb, 0x7606), USB_DEVICE_DATA(BOARD_505)},
208         /*
209          * at76c505-rfmd2958
210          */
211         /* Generic AT76C505/RFMD, OvisLink WL-1130USB */
212         {USB_DEVICE(0x03eb, 0x7613), USB_DEVICE_DATA(BOARD_505_2958)},
213         /* Fiberline FL-WL240U */
214         {USB_DEVICE(0x1371, 0x0014), USB_DEVICE_DATA(BOARD_505_2958)},
215         /* CNet CNUSB-611G */
216         {USB_DEVICE(0x1371, 0x0013), USB_DEVICE_DATA(BOARD_505_2958)},
217         /* Linksys WUSB11 v2.8 */
218         {USB_DEVICE(0x1915, 0x2233), USB_DEVICE_DATA(BOARD_505_2958)},
219         /* Xterasys XN-2122B, IBlitzz BWU613B/BWU613SB */
220         {USB_DEVICE(0x12fd, 0x1001), USB_DEVICE_DATA(BOARD_505_2958)},
221         /* Corega WLAN USB Stick 11 */
222         {USB_DEVICE(0x07aa, 0x7613), USB_DEVICE_DATA(BOARD_505_2958)},
223         /* Microstar MSI Box MS6978 */
224         {USB_DEVICE(0x0db0, 0x1020), USB_DEVICE_DATA(BOARD_505_2958)},
225         /*
226          * at76c505a-rfmd2958
227          */
228         /* Generic AT76C505A device */
229         {USB_DEVICE(0x03eb, 0x7614), USB_DEVICE_DATA(BOARD_505A)},
230         /* Generic AT76C505AS device */
231         {USB_DEVICE(0x03eb, 0x7617), USB_DEVICE_DATA(BOARD_505A)},
232         /* Siemens Gigaset USB WLAN Adapter 11 */
233         {USB_DEVICE(0x1690, 0x0701), USB_DEVICE_DATA(BOARD_505A)},
234         /*
235          * at76c505amx-rfmd
236          */
237         /* Generic AT76C505AMX device */
238         {USB_DEVICE(0x03eb, 0x7615), USB_DEVICE_DATA(BOARD_505AMX)},
239         {}
240 };
241
242 MODULE_DEVICE_TABLE(usb, dev_table);
243
244 /* Supported rates of this hardware, bit 7 marks basic rates */
245 static const u8 hw_rates[] = { 0x82, 0x84, 0x0b, 0x16 };
246
247 /* Frequency of each channel in MHz */
248 static const long channel_frequency[] = {
249         2412, 2417, 2422, 2427, 2432, 2437, 2442,
250         2447, 2452, 2457, 2462, 2467, 2472, 2484
251 };
252
253 #define NUM_CHANNELS ARRAY_SIZE(channel_frequency)
254
255 static const char *const preambles[] = { "long", "short", "auto" };
256
257 static const char *const mac_states[] = {
258         [MAC_INIT] = "INIT",
259         [MAC_SCANNING] = "SCANNING",
260         [MAC_AUTH] = "AUTH",
261         [MAC_ASSOC] = "ASSOC",
262         [MAC_JOINING] = "JOINING",
263         [MAC_CONNECTED] = "CONNECTED",
264         [MAC_OWN_IBSS] = "OWN_IBSS"
265 };
266
267 /* Firmware download */
268 /* DFU states */
269 #define STATE_IDLE                      0x00
270 #define STATE_DETACH                    0x01
271 #define STATE_DFU_IDLE                  0x02
272 #define STATE_DFU_DOWNLOAD_SYNC         0x03
273 #define STATE_DFU_DOWNLOAD_BUSY         0x04
274 #define STATE_DFU_DOWNLOAD_IDLE         0x05
275 #define STATE_DFU_MANIFEST_SYNC         0x06
276 #define STATE_DFU_MANIFEST              0x07
277 #define STATE_DFU_MANIFEST_WAIT_RESET   0x08
278 #define STATE_DFU_UPLOAD_IDLE           0x09
279 #define STATE_DFU_ERROR                 0x0a
280
281 /* DFU commands */
282 #define DFU_DETACH                      0
283 #define DFU_DNLOAD                      1
284 #define DFU_UPLOAD                      2
285 #define DFU_GETSTATUS                   3
286 #define DFU_CLRSTATUS                   4
287 #define DFU_GETSTATE                    5
288 #define DFU_ABORT                       6
289
290 #define FW_BLOCK_SIZE 1024
291
292 struct dfu_status {
293         unsigned char status;
294         unsigned char poll_timeout[3];
295         unsigned char state;
296         unsigned char string;
297 } __attribute__((packed));
298
299 static inline int at76_is_intersil(enum board_type board)
300 {
301         return (board == BOARD_503_ISL3861 || board == BOARD_503_ISL3863);
302 }
303
304 static inline int at76_is_503rfmd(enum board_type board)
305 {
306         return (board == BOARD_503 || board == BOARD_503_ACC);
307 }
308
309 static inline int at76_is_505a(enum board_type board)
310 {
311         return (board == BOARD_505A || board == BOARD_505AMX);
312 }
313
314 /* Load a block of the first (internal) part of the firmware */
315 static int at76_load_int_fw_block(struct usb_device *udev, int blockno,
316                                   void *block, int size)
317 {
318         return usb_control_msg(udev, usb_sndctrlpipe(udev, 0), DFU_DNLOAD,
319                                USB_TYPE_CLASS | USB_DIR_OUT |
320                                USB_RECIP_INTERFACE, blockno, 0, block, size,
321                                USB_CTRL_GET_TIMEOUT);
322 }
323
324 static int at76_dfu_get_status(struct usb_device *udev,
325                                struct dfu_status *status)
326 {
327         int ret;
328
329         ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), DFU_GETSTATUS,
330                               USB_TYPE_CLASS | USB_DIR_IN | USB_RECIP_INTERFACE,
331                               0, 0, status, sizeof(struct dfu_status),
332                               USB_CTRL_GET_TIMEOUT);
333         return ret;
334 }
335
336 static u8 at76_dfu_get_state(struct usb_device *udev, u8 *state)
337 {
338         int ret;
339
340         ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), DFU_GETSTATE,
341                               USB_TYPE_CLASS | USB_DIR_IN | USB_RECIP_INTERFACE,
342                               0, 0, state, 1, USB_CTRL_GET_TIMEOUT);
343         return ret;
344 }
345
346 /* Convert timeout from the DFU status to jiffies */
347 static inline unsigned long at76_get_timeout(struct dfu_status *s)
348 {
349         return msecs_to_jiffies((s->poll_timeout[2] << 16)
350                                 | (s->poll_timeout[1] << 8)
351                                 | (s->poll_timeout[0]));
352 }
353
354 /* Load internal firmware from the buffer.  If manifest_sync_timeout > 0, use
355  * its value in jiffies in the MANIFEST_SYNC state.  */
356 static int at76_usbdfu_download(struct usb_device *udev, u8 *buf, u32 size,
357                                 int manifest_sync_timeout)
358 {
359         u8 *block;
360         struct dfu_status dfu_stat_buf;
361         int ret = 0;
362         int need_dfu_state = 1;
363         int is_done = 0;
364         u8 dfu_state = 0;
365         u32 dfu_timeout = 0;
366         int bsize = 0;
367         int blockno = 0;
368
369         at76_dbg(DBG_DFU, "%s( %p, %u, %d)", __func__, buf, size,
370                  manifest_sync_timeout);
371
372         if (!size) {
373                 dev_printk(KERN_ERR, &udev->dev, "FW buffer length invalid!\n");
374                 return -EINVAL;
375         }
376
377         block = kmalloc(FW_BLOCK_SIZE, GFP_KERNEL);
378         if (!block)
379                 return -ENOMEM;
380
381         do {
382                 if (need_dfu_state) {
383                         ret = at76_dfu_get_state(udev, &dfu_state);
384                         if (ret < 0) {
385                                 dev_printk(KERN_ERR, &udev->dev,
386                                            "cannot get DFU state: %d\n", ret);
387                                 goto exit;
388                         }
389                         need_dfu_state = 0;
390                 }
391
392                 switch (dfu_state) {
393                 case STATE_DFU_DOWNLOAD_SYNC:
394                         at76_dbg(DBG_DFU, "STATE_DFU_DOWNLOAD_SYNC");
395                         ret = at76_dfu_get_status(udev, &dfu_stat_buf);
396                         if (ret >= 0) {
397                                 dfu_state = dfu_stat_buf.state;
398                                 dfu_timeout = at76_get_timeout(&dfu_stat_buf);
399                                 need_dfu_state = 0;
400                         } else
401                                 dev_printk(KERN_ERR, &udev->dev,
402                                            "at76_dfu_get_status returned %d\n",
403                                            ret);
404                         break;
405
406                 case STATE_DFU_DOWNLOAD_BUSY:
407                         at76_dbg(DBG_DFU, "STATE_DFU_DOWNLOAD_BUSY");
408                         need_dfu_state = 1;
409
410                         at76_dbg(DBG_DFU, "DFU: Resetting device");
411                         schedule_timeout_interruptible(dfu_timeout);
412                         break;
413
414                 case STATE_DFU_DOWNLOAD_IDLE:
415                         at76_dbg(DBG_DFU, "DOWNLOAD...");
416                         /* fall through */
417                 case STATE_DFU_IDLE:
418                         at76_dbg(DBG_DFU, "DFU IDLE");
419
420                         bsize = min_t(int, size, FW_BLOCK_SIZE);
421                         memcpy(block, buf, bsize);
422                         at76_dbg(DBG_DFU, "int fw, size left = %5d, "
423                                  "bsize = %4d, blockno = %2d", size, bsize,
424                                  blockno);
425                         ret =
426                             at76_load_int_fw_block(udev, blockno, block, bsize);
427                         buf += bsize;
428                         size -= bsize;
429                         blockno++;
430
431                         if (ret != bsize)
432                                 dev_printk(KERN_ERR, &udev->dev,
433                                            "at76_load_int_fw_block "
434                                            "returned %d\n", ret);
435                         need_dfu_state = 1;
436                         break;
437
438                 case STATE_DFU_MANIFEST_SYNC:
439                         at76_dbg(DBG_DFU, "STATE_DFU_MANIFEST_SYNC");
440
441                         ret = at76_dfu_get_status(udev, &dfu_stat_buf);
442                         if (ret < 0)
443                                 break;
444
445                         dfu_state = dfu_stat_buf.state;
446                         dfu_timeout = at76_get_timeout(&dfu_stat_buf);
447                         need_dfu_state = 0;
448
449                         /* override the timeout from the status response,
450                            needed for AT76C505A */
451                         if (manifest_sync_timeout > 0)
452                                 dfu_timeout = manifest_sync_timeout;
453
454                         at76_dbg(DBG_DFU, "DFU: Waiting for manifest phase");
455                         schedule_timeout_interruptible(dfu_timeout);
456                         break;
457
458                 case STATE_DFU_MANIFEST:
459                         at76_dbg(DBG_DFU, "STATE_DFU_MANIFEST");
460                         is_done = 1;
461                         break;
462
463                 case STATE_DFU_MANIFEST_WAIT_RESET:
464                         at76_dbg(DBG_DFU, "STATE_DFU_MANIFEST_WAIT_RESET");
465                         is_done = 1;
466                         break;
467
468                 case STATE_DFU_UPLOAD_IDLE:
469                         at76_dbg(DBG_DFU, "STATE_DFU_UPLOAD_IDLE");
470                         break;
471
472                 case STATE_DFU_ERROR:
473                         at76_dbg(DBG_DFU, "STATE_DFU_ERROR");
474                         ret = -EPIPE;
475                         break;
476
477                 default:
478                         at76_dbg(DBG_DFU, "DFU UNKNOWN STATE (%d)", dfu_state);
479                         ret = -EINVAL;
480                         break;
481                 }
482         } while (!is_done && (ret >= 0));
483
484 exit:
485         kfree(block);
486         if (ret >= 0)
487                 ret = 0;
488
489         return ret;
490 }
491
492 /* Report that the scan results are ready */
493 static inline void at76_iwevent_scan_complete(struct net_device *netdev)
494 {
495         union iwreq_data wrqu;
496         wrqu.data.length = 0;
497         wrqu.data.flags = 0;
498         wireless_send_event(netdev, SIOCGIWSCAN, &wrqu, NULL);
499         at76_dbg(DBG_WE_EVENTS, "%s: SIOCGIWSCAN sent", netdev->name);
500 }
501
502 static inline void at76_iwevent_bss_connect(struct net_device *netdev,
503                                             u8 *bssid)
504 {
505         union iwreq_data wrqu;
506         wrqu.data.length = 0;
507         wrqu.data.flags = 0;
508         memcpy(wrqu.ap_addr.sa_data, bssid, ETH_ALEN);
509         wrqu.ap_addr.sa_family = ARPHRD_ETHER;
510         wireless_send_event(netdev, SIOCGIWAP, &wrqu, NULL);
511         at76_dbg(DBG_WE_EVENTS, "%s: %s: SIOCGIWAP sent", netdev->name,
512                  __func__);
513 }
514
515 static inline void at76_iwevent_bss_disconnect(struct net_device *netdev)
516 {
517         union iwreq_data wrqu;
518         wrqu.data.length = 0;
519         wrqu.data.flags = 0;
520         memset(wrqu.ap_addr.sa_data, 0, ETH_ALEN);
521         wrqu.ap_addr.sa_family = ARPHRD_ETHER;
522         wireless_send_event(netdev, SIOCGIWAP, &wrqu, NULL);
523         at76_dbg(DBG_WE_EVENTS, "%s: %s: SIOCGIWAP sent", netdev->name,
524                  __func__);
525 }
526
527 #define HEX2STR_BUFFERS 4
528 #define HEX2STR_MAX_LEN 64
529 #define BIN2HEX(x) ((x) < 10 ? '0' + (x) : (x) + 'A' - 10)
530
531 /* Convert binary data into hex string */
532 static char *hex2str(void *buf, int len)
533 {
534         static atomic_t a = ATOMIC_INIT(0);
535         static char bufs[HEX2STR_BUFFERS][3 * HEX2STR_MAX_LEN + 1];
536         char *ret = bufs[atomic_inc_return(&a) & (HEX2STR_BUFFERS - 1)];
537         char *obuf = ret;
538         u8 *ibuf = buf;
539
540         if (len > HEX2STR_MAX_LEN)
541                 len = HEX2STR_MAX_LEN;
542
543         if (len <= 0) {
544                 ret[0] = '\0';
545                 return ret;
546         }
547
548         while (len--) {
549                 *obuf++ = BIN2HEX(*ibuf >> 4);
550                 *obuf++ = BIN2HEX(*ibuf & 0xf);
551                 *obuf++ = '-';
552                 ibuf++;
553         }
554         *(--obuf) = '\0';
555
556         return ret;
557 }
558
559 #define MAC2STR_BUFFERS 4
560
561 static inline char *mac2str(u8 *mac)
562 {
563         static atomic_t a = ATOMIC_INIT(0);
564         static char bufs[MAC2STR_BUFFERS][6 * 3];
565         char *str;
566
567         str = bufs[atomic_inc_return(&a) & (MAC2STR_BUFFERS - 1)];
568         sprintf(str, "%02x:%02x:%02x:%02x:%02x:%02x",
569                 mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
570         return str;
571 }
572
573 /* LED trigger */
574 static int tx_activity;
575 static void at76_ledtrig_tx_timerfunc(unsigned long data);
576 static DEFINE_TIMER(ledtrig_tx_timer, at76_ledtrig_tx_timerfunc, 0, 0);
577 DEFINE_LED_TRIGGER(ledtrig_tx);
578
579 static void at76_ledtrig_tx_timerfunc(unsigned long data)
580 {
581         static int tx_lastactivity;
582
583         if (tx_lastactivity != tx_activity) {
584                 tx_lastactivity = tx_activity;
585                 led_trigger_event(ledtrig_tx, LED_FULL);
586                 mod_timer(&ledtrig_tx_timer, jiffies + HZ / 4);
587         } else
588                 led_trigger_event(ledtrig_tx, LED_OFF);
589 }
590
591 static void at76_ledtrig_tx_activity(void)
592 {
593         tx_activity++;
594         if (!timer_pending(&ledtrig_tx_timer))
595                 mod_timer(&ledtrig_tx_timer, jiffies + HZ / 4);
596 }
597
598 /* Check if the given ssid is hidden */
599 static inline int at76_is_hidden_ssid(u8 *ssid, int length)
600 {
601         static const u8 zeros[32];
602
603         if (length == 0)
604                 return 1;
605
606         if (length == 1 && ssid[0] == ' ')
607                 return 1;
608
609         return (memcmp(ssid, zeros, length) == 0);
610 }
611
612 static inline void at76_free_bss_list(struct at76_priv *priv)
613 {
614         struct list_head *next, *ptr;
615         unsigned long flags;
616
617         spin_lock_irqsave(&priv->bss_list_spinlock, flags);
618
619         priv->curr_bss = NULL;
620
621         list_for_each_safe(ptr, next, &priv->bss_list) {
622                 list_del(ptr);
623                 kfree(list_entry(ptr, struct bss_info, list));
624         }
625
626         spin_unlock_irqrestore(&priv->bss_list_spinlock, flags);
627 }
628
629 static int at76_remap(struct usb_device *udev)
630 {
631         int ret;
632         ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0a,
633                               USB_TYPE_VENDOR | USB_DIR_OUT |
634                               USB_RECIP_INTERFACE, 0, 0, NULL, 0,
635                               USB_CTRL_GET_TIMEOUT);
636         if (ret < 0)
637                 return ret;
638         return 0;
639 }
640
641 static int at76_get_op_mode(struct usb_device *udev)
642 {
643         int ret;
644         u8 op_mode;
645
646         ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33,
647                               USB_TYPE_VENDOR | USB_DIR_IN |
648                               USB_RECIP_INTERFACE, 0x01, 0, &op_mode, 1,
649                               USB_CTRL_GET_TIMEOUT);
650         if (ret < 0)
651                 return ret;
652         else if (ret < 1)
653                 return -EIO;
654         else
655                 return op_mode;
656 }
657
658 /* Load a block of the second ("external") part of the firmware */
659 static inline int at76_load_ext_fw_block(struct usb_device *udev, int blockno,
660                                          void *block, int size)
661 {
662         return usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0e,
663                                USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
664                                0x0802, blockno, block, size,
665                                USB_CTRL_GET_TIMEOUT);
666 }
667
668 static inline int at76_get_hw_cfg(struct usb_device *udev,
669                                   union at76_hwcfg *buf, int buf_size)
670 {
671         return usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33,
672                                USB_TYPE_VENDOR | USB_DIR_IN |
673                                USB_RECIP_INTERFACE, 0x0a02, 0,
674                                buf, buf_size, USB_CTRL_GET_TIMEOUT);
675 }
676
677 /* Intersil boards use a different "value" for GetHWConfig requests */
678 static inline int at76_get_hw_cfg_intersil(struct usb_device *udev,
679                                            union at76_hwcfg *buf, int buf_size)
680 {
681         return usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33,
682                                USB_TYPE_VENDOR | USB_DIR_IN |
683                                USB_RECIP_INTERFACE, 0x0902, 0,
684                                buf, buf_size, USB_CTRL_GET_TIMEOUT);
685 }
686
687 /* Get the hardware configuration for the adapter and put it to the appropriate
688  * fields of 'priv' (the GetHWConfig request and interpretation of the result
689  * depends on the board type) */
690 static int at76_get_hw_config(struct at76_priv *priv)
691 {
692         int ret;
693         union at76_hwcfg *hwcfg = kmalloc(sizeof(*hwcfg), GFP_KERNEL);
694
695         if (!hwcfg)
696                 return -ENOMEM;
697
698         if (at76_is_intersil(priv->board_type)) {
699                 ret = at76_get_hw_cfg_intersil(priv->udev, hwcfg,
700                                                sizeof(hwcfg->i));
701                 if (ret < 0)
702                         goto exit;
703                 memcpy(priv->mac_addr, hwcfg->i.mac_addr, ETH_ALEN);
704                 priv->regulatory_domain = hwcfg->i.regulatory_domain;
705         } else if (at76_is_503rfmd(priv->board_type)) {
706                 ret = at76_get_hw_cfg(priv->udev, hwcfg, sizeof(hwcfg->r3));
707                 if (ret < 0)
708                         goto exit;
709                 memcpy(priv->mac_addr, hwcfg->r3.mac_addr, ETH_ALEN);
710                 priv->regulatory_domain = hwcfg->r3.regulatory_domain;
711         } else {
712                 ret = at76_get_hw_cfg(priv->udev, hwcfg, sizeof(hwcfg->r5));
713                 if (ret < 0)
714                         goto exit;
715                 memcpy(priv->mac_addr, hwcfg->r5.mac_addr, ETH_ALEN);
716                 priv->regulatory_domain = hwcfg->r5.regulatory_domain;
717         }
718
719 exit:
720         kfree(hwcfg);
721         if (ret < 0)
722                 printk(KERN_ERR "%s: cannot get HW Config (error %d)\n",
723                        priv->netdev->name, ret);
724
725         return ret;
726 }
727
728 static struct reg_domain const *at76_get_reg_domain(u16 code)
729 {
730         int i;
731         static struct reg_domain const fd_tab[] = {
732                 {0x10, "FCC (USA)", 0x7ff},     /* ch 1-11 */
733                 {0x20, "IC (Canada)", 0x7ff},   /* ch 1-11 */
734                 {0x30, "ETSI (most of Europe)", 0x1fff},        /* ch 1-13 */
735                 {0x31, "Spain", 0x600}, /* ch 10-11 */
736                 {0x32, "France", 0x1e00},       /* ch 10-13 */
737                 {0x40, "MKK (Japan)", 0x2000},  /* ch 14 */
738                 {0x41, "MKK1 (Japan)", 0x3fff}, /* ch 1-14 */
739                 {0x50, "Israel", 0x3fc},        /* ch 3-9 */
740                 {0x00, "<unknown>", 0xffffffff} /* ch 1-32 */
741         };
742
743         /* Last entry is fallback for unknown domain code */
744         for (i = 0; i < ARRAY_SIZE(fd_tab) - 1; i++)
745                 if (code == fd_tab[i].code)
746                         break;
747
748         return &fd_tab[i];
749 }
750
751 static inline int at76_get_mib(struct usb_device *udev, u16 mib, void *buf,
752                                int buf_size)
753 {
754         int ret;
755
756         ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33,
757                               USB_TYPE_VENDOR | USB_DIR_IN |
758                               USB_RECIP_INTERFACE, mib << 8, 0, buf, buf_size,
759                               USB_CTRL_GET_TIMEOUT);
760         if (ret >= 0 && ret != buf_size)
761                 return -EIO;
762         return ret;
763 }
764
765 /* Return positive number for status, negative for an error */
766 static inline int at76_get_cmd_status(struct usb_device *udev, u8 cmd)
767 {
768         u8 stat_buf[40];
769         int ret;
770
771         ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x22,
772                               USB_TYPE_VENDOR | USB_DIR_IN |
773                               USB_RECIP_INTERFACE, cmd, 0, stat_buf,
774                               sizeof(stat_buf), USB_CTRL_GET_TIMEOUT);
775         if (ret < 0)
776                 return ret;
777
778         return stat_buf[5];
779 }
780
781 static int at76_set_card_command(struct usb_device *udev, int cmd, void *buf,
782                                  int buf_size)
783 {
784         int ret;
785         struct at76_command *cmd_buf = kmalloc(sizeof(struct at76_command) +
786                                                buf_size, GFP_KERNEL);
787
788         if (!cmd_buf)
789                 return -ENOMEM;
790
791         cmd_buf->cmd = cmd;
792         cmd_buf->reserved = 0;
793         cmd_buf->size = cpu_to_le16(buf_size);
794         memcpy(cmd_buf->data, buf, buf_size);
795
796         ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0e,
797                               USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
798                               0, 0, cmd_buf,
799                               sizeof(struct at76_command) + buf_size,
800                               USB_CTRL_GET_TIMEOUT);
801         kfree(cmd_buf);
802         return ret;
803 }
804
805 #define MAKE_CMD_STATUS_CASE(c) case (c): return #c
806 static const char *at76_get_cmd_status_string(u8 cmd_status)
807 {
808         switch (cmd_status) {
809                 MAKE_CMD_STATUS_CASE(CMD_STATUS_IDLE);
810                 MAKE_CMD_STATUS_CASE(CMD_STATUS_COMPLETE);
811                 MAKE_CMD_STATUS_CASE(CMD_STATUS_UNKNOWN);
812                 MAKE_CMD_STATUS_CASE(CMD_STATUS_INVALID_PARAMETER);
813                 MAKE_CMD_STATUS_CASE(CMD_STATUS_FUNCTION_NOT_SUPPORTED);
814                 MAKE_CMD_STATUS_CASE(CMD_STATUS_TIME_OUT);
815                 MAKE_CMD_STATUS_CASE(CMD_STATUS_IN_PROGRESS);
816                 MAKE_CMD_STATUS_CASE(CMD_STATUS_HOST_FAILURE);
817                 MAKE_CMD_STATUS_CASE(CMD_STATUS_SCAN_FAILED);
818         }
819
820         return "UNKNOWN";
821 }
822
823 /* Wait until the command is completed */
824 static int at76_wait_completion(struct at76_priv *priv, int cmd)
825 {
826         int status = 0;
827         unsigned long timeout = jiffies + CMD_COMPLETION_TIMEOUT;
828
829         do {
830                 status = at76_get_cmd_status(priv->udev, cmd);
831                 if (status < 0) {
832                         printk(KERN_ERR "%s: at76_get_cmd_status failed: %d\n",
833                                priv->netdev->name, status);
834                         break;
835                 }
836
837                 at76_dbg(DBG_WAIT_COMPLETE,
838                          "%s: Waiting on cmd %d, status = %d (%s)",
839                          priv->netdev->name, cmd, status,
840                          at76_get_cmd_status_string(status));
841
842                 if (status != CMD_STATUS_IN_PROGRESS
843                     && status != CMD_STATUS_IDLE)
844                         break;
845
846                 schedule_timeout_interruptible(HZ / 10);        /* 100 ms */
847                 if (time_after(jiffies, timeout)) {
848                         printk(KERN_ERR
849                                "%s: completion timeout for command %d\n",
850                                priv->netdev->name, cmd);
851                         status = -ETIMEDOUT;
852                         break;
853                 }
854         } while (1);
855
856         return status;
857 }
858
859 static int at76_set_mib(struct at76_priv *priv, struct set_mib_buffer *buf)
860 {
861         int ret;
862
863         ret = at76_set_card_command(priv->udev, CMD_SET_MIB, buf,
864                                     offsetof(struct set_mib_buffer,
865                                              data) + buf->size);
866         if (ret < 0)
867                 return ret;
868
869         ret = at76_wait_completion(priv, CMD_SET_MIB);
870         if (ret != CMD_STATUS_COMPLETE) {
871                 printk(KERN_INFO
872                        "%s: set_mib: at76_wait_completion failed "
873                        "with %d\n", priv->netdev->name, ret);
874                 ret = -EIO;
875         }
876
877         return ret;
878 }
879
880 /* Return < 0 on error, == 0 if no command sent, == 1 if cmd sent */
881 static int at76_set_radio(struct at76_priv *priv, int enable)
882 {
883         int ret;
884         int cmd;
885
886         if (priv->radio_on == enable)
887                 return 0;
888
889         cmd = enable ? CMD_RADIO_ON : CMD_RADIO_OFF;
890
891         ret = at76_set_card_command(priv->udev, cmd, NULL, 0);
892         if (ret < 0)
893                 printk(KERN_ERR "%s: at76_set_card_command(%d) failed: %d\n",
894                        priv->netdev->name, cmd, ret);
895         else
896                 ret = 1;
897
898         priv->radio_on = enable;
899         return ret;
900 }
901
902 /* Set current power save mode (AT76_PM_OFF/AT76_PM_ON/AT76_PM_SMART) */
903 static int at76_set_pm_mode(struct at76_priv *priv)
904 {
905         int ret = 0;
906
907         priv->mib_buf.type = MIB_MAC_MGMT;
908         priv->mib_buf.size = 1;
909         priv->mib_buf.index = offsetof(struct mib_mac_mgmt, power_mgmt_mode);
910         priv->mib_buf.data.byte = priv->pm_mode;
911
912         ret = at76_set_mib(priv, &priv->mib_buf);
913         if (ret < 0)
914                 printk(KERN_ERR "%s: set_mib (pm_mode) failed: %d\n",
915                        priv->netdev->name, ret);
916
917         return ret;
918 }
919
920 /* Set the association id for power save mode */
921 static int at76_set_associd(struct at76_priv *priv, u16 id)
922 {
923         int ret = 0;
924
925         priv->mib_buf.type = MIB_MAC_MGMT;
926         priv->mib_buf.size = 2;
927         priv->mib_buf.index = offsetof(struct mib_mac_mgmt, station_id);
928         priv->mib_buf.data.word = cpu_to_le16(id);
929
930         ret = at76_set_mib(priv, &priv->mib_buf);
931         if (ret < 0)
932                 printk(KERN_ERR "%s: set_mib (associd) failed: %d\n",
933                        priv->netdev->name, ret);
934
935         return ret;
936 }
937
938 /* Set the listen interval for power save mode */
939 static int at76_set_listen_interval(struct at76_priv *priv, u16 interval)
940 {
941         int ret = 0;
942
943         priv->mib_buf.type = MIB_MAC;
944         priv->mib_buf.size = 2;
945         priv->mib_buf.index = offsetof(struct mib_mac, listen_interval);
946         priv->mib_buf.data.word = cpu_to_le16(interval);
947
948         ret = at76_set_mib(priv, &priv->mib_buf);
949         if (ret < 0)
950                 printk(KERN_ERR
951                        "%s: set_mib (listen_interval) failed: %d\n",
952                        priv->netdev->name, ret);
953
954         return ret;
955 }
956
957 static int at76_set_preamble(struct at76_priv *priv, u8 type)
958 {
959         int ret = 0;
960
961         priv->mib_buf.type = MIB_LOCAL;
962         priv->mib_buf.size = 1;
963         priv->mib_buf.index = offsetof(struct mib_local, preamble_type);
964         priv->mib_buf.data.byte = type;
965
966         ret = at76_set_mib(priv, &priv->mib_buf);
967         if (ret < 0)
968                 printk(KERN_ERR "%s: set_mib (preamble) failed: %d\n",
969                        priv->netdev->name, ret);
970
971         return ret;
972 }
973
974 static int at76_set_frag(struct at76_priv *priv, u16 size)
975 {
976         int ret = 0;
977
978         priv->mib_buf.type = MIB_MAC;
979         priv->mib_buf.size = 2;
980         priv->mib_buf.index = offsetof(struct mib_mac, frag_threshold);
981         priv->mib_buf.data.word = cpu_to_le16(size);
982
983         ret = at76_set_mib(priv, &priv->mib_buf);
984         if (ret < 0)
985                 printk(KERN_ERR "%s: set_mib (frag threshold) failed: %d\n",
986                        priv->netdev->name, ret);
987
988         return ret;
989 }
990
991 static int at76_set_rts(struct at76_priv *priv, u16 size)
992 {
993         int ret = 0;
994
995         priv->mib_buf.type = MIB_MAC;
996         priv->mib_buf.size = 2;
997         priv->mib_buf.index = offsetof(struct mib_mac, rts_threshold);
998         priv->mib_buf.data.word = cpu_to_le16(size);
999
1000         ret = at76_set_mib(priv, &priv->mib_buf);
1001         if (ret < 0)
1002                 printk(KERN_ERR "%s: set_mib (rts) failed: %d\n",
1003                        priv->netdev->name, ret);
1004
1005         return ret;
1006 }
1007
1008 static int at76_set_autorate_fallback(struct at76_priv *priv, int onoff)
1009 {
1010         int ret = 0;
1011
1012         priv->mib_buf.type = MIB_LOCAL;
1013         priv->mib_buf.size = 1;
1014         priv->mib_buf.index = offsetof(struct mib_local, txautorate_fallback);
1015         priv->mib_buf.data.byte = onoff;
1016
1017         ret = at76_set_mib(priv, &priv->mib_buf);
1018         if (ret < 0)
1019                 printk(KERN_ERR "%s: set_mib (autorate fallback) failed: %d\n",
1020                        priv->netdev->name, ret);
1021
1022         return ret;
1023 }
1024
1025 static int at76_add_mac_address(struct at76_priv *priv, void *addr)
1026 {
1027         int ret = 0;
1028
1029         priv->mib_buf.type = MIB_MAC_ADDR;
1030         priv->mib_buf.size = ETH_ALEN;
1031         priv->mib_buf.index = offsetof(struct mib_mac_addr, mac_addr);
1032         memcpy(priv->mib_buf.data.addr, addr, ETH_ALEN);
1033
1034         ret = at76_set_mib(priv, &priv->mib_buf);
1035         if (ret < 0)
1036                 printk(KERN_ERR "%s: set_mib (MAC_ADDR, mac_addr) failed: %d\n",
1037                        priv->netdev->name, ret);
1038
1039         return ret;
1040 }
1041
1042 static void at76_dump_mib_mac_addr(struct at76_priv *priv)
1043 {
1044         int i;
1045         int ret;
1046         struct mib_mac_addr *m = kmalloc(sizeof(struct mib_mac_addr),
1047                                          GFP_KERNEL);
1048
1049         if (!m)
1050                 return;
1051
1052         ret = at76_get_mib(priv->udev, MIB_MAC_ADDR, m,
1053                            sizeof(struct mib_mac_addr));
1054         if (ret < 0) {
1055                 printk(KERN_ERR "%s: at76_get_mib (MAC_ADDR) failed: %d\n",
1056                        priv->netdev->name, ret);
1057                 goto exit;
1058         }
1059
1060         at76_dbg(DBG_MIB, "%s: MIB MAC_ADDR: mac_addr %s res 0x%x 0x%x",
1061                  priv->netdev->name,
1062                  mac2str(m->mac_addr), m->res[0], m->res[1]);
1063         for (i = 0; i < ARRAY_SIZE(m->group_addr); i++)
1064                 at76_dbg(DBG_MIB, "%s: MIB MAC_ADDR: group addr %d: %s, "
1065                          "status %d", priv->netdev->name, i,
1066                          mac2str(m->group_addr[i]), m->group_addr_status[i]);
1067 exit:
1068         kfree(m);
1069 }
1070
1071 static void at76_dump_mib_mac_wep(struct at76_priv *priv)
1072 {
1073         int i;
1074         int ret;
1075         int key_len;
1076         struct mib_mac_wep *m = kmalloc(sizeof(struct mib_mac_wep), GFP_KERNEL);
1077
1078         if (!m)
1079                 return;
1080
1081         ret = at76_get_mib(priv->udev, MIB_MAC_WEP, m,
1082                            sizeof(struct mib_mac_wep));
1083         if (ret < 0) {
1084                 printk(KERN_ERR "%s: at76_get_mib (MAC_WEP) failed: %d\n",
1085                        priv->netdev->name, ret);
1086                 goto exit;
1087         }
1088
1089         at76_dbg(DBG_MIB, "%s: MIB MAC_WEP: priv_invoked %u def_key_id %u "
1090                  "key_len %u excl_unencr %u wep_icv_err %u wep_excluded %u "
1091                  "encr_level %u key %d", priv->netdev->name,
1092                  m->privacy_invoked, m->wep_default_key_id,
1093                  m->wep_key_mapping_len, m->exclude_unencrypted,
1094                  le32_to_cpu(m->wep_icv_error_count),
1095                  le32_to_cpu(m->wep_excluded_count), m->encryption_level,
1096                  m->wep_default_key_id);
1097
1098         key_len = (m->encryption_level == 1) ?
1099             WEP_SMALL_KEY_LEN : WEP_LARGE_KEY_LEN;
1100
1101         for (i = 0; i < WEP_KEYS; i++)
1102                 at76_dbg(DBG_MIB, "%s: MIB MAC_WEP: key %d: %s",
1103                          priv->netdev->name, i,
1104                          hex2str(m->wep_default_keyvalue[i], key_len));
1105 exit:
1106         kfree(m);
1107 }
1108
1109 static void at76_dump_mib_mac_mgmt(struct at76_priv *priv)
1110 {
1111         int ret;
1112         struct mib_mac_mgmt *m = kmalloc(sizeof(struct mib_mac_mgmt),
1113                                          GFP_KERNEL);
1114
1115         if (!m)
1116                 return;
1117
1118         ret = at76_get_mib(priv->udev, MIB_MAC_MGMT, m,
1119                            sizeof(struct mib_mac_mgmt));
1120         if (ret < 0) {
1121                 printk(KERN_ERR "%s: at76_get_mib (MAC_MGMT) failed: %d\n",
1122                        priv->netdev->name, ret);
1123                 goto exit;
1124         }
1125
1126         at76_dbg(DBG_MIB, "%s: MIB MAC_MGMT: beacon_period %d CFP_max_duration "
1127                  "%d medium_occupancy_limit %d station_id 0x%x ATIM_window %d "
1128                  "CFP_mode %d privacy_opt_impl %d DTIM_period %d CFP_period %d "
1129                  "current_bssid %s current_essid %s current_bss_type %d "
1130                  "pm_mode %d ibss_change %d res %d "
1131                  "multi_domain_capability_implemented %d "
1132                  "international_roaming %d country_string %.3s",
1133                  priv->netdev->name, le16_to_cpu(m->beacon_period),
1134                  le16_to_cpu(m->CFP_max_duration),
1135                  le16_to_cpu(m->medium_occupancy_limit),
1136                  le16_to_cpu(m->station_id), le16_to_cpu(m->ATIM_window),
1137                  m->CFP_mode, m->privacy_option_implemented, m->DTIM_period,
1138                  m->CFP_period, mac2str(m->current_bssid),
1139                  hex2str(m->current_essid, IW_ESSID_MAX_SIZE),
1140                  m->current_bss_type, m->power_mgmt_mode, m->ibss_change,
1141                  m->res, m->multi_domain_capability_implemented,
1142                  m->multi_domain_capability_enabled, m->country_string);
1143 exit:
1144         kfree(m);
1145 }
1146
1147 static void at76_dump_mib_mac(struct at76_priv *priv)
1148 {
1149         int ret;
1150         struct mib_mac *m = kmalloc(sizeof(struct mib_mac), GFP_KERNEL);
1151
1152         if (!m)
1153                 return;
1154
1155         ret = at76_get_mib(priv->udev, MIB_MAC, m, sizeof(struct mib_mac));
1156         if (ret < 0) {
1157                 printk(KERN_ERR "%s: at76_get_mib (MAC) failed: %d\n",
1158                        priv->netdev->name, ret);
1159                 goto exit;
1160         }
1161
1162         at76_dbg(DBG_MIB, "%s: MIB MAC: max_tx_msdu_lifetime %d "
1163                  "max_rx_lifetime %d frag_threshold %d rts_threshold %d "
1164                  "cwmin %d cwmax %d short_retry_time %d long_retry_time %d "
1165                  "scan_type %d scan_channel %d probe_delay %u "
1166                  "min_channel_time %d max_channel_time %d listen_int %d "
1167                  "desired_ssid %s desired_bssid %s desired_bsstype %d",
1168                  priv->netdev->name, le32_to_cpu(m->max_tx_msdu_lifetime),
1169                  le32_to_cpu(m->max_rx_lifetime),
1170                  le16_to_cpu(m->frag_threshold), le16_to_cpu(m->rts_threshold),
1171                  le16_to_cpu(m->cwmin), le16_to_cpu(m->cwmax),
1172                  m->short_retry_time, m->long_retry_time, m->scan_type,
1173                  m->scan_channel, le16_to_cpu(m->probe_delay),
1174                  le16_to_cpu(m->min_channel_time),
1175                  le16_to_cpu(m->max_channel_time),
1176                  le16_to_cpu(m->listen_interval),
1177                  hex2str(m->desired_ssid, IW_ESSID_MAX_SIZE),
1178                  mac2str(m->desired_bssid), m->desired_bsstype);
1179 exit:
1180         kfree(m);
1181 }
1182
1183 static void at76_dump_mib_phy(struct at76_priv *priv)
1184 {
1185         int ret;
1186         struct mib_phy *m = kmalloc(sizeof(struct mib_phy), GFP_KERNEL);
1187
1188         if (!m)
1189                 return;
1190
1191         ret = at76_get_mib(priv->udev, MIB_PHY, m, sizeof(struct mib_phy));
1192         if (ret < 0) {
1193                 printk(KERN_ERR "%s: at76_get_mib (PHY) failed: %d\n",
1194                        priv->netdev->name, ret);
1195                 goto exit;
1196         }
1197
1198         at76_dbg(DBG_MIB, "%s: MIB PHY: ed_threshold %d slot_time %d "
1199                  "sifs_time %d preamble_length %d plcp_header_length %d "
1200                  "mpdu_max_length %d cca_mode_supported %d operation_rate_set "
1201                  "0x%x 0x%x 0x%x 0x%x channel_id %d current_cca_mode %d "
1202                  "phy_type %d current_reg_domain %d",
1203                  priv->netdev->name, le32_to_cpu(m->ed_threshold),
1204                  le16_to_cpu(m->slot_time), le16_to_cpu(m->sifs_time),
1205                  le16_to_cpu(m->preamble_length),
1206                  le16_to_cpu(m->plcp_header_length),
1207                  le16_to_cpu(m->mpdu_max_length),
1208                  le16_to_cpu(m->cca_mode_supported), m->operation_rate_set[0],
1209                  m->operation_rate_set[1], m->operation_rate_set[2],
1210                  m->operation_rate_set[3], m->channel_id, m->current_cca_mode,
1211                  m->phy_type, m->current_reg_domain);
1212 exit:
1213         kfree(m);
1214 }
1215
1216 static void at76_dump_mib_local(struct at76_priv *priv)
1217 {
1218         int ret;
1219         struct mib_local *m = kmalloc(sizeof(struct mib_phy), GFP_KERNEL);
1220
1221         if (!m)
1222                 return;
1223
1224         ret = at76_get_mib(priv->udev, MIB_LOCAL, m, sizeof(struct mib_local));
1225         if (ret < 0) {
1226                 printk(KERN_ERR "%s: at76_get_mib (LOCAL) failed: %d\n",
1227                        priv->netdev->name, ret);
1228                 goto exit;
1229         }
1230
1231         at76_dbg(DBG_MIB, "%s: MIB LOCAL: beacon_enable %d "
1232                  "txautorate_fallback %d ssid_size %d promiscuous_mode %d "
1233                  "preamble_type %d", priv->netdev->name, m->beacon_enable,
1234                  m->txautorate_fallback, m->ssid_size, m->promiscuous_mode,
1235                  m->preamble_type);
1236 exit:
1237         kfree(m);
1238 }
1239
1240 static void at76_dump_mib_mdomain(struct at76_priv *priv)
1241 {
1242         int ret;
1243         struct mib_mdomain *m = kmalloc(sizeof(struct mib_mdomain), GFP_KERNEL);
1244
1245         if (!m)
1246                 return;
1247
1248         ret = at76_get_mib(priv->udev, MIB_MDOMAIN, m,
1249                            sizeof(struct mib_mdomain));
1250         if (ret < 0) {
1251                 printk(KERN_ERR "%s: at76_get_mib (MDOMAIN) failed: %d\n",
1252                        priv->netdev->name, ret);
1253                 goto exit;
1254         }
1255
1256         at76_dbg(DBG_MIB, "%s: MIB MDOMAIN: channel_list %s",
1257                  priv->netdev->name,
1258                  hex2str(m->channel_list, sizeof(m->channel_list)));
1259
1260         at76_dbg(DBG_MIB, "%s: MIB MDOMAIN: tx_powerlevel %s",
1261                  priv->netdev->name,
1262                  hex2str(m->tx_powerlevel, sizeof(m->tx_powerlevel)));
1263 exit:
1264         kfree(m);
1265 }
1266
1267 static int at76_get_current_bssid(struct at76_priv *priv)
1268 {
1269         int ret = 0;
1270         struct mib_mac_mgmt *mac_mgmt =
1271             kmalloc(sizeof(struct mib_mac_mgmt), GFP_KERNEL);
1272
1273         if (!mac_mgmt) {
1274                 ret = -ENOMEM;
1275                 goto exit;
1276         }
1277
1278         ret = at76_get_mib(priv->udev, MIB_MAC_MGMT, mac_mgmt,
1279                            sizeof(struct mib_mac_mgmt));
1280         if (ret < 0) {
1281                 printk(KERN_ERR "%s: at76_get_mib failed: %d\n",
1282                        priv->netdev->name, ret);
1283                 goto error;
1284         }
1285         memcpy(priv->bssid, mac_mgmt->current_bssid, ETH_ALEN);
1286         printk(KERN_INFO "%s: using BSSID %s\n", priv->netdev->name,
1287                mac2str(priv->bssid));
1288 error:
1289         kfree(mac_mgmt);
1290 exit:
1291         return ret;
1292 }
1293
1294 static int at76_get_current_channel(struct at76_priv *priv)
1295 {
1296         int ret = 0;
1297         struct mib_phy *phy = kmalloc(sizeof(struct mib_phy), GFP_KERNEL);
1298
1299         if (!phy) {
1300                 ret = -ENOMEM;
1301                 goto exit;
1302         }
1303         ret = at76_get_mib(priv->udev, MIB_PHY, phy, sizeof(struct mib_phy));
1304         if (ret < 0) {
1305                 printk(KERN_ERR "%s: at76_get_mib(MIB_PHY) failed: %d\n",
1306                        priv->netdev->name, ret);
1307                 goto error;
1308         }
1309         priv->channel = phy->channel_id;
1310 error:
1311         kfree(phy);
1312 exit:
1313         return ret;
1314 }
1315
1316 /**
1317  * at76_start_scan - start a scan
1318  *
1319  * @use_essid - use the configured ESSID in non passive mode
1320  */
1321 static int at76_start_scan(struct at76_priv *priv, int use_essid)
1322 {
1323         struct at76_req_scan scan;
1324
1325         memset(&scan, 0, sizeof(struct at76_req_scan));
1326         memset(scan.bssid, 0xff, ETH_ALEN);
1327
1328         if (use_essid) {
1329                 memcpy(scan.essid, priv->essid, IW_ESSID_MAX_SIZE);
1330                 scan.essid_size = priv->essid_size;
1331         } else
1332                 scan.essid_size = 0;
1333
1334         /* jal: why should we start at a certain channel? we do scan the whole
1335            range allowed by reg domain. */
1336         scan.channel = priv->channel;
1337
1338         /* atmelwlandriver differs between scan type 0 and 1 (active/passive)
1339            For ad-hoc mode, it uses type 0 only. */
1340         scan.scan_type = priv->scan_mode;
1341
1342         /* INFO: For probe_delay, not multiplying by 1024 as this will be
1343            slightly less than min_channel_time
1344            (per spec: probe delay < min. channel time) */
1345         scan.min_channel_time = cpu_to_le16(priv->scan_min_time);
1346         scan.max_channel_time = cpu_to_le16(priv->scan_max_time);
1347         scan.probe_delay = cpu_to_le16(priv->scan_min_time * 1000);
1348         scan.international_scan = 0;
1349
1350         /* other values are set to 0 for type 0 */
1351
1352         at76_dbg(DBG_PROGRESS, "%s: start_scan (use_essid = %d, intl = %d, "
1353                  "channel = %d, probe_delay = %d, scan_min_time = %d, "
1354                  "scan_max_time = %d)",
1355                  priv->netdev->name, use_essid,
1356                  scan.international_scan, scan.channel,
1357                  le16_to_cpu(scan.probe_delay),
1358                  le16_to_cpu(scan.min_channel_time),
1359                  le16_to_cpu(scan.max_channel_time));
1360
1361         return at76_set_card_command(priv->udev, CMD_SCAN, &scan, sizeof(scan));
1362 }
1363
1364 /* Enable monitor mode */
1365 static int at76_start_monitor(struct at76_priv *priv)
1366 {
1367         struct at76_req_scan scan;
1368         int ret;
1369
1370         memset(&scan, 0, sizeof(struct at76_req_scan));
1371         memset(scan.bssid, 0xff, ETH_ALEN);
1372
1373         scan.channel = priv->channel;
1374         scan.scan_type = SCAN_TYPE_PASSIVE;
1375         scan.international_scan = 0;
1376
1377         ret = at76_set_card_command(priv->udev, CMD_SCAN, &scan, sizeof(scan));
1378         if (ret >= 0)
1379                 ret = at76_get_cmd_status(priv->udev, CMD_SCAN);
1380
1381         return ret;
1382 }
1383
1384 static int at76_start_ibss(struct at76_priv *priv)
1385 {
1386         struct at76_req_ibss bss;
1387         int ret;
1388
1389         WARN_ON(priv->mac_state != MAC_OWN_IBSS);
1390         if (priv->mac_state != MAC_OWN_IBSS)
1391                 return -EBUSY;
1392
1393         memset(&bss, 0, sizeof(struct at76_req_ibss));
1394         memset(bss.bssid, 0xff, ETH_ALEN);
1395         memcpy(bss.essid, priv->essid, IW_ESSID_MAX_SIZE);
1396         bss.essid_size = priv->essid_size;
1397         bss.bss_type = ADHOC_MODE;
1398         bss.channel = priv->channel;
1399
1400         ret = at76_set_card_command(priv->udev, CMD_START_IBSS, &bss,
1401                                     sizeof(struct at76_req_ibss));
1402         if (ret < 0) {
1403                 printk(KERN_ERR "%s: start_ibss failed: %d\n",
1404                        priv->netdev->name, ret);
1405                 return ret;
1406         }
1407
1408         ret = at76_wait_completion(priv, CMD_START_IBSS);
1409         if (ret != CMD_STATUS_COMPLETE) {
1410                 printk(KERN_ERR "%s: start_ibss failed to complete, %d\n",
1411                        priv->netdev->name, ret);
1412                 return ret;
1413         }
1414
1415         ret = at76_get_current_bssid(priv);
1416         if (ret < 0)
1417                 return ret;
1418
1419         ret = at76_get_current_channel(priv);
1420         if (ret < 0)
1421                 return ret;
1422
1423         /* not sure what this is good for ??? */
1424         priv->mib_buf.type = MIB_MAC_MGMT;
1425         priv->mib_buf.size = 1;
1426         priv->mib_buf.index = offsetof(struct mib_mac_mgmt, ibss_change);
1427         priv->mib_buf.data.byte = 0;
1428
1429         ret = at76_set_mib(priv, &priv->mib_buf);
1430         if (ret < 0) {
1431                 printk(KERN_ERR "%s: set_mib (ibss change ok) failed: %d\n",
1432                        priv->netdev->name, ret);
1433                 return ret;
1434         }
1435
1436         netif_carrier_on(priv->netdev);
1437         netif_start_queue(priv->netdev);
1438         return 0;
1439 }
1440
1441 /* Request card to join BSS in managed or ad-hoc mode */
1442 static int at76_join_bss(struct at76_priv *priv, struct bss_info *ptr)
1443 {
1444         struct at76_req_join join;
1445
1446         BUG_ON(!ptr);
1447
1448         memset(&join, 0, sizeof(struct at76_req_join));
1449         memcpy(join.bssid, ptr->bssid, ETH_ALEN);
1450         memcpy(join.essid, ptr->ssid, ptr->ssid_len);
1451         join.essid_size = ptr->ssid_len;
1452         join.bss_type = (priv->iw_mode == IW_MODE_ADHOC ? 1 : 2);
1453         join.channel = ptr->channel;
1454         join.timeout = cpu_to_le16(2000);
1455
1456         at76_dbg(DBG_PROGRESS,
1457                  "%s join addr %s ssid %s type %d ch %d timeout %d",
1458                  priv->netdev->name, mac2str(join.bssid), join.essid,
1459                  join.bss_type, join.channel, le16_to_cpu(join.timeout));
1460         return at76_set_card_command(priv->udev, CMD_JOIN, &join,
1461                                      sizeof(struct at76_req_join));
1462 }
1463
1464 /* Calculate padding from txbuf->wlength (which excludes the USB TX header),
1465    likely to compensate a flaw in the AT76C503A USB part ... */
1466 static inline int at76_calc_padding(int wlen)
1467 {
1468         /* add the USB TX header */
1469         wlen += AT76_TX_HDRLEN;
1470
1471         wlen = wlen % 64;
1472
1473         if (wlen < 50)
1474                 return 50 - wlen;
1475
1476         if (wlen >= 61)
1477                 return 64 + 50 - wlen;
1478
1479         return 0;
1480 }
1481
1482 /* We are doing a lot of things here in an interrupt. Need
1483    a bh handler (Watching TV with a TV card is probably
1484    a good test: if you see flickers, we are doing too much.
1485    Currently I do see flickers... even with our tasklet :-( )
1486    Maybe because the bttv driver and usb-uhci use the same interrupt
1487 */
1488 /* Or maybe because our BH handler is preempting bttv's BH handler.. BHs don't
1489  * solve everything.. (alex) */
1490 static void at76_rx_callback(struct urb *urb)
1491 {
1492         struct at76_priv *priv = urb->context;
1493
1494         priv->rx_tasklet.data = (unsigned long)urb;
1495         tasklet_schedule(&priv->rx_tasklet);
1496         return;
1497 }
1498
1499 static void at76_tx_callback(struct urb *urb)
1500 {
1501         struct at76_priv *priv = urb->context;
1502         struct net_device_stats *stats = &priv->stats;
1503         unsigned long flags;
1504         struct at76_tx_buffer *mgmt_buf;
1505         int ret;
1506
1507         switch (urb->status) {
1508         case 0:
1509                 stats->tx_packets++;
1510                 break;
1511         case -ENOENT:
1512         case -ECONNRESET:
1513                 /* urb has been unlinked */
1514                 return;
1515         default:
1516                 at76_dbg(DBG_URB, "%s - nonzero tx status received: %d",
1517                          __func__, urb->status);
1518                 stats->tx_errors++;
1519                 break;
1520         }
1521
1522         spin_lock_irqsave(&priv->mgmt_spinlock, flags);
1523         mgmt_buf = priv->next_mgmt_bulk;
1524         priv->next_mgmt_bulk = NULL;
1525         spin_unlock_irqrestore(&priv->mgmt_spinlock, flags);
1526
1527         if (!mgmt_buf) {
1528                 netif_wake_queue(priv->netdev);
1529                 return;
1530         }
1531
1532         /* we don't copy the padding bytes, but add them
1533            to the length */
1534         memcpy(priv->bulk_out_buffer, mgmt_buf,
1535                le16_to_cpu(mgmt_buf->wlength) + AT76_TX_HDRLEN);
1536         usb_fill_bulk_urb(priv->tx_urb, priv->udev, priv->tx_pipe,
1537                           priv->bulk_out_buffer,
1538                           le16_to_cpu(mgmt_buf->wlength) + mgmt_buf->padding +
1539                           AT76_TX_HDRLEN, at76_tx_callback, priv);
1540         ret = usb_submit_urb(priv->tx_urb, GFP_ATOMIC);
1541         if (ret)
1542                 printk(KERN_ERR "%s: error in tx submit urb: %d\n",
1543                        priv->netdev->name, ret);
1544
1545         kfree(mgmt_buf);
1546 }
1547
1548 /* Send a management frame on bulk-out.  txbuf->wlength must be set */
1549 static int at76_tx_mgmt(struct at76_priv *priv, struct at76_tx_buffer *txbuf)
1550 {
1551         unsigned long flags;
1552         int ret;
1553         int urb_status;
1554         void *oldbuf = NULL;
1555
1556         netif_carrier_off(priv->netdev);        /* stop netdev watchdog */
1557         netif_stop_queue(priv->netdev); /* stop tx data packets */
1558
1559         spin_lock_irqsave(&priv->mgmt_spinlock, flags);
1560
1561         urb_status = priv->tx_urb->status;
1562         if (urb_status == -EINPROGRESS) {
1563                 /* cannot transmit now, put in the queue */
1564                 oldbuf = priv->next_mgmt_bulk;
1565                 priv->next_mgmt_bulk = txbuf;
1566         }
1567         spin_unlock_irqrestore(&priv->mgmt_spinlock, flags);
1568
1569         if (oldbuf) {
1570                 /* a data/mgmt tx is already pending in the URB -
1571                    if this is no error in some situations we must
1572                    implement a queue or silently modify the old msg */
1573                 printk(KERN_ERR "%s: removed pending mgmt buffer %s\n",
1574                        priv->netdev->name, hex2str(oldbuf, 64));
1575                 kfree(oldbuf);
1576                 return 0;
1577         }
1578
1579         txbuf->tx_rate = TX_RATE_1MBIT;
1580         txbuf->padding = at76_calc_padding(le16_to_cpu(txbuf->wlength));
1581         memset(txbuf->reserved, 0, sizeof(txbuf->reserved));
1582
1583         if (priv->next_mgmt_bulk)
1584                 printk(KERN_ERR "%s: URB status %d, but mgmt is pending\n",
1585                        priv->netdev->name, urb_status);
1586
1587         at76_dbg(DBG_TX_MGMT,
1588                  "%s: tx mgmt: wlen %d tx_rate %d pad %d %s",
1589                  priv->netdev->name, le16_to_cpu(txbuf->wlength),
1590                  txbuf->tx_rate, txbuf->padding,
1591                  hex2str(txbuf->packet, le16_to_cpu(txbuf->wlength)));
1592
1593         /* txbuf was not consumed above -> send mgmt msg immediately */
1594         memcpy(priv->bulk_out_buffer, txbuf,
1595                le16_to_cpu(txbuf->wlength) + AT76_TX_HDRLEN);
1596         usb_fill_bulk_urb(priv->tx_urb, priv->udev, priv->tx_pipe,
1597                           priv->bulk_out_buffer,
1598                           le16_to_cpu(txbuf->wlength) + txbuf->padding +
1599                           AT76_TX_HDRLEN, at76_tx_callback, priv);
1600         ret = usb_submit_urb(priv->tx_urb, GFP_ATOMIC);
1601         if (ret)
1602                 printk(KERN_ERR "%s: error in tx submit urb: %d\n",
1603                        priv->netdev->name, ret);
1604
1605         kfree(txbuf);
1606
1607         return ret;
1608 }
1609
1610 /* Go to the next information element */
1611 static inline void next_ie(struct ieee80211_info_element **ie)
1612 {
1613         *ie = (struct ieee80211_info_element *)(&(*ie)->data[(*ie)->len]);
1614 }
1615
1616 /* Challenge is the challenge string (in TLV format)
1617    we got with seq_nr 2 for shared secret authentication only and
1618    send in seq_nr 3 WEP encrypted to prove we have the correct WEP key;
1619    otherwise it is NULL */
1620 static int at76_auth_req(struct at76_priv *priv, struct bss_info *bss,
1621                          int seq_nr, struct ieee80211_info_element *challenge)
1622 {
1623         struct at76_tx_buffer *tx_buffer;
1624         struct ieee80211_hdr_3addr *mgmt;
1625         struct ieee80211_auth *req;
1626         int buf_len = (seq_nr != 3 ? AUTH_FRAME_SIZE :
1627                        AUTH_FRAME_SIZE + 1 + 1 + challenge->len);
1628
1629         BUG_ON(!bss);
1630         BUG_ON(seq_nr == 3 && !challenge);
1631         tx_buffer = kmalloc(buf_len + MAX_PADDING_SIZE, GFP_ATOMIC);
1632         if (!tx_buffer)
1633                 return -ENOMEM;
1634
1635         req = (struct ieee80211_auth *)tx_buffer->packet;
1636         mgmt = &req->header;
1637
1638         /* make wireless header */
1639         /* first auth msg is not encrypted, only the second (seq_nr == 3) */
1640         mgmt->frame_ctl =
1641             cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_AUTH |
1642                         (seq_nr == 3 ? IEEE80211_FCTL_PROTECTED : 0));
1643
1644         mgmt->duration_id = cpu_to_le16(0x8000);
1645         memcpy(mgmt->addr1, bss->bssid, ETH_ALEN);
1646         memcpy(mgmt->addr2, priv->netdev->dev_addr, ETH_ALEN);
1647         memcpy(mgmt->addr3, bss->bssid, ETH_ALEN);
1648         mgmt->seq_ctl = cpu_to_le16(0);
1649
1650         req->algorithm = cpu_to_le16(priv->auth_mode);
1651         req->transaction = cpu_to_le16(seq_nr);
1652         req->status = cpu_to_le16(0);
1653
1654         if (seq_nr == 3)
1655                 memcpy(req->info_element, challenge, 1 + 1 + challenge->len);
1656
1657         /* init. at76_priv tx header */
1658         tx_buffer->wlength = cpu_to_le16(buf_len - AT76_TX_HDRLEN);
1659         at76_dbg(DBG_TX_MGMT, "%s: AuthReq bssid %s alg %d seq_nr %d",
1660                  priv->netdev->name, mac2str(mgmt->addr3),
1661                  le16_to_cpu(req->algorithm), le16_to_cpu(req->transaction));
1662         if (seq_nr == 3)
1663                 at76_dbg(DBG_TX_MGMT, "%s: AuthReq challenge: %s ...",
1664                          priv->netdev->name, hex2str(req->info_element, 18));
1665
1666         /* either send immediately (if no data tx is pending
1667            or put it in pending list */
1668         return at76_tx_mgmt(priv, tx_buffer);
1669 }
1670
1671 static int at76_assoc_req(struct at76_priv *priv, struct bss_info *bss)
1672 {
1673         struct at76_tx_buffer *tx_buffer;
1674         struct ieee80211_hdr_3addr *mgmt;
1675         struct ieee80211_assoc_request *req;
1676         struct ieee80211_info_element *ie;
1677         char *essid;
1678         int essid_len;
1679         u16 capa;
1680
1681         BUG_ON(!bss);
1682
1683         tx_buffer = kmalloc(ASSOCREQ_MAX_SIZE + MAX_PADDING_SIZE, GFP_ATOMIC);
1684         if (!tx_buffer)
1685                 return -ENOMEM;
1686
1687         req = (struct ieee80211_assoc_request *)tx_buffer->packet;
1688         mgmt = &req->header;
1689         ie = req->info_element;
1690
1691         /* make wireless header */
1692         mgmt->frame_ctl = cpu_to_le16(IEEE80211_FTYPE_MGMT |
1693                                       IEEE80211_STYPE_ASSOC_REQ);
1694
1695         mgmt->duration_id = cpu_to_le16(0x8000);
1696         memcpy(mgmt->addr1, bss->bssid, ETH_ALEN);
1697         memcpy(mgmt->addr2, priv->netdev->dev_addr, ETH_ALEN);
1698         memcpy(mgmt->addr3, bss->bssid, ETH_ALEN);
1699         mgmt->seq_ctl = cpu_to_le16(0);
1700
1701         /* we must set the Privacy bit in the capabilities to assure an
1702            Agere-based AP with optional WEP transmits encrypted frames
1703            to us.  AP only set the Privacy bit in their capabilities
1704            if WEP is mandatory in the BSS! */
1705         capa = bss->capa;
1706         if (priv->wep_enabled)
1707                 capa |= WLAN_CAPABILITY_PRIVACY;
1708         if (priv->preamble_type != PREAMBLE_TYPE_LONG)
1709                 capa |= WLAN_CAPABILITY_SHORT_PREAMBLE;
1710         req->capability = cpu_to_le16(capa);
1711
1712         req->listen_interval = cpu_to_le16(2 * bss->beacon_interval);
1713
1714         /* write TLV data elements */
1715
1716         ie->id = MFIE_TYPE_SSID;
1717         ie->len = bss->ssid_len;
1718         memcpy(ie->data, bss->ssid, bss->ssid_len);
1719         next_ie(&ie);
1720
1721         ie->id = MFIE_TYPE_RATES;
1722         ie->len = sizeof(hw_rates);
1723         memcpy(ie->data, hw_rates, sizeof(hw_rates));
1724         next_ie(&ie);           /* ie points behind the supp_rates field */
1725
1726         /* init. at76_priv tx header */
1727         tx_buffer->wlength = cpu_to_le16((u8 *)ie - (u8 *)mgmt);
1728
1729         ie = req->info_element;
1730         essid = ie->data;
1731         essid_len = min_t(int, IW_ESSID_MAX_SIZE, ie->len);
1732
1733         next_ie(&ie);           /* points to IE of rates now */
1734         at76_dbg(DBG_TX_MGMT,
1735                  "%s: AssocReq bssid %s capa 0x%04x ssid %.*s rates %s",
1736                  priv->netdev->name, mac2str(mgmt->addr3),
1737                  le16_to_cpu(req->capability), essid_len, essid,
1738                  hex2str(ie->data, ie->len));
1739
1740         /* either send immediately (if no data tx is pending
1741            or put it in pending list */
1742         return at76_tx_mgmt(priv, tx_buffer);
1743 }
1744
1745 /* We got to check the bss_list for old entries */
1746 static void at76_bss_list_timeout(unsigned long par)
1747 {
1748         struct at76_priv *priv = (struct at76_priv *)par;
1749         unsigned long flags;
1750         struct list_head *lptr, *nptr;
1751         struct bss_info *ptr;
1752
1753         spin_lock_irqsave(&priv->bss_list_spinlock, flags);
1754
1755         list_for_each_safe(lptr, nptr, &priv->bss_list) {
1756
1757                 ptr = list_entry(lptr, struct bss_info, list);
1758
1759                 if (ptr != priv->curr_bss
1760                     && time_after(jiffies, ptr->last_rx + BSS_LIST_TIMEOUT)) {
1761                         at76_dbg(DBG_BSS_TABLE_RM,
1762                                  "%s: bss_list: removing old BSS %s ch %d",
1763                                  priv->netdev->name, mac2str(ptr->bssid),
1764                                  ptr->channel);
1765                         list_del(&ptr->list);
1766                         kfree(ptr);
1767                 }
1768         }
1769         spin_unlock_irqrestore(&priv->bss_list_spinlock, flags);
1770         /* restart the timer */
1771         mod_timer(&priv->bss_list_timer, jiffies + BSS_LIST_TIMEOUT);
1772 }
1773
1774 static inline void at76_set_mac_state(struct at76_priv *priv,
1775                                       enum mac_state mac_state)
1776 {
1777         at76_dbg(DBG_MAC_STATE, "%s state: %s", priv->netdev->name,
1778                  mac_states[mac_state]);
1779         priv->mac_state = mac_state;
1780 }
1781
1782 static void at76_dump_bss_table(struct at76_priv *priv)
1783 {
1784         struct bss_info *ptr;
1785         unsigned long flags;
1786         struct list_head *lptr;
1787
1788         spin_lock_irqsave(&priv->bss_list_spinlock, flags);
1789
1790         at76_dbg(DBG_BSS_TABLE, "%s BSS table (curr=%p):", priv->netdev->name,
1791                  priv->curr_bss);
1792
1793         list_for_each(lptr, &priv->bss_list) {
1794                 ptr = list_entry(lptr, struct bss_info, list);
1795                 at76_dbg(DBG_BSS_TABLE, "0x%p: bssid %s channel %d ssid %.*s "
1796                          "(%s) capa 0x%04x rates %s rssi %d link %d noise %d",
1797                          ptr, mac2str(ptr->bssid), ptr->channel, ptr->ssid_len,
1798                          ptr->ssid, hex2str(ptr->ssid, ptr->ssid_len),
1799                          ptr->capa, hex2str(ptr->rates, ptr->rates_len),
1800                          ptr->rssi, ptr->link_qual, ptr->noise_level);
1801         }
1802         spin_unlock_irqrestore(&priv->bss_list_spinlock, flags);
1803 }
1804
1805 /* Called upon successful association to mark interface as connected */
1806 static void at76_work_assoc_done(struct work_struct *work)
1807 {
1808         struct at76_priv *priv = container_of(work, struct at76_priv,
1809                                               work_assoc_done);
1810
1811         mutex_lock(&priv->mtx);
1812
1813         WARN_ON(priv->mac_state != MAC_ASSOC);
1814         WARN_ON(!priv->curr_bss);
1815         if (priv->mac_state != MAC_ASSOC || !priv->curr_bss)
1816                 goto exit;
1817
1818         if (priv->iw_mode == IW_MODE_INFRA) {
1819                 if (priv->pm_mode != AT76_PM_OFF) {
1820                         /* calculate the listen interval in units of
1821                            beacon intervals of the curr_bss */
1822                         u32 pm_period_beacon = (priv->pm_period >> 10) /
1823                             priv->curr_bss->beacon_interval;
1824
1825                         pm_period_beacon = max(pm_period_beacon, 2u);
1826                         pm_period_beacon = min(pm_period_beacon, 0xffffu);
1827
1828                         at76_dbg(DBG_PM,
1829                                  "%s: pm_mode %d assoc id 0x%x listen int %d",
1830                                  priv->netdev->name, priv->pm_mode,
1831                                  priv->assoc_id, pm_period_beacon);
1832
1833                         at76_set_associd(priv, priv->assoc_id);
1834                         at76_set_listen_interval(priv, (u16)pm_period_beacon);
1835                 }
1836                 schedule_delayed_work(&priv->dwork_beacon, BEACON_TIMEOUT);
1837         }
1838         at76_set_pm_mode(priv);
1839
1840         netif_carrier_on(priv->netdev);
1841         netif_wake_queue(priv->netdev);
1842         at76_set_mac_state(priv, MAC_CONNECTED);
1843         at76_iwevent_bss_connect(priv->netdev, priv->curr_bss->bssid);
1844         at76_dbg(DBG_PROGRESS, "%s: connected to BSSID %s",
1845                  priv->netdev->name, mac2str(priv->curr_bss->bssid));
1846
1847 exit:
1848         mutex_unlock(&priv->mtx);
1849 }
1850
1851 /* We only store the new mac address in netdev struct,
1852    it gets set when the netdev is opened. */
1853 static int at76_set_mac_address(struct net_device *netdev, void *addr)
1854 {
1855         struct sockaddr *mac = addr;
1856         memcpy(netdev->dev_addr, mac->sa_data, ETH_ALEN);
1857         return 1;
1858 }
1859
1860 static struct net_device_stats *at76_get_stats(struct net_device *netdev)
1861 {
1862         struct at76_priv *priv = netdev_priv(netdev);
1863         return &priv->stats;
1864 }
1865
1866 static struct iw_statistics *at76_get_wireless_stats(struct net_device *netdev)
1867 {
1868         struct at76_priv *priv = netdev_priv(netdev);
1869
1870         at76_dbg(DBG_IOCTL, "RETURN qual %d level %d noise %d updated %d",
1871                  priv->wstats.qual.qual, priv->wstats.qual.level,
1872                  priv->wstats.qual.noise, priv->wstats.qual.updated);
1873
1874         return &priv->wstats;
1875 }
1876
1877 static void at76_set_multicast(struct net_device *netdev)
1878 {
1879         struct at76_priv *priv = netdev_priv(netdev);
1880         int promisc;
1881
1882         promisc = ((netdev->flags & IFF_PROMISC) != 0);
1883         if (promisc != priv->promisc) {
1884                 /* This gets called in interrupt, must reschedule */
1885                 priv->promisc = promisc;
1886                 schedule_work(&priv->work_set_promisc);
1887         }
1888 }
1889
1890 /* Stop all network activity, flush all pending tasks */
1891 static void at76_quiesce(struct at76_priv *priv)
1892 {
1893         unsigned long flags;
1894
1895         netif_stop_queue(priv->netdev);
1896         netif_carrier_off(priv->netdev);
1897
1898         at76_set_mac_state(priv, MAC_INIT);
1899
1900         cancel_delayed_work(&priv->dwork_get_scan);
1901         cancel_delayed_work(&priv->dwork_beacon);
1902         cancel_delayed_work(&priv->dwork_auth);
1903         cancel_delayed_work(&priv->dwork_assoc);
1904         cancel_delayed_work(&priv->dwork_restart);
1905
1906         spin_lock_irqsave(&priv->mgmt_spinlock, flags);
1907         kfree(priv->next_mgmt_bulk);
1908         priv->next_mgmt_bulk = NULL;
1909         spin_unlock_irqrestore(&priv->mgmt_spinlock, flags);
1910 }
1911
1912 /*******************************************************************************
1913  * at76_priv implementations of iw_handler functions:
1914  */
1915 static int at76_iw_handler_commit(struct net_device *netdev,
1916                                   struct iw_request_info *info,
1917                                   void *null, char *extra)
1918 {
1919         struct at76_priv *priv = netdev_priv(netdev);
1920
1921         at76_dbg(DBG_IOCTL, "%s %s: restarting the device", netdev->name,
1922                  __func__);
1923
1924         if (priv->mac_state != MAC_INIT)
1925                 at76_quiesce(priv);
1926
1927         /* Wait half second before the restart to process subsequent
1928          * requests from the same iwconfig in a single restart */
1929         schedule_delayed_work(&priv->dwork_restart, HZ / 2);
1930
1931         return 0;
1932 }
1933
1934 static int at76_iw_handler_get_name(struct net_device *netdev,
1935                                     struct iw_request_info *info,
1936                                     char *name, char *extra)
1937 {
1938         strcpy(name, "IEEE 802.11b");
1939         at76_dbg(DBG_IOCTL, "%s: SIOCGIWNAME - name %s", netdev->name, name);
1940         return 0;
1941 }
1942
1943 static int at76_iw_handler_set_freq(struct net_device *netdev,
1944                                     struct iw_request_info *info,
1945                                     struct iw_freq *freq, char *extra)
1946 {
1947         struct at76_priv *priv = netdev_priv(netdev);
1948         int chan = -1;
1949         int ret = -EIWCOMMIT;
1950         at76_dbg(DBG_IOCTL, "%s: SIOCSIWFREQ - freq.m %d freq.e %d",
1951                  netdev->name, freq->m, freq->e);
1952
1953         if ((freq->e == 0) && (freq->m <= 1000))
1954                 /* Setting by channel number */
1955                 chan = freq->m;
1956         else {
1957                 /* Setting by frequency - search the table */
1958                 int mult = 1;
1959                 int i;
1960
1961                 for (i = 0; i < (6 - freq->e); i++)
1962                         mult *= 10;
1963
1964                 for (i = 0; i < NUM_CHANNELS; i++) {
1965                         if (freq->m == (channel_frequency[i] * mult))
1966                                 chan = i + 1;
1967                 }
1968         }
1969
1970         if (chan < 1 || !priv->domain)
1971                 /* non-positive channels are invalid
1972                  * we need a domain info to set the channel
1973                  * either that or an invalid frequency was
1974                  * provided by the user */
1975                 ret = -EINVAL;
1976         else if (!(priv->domain->channel_map & (1 << (chan - 1)))) {
1977                 printk(KERN_INFO "%s: channel %d not allowed for domain %s\n",
1978                        priv->netdev->name, chan, priv->domain->name);
1979                 ret = -EINVAL;
1980         }
1981
1982         if (ret == -EIWCOMMIT) {
1983                 priv->channel = chan;
1984                 at76_dbg(DBG_IOCTL, "%s: SIOCSIWFREQ - ch %d", netdev->name,
1985                          chan);
1986         }
1987
1988         return ret;
1989 }
1990
1991 static int at76_iw_handler_get_freq(struct net_device *netdev,
1992                                     struct iw_request_info *info,
1993                                     struct iw_freq *freq, char *extra)
1994 {
1995         struct at76_priv *priv = netdev_priv(netdev);
1996
1997         freq->m = priv->channel;
1998         freq->e = 0;
1999
2000         if (priv->channel)
2001                 at76_dbg(DBG_IOCTL, "%s: SIOCGIWFREQ - freq %ld x 10e%d",
2002                          netdev->name, channel_frequency[priv->channel - 1], 6);
2003
2004         at76_dbg(DBG_IOCTL, "%s: SIOCGIWFREQ - ch %d", netdev->name,
2005                  priv->channel);
2006
2007         return 0;
2008 }
2009
2010 static int at76_iw_handler_set_mode(struct net_device *netdev,
2011                                     struct iw_request_info *info,
2012                                     __u32 *mode, char *extra)
2013 {
2014         struct at76_priv *priv = netdev_priv(netdev);
2015
2016         at76_dbg(DBG_IOCTL, "%s: SIOCSIWMODE - %d", netdev->name, *mode);
2017
2018         if ((*mode != IW_MODE_ADHOC) && (*mode != IW_MODE_INFRA) &&
2019             (*mode != IW_MODE_MONITOR))
2020                 return -EINVAL;
2021
2022         priv->iw_mode = *mode;
2023         if (priv->iw_mode != IW_MODE_INFRA)
2024                 priv->pm_mode = AT76_PM_OFF;
2025
2026         return -EIWCOMMIT;
2027 }
2028
2029 static int at76_iw_handler_get_mode(struct net_device *netdev,
2030                                     struct iw_request_info *info,
2031                                     __u32 *mode, char *extra)
2032 {
2033         struct at76_priv *priv = netdev_priv(netdev);
2034
2035         *mode = priv->iw_mode;
2036
2037         at76_dbg(DBG_IOCTL, "%s: SIOCGIWMODE - %d", netdev->name, *mode);
2038
2039         return 0;
2040 }
2041
2042 static int at76_iw_handler_get_range(struct net_device *netdev,
2043                                      struct iw_request_info *info,
2044                                      struct iw_point *data, char *extra)
2045 {
2046         /* inspired by atmel.c */
2047         struct at76_priv *priv = netdev_priv(netdev);
2048         struct iw_range *range = (struct iw_range *)extra;
2049         int i;
2050
2051         data->length = sizeof(struct iw_range);
2052         memset(range, 0, sizeof(struct iw_range));
2053
2054         /* TODO: range->throughput = xxxxxx; */
2055
2056         range->min_nwid = 0x0000;
2057         range->max_nwid = 0x0000;
2058
2059         /* this driver doesn't maintain sensitivity information */
2060         range->sensitivity = 0;
2061
2062         range->max_qual.qual = 100;
2063         range->max_qual.level = 100;
2064         range->max_qual.noise = 0;
2065         range->max_qual.updated = IW_QUAL_NOISE_INVALID;
2066
2067         range->avg_qual.qual = 50;
2068         range->avg_qual.level = 50;
2069         range->avg_qual.noise = 0;
2070         range->avg_qual.updated = IW_QUAL_NOISE_INVALID;
2071
2072         range->bitrate[0] = 1000000;
2073         range->bitrate[1] = 2000000;
2074         range->bitrate[2] = 5500000;
2075         range->bitrate[3] = 11000000;
2076         range->num_bitrates = 4;
2077
2078         range->min_rts = 0;
2079         range->max_rts = MAX_RTS_THRESHOLD;
2080
2081         range->min_frag = MIN_FRAG_THRESHOLD;
2082         range->max_frag = MAX_FRAG_THRESHOLD;
2083
2084         range->pmp_flags = IW_POWER_PERIOD;
2085         range->pmt_flags = IW_POWER_ON;
2086         range->pm_capa = IW_POWER_PERIOD | IW_POWER_ALL_R;
2087
2088         range->encoding_size[0] = WEP_SMALL_KEY_LEN;
2089         range->encoding_size[1] = WEP_LARGE_KEY_LEN;
2090         range->num_encoding_sizes = 2;
2091         range->max_encoding_tokens = WEP_KEYS;
2092
2093         /* both WL-240U and Linksys WUSB11 v2.6 specify 15 dBm as output power
2094            - take this for all (ignore antenna gains) */
2095         range->txpower[0] = 15;
2096         range->num_txpower = 1;
2097         range->txpower_capa = IW_TXPOW_DBM;
2098
2099         range->we_version_source = WIRELESS_EXT;
2100         range->we_version_compiled = WIRELESS_EXT;
2101
2102         /* same as the values used in atmel.c */
2103         range->retry_capa = IW_RETRY_LIMIT;
2104         range->retry_flags = IW_RETRY_LIMIT;
2105         range->r_time_flags = 0;
2106         range->min_retry = 1;
2107         range->max_retry = 255;
2108
2109         range->num_channels = NUM_CHANNELS;
2110         range->num_frequency = 0;
2111
2112         for (i = 0; i < NUM_CHANNELS; i++) {
2113                 /* test if channel map bit is raised */
2114                 if (priv->domain->channel_map & (0x1 << i)) {
2115                         range->num_frequency += 1;
2116
2117                         range->freq[i].i = i + 1;
2118                         range->freq[i].m = channel_frequency[i] * 100000;
2119                         range->freq[i].e = 1;   /* freq * 10^1 */
2120                 }
2121         }
2122
2123         at76_dbg(DBG_IOCTL, "%s: SIOCGIWRANGE", netdev->name);
2124
2125         return 0;
2126 }
2127
2128 static int at76_iw_handler_set_spy(struct net_device *netdev,
2129                                    struct iw_request_info *info,
2130                                    struct iw_point *data, char *extra)
2131 {
2132         struct at76_priv *priv = netdev_priv(netdev);
2133         int ret = 0;
2134
2135         at76_dbg(DBG_IOCTL, "%s: SIOCSIWSPY - number of addresses %d",
2136                  netdev->name, data->length);
2137
2138         spin_lock_bh(&priv->spy_spinlock);
2139         ret = iw_handler_set_spy(priv->netdev, info, (union iwreq_data *)data,
2140                                  extra);
2141         spin_unlock_bh(&priv->spy_spinlock);
2142
2143         return ret;
2144 }
2145
2146 static int at76_iw_handler_get_spy(struct net_device *netdev,
2147                                    struct iw_request_info *info,
2148                                    struct iw_point *data, char *extra)
2149 {
2150
2151         struct at76_priv *priv = netdev_priv(netdev);
2152         int ret = 0;
2153
2154         spin_lock_bh(&priv->spy_spinlock);
2155         ret = iw_handler_get_spy(priv->netdev, info,
2156                                  (union iwreq_data *)data, extra);
2157         spin_unlock_bh(&priv->spy_spinlock);
2158
2159         at76_dbg(DBG_IOCTL, "%s: SIOCGIWSPY - number of addresses %d",
2160                  netdev->name, data->length);
2161
2162         return ret;
2163 }
2164
2165 static int at76_iw_handler_set_thrspy(struct net_device *netdev,
2166                                       struct iw_request_info *info,
2167                                       struct iw_point *data, char *extra)
2168 {
2169         struct at76_priv *priv = netdev_priv(netdev);
2170         int ret;
2171
2172         at76_dbg(DBG_IOCTL, "%s: SIOCSIWTHRSPY - number of addresses %d)",
2173                  netdev->name, data->length);
2174
2175         spin_lock_bh(&priv->spy_spinlock);
2176         ret = iw_handler_set_thrspy(netdev, info, (union iwreq_data *)data,
2177                                     extra);
2178         spin_unlock_bh(&priv->spy_spinlock);
2179
2180         return ret;
2181 }
2182
2183 static int at76_iw_handler_get_thrspy(struct net_device *netdev,
2184                                       struct iw_request_info *info,
2185                                       struct iw_point *data, char *extra)
2186 {
2187         struct at76_priv *priv = netdev_priv(netdev);
2188         int ret;
2189
2190         spin_lock_bh(&priv->spy_spinlock);
2191         ret = iw_handler_get_thrspy(netdev, info, (union iwreq_data *)data,
2192                                     extra);
2193         spin_unlock_bh(&priv->spy_spinlock);
2194
2195         at76_dbg(DBG_IOCTL, "%s: SIOCGIWTHRSPY - number of addresses %d)",
2196                  netdev->name, data->length);
2197
2198         return ret;
2199 }
2200
2201 static int at76_iw_handler_set_wap(struct net_device *netdev,
2202                                    struct iw_request_info *info,
2203                                    struct sockaddr *ap_addr, char *extra)
2204 {
2205         struct at76_priv *priv = netdev_priv(netdev);
2206
2207         at76_dbg(DBG_IOCTL, "%s: SIOCSIWAP - wap/bssid %s", netdev->name,
2208                  mac2str(ap_addr->sa_data));
2209
2210         /* if the incoming address == ff:ff:ff:ff:ff:ff, the user has
2211            chosen any or auto AP preference */
2212         if (is_broadcast_ether_addr(ap_addr->sa_data)
2213             || is_zero_ether_addr(ap_addr->sa_data))
2214                 priv->wanted_bssid_valid = 0;
2215         else {
2216                 /* user wants to set a preferred AP address */
2217                 priv->wanted_bssid_valid = 1;
2218                 memcpy(priv->wanted_bssid, ap_addr->sa_data, ETH_ALEN);
2219         }
2220
2221         return -EIWCOMMIT;
2222 }
2223
2224 static int at76_iw_handler_get_wap(struct net_device *netdev,
2225                                    struct iw_request_info *info,
2226                                    struct sockaddr *ap_addr, char *extra)
2227 {
2228         struct at76_priv *priv = netdev_priv(netdev);
2229
2230         ap_addr->sa_family = ARPHRD_ETHER;
2231         memcpy(ap_addr->sa_data, priv->bssid, ETH_ALEN);
2232
2233         at76_dbg(DBG_IOCTL, "%s: SIOCGIWAP - wap/bssid %s", netdev->name,
2234                  mac2str(ap_addr->sa_data));
2235
2236         return 0;
2237 }
2238
2239 static int at76_iw_handler_set_scan(struct net_device *netdev,
2240                                     struct iw_request_info *info,
2241                                     union iwreq_data *wrqu, char *extra)
2242 {
2243         struct at76_priv *priv = netdev_priv(netdev);
2244         int ret = 0;
2245
2246         at76_dbg(DBG_IOCTL, "%s: SIOCSIWSCAN", netdev->name);
2247
2248         if (mutex_lock_interruptible(&priv->mtx))
2249                 return -EINTR;
2250
2251         if (!netif_running(netdev)) {
2252                 ret = -ENETDOWN;
2253                 goto exit;
2254         }
2255
2256         /* jal: we don't allow "iwlist ethX scan" while we are
2257            in monitor mode */
2258         if (priv->iw_mode == IW_MODE_MONITOR) {
2259                 ret = -EBUSY;
2260                 goto exit;
2261         }
2262
2263         /* Discard old scan results */
2264         if ((jiffies - priv->last_scan) > (20 * HZ))
2265                 priv->scan_state = SCAN_IDLE;
2266         priv->last_scan = jiffies;
2267
2268         /* Initiate a scan command */
2269         if (priv->scan_state == SCAN_IN_PROGRESS) {
2270                 ret = -EBUSY;
2271                 goto exit;
2272         }
2273
2274         priv->scan_state = SCAN_IN_PROGRESS;
2275
2276         at76_quiesce(priv);
2277
2278         /* Try to do passive or active scan if WE asks as. */
2279         if (wrqu->data.length
2280             && wrqu->data.length == sizeof(struct iw_scan_req)) {
2281                 struct iw_scan_req *req = (struct iw_scan_req *)extra;
2282
2283                 if (req->scan_type == IW_SCAN_TYPE_PASSIVE)
2284                         priv->scan_mode = SCAN_TYPE_PASSIVE;
2285                 else if (req->scan_type == IW_SCAN_TYPE_ACTIVE)
2286                         priv->scan_mode = SCAN_TYPE_ACTIVE;
2287
2288                 /* Sanity check values? */
2289                 if (req->min_channel_time > 0)
2290                         priv->scan_min_time = req->min_channel_time;
2291
2292                 if (req->max_channel_time > 0)
2293                         priv->scan_max_time = req->max_channel_time;
2294         }
2295
2296         /* change to scanning state */
2297         at76_set_mac_state(priv, MAC_SCANNING);
2298         schedule_work(&priv->work_start_scan);
2299
2300 exit:
2301         mutex_unlock(&priv->mtx);
2302         return ret;
2303 }
2304
2305 static int at76_iw_handler_get_scan(struct net_device *netdev,
2306                                     struct iw_request_info *info,
2307                                     struct iw_point *data, char *extra)
2308 {
2309         struct at76_priv *priv = netdev_priv(netdev);
2310         unsigned long flags;
2311         struct list_head *lptr, *nptr;
2312         struct bss_info *curr_bss;
2313         struct iw_event *iwe = kmalloc(sizeof(struct iw_event), GFP_KERNEL);
2314         char *curr_val, *curr_pos = extra;
2315         int i;
2316
2317         at76_dbg(DBG_IOCTL, "%s: SIOCGIWSCAN", netdev->name);
2318
2319         if (!iwe)
2320                 return -ENOMEM;
2321
2322         if (priv->scan_state != SCAN_COMPLETED) {
2323                 /* scan not yet finished */
2324                 kfree(iwe);
2325                 return -EAGAIN;
2326         }
2327
2328         spin_lock_irqsave(&priv->bss_list_spinlock, flags);
2329
2330         list_for_each_safe(lptr, nptr, &priv->bss_list) {
2331                 curr_bss = list_entry(lptr, struct bss_info, list);
2332
2333                 iwe->cmd = SIOCGIWAP;
2334                 iwe->u.ap_addr.sa_family = ARPHRD_ETHER;
2335                 memcpy(iwe->u.ap_addr.sa_data, curr_bss->bssid, 6);
2336                 curr_pos = iwe_stream_add_event(info, curr_pos,
2337                                                 extra + IW_SCAN_MAX_DATA, iwe,
2338                                                 IW_EV_ADDR_LEN);
2339
2340                 iwe->u.data.length = curr_bss->ssid_len;
2341                 iwe->cmd = SIOCGIWESSID;
2342                 iwe->u.data.flags = 1;
2343
2344                 curr_pos = iwe_stream_add_point(info, curr_pos,
2345                                                 extra + IW_SCAN_MAX_DATA, iwe,
2346                                                 curr_bss->ssid);
2347
2348                 iwe->cmd = SIOCGIWMODE;
2349                 iwe->u.mode = (curr_bss->capa & WLAN_CAPABILITY_IBSS) ?
2350                     IW_MODE_ADHOC :
2351                     (curr_bss->capa & WLAN_CAPABILITY_ESS) ?
2352                     IW_MODE_MASTER : IW_MODE_AUTO;
2353                 /* IW_MODE_AUTO = 0 which I thought is
2354                  * the most logical value to return in this case */
2355                 curr_pos = iwe_stream_add_event(info, curr_pos,
2356                                                 extra + IW_SCAN_MAX_DATA, iwe,
2357                                                 IW_EV_UINT_LEN);
2358
2359                 iwe->cmd = SIOCGIWFREQ;
2360                 iwe->u.freq.m = curr_bss->channel;
2361                 iwe->u.freq.e = 0;
2362                 curr_pos = iwe_stream_add_event(info, curr_pos,
2363                                                 extra + IW_SCAN_MAX_DATA, iwe,
2364                                                 IW_EV_FREQ_LEN);
2365
2366                 iwe->cmd = SIOCGIWENCODE;
2367                 if (curr_bss->capa & WLAN_CAPABILITY_PRIVACY)
2368                         iwe->u.data.flags = IW_ENCODE_ENABLED | IW_ENCODE_NOKEY;
2369                 else
2370                         iwe->u.data.flags = IW_ENCODE_DISABLED;
2371
2372                 iwe->u.data.length = 0;
2373                 curr_pos = iwe_stream_add_point(info, curr_pos,
2374                                                 extra + IW_SCAN_MAX_DATA, iwe,
2375                                                 NULL);
2376
2377                 /* Add quality statistics */
2378                 iwe->cmd = IWEVQUAL;
2379                 iwe->u.qual.noise = 0;
2380                 iwe->u.qual.updated =
2381                     IW_QUAL_NOISE_INVALID | IW_QUAL_LEVEL_UPDATED;
2382                 iwe->u.qual.level = (curr_bss->rssi * 100 / 42);
2383                 if (iwe->u.qual.level > 100)
2384                         iwe->u.qual.level = 100;
2385                 if (at76_is_intersil(priv->board_type))
2386                         iwe->u.qual.qual = curr_bss->link_qual;
2387                 else {
2388                         iwe->u.qual.qual = 0;
2389                         iwe->u.qual.updated |= IW_QUAL_QUAL_INVALID;
2390                 }
2391                 /* Add new value to event */
2392                 curr_pos = iwe_stream_add_event(info, curr_pos,
2393                                                 extra + IW_SCAN_MAX_DATA, iwe,
2394                                                 IW_EV_QUAL_LEN);
2395
2396                 /* Rate: stuffing multiple values in a single event requires
2397                  * a bit more of magic - Jean II */
2398                 curr_val = curr_pos + IW_EV_LCP_LEN;
2399
2400                 iwe->cmd = SIOCGIWRATE;
2401                 /* Those two flags are ignored... */
2402                 iwe->u.bitrate.fixed = 0;
2403                 iwe->u.bitrate.disabled = 0;
2404                 /* Max 8 values */
2405                 for (i = 0; i < curr_bss->rates_len; i++) {
2406                         /* Bit rate given in 500 kb/s units (+ 0x80) */
2407                         iwe->u.bitrate.value =
2408                             ((curr_bss->rates[i] & 0x7f) * 500000);
2409                         /* Add new value to event */
2410                         curr_val = iwe_stream_add_value(info, curr_pos,
2411                                                         curr_val,
2412                                                         extra +
2413                                                         IW_SCAN_MAX_DATA, iwe,
2414                                                         IW_EV_PARAM_LEN);
2415                 }
2416
2417                 /* Check if we added any event */
2418                 if ((curr_val - curr_pos) > IW_EV_LCP_LEN)
2419                         curr_pos = curr_val;
2420
2421                 /* more information may be sent back using IWECUSTOM */
2422
2423         }
2424
2425         spin_unlock_irqrestore(&priv->bss_list_spinlock, flags);
2426
2427         data->length = (curr_pos - extra);
2428         data->flags = 0;
2429
2430         kfree(iwe);
2431         return 0;
2432 }
2433
2434 static int at76_iw_handler_set_essid(struct net_device *netdev,
2435                                      struct iw_request_info *info,
2436                                      struct iw_point *data, char *extra)
2437 {
2438         struct at76_priv *priv = netdev_priv(netdev);
2439
2440         at76_dbg(DBG_IOCTL, "%s: SIOCSIWESSID - %s", netdev->name, extra);
2441
2442         if (data->flags) {
2443                 memcpy(priv->essid, extra, data->length);
2444                 priv->essid_size = data->length;
2445         } else
2446                 priv->essid_size = 0;   /* Use any SSID */
2447
2448         return -EIWCOMMIT;
2449 }
2450
2451 static int at76_iw_handler_get_essid(struct net_device *netdev,
2452                                      struct iw_request_info *info,
2453                                      struct iw_point *data, char *extra)
2454 {
2455         struct at76_priv *priv = netdev_priv(netdev);
2456
2457         if (priv->essid_size) {
2458                 /* not the ANY ssid in priv->essid */
2459                 data->flags = 1;
2460                 data->length = priv->essid_size;
2461                 memcpy(extra, priv->essid, data->length);
2462         } else {
2463                 /* the ANY ssid was specified */
2464                 if (priv->mac_state == MAC_CONNECTED && priv->curr_bss) {
2465                         /* report the SSID we have found */
2466                         data->flags = 1;
2467                         data->length = priv->curr_bss->ssid_len;
2468                         memcpy(extra, priv->curr_bss->ssid, data->length);
2469                 } else {
2470                         /* report ANY back */
2471                         data->flags = 0;
2472                         data->length = 0;
2473                 }
2474         }
2475
2476         at76_dbg(DBG_IOCTL, "%s: SIOCGIWESSID - %.*s", netdev->name,
2477                  data->length, extra);
2478
2479         return 0;
2480 }
2481
2482 static int at76_iw_handler_set_rate(struct net_device *netdev,
2483                                     struct iw_request_info *info,
2484                                     struct iw_param *bitrate, char *extra)
2485 {
2486         struct at76_priv *priv = netdev_priv(netdev);
2487         int ret = -EIWCOMMIT;
2488
2489         at76_dbg(DBG_IOCTL, "%s: SIOCSIWRATE - %d", netdev->name,
2490                  bitrate->value);
2491
2492         switch (bitrate->value) {
2493         case -1:
2494                 priv->txrate = TX_RATE_AUTO;
2495                 break;          /* auto rate */
2496         case 1000000:
2497                 priv->txrate = TX_RATE_1MBIT;
2498                 break;
2499         case 2000000:
2500                 priv->txrate = TX_RATE_2MBIT;
2501                 break;
2502         case 5500000:
2503                 priv->txrate = TX_RATE_5_5MBIT;
2504                 break;
2505         case 11000000:
2506                 priv->txrate = TX_RATE_11MBIT;
2507                 break;
2508         default:
2509                 ret = -EINVAL;
2510         }
2511
2512         return ret;
2513 }
2514
2515 static int at76_iw_handler_get_rate(struct net_device *netdev,
2516                                     struct iw_request_info *info,
2517                                     struct iw_param *bitrate, char *extra)
2518 {
2519         struct at76_priv *priv = netdev_priv(netdev);
2520         int ret = 0;
2521
2522         switch (priv->txrate) {
2523                 /* return max rate if RATE_AUTO */
2524         case TX_RATE_AUTO:
2525                 bitrate->value = 11000000;
2526                 break;
2527         case TX_RATE_1MBIT:
2528                 bitrate->value = 1000000;
2529                 break;
2530         case TX_RATE_2MBIT:
2531                 bitrate->value = 2000000;
2532                 break;
2533         case TX_RATE_5_5MBIT:
2534                 bitrate->value = 5500000;
2535                 break;
2536         case TX_RATE_11MBIT:
2537                 bitrate->value = 11000000;
2538                 break;
2539         default:
2540                 ret = -EINVAL;
2541         }
2542
2543         bitrate->fixed = (priv->txrate != TX_RATE_AUTO);
2544         bitrate->disabled = 0;
2545
2546         at76_dbg(DBG_IOCTL, "%s: SIOCGIWRATE - %d", netdev->name,
2547                  bitrate->value);
2548
2549         return ret;
2550 }
2551
2552 static int at76_iw_handler_set_rts(struct net_device *netdev,
2553                                    struct iw_request_info *info,
2554                                    struct iw_param *rts, char *extra)
2555 {
2556         struct at76_priv *priv = netdev_priv(netdev);
2557         int ret = -EIWCOMMIT;
2558         int rthr = rts->value;
2559
2560         at76_dbg(DBG_IOCTL, "%s: SIOCSIWRTS - value %d disabled %s",
2561                  netdev->name, rts->value, (rts->disabled) ? "true" : "false");
2562
2563         if (rts->disabled)
2564                 rthr = MAX_RTS_THRESHOLD;
2565
2566         if ((rthr < 0) || (rthr > MAX_RTS_THRESHOLD))
2567                 ret = -EINVAL;
2568         else
2569                 priv->rts_threshold = rthr;
2570
2571         return ret;
2572 }
2573
2574 static int at76_iw_handler_get_rts(struct net_device *netdev,
2575                                    struct iw_request_info *info,
2576                                    struct iw_param *rts, char *extra)
2577 {
2578         struct at76_priv *priv = netdev_priv(netdev);
2579
2580         rts->value = priv->rts_threshold;
2581         rts->disabled = (rts->value >= MAX_RTS_THRESHOLD);
2582         rts->fixed = 1;
2583
2584         at76_dbg(DBG_IOCTL, "%s: SIOCGIWRTS - value %d disabled %s",
2585                  netdev->name, rts->value, (rts->disabled) ? "true" : "false");
2586
2587         return 0;
2588 }
2589
2590 static int at76_iw_handler_set_frag(struct net_device *netdev,
2591                                     struct iw_request_info *info,
2592                                     struct iw_param *frag, char *extra)
2593 {
2594         struct at76_priv *priv = netdev_priv(netdev);
2595         int ret = -EIWCOMMIT;
2596         int fthr = frag->value;
2597
2598         at76_dbg(DBG_IOCTL, "%s: SIOCSIWFRAG - value %d, disabled %s",
2599                  netdev->name, frag->value,
2600                  (frag->disabled) ? "true" : "false");
2601
2602         if (frag->disabled)
2603                 fthr = MAX_FRAG_THRESHOLD;
2604
2605         if ((fthr < MIN_FRAG_THRESHOLD) || (fthr > MAX_FRAG_THRESHOLD))
2606                 ret = -EINVAL;
2607         else
2608                 priv->frag_threshold = fthr & ~0x1;     /* get an even value */
2609
2610         return ret;
2611 }
2612
2613 static int at76_iw_handler_get_frag(struct net_device *netdev,
2614                                     struct iw_request_info *info,
2615                                     struct iw_param *frag, char *extra)
2616 {
2617         struct at76_priv *priv = netdev_priv(netdev);
2618
2619         frag->value = priv->frag_threshold;
2620         frag->disabled = (frag->value >= MAX_FRAG_THRESHOLD);
2621         frag->fixed = 1;
2622
2623         at76_dbg(DBG_IOCTL, "%s: SIOCGIWFRAG - value %d, disabled %s",
2624                  netdev->name, frag->value,
2625                  (frag->disabled) ? "true" : "false");
2626
2627         return 0;
2628 }
2629
2630 static int at76_iw_handler_get_txpow(struct net_device *netdev,
2631                                      struct iw_request_info *info,
2632                                      struct iw_param *power, char *extra)
2633 {
2634         power->value = 15;
2635         power->fixed = 1;       /* No power control */
2636         power->disabled = 0;
2637         power->flags = IW_TXPOW_DBM;
2638
2639         at76_dbg(DBG_IOCTL, "%s: SIOCGIWTXPOW - txpow %d dBm", netdev->name,
2640                  power->value);
2641
2642         return 0;
2643 }
2644
2645 /* jal: short retry is handled by the firmware (at least 0.90.x),
2646    while long retry is not (?) */
2647 static int at76_iw_handler_set_retry(struct net_device *netdev,
2648                                      struct iw_request_info *info,
2649                                      struct iw_param *retry, char *extra)
2650 {
2651         struct at76_priv *priv = netdev_priv(netdev);
2652         int ret = -EIWCOMMIT;
2653
2654         at76_dbg(DBG_IOCTL, "%s: SIOCSIWRETRY disabled %d flags 0x%x val %d",
2655                  netdev->name, retry->disabled, retry->flags, retry->value);
2656
2657         if (!retry->disabled && (retry->flags & IW_RETRY_LIMIT)) {
2658                 if ((retry->flags & IW_RETRY_MIN) ||
2659                     !(retry->flags & IW_RETRY_MAX))
2660                         priv->short_retry_limit = retry->value;
2661                 else
2662                         ret = -EINVAL;
2663         } else
2664                 ret = -EINVAL;
2665
2666         return ret;
2667 }
2668
2669 /* Adapted (ripped) from atmel.c */
2670 static int at76_iw_handler_get_retry(struct net_device *netdev,
2671                                      struct iw_request_info *info,
2672                                      struct iw_param *retry, char *extra)
2673 {
2674         struct at76_priv *priv = netdev_priv(netdev);
2675
2676         at76_dbg(DBG_IOCTL, "%s: SIOCGIWRETRY", netdev->name);
2677
2678         retry->disabled = 0;    /* Can't be disabled */
2679         retry->flags = IW_RETRY_LIMIT;
2680         retry->value = priv->short_retry_limit;
2681
2682         return 0;
2683 }
2684
2685 static int at76_iw_handler_set_encode(struct net_device *netdev,
2686                                       struct iw_request_info *info,
2687                                       struct iw_point *encoding, char *extra)
2688 {
2689         struct at76_priv *priv = netdev_priv(netdev);
2690         int index = (encoding->flags & IW_ENCODE_INDEX) - 1;
2691         int len = encoding->length;
2692
2693         at76_dbg(DBG_IOCTL, "%s: SIOCSIWENCODE - enc.flags %08x "
2694                  "pointer %p len %d", netdev->name, encoding->flags,
2695                  encoding->pointer, encoding->length);
2696         at76_dbg(DBG_IOCTL,
2697                  "%s: SIOCSIWENCODE - old wepstate: enabled %s key_id %d "
2698                  "auth_mode %s", netdev->name,
2699                  (priv->wep_enabled) ? "true" : "false", priv->wep_key_id,
2700                  (priv->auth_mode ==
2701                   WLAN_AUTH_SHARED_KEY) ? "restricted" : "open");
2702
2703         /* take the old default key if index is invalid */
2704         if ((index < 0) || (index >= WEP_KEYS))
2705                 index = priv->wep_key_id;
2706
2707         if (len > 0) {
2708                 if (len > WEP_LARGE_KEY_LEN)
2709                         len = WEP_LARGE_KEY_LEN;
2710
2711                 memset(priv->wep_keys[index], 0, WEP_KEY_LEN);
2712                 memcpy(priv->wep_keys[index], extra, len);
2713                 priv->wep_keys_len[index] = (len <= WEP_SMALL_KEY_LEN) ?
2714                     WEP_SMALL_KEY_LEN : WEP_LARGE_KEY_LEN;
2715                 priv->wep_enabled = 1;
2716         }
2717
2718         priv->wep_key_id = index;
2719         priv->wep_enabled = ((encoding->flags & IW_ENCODE_DISABLED) == 0);
2720
2721         if (encoding->flags & IW_ENCODE_RESTRICTED)
2722                 priv->auth_mode = WLAN_AUTH_SHARED_KEY;
2723         if (encoding->flags & IW_ENCODE_OPEN)
2724                 priv->auth_mode = WLAN_AUTH_OPEN;
2725
2726         at76_dbg(DBG_IOCTL,
2727                  "%s: SIOCSIWENCODE - new wepstate: enabled %s key_id %d "
2728                  "key_len %d auth_mode %s", netdev->name,
2729                  (priv->wep_enabled) ? "true" : "false", priv->wep_key_id + 1,
2730                  priv->wep_keys_len[priv->wep_key_id],
2731                  (priv->auth_mode ==
2732                   WLAN_AUTH_SHARED_KEY) ? "restricted" : "open");
2733
2734         return -EIWCOMMIT;
2735 }
2736
2737 static int at76_iw_handler_get_encode(struct net_device *netdev,
2738                                       struct iw_request_info *info,
2739                                       struct iw_point *encoding, char *extra)
2740 {
2741         struct at76_priv *priv = netdev_priv(netdev);
2742         int index = (encoding->flags & IW_ENCODE_INDEX) - 1;
2743
2744         if ((index < 0) || (index >= WEP_KEYS))
2745                 index = priv->wep_key_id;
2746
2747         encoding->flags =
2748             (priv->auth_mode == WLAN_AUTH_SHARED_KEY) ?
2749             IW_ENCODE_RESTRICTED : IW_ENCODE_OPEN;
2750
2751         if (!priv->wep_enabled)
2752                 encoding->flags |= IW_ENCODE_DISABLED;
2753
2754         if (encoding->pointer) {
2755                 encoding->length = priv->wep_keys_len[index];
2756
2757                 memcpy(extra, priv->wep_keys[index], priv->wep_keys_len[index]);
2758
2759                 encoding->flags |= (index + 1);
2760         }
2761
2762         at76_dbg(DBG_IOCTL, "%s: SIOCGIWENCODE - enc.flags %08x "
2763                  "pointer %p len %d", netdev->name, encoding->flags,
2764                  encoding->pointer, encoding->length);
2765         at76_dbg(DBG_IOCTL,
2766                  "%s: SIOCGIWENCODE - wepstate: enabled %s key_id %d "
2767                  "key_len %d auth_mode %s", netdev->name,
2768                  (priv->wep_enabled) ? "true" : "false", priv->wep_key_id + 1,
2769                  priv->wep_keys_len[priv->wep_key_id],
2770                  (priv->auth_mode ==
2771                   WLAN_AUTH_SHARED_KEY) ? "restricted" : "open");
2772
2773         return 0;
2774 }
2775
2776 static int at76_iw_handler_set_power(struct net_device *netdev,
2777                                      struct iw_request_info *info,
2778                                      struct iw_param *prq, char *extra)
2779 {
2780         int err = -EIWCOMMIT;
2781         struct at76_priv *priv = netdev_priv(netdev);
2782
2783         at76_dbg(DBG_IOCTL,
2784                  "%s: SIOCSIWPOWER - disabled %s flags 0x%x value 0x%x",
2785                  netdev->name, (prq->disabled) ? "true" : "false", prq->flags,
2786                  prq->value);
2787
2788         if (prq->disabled)
2789                 priv->pm_mode = AT76_PM_OFF;
2790         else {
2791                 switch (prq->flags & IW_POWER_MODE) {
2792                 case IW_POWER_ALL_R:
2793                 case IW_POWER_ON:
2794                         break;
2795                 default:
2796                         err = -EINVAL;
2797                         goto exit;
2798                 }
2799                 if (prq->flags & IW_POWER_PERIOD)
2800                         priv->pm_period = prq->value;
2801
2802                 if (prq->flags & IW_POWER_TIMEOUT) {
2803                         err = -EINVAL;
2804                         goto exit;
2805                 }
2806                 priv->pm_mode = AT76_PM_ON;
2807         }
2808 exit:
2809         return err;
2810 }
2811
2812 static int at76_iw_handler_get_power(struct net_device *netdev,
2813                                      struct iw_request_info *info,
2814                                      struct iw_param *power, char *extra)
2815 {
2816         struct at76_priv *priv = netdev_priv(netdev);
2817
2818         power->disabled = (priv->pm_mode == AT76_PM_OFF);
2819         if (!power->disabled) {
2820                 power->flags = IW_POWER_PERIOD | IW_POWER_ALL_R;
2821                 power->value = priv->pm_period;
2822         }
2823
2824         at76_dbg(DBG_IOCTL, "%s: SIOCGIWPOWER - %s flags 0x%x value 0x%x",
2825                  netdev->name, power->disabled ? "disabled" : "enabled",
2826                  power->flags, power->value);
2827
2828         return 0;
2829 }
2830
2831 /*******************************************************************************
2832  * Private IOCTLS
2833  */
2834 static int at76_iw_set_short_preamble(struct net_device *netdev,
2835                                       struct iw_request_info *info, char *name,
2836                                       char *extra)
2837 {
2838         struct at76_priv *priv = netdev_priv(netdev);
2839         int val = *((int *)name);
2840         int ret = -EIWCOMMIT;
2841
2842         at76_dbg(DBG_IOCTL, "%s: AT76_SET_SHORT_PREAMBLE, %d",
2843                  netdev->name, val);
2844
2845         if (val < PREAMBLE_TYPE_LONG || val > PREAMBLE_TYPE_AUTO)
2846                 ret = -EINVAL;
2847         else
2848                 priv->preamble_type = val;
2849
2850         return ret;
2851 }
2852
2853 static int at76_iw_get_short_preamble(struct net_device *netdev,
2854                                       struct iw_request_info *info,
2855                                       union iwreq_data *wrqu, char *extra)
2856 {
2857         struct at76_priv *priv = netdev_priv(netdev);
2858
2859         snprintf(wrqu->name, sizeof(wrqu->name), "%s (%d)",
2860                  preambles[priv->preamble_type], priv->preamble_type);
2861         return 0;
2862 }
2863
2864 static int at76_iw_set_debug(struct net_device *netdev,
2865                              struct iw_request_info *info,
2866                              struct iw_point *data, char *extra)
2867 {
2868         char *ptr;
2869         u32 val;
2870
2871         if (data->length > 0) {
2872                 val = simple_strtol(extra, &ptr, 0);
2873
2874                 if (ptr == extra)
2875                         val = DBG_DEFAULTS;
2876
2877                 at76_dbg(DBG_IOCTL, "%s: AT76_SET_DEBUG input %d: %s -> 0x%x",
2878                          netdev->name, data->length, extra, val);
2879         } else
2880                 val = DBG_DEFAULTS;
2881
2882         at76_dbg(DBG_IOCTL, "%s: AT76_SET_DEBUG, old 0x%x, new 0x%x",
2883                  netdev->name, at76_debug, val);
2884
2885         /* jal: some more output to pin down lockups */
2886         at76_dbg(DBG_IOCTL, "%s: netif running %d queue_stopped %d "
2887                  "carrier_ok %d", netdev->name, netif_running(netdev),
2888                  netif_queue_stopped(netdev), netif_carrier_ok(netdev));
2889
2890         at76_debug = val;
2891
2892         return 0;
2893 }
2894
2895 static int at76_iw_get_debug(struct net_device *netdev,
2896                              struct iw_request_info *info,
2897                              union iwreq_data *wrqu, char *extra)
2898 {
2899         snprintf(wrqu->name, sizeof(wrqu->name), "0x%08x", at76_debug);
2900         return 0;
2901 }
2902
2903 static int at76_iw_set_powersave_mode(struct net_device *netdev,
2904                                       struct iw_request_info *info, char *name,
2905                                       char *extra)
2906 {
2907         struct at76_priv *priv = netdev_priv(netdev);
2908         int val = *((int *)name);
2909         int ret = -EIWCOMMIT;
2910
2911         at76_dbg(DBG_IOCTL, "%s: AT76_SET_POWERSAVE_MODE, %d (%s)",
2912                  netdev->name, val,
2913                  val == AT76_PM_OFF ? "active" : val == AT76_PM_ON ? "save" :
2914                  val == AT76_PM_SMART ? "smart save" : "<invalid>");
2915         if (val < AT76_PM_OFF || val > AT76_PM_SMART)
2916                 ret = -EINVAL;
2917         else
2918                 priv->pm_mode = val;
2919
2920         return ret;
2921 }
2922
2923 static int at76_iw_get_powersave_mode(struct net_device *netdev,
2924                                       struct iw_request_info *info,
2925                                       union iwreq_data *wrqu, char *extra)
2926 {
2927         struct at76_priv *priv = netdev_priv(netdev);
2928         int *param = (int *)extra;
2929
2930         param[0] = priv->pm_mode;
2931         return 0;
2932 }
2933
2934 static int at76_iw_set_scan_times(struct net_device *netdev,
2935                                   struct iw_request_info *info, char *name,
2936                                   char *extra)
2937 {
2938         struct at76_priv *priv = netdev_priv(netdev);
2939         int mint = *((int *)name);
2940         int maxt = *((int *)name + 1);
2941         int ret = -EIWCOMMIT;
2942
2943         at76_dbg(DBG_IOCTL, "%s: AT76_SET_SCAN_TIMES - min %d max %d",
2944                  netdev->name, mint, maxt);
2945         if (mint <= 0 || maxt <= 0 || mint > maxt)
2946                 ret = -EINVAL;
2947         else {
2948                 priv->scan_min_time = mint;
2949                 priv->scan_max_time = maxt;
2950         }
2951
2952         return ret;
2953 }
2954
2955 static int at76_iw_get_scan_times(struct net_device *netdev,
2956                                   struct iw_request_info *info,
2957                                   union iwreq_data *wrqu, char *extra)
2958 {
2959         struct at76_priv *priv = netdev_priv(netdev);
2960         int *param = (int *)extra;
2961
2962         param[0] = priv->scan_min_time;
2963         param[1] = priv->scan_max_time;
2964         return 0;
2965 }
2966
2967 static int at76_iw_set_scan_mode(struct net_device *netdev,
2968                                  struct iw_request_info *info, char *name,
2969                                  char *extra)
2970 {
2971         struct at76_priv *priv = netdev_priv(netdev);
2972         int val = *((int *)name);
2973         int ret = -EIWCOMMIT;
2974
2975         at76_dbg(DBG_IOCTL, "%s: AT76_SET_SCAN_MODE - mode %s",
2976                  netdev->name, (val = SCAN_TYPE_ACTIVE) ? "active" :
2977                  (val = SCAN_TYPE_PASSIVE) ? "passive" : "<invalid>");
2978
2979         if (val != SCAN_TYPE_ACTIVE && val != SCAN_TYPE_PASSIVE)
2980                 ret = -EINVAL;
2981         else
2982                 priv->scan_mode = val;
2983
2984         return ret;
2985 }
2986
2987 static int at76_iw_get_scan_mode(struct net_device *netdev,
2988                                  struct iw_request_info *info,
2989                                  union iwreq_data *wrqu, char *extra)
2990 {
2991         struct at76_priv *priv = netdev_priv(netdev);
2992         int *param = (int *)extra;
2993
2994         param[0] = priv->scan_mode;
2995         return 0;
2996 }
2997
2998 #define AT76_SET_HANDLER(h, f) [h - SIOCIWFIRST] = (iw_handler) f
2999
3000 /* Standard wireless handlers */
3001 static const iw_handler at76_handlers[] = {
3002         AT76_SET_HANDLER(SIOCSIWCOMMIT, at76_iw_handler_commit),
3003         AT76_SET_HANDLER(SIOCGIWNAME, at76_iw_handler_get_name),
3004         AT76_SET_HANDLER(SIOCSIWFREQ, at76_iw_handler_set_freq),
3005         AT76_SET_HANDLER(SIOCGIWFREQ, at76_iw_handler_get_freq),
3006         AT76_SET_HANDLER(SIOCSIWMODE, at76_iw_handler_set_mode),
3007         AT76_SET_HANDLER(SIOCGIWMODE, at76_iw_handler_get_mode),
3008         AT76_SET_HANDLER(SIOCGIWRANGE, at76_iw_handler_get_range),
3009         AT76_SET_HANDLER(SIOCSIWSPY, at76_iw_handler_set_spy),
3010         AT76_SET_HANDLER(SIOCGIWSPY, at76_iw_handler_get_spy),
3011         AT76_SET_HANDLER(SIOCSIWTHRSPY, at76_iw_handler_set_thrspy),
3012         AT76_SET_HANDLER(SIOCGIWTHRSPY, at76_iw_handler_get_thrspy),
3013         AT76_SET_HANDLER(SIOCSIWAP, at76_iw_handler_set_wap),
3014         AT76_SET_HANDLER(SIOCGIWAP, at76_iw_handler_get_wap),
3015         AT76_SET_HANDLER(SIOCSIWSCAN, at76_iw_handler_set_scan),
3016         AT76_SET_HANDLER(SIOCGIWSCAN, at76_iw_handler_get_scan),
3017         AT76_SET_HANDLER(SIOCSIWESSID, at76_iw_handler_set_essid),
3018         AT76_SET_HANDLER(SIOCGIWESSID, at76_iw_handler_get_essid),
3019         AT76_SET_HANDLER(SIOCSIWRATE, at76_iw_handler_set_rate),
3020         AT76_SET_HANDLER(SIOCGIWRATE, at76_iw_handler_get_rate),
3021         AT76_SET_HANDLER(SIOCSIWRTS, at76_iw_handler_set_rts),
3022         AT76_SET_HANDLER(SIOCGIWRTS, at76_iw_handler_get_rts),
3023         AT76_SET_HANDLER(SIOCSIWFRAG, at76_iw_handler_set_frag),
3024         AT76_SET_HANDLER(SIOCGIWFRAG, at76_iw_handler_get_frag),
3025         AT76_SET_HANDLER(SIOCGIWTXPOW, at76_iw_handler_get_txpow),
3026         AT76_SET_HANDLER(SIOCSIWRETRY, at76_iw_handler_set_retry),
3027         AT76_SET_HANDLER(SIOCGIWRETRY, at76_iw_handler_get_retry),
3028         AT76_SET_HANDLER(SIOCSIWENCODE, at76_iw_handler_set_encode),
3029         AT76_SET_HANDLER(SIOCGIWENCODE, at76_iw_handler_get_encode),
3030         AT76_SET_HANDLER(SIOCSIWPOWER, at76_iw_handler_set_power),
3031         AT76_SET_HANDLER(SIOCGIWPOWER, at76_iw_handler_get_power)
3032 };
3033
3034 #define AT76_SET_PRIV(h, f) [h - SIOCIWFIRSTPRIV] = (iw_handler) f
3035
3036 /* Private wireless handlers */
3037 static const iw_handler at76_priv_handlers[] = {
3038         AT76_SET_PRIV(AT76_SET_SHORT_PREAMBLE, at76_iw_set_short_preamble),
3039         AT76_SET_PRIV(AT76_GET_SHORT_PREAMBLE, at76_iw_get_short_preamble),
3040         AT76_SET_PRIV(AT76_SET_DEBUG, at76_iw_set_debug),
3041         AT76_SET_PRIV(AT76_GET_DEBUG, at76_iw_get_debug),
3042         AT76_SET_PRIV(AT76_SET_POWERSAVE_MODE, at76_iw_set_powersave_mode),
3043         AT76_SET_PRIV(AT76_GET_POWERSAVE_MODE, at76_iw_get_powersave_mode),
3044         AT76_SET_PRIV(AT76_SET_SCAN_TIMES, at76_iw_set_scan_times),
3045         AT76_SET_PRIV(AT76_GET_SCAN_TIMES, at76_iw_get_scan_times),
3046         AT76_SET_PRIV(AT76_SET_SCAN_MODE, at76_iw_set_scan_mode),
3047         AT76_SET_PRIV(AT76_GET_SCAN_MODE, at76_iw_get_scan_mode),
3048 };
3049
3050 /* Names and arguments of private wireless handlers */
3051 static const struct iw_priv_args at76_priv_args[] = {
3052         /* 0 - long, 1 - short */
3053         {AT76_SET_SHORT_PREAMBLE,
3054          IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "set_preamble"},
3055
3056         {AT76_GET_SHORT_PREAMBLE,
3057          0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | 10, "get_preamble"},
3058
3059         /* we must pass the new debug mask as a string, because iwpriv cannot
3060          * parse hex numbers starting with 0x :-(  */
3061         {AT76_SET_DEBUG,
3062          IW_PRIV_TYPE_CHAR | 10, 0, "set_debug"},
3063
3064         {AT76_GET_DEBUG,
3065          0, IW_PRIV_TYPE_CHAR | IW_PRIV_SIZE_FIXED | 10, "get_debug"},
3066
3067         /* 1 - active, 2 - power save, 3 - smart power save */
3068         {AT76_SET_POWERSAVE_MODE,
3069          IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "set_powersave"},
3070
3071         {AT76_GET_POWERSAVE_MODE,
3072          0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "get_powersave"},
3073
3074         /* min_channel_time, max_channel_time */
3075         {AT76_SET_SCAN_TIMES,
3076          IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 2, 0, "set_scan_times"},
3077
3078         {AT76_GET_SCAN_TIMES,
3079          0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 2, "get_scan_times"},
3080
3081         /* 0 - active, 1 - passive scan */
3082         {AT76_SET_SCAN_MODE,
3083          IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, 0, "set_scan_mode"},
3084
3085         {AT76_GET_SCAN_MODE,
3086          0, IW_PRIV_TYPE_INT | IW_PRIV_SIZE_FIXED | 1, "get_scan_mode"},
3087 };
3088
3089 static const struct iw_handler_def at76_handler_def = {
3090         .num_standard = ARRAY_SIZE(at76_handlers),
3091         .num_private = ARRAY_SIZE(at76_priv_handlers),
3092         .num_private_args = ARRAY_SIZE(at76_priv_args),
3093         .standard = at76_handlers,
3094         .private = at76_priv_handlers,
3095         .private_args = at76_priv_args,
3096         .get_wireless_stats = at76_get_wireless_stats,
3097 };
3098
3099 static const u8 snapsig[] = { 0xaa, 0xaa, 0x03 };
3100
3101 /* RFC 1042 encapsulates Ethernet frames in 802.2 SNAP (0xaa, 0xaa, 0x03) with
3102  * a SNAP OID of 0 (0x00, 0x00, 0x00) */
3103 static const u8 rfc1042sig[] = { 0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00 };
3104
3105 static int at76_tx(struct sk_buff *skb, struct net_device *netdev)
3106 {
3107         struct at76_priv *priv = netdev_priv(netdev);
3108         struct net_device_stats *stats = &priv->stats;
3109         int ret = 0;
3110         int wlen;
3111         int submit_len;
3112         struct at76_tx_buffer *tx_buffer = priv->bulk_out_buffer;
3113         struct ieee80211_hdr_3addr *i802_11_hdr =
3114             (struct ieee80211_hdr_3addr *)tx_buffer->packet;
3115         u8 *payload = i802_11_hdr->payload;
3116         struct ethhdr *eh = (struct ethhdr *)skb->data;
3117
3118         if (netif_queue_stopped(netdev)) {
3119                 printk(KERN_ERR "%s: %s called while netdev is stopped\n",
3120                        netdev->name, __func__);
3121                 /* skip this packet */
3122                 dev_kfree_skb(skb);
3123                 return 0;
3124         }
3125
3126         if (priv->tx_urb->status == -EINPROGRESS) {
3127                 printk(KERN_ERR "%s: %s called while tx urb is pending\n",
3128                        netdev->name, __func__);
3129                 /* skip this packet */
3130                 dev_kfree_skb(skb);
3131                 return 0;
3132         }
3133
3134         if (skb->len < ETH_HLEN) {
3135                 printk(KERN_ERR "%s: %s: skb too short (%d)\n",
3136                        netdev->name, __func__, skb->len);
3137                 dev_kfree_skb(skb);
3138                 return 0;
3139         }
3140
3141         at76_ledtrig_tx_activity();     /* tell ledtrigger we send a packet */
3142
3143         /* we can get rid of memcpy if we set netdev->hard_header_len to
3144            reserve enough space, but we would need to keep the skb around */
3145
3146         if (ntohs(eh->h_proto) <= ETH_DATA_LEN) {
3147                 /* this is a 802.3 packet */
3148                 if (skb->len >= ETH_HLEN + sizeof(rfc1042sig)
3149                     && skb->data[ETH_HLEN] == rfc1042sig[0]
3150                     && skb->data[ETH_HLEN + 1] == rfc1042sig[1]) {
3151                         /* higher layer delivered SNAP header - keep it */
3152                         memcpy(payload, skb->data + ETH_HLEN,
3153                                skb->len - ETH_HLEN);
3154                         wlen = IEEE80211_3ADDR_LEN + skb->len - ETH_HLEN;
3155                 } else {
3156                         printk(KERN_ERR "%s: dropping non-SNAP 802.2 packet "
3157                                "(DSAP 0x%02x SSAP 0x%02x cntrl 0x%02x)\n",
3158                                priv->netdev->name, skb->data[ETH_HLEN],
3159                                skb->data[ETH_HLEN + 1],
3160                                skb->data[ETH_HLEN + 2]);
3161                         dev_kfree_skb(skb);
3162                         return 0;
3163                 }
3164         } else {
3165                 /* add RFC 1042 header in front */
3166                 memcpy(payload, rfc1042sig, sizeof(rfc1042sig));
3167                 memcpy(payload + sizeof(rfc1042sig), &eh->h_proto,
3168                        skb->len - offsetof(struct ethhdr, h_proto));
3169                 wlen = IEEE80211_3ADDR_LEN + sizeof(rfc1042sig) + skb->len -
3170                     offsetof(struct ethhdr, h_proto);
3171         }
3172
3173         /* make wireless header */
3174         i802_11_hdr->frame_ctl =
3175             cpu_to_le16(IEEE80211_FTYPE_DATA |
3176                         (priv->wep_enabled ? IEEE80211_FCTL_PROTECTED : 0) |
3177                         (priv->iw_mode ==
3178                          IW_MODE_INFRA ? IEEE80211_FCTL_TODS : 0));
3179
3180         if (priv->iw_mode == IW_MODE_ADHOC) {
3181                 memcpy(i802_11_hdr->addr1, eh->h_dest, ETH_ALEN);
3182                 memcpy(i802_11_hdr->addr2, eh->h_source, ETH_ALEN);
3183                 memcpy(i802_11_hdr->addr3, priv->bssid, ETH_ALEN);
3184         } else if (priv->iw_mode == IW_MODE_INFRA) {
3185                 memcpy(i802_11_hdr->addr1, priv->bssid, ETH_ALEN);
3186                 memcpy(i802_11_hdr->addr2, eh->h_source, ETH_ALEN);
3187                 memcpy(i802_11_hdr->addr3, eh->h_dest, ETH_ALEN);
3188         }
3189
3190         i802_11_hdr->duration_id = cpu_to_le16(0);
3191         i802_11_hdr->seq_ctl = cpu_to_le16(0);
3192
3193         /* setup 'Atmel' header */
3194         tx_buffer->wlength = cpu_to_le16(wlen);
3195         tx_buffer->tx_rate = priv->txrate;
3196         /* for broadcast destination addresses, the firmware 0.100.x
3197            seems to choose the highest rate set with CMD_STARTUP in
3198            basic_rate_set replacing this value */
3199
3200         memset(tx_buffer->reserved, 0, sizeof(tx_buffer->reserved));
3201
3202         tx_buffer->padding = at76_calc_padding(wlen);
3203         submit_len = wlen + AT76_TX_HDRLEN + tx_buffer->padding;
3204
3205         at76_dbg(DBG_TX_DATA_CONTENT, "%s skb->data %s", priv->netdev->name,
3206                  hex2str(skb->data, 32));
3207         at76_dbg(DBG_TX_DATA, "%s tx: wlen 0x%x pad 0x%x rate %d hdr %s",
3208                  priv->netdev->name,
3209                  le16_to_cpu(tx_buffer->wlength),
3210                  tx_buffer->padding, tx_buffer->tx_rate,
3211                  hex2str(i802_11_hdr, sizeof(*i802_11_hdr)));
3212         at76_dbg(DBG_TX_DATA_CONTENT, "%s payload %s", priv->netdev->name,
3213                  hex2str(payload, 48));
3214
3215         /* send stuff */
3216         netif_stop_queue(netdev);
3217         netdev->trans_start = jiffies;
3218
3219         usb_fill_bulk_urb(priv->tx_urb, priv->udev, priv->tx_pipe, tx_buffer,
3220                           submit_len, at76_tx_callback, priv);
3221         ret = usb_submit_urb(priv->tx_urb, GFP_ATOMIC);
3222         if (ret) {
3223                 stats->tx_errors++;
3224                 printk(KERN_ERR "%s: error in tx submit urb: %d\n",
3225                        netdev->name, ret);
3226                 if (ret == -EINVAL)
3227                         printk(KERN_ERR
3228                                "%s: -EINVAL: tx urb %p hcpriv %p complete %p\n",
3229                                priv->netdev->name, priv->tx_urb,
3230                                priv->tx_urb->hcpriv, priv->tx_urb->complete);
3231         } else {
3232                 stats->tx_bytes += skb->len;
3233                 dev_kfree_skb(skb);
3234         }
3235
3236         return ret;
3237 }
3238
3239 static void at76_tx_timeout(struct net_device *netdev)
3240 {
3241         struct at76_priv *priv = netdev_priv(netdev);
3242
3243         if (!priv)
3244                 return;
3245         dev_warn(&netdev->dev, "tx timeout.");
3246
3247         usb_unlink_urb(priv->tx_urb);
3248         priv->stats.tx_errors++;
3249 }
3250
3251 static int at76_submit_rx_urb(struct at76_priv *priv)
3252 {
3253         int ret;
3254         int size;
3255         struct sk_buff *skb = priv->rx_skb;
3256
3257         if (!priv->rx_urb) {
3258                 printk(KERN_ERR "%s: %s: priv->rx_urb is NULL\n",
3259                        priv->netdev->name, __func__);
3260                 return -EFAULT;
3261         }
3262
3263         if (!skb) {
3264                 skb = dev_alloc_skb(sizeof(struct at76_rx_buffer));
3265                 if (!skb) {
3266                         printk(KERN_ERR "%s: cannot allocate rx skbuff\n",
3267                                priv->netdev->name);
3268                         ret = -ENOMEM;
3269                         goto exit;
3270                 }
3271                 priv->rx_skb = skb;
3272         } else {
3273                 skb_push(skb, skb_headroom(skb));
3274                 skb_trim(skb, 0);
3275         }
3276
3277         size = skb_tailroom(skb);
3278         usb_fill_bulk_urb(priv->rx_urb, priv->udev, priv->rx_pipe,
3279                           skb_put(skb, size), size, at76_rx_callback, priv);
3280         ret = usb_submit_urb(priv->rx_urb, GFP_ATOMIC);
3281         if (ret < 0) {
3282                 if (ret == -ENODEV)
3283                         at76_dbg(DBG_DEVSTART,
3284                                  "usb_submit_urb returned -ENODEV");
3285                 else
3286                         printk(KERN_ERR "%s: rx, usb_submit_urb failed: %d\n",
3287                                priv->netdev->name, ret);
3288         }
3289
3290 exit:
3291         if (ret < 0 && ret != -ENODEV)
3292                 printk(KERN_ERR "%s: cannot submit rx urb - please unload the "
3293                        "driver and/or power cycle the device\n",
3294                        priv->netdev->name);
3295
3296         return ret;
3297 }
3298
3299 static int at76_open(struct net_device *netdev)
3300 {
3301         struct at76_priv *priv = netdev_priv(netdev);
3302         int ret = 0;
3303
3304         at76_dbg(DBG_PROC_ENTRY, "%s(): entry", __func__);
3305
3306         if (mutex_lock_interruptible(&priv->mtx))
3307                 return -EINTR;
3308
3309         /* if netdev->dev_addr != priv->mac_addr we must
3310            set the mac address in the device ! */
3311         if (compare_ether_addr(netdev->dev_addr, priv->mac_addr)) {
3312                 if (at76_add_mac_address(priv, netdev->dev_addr) >= 0)
3313                         at76_dbg(DBG_PROGRESS, "%s: set new MAC addr %s",
3314                                  netdev->name, mac2str(netdev->dev_addr));
3315         }
3316
3317         priv->scan_state = SCAN_IDLE;
3318         priv->last_scan = jiffies;
3319
3320         ret = at76_submit_rx_urb(priv);
3321         if (ret < 0) {
3322                 printk(KERN_ERR "%s: open: submit_rx_urb failed: %d\n",
3323                        netdev->name, ret);
3324                 goto error;
3325         }
3326
3327         schedule_delayed_work(&priv->dwork_restart, 0);
3328
3329         at76_dbg(DBG_PROC_ENTRY, "%s(): end", __func__);
3330 error:
3331         mutex_unlock(&priv->mtx);
3332         return ret < 0 ? ret : 0;
3333 }
3334
3335 static int at76_stop(struct net_device *netdev)
3336 {
3337         struct at76_priv *priv = netdev_priv(netdev);
3338
3339         at76_dbg(DBG_DEVSTART, "%s: ENTER", __func__);
3340
3341         if (mutex_lock_interruptible(&priv->mtx))
3342                 return -EINTR;
3343
3344         at76_quiesce(priv);
3345
3346         if (!priv->device_unplugged) {
3347                 /* We are called by "ifconfig ethX down", not because the
3348                  * device is not available anymore. */
3349                 at76_set_radio(priv, 0);
3350
3351                 /* We unlink rx_urb because at76_open() re-submits it.
3352                  * If unplugged, at76_delete_device() takes care of it. */
3353                 usb_kill_urb(priv->rx_urb);
3354         }
3355
3356         /* free the bss_list */
3357         at76_free_bss_list(priv);
3358
3359         mutex_unlock(&priv->mtx);
3360         at76_dbg(DBG_DEVSTART, "%s: EXIT", __func__);
3361
3362         return 0;
3363 }
3364
3365 static void at76_ethtool_get_drvinfo(struct net_device *netdev,
3366                                      struct ethtool_drvinfo *info)
3367 {
3368         struct at76_priv *priv = netdev_priv(netdev);
3369
3370         strncpy(info->driver, DRIVER_NAME, sizeof(info->driver));
3371         strncpy(info->version, DRIVER_VERSION, sizeof(info->version));
3372
3373         usb_make_path(priv->udev, info->bus_info, sizeof(info->bus_info));
3374
3375         snprintf(info->fw_version, sizeof(info->fw_version), "%d.%d.%d-%d",
3376                  priv->fw_version.major, priv->fw_version.minor,
3377                  priv->fw_version.patch, priv->fw_version.build);
3378 }
3379
3380 static u32 at76_ethtool_get_link(struct net_device *netdev)
3381 {
3382         struct at76_priv *priv = netdev_priv(netdev);
3383         return priv->mac_state == MAC_CONNECTED;
3384 }
3385
3386 static struct ethtool_ops at76_ethtool_ops = {
3387         .get_drvinfo = at76_ethtool_get_drvinfo,
3388         .get_link = at76_ethtool_get_link,
3389 };
3390
3391 /* Download external firmware */
3392 static int at76_load_external_fw(struct usb_device *udev, struct fwentry *fwe)
3393 {
3394         int ret;
3395         int op_mode;
3396         int blockno = 0;
3397         int bsize;
3398         u8 *block;
3399         u8 *buf = fwe->extfw;
3400         int size = fwe->extfw_size;
3401
3402         if (!buf || !size)
3403                 return -ENOENT;
3404
3405         op_mode = at76_get_op_mode(udev);
3406         at76_dbg(DBG_DEVSTART, "opmode %d", op_mode);
3407
3408         if (op_mode != OPMODE_NORMAL_NIC_WITHOUT_FLASH) {
3409                 dev_printk(KERN_ERR, &udev->dev, "unexpected opmode %d\n",
3410                            op_mode);
3411                 return -EINVAL;
3412         }
3413
3414         block = kmalloc(FW_BLOCK_SIZE, GFP_KERNEL);
3415         if (!block)
3416                 return -ENOMEM;
3417
3418         at76_dbg(DBG_DEVSTART, "downloading external firmware");
3419
3420         /* for fw >= 0.100, the device needs an extra empty block */
3421         do {
3422                 bsize = min_t(int, size, FW_BLOCK_SIZE);
3423                 memcpy(block, buf, bsize);
3424                 at76_dbg(DBG_DEVSTART,
3425                          "ext fw, size left = %5d, bsize = %4d, blockno = %2d",
3426                          size, bsize, blockno);
3427                 ret = at76_load_ext_fw_block(udev, blockno, block, bsize);
3428                 if (ret != bsize) {
3429                         dev_printk(KERN_ERR, &udev->dev,
3430                                    "loading %dth firmware block failed: %d\n",
3431                                    blockno, ret);
3432                         goto exit;
3433                 }
3434                 buf += bsize;
3435                 size -= bsize;
3436                 blockno++;
3437         } while (bsize > 0);
3438
3439         if (at76_is_505a(fwe->board_type)) {
3440                 at76_dbg(DBG_DEVSTART, "200 ms delay for 505a");
3441                 schedule_timeout_interruptible(HZ / 5 + 1);
3442         }
3443
3444 exit:
3445         kfree(block);
3446         if (ret < 0)
3447                 dev_printk(KERN_ERR, &udev->dev,
3448                            "downloading external firmware failed: %d\n", ret);
3449         return ret;
3450 }
3451
3452 /* Download internal firmware */
3453 static int at76_load_internal_fw(struct usb_device *udev, struct fwentry *fwe)
3454 {
3455         int ret;
3456         int need_remap = !at76_is_505a(fwe->board_type);
3457
3458         ret = at76_usbdfu_download(udev, fwe->intfw, fwe->intfw_size,
3459                                    need_remap ? 0 : 2 * HZ);
3460
3461         if (ret < 0) {
3462                 dev_printk(KERN_ERR, &udev->dev,
3463                            "downloading internal fw failed with %d\n", ret);
3464                 goto exit;
3465         }
3466
3467         at76_dbg(DBG_DEVSTART, "sending REMAP");
3468
3469         /* no REMAP for 505A (see SF driver) */
3470         if (need_remap) {
3471                 ret = at76_remap(udev);
3472                 if (ret < 0) {
3473                         dev_printk(KERN_ERR, &udev->dev,
3474                                    "sending REMAP failed with %d\n", ret);
3475                         goto exit;
3476                 }
3477         }
3478
3479         at76_dbg(DBG_DEVSTART, "sleeping for 2 seconds");
3480         schedule_timeout_interruptible(2 * HZ + 1);
3481         usb_reset_device(udev);
3482
3483 exit:
3484         return ret;
3485 }
3486
3487 static int at76_match_essid(struct at76_priv *priv, struct bss_info *ptr)
3488 {
3489         /* common criteria for both modi */
3490
3491         int ret = (priv->essid_size == 0 /* ANY ssid */  ||
3492                    (priv->essid_size == ptr->ssid_len &&
3493                     !memcmp(priv->essid, ptr->ssid, ptr->ssid_len)));
3494         if (!ret)
3495                 at76_dbg(DBG_BSS_MATCH,
3496                          "%s bss table entry %p: essid didn't match",
3497                          priv->netdev->name, ptr);
3498         return ret;
3499 }
3500
3501 static inline int at76_match_mode(struct at76_priv *priv, struct bss_info *ptr)
3502 {
3503         int ret;
3504
3505         if (priv->iw_mode == IW_MODE_ADHOC)
3506                 ret = ptr->capa & WLAN_CAPABILITY_IBSS;
3507         else
3508                 ret = ptr->capa & WLAN_CAPABILITY_ESS;
3509         if (!ret)
3510                 at76_dbg(DBG_BSS_MATCH,
3511                          "%s bss table entry %p: mode didn't match",
3512                          priv->netdev->name, ptr);
3513         return ret;
3514 }
3515
3516 static int at76_match_rates(struct at76_priv *priv, struct bss_info *ptr)
3517 {
3518         int i;
3519
3520         for (i = 0; i < ptr->rates_len; i++) {
3521                 u8 rate = ptr->rates[i];
3522
3523                 if (!(rate & 0x80))
3524                         continue;
3525
3526                 /* this is a basic rate we have to support
3527                    (see IEEE802.11, ch. 7.3.2.2) */
3528                 if (rate != (0x80 | hw_rates[0])
3529                     && rate != (0x80 | hw_rates[1])
3530                     && rate != (0x80 | hw_rates[2])
3531                     && rate != (0x80 | hw_rates[3])) {
3532                         at76_dbg(DBG_BSS_MATCH,
3533                                  "%s: bss table entry %p: basic rate %02x not "
3534                                  "supported", priv->netdev->name, ptr, rate);
3535                         return 0;
3536                 }
3537         }
3538
3539         /* if we use short preamble, the bss must support it */
3540         if (priv->preamble_type == PREAMBLE_TYPE_SHORT &&
3541             !(ptr->capa & WLAN_CAPABILITY_SHORT_PREAMBLE)) {
3542                 at76_dbg(DBG_BSS_MATCH,
3543                          "%s: %p does not support short preamble",
3544                          priv->netdev->name, ptr);
3545                 return 0;
3546         } else
3547                 return 1;
3548 }
3549
3550 static inline int at76_match_wep(struct at76_priv *priv, struct bss_info *ptr)
3551 {
3552         if (!priv->wep_enabled && ptr->capa & WLAN_CAPABILITY_PRIVACY) {
3553                 /* we have disabled WEP, but the BSS signals privacy */
3554                 at76_dbg(DBG_BSS_MATCH,
3555                          "%s: bss table entry %p: requires encryption",
3556                          priv->netdev->name, ptr);
3557                 return 0;
3558         }
3559         /* otherwise if the BSS does not signal privacy it may well
3560            accept encrypted packets from us ... */
3561         return 1;
3562 }
3563
3564 static inline int at76_match_bssid(struct at76_priv *priv, struct bss_info *ptr)
3565 {
3566         if (!priv->wanted_bssid_valid ||
3567             !compare_ether_addr(ptr->bssid, priv->wanted_bssid))
3568                 return 1;
3569
3570         at76_dbg(DBG_BSS_MATCH,
3571                  "%s: requested bssid - %s does not match",
3572                  priv->netdev->name, mac2str(priv->wanted_bssid));
3573         at76_dbg(DBG_BSS_MATCH,
3574                  "      AP bssid - %s of bss table entry %p",
3575                  mac2str(ptr->bssid), ptr);
3576         return 0;
3577 }
3578
3579 /**
3580  * at76_match_bss - try to find a matching bss in priv->bss
3581  *
3582  * last - last bss tried
3583  *
3584  * last == NULL signals a new round starting with priv->bss_list.next
3585  * this function must be called inside an acquired priv->bss_list_spinlock
3586  * otherwise the timeout on bss may remove the newly chosen entry
3587  */
3588 static struct bss_info *at76_match_bss(struct at76_priv *priv,
3589                                        struct bss_info *last)
3590 {
3591         struct bss_info *ptr = NULL;
3592         struct list_head *curr;
3593
3594         curr = last ? last->list.next : priv->bss_list.next;
3595         while (curr != &priv->bss_list) {
3596                 ptr = list_entry(curr, struct bss_info, list);
3597                 if (at76_match_essid(priv, ptr) && at76_match_mode(priv, ptr)
3598                     && at76_match_wep(priv, ptr) && at76_match_rates(priv, ptr)
3599                     && at76_match_bssid(priv, ptr))
3600                         break;
3601                 curr = curr->next;
3602         }
3603
3604         if (curr == &priv->bss_list)
3605                 ptr = NULL;
3606         /* otherwise ptr points to the struct bss_info we have chosen */
3607
3608         at76_dbg(DBG_BSS_TABLE, "%s %s: returned %p", priv->netdev->name,
3609                  __func__, ptr);
3610         return ptr;
3611 }
3612
3613 /* Start joining a matching BSS, or create own IBSS */
3614 static void at76_work_join(struct work_struct *work)
3615 {
3616         struct at76_priv *priv = container_of(work, struct at76_priv,
3617                                               work_join);
3618         int ret;
3619         unsigned long flags;
3620
3621         mutex_lock(&priv->mtx);
3622
3623         WARN_ON(priv->mac_state != MAC_JOINING);
3624         if (priv->mac_state != MAC_JOINING)
3625                 goto exit;
3626
3627         /* secure the access to priv->curr_bss ! */
3628         spin_lock_irqsave(&priv->bss_list_spinlock, flags);
3629         priv->curr_bss = at76_match_bss(priv, priv->curr_bss);
3630         spin_unlock_irqrestore(&priv->bss_list_spinlock, flags);
3631
3632         if (!priv->curr_bss) {
3633                 /* here we haven't found a matching (i)bss ... */
3634                 if (priv->iw_mode == IW_MODE_ADHOC) {
3635                         at76_set_mac_state(priv, MAC_OWN_IBSS);
3636                         at76_start_ibss(priv);
3637                         goto exit;
3638                 }
3639                 /* haven't found a matching BSS in infra mode - try again */
3640                 at76_set_mac_state(priv, MAC_SCANNING);
3641                 schedule_work(&priv->work_start_scan);
3642                 goto exit;
3643         }
3644
3645         ret = at76_join_bss(priv, priv->curr_bss);
3646         if (ret < 0) {
3647                 printk(KERN_ERR "%s: join_bss failed with %d\n",
3648                        priv->netdev->name, ret);
3649                 goto exit;
3650         }
3651
3652         ret = at76_wait_completion(priv, CMD_JOIN);
3653         if (ret != CMD_STATUS_COMPLETE) {
3654                 if (ret != CMD_STATUS_TIME_OUT)
3655                         printk(KERN_ERR "%s: join_bss completed with %d\n",
3656                                priv->netdev->name, ret);
3657                 else
3658                         printk(KERN_INFO "%s: join_bss ssid %s timed out\n",
3659                                priv->netdev->name,
3660                                mac2str(priv->curr_bss->bssid));
3661
3662                 /* retry next BSS immediately */
3663                 schedule_work(&priv->work_join);
3664                 goto exit;
3665         }
3666
3667         /* here we have joined the (I)BSS */
3668         if (priv->iw_mode == IW_MODE_ADHOC) {
3669                 struct bss_info *bptr = priv->curr_bss;
3670                 at76_set_mac_state(priv, MAC_CONNECTED);
3671                 /* get ESSID, BSSID and channel for priv->curr_bss */
3672                 priv->essid_size = bptr->ssid_len;
3673                 memcpy(priv->essid, bptr->ssid, bptr->ssid_len);
3674                 memcpy(priv->bssid, bptr->bssid, ETH_ALEN);
3675                 priv->channel = bptr->channel;
3676                 at76_iwevent_bss_connect(priv->netdev, bptr->bssid);
3677                 netif_carrier_on(priv->netdev);
3678                 netif_start_queue(priv->netdev);
3679                 /* just to be sure */
3680                 cancel_delayed_work(&priv->dwork_get_scan);
3681                 cancel_delayed_work(&priv->dwork_auth);
3682                 cancel_delayed_work(&priv->dwork_assoc);
3683         } else {
3684                 /* send auth req */
3685                 priv->retries = AUTH_RETRIES;
3686                 at76_set_mac_state(priv, MAC_AUTH);
3687                 at76_auth_req(priv, priv->curr_bss, 1, NULL);
3688                 at76_dbg(DBG_MGMT_TIMER,
3689                          "%s:%d: starting mgmt_timer + HZ", __func__, __LINE__);
3690                 schedule_delayed_work(&priv->dwork_auth, AUTH_TIMEOUT);
3691         }
3692
3693 exit:
3694         mutex_unlock(&priv->mtx);
3695 }
3696
3697 /* Reap scan results */
3698 static void at76_dwork_get_scan(struct work_struct *work)
3699 {
3700         int status;
3701         int ret;
3702         struct at76_priv *priv = container_of(work, struct at76_priv,
3703                                               dwork_get_scan.work);
3704
3705         mutex_lock(&priv->mtx);
3706         WARN_ON(priv->mac_state != MAC_SCANNING);
3707         if (priv->mac_state != MAC_SCANNING)
3708                 goto exit;
3709
3710         status = at76_get_cmd_status(priv->udev, CMD_SCAN);
3711         if (status < 0) {
3712                 printk(KERN_ERR "%s: %s: at76_get_cmd_status failed with %d\n",
3713                        priv->netdev->name, __func__, status);
3714                 status = CMD_STATUS_IN_PROGRESS;
3715                 /* INFO: Hope it was a one off error - if not, scanning
3716                    further down the line and stop this cycle */
3717         }
3718         at76_dbg(DBG_PROGRESS,
3719                  "%s %s: got cmd_status %d (state %s, need_any %d)",
3720                  priv->netdev->name, __func__, status,
3721                  mac_states[priv->mac_state], priv->scan_need_any);
3722
3723         if (status != CMD_STATUS_COMPLETE) {
3724                 if ((status != CMD_STATUS_IN_PROGRESS) &&
3725                     (status != CMD_STATUS_IDLE))
3726                         printk(KERN_ERR "%s: %s: Bad scan status: %s\n",
3727                                priv->netdev->name, __func__,
3728                                at76_get_cmd_status_string(status));
3729
3730                 /* the first cmd status after scan start is always a IDLE ->
3731                    start the timer to poll again until COMPLETED */
3732                 at76_dbg(DBG_MGMT_TIMER,
3733                          "%s:%d: starting mgmt_timer for %d ticks",
3734                          __func__, __LINE__, SCAN_POLL_INTERVAL);
3735                 schedule_delayed_work(&priv->dwork_get_scan,
3736                                       SCAN_POLL_INTERVAL);
3737                 goto exit;
3738         }
3739
3740         if (at76_debug & DBG_BSS_TABLE)
3741                 at76_dump_bss_table(priv);
3742
3743         if (priv->scan_need_any) {
3744                 ret = at76_start_scan(priv, 0);
3745                 if (ret < 0)
3746                         printk(KERN_ERR
3747                                "%s: %s: start_scan (ANY) failed with %d\n",
3748                                priv->netdev->name, __func__, ret);
3749                 at76_dbg(DBG_MGMT_TIMER,
3750                          "%s:%d: starting mgmt_timer for %d ticks", __func__,
3751                          __LINE__, SCAN_POLL_INTERVAL);
3752                 schedule_delayed_work(&priv->dwork_get_scan,
3753                                       SCAN_POLL_INTERVAL);
3754                 priv->scan_need_any = 0;
3755         } else {
3756                 priv->scan_state = SCAN_COMPLETED;
3757                 /* report the end of scan to user space */
3758                 at76_iwevent_scan_complete(priv->netdev);
3759                 at76_set_mac_state(priv, MAC_JOINING);
3760                 schedule_work(&priv->work_join);
3761         }
3762
3763 exit:
3764         mutex_unlock(&priv->mtx);
3765 }
3766
3767 /* Handle loss of beacons from the AP */
3768 static void at76_dwork_beacon(struct work_struct *work)
3769 {
3770         struct at76_priv *priv = container_of(work, struct at76_priv,
3771                                               dwork_beacon.work);
3772
3773         mutex_lock(&priv->mtx);
3774         if (priv->mac_state != MAC_CONNECTED || priv->iw_mode != IW_MODE_INFRA)
3775                 goto exit;
3776
3777         /* We haven't received any beacons from out AP for BEACON_TIMEOUT */
3778         printk(KERN_INFO "%s: lost beacon bssid %s\n",
3779                priv->netdev->name, mac2str(priv->curr_bss->bssid));
3780
3781         netif_carrier_off(priv->netdev);
3782         netif_stop_queue(priv->netdev);
3783         at76_iwevent_bss_disconnect(priv->netdev);
3784         at76_set_mac_state(priv, MAC_SCANNING);
3785         schedule_work(&priv->work_start_scan);
3786
3787 exit:
3788         mutex_unlock(&priv->mtx);
3789 }
3790
3791 /* Handle authentication response timeout */
3792 static void at76_dwork_auth(struct work_struct *work)
3793 {
3794         struct at76_priv *priv = container_of(work, struct at76_priv,
3795                                               dwork_auth.work);
3796
3797         mutex_lock(&priv->mtx);
3798         WARN_ON(priv->mac_state != MAC_AUTH);
3799         if (priv->mac_state != MAC_AUTH)
3800                 goto exit;
3801
3802         at76_dbg(DBG_PROGRESS, "%s: authentication response timeout",
3803                  priv->netdev->name);
3804
3805         if (priv->retries-- >= 0) {
3806                 at76_auth_req(priv, priv->curr_bss, 1, NULL);
3807                 at76_dbg(DBG_MGMT_TIMER, "%s:%d: starting mgmt_timer + HZ",
3808                          __func__, __LINE__);
3809                 schedule_delayed_work(&priv->dwork_auth, AUTH_TIMEOUT);
3810         } else {
3811                 /* try to get next matching BSS */
3812                 at76_set_mac_state(priv, MAC_JOINING);
3813                 schedule_work(&priv->work_join);
3814         }
3815
3816 exit:
3817         mutex_unlock(&priv->mtx);
3818 }
3819
3820 /* Handle association response timeout */
3821 static void at76_dwork_assoc(struct work_struct *work)
3822 {
3823         struct at76_priv *priv = container_of(work, struct at76_priv,
3824                                               dwork_assoc.work);
3825
3826         mutex_lock(&priv->mtx);
3827         WARN_ON(priv->mac_state != MAC_ASSOC);
3828         if (priv->mac_state != MAC_ASSOC)
3829                 goto exit;
3830
3831         at76_dbg(DBG_PROGRESS, "%s: association response timeout",
3832                  priv->netdev->name);
3833
3834         if (priv->retries-- >= 0) {
3835                 at76_assoc_req(priv, priv->curr_bss);
3836                 at76_dbg(DBG_MGMT_TIMER, "%s:%d: starting mgmt_timer + HZ",
3837                          __func__, __LINE__);
3838                 schedule_delayed_work(&priv->dwork_assoc, ASSOC_TIMEOUT);
3839         } else {
3840                 /* try to get next matching BSS */
3841                 at76_set_mac_state(priv, MAC_JOINING);
3842                 schedule_work(&priv->work_join);
3843         }
3844
3845 exit:
3846         mutex_unlock(&priv->mtx);
3847 }
3848
3849 /* Read new bssid in ad-hoc mode */
3850 static void at76_work_new_bss(struct work_struct *work)
3851 {
3852         struct at76_priv *priv = container_of(work, struct at76_priv,
3853                                               work_new_bss);
3854         int ret;
3855         struct mib_mac_mgmt mac_mgmt;
3856
3857         mutex_lock(&priv->mtx);
3858
3859         ret = at76_get_mib(priv->udev, MIB_MAC_MGMT, &mac_mgmt,
3860                            sizeof(struct mib_mac_mgmt));
3861         if (ret < 0) {
3862                 printk(KERN_ERR "%s: at76_get_mib failed: %d\n",
3863                        priv->netdev->name, ret);
3864                 goto exit;
3865         }
3866
3867         at76_dbg(DBG_PROGRESS, "ibss_change = 0x%2x", mac_mgmt.ibss_change);
3868         memcpy(priv->bssid, mac_mgmt.current_bssid, ETH_ALEN);
3869         at76_dbg(DBG_PROGRESS, "using BSSID %s", mac2str(priv->bssid));
3870
3871         at76_iwevent_bss_connect(priv->netdev, priv->bssid);
3872
3873         priv->mib_buf.type = MIB_MAC_MGMT;
3874         priv->mib_buf.size = 1;
3875         priv->mib_buf.index = offsetof(struct mib_mac_mgmt, ibss_change);
3876         priv->mib_buf.data.byte = 0;
3877
3878         ret = at76_set_mib(priv, &priv->mib_buf);
3879         if (ret < 0)
3880                 printk(KERN_ERR "%s: set_mib (ibss change ok) failed: %d\n",
3881                        priv->netdev->name, ret);
3882
3883 exit:
3884         mutex_unlock(&priv->mtx);
3885 }
3886
3887 static int at76_startup_device(struct at76_priv *priv)
3888 {
3889         struct at76_card_config *ccfg = &priv->card_config;
3890         int ret;
3891
3892         at76_dbg(DBG_PARAMS,
3893                  "%s param: ssid %.*s (%s) mode %s ch %d wep %s key %d "
3894                  "keylen %d", priv->netdev->name, priv->essid_size, priv->essid,
3895                  hex2str(priv->essid, IW_ESSID_MAX_SIZE),
3896                  priv->iw_mode == IW_MODE_ADHOC ? "adhoc" : "infra",
3897                  priv->channel, priv->wep_enabled ? "enabled" : "disabled",
3898                  priv->wep_key_id, priv->wep_keys_len[priv->wep_key_id]);
3899         at76_dbg(DBG_PARAMS,
3900                  "%s param: preamble %s rts %d retry %d frag %d "
3901                  "txrate %s auth_mode %d", priv->netdev->name,
3902                  preambles[priv->preamble_type], priv->rts_threshold,
3903                  priv->short_retry_limit, priv->frag_threshold,
3904                  priv->txrate == TX_RATE_1MBIT ? "1MBit" : priv->txrate ==
3905                  TX_RATE_2MBIT ? "2MBit" : priv->txrate ==
3906                  TX_RATE_5_5MBIT ? "5.5MBit" : priv->txrate ==
3907                  TX_RATE_11MBIT ? "11MBit" : priv->txrate ==
3908                  TX_RATE_AUTO ? "auto" : "<invalid>", priv->auth_mode);
3909         at76_dbg(DBG_PARAMS,
3910                  "%s param: pm_mode %d pm_period %d auth_mode %s "
3911                  "scan_times %d %d scan_mode %s",
3912                  priv->netdev->name, priv->pm_mode, priv->pm_period,
3913                  priv->auth_mode == WLAN_AUTH_OPEN ? "open" : "shared_secret",
3914                  priv->scan_min_time, priv->scan_max_time,
3915                  priv->scan_mode == SCAN_TYPE_ACTIVE ? "active" : "passive");
3916
3917         memset(ccfg, 0, sizeof(struct at76_card_config));
3918         ccfg->promiscuous_mode = 0;
3919         ccfg->short_retry_limit = priv->short_retry_limit;
3920
3921         if (priv->wep_enabled) {
3922                 if (priv->wep_keys_len[priv->wep_key_id] > WEP_SMALL_KEY_LEN)
3923                         ccfg->encryption_type = 2;
3924                 else
3925                         ccfg->encryption_type = 1;
3926
3927                 /* jal: always exclude unencrypted if WEP is active */
3928                 ccfg->exclude_unencrypted = 1;
3929         } else {
3930                 ccfg->exclude_unencrypted = 0;
3931                 ccfg->encryption_type = 0;
3932         }
3933
3934         ccfg->rts_threshold = cpu_to_le16(priv->rts_threshold);
3935         ccfg->fragmentation_threshold = cpu_to_le16(priv->frag_threshold);
3936
3937         memcpy(ccfg->basic_rate_set, hw_rates, 4);
3938         /* jal: really needed, we do a set_mib for autorate later ??? */
3939         ccfg->auto_rate_fallback = (priv->txrate == TX_RATE_AUTO ? 1 : 0);
3940         ccfg->channel = priv->channel;
3941         ccfg->privacy_invoked = priv->wep_enabled;
3942         memcpy(ccfg->current_ssid, priv->essid, IW_ESSID_MAX_SIZE);
3943         ccfg->ssid_len = priv->essid_size;
3944
3945         ccfg->wep_default_key_id = priv->wep_key_id;
3946         memcpy(ccfg->wep_default_key_value, priv->wep_keys, 4 * WEP_KEY_LEN);
3947
3948         ccfg->short_preamble = priv->preamble_type;
3949         ccfg->beacon_period = cpu_to_le16(priv->beacon_period);
3950
3951         ret = at76_set_card_command(priv->udev, CMD_STARTUP, &priv->card_config,
3952                                     sizeof(struct at76_card_config));
3953         if (ret < 0) {
3954                 printk(KERN_ERR "%s: at76_set_card_command failed: %d\n",
3955                        priv->netdev->name, ret);
3956                 return ret;
3957         }
3958
3959         at76_wait_completion(priv, CMD_STARTUP);
3960
3961         /* remove BSSID from previous run */
3962         memset(priv->bssid, 0, ETH_ALEN);
3963
3964         if (at76_set_radio(priv, 1) == 1)
3965                 at76_wait_completion(priv, CMD_RADIO_ON);
3966
3967         ret = at76_set_preamble(priv, priv->preamble_type);
3968         if (ret < 0)
3969                 return ret;
3970
3971         ret = at76_set_frag(priv, priv->frag_threshold);
3972         if (ret < 0)
3973                 return ret;
3974
3975         ret = at76_set_rts(priv, priv->rts_threshold);
3976         if (ret < 0)
3977                 return ret;
3978
3979         ret = at76_set_autorate_fallback(priv,
3980                                          priv->txrate == TX_RATE_AUTO ? 1 : 0);
3981         if (ret < 0)
3982                 return ret;
3983
3984         ret = at76_set_pm_mode(priv);
3985         if (ret < 0)
3986                 return ret;
3987
3988         if (at76_debug & DBG_MIB) {
3989                 at76_dump_mib_mac(priv);
3990                 at76_dump_mib_mac_addr(priv);
3991                 at76_dump_mib_mac_mgmt(priv);
3992                 at76_dump_mib_mac_wep(priv);
3993                 at76_dump_mib_mdomain(priv);
3994                 at76_dump_mib_phy(priv);
3995                 at76_dump_mib_local(priv);
3996         }
3997
3998         return 0;
3999 }
4000
4001 /* Restart the interface */
4002 static void at76_dwork_restart(struct work_struct *work)
4003 {
4004         struct at76_priv *priv = container_of(work, struct at76_priv,
4005                                               dwork_restart.work);
4006
4007         mutex_lock(&priv->mtx);
4008
4009         netif_carrier_off(priv->netdev);        /* stop netdev watchdog */
4010         netif_stop_queue(priv->netdev); /* stop tx data packets */
4011
4012         at76_startup_device(priv);
4013
4014         if (priv->iw_mode != IW_MODE_MONITOR) {
4015                 priv->netdev->type = ARPHRD_ETHER;
4016                 at76_set_mac_state(priv, MAC_SCANNING);
4017                 schedule_work(&priv->work_start_scan);
4018         } else {
4019                 priv->netdev->type = ARPHRD_IEEE80211_RADIOTAP;
4020                 at76_start_monitor(priv);
4021         }
4022
4023         mutex_unlock(&priv->mtx);
4024 }
4025
4026 /* Initiate scanning */
4027 static void at76_work_start_scan(struct work_struct *work)
4028 {
4029         struct at76_priv *priv = container_of(work, struct at76_priv,
4030                                               work_start_scan);
4031         int ret;
4032
4033         mutex_lock(&priv->mtx);
4034
4035         WARN_ON(priv->mac_state != MAC_SCANNING);
4036         if (priv->mac_state != MAC_SCANNING)
4037                 goto exit;
4038
4039         /* only clear the bss list when a scan is actively initiated,
4040          * otherwise simply rely on at76_bss_list_timeout */
4041         if (priv->scan_state == SCAN_IN_PROGRESS) {
4042                 at76_free_bss_list(priv);
4043                 priv->scan_need_any = 1;
4044         } else
4045                 priv->scan_need_any = 0;
4046
4047         ret = at76_start_scan(priv, 1);
4048
4049         if (ret < 0)
4050                 printk(KERN_ERR "%s: %s: start_scan failed with %d\n",
4051                        priv->netdev->name, __func__, ret);
4052         else {
4053                 at76_dbg(DBG_MGMT_TIMER,
4054                          "%s:%d: starting mgmt_timer for %d ticks",
4055                          __func__, __LINE__, SCAN_POLL_INTERVAL);
4056                 schedule_delayed_work(&priv->dwork_get_scan,
4057                                       SCAN_POLL_INTERVAL);
4058         }
4059
4060 exit:
4061         mutex_unlock(&priv->mtx);
4062 }
4063
4064 /* Enable or disable promiscuous mode */
4065 static void at76_work_set_promisc(struct work_struct *work)
4066 {
4067         struct at76_priv *priv = container_of(work, struct at76_priv,
4068                                               work_set_promisc);
4069         int ret = 0;
4070
4071         mutex_lock(&priv->mtx);
4072
4073         priv->mib_buf.type = MIB_LOCAL;
4074         priv->mib_buf.size = 1;
4075         priv->mib_buf.index = offsetof(struct mib_local, promiscuous_mode);
4076         priv->mib_buf.data.byte = priv->promisc ? 1 : 0;
4077
4078         ret = at76_set_mib(priv, &priv->mib_buf);
4079         if (ret < 0)
4080                 printk(KERN_ERR "%s: set_mib (promiscuous_mode) failed: %d\n",
4081                        priv->netdev->name, ret);
4082
4083         mutex_unlock(&priv->mtx);
4084 }
4085
4086 /* Submit Rx urb back to the device */
4087 static void at76_work_submit_rx(struct work_struct *work)
4088 {
4089         struct at76_priv *priv = container_of(work, struct at76_priv,
4090                                               work_submit_rx);
4091
4092         mutex_lock(&priv->mtx);
4093         at76_submit_rx_urb(priv);
4094         mutex_unlock(&priv->mtx);
4095 }
4096
4097 /* We got an association response */
4098 static void at76_rx_mgmt_assoc(struct at76_priv *priv,
4099                                struct at76_rx_buffer *buf)
4100 {
4101         struct ieee80211_assoc_response *resp =
4102             (struct ieee80211_assoc_response *)buf->packet;
4103         u16 assoc_id = le16_to_cpu(resp->aid);
4104         u16 status = le16_to_cpu(resp->status);
4105
4106         at76_dbg(DBG_RX_MGMT, "%s: rx AssocResp bssid %s capa 0x%04x status "
4107                  "0x%04x assoc_id 0x%04x rates %s", priv->netdev->name,
4108                  mac2str(resp->header.addr3), le16_to_cpu(resp->capability),
4109                  status, assoc_id, hex2str(resp->info_element->data,
4110                                            resp->info_element->len));
4111
4112         if (priv->mac_state != MAC_ASSOC) {
4113                 printk(KERN_INFO "%s: AssocResp in state %s ignored\n",
4114                        priv->netdev->name, mac_states[priv->mac_state]);
4115                 return;
4116         }
4117
4118         BUG_ON(!priv->curr_bss);
4119
4120         cancel_delayed_work(&priv->dwork_assoc);
4121         if (status == WLAN_STATUS_SUCCESS) {
4122                 struct bss_info *ptr = priv->curr_bss;
4123                 priv->assoc_id = assoc_id & 0x3fff;
4124                 /* update iwconfig params */
4125                 memcpy(priv->bssid, ptr->bssid, ETH_ALEN);
4126                 memcpy(priv->essid, ptr->ssid, ptr->ssid_len);
4127                 priv->essid_size = ptr->ssid_len;
4128                 priv->channel = ptr->channel;
4129                 schedule_work(&priv->work_assoc_done);
4130         } else {
4131                 at76_set_mac_state(priv, MAC_JOINING);
4132                 schedule_work(&priv->work_join);
4133         }
4134 }
4135
4136 /* Process disassociation request from the AP */
4137 static void at76_rx_mgmt_disassoc(struct at76_priv *priv,
4138                                   struct at76_rx_buffer *buf)
4139 {
4140         struct ieee80211_disassoc *resp =
4141             (struct ieee80211_disassoc *)buf->packet;
4142         struct ieee80211_hdr_3addr *mgmt = &resp->header;
4143
4144         at76_dbg(DBG_RX_MGMT,
4145                  "%s: rx DisAssoc bssid %s reason 0x%04x destination %s",
4146                  priv->netdev->name, mac2str(mgmt->addr3),
4147                  le16_to_cpu(resp->reason), mac2str(mgmt->addr1));
4148
4149         /* We are not connected, ignore */
4150         if (priv->mac_state == MAC_SCANNING || priv->mac_state == MAC_INIT
4151             || !priv->curr_bss)
4152                 return;
4153
4154         /* Not our BSSID, ignore */
4155         if (compare_ether_addr(mgmt->addr3, priv->curr_bss->bssid))
4156                 return;
4157
4158         /* Not for our STA and not broadcast, ignore */
4159         if (compare_ether_addr(priv->netdev->dev_addr, mgmt->addr1)
4160             && !is_broadcast_ether_addr(mgmt->addr1))
4161                 return;
4162
4163         if (priv->mac_state != MAC_ASSOC && priv->mac_state != MAC_CONNECTED
4164             && priv->mac_state != MAC_JOINING) {
4165                 printk(KERN_INFO "%s: DisAssoc in state %s ignored\n",
4166                        priv->netdev->name, mac_states[priv->mac_state]);
4167                 return;
4168         }
4169
4170         if (priv->mac_state == MAC_CONNECTED) {
4171                 netif_carrier_off(priv->netdev);
4172                 netif_stop_queue(priv->netdev);
4173                 at76_iwevent_bss_disconnect(priv->netdev);
4174         }
4175         cancel_delayed_work(&priv->dwork_get_scan);
4176         cancel_delayed_work(&priv->dwork_beacon);
4177         cancel_delayed_work(&priv->dwork_auth);
4178         cancel_delayed_work(&priv->dwork_assoc);
4179         at76_set_mac_state(priv, MAC_JOINING);
4180         schedule_work(&priv->work_join);
4181 }
4182
4183 static void at76_rx_mgmt_auth(struct at76_priv *priv,
4184                               struct at76_rx_buffer *buf)
4185 {
4186         struct ieee80211_auth *resp = (struct ieee80211_auth *)buf->packet;
4187         struct ieee80211_hdr_3addr *mgmt = &resp->header;
4188         int seq_nr = le16_to_cpu(resp->transaction);
4189         int alg = le16_to_cpu(resp->algorithm);
4190         int status = le16_to_cpu(resp->status);
4191
4192         at76_dbg(DBG_RX_MGMT,
4193                  "%s: rx AuthFrame bssid %s alg %d seq_nr %d status %d "
4194                  "destination %s", priv->netdev->name, mac2str(mgmt->addr3),
4195                  alg, seq_nr, status, mac2str(mgmt->addr1));
4196
4197         if (alg == WLAN_AUTH_SHARED_KEY && seq_nr == 2)
4198                 at76_dbg(DBG_RX_MGMT, "%s: AuthFrame challenge %s ...",
4199                          priv->netdev->name, hex2str(resp->info_element, 18));
4200
4201         if (priv->mac_state != MAC_AUTH) {
4202                 printk(KERN_INFO "%s: ignored AuthFrame in state %s\n",
4203                        priv->netdev->name, mac_states[priv->mac_state]);
4204                 return;
4205         }
4206         if (priv->auth_mode != alg) {
4207                 printk(KERN_INFO "%s: ignored AuthFrame for alg %d\n",
4208                        priv->netdev->name, alg);
4209                 return;
4210         }
4211
4212         BUG_ON(!priv->curr_bss);
4213
4214         /* Not our BSSID or not for our STA, ignore */
4215         if (compare_ether_addr(mgmt->addr3, priv->curr_bss->bssid)
4216             || compare_ether_addr(priv->netdev->dev_addr, mgmt->addr1))
4217                 return;
4218
4219         cancel_delayed_work(&priv->dwork_auth);
4220         if (status != WLAN_STATUS_SUCCESS) {
4221                 /* try to join next bss */
4222                 at76_set_mac_state(priv, MAC_JOINING);
4223                 schedule_work(&priv->work_join);
4224                 return;
4225         }
4226
4227         if (priv->auth_mode == WLAN_AUTH_OPEN || seq_nr == 4) {
4228                 priv->retries = ASSOC_RETRIES;
4229                 at76_set_mac_state(priv, MAC_ASSOC);
4230                 at76_assoc_req(priv, priv->curr_bss);
4231                 at76_dbg(DBG_MGMT_TIMER,
4232                          "%s:%d: starting mgmt_timer + HZ", __func__, __LINE__);
4233                 schedule_delayed_work(&priv->dwork_assoc, ASSOC_TIMEOUT);
4234                 return;
4235         }
4236
4237         WARN_ON(seq_nr != 2);
4238         at76_auth_req(priv, priv->curr_bss, seq_nr + 1, resp->info_element);
4239         at76_dbg(DBG_MGMT_TIMER, "%s:%d: starting mgmt_timer + HZ", __func__,
4240                  __LINE__);
4241         schedule_delayed_work(&priv->dwork_auth, AUTH_TIMEOUT);
4242 }
4243
4244 static void at76_rx_mgmt_deauth(struct at76_priv *priv,
4245                                 struct at76_rx_buffer *buf)
4246 {
4247         struct ieee80211_disassoc *resp =
4248             (struct ieee80211_disassoc *)buf->packet;
4249         struct ieee80211_hdr_3addr *mgmt = &resp->header;
4250
4251         at76_dbg(DBG_RX_MGMT | DBG_PROGRESS,
4252                  "%s: rx DeAuth bssid %s reason 0x%04x destination %s",
4253                  priv->netdev->name, mac2str(mgmt->addr3),
4254                  le16_to_cpu(resp->reason), mac2str(mgmt->addr1));
4255
4256         if (priv->mac_state != MAC_AUTH && priv->mac_state != MAC_ASSOC
4257             && priv->mac_state != MAC_CONNECTED) {
4258                 printk(KERN_INFO "%s: DeAuth in state %s ignored\n",
4259                        priv->netdev->name, mac_states[priv->mac_state]);
4260                 return;
4261         }
4262
4263         BUG_ON(!priv->curr_bss);
4264
4265         /* Not our BSSID, ignore */
4266         if (compare_ether_addr(mgmt->addr3, priv->curr_bss->bssid))
4267                 return;
4268
4269         /* Not for our STA and not broadcast, ignore */
4270         if (compare_ether_addr(priv->netdev->dev_addr, mgmt->addr1)
4271             && !is_broadcast_ether_addr(mgmt->addr1))
4272                 return;
4273
4274         if (priv->mac_state == MAC_CONNECTED)
4275                 at76_iwevent_bss_disconnect(priv->netdev);
4276
4277         at76_set_mac_state(priv, MAC_JOINING);
4278         schedule_work(&priv->work_join);
4279         cancel_delayed_work(&priv->dwork_get_scan);
4280         cancel_delayed_work(&priv->dwork_beacon);
4281         cancel_delayed_work(&priv->dwork_auth);
4282         cancel_delayed_work(&priv->dwork_assoc);
4283 }
4284
4285 static void at76_rx_mgmt_beacon(struct at76_priv *priv,
4286                                 struct at76_rx_buffer *buf)
4287 {
4288         int varpar_len;
4289         /* beacon content */
4290         struct ieee80211_beacon *bdata = (struct ieee80211_beacon *)buf->packet;
4291         struct ieee80211_hdr_3addr *mgmt = &bdata->header;
4292
4293         struct list_head *lptr;
4294         struct bss_info *match; /* entry matching addr3 with its bssid */
4295         int new_entry = 0;
4296         int len;
4297         struct ieee80211_info_element *ie;
4298         int have_ssid = 0;
4299         int have_rates = 0;
4300         int have_channel = 0;
4301         int keep_going = 1;
4302         unsigned long flags;
4303
4304         spin_lock_irqsave(&priv->bss_list_spinlock, flags);
4305         if (priv->mac_state == MAC_CONNECTED) {
4306                 /* in state MAC_CONNECTED we use the mgmt_timer to control
4307                    the beacon of the BSS */
4308                 BUG_ON(!priv->curr_bss);
4309
4310                 if (!compare_ether_addr(priv->curr_bss->bssid, mgmt->addr3)) {
4311                         /* We got our AP's beacon, defer the timeout handler.
4312                            Kill pending work first, as schedule_delayed_work()
4313                            won't do it. */
4314                         cancel_delayed_work(&priv->dwork_beacon);
4315                         schedule_delayed_work(&priv->dwork_beacon,
4316                                               BEACON_TIMEOUT);
4317                         priv->curr_bss->rssi = buf->rssi;
4318                         priv->beacons_received++;
4319                         goto exit;
4320                 }
4321         }
4322
4323         /* look if we have this BSS already in the list */
4324         match = NULL;
4325
4326         if (!list_empty(&priv->bss_list)) {
4327                 list_for_each(lptr, &priv->bss_list) {
4328                         struct bss_info *bss_ptr =
4329                             list_entry(lptr, struct bss_info, list);
4330                         if (!compare_ether_addr(bss_ptr->bssid, mgmt->addr3)) {
4331                                 match = bss_ptr;
4332                                 break;
4333                         }
4334                 }
4335         }
4336
4337         if (!match) {
4338                 /* BSS not in the list - append it */
4339                 match = kzalloc(sizeof(struct bss_info), GFP_ATOMIC);
4340                 if (!match) {
4341                         at76_dbg(DBG_BSS_TABLE,
4342                                  "%s: cannot kmalloc new bss info (%zd byte)",
4343                                  priv->netdev->name, sizeof(struct bss_info));
4344                         goto exit;
4345                 }
4346                 new_entry = 1;
4347                 list_add_tail(&match->list, &priv->bss_list);
4348         }
4349
4350         match->capa = le16_to_cpu(bdata->capability);
4351         match->beacon_interval = le16_to_cpu(bdata->beacon_interval);
4352         match->rssi = buf->rssi;
4353         match->link_qual = buf->link_quality;
4354         match->noise_level = buf->noise_level;
4355         memcpy(match->bssid, mgmt->addr3, ETH_ALEN);
4356         at76_dbg(DBG_RX_BEACON, "%s: bssid %s", priv->netdev->name,
4357                  mac2str(match->bssid));
4358
4359         ie = bdata->info_element;
4360
4361         /* length of var length beacon parameters */
4362         varpar_len = min_t(int, le16_to_cpu(buf->wlength) -
4363                            sizeof(struct ieee80211_beacon),
4364                            BEACON_MAX_DATA_LENGTH);
4365
4366         /* This routine steps through the bdata->data array to get
4367          * some useful information about the access point.
4368          * Currently, this implementation supports receipt of: SSID,
4369          * supported transfer rates and channel, in any order, with some
4370          * tolerance for intermittent unknown codes (although this
4371          * functionality may not be necessary as the useful information will
4372          * usually arrive in consecutively, but there have been some
4373          * reports of some of the useful information fields arriving in a
4374          * different order).
4375          * It does not support any more IE types although MFIE_TYPE_TIM may
4376          * be supported (on my AP at least).
4377          * The bdata->data array is about 1500 bytes long but only ~36 of those
4378          * bytes are useful, hence the have_ssid etc optimizations. */
4379
4380         while (keep_going &&
4381                ((&ie->data[ie->len] - (u8 *)bdata->info_element) <=
4382                 varpar_len)) {
4383
4384                 switch (ie->id) {
4385
4386                 case MFIE_TYPE_SSID:
4387                         if (have_ssid)
4388                                 break;
4389
4390                         len = min_t(int, IW_ESSID_MAX_SIZE, ie->len);
4391
4392                         /* we copy only if this is a new entry,
4393                            or the incoming SSID is not a hidden SSID. This
4394                            will protect us from overwriting a real SSID read
4395                            in a ProbeResponse with a hidden one from a
4396                            following beacon. */
4397                         if (!new_entry && at76_is_hidden_ssid(ie->data, len)) {
4398                                 have_ssid = 1;
4399                                 break;
4400                         }
4401
4402                         match->ssid_len = len;
4403                         memcpy(match->ssid, ie->data, len);
4404                         at76_dbg(DBG_RX_BEACON, "%s: SSID - %.*s",
4405                                  priv->netdev->name, len, match->ssid);
4406                         have_ssid = 1;
4407                         break;
4408
4409                 case MFIE_TYPE_RATES:
4410                         if (have_rates)
4411                                 break;
4412
4413                         match->rates_len =
4414                             min_t(int, sizeof(match->rates), ie->len);
4415                         memcpy(match->rates, ie->data, match->rates_len);
4416                         have_rates = 1;
4417                         at76_dbg(DBG_RX_BEACON, "%s: SUPPORTED RATES %s",
4418                                  priv->netdev->name,
4419                                  hex2str(ie->data, ie->len));
4420                         break;
4421
4422                 case MFIE_TYPE_DS_SET:
4423                         if (have_channel)
4424                                 break;
4425
4426                         match->channel = ie->data[0];
4427                         have_channel = 1;
4428                         at76_dbg(DBG_RX_BEACON, "%s: CHANNEL - %d",
4429                                  priv->netdev->name, match->channel);
4430                         break;
4431
4432                 case MFIE_TYPE_CF_SET:
4433                 case MFIE_TYPE_TIM:
4434                 case MFIE_TYPE_IBSS_SET:
4435                 default:
4436                         at76_dbg(DBG_RX_BEACON, "%s: beacon IE id %d len %d %s",
4437                                  priv->netdev->name, ie->id, ie->len,
4438                                  hex2str(ie->data, ie->len));
4439                         break;
4440                 }
4441
4442                 /* advance to the next informational element */
4443                 next_ie(&ie);
4444
4445                 /* Optimization: after all, the bdata->data array is
4446                  * varpar_len bytes long, whereas we get all of the useful
4447                  * information after only ~36 bytes, this saves us a lot of
4448                  * time (and trouble as the remaining portion of the array
4449                  * could be full of junk)
4450                  * Comment this out if you want to see what other information
4451                  * comes from the AP - although little of it may be useful */
4452         }
4453
4454         at76_dbg(DBG_RX_BEACON, "%s: Finished processing beacon data",
4455                  priv->netdev->name);
4456
4457         match->last_rx = jiffies;       /* record last rx of beacon */
4458
4459 exit:
4460         spin_unlock_irqrestore(&priv->bss_list_spinlock, flags);
4461 }
4462
4463 /* Calculate the link level from a given rx_buffer */
4464 static void at76_calc_level(struct at76_priv *priv, struct at76_rx_buffer *buf,
4465                             struct iw_quality *qual)
4466 {
4467         /* just a guess for now, might be different for other chips */
4468         int max_rssi = 42;
4469
4470         qual->level = (buf->rssi * 100 / max_rssi);
4471         if (qual->level > 100)
4472                 qual->level = 100;
4473         qual->updated |= IW_QUAL_LEVEL_UPDATED;
4474 }
4475
4476 /* Calculate the link quality from a given rx_buffer */
4477 static void at76_calc_qual(struct at76_priv *priv, struct at76_rx_buffer *buf,
4478                            struct iw_quality *qual)
4479 {
4480         if (at76_is_intersil(priv->board_type))
4481                 qual->qual = buf->link_quality;
4482         else {
4483                 unsigned long elapsed;
4484
4485                 /* Update qual at most once a second */
4486                 elapsed = jiffies - priv->beacons_last_qual;
4487                 if (elapsed < 1 * HZ)
4488                         return;
4489
4490                 qual->qual = qual->level * priv->beacons_received *
4491                     msecs_to_jiffies(priv->beacon_period) / elapsed;
4492
4493                 priv->beacons_last_qual = jiffies;
4494                 priv->beacons_received = 0;
4495         }
4496         qual->qual = (qual->qual > 100) ? 100 : qual->qual;
4497         qual->updated |= IW_QUAL_QUAL_UPDATED;
4498 }
4499
4500 /* Calculate the noise quality from a given rx_buffer */
4501 static void at76_calc_noise(struct at76_priv *priv, struct at76_rx_buffer *buf,
4502                             struct iw_quality *qual)
4503 {
4504         qual->noise = 0;
4505         qual->updated |= IW_QUAL_NOISE_INVALID;
4506 }
4507
4508 static void at76_update_wstats(struct at76_priv *priv,
4509                                struct at76_rx_buffer *buf)
4510 {
4511         struct iw_quality *qual = &priv->wstats.qual;
4512
4513         if (buf->rssi && priv->mac_state == MAC_CONNECTED) {
4514                 qual->updated = 0;
4515                 at76_calc_level(priv, buf, qual);
4516                 at76_calc_qual(priv, buf, qual);
4517                 at76_calc_noise(priv, buf, qual);
4518         } else {
4519                 qual->qual = 0;
4520                 qual->level = 0;
4521                 qual->noise = 0;
4522                 qual->updated = IW_QUAL_ALL_INVALID;
4523         }
4524 }
4525
4526 static void at76_rx_mgmt(struct at76_priv *priv, struct at76_rx_buffer *buf)
4527 {
4528         struct ieee80211_hdr_3addr *mgmt =
4529             (struct ieee80211_hdr_3addr *)buf->packet;
4530         u16 framectl = le16_to_cpu(mgmt->frame_ctl);
4531
4532         /* update wstats */
4533         if (priv->mac_state != MAC_INIT && priv->mac_state != MAC_SCANNING) {
4534                 /* jal: this is a dirty hack needed by Tim in ad-hoc mode */
4535                 /* Data packets always seem to have a 0 link level, so we
4536                    only read link quality info from management packets.
4537                    Atmel driver actually averages the present, and previous
4538                    values, we just present the raw value at the moment - TJS */
4539                 if (priv->iw_mode == IW_MODE_ADHOC
4540                     || (priv->curr_bss
4541                         && !compare_ether_addr(mgmt->addr3,
4542                                                priv->curr_bss->bssid)))
4543                         at76_update_wstats(priv, buf);
4544         }
4545
4546         at76_dbg(DBG_RX_MGMT_CONTENT, "%s rx mgmt framectl 0x%x %s",
4547                  priv->netdev->name, framectl,
4548                  hex2str(mgmt, le16_to_cpu(buf->wlength)));
4549
4550         switch (framectl & IEEE80211_FCTL_STYPE) {
4551         case IEEE80211_STYPE_BEACON:
4552         case IEEE80211_STYPE_PROBE_RESP:
4553                 at76_rx_mgmt_beacon(priv, buf);
4554                 break;
4555
4556         case IEEE80211_STYPE_ASSOC_RESP:
4557                 at76_rx_mgmt_assoc(priv, buf);
4558                 break;
4559
4560         case IEEE80211_STYPE_DISASSOC:
4561                 at76_rx_mgmt_disassoc(priv, buf);
4562                 break;
4563
4564         case IEEE80211_STYPE_AUTH:
4565                 at76_rx_mgmt_auth(priv, buf);
4566                 break;
4567
4568         case IEEE80211_STYPE_DEAUTH:
4569                 at76_rx_mgmt_deauth(priv, buf);
4570                 break;
4571
4572         default:
4573                 printk(KERN_DEBUG "%s: ignoring frame with framectl 0x%04x\n",
4574                        priv->netdev->name, framectl);
4575         }
4576
4577         return;
4578 }
4579
4580 /* Convert the 802.11 header into an ethernet-style header, make skb
4581  * ready for consumption by netif_rx() */
4582 static void at76_ieee80211_to_eth(struct sk_buff *skb, int iw_mode)
4583 {
4584         struct ieee80211_hdr_3addr *i802_11_hdr;
4585         struct ethhdr *eth_hdr_p;
4586         u8 *src_addr;
4587         u8 *dest_addr;
4588
4589         i802_11_hdr = (struct ieee80211_hdr_3addr *)skb->data;
4590
4591         /* That would be the ethernet header if the hardware converted
4592          * the frame for us.  Make sure the source and the destination
4593          * match the 802.11 header.  Which hardware does it? */
4594         eth_hdr_p = (struct ethhdr *)skb_pull(skb, IEEE80211_3ADDR_LEN);
4595
4596         dest_addr = i802_11_hdr->addr1;
4597         if (iw_mode == IW_MODE_ADHOC)
4598                 src_addr = i802_11_hdr->addr2;
4599         else
4600                 src_addr = i802_11_hdr->addr3;
4601
4602         if (!compare_ether_addr(eth_hdr_p->h_source, src_addr) &&
4603             !compare_ether_addr(eth_hdr_p->h_dest, dest_addr))
4604                 /* Yes, we already have an ethernet header */
4605                 skb_reset_mac_header(skb);
4606         else {
4607                 u16 len;
4608
4609                 /* Need to build an ethernet header */
4610                 if (!memcmp(skb->data, snapsig, sizeof(snapsig))) {
4611                         /* SNAP frame - decapsulate, keep proto */
4612                         skb_push(skb, offsetof(struct ethhdr, h_proto) -
4613                                  sizeof(rfc1042sig));
4614                         len = 0;
4615                 } else {
4616                         /* 802.3 frame, proto is length */
4617                         len = skb->len;
4618                         skb_push(skb, ETH_HLEN);
4619                 }
4620
4621                 skb_reset_mac_header(skb);
4622                 eth_hdr_p = eth_hdr(skb);
4623                 /* This needs to be done in this order (eth_hdr_p->h_dest may
4624                  * overlap src_addr) */
4625                 memcpy(eth_hdr_p->h_source, src_addr, ETH_ALEN);
4626                 memcpy(eth_hdr_p->h_dest, dest_addr, ETH_ALEN);
4627                 if (len)
4628                         eth_hdr_p->h_proto = htons(len);
4629         }
4630
4631         skb->protocol = eth_type_trans(skb, skb->dev);
4632 }
4633
4634 /* Check for fragmented data in priv->rx_skb. If the packet was no fragment
4635    or it was the last of a fragment set a skb containing the whole packet
4636    is returned for further processing. Otherwise we get NULL and are
4637    done and the packet is either stored inside the fragment buffer
4638    or thrown away.  Every returned skb starts with the ieee802_11 header
4639    and contains _no_ FCS at the end */
4640 static struct sk_buff *at76_check_for_rx_frags(struct at76_priv *priv)
4641 {
4642         struct sk_buff *skb = priv->rx_skb;
4643         struct at76_rx_buffer *buf = (struct at76_rx_buffer *)skb->data;
4644         struct ieee80211_hdr_3addr *i802_11_hdr =
4645             (struct ieee80211_hdr_3addr *)buf->packet;
4646         /* seq_ctrl, fragment_number, sequence number of new packet */
4647         u16 sctl = le16_to_cpu(i802_11_hdr->seq_ctl);
4648         u16 fragnr = sctl & 0xf;
4649         u16 seqnr = sctl >> 4;
4650         u16 frame_ctl = le16_to_cpu(i802_11_hdr->frame_ctl);
4651
4652         /* Length including the IEEE802.11 header, but without the trailing
4653          * FCS and without the Atmel Rx header */
4654         int length = le16_to_cpu(buf->wlength) - IEEE80211_FCS_LEN;
4655
4656         /* where does the data payload start in skb->data ? */
4657         u8 *data = i802_11_hdr->payload;
4658
4659         /* length of payload, excl. the trailing FCS */
4660         int data_len = length - IEEE80211_3ADDR_LEN;
4661
4662         int i;
4663         struct rx_data_buf *bptr, *optr;
4664         unsigned long oldest = ~0UL;
4665
4666         at76_dbg(DBG_RX_FRAGS,
4667                  "%s: rx data frame_ctl %04x addr2 %s seq/frag %d/%d "
4668                  "length %d data %d: %s ...", priv->netdev->name, frame_ctl,
4669                  mac2str(i802_11_hdr->addr2), seqnr, fragnr, length, data_len,
4670                  hex2str(data, 32));
4671
4672         at76_dbg(DBG_RX_FRAGS_SKB, "%s: incoming skb: head %p data %p "
4673                  "tail %p end %p len %d", priv->netdev->name, skb->head,
4674                  skb->data, skb_tail_pointer(skb), skb_end_pointer(skb),
4675                  skb->len);
4676
4677         if (data_len < 0) {
4678                 /* make sure data starts in the buffer */
4679                 printk(KERN_INFO "%s: data frame too short\n",
4680                        priv->netdev->name);
4681                 return NULL;
4682         }
4683
4684         WARN_ON(length <= AT76_RX_HDRLEN);
4685         if (length <= AT76_RX_HDRLEN)
4686                 return NULL;
4687
4688         /* remove the at76_rx_buffer header - we don't need it anymore */
4689         /* we need the IEEE802.11 header (for the addresses) if this packet
4690            is the first of a chain */
4691         skb_pull(skb, AT76_RX_HDRLEN);
4692
4693         /* remove FCS at end */
4694         skb_trim(skb, length);
4695
4696         at76_dbg(DBG_RX_FRAGS_SKB, "%s: trimmed skb: head %p data %p tail %p "
4697                  "end %p len %d data %p data_len %d", priv->netdev->name,
4698                  skb->head, skb->data, skb_tail_pointer(skb),
4699                  skb_end_pointer(skb), skb->len, data, data_len);
4700
4701         if (fragnr == 0 && !(frame_ctl & IEEE80211_FCTL_MOREFRAGS)) {
4702                 /* unfragmented packet received */
4703                 /* Use a new skb for the next receive */
4704                 priv->rx_skb = NULL;
4705                 at76_dbg(DBG_RX_FRAGS, "%s: unfragmented", priv->netdev->name);
4706                 return skb;
4707         }
4708
4709         /* look if we've got a chain for the sender address.
4710            afterwards optr points to first free or the oldest entry,
4711            or, if i < NR_RX_DATA_BUF, bptr points to the entry for the
4712            sender address */
4713         /* determining the oldest entry doesn't cope with jiffies wrapping
4714            but I don't care to delete a young entry at these rare moments ... */
4715
4716         bptr = priv->rx_data;
4717         optr = NULL;
4718         for (i = 0; i < NR_RX_DATA_BUF; i++, bptr++) {
4719                 if (!bptr->skb) {
4720                         optr = bptr;
4721                         oldest = 0UL;
4722                         continue;
4723                 }
4724
4725                 if (!compare_ether_addr(i802_11_hdr->addr2, bptr->sender))
4726                         break;
4727
4728                 if (!optr) {
4729                         optr = bptr;
4730                         oldest = bptr->last_rx;
4731                 } else if (bptr->last_rx < oldest)
4732                         optr = bptr;
4733         }
4734
4735         if (i < NR_RX_DATA_BUF) {
4736
4737                 at76_dbg(DBG_RX_FRAGS, "%s: %d. cacheentry (seq/frag = %d/%d) "
4738                          "matched sender addr",
4739                          priv->netdev->name, i, bptr->seqnr, bptr->fragnr);
4740
4741                 /* bptr points to an entry for the sender address */
4742                 if (bptr->seqnr == seqnr) {
4743                         int left;
4744                         /* the fragment has the current sequence number */
4745                         if (((bptr->fragnr + 1) & 0xf) != fragnr) {
4746                                 /* wrong fragment number -> ignore it */
4747                                 /* is & 0xf necessary above ??? */
4748                                 at76_dbg(DBG_RX_FRAGS,
4749                                          "%s: frag nr mismatch: %d + 1 != %d",
4750                                          priv->netdev->name, bptr->fragnr,
4751                                          fragnr);
4752                                 return NULL;
4753                         }
4754                         bptr->last_rx = jiffies;
4755                         /* the next following fragment number ->
4756                            add the data at the end */
4757
4758                         /* for test only ??? */
4759                         left = skb_tailroom(bptr->skb);
4760                         if (left < data_len)
4761                                 printk(KERN_INFO
4762                                        "%s: only %d byte free (need %d)\n",
4763                                        priv->netdev->name, left, data_len);
4764                         else
4765                                 memcpy(skb_put(bptr->skb, data_len), data,
4766                                        data_len);
4767
4768                         bptr->fragnr = fragnr;
4769                         if (frame_ctl & IEEE80211_FCTL_MOREFRAGS)
4770                                 return NULL;
4771
4772                         /* this was the last fragment - send it */
4773                         skb = bptr->skb;
4774                         bptr->skb = NULL;       /* free the entry */
4775                         at76_dbg(DBG_RX_FRAGS, "%s: last frag of seq %d",
4776                                  priv->netdev->name, seqnr);
4777                         return skb;
4778                 }
4779
4780                 /* got another sequence number */
4781                 if (fragnr == 0) {
4782                         /* it's the start of a new chain - replace the
4783                            old one by this */
4784                         /* bptr->sender has the correct value already */
4785                         at76_dbg(DBG_RX_FRAGS,
4786                                  "%s: start of new seq %d, removing old seq %d",
4787                                  priv->netdev->name, seqnr, bptr->seqnr);
4788                         bptr->seqnr = seqnr;
4789                         bptr->fragnr = 0;
4790                         bptr->last_rx = jiffies;
4791                         /* swap bptr->skb and priv->rx_skb */
4792                         skb = bptr->skb;
4793                         bptr->skb = priv->rx_skb;
4794                         priv->rx_skb = skb;
4795                 } else {
4796                         /* it from the middle of a new chain ->
4797                            delete the old entry and skip the new one */
4798                         at76_dbg(DBG_RX_FRAGS,
4799                                  "%s: middle of new seq %d (%d) "
4800                                  "removing old seq %d",
4801                                  priv->netdev->name, seqnr, fragnr,
4802                                  bptr->seqnr);
4803                         dev_kfree_skb(bptr->skb);
4804                         bptr->skb = NULL;
4805                 }
4806                 return NULL;
4807         }
4808
4809         /* if we didn't find a chain for the sender address, optr
4810            points either to the first free or the oldest entry */
4811
4812         if (fragnr != 0) {
4813                 /* this is not the begin of a fragment chain ... */
4814                 at76_dbg(DBG_RX_FRAGS,
4815                          "%s: no chain for non-first fragment (%d)",
4816                          priv->netdev->name, fragnr);
4817                 return NULL;
4818         }
4819
4820         BUG_ON(!optr);
4821         if (optr->skb) {
4822                 /* swap the skb's */
4823                 skb = optr->skb;
4824                 optr->skb = priv->rx_skb;
4825                 priv->rx_skb = skb;
4826
4827                 at76_dbg(DBG_RX_FRAGS,
4828                          "%s: free old contents: sender %s seq/frag %d/%d",
4829                          priv->netdev->name, mac2str(optr->sender),
4830                          optr->seqnr, optr->fragnr);
4831
4832         } else {
4833                 /* take the skb from priv->rx_skb */
4834                 optr->skb = priv->rx_skb;
4835                 /* let at76_submit_rx_urb() allocate a new skb */
4836                 priv->rx_skb = NULL;
4837
4838                 at76_dbg(DBG_RX_FRAGS, "%s: use a free entry",
4839                          priv->netdev->name);
4840         }
4841         memcpy(optr->sender, i802_11_hdr->addr2, ETH_ALEN);
4842         optr->seqnr = seqnr;
4843         optr->fragnr = 0;
4844         optr->last_rx = jiffies;
4845
4846         return NULL;
4847 }
4848
4849 /* Rx interrupt: we expect the complete data buffer in priv->rx_skb */
4850 static void at76_rx_data(struct at76_priv *priv)
4851 {
4852         struct net_device *netdev = priv->netdev;
4853         struct net_device_stats *stats = &priv->stats;
4854         struct sk_buff *skb = priv->rx_skb;
4855         struct at76_rx_buffer *buf = (struct at76_rx_buffer *)skb->data;
4856         struct ieee80211_hdr_3addr *i802_11_hdr;
4857         int length = le16_to_cpu(buf->wlength);
4858
4859         at76_dbg(DBG_RX_DATA, "%s received data packet: %s", netdev->name,
4860                  hex2str(skb->data, AT76_RX_HDRLEN));
4861
4862         at76_dbg(DBG_RX_DATA_CONTENT, "rx packet: %s",
4863                  hex2str(skb->data + AT76_RX_HDRLEN, length));
4864
4865         skb = at76_check_for_rx_frags(priv);
4866         if (!skb)
4867                 return;
4868
4869         /* Atmel header and the FCS are already removed */
4870         i802_11_hdr = (struct ieee80211_hdr_3addr *)skb->data;
4871
4872         skb->dev = netdev;
4873         skb->ip_summed = CHECKSUM_NONE; /* TODO: should check CRC */
4874
4875         if (is_broadcast_ether_addr(i802_11_hdr->addr1)) {
4876                 if (!compare_ether_addr(i802_11_hdr->addr1, netdev->broadcast))
4877                         skb->pkt_type = PACKET_BROADCAST;
4878                 else
4879                         skb->pkt_type = PACKET_MULTICAST;
4880         } else if (compare_ether_addr(i802_11_hdr->addr1, netdev->dev_addr))
4881                 skb->pkt_type = PACKET_OTHERHOST;
4882
4883         at76_ieee80211_to_eth(skb, priv->iw_mode);
4884
4885         netdev->last_rx = jiffies;
4886         netif_rx(skb);
4887         stats->rx_packets++;
4888         stats->rx_bytes += length;
4889
4890         return;
4891 }
4892
4893 static void at76_rx_monitor_mode(struct at76_priv *priv)
4894 {
4895         struct at76_rx_radiotap *rt;
4896         u8 *payload;
4897         int skblen;
4898         struct net_device *netdev = priv->netdev;
4899         struct at76_rx_buffer *buf =
4900             (struct at76_rx_buffer *)priv->rx_skb->data;
4901         /* length including the IEEE802.11 header and the trailing FCS,
4902            but not at76_rx_buffer */
4903         int length = le16_to_cpu(buf->wlength);
4904         struct sk_buff *skb = priv->rx_skb;
4905         struct net_device_stats *stats = &priv->stats;
4906
4907         if (length < IEEE80211_FCS_LEN) {
4908                 /* buffer contains no data */
4909                 at76_dbg(DBG_MONITOR_MODE,
4910                          "%s: MONITOR MODE: rx skb without data",
4911                          priv->netdev->name);
4912                 return;
4913         }
4914
4915         skblen = sizeof(struct at76_rx_radiotap) + length;
4916
4917         skb = dev_alloc_skb(skblen);
4918         if (!skb) {
4919                 printk(KERN_ERR "%s: MONITOR MODE: dev_alloc_skb for radiotap "
4920                        "header returned NULL\n", priv->netdev->name);
4921                 return;
4922         }
4923
4924         skb_put(skb, skblen);
4925
4926         rt = (struct at76_rx_radiotap *)skb->data;
4927         payload = skb->data + sizeof(struct at76_rx_radiotap);
4928
4929         rt->rt_hdr.it_version = 0;
4930         rt->rt_hdr.it_pad = 0;
4931         rt->rt_hdr.it_len = cpu_to_le16(sizeof(struct at76_rx_radiotap));
4932         rt->rt_hdr.it_present = cpu_to_le32(AT76_RX_RADIOTAP_PRESENT);
4933
4934         rt->rt_tsft = cpu_to_le64(le32_to_cpu(buf->rx_time));
4935         rt->rt_rate = hw_rates[buf->rx_rate] & (~0x80);
4936         rt->rt_signal = buf->rssi;
4937         rt->rt_noise = buf->noise_level;
4938         rt->rt_flags = IEEE80211_RADIOTAP_F_FCS;
4939         if (buf->fragmentation)
4940                 rt->rt_flags |= IEEE80211_RADIOTAP_F_FRAG;
4941
4942         memcpy(payload, buf->packet, length);
4943         skb->dev = netdev;
4944         skb->ip_summed = CHECKSUM_NONE;
4945         skb_reset_mac_header(skb);
4946         skb->pkt_type = PACKET_OTHERHOST;
4947         skb->protocol = htons(ETH_P_802_2);
4948
4949         netdev->last_rx = jiffies;
4950         netif_rx(skb);
4951         stats->rx_packets++;
4952         stats->rx_bytes += length;
4953 }
4954
4955 /* Check if we spy on the sender address in buf and update stats */
4956 static void at76_iwspy_update(struct at76_priv *priv,
4957                               struct at76_rx_buffer *buf)
4958 {
4959         struct ieee80211_hdr_3addr *hdr =
4960             (struct ieee80211_hdr_3addr *)buf->packet;
4961         struct iw_quality qual;
4962
4963         /* We can only set the level here */
4964         qual.updated = IW_QUAL_QUAL_INVALID | IW_QUAL_NOISE_INVALID;
4965         qual.level = 0;
4966         qual.noise = 0;
4967         at76_calc_level(priv, buf, &qual);
4968
4969         spin_lock_bh(&priv->spy_spinlock);
4970
4971         if (priv->spy_data.spy_number > 0)
4972                 wireless_spy_update(priv->netdev, hdr->addr2, &qual);
4973
4974         spin_unlock_bh(&priv->spy_spinlock);
4975 }
4976
4977 static void at76_rx_tasklet(unsigned long param)
4978 {
4979         struct urb *urb = (struct urb *)param;
4980         struct at76_priv *priv = urb->context;
4981         struct net_device *netdev = priv->netdev;
4982         struct at76_rx_buffer *buf;
4983         struct ieee80211_hdr_3addr *i802_11_hdr;
4984         u16 frame_ctl;
4985
4986         if (priv->device_unplugged) {
4987                 at76_dbg(DBG_DEVSTART, "device unplugged");
4988                 if (urb)
4989                         at76_dbg(DBG_DEVSTART, "urb status %d", urb->status);
4990                 return;
4991         }
4992
4993         if (!priv->rx_skb || !netdev || !priv->rx_skb->data)
4994                 return;
4995
4996         buf = (struct at76_rx_buffer *)priv->rx_skb->data;
4997
4998         i802_11_hdr = (struct ieee80211_hdr_3addr *)buf->packet;
4999
5000         frame_ctl = le16_to_cpu(i802_11_hdr->frame_ctl);
5001
5002         if (urb->status != 0) {
5003                 if (urb->status != -ENOENT && urb->status != -ECONNRESET)
5004                         at76_dbg(DBG_URB,
5005                                  "%s %s: - nonzero Rx bulk status received: %d",
5006                                  __func__, netdev->name, urb->status);
5007                 return;
5008         }
5009
5010         at76_dbg(DBG_RX_ATMEL_HDR,
5011                  "%s: rx frame: rate %d rssi %d noise %d link %d %s",
5012                  priv->netdev->name, buf->rx_rate, buf->rssi, buf->noise_level,
5013                  buf->link_quality, hex2str(i802_11_hdr, 48));
5014         if (priv->iw_mode == IW_MODE_MONITOR) {
5015                 at76_rx_monitor_mode(priv);
5016                 goto exit;
5017         }
5018
5019         /* there is a new bssid around, accept it: */
5020         if (buf->newbss && priv->iw_mode == IW_MODE_ADHOC) {
5021                 at76_dbg(DBG_PROGRESS, "%s: rx newbss", netdev->name);
5022                 schedule_work(&priv->work_new_bss);
5023         }
5024
5025         switch (frame_ctl & IEEE80211_FCTL_FTYPE) {
5026         case IEEE80211_FTYPE_DATA:
5027                 at76_rx_data(priv);
5028                 break;
5029
5030         case IEEE80211_FTYPE_MGMT:
5031                 /* jal: TODO: find out if we can update iwspy also on
5032                    other frames than management (might depend on the
5033                    radio chip / firmware version !) */
5034
5035                 at76_iwspy_update(priv, buf);
5036
5037                 at76_rx_mgmt(priv, buf);
5038                 break;
5039
5040         case IEEE80211_FTYPE_CTL:
5041                 at76_dbg(DBG_RX_CTRL, "%s: ignored ctrl frame: %04x",
5042                          priv->netdev->name, frame_ctl);
5043                 break;
5044
5045         default:
5046                 printk(KERN_DEBUG "%s: ignoring frame with framectl 0x%04x\n",
5047                        priv->netdev->name, frame_ctl);
5048         }
5049 exit:
5050         at76_submit_rx_urb(priv);
5051 }
5052
5053 /* Load firmware into kernel memory and parse it */
5054 static struct fwentry *at76_load_firmware(struct usb_device *udev,
5055                                           enum board_type board_type)
5056 {
5057         int ret;
5058         char *str;
5059         struct at76_fw_header *fwh;
5060         struct fwentry *fwe = &firmwares[board_type];
5061
5062         mutex_lock(&fw_mutex);
5063
5064         if (fwe->loaded) {
5065                 at76_dbg(DBG_FW, "re-using previously loaded fw");
5066                 goto exit;
5067         }
5068
5069         at76_dbg(DBG_FW, "downloading firmware %s", fwe->fwname);
5070         ret = request_firmware(&fwe->fw, fwe->fwname, &udev->dev);
5071         if (ret < 0) {
5072                 dev_printk(KERN_ERR, &udev->dev, "firmware %s not found!\n",
5073                            fwe->fwname);
5074                 dev_printk(KERN_ERR, &udev->dev,
5075                            "you may need to download the firmware from "
5076                            "http://developer.berlios.de/projects/at76c503a/");
5077                 goto exit;
5078         }
5079
5080         at76_dbg(DBG_FW, "got it.");
5081         fwh = (struct at76_fw_header *)(fwe->fw->data);
5082
5083         if (fwe->fw->size <= sizeof(*fwh)) {
5084                 dev_printk(KERN_ERR, &udev->dev,
5085                            "firmware is too short (0x%zx)\n", fwe->fw->size);
5086                 goto exit;
5087         }
5088
5089         /* CRC currently not checked */
5090         fwe->board_type = le32_to_cpu(fwh->board_type);
5091         if (fwe->board_type != board_type) {
5092                 dev_printk(KERN_ERR, &udev->dev,
5093                            "board type mismatch, requested %u, got %u\n",
5094                            board_type, fwe->board_type);
5095                 goto exit;
5096         }
5097
5098         fwe->fw_version.major = fwh->major;
5099         fwe->fw_version.minor = fwh->minor;
5100         fwe->fw_version.patch = fwh->patch;
5101         fwe->fw_version.build = fwh->build;
5102
5103         str = (char *)fwh + le32_to_cpu(fwh->str_offset);
5104         fwe->intfw = (u8 *)fwh + le32_to_cpu(fwh->int_fw_offset);
5105         fwe->intfw_size = le32_to_cpu(fwh->int_fw_len);
5106         fwe->extfw = (u8 *)fwh + le32_to_cpu(fwh->ext_fw_offset);
5107         fwe->extfw_size = le32_to_cpu(fwh->ext_fw_len);
5108
5109         fwe->loaded = 1;
5110
5111         dev_printk(KERN_DEBUG, &udev->dev,
5112                    "using firmware %s (version %d.%d.%d-%d)\n",
5113                    fwe->fwname, fwh->major, fwh->minor, fwh->patch, fwh->build);
5114
5115         at76_dbg(DBG_DEVSTART, "board %u, int %d:%d, ext %d:%d", board_type,
5116                  le32_to_cpu(fwh->int_fw_offset), le32_to_cpu(fwh->int_fw_len),
5117                  le32_to_cpu(fwh->ext_fw_offset), le32_to_cpu(fwh->ext_fw_len));
5118         at76_dbg(DBG_DEVSTART, "firmware id %s", str);
5119
5120 exit:
5121         mutex_unlock(&fw_mutex);
5122
5123         if (fwe->loaded)
5124                 return fwe;
5125         else
5126                 return NULL;
5127 }
5128
5129 /* Allocate network device and initialize private data */
5130 static struct at76_priv *at76_alloc_new_device(struct usb_device *udev)
5131 {
5132         struct net_device *netdev;
5133         struct at76_priv *priv;
5134         int i;
5135
5136         /* allocate memory for our device state and initialize it */
5137         netdev = alloc_etherdev(sizeof(struct at76_priv));
5138         if (!netdev) {
5139                 dev_printk(KERN_ERR, &udev->dev, "out of memory\n");
5140                 return NULL;
5141         }
5142
5143         priv = netdev_priv(netdev);
5144
5145         priv->udev = udev;
5146         priv->netdev = netdev;
5147
5148         mutex_init(&priv->mtx);
5149         INIT_WORK(&priv->work_assoc_done, at76_work_assoc_done);
5150         INIT_WORK(&priv->work_join, at76_work_join);
5151         INIT_WORK(&priv->work_new_bss, at76_work_new_bss);
5152         INIT_WORK(&priv->work_start_scan, at76_work_start_scan);
5153         INIT_WORK(&priv->work_set_promisc, at76_work_set_promisc);
5154         INIT_WORK(&priv->work_submit_rx, at76_work_submit_rx);
5155         INIT_DELAYED_WORK(&priv->dwork_restart, at76_dwork_restart);
5156         INIT_DELAYED_WORK(&priv->dwork_get_scan, at76_dwork_get_scan);
5157         INIT_DELAYED_WORK(&priv->dwork_beacon, at76_dwork_beacon);
5158         INIT_DELAYED_WORK(&priv->dwork_auth, at76_dwork_auth);
5159         INIT_DELAYED_WORK(&priv->dwork_assoc, at76_dwork_assoc);
5160
5161         spin_lock_init(&priv->mgmt_spinlock);
5162         priv->next_mgmt_bulk = NULL;
5163         priv->mac_state = MAC_INIT;
5164
5165         /* initialize empty BSS list */
5166         priv->curr_bss = NULL;
5167         INIT_LIST_HEAD(&priv->bss_list);
5168         spin_lock_init(&priv->bss_list_spinlock);
5169
5170         init_timer(&priv->bss_list_timer);
5171         priv->bss_list_timer.data = (unsigned long)priv;
5172         priv->bss_list_timer.function = at76_bss_list_timeout;
5173
5174         spin_lock_init(&priv->spy_spinlock);
5175
5176         /* mark all rx data entries as unused */
5177         for (i = 0; i < NR_RX_DATA_BUF; i++)
5178                 priv->rx_data[i].skb = NULL;
5179
5180         priv->rx_tasklet.func = at76_rx_tasklet;
5181         priv->rx_tasklet.data = 0;
5182
5183         priv->pm_mode = AT76_PM_OFF;
5184         priv->pm_period = 0;
5185
5186         return priv;
5187 }
5188
5189 static int at76_alloc_urbs(struct at76_priv *priv,
5190                            struct usb_interface *interface)
5191 {
5192         struct usb_endpoint_descriptor *endpoint, *ep_in, *ep_out;
5193         int i;
5194         int buffer_size;
5195         struct usb_host_interface *iface_desc;
5196
5197         at76_dbg(DBG_PROC_ENTRY, "%s: ENTER", __func__);
5198
5199         at76_dbg(DBG_URB, "%s: NumEndpoints %d ", __func__,
5200                  interface->altsetting[0].desc.bNumEndpoints);
5201
5202         ep_in = NULL;
5203         ep_out = NULL;
5204         iface_desc = interface->cur_altsetting;
5205         for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) {
5206                 endpoint = &iface_desc->endpoint[i].desc;
5207
5208                 at76_dbg(DBG_URB, "%s: %d. endpoint: addr 0x%x attr 0x%x",
5209                          __func__, i, endpoint->bEndpointAddress,
5210                          endpoint->bmAttributes);
5211
5212                 if (!ep_in && usb_endpoint_is_bulk_in(endpoint))
5213                         ep_in = endpoint;
5214
5215                 if (!ep_out && usb_endpoint_is_bulk_out(endpoint))
5216                         ep_out = endpoint;
5217         }
5218
5219         if (!ep_in || !ep_out) {
5220                 dev_printk(KERN_ERR, &interface->dev,
5221                            "bulk endpoints missing\n");
5222                 return -ENXIO;
5223         }
5224
5225         priv->rx_pipe = usb_rcvbulkpipe(priv->udev, ep_in->bEndpointAddress);
5226         priv->tx_pipe = usb_sndbulkpipe(priv->udev, ep_out->bEndpointAddress);
5227
5228         priv->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
5229         priv->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
5230         if (!priv->rx_urb || !priv->tx_urb) {
5231                 dev_printk(KERN_ERR, &interface->dev, "cannot allocate URB\n");
5232                 return -ENOMEM;
5233         }
5234
5235         buffer_size = sizeof(struct at76_tx_buffer) + MAX_PADDING_SIZE;
5236         priv->bulk_out_buffer = kmalloc(buffer_size, GFP_KERNEL);
5237         if (!priv->bulk_out_buffer) {
5238                 dev_printk(KERN_ERR, &interface->dev,
5239                            "cannot allocate output buffer\n");
5240                 return -ENOMEM;
5241         }
5242
5243         at76_dbg(DBG_PROC_ENTRY, "%s: EXIT", __func__);
5244
5245         return 0;
5246 }
5247
5248 /* Register network device and initialize the hardware */
5249 static int at76_init_new_device(struct at76_priv *priv,
5250                                 struct usb_interface *interface)
5251 {
5252         struct net_device *netdev = priv->netdev;
5253         int ret;
5254
5255         /* set up the endpoint information */
5256         /* check out the endpoints */
5257
5258         at76_dbg(DBG_DEVSTART, "USB interface: %d endpoints",
5259                  interface->cur_altsetting->desc.bNumEndpoints);
5260
5261         ret = at76_alloc_urbs(priv, interface);
5262         if (ret < 0)
5263                 goto exit;
5264
5265         /* MAC address */
5266         ret = at76_get_hw_config(priv);
5267         if (ret < 0) {
5268                 dev_printk(KERN_ERR, &interface->dev,
5269                            "cannot get MAC address\n");
5270                 goto exit;
5271         }
5272
5273         priv->domain = at76_get_reg_domain(priv->regulatory_domain);
5274         /* init. netdev->dev_addr */
5275         memcpy(netdev->dev_addr, priv->mac_addr, ETH_ALEN);
5276
5277         priv->channel = DEF_CHANNEL;
5278         priv->iw_mode = IW_MODE_INFRA;
5279         priv->rts_threshold = DEF_RTS_THRESHOLD;
5280         priv->frag_threshold = DEF_FRAG_THRESHOLD;
5281         priv->short_retry_limit = DEF_SHORT_RETRY_LIMIT;
5282         priv->txrate = TX_RATE_AUTO;
5283         priv->preamble_type = PREAMBLE_TYPE_LONG;
5284         priv->beacon_period = 100;
5285         priv->beacons_last_qual = jiffies;
5286         priv->auth_mode = WLAN_AUTH_OPEN;
5287         priv->scan_min_time = DEF_SCAN_MIN_TIME;
5288         priv->scan_max_time = DEF_SCAN_MAX_TIME;
5289         priv->scan_mode = SCAN_TYPE_ACTIVE;
5290
5291         netdev->flags &= ~IFF_MULTICAST;        /* not yet or never */
5292         netdev->open = at76_open;
5293         netdev->stop = at76_stop;
5294         netdev->get_stats = at76_get_stats;
5295         netdev->ethtool_ops = &at76_ethtool_ops;
5296
5297         /* Add pointers to enable iwspy support. */
5298         priv->wireless_data.spy_data = &priv->spy_data;
5299         netdev->wireless_data = &priv->wireless_data;
5300
5301         netdev->hard_start_xmit = at76_tx;
5302         netdev->tx_timeout = at76_tx_timeout;
5303         netdev->watchdog_timeo = 2 * HZ;
5304         netdev->wireless_handlers = &at76_handler_def;
5305         netdev->set_multicast_list = at76_set_multicast;
5306         netdev->set_mac_address = at76_set_mac_address;
5307         dev_alloc_name(netdev, "wlan%d");
5308
5309         ret = register_netdev(priv->netdev);
5310         if (ret) {
5311                 dev_printk(KERN_ERR, &interface->dev,
5312                            "cannot register netdevice (status %d)!\n", ret);
5313                 goto exit;
5314         }
5315         priv->netdev_registered = 1;
5316
5317         printk(KERN_INFO "%s: USB %s, MAC %s, firmware %d.%d.%d-%d\n",
5318                netdev->name, interface->dev.bus_id, mac2str(priv->mac_addr),
5319                priv->fw_version.major, priv->fw_version.minor,
5320                priv->fw_version.patch, priv->fw_version.build);
5321         printk(KERN_INFO "%s: regulatory domain 0x%02x: %s\n", netdev->name,
5322                priv->regulatory_domain, priv->domain->name);
5323
5324         /* we let this timer run the whole time this driver instance lives */
5325         mod_timer(&priv->bss_list_timer, jiffies + BSS_LIST_TIMEOUT);
5326
5327 exit:
5328         return ret;
5329 }
5330
5331 static void at76_delete_device(struct at76_priv *priv)
5332 {
5333         int i;
5334
5335         at76_dbg(DBG_PROC_ENTRY, "%s: ENTER", __func__);
5336
5337         /* The device is gone, don't bother turning it off */
5338         priv->device_unplugged = 1;
5339
5340         if (priv->netdev_registered)
5341                 unregister_netdev(priv->netdev);
5342
5343         /* assuming we used keventd, it must quiesce too */
5344         flush_scheduled_work();
5345
5346         kfree(priv->bulk_out_buffer);
5347
5348         if (priv->tx_urb) {
5349                 usb_kill_urb(priv->tx_urb);
5350                 usb_free_urb(priv->tx_urb);
5351         }
5352         if (priv->rx_urb) {
5353                 usb_kill_urb(priv->rx_urb);
5354                 usb_free_urb(priv->rx_urb);
5355         }
5356
5357         at76_dbg(DBG_PROC_ENTRY, "%s: unlinked urbs", __func__);
5358
5359         if (priv->rx_skb)
5360                 kfree_skb(priv->rx_skb);
5361
5362         at76_free_bss_list(priv);
5363         del_timer_sync(&priv->bss_list_timer);
5364         cancel_delayed_work(&priv->dwork_get_scan);
5365         cancel_delayed_work(&priv->dwork_beacon);
5366         cancel_delayed_work(&priv->dwork_auth);
5367         cancel_delayed_work(&priv->dwork_assoc);
5368
5369         if (priv->mac_state == MAC_CONNECTED)
5370                 at76_iwevent_bss_disconnect(priv->netdev);
5371
5372         for (i = 0; i < NR_RX_DATA_BUF; i++)
5373                 if (priv->rx_data[i].skb) {
5374                         dev_kfree_skb(priv->rx_data[i].skb);
5375                         priv->rx_data[i].skb = NULL;
5376                 }
5377         usb_put_dev(priv->udev);
5378
5379         at76_dbg(DBG_PROC_ENTRY, "%s: before freeing priv/netdev", __func__);
5380         free_netdev(priv->netdev);      /* priv is in netdev */
5381
5382         at76_dbg(DBG_PROC_ENTRY, "%s: EXIT", __func__);
5383 }
5384
5385 static int at76_probe(struct usb_interface *interface,
5386                       const struct usb_device_id *id)
5387 {
5388         int ret;
5389         struct at76_priv *priv;
5390         struct fwentry *fwe;
5391         struct usb_device *udev;
5392         int op_mode;
5393         int need_ext_fw = 0;
5394         struct mib_fw_version fwv;
5395         int board_type = (int)id->driver_info;
5396
5397         udev = usb_get_dev(interface_to_usbdev(interface));
5398
5399         /* Load firmware into kernel memory */
5400         fwe = at76_load_firmware(udev, board_type);
5401         if (!fwe) {
5402                 ret = -ENOENT;
5403                 goto error;
5404         }
5405
5406         op_mode = at76_get_op_mode(udev);
5407
5408         at76_dbg(DBG_DEVSTART, "opmode %d", op_mode);
5409
5410         /* we get OPMODE_NONE with 2.4.23, SMC2662W-AR ???
5411            we get 204 with 2.4.23, Fiberline FL-WL240u (505A+RFMD2958) ??? */
5412
5413         if (op_mode == OPMODE_HW_CONFIG_MODE) {
5414                 dev_printk(KERN_ERR, &interface->dev,
5415                            "cannot handle a device in HW_CONFIG_MODE\n");
5416                 ret = -EBUSY;
5417                 goto error;
5418         }
5419
5420         if (op_mode != OPMODE_NORMAL_NIC_WITH_FLASH
5421             && op_mode != OPMODE_NORMAL_NIC_WITHOUT_FLASH) {
5422                 /* download internal firmware part */
5423                 dev_printk(KERN_DEBUG, &interface->dev,
5424                            "downloading internal firmware\n");
5425                 ret = at76_load_internal_fw(udev, fwe);
5426                 if (ret < 0) {
5427                         dev_printk(KERN_ERR, &interface->dev,
5428                                    "error %d downloading internal firmware\n",
5429                                    ret);
5430                         goto error;
5431                 }
5432                 usb_put_dev(udev);
5433                 return ret;
5434         }
5435
5436         /* Internal firmware already inside the device.  Get firmware
5437          * version to test if external firmware is loaded.
5438          * This works only for newer firmware, e.g. the Intersil 0.90.x
5439          * says "control timeout on ep0in" and subsequent
5440          * at76_get_op_mode() fail too :-( */
5441
5442         /* if version >= 0.100.x.y or device with built-in flash we can
5443          * query the device for the fw version */
5444         if ((fwe->fw_version.major > 0 || fwe->fw_version.minor >= 100)
5445             || (op_mode == OPMODE_NORMAL_NIC_WITH_FLASH)) {
5446                 ret = at76_get_mib(udev, MIB_FW_VERSION, &fwv, sizeof(fwv));
5447                 if (ret < 0 || (fwv.major | fwv.minor) == 0)
5448                         need_ext_fw = 1;
5449         } else
5450                 /* No way to check firmware version, reload to be sure */
5451                 need_ext_fw = 1;
5452
5453         if (need_ext_fw) {
5454                 dev_printk(KERN_DEBUG, &interface->dev,
5455                            "downloading external firmware\n");
5456
5457                 ret = at76_load_external_fw(udev, fwe);
5458                 if (ret)
5459                         goto error;
5460
5461                 /* Re-check firmware version */
5462                 ret = at76_get_mib(udev, MIB_FW_VERSION, &fwv, sizeof(fwv));
5463                 if (ret < 0) {
5464                         dev_printk(KERN_ERR, &interface->dev,
5465                                    "error %d getting firmware version\n", ret);
5466                         goto error;
5467                 }
5468         }
5469
5470         priv = at76_alloc_new_device(udev);
5471         if (!priv) {
5472                 ret = -ENOMEM;
5473                 goto error;
5474         }
5475
5476         SET_NETDEV_DEV(priv->netdev, &interface->dev);
5477         usb_set_intfdata(interface, priv);
5478
5479         memcpy(&priv->fw_version, &fwv, sizeof(struct mib_fw_version));
5480         priv->board_type = board_type;
5481
5482         ret = at76_init_new_device(priv, interface);
5483         if (ret < 0)
5484                 at76_delete_device(priv);
5485
5486         return ret;
5487
5488 error:
5489         usb_put_dev(udev);
5490         return ret;
5491 }
5492
5493 static void at76_disconnect(struct usb_interface *interface)
5494 {
5495         struct at76_priv *priv;
5496
5497         priv = usb_get_intfdata(interface);
5498         usb_set_intfdata(interface, NULL);
5499
5500         /* Disconnect after loading internal firmware */
5501         if (!priv)
5502                 return;
5503
5504         printk(KERN_INFO "%s: disconnecting\n", priv->netdev->name);
5505         at76_delete_device(priv);
5506         dev_printk(KERN_INFO, &interface->dev, "disconnected\n");
5507 }
5508
5509 /* Structure for registering this driver with the USB subsystem */
5510 static struct usb_driver at76_driver = {
5511         .name = DRIVER_NAME,
5512         .probe = at76_probe,
5513         .disconnect = at76_disconnect,
5514         .id_table = dev_table,
5515 };
5516
5517 static int __init at76_mod_init(void)
5518 {
5519         int result;
5520
5521         printk(KERN_INFO DRIVER_DESC " " DRIVER_VERSION " loading\n");
5522
5523         mutex_init(&fw_mutex);
5524
5525         /* register this driver with the USB subsystem */
5526         result = usb_register(&at76_driver);
5527         if (result < 0)
5528                 printk(KERN_ERR DRIVER_NAME
5529                        ": usb_register failed (status %d)\n", result);
5530
5531         led_trigger_register_simple("at76_usb-tx", &ledtrig_tx);
5532         return result;
5533 }
5534
5535 static void __exit at76_mod_exit(void)
5536 {
5537         int i;
5538
5539         printk(KERN_INFO DRIVER_DESC " " DRIVER_VERSION " unloading\n");
5540         usb_deregister(&at76_driver);
5541         for (i = 0; i < ARRAY_SIZE(firmwares); i++) {
5542                 if (firmwares[i].fw)
5543                         release_firmware(firmwares[i].fw);
5544         }
5545         led_trigger_unregister_simple(ledtrig_tx);
5546 }
5547
5548 module_param_named(debug, at76_debug, int, 0600);
5549 MODULE_PARM_DESC(debug, "Debugging level");
5550
5551 module_init(at76_mod_init);
5552 module_exit(at76_mod_exit);
5553
5554 MODULE_AUTHOR("Oliver Kurth <oku@masqmail.cx>");
5555 MODULE_AUTHOR("Joerg Albert <joerg.albert@gmx.de>");
5556 MODULE_AUTHOR("Alex <alex@foogod.com>");
5557 MODULE_AUTHOR("Nick Jones");
5558 MODULE_AUTHOR("Balint Seeber <n0_5p4m_p13453@hotmail.com>");
5559 MODULE_AUTHOR("Pavel Roskin <proski@gnu.org>");
5560 MODULE_DESCRIPTION(DRIVER_DESC);
5561 MODULE_LICENSE("GPL");