GNU Linux-libre 5.19-rc6-gnu
[releases.git] / drivers / net / wireless / atmel / at76c50x-usb.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * at76c503/at76c505 USB driver
4  *
5  * Copyright (c) 2002 - 2003 Oliver Kurth
6  * Copyright (c) 2004 Joerg Albert <joerg.albert@gmx.de>
7  * Copyright (c) 2004 Nick Jones
8  * Copyright (c) 2004 Balint Seeber <n0_5p4m_p13453@hotmail.com>
9  * Copyright (c) 2007 Guido Guenther <agx@sigxcpu.org>
10  * Copyright (c) 2007 Kalle Valo <kalle.valo@iki.fi>
11  * Copyright (c) 2010 Sebastian Smolorz <sesmo@gmx.net>
12  *
13  * This file is part of the Berlios driver for WLAN USB devices based on the
14  * Atmel AT76C503A/505/505A.
15  *
16  * Some iw_handler code was taken from airo.c, (C) 1999 Benjamin Reed
17  *
18  * TODO list is at the wiki:
19  *
20  * https://wireless.wiki.kernel.org/en/users/Drivers/at76c50x-usb#TODO
21  */
22
23 #include <linux/init.h>
24 #include <linux/kernel.h>
25 #include <linux/sched.h>
26 #include <linux/errno.h>
27 #include <linux/slab.h>
28 #include <linux/module.h>
29 #include <linux/spinlock.h>
30 #include <linux/list.h>
31 #include <linux/usb.h>
32 #include <linux/netdevice.h>
33 #include <linux/if_arp.h>
34 #include <linux/etherdevice.h>
35 #include <linux/ethtool.h>
36 #include <linux/wireless.h>
37 #include <net/iw_handler.h>
38 #include <net/ieee80211_radiotap.h>
39 #include <linux/firmware.h>
40 #include <linux/leds.h>
41 #include <net/mac80211.h>
42
43 #include "at76c50x-usb.h"
44
45 /* Version information */
46 #define DRIVER_NAME "at76c50x-usb"
47 #define DRIVER_VERSION  "0.17"
48 #define DRIVER_DESC "Atmel at76x USB Wireless LAN Driver"
49
50 /* at76_debug bits */
51 #define DBG_PROGRESS            0x00000001      /* authentication/accociation */
52 #define DBG_BSS_TABLE           0x00000002      /* show BSS table after scans */
53 #define DBG_IOCTL               0x00000004      /* ioctl calls / settings */
54 #define DBG_MAC_STATE           0x00000008      /* MAC state transitions */
55 #define DBG_TX_DATA             0x00000010      /* tx header */
56 #define DBG_TX_DATA_CONTENT     0x00000020      /* tx content */
57 #define DBG_TX_MGMT             0x00000040      /* tx management */
58 #define DBG_RX_DATA             0x00000080      /* rx data header */
59 #define DBG_RX_DATA_CONTENT     0x00000100      /* rx data content */
60 #define DBG_RX_MGMT             0x00000200      /* rx mgmt frame headers */
61 #define DBG_RX_BEACON           0x00000400      /* rx beacon */
62 #define DBG_RX_CTRL             0x00000800      /* rx control */
63 #define DBG_RX_MGMT_CONTENT     0x00001000      /* rx mgmt content */
64 #define DBG_RX_FRAGS            0x00002000      /* rx data fragment handling */
65 #define DBG_DEVSTART            0x00004000      /* fw download, device start */
66 #define DBG_URB                 0x00008000      /* rx urb status, ... */
67 #define DBG_RX_ATMEL_HDR        0x00010000      /* Atmel-specific Rx headers */
68 #define DBG_PROC_ENTRY          0x00020000      /* procedure entries/exits */
69 #define DBG_PM                  0x00040000      /* power management settings */
70 #define DBG_BSS_MATCH           0x00080000      /* BSS match failures */
71 #define DBG_PARAMS              0x00100000      /* show configured parameters */
72 #define DBG_WAIT_COMPLETE       0x00200000      /* command completion */
73 #define DBG_RX_FRAGS_SKB        0x00400000      /* skb header of Rx fragments */
74 #define DBG_BSS_TABLE_RM        0x00800000      /* purging bss table entries */
75 #define DBG_MONITOR_MODE        0x01000000      /* monitor mode */
76 #define DBG_MIB                 0x02000000      /* dump all MIBs on startup */
77 #define DBG_MGMT_TIMER          0x04000000      /* dump mgmt_timer ops */
78 #define DBG_WE_EVENTS           0x08000000      /* dump wireless events */
79 #define DBG_FW                  0x10000000      /* firmware download */
80 #define DBG_DFU                 0x20000000      /* device firmware upgrade */
81 #define DBG_CMD                 0x40000000
82 #define DBG_MAC80211            0x80000000
83
84 #define DBG_DEFAULTS            0
85
86 /* Use our own dbg macro */
87 #define at76_dbg(bits, format, arg...)                                  \
88 do {                                                                    \
89         if (at76_debug & (bits))                                        \
90                 printk(KERN_DEBUG DRIVER_NAME ": " format "\n", ##arg); \
91 } while (0)
92
93 #define at76_dbg_dump(bits, buf, len, format, arg...)                   \
94 do {                                                                    \
95         if (at76_debug & (bits)) {                                      \
96                 printk(KERN_DEBUG DRIVER_NAME ": " format "\n", ##arg); \
97                 print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, buf, len); \
98         }                                                               \
99 } while (0)
100
101 static uint at76_debug = DBG_DEFAULTS;
102
103 /* Protect against concurrent firmware loading and parsing */
104 static DEFINE_MUTEX(fw_mutex);
105
106 static struct fwentry firmwares[] = {
107         [0] = { "" },
108         [BOARD_503_ISL3861] = { "/*(DEBLOBBED)*/" },
109         [BOARD_503_ISL3863] = { "/*(DEBLOBBED)*/" },
110         [BOARD_503] = { "/*(DEBLOBBED)*/" },
111         [BOARD_503_ACC] = { "/*(DEBLOBBED)*/" },
112         [BOARD_505] = { "/*(DEBLOBBED)*/" },
113         [BOARD_505_2958] = { "/*(DEBLOBBED)*/" },
114         [BOARD_505A] = { "/*(DEBLOBBED)*/" },
115         [BOARD_505AMX] = { "/*(DEBLOBBED)*/" },
116 };
117 /*(DEBLOBBED)*/
118
119 #define USB_DEVICE_DATA(__ops)  .driver_info = (kernel_ulong_t)(__ops)
120
121 static const struct usb_device_id dev_table[] = {
122         /*
123          * at76c503-i3861
124          */
125         /* Generic AT76C503/3861 device */
126         { USB_DEVICE(0x03eb, 0x7603), USB_DEVICE_DATA(BOARD_503_ISL3861) },
127         /* Linksys WUSB11 v2.1/v2.6 */
128         { USB_DEVICE(0x066b, 0x2211), USB_DEVICE_DATA(BOARD_503_ISL3861) },
129         /* Netgear MA101 rev. A */
130         { USB_DEVICE(0x0864, 0x4100), USB_DEVICE_DATA(BOARD_503_ISL3861) },
131         /* Tekram U300C / Allnet ALL0193 */
132         { USB_DEVICE(0x0b3b, 0x1612), USB_DEVICE_DATA(BOARD_503_ISL3861) },
133         /* HP HN210W J7801A */
134         { USB_DEVICE(0x03f0, 0x011c), USB_DEVICE_DATA(BOARD_503_ISL3861) },
135         /* Sitecom/Z-Com/Zyxel M4Y-750 */
136         { USB_DEVICE(0x0cde, 0x0001), USB_DEVICE_DATA(BOARD_503_ISL3861) },
137         /* Dynalink/Askey WLL013 (intersil) */
138         { USB_DEVICE(0x069a, 0x0320), USB_DEVICE_DATA(BOARD_503_ISL3861) },
139         /* EZ connect 11Mpbs Wireless USB Adapter SMC2662W v1 */
140         { USB_DEVICE(0x0d5c, 0xa001), USB_DEVICE_DATA(BOARD_503_ISL3861) },
141         /* BenQ AWL300 */
142         { USB_DEVICE(0x04a5, 0x9000), USB_DEVICE_DATA(BOARD_503_ISL3861) },
143         /* Addtron AWU-120, Compex WLU11 */
144         { USB_DEVICE(0x05dd, 0xff31), USB_DEVICE_DATA(BOARD_503_ISL3861) },
145         /* Intel AP310 AnyPoint II USB */
146         { USB_DEVICE(0x8086, 0x0200), USB_DEVICE_DATA(BOARD_503_ISL3861) },
147         /* Dynalink L11U */
148         { USB_DEVICE(0x0d8e, 0x7100), USB_DEVICE_DATA(BOARD_503_ISL3861) },
149         /* Arescom WL-210, FCC id 07J-GL2411USB */
150         { USB_DEVICE(0x0d8e, 0x7110), USB_DEVICE_DATA(BOARD_503_ISL3861) },
151         /* I-O DATA WN-B11/USB */
152         { USB_DEVICE(0x04bb, 0x0919), USB_DEVICE_DATA(BOARD_503_ISL3861) },
153         /* BT Voyager 1010 */
154         { USB_DEVICE(0x069a, 0x0821), USB_DEVICE_DATA(BOARD_503_ISL3861) },
155         /*
156          * at76c503-i3863
157          */
158         /* Generic AT76C503/3863 device */
159         { USB_DEVICE(0x03eb, 0x7604), USB_DEVICE_DATA(BOARD_503_ISL3863) },
160         /* Samsung SWL-2100U */
161         { USB_DEVICE(0x055d, 0xa000), USB_DEVICE_DATA(BOARD_503_ISL3863) },
162         /*
163          * at76c503-rfmd
164          */
165         /* Generic AT76C503/RFMD device */
166         { USB_DEVICE(0x03eb, 0x7605), USB_DEVICE_DATA(BOARD_503) },
167         /* Dynalink/Askey WLL013 (rfmd) */
168         { USB_DEVICE(0x069a, 0x0321), USB_DEVICE_DATA(BOARD_503) },
169         /* Linksys WUSB11 v2.6 */
170         { USB_DEVICE(0x077b, 0x2219), USB_DEVICE_DATA(BOARD_503) },
171         /* Network Everywhere NWU11B */
172         { USB_DEVICE(0x077b, 0x2227), USB_DEVICE_DATA(BOARD_503) },
173         /* Netgear MA101 rev. B */
174         { USB_DEVICE(0x0864, 0x4102), USB_DEVICE_DATA(BOARD_503) },
175         /* D-Link DWL-120 rev. E */
176         { USB_DEVICE(0x2001, 0x3200), USB_DEVICE_DATA(BOARD_503) },
177         /* Actiontec 802UAT1, HWU01150-01UK */
178         { USB_DEVICE(0x1668, 0x7605), USB_DEVICE_DATA(BOARD_503) },
179         /* AirVast W-Buddie WN210 */
180         { USB_DEVICE(0x03eb, 0x4102), USB_DEVICE_DATA(BOARD_503) },
181         /* Dick Smith Electronics XH1153 802.11b USB adapter */
182         { USB_DEVICE(0x1371, 0x5743), USB_DEVICE_DATA(BOARD_503) },
183         /* CNet CNUSB611 */
184         { USB_DEVICE(0x1371, 0x0001), USB_DEVICE_DATA(BOARD_503) },
185         /* FiberLine FL-WL200U */
186         { USB_DEVICE(0x1371, 0x0002), USB_DEVICE_DATA(BOARD_503) },
187         /* BenQ AWL400 USB stick */
188         { USB_DEVICE(0x04a5, 0x9001), USB_DEVICE_DATA(BOARD_503) },
189         /* 3Com 3CRSHEW696 */
190         { USB_DEVICE(0x0506, 0x0a01), USB_DEVICE_DATA(BOARD_503) },
191         /* Siemens Santis ADSL WLAN USB adapter WLL 013 */
192         { USB_DEVICE(0x0681, 0x001b), USB_DEVICE_DATA(BOARD_503) },
193         /* Belkin F5D6050, version 2 */
194         { USB_DEVICE(0x050d, 0x0050), USB_DEVICE_DATA(BOARD_503) },
195         /* iBlitzz, BWU613 (not *B or *SB) */
196         { USB_DEVICE(0x07b8, 0xb000), USB_DEVICE_DATA(BOARD_503) },
197         /* Gigabyte GN-WLBM101 */
198         { USB_DEVICE(0x1044, 0x8003), USB_DEVICE_DATA(BOARD_503) },
199         /* Planex GW-US11S */
200         { USB_DEVICE(0x2019, 0x3220), USB_DEVICE_DATA(BOARD_503) },
201         /* Internal WLAN adapter in h5[4,5]xx series iPAQs */
202         { USB_DEVICE(0x049f, 0x0032), USB_DEVICE_DATA(BOARD_503) },
203         /* Corega Wireless LAN USB-11 mini */
204         { USB_DEVICE(0x07aa, 0x0011), USB_DEVICE_DATA(BOARD_503) },
205         /* Corega Wireless LAN USB-11 mini2 */
206         { USB_DEVICE(0x07aa, 0x0018), USB_DEVICE_DATA(BOARD_503) },
207         /* Uniden PCW100 */
208         { USB_DEVICE(0x05dd, 0xff35), USB_DEVICE_DATA(BOARD_503) },
209         /*
210          * at76c503-rfmd-acc
211          */
212         /* SMC2664W */
213         { USB_DEVICE(0x083a, 0x3501), USB_DEVICE_DATA(BOARD_503_ACC) },
214         /* Belkin F5D6050, SMC2662W v2, SMC2662W-AR */
215         { USB_DEVICE(0x0d5c, 0xa002), USB_DEVICE_DATA(BOARD_503_ACC) },
216         /*
217          * at76c505-rfmd
218          */
219         /* Generic AT76C505/RFMD */
220         { USB_DEVICE(0x03eb, 0x7606), USB_DEVICE_DATA(BOARD_505) },
221         /*
222          * at76c505-rfmd2958
223          */
224         /* Generic AT76C505/RFMD, OvisLink WL-1130USB */
225         { USB_DEVICE(0x03eb, 0x7613), USB_DEVICE_DATA(BOARD_505_2958) },
226         /* Fiberline FL-WL240U */
227         { USB_DEVICE(0x1371, 0x0014), USB_DEVICE_DATA(BOARD_505_2958) },
228         /* CNet CNUSB-611G */
229         { USB_DEVICE(0x1371, 0x0013), USB_DEVICE_DATA(BOARD_505_2958) },
230         /* Linksys WUSB11 v2.8 */
231         { USB_DEVICE(0x1915, 0x2233), USB_DEVICE_DATA(BOARD_505_2958) },
232         /* Xterasys XN-2122B, IBlitzz BWU613B/BWU613SB */
233         { USB_DEVICE(0x12fd, 0x1001), USB_DEVICE_DATA(BOARD_505_2958) },
234         /* Corega WLAN USB Stick 11 */
235         { USB_DEVICE(0x07aa, 0x7613), USB_DEVICE_DATA(BOARD_505_2958) },
236         /* Microstar MSI Box MS6978 */
237         { USB_DEVICE(0x0db0, 0x1020), USB_DEVICE_DATA(BOARD_505_2958) },
238         /*
239          * at76c505a-rfmd2958
240          */
241         /* Generic AT76C505A device */
242         { USB_DEVICE(0x03eb, 0x7614), USB_DEVICE_DATA(BOARD_505A) },
243         /* Generic AT76C505AS device */
244         { USB_DEVICE(0x03eb, 0x7617), USB_DEVICE_DATA(BOARD_505A) },
245         /* Siemens Gigaset USB WLAN Adapter 11 */
246         { USB_DEVICE(0x1690, 0x0701), USB_DEVICE_DATA(BOARD_505A) },
247         /* OQO Model 01+ Internal Wi-Fi */
248         { USB_DEVICE(0x1557, 0x0002), USB_DEVICE_DATA(BOARD_505A) },
249         /*
250          * at76c505amx-rfmd
251          */
252         /* Generic AT76C505AMX device */
253         { USB_DEVICE(0x03eb, 0x7615), USB_DEVICE_DATA(BOARD_505AMX) },
254         { }
255 };
256
257 MODULE_DEVICE_TABLE(usb, dev_table);
258
259 /* Supported rates of this hardware, bit 7 marks basic rates */
260 static const u8 hw_rates[] = { 0x82, 0x84, 0x0b, 0x16 };
261
262 static const char *const preambles[] = { "long", "short", "auto" };
263
264 /* Firmware download */
265 /* DFU states */
266 #define STATE_IDLE                      0x00
267 #define STATE_DETACH                    0x01
268 #define STATE_DFU_IDLE                  0x02
269 #define STATE_DFU_DOWNLOAD_SYNC         0x03
270 #define STATE_DFU_DOWNLOAD_BUSY         0x04
271 #define STATE_DFU_DOWNLOAD_IDLE         0x05
272 #define STATE_DFU_MANIFEST_SYNC         0x06
273 #define STATE_DFU_MANIFEST              0x07
274 #define STATE_DFU_MANIFEST_WAIT_RESET   0x08
275 #define STATE_DFU_UPLOAD_IDLE           0x09
276 #define STATE_DFU_ERROR                 0x0a
277
278 /* DFU commands */
279 #define DFU_DETACH                      0
280 #define DFU_DNLOAD                      1
281 #define DFU_UPLOAD                      2
282 #define DFU_GETSTATUS                   3
283 #define DFU_CLRSTATUS                   4
284 #define DFU_GETSTATE                    5
285 #define DFU_ABORT                       6
286
287 #define FW_BLOCK_SIZE 1024
288
289 struct dfu_status {
290         unsigned char status;
291         unsigned char poll_timeout[3];
292         unsigned char state;
293         unsigned char string;
294 } __packed;
295
296 static inline int at76_is_intersil(enum board_type board)
297 {
298         return (board == BOARD_503_ISL3861 || board == BOARD_503_ISL3863);
299 }
300
301 static inline int at76_is_503rfmd(enum board_type board)
302 {
303         return (board == BOARD_503 || board == BOARD_503_ACC);
304 }
305
306 static inline int at76_is_505a(enum board_type board)
307 {
308         return (board == BOARD_505A || board == BOARD_505AMX);
309 }
310
311 /* Load a block of the first (internal) part of the firmware */
312 static int at76_load_int_fw_block(struct usb_device *udev, int blockno,
313                                   void *block, int size)
314 {
315         return usb_control_msg(udev, usb_sndctrlpipe(udev, 0), DFU_DNLOAD,
316                                USB_TYPE_CLASS | USB_DIR_OUT |
317                                USB_RECIP_INTERFACE, blockno, 0, block, size,
318                                USB_CTRL_GET_TIMEOUT);
319 }
320
321 static int at76_dfu_get_status(struct usb_device *udev,
322                                struct dfu_status *status)
323 {
324         int ret;
325
326         ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), DFU_GETSTATUS,
327                               USB_TYPE_CLASS | USB_DIR_IN | USB_RECIP_INTERFACE,
328                               0, 0, status, sizeof(struct dfu_status),
329                               USB_CTRL_GET_TIMEOUT);
330         return ret;
331 }
332
333 static int at76_dfu_get_state(struct usb_device *udev, u8 *state)
334 {
335         int ret;
336
337         ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), DFU_GETSTATE,
338                               USB_TYPE_CLASS | USB_DIR_IN | USB_RECIP_INTERFACE,
339                               0, 0, state, 1, USB_CTRL_GET_TIMEOUT);
340         return ret;
341 }
342
343 /* Convert timeout from the DFU status to jiffies */
344 static inline unsigned long at76_get_timeout(struct dfu_status *s)
345 {
346         return msecs_to_jiffies((s->poll_timeout[2] << 16)
347                                 | (s->poll_timeout[1] << 8)
348                                 | (s->poll_timeout[0]));
349 }
350
351 /* Load internal firmware from the buffer.  If manifest_sync_timeout > 0, use
352  * its value in jiffies in the MANIFEST_SYNC state.  */
353 static int at76_usbdfu_download(struct usb_device *udev, u8 *buf, u32 size,
354                                 int manifest_sync_timeout)
355 {
356         int ret = 0;
357         int need_dfu_state = 1;
358         int is_done = 0;
359         u32 dfu_timeout = 0;
360         int bsize = 0;
361         int blockno = 0;
362         struct dfu_status *dfu_stat_buf = NULL;
363         u8 *dfu_state = NULL;
364         u8 *block = NULL;
365
366         at76_dbg(DBG_DFU, "%s( %p, %u, %d)", __func__, buf, size,
367                  manifest_sync_timeout);
368
369         if (!size) {
370                 dev_err(&udev->dev, "FW buffer length invalid!\n");
371                 return -EINVAL;
372         }
373
374         dfu_stat_buf = kmalloc(sizeof(struct dfu_status), GFP_KERNEL);
375         if (!dfu_stat_buf) {
376                 ret = -ENOMEM;
377                 goto exit;
378         }
379
380         block = kmalloc(FW_BLOCK_SIZE, GFP_KERNEL);
381         if (!block) {
382                 ret = -ENOMEM;
383                 goto exit;
384         }
385
386         dfu_state = kmalloc(sizeof(u8), GFP_KERNEL);
387         if (!dfu_state) {
388                 ret = -ENOMEM;
389                 goto exit;
390         }
391         *dfu_state = 0;
392
393         do {
394                 if (need_dfu_state) {
395                         ret = at76_dfu_get_state(udev, dfu_state);
396                         if (ret < 0) {
397                                 dev_err(&udev->dev,
398                                         "cannot get DFU state: %d\n", ret);
399                                 goto exit;
400                         }
401                         need_dfu_state = 0;
402                 }
403
404                 switch (*dfu_state) {
405                 case STATE_DFU_DOWNLOAD_SYNC:
406                         at76_dbg(DBG_DFU, "STATE_DFU_DOWNLOAD_SYNC");
407                         ret = at76_dfu_get_status(udev, dfu_stat_buf);
408                         if (ret >= 0) {
409                                 *dfu_state = dfu_stat_buf->state;
410                                 dfu_timeout = at76_get_timeout(dfu_stat_buf);
411                                 need_dfu_state = 0;
412                         } else
413                                 dev_err(&udev->dev,
414                                         "at76_dfu_get_status returned %d\n",
415                                         ret);
416                         break;
417
418                 case STATE_DFU_DOWNLOAD_BUSY:
419                         at76_dbg(DBG_DFU, "STATE_DFU_DOWNLOAD_BUSY");
420                         need_dfu_state = 1;
421
422                         at76_dbg(DBG_DFU, "DFU: Resetting device");
423                         schedule_timeout_interruptible(dfu_timeout);
424                         break;
425
426                 case STATE_DFU_DOWNLOAD_IDLE:
427                         at76_dbg(DBG_DFU, "DOWNLOAD...");
428                         fallthrough;
429                 case STATE_DFU_IDLE:
430                         at76_dbg(DBG_DFU, "DFU IDLE");
431
432                         bsize = min_t(int, size, FW_BLOCK_SIZE);
433                         memcpy(block, buf, bsize);
434                         at76_dbg(DBG_DFU, "int fw, size left = %5d, "
435                                  "bsize = %4d, blockno = %2d", size, bsize,
436                                  blockno);
437                         ret =
438                             at76_load_int_fw_block(udev, blockno, block, bsize);
439                         buf += bsize;
440                         size -= bsize;
441                         blockno++;
442
443                         if (ret != bsize)
444                                 dev_err(&udev->dev,
445                                         "at76_load_int_fw_block returned %d\n",
446                                         ret);
447                         need_dfu_state = 1;
448                         break;
449
450                 case STATE_DFU_MANIFEST_SYNC:
451                         at76_dbg(DBG_DFU, "STATE_DFU_MANIFEST_SYNC");
452
453                         ret = at76_dfu_get_status(udev, dfu_stat_buf);
454                         if (ret < 0)
455                                 break;
456
457                         *dfu_state = dfu_stat_buf->state;
458                         dfu_timeout = at76_get_timeout(dfu_stat_buf);
459                         need_dfu_state = 0;
460
461                         /* override the timeout from the status response,
462                            needed for AT76C505A */
463                         if (manifest_sync_timeout > 0)
464                                 dfu_timeout = manifest_sync_timeout;
465
466                         at76_dbg(DBG_DFU, "DFU: Waiting for manifest phase");
467                         schedule_timeout_interruptible(dfu_timeout);
468                         break;
469
470                 case STATE_DFU_MANIFEST:
471                         at76_dbg(DBG_DFU, "STATE_DFU_MANIFEST");
472                         is_done = 1;
473                         break;
474
475                 case STATE_DFU_MANIFEST_WAIT_RESET:
476                         at76_dbg(DBG_DFU, "STATE_DFU_MANIFEST_WAIT_RESET");
477                         is_done = 1;
478                         break;
479
480                 case STATE_DFU_UPLOAD_IDLE:
481                         at76_dbg(DBG_DFU, "STATE_DFU_UPLOAD_IDLE");
482                         break;
483
484                 case STATE_DFU_ERROR:
485                         at76_dbg(DBG_DFU, "STATE_DFU_ERROR");
486                         ret = -EPIPE;
487                         break;
488
489                 default:
490                         at76_dbg(DBG_DFU, "DFU UNKNOWN STATE (%d)", *dfu_state);
491                         ret = -EINVAL;
492                         break;
493                 }
494         } while (!is_done && (ret >= 0));
495
496 exit:
497         kfree(dfu_state);
498         kfree(block);
499         kfree(dfu_stat_buf);
500
501         if (ret >= 0)
502                 ret = 0;
503
504         return ret;
505 }
506
507 /* LED trigger */
508 static int tx_activity;
509 static void at76_ledtrig_tx_timerfunc(struct timer_list *unused);
510 static DEFINE_TIMER(ledtrig_tx_timer, at76_ledtrig_tx_timerfunc);
511 DEFINE_LED_TRIGGER(ledtrig_tx);
512
513 static void at76_ledtrig_tx_timerfunc(struct timer_list *unused)
514 {
515         static int tx_lastactivity;
516
517         if (tx_lastactivity != tx_activity) {
518                 tx_lastactivity = tx_activity;
519                 led_trigger_event(ledtrig_tx, LED_FULL);
520                 mod_timer(&ledtrig_tx_timer, jiffies + HZ / 4);
521         } else
522                 led_trigger_event(ledtrig_tx, LED_OFF);
523 }
524
525 static void at76_ledtrig_tx_activity(void)
526 {
527         tx_activity++;
528         if (!timer_pending(&ledtrig_tx_timer))
529                 mod_timer(&ledtrig_tx_timer, jiffies + HZ / 4);
530 }
531
532 static int at76_remap(struct usb_device *udev)
533 {
534         int ret;
535         ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0a,
536                               USB_TYPE_VENDOR | USB_DIR_OUT |
537                               USB_RECIP_INTERFACE, 0, 0, NULL, 0,
538                               USB_CTRL_GET_TIMEOUT);
539         if (ret < 0)
540                 return ret;
541         return 0;
542 }
543
544 static int at76_get_op_mode(struct usb_device *udev)
545 {
546         int ret;
547         u8 saved;
548         u8 *op_mode;
549
550         op_mode = kmalloc(1, GFP_NOIO);
551         if (!op_mode)
552                 return -ENOMEM;
553         ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33,
554                               USB_TYPE_VENDOR | USB_DIR_IN |
555                               USB_RECIP_INTERFACE, 0x01, 0, op_mode, 1,
556                               USB_CTRL_GET_TIMEOUT);
557         saved = *op_mode;
558         kfree(op_mode);
559
560         if (ret < 0)
561                 return ret;
562         else if (ret < 1)
563                 return -EIO;
564         else
565                 return saved;
566 }
567
568 /* Load a block of the second ("external") part of the firmware */
569 static inline int at76_load_ext_fw_block(struct usb_device *udev, int blockno,
570                                          void *block, int size)
571 {
572         return usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0e,
573                                USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
574                                0x0802, blockno, block, size,
575                                USB_CTRL_GET_TIMEOUT);
576 }
577
578 static inline int at76_get_hw_cfg(struct usb_device *udev,
579                                   union at76_hwcfg *buf, int buf_size)
580 {
581         return usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33,
582                                USB_TYPE_VENDOR | USB_DIR_IN |
583                                USB_RECIP_INTERFACE, 0x0a02, 0,
584                                buf, buf_size, USB_CTRL_GET_TIMEOUT);
585 }
586
587 /* Intersil boards use a different "value" for GetHWConfig requests */
588 static inline int at76_get_hw_cfg_intersil(struct usb_device *udev,
589                                            union at76_hwcfg *buf, int buf_size)
590 {
591         return usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33,
592                                USB_TYPE_VENDOR | USB_DIR_IN |
593                                USB_RECIP_INTERFACE, 0x0902, 0,
594                                buf, buf_size, USB_CTRL_GET_TIMEOUT);
595 }
596
597 /* Get the hardware configuration for the adapter and put it to the appropriate
598  * fields of 'priv' (the GetHWConfig request and interpretation of the result
599  * depends on the board type) */
600 static int at76_get_hw_config(struct at76_priv *priv)
601 {
602         int ret;
603         union at76_hwcfg *hwcfg = kmalloc(sizeof(*hwcfg), GFP_KERNEL);
604
605         if (!hwcfg)
606                 return -ENOMEM;
607
608         if (at76_is_intersil(priv->board_type)) {
609                 ret = at76_get_hw_cfg_intersil(priv->udev, hwcfg,
610                                                sizeof(hwcfg->i));
611                 if (ret < 0)
612                         goto exit;
613                 memcpy(priv->mac_addr, hwcfg->i.mac_addr, ETH_ALEN);
614                 priv->regulatory_domain = hwcfg->i.regulatory_domain;
615         } else if (at76_is_503rfmd(priv->board_type)) {
616                 ret = at76_get_hw_cfg(priv->udev, hwcfg, sizeof(hwcfg->r3));
617                 if (ret < 0)
618                         goto exit;
619                 memcpy(priv->mac_addr, hwcfg->r3.mac_addr, ETH_ALEN);
620                 priv->regulatory_domain = hwcfg->r3.regulatory_domain;
621         } else {
622                 ret = at76_get_hw_cfg(priv->udev, hwcfg, sizeof(hwcfg->r5));
623                 if (ret < 0)
624                         goto exit;
625                 memcpy(priv->mac_addr, hwcfg->r5.mac_addr, ETH_ALEN);
626                 priv->regulatory_domain = hwcfg->r5.regulatory_domain;
627         }
628
629 exit:
630         kfree(hwcfg);
631         if (ret < 0)
632                 wiphy_err(priv->hw->wiphy, "cannot get HW Config (error %d)\n",
633                           ret);
634
635         return ret;
636 }
637
638 static struct reg_domain const *at76_get_reg_domain(u16 code)
639 {
640         int i;
641         static struct reg_domain const fd_tab[] = {
642                 { 0x10, "FCC (USA)", 0x7ff },   /* ch 1-11 */
643                 { 0x20, "IC (Canada)", 0x7ff }, /* ch 1-11 */
644                 { 0x30, "ETSI (most of Europe)", 0x1fff },      /* ch 1-13 */
645                 { 0x31, "Spain", 0x600 },       /* ch 10-11 */
646                 { 0x32, "France", 0x1e00 },     /* ch 10-13 */
647                 { 0x40, "MKK (Japan)", 0x2000 },        /* ch 14 */
648                 { 0x41, "MKK1 (Japan)", 0x3fff },       /* ch 1-14 */
649                 { 0x50, "Israel", 0x3fc },      /* ch 3-9 */
650                 { 0x00, "<unknown>", 0xffffffff }       /* ch 1-32 */
651         };
652
653         /* Last entry is fallback for unknown domain code */
654         for (i = 0; i < ARRAY_SIZE(fd_tab) - 1; i++)
655                 if (code == fd_tab[i].code)
656                         break;
657
658         return &fd_tab[i];
659 }
660
661 static inline int at76_get_mib(struct usb_device *udev, u16 mib, void *buf,
662                                int buf_size)
663 {
664         int ret;
665
666         ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x33,
667                               USB_TYPE_VENDOR | USB_DIR_IN |
668                               USB_RECIP_INTERFACE, mib << 8, 0, buf, buf_size,
669                               USB_CTRL_GET_TIMEOUT);
670         if (ret >= 0 && ret != buf_size)
671                 return -EIO;
672         return ret;
673 }
674
675 /* Return positive number for status, negative for an error */
676 static inline int at76_get_cmd_status(struct usb_device *udev, u8 cmd)
677 {
678         u8 *stat_buf;
679         int ret;
680
681         stat_buf = kmalloc(40, GFP_NOIO);
682         if (!stat_buf)
683                 return -ENOMEM;
684
685         ret = usb_control_msg(udev, usb_rcvctrlpipe(udev, 0), 0x22,
686                         USB_TYPE_VENDOR | USB_DIR_IN |
687                         USB_RECIP_INTERFACE, cmd, 0, stat_buf,
688                         40, USB_CTRL_GET_TIMEOUT);
689         if (ret >= 0)
690                 ret = stat_buf[5];
691         kfree(stat_buf);
692
693         return ret;
694 }
695
696 #define MAKE_CMD_CASE(c) case (c): return #c
697 static const char *at76_get_cmd_string(u8 cmd_status)
698 {
699         switch (cmd_status) {
700                 MAKE_CMD_CASE(CMD_SET_MIB);
701                 MAKE_CMD_CASE(CMD_GET_MIB);
702                 MAKE_CMD_CASE(CMD_SCAN);
703                 MAKE_CMD_CASE(CMD_JOIN);
704                 MAKE_CMD_CASE(CMD_START_IBSS);
705                 MAKE_CMD_CASE(CMD_RADIO_ON);
706                 MAKE_CMD_CASE(CMD_RADIO_OFF);
707                 MAKE_CMD_CASE(CMD_STARTUP);
708         }
709
710         return "UNKNOWN";
711 }
712
713 static int at76_set_card_command(struct usb_device *udev, u8 cmd, void *buf,
714                                  int buf_size)
715 {
716         int ret;
717         struct at76_command *cmd_buf = kmalloc(sizeof(struct at76_command) +
718                                                buf_size, GFP_KERNEL);
719
720         if (!cmd_buf)
721                 return -ENOMEM;
722
723         cmd_buf->cmd = cmd;
724         cmd_buf->reserved = 0;
725         cmd_buf->size = cpu_to_le16(buf_size);
726         memcpy(cmd_buf->data, buf, buf_size);
727
728         at76_dbg_dump(DBG_CMD, cmd_buf, sizeof(struct at76_command) + buf_size,
729                       "issuing command %s (0x%02x)",
730                       at76_get_cmd_string(cmd), cmd);
731
732         ret = usb_control_msg(udev, usb_sndctrlpipe(udev, 0), 0x0e,
733                               USB_TYPE_VENDOR | USB_DIR_OUT | USB_RECIP_DEVICE,
734                               0, 0, cmd_buf,
735                               sizeof(struct at76_command) + buf_size,
736                               USB_CTRL_GET_TIMEOUT);
737         kfree(cmd_buf);
738         return ret;
739 }
740
741 #define MAKE_CMD_STATUS_CASE(c) case (c): return #c
742 static const char *at76_get_cmd_status_string(u8 cmd_status)
743 {
744         switch (cmd_status) {
745                 MAKE_CMD_STATUS_CASE(CMD_STATUS_IDLE);
746                 MAKE_CMD_STATUS_CASE(CMD_STATUS_COMPLETE);
747                 MAKE_CMD_STATUS_CASE(CMD_STATUS_UNKNOWN);
748                 MAKE_CMD_STATUS_CASE(CMD_STATUS_INVALID_PARAMETER);
749                 MAKE_CMD_STATUS_CASE(CMD_STATUS_FUNCTION_NOT_SUPPORTED);
750                 MAKE_CMD_STATUS_CASE(CMD_STATUS_TIME_OUT);
751                 MAKE_CMD_STATUS_CASE(CMD_STATUS_IN_PROGRESS);
752                 MAKE_CMD_STATUS_CASE(CMD_STATUS_HOST_FAILURE);
753                 MAKE_CMD_STATUS_CASE(CMD_STATUS_SCAN_FAILED);
754         }
755
756         return "UNKNOWN";
757 }
758
759 /* Wait until the command is completed */
760 static int at76_wait_completion(struct at76_priv *priv, int cmd)
761 {
762         int status = 0;
763         unsigned long timeout = jiffies + CMD_COMPLETION_TIMEOUT;
764
765         do {
766                 status = at76_get_cmd_status(priv->udev, cmd);
767                 if (status < 0) {
768                         wiphy_err(priv->hw->wiphy,
769                                   "at76_get_cmd_status failed: %d\n",
770                                   status);
771                         break;
772                 }
773
774                 at76_dbg(DBG_WAIT_COMPLETE,
775                          "%s: Waiting on cmd %d, status = %d (%s)",
776                          wiphy_name(priv->hw->wiphy), cmd, status,
777                          at76_get_cmd_status_string(status));
778
779                 if (status != CMD_STATUS_IN_PROGRESS
780                     && status != CMD_STATUS_IDLE)
781                         break;
782
783                 schedule_timeout_interruptible(HZ / 10);        /* 100 ms */
784                 if (time_after(jiffies, timeout)) {
785                         wiphy_err(priv->hw->wiphy,
786                                   "completion timeout for command %d\n", cmd);
787                         status = -ETIMEDOUT;
788                         break;
789                 }
790         } while (1);
791
792         return status;
793 }
794
795 static int at76_set_mib(struct at76_priv *priv, struct set_mib_buffer *buf)
796 {
797         int ret;
798
799         ret = at76_set_card_command(priv->udev, CMD_SET_MIB, buf,
800                                     offsetof(struct set_mib_buffer,
801                                              data) + buf->size);
802         if (ret < 0)
803                 return ret;
804
805         ret = at76_wait_completion(priv, CMD_SET_MIB);
806         if (ret != CMD_STATUS_COMPLETE) {
807                 wiphy_info(priv->hw->wiphy,
808                            "set_mib: at76_wait_completion failed with %d\n",
809                            ret);
810                 ret = -EIO;
811         }
812
813         return ret;
814 }
815
816 /* Return < 0 on error, == 0 if no command sent, == 1 if cmd sent */
817 static int at76_set_radio(struct at76_priv *priv, int enable)
818 {
819         int ret;
820         int cmd;
821
822         if (priv->radio_on == enable)
823                 return 0;
824
825         cmd = enable ? CMD_RADIO_ON : CMD_RADIO_OFF;
826
827         ret = at76_set_card_command(priv->udev, cmd, NULL, 0);
828         if (ret < 0)
829                 wiphy_err(priv->hw->wiphy,
830                           "at76_set_card_command(%d) failed: %d\n", cmd, ret);
831         else
832                 ret = 1;
833
834         priv->radio_on = enable;
835         return ret;
836 }
837
838 /* Set current power save mode (AT76_PM_OFF/AT76_PM_ON/AT76_PM_SMART) */
839 static int at76_set_pm_mode(struct at76_priv *priv)
840 {
841         int ret = 0;
842
843         priv->mib_buf.type = MIB_MAC_MGMT;
844         priv->mib_buf.size = 1;
845         priv->mib_buf.index = offsetof(struct mib_mac_mgmt, power_mgmt_mode);
846         priv->mib_buf.data.byte = priv->pm_mode;
847
848         ret = at76_set_mib(priv, &priv->mib_buf);
849         if (ret < 0)
850                 wiphy_err(priv->hw->wiphy, "set_mib (pm_mode) failed: %d\n",
851                           ret);
852
853         return ret;
854 }
855
856 static int at76_set_preamble(struct at76_priv *priv, u8 type)
857 {
858         int ret = 0;
859
860         priv->mib_buf.type = MIB_LOCAL;
861         priv->mib_buf.size = 1;
862         priv->mib_buf.index = offsetof(struct mib_local, preamble_type);
863         priv->mib_buf.data.byte = type;
864
865         ret = at76_set_mib(priv, &priv->mib_buf);
866         if (ret < 0)
867                 wiphy_err(priv->hw->wiphy, "set_mib (preamble) failed: %d\n",
868                           ret);
869
870         return ret;
871 }
872
873 static int at76_set_frag(struct at76_priv *priv, u16 size)
874 {
875         int ret = 0;
876
877         priv->mib_buf.type = MIB_MAC;
878         priv->mib_buf.size = 2;
879         priv->mib_buf.index = offsetof(struct mib_mac, frag_threshold);
880         priv->mib_buf.data.word = cpu_to_le16(size);
881
882         ret = at76_set_mib(priv, &priv->mib_buf);
883         if (ret < 0)
884                 wiphy_err(priv->hw->wiphy,
885                           "set_mib (frag threshold) failed: %d\n", ret);
886
887         return ret;
888 }
889
890 static int at76_set_rts(struct at76_priv *priv, u16 size)
891 {
892         int ret = 0;
893
894         priv->mib_buf.type = MIB_MAC;
895         priv->mib_buf.size = 2;
896         priv->mib_buf.index = offsetof(struct mib_mac, rts_threshold);
897         priv->mib_buf.data.word = cpu_to_le16(size);
898
899         ret = at76_set_mib(priv, &priv->mib_buf);
900         if (ret < 0)
901                 wiphy_err(priv->hw->wiphy, "set_mib (rts) failed: %d\n", ret);
902
903         return ret;
904 }
905
906 static int at76_set_autorate_fallback(struct at76_priv *priv, int onoff)
907 {
908         int ret = 0;
909
910         priv->mib_buf.type = MIB_LOCAL;
911         priv->mib_buf.size = 1;
912         priv->mib_buf.index = offsetof(struct mib_local, txautorate_fallback);
913         priv->mib_buf.data.byte = onoff;
914
915         ret = at76_set_mib(priv, &priv->mib_buf);
916         if (ret < 0)
917                 wiphy_err(priv->hw->wiphy,
918                           "set_mib (autorate fallback) failed: %d\n", ret);
919
920         return ret;
921 }
922
923 static void at76_dump_mib_mac_addr(struct at76_priv *priv)
924 {
925         int i;
926         int ret;
927         struct mib_mac_addr *m = kmalloc(sizeof(struct mib_mac_addr),
928                                          GFP_KERNEL);
929
930         if (!m)
931                 return;
932
933         ret = at76_get_mib(priv->udev, MIB_MAC_ADDR, m,
934                            sizeof(struct mib_mac_addr));
935         if (ret < 0) {
936                 wiphy_err(priv->hw->wiphy,
937                           "at76_get_mib (MAC_ADDR) failed: %d\n", ret);
938                 goto exit;
939         }
940
941         at76_dbg(DBG_MIB, "%s: MIB MAC_ADDR: mac_addr %pM res 0x%x 0x%x",
942                  wiphy_name(priv->hw->wiphy),
943                  m->mac_addr, m->res[0], m->res[1]);
944         for (i = 0; i < ARRAY_SIZE(m->group_addr); i++)
945                 at76_dbg(DBG_MIB, "%s: MIB MAC_ADDR: group addr %d: %pM, "
946                          "status %d", wiphy_name(priv->hw->wiphy), i,
947                          m->group_addr[i], m->group_addr_status[i]);
948 exit:
949         kfree(m);
950 }
951
952 static void at76_dump_mib_mac_wep(struct at76_priv *priv)
953 {
954         int i;
955         int ret;
956         int key_len;
957         struct mib_mac_wep *m = kmalloc(sizeof(struct mib_mac_wep), GFP_KERNEL);
958
959         if (!m)
960                 return;
961
962         ret = at76_get_mib(priv->udev, MIB_MAC_WEP, m,
963                            sizeof(struct mib_mac_wep));
964         if (ret < 0) {
965                 wiphy_err(priv->hw->wiphy,
966                           "at76_get_mib (MAC_WEP) failed: %d\n", ret);
967                 goto exit;
968         }
969
970         at76_dbg(DBG_MIB, "%s: MIB MAC_WEP: priv_invoked %u def_key_id %u "
971                  "key_len %u excl_unencr %u wep_icv_err %u wep_excluded %u "
972                  "encr_level %u key %d", wiphy_name(priv->hw->wiphy),
973                  m->privacy_invoked, m->wep_default_key_id,
974                  m->wep_key_mapping_len, m->exclude_unencrypted,
975                  le32_to_cpu(m->wep_icv_error_count),
976                  le32_to_cpu(m->wep_excluded_count), m->encryption_level,
977                  m->wep_default_key_id);
978
979         key_len = (m->encryption_level == 1) ?
980             WEP_SMALL_KEY_LEN : WEP_LARGE_KEY_LEN;
981
982         for (i = 0; i < WEP_KEYS; i++)
983                 at76_dbg(DBG_MIB, "%s: MIB MAC_WEP: key %d: %*phD",
984                          wiphy_name(priv->hw->wiphy), i,
985                          key_len, m->wep_default_keyvalue[i]);
986 exit:
987         kfree(m);
988 }
989
990 static void at76_dump_mib_mac_mgmt(struct at76_priv *priv)
991 {
992         int ret;
993         struct mib_mac_mgmt *m = kmalloc(sizeof(struct mib_mac_mgmt),
994                                          GFP_KERNEL);
995
996         if (!m)
997                 return;
998
999         ret = at76_get_mib(priv->udev, MIB_MAC_MGMT, m,
1000                            sizeof(struct mib_mac_mgmt));
1001         if (ret < 0) {
1002                 wiphy_err(priv->hw->wiphy,
1003                           "at76_get_mib (MAC_MGMT) failed: %d\n", ret);
1004                 goto exit;
1005         }
1006
1007         at76_dbg(DBG_MIB, "%s: MIB MAC_MGMT: beacon_period %d CFP_max_duration "
1008                  "%d medium_occupancy_limit %d station_id 0x%x ATIM_window %d "
1009                  "CFP_mode %d privacy_opt_impl %d DTIM_period %d CFP_period %d "
1010                  "current_bssid %pM current_essid %*phD current_bss_type %d "
1011                  "pm_mode %d ibss_change %d res %d "
1012                  "multi_domain_capability_implemented %d "
1013                  "international_roaming %d country_string %.3s",
1014                  wiphy_name(priv->hw->wiphy), le16_to_cpu(m->beacon_period),
1015                  le16_to_cpu(m->CFP_max_duration),
1016                  le16_to_cpu(m->medium_occupancy_limit),
1017                  le16_to_cpu(m->station_id), le16_to_cpu(m->ATIM_window),
1018                  m->CFP_mode, m->privacy_option_implemented, m->DTIM_period,
1019                  m->CFP_period, m->current_bssid,
1020                  IW_ESSID_MAX_SIZE, m->current_essid,
1021                  m->current_bss_type, m->power_mgmt_mode, m->ibss_change,
1022                  m->res, m->multi_domain_capability_implemented,
1023                  m->multi_domain_capability_enabled, m->country_string);
1024 exit:
1025         kfree(m);
1026 }
1027
1028 static void at76_dump_mib_mac(struct at76_priv *priv)
1029 {
1030         int ret;
1031         struct mib_mac *m = kmalloc(sizeof(struct mib_mac), GFP_KERNEL);
1032
1033         if (!m)
1034                 return;
1035
1036         ret = at76_get_mib(priv->udev, MIB_MAC, m, sizeof(struct mib_mac));
1037         if (ret < 0) {
1038                 wiphy_err(priv->hw->wiphy,
1039                           "at76_get_mib (MAC) failed: %d\n", ret);
1040                 goto exit;
1041         }
1042
1043         at76_dbg(DBG_MIB, "%s: MIB MAC: max_tx_msdu_lifetime %d "
1044                  "max_rx_lifetime %d frag_threshold %d rts_threshold %d "
1045                  "cwmin %d cwmax %d short_retry_time %d long_retry_time %d "
1046                  "scan_type %d scan_channel %d probe_delay %u "
1047                  "min_channel_time %d max_channel_time %d listen_int %d "
1048                  "desired_ssid %*phD desired_bssid %pM desired_bsstype %d",
1049                  wiphy_name(priv->hw->wiphy),
1050                  le32_to_cpu(m->max_tx_msdu_lifetime),
1051                  le32_to_cpu(m->max_rx_lifetime),
1052                  le16_to_cpu(m->frag_threshold), le16_to_cpu(m->rts_threshold),
1053                  le16_to_cpu(m->cwmin), le16_to_cpu(m->cwmax),
1054                  m->short_retry_time, m->long_retry_time, m->scan_type,
1055                  m->scan_channel, le16_to_cpu(m->probe_delay),
1056                  le16_to_cpu(m->min_channel_time),
1057                  le16_to_cpu(m->max_channel_time),
1058                  le16_to_cpu(m->listen_interval),
1059                  IW_ESSID_MAX_SIZE, m->desired_ssid,
1060                  m->desired_bssid, m->desired_bsstype);
1061 exit:
1062         kfree(m);
1063 }
1064
1065 static void at76_dump_mib_phy(struct at76_priv *priv)
1066 {
1067         int ret;
1068         struct mib_phy *m = kmalloc(sizeof(struct mib_phy), GFP_KERNEL);
1069
1070         if (!m)
1071                 return;
1072
1073         ret = at76_get_mib(priv->udev, MIB_PHY, m, sizeof(struct mib_phy));
1074         if (ret < 0) {
1075                 wiphy_err(priv->hw->wiphy,
1076                           "at76_get_mib (PHY) failed: %d\n", ret);
1077                 goto exit;
1078         }
1079
1080         at76_dbg(DBG_MIB, "%s: MIB PHY: ed_threshold %d slot_time %d "
1081                  "sifs_time %d preamble_length %d plcp_header_length %d "
1082                  "mpdu_max_length %d cca_mode_supported %d operation_rate_set "
1083                  "0x%x 0x%x 0x%x 0x%x channel_id %d current_cca_mode %d "
1084                  "phy_type %d current_reg_domain %d",
1085                  wiphy_name(priv->hw->wiphy), le32_to_cpu(m->ed_threshold),
1086                  le16_to_cpu(m->slot_time), le16_to_cpu(m->sifs_time),
1087                  le16_to_cpu(m->preamble_length),
1088                  le16_to_cpu(m->plcp_header_length),
1089                  le16_to_cpu(m->mpdu_max_length),
1090                  le16_to_cpu(m->cca_mode_supported), m->operation_rate_set[0],
1091                  m->operation_rate_set[1], m->operation_rate_set[2],
1092                  m->operation_rate_set[3], m->channel_id, m->current_cca_mode,
1093                  m->phy_type, m->current_reg_domain);
1094 exit:
1095         kfree(m);
1096 }
1097
1098 static void at76_dump_mib_local(struct at76_priv *priv)
1099 {
1100         int ret;
1101         struct mib_local *m = kmalloc(sizeof(*m), GFP_KERNEL);
1102
1103         if (!m)
1104                 return;
1105
1106         ret = at76_get_mib(priv->udev, MIB_LOCAL, m, sizeof(*m));
1107         if (ret < 0) {
1108                 wiphy_err(priv->hw->wiphy,
1109                           "at76_get_mib (LOCAL) failed: %d\n", ret);
1110                 goto exit;
1111         }
1112
1113         at76_dbg(DBG_MIB, "%s: MIB LOCAL: beacon_enable %d "
1114                  "txautorate_fallback %d ssid_size %d promiscuous_mode %d "
1115                  "preamble_type %d", wiphy_name(priv->hw->wiphy),
1116                  m->beacon_enable,
1117                  m->txautorate_fallback, m->ssid_size, m->promiscuous_mode,
1118                  m->preamble_type);
1119 exit:
1120         kfree(m);
1121 }
1122
1123 static void at76_dump_mib_mdomain(struct at76_priv *priv)
1124 {
1125         int ret;
1126         struct mib_mdomain *m = kmalloc(sizeof(struct mib_mdomain), GFP_KERNEL);
1127
1128         if (!m)
1129                 return;
1130
1131         ret = at76_get_mib(priv->udev, MIB_MDOMAIN, m,
1132                            sizeof(struct mib_mdomain));
1133         if (ret < 0) {
1134                 wiphy_err(priv->hw->wiphy,
1135                           "at76_get_mib (MDOMAIN) failed: %d\n", ret);
1136                 goto exit;
1137         }
1138
1139         at76_dbg(DBG_MIB, "%s: MIB MDOMAIN: channel_list %*phD",
1140                  wiphy_name(priv->hw->wiphy),
1141                  (int)sizeof(m->channel_list), m->channel_list);
1142
1143         at76_dbg(DBG_MIB, "%s: MIB MDOMAIN: tx_powerlevel %*phD",
1144                  wiphy_name(priv->hw->wiphy),
1145                  (int)sizeof(m->tx_powerlevel), m->tx_powerlevel);
1146 exit:
1147         kfree(m);
1148 }
1149
1150 /* Enable monitor mode */
1151 static int at76_start_monitor(struct at76_priv *priv)
1152 {
1153         struct at76_req_scan scan;
1154         int ret;
1155
1156         memset(&scan, 0, sizeof(struct at76_req_scan));
1157         eth_broadcast_addr(scan.bssid);
1158
1159         scan.channel = priv->channel;
1160         scan.scan_type = SCAN_TYPE_PASSIVE;
1161         scan.international_scan = 0;
1162         scan.min_channel_time = cpu_to_le16(priv->scan_min_time);
1163         scan.max_channel_time = cpu_to_le16(priv->scan_max_time);
1164         scan.probe_delay = cpu_to_le16(0);
1165
1166         ret = at76_set_card_command(priv->udev, CMD_SCAN, &scan, sizeof(scan));
1167         if (ret >= 0)
1168                 ret = at76_get_cmd_status(priv->udev, CMD_SCAN);
1169
1170         return ret;
1171 }
1172
1173 /* Calculate padding from txbuf->wlength (which excludes the USB TX header),
1174    likely to compensate a flaw in the AT76C503A USB part ... */
1175 static inline int at76_calc_padding(int wlen)
1176 {
1177         /* add the USB TX header */
1178         wlen += AT76_TX_HDRLEN;
1179
1180         wlen = wlen % 64;
1181
1182         if (wlen < 50)
1183                 return 50 - wlen;
1184
1185         if (wlen >= 61)
1186                 return 64 + 50 - wlen;
1187
1188         return 0;
1189 }
1190
1191 static void at76_rx_callback(struct urb *urb)
1192 {
1193         struct at76_priv *priv = urb->context;
1194
1195         tasklet_schedule(&priv->rx_tasklet);
1196 }
1197
1198 static int at76_submit_rx_urb(struct at76_priv *priv)
1199 {
1200         int ret;
1201         int size;
1202         struct sk_buff *skb = priv->rx_skb;
1203
1204         if (!priv->rx_urb) {
1205                 wiphy_err(priv->hw->wiphy, "%s: priv->rx_urb is NULL\n",
1206                           __func__);
1207                 return -EFAULT;
1208         }
1209
1210         if (!skb) {
1211                 skb = dev_alloc_skb(sizeof(struct at76_rx_buffer));
1212                 if (!skb) {
1213                         wiphy_err(priv->hw->wiphy,
1214                                   "cannot allocate rx skbuff\n");
1215                         ret = -ENOMEM;
1216                         goto exit;
1217                 }
1218                 priv->rx_skb = skb;
1219         } else {
1220                 skb_push(skb, skb_headroom(skb));
1221                 skb_trim(skb, 0);
1222         }
1223
1224         size = skb_tailroom(skb);
1225         usb_fill_bulk_urb(priv->rx_urb, priv->udev, priv->rx_pipe,
1226                           skb_put(skb, size), size, at76_rx_callback, priv);
1227         ret = usb_submit_urb(priv->rx_urb, GFP_ATOMIC);
1228         if (ret < 0) {
1229                 if (ret == -ENODEV)
1230                         at76_dbg(DBG_DEVSTART,
1231                                  "usb_submit_urb returned -ENODEV");
1232                 else
1233                         wiphy_err(priv->hw->wiphy,
1234                                   "rx, usb_submit_urb failed: %d\n", ret);
1235         }
1236
1237 exit:
1238         if (ret < 0 && ret != -ENODEV)
1239                 wiphy_err(priv->hw->wiphy,
1240                           "cannot submit rx urb - please unload the driver and/or power cycle the device\n");
1241
1242         return ret;
1243 }
1244
1245 /* Download external firmware */
1246 static int at76_load_external_fw(struct usb_device *udev, struct fwentry *fwe)
1247 {
1248         int ret;
1249         int op_mode;
1250         int blockno = 0;
1251         int bsize;
1252         u8 *block;
1253         u8 *buf = fwe->extfw;
1254         int size = fwe->extfw_size;
1255
1256         if (!buf || !size)
1257                 return -ENOENT;
1258
1259         op_mode = at76_get_op_mode(udev);
1260         at76_dbg(DBG_DEVSTART, "opmode %d", op_mode);
1261
1262         if (op_mode != OPMODE_NORMAL_NIC_WITHOUT_FLASH) {
1263                 dev_err(&udev->dev, "unexpected opmode %d\n", op_mode);
1264                 return -EINVAL;
1265         }
1266
1267         block = kmalloc(FW_BLOCK_SIZE, GFP_KERNEL);
1268         if (!block)
1269                 return -ENOMEM;
1270
1271         at76_dbg(DBG_DEVSTART, "downloading external firmware");
1272
1273         /* for fw >= 0.100, the device needs an extra empty block */
1274         do {
1275                 bsize = min_t(int, size, FW_BLOCK_SIZE);
1276                 memcpy(block, buf, bsize);
1277                 at76_dbg(DBG_DEVSTART,
1278                          "ext fw, size left = %5d, bsize = %4d, blockno = %2d",
1279                          size, bsize, blockno);
1280                 ret = at76_load_ext_fw_block(udev, blockno, block, bsize);
1281                 if (ret != bsize) {
1282                         dev_err(&udev->dev,
1283                                 "loading %dth firmware block failed: %d\n",
1284                                 blockno, ret);
1285                         ret = -EIO;
1286                         goto exit;
1287                 }
1288                 buf += bsize;
1289                 size -= bsize;
1290                 blockno++;
1291         } while (bsize > 0);
1292
1293         if (at76_is_505a(fwe->board_type)) {
1294                 at76_dbg(DBG_DEVSTART, "200 ms delay for 505a");
1295                 schedule_timeout_interruptible(HZ / 5 + 1);
1296         }
1297
1298 exit:
1299         kfree(block);
1300         if (ret < 0)
1301                 dev_err(&udev->dev,
1302                         "downloading external firmware failed: %d\n", ret);
1303         return ret;
1304 }
1305
1306 /* Download internal firmware */
1307 static int at76_load_internal_fw(struct usb_device *udev, struct fwentry *fwe)
1308 {
1309         int ret;
1310         int need_remap = !at76_is_505a(fwe->board_type);
1311
1312         ret = at76_usbdfu_download(udev, fwe->intfw, fwe->intfw_size,
1313                                    need_remap ? 0 : 2 * HZ);
1314
1315         if (ret < 0) {
1316                 dev_err(&udev->dev,
1317                         "downloading internal fw failed with %d\n", ret);
1318                 goto exit;
1319         }
1320
1321         at76_dbg(DBG_DEVSTART, "sending REMAP");
1322
1323         /* no REMAP for 505A (see SF driver) */
1324         if (need_remap) {
1325                 ret = at76_remap(udev);
1326                 if (ret < 0) {
1327                         dev_err(&udev->dev,
1328                                 "sending REMAP failed with %d\n", ret);
1329                         goto exit;
1330                 }
1331         }
1332
1333         at76_dbg(DBG_DEVSTART, "sleeping for 2 seconds");
1334         schedule_timeout_interruptible(2 * HZ + 1);
1335         usb_reset_device(udev);
1336
1337 exit:
1338         return ret;
1339 }
1340
1341 static int at76_startup_device(struct at76_priv *priv)
1342 {
1343         struct at76_card_config *ccfg = &priv->card_config;
1344         int ret;
1345
1346         at76_dbg(DBG_PARAMS,
1347                  "%s param: ssid %.*s (%*phD) mode %s ch %d wep %s key %d "
1348                  "keylen %d", wiphy_name(priv->hw->wiphy), priv->essid_size,
1349                  priv->essid, IW_ESSID_MAX_SIZE, priv->essid,
1350                  priv->iw_mode == IW_MODE_ADHOC ? "adhoc" : "infra",
1351                  priv->channel, priv->wep_enabled ? "enabled" : "disabled",
1352                  priv->wep_key_id, priv->wep_keys_len[priv->wep_key_id]);
1353         at76_dbg(DBG_PARAMS,
1354                  "%s param: preamble %s rts %d retry %d frag %d "
1355                  "txrate %s auth_mode %d", wiphy_name(priv->hw->wiphy),
1356                  preambles[priv->preamble_type], priv->rts_threshold,
1357                  priv->short_retry_limit, priv->frag_threshold,
1358                  priv->txrate == TX_RATE_1MBIT ? "1MBit" : priv->txrate ==
1359                  TX_RATE_2MBIT ? "2MBit" : priv->txrate ==
1360                  TX_RATE_5_5MBIT ? "5.5MBit" : priv->txrate ==
1361                  TX_RATE_11MBIT ? "11MBit" : priv->txrate ==
1362                  TX_RATE_AUTO ? "auto" : "<invalid>", priv->auth_mode);
1363         at76_dbg(DBG_PARAMS,
1364                  "%s param: pm_mode %d pm_period %d auth_mode %s "
1365                  "scan_times %d %d scan_mode %s",
1366                  wiphy_name(priv->hw->wiphy), priv->pm_mode, priv->pm_period,
1367                  priv->auth_mode == WLAN_AUTH_OPEN ? "open" : "shared_secret",
1368                  priv->scan_min_time, priv->scan_max_time,
1369                  priv->scan_mode == SCAN_TYPE_ACTIVE ? "active" : "passive");
1370
1371         memset(ccfg, 0, sizeof(struct at76_card_config));
1372         ccfg->promiscuous_mode = 0;
1373         ccfg->short_retry_limit = priv->short_retry_limit;
1374
1375         if (priv->wep_enabled) {
1376                 if (priv->wep_keys_len[priv->wep_key_id] > WEP_SMALL_KEY_LEN)
1377                         ccfg->encryption_type = 2;
1378                 else
1379                         ccfg->encryption_type = 1;
1380
1381                 /* jal: always exclude unencrypted if WEP is active */
1382                 ccfg->exclude_unencrypted = 1;
1383         } else {
1384                 ccfg->exclude_unencrypted = 0;
1385                 ccfg->encryption_type = 0;
1386         }
1387
1388         ccfg->rts_threshold = cpu_to_le16(priv->rts_threshold);
1389         ccfg->fragmentation_threshold = cpu_to_le16(priv->frag_threshold);
1390
1391         memcpy(ccfg->basic_rate_set, hw_rates, 4);
1392         /* jal: really needed, we do a set_mib for autorate later ??? */
1393         ccfg->auto_rate_fallback = (priv->txrate == TX_RATE_AUTO ? 1 : 0);
1394         ccfg->channel = priv->channel;
1395         ccfg->privacy_invoked = priv->wep_enabled;
1396         memcpy(ccfg->current_ssid, priv->essid, IW_ESSID_MAX_SIZE);
1397         ccfg->ssid_len = priv->essid_size;
1398
1399         ccfg->wep_default_key_id = priv->wep_key_id;
1400         memcpy(ccfg->wep_default_key_value, priv->wep_keys,
1401                sizeof(priv->wep_keys));
1402
1403         ccfg->short_preamble = priv->preamble_type;
1404         ccfg->beacon_period = cpu_to_le16(priv->beacon_period);
1405
1406         ret = at76_set_card_command(priv->udev, CMD_STARTUP, &priv->card_config,
1407                                     sizeof(struct at76_card_config));
1408         if (ret < 0) {
1409                 wiphy_err(priv->hw->wiphy, "at76_set_card_command failed: %d\n",
1410                           ret);
1411                 return ret;
1412         }
1413
1414         at76_wait_completion(priv, CMD_STARTUP);
1415
1416         /* remove BSSID from previous run */
1417         eth_zero_addr(priv->bssid);
1418
1419         priv->scanning = false;
1420
1421         if (at76_set_radio(priv, 1) == 1)
1422                 at76_wait_completion(priv, CMD_RADIO_ON);
1423
1424         ret = at76_set_preamble(priv, priv->preamble_type);
1425         if (ret < 0)
1426                 return ret;
1427
1428         ret = at76_set_frag(priv, priv->frag_threshold);
1429         if (ret < 0)
1430                 return ret;
1431
1432         ret = at76_set_rts(priv, priv->rts_threshold);
1433         if (ret < 0)
1434                 return ret;
1435
1436         ret = at76_set_autorate_fallback(priv,
1437                                          priv->txrate == TX_RATE_AUTO ? 1 : 0);
1438         if (ret < 0)
1439                 return ret;
1440
1441         ret = at76_set_pm_mode(priv);
1442         if (ret < 0)
1443                 return ret;
1444
1445         if (at76_debug & DBG_MIB) {
1446                 at76_dump_mib_mac(priv);
1447                 at76_dump_mib_mac_addr(priv);
1448                 at76_dump_mib_mac_mgmt(priv);
1449                 at76_dump_mib_mac_wep(priv);
1450                 at76_dump_mib_mdomain(priv);
1451                 at76_dump_mib_phy(priv);
1452                 at76_dump_mib_local(priv);
1453         }
1454
1455         return 0;
1456 }
1457
1458 /* Enable or disable promiscuous mode */
1459 static void at76_work_set_promisc(struct work_struct *work)
1460 {
1461         struct at76_priv *priv = container_of(work, struct at76_priv,
1462                                               work_set_promisc);
1463         int ret = 0;
1464
1465         if (priv->device_unplugged)
1466                 return;
1467
1468         mutex_lock(&priv->mtx);
1469
1470         priv->mib_buf.type = MIB_LOCAL;
1471         priv->mib_buf.size = 1;
1472         priv->mib_buf.index = offsetof(struct mib_local, promiscuous_mode);
1473         priv->mib_buf.data.byte = priv->promisc ? 1 : 0;
1474
1475         ret = at76_set_mib(priv, &priv->mib_buf);
1476         if (ret < 0)
1477                 wiphy_err(priv->hw->wiphy,
1478                           "set_mib (promiscuous_mode) failed: %d\n", ret);
1479
1480         mutex_unlock(&priv->mtx);
1481 }
1482
1483 /* Submit Rx urb back to the device */
1484 static void at76_work_submit_rx(struct work_struct *work)
1485 {
1486         struct at76_priv *priv = container_of(work, struct at76_priv,
1487                                               work_submit_rx);
1488
1489         mutex_lock(&priv->mtx);
1490         at76_submit_rx_urb(priv);
1491         mutex_unlock(&priv->mtx);
1492 }
1493
1494 /* This is a workaround to make scan working:
1495  * currently mac80211 does not process frames with no frequency
1496  * information.
1497  * However during scan the HW performs a sweep by itself, and we
1498  * are unable to know where the radio is actually tuned.
1499  * This function tries to do its best to guess this information..
1500  * During scan, If the current frame is a beacon or a probe response,
1501  * the channel information is extracted from it.
1502  * When not scanning, for other frames, or if it happens that for
1503  * whatever reason we fail to parse beacons and probe responses, this
1504  * function returns the priv->channel information, that should be correct
1505  * at least when we are not scanning.
1506  */
1507 static inline int at76_guess_freq(struct at76_priv *priv)
1508 {
1509         size_t el_off;
1510         const u8 *el;
1511         int channel = priv->channel;
1512         int len = priv->rx_skb->len;
1513         struct ieee80211_hdr *hdr = (void *)priv->rx_skb->data;
1514
1515         if (!priv->scanning)
1516                 goto exit;
1517
1518         if (len < 24)
1519                 goto exit;
1520
1521         if (ieee80211_is_probe_resp(hdr->frame_control)) {
1522                 el_off = offsetof(struct ieee80211_mgmt, u.probe_resp.variable);
1523                 el = ((struct ieee80211_mgmt *)hdr)->u.probe_resp.variable;
1524         } else if (ieee80211_is_beacon(hdr->frame_control)) {
1525                 el_off = offsetof(struct ieee80211_mgmt, u.beacon.variable);
1526                 el = ((struct ieee80211_mgmt *)hdr)->u.beacon.variable;
1527         } else {
1528                 goto exit;
1529         }
1530         len -= el_off;
1531
1532         el = cfg80211_find_ie(WLAN_EID_DS_PARAMS, el, len);
1533         if (el && el[1] > 0)
1534                 channel = el[2];
1535
1536 exit:
1537         return ieee80211_channel_to_frequency(channel, NL80211_BAND_2GHZ);
1538 }
1539
1540 static void at76_rx_tasklet(struct tasklet_struct *t)
1541 {
1542         struct at76_priv *priv = from_tasklet(priv, t, rx_tasklet);
1543         struct urb *urb = priv->rx_urb;
1544         struct at76_rx_buffer *buf;
1545         struct ieee80211_rx_status rx_status = { 0 };
1546
1547         if (priv->device_unplugged) {
1548                 at76_dbg(DBG_DEVSTART, "device unplugged");
1549                 at76_dbg(DBG_DEVSTART, "urb status %d", urb->status);
1550                 return;
1551         }
1552
1553         if (!priv->rx_skb || !priv->rx_skb->data)
1554                 return;
1555
1556         buf = (struct at76_rx_buffer *)priv->rx_skb->data;
1557
1558         if (urb->status != 0) {
1559                 if (urb->status != -ENOENT && urb->status != -ECONNRESET)
1560                         at76_dbg(DBG_URB,
1561                                  "%s %s: - nonzero Rx bulk status received: %d",
1562                                  __func__, wiphy_name(priv->hw->wiphy),
1563                                  urb->status);
1564                 return;
1565         }
1566
1567         at76_dbg(DBG_RX_ATMEL_HDR,
1568                  "%s: rx frame: rate %d rssi %d noise %d link %d",
1569                  wiphy_name(priv->hw->wiphy), buf->rx_rate, buf->rssi,
1570                  buf->noise_level, buf->link_quality);
1571
1572         skb_pull(priv->rx_skb, AT76_RX_HDRLEN);
1573         skb_trim(priv->rx_skb, le16_to_cpu(buf->wlength));
1574         at76_dbg_dump(DBG_RX_DATA, priv->rx_skb->data,
1575                       priv->rx_skb->len, "RX: len=%d", priv->rx_skb->len);
1576
1577         rx_status.signal = buf->rssi;
1578         rx_status.flag |= RX_FLAG_DECRYPTED;
1579         rx_status.flag |= RX_FLAG_IV_STRIPPED;
1580         rx_status.band = NL80211_BAND_2GHZ;
1581         rx_status.freq = at76_guess_freq(priv);
1582
1583         at76_dbg(DBG_MAC80211, "calling ieee80211_rx_irqsafe(): %d/%d",
1584                  priv->rx_skb->len, priv->rx_skb->data_len);
1585         memcpy(IEEE80211_SKB_RXCB(priv->rx_skb), &rx_status, sizeof(rx_status));
1586         ieee80211_rx_irqsafe(priv->hw, priv->rx_skb);
1587
1588         /* Use a new skb for the next receive */
1589         priv->rx_skb = NULL;
1590
1591         at76_submit_rx_urb(priv);
1592 }
1593
1594 /* Load firmware into kernel memory and parse it */
1595 static struct fwentry *at76_load_firmware(struct usb_device *udev,
1596                                           enum board_type board_type)
1597 {
1598         int ret;
1599         char *str;
1600         struct at76_fw_header *fwh;
1601         struct fwentry *fwe = &firmwares[board_type];
1602
1603         mutex_lock(&fw_mutex);
1604
1605         if (fwe->loaded) {
1606                 at76_dbg(DBG_FW, "re-using previously loaded fw");
1607                 goto exit;
1608         }
1609
1610         at76_dbg(DBG_FW, "downloading firmware %s", fwe->fwname);
1611         ret = reject_firmware(&fwe->fw, fwe->fwname, &udev->dev);
1612         if (ret < 0) {
1613                 dev_err(&udev->dev, "firmware %s not found!\n",
1614                         fwe->fwname);
1615                 dev_err(&udev->dev,
1616                         "you may need to download the firmware from http://developer.berlios.de/projects/at76c503a/\n");
1617                 goto exit;
1618         }
1619
1620         at76_dbg(DBG_FW, "got it.");
1621         fwh = (struct at76_fw_header *)(fwe->fw->data);
1622
1623         if (fwe->fw->size <= sizeof(*fwh)) {
1624                 dev_err(&udev->dev,
1625                         "firmware is too short (0x%zx)\n", fwe->fw->size);
1626                 goto exit;
1627         }
1628
1629         /* CRC currently not checked */
1630         fwe->board_type = le32_to_cpu(fwh->board_type);
1631         if (fwe->board_type != board_type) {
1632                 dev_err(&udev->dev,
1633                         "board type mismatch, requested %u, got %u\n",
1634                         board_type, fwe->board_type);
1635                 goto exit;
1636         }
1637
1638         fwe->fw_version.major = fwh->major;
1639         fwe->fw_version.minor = fwh->minor;
1640         fwe->fw_version.patch = fwh->patch;
1641         fwe->fw_version.build = fwh->build;
1642
1643         str = (char *)fwh + le32_to_cpu(fwh->str_offset);
1644         fwe->intfw = (u8 *)fwh + le32_to_cpu(fwh->int_fw_offset);
1645         fwe->intfw_size = le32_to_cpu(fwh->int_fw_len);
1646         fwe->extfw = (u8 *)fwh + le32_to_cpu(fwh->ext_fw_offset);
1647         fwe->extfw_size = le32_to_cpu(fwh->ext_fw_len);
1648
1649         fwe->loaded = 1;
1650
1651         dev_printk(KERN_DEBUG, &udev->dev,
1652                    "using firmware %s (version %d.%d.%d-%d)\n",
1653                    fwe->fwname, fwh->major, fwh->minor, fwh->patch, fwh->build);
1654
1655         at76_dbg(DBG_DEVSTART, "board %u, int %d:%d, ext %d:%d", board_type,
1656                  le32_to_cpu(fwh->int_fw_offset), le32_to_cpu(fwh->int_fw_len),
1657                  le32_to_cpu(fwh->ext_fw_offset), le32_to_cpu(fwh->ext_fw_len));
1658         at76_dbg(DBG_DEVSTART, "firmware id %s", str);
1659
1660 exit:
1661         mutex_unlock(&fw_mutex);
1662
1663         if (fwe->loaded)
1664                 return fwe;
1665         else
1666                 return NULL;
1667 }
1668
1669 static int at76_join(struct at76_priv *priv)
1670 {
1671         struct at76_req_join join;
1672         int ret;
1673
1674         memset(&join, 0, sizeof(struct at76_req_join));
1675         memcpy(join.essid, priv->essid, priv->essid_size);
1676         join.essid_size = priv->essid_size;
1677         memcpy(join.bssid, priv->bssid, ETH_ALEN);
1678         join.bss_type = INFRASTRUCTURE_MODE;
1679         join.channel = priv->channel;
1680         join.timeout = cpu_to_le16(2000);
1681
1682         at76_dbg(DBG_MAC80211, "%s: sending CMD_JOIN", __func__);
1683         ret = at76_set_card_command(priv->udev, CMD_JOIN, &join,
1684                                     sizeof(struct at76_req_join));
1685
1686         if (ret < 0) {
1687                 wiphy_err(priv->hw->wiphy, "at76_set_card_command failed: %d\n",
1688                           ret);
1689                 return 0;
1690         }
1691
1692         ret = at76_wait_completion(priv, CMD_JOIN);
1693         at76_dbg(DBG_MAC80211, "%s: CMD_JOIN returned: 0x%02x", __func__, ret);
1694         if (ret != CMD_STATUS_COMPLETE) {
1695                 wiphy_err(priv->hw->wiphy, "at76_wait_completion failed: %d\n",
1696                           ret);
1697                 return 0;
1698         }
1699
1700         at76_set_pm_mode(priv);
1701
1702         return 0;
1703 }
1704
1705 static void at76_work_join_bssid(struct work_struct *work)
1706 {
1707         struct at76_priv *priv = container_of(work, struct at76_priv,
1708                                               work_join_bssid);
1709
1710         if (priv->device_unplugged)
1711                 return;
1712
1713         mutex_lock(&priv->mtx);
1714
1715         if (is_valid_ether_addr(priv->bssid))
1716                 at76_join(priv);
1717
1718         mutex_unlock(&priv->mtx);
1719 }
1720
1721 static void at76_mac80211_tx_callback(struct urb *urb)
1722 {
1723         struct at76_priv *priv = urb->context;
1724         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(priv->tx_skb);
1725
1726         at76_dbg(DBG_MAC80211, "%s()", __func__);
1727
1728         switch (urb->status) {
1729         case 0:
1730                 /* success */
1731                 info->flags |= IEEE80211_TX_STAT_ACK;
1732                 break;
1733         case -ENOENT:
1734         case -ECONNRESET:
1735                 /* fail, urb has been unlinked */
1736                 /* FIXME: add error message */
1737                 break;
1738         default:
1739                 at76_dbg(DBG_URB, "%s - nonzero tx status received: %d",
1740                          __func__, urb->status);
1741                 break;
1742         }
1743
1744         memset(&info->status, 0, sizeof(info->status));
1745
1746         ieee80211_tx_status_irqsafe(priv->hw, priv->tx_skb);
1747
1748         priv->tx_skb = NULL;
1749
1750         ieee80211_wake_queues(priv->hw);
1751 }
1752
1753 static void at76_mac80211_tx(struct ieee80211_hw *hw,
1754                              struct ieee80211_tx_control *control,
1755                              struct sk_buff *skb)
1756 {
1757         struct at76_priv *priv = hw->priv;
1758         struct at76_tx_buffer *tx_buffer = priv->bulk_out_buffer;
1759         struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb);
1760         struct ieee80211_mgmt *mgmt = (struct ieee80211_mgmt *)skb->data;
1761         int padding, submit_len, ret;
1762
1763         at76_dbg(DBG_MAC80211, "%s()", __func__);
1764
1765         if (priv->tx_urb->status == -EINPROGRESS) {
1766                 wiphy_err(priv->hw->wiphy,
1767                           "%s called while tx urb is pending\n", __func__);
1768                 dev_kfree_skb_any(skb);
1769                 return;
1770         }
1771
1772         /* The following code lines are important when the device is going to
1773          * authenticate with a new bssid. The driver must send CMD_JOIN before
1774          * an authentication frame is transmitted. For this to succeed, the
1775          * correct bssid of the AP must be known. As mac80211 does not inform
1776          * drivers about the bssid prior to the authentication process the
1777          * following workaround is necessary. If the TX frame is an
1778          * authentication frame extract the bssid and send the CMD_JOIN. */
1779         if (mgmt->frame_control & cpu_to_le16(IEEE80211_STYPE_AUTH)) {
1780                 if (!ether_addr_equal_64bits(priv->bssid, mgmt->bssid)) {
1781                         memcpy(priv->bssid, mgmt->bssid, ETH_ALEN);
1782                         ieee80211_queue_work(hw, &priv->work_join_bssid);
1783                         dev_kfree_skb_any(skb);
1784                         return;
1785                 }
1786         }
1787
1788         ieee80211_stop_queues(hw);
1789
1790         at76_ledtrig_tx_activity();     /* tell ledtrigger we send a packet */
1791
1792         WARN_ON(priv->tx_skb != NULL);
1793
1794         priv->tx_skb = skb;
1795         padding = at76_calc_padding(skb->len);
1796         submit_len = AT76_TX_HDRLEN + skb->len + padding;
1797
1798         /* setup 'Atmel' header */
1799         memset(tx_buffer, 0, sizeof(*tx_buffer));
1800         tx_buffer->padding = padding;
1801         tx_buffer->wlength = cpu_to_le16(skb->len);
1802         tx_buffer->tx_rate = ieee80211_get_tx_rate(hw, info)->hw_value;
1803         memset(tx_buffer->reserved, 0, sizeof(tx_buffer->reserved));
1804         memcpy(tx_buffer->packet, skb->data, skb->len);
1805
1806         at76_dbg(DBG_TX_DATA, "%s tx: wlen 0x%x pad 0x%x rate %d hdr",
1807                  wiphy_name(priv->hw->wiphy), le16_to_cpu(tx_buffer->wlength),
1808                  tx_buffer->padding, tx_buffer->tx_rate);
1809
1810         /* send stuff */
1811         at76_dbg_dump(DBG_TX_DATA_CONTENT, tx_buffer, submit_len,
1812                       "%s(): tx_buffer %d bytes:", __func__, submit_len);
1813         usb_fill_bulk_urb(priv->tx_urb, priv->udev, priv->tx_pipe, tx_buffer,
1814                           submit_len, at76_mac80211_tx_callback, priv);
1815         ret = usb_submit_urb(priv->tx_urb, GFP_ATOMIC);
1816         if (ret) {
1817                 wiphy_err(priv->hw->wiphy, "error in tx submit urb: %d\n", ret);
1818                 if (ret == -EINVAL)
1819                         wiphy_err(priv->hw->wiphy,
1820                                   "-EINVAL: tx urb %p hcpriv %p complete %p\n",
1821                                   priv->tx_urb,
1822                                   priv->tx_urb->hcpriv, priv->tx_urb->complete);
1823         }
1824 }
1825
1826 static int at76_mac80211_start(struct ieee80211_hw *hw)
1827 {
1828         struct at76_priv *priv = hw->priv;
1829         int ret;
1830
1831         at76_dbg(DBG_MAC80211, "%s()", __func__);
1832
1833         mutex_lock(&priv->mtx);
1834
1835         ret = at76_submit_rx_urb(priv);
1836         if (ret < 0) {
1837                 wiphy_err(priv->hw->wiphy, "open: submit_rx_urb failed: %d\n",
1838                           ret);
1839                 goto error;
1840         }
1841
1842         at76_startup_device(priv);
1843
1844         at76_start_monitor(priv);
1845
1846 error:
1847         mutex_unlock(&priv->mtx);
1848
1849         return 0;
1850 }
1851
1852 static void at76_mac80211_stop(struct ieee80211_hw *hw)
1853 {
1854         struct at76_priv *priv = hw->priv;
1855
1856         at76_dbg(DBG_MAC80211, "%s()", __func__);
1857
1858         cancel_delayed_work(&priv->dwork_hw_scan);
1859         cancel_work_sync(&priv->work_join_bssid);
1860         cancel_work_sync(&priv->work_set_promisc);
1861
1862         mutex_lock(&priv->mtx);
1863
1864         if (!priv->device_unplugged) {
1865                 /* We are called by "ifconfig ethX down", not because the
1866                  * device is not available anymore. */
1867                 at76_set_radio(priv, 0);
1868
1869                 /* We unlink rx_urb because at76_open() re-submits it.
1870                  * If unplugged, at76_delete_device() takes care of it. */
1871                 usb_kill_urb(priv->rx_urb);
1872         }
1873
1874         mutex_unlock(&priv->mtx);
1875 }
1876
1877 static int at76_add_interface(struct ieee80211_hw *hw,
1878                               struct ieee80211_vif *vif)
1879 {
1880         struct at76_priv *priv = hw->priv;
1881         int ret = 0;
1882
1883         at76_dbg(DBG_MAC80211, "%s()", __func__);
1884
1885         mutex_lock(&priv->mtx);
1886
1887         switch (vif->type) {
1888         case NL80211_IFTYPE_STATION:
1889                 priv->iw_mode = IW_MODE_INFRA;
1890                 break;
1891         default:
1892                 ret = -EOPNOTSUPP;
1893                 goto exit;
1894         }
1895
1896 exit:
1897         mutex_unlock(&priv->mtx);
1898
1899         return ret;
1900 }
1901
1902 static void at76_remove_interface(struct ieee80211_hw *hw,
1903                                   struct ieee80211_vif *vif)
1904 {
1905         at76_dbg(DBG_MAC80211, "%s()", __func__);
1906 }
1907
1908 static void at76_dwork_hw_scan(struct work_struct *work)
1909 {
1910         struct at76_priv *priv = container_of(work, struct at76_priv,
1911                                               dwork_hw_scan.work);
1912         struct cfg80211_scan_info info = {
1913                 .aborted = false,
1914         };
1915         int ret;
1916
1917         if (priv->device_unplugged)
1918                 return;
1919
1920         mutex_lock(&priv->mtx);
1921
1922         ret = at76_get_cmd_status(priv->udev, CMD_SCAN);
1923         at76_dbg(DBG_MAC80211, "%s: CMD_SCAN status 0x%02x", __func__, ret);
1924
1925         /* FIXME: add maximum time for scan to complete */
1926
1927         if (ret != CMD_STATUS_COMPLETE) {
1928                 ieee80211_queue_delayed_work(priv->hw, &priv->dwork_hw_scan,
1929                                              SCAN_POLL_INTERVAL);
1930                 mutex_unlock(&priv->mtx);
1931                 return;
1932         }
1933
1934         if (is_valid_ether_addr(priv->bssid))
1935                 at76_join(priv);
1936
1937         priv->scanning = false;
1938
1939         mutex_unlock(&priv->mtx);
1940
1941         ieee80211_scan_completed(priv->hw, &info);
1942
1943         ieee80211_wake_queues(priv->hw);
1944 }
1945
1946 static int at76_hw_scan(struct ieee80211_hw *hw,
1947                         struct ieee80211_vif *vif,
1948                         struct ieee80211_scan_request *hw_req)
1949 {
1950         struct cfg80211_scan_request *req = &hw_req->req;
1951         struct at76_priv *priv = hw->priv;
1952         struct at76_req_scan scan;
1953         u8 *ssid = NULL;
1954         int ret, len = 0;
1955
1956         at76_dbg(DBG_MAC80211, "%s():", __func__);
1957
1958         if (priv->device_unplugged)
1959                 return 0;
1960
1961         mutex_lock(&priv->mtx);
1962
1963         ieee80211_stop_queues(hw);
1964
1965         memset(&scan, 0, sizeof(struct at76_req_scan));
1966         eth_broadcast_addr(scan.bssid);
1967
1968         if (req->n_ssids) {
1969                 scan.scan_type = SCAN_TYPE_ACTIVE;
1970                 ssid = req->ssids[0].ssid;
1971                 len = req->ssids[0].ssid_len;
1972         } else {
1973                 scan.scan_type = SCAN_TYPE_PASSIVE;
1974         }
1975
1976         if (len) {
1977                 memcpy(scan.essid, ssid, len);
1978                 scan.essid_size = len;
1979         }
1980
1981         scan.min_channel_time = cpu_to_le16(priv->scan_min_time);
1982         scan.max_channel_time = cpu_to_le16(priv->scan_max_time);
1983         scan.probe_delay = cpu_to_le16(priv->scan_min_time * 1000);
1984         scan.international_scan = 0;
1985
1986         at76_dbg(DBG_MAC80211, "%s: sending CMD_SCAN", __func__);
1987         ret = at76_set_card_command(priv->udev, CMD_SCAN, &scan, sizeof(scan));
1988
1989         if (ret < 0) {
1990                 wiphy_err(priv->hw->wiphy, "CMD_SCAN failed: %d\n", ret);
1991                 goto exit;
1992         }
1993
1994         priv->scanning = true;
1995         ieee80211_queue_delayed_work(priv->hw, &priv->dwork_hw_scan,
1996                                      SCAN_POLL_INTERVAL);
1997
1998 exit:
1999         mutex_unlock(&priv->mtx);
2000
2001         return 0;
2002 }
2003
2004 static int at76_config(struct ieee80211_hw *hw, u32 changed)
2005 {
2006         struct at76_priv *priv = hw->priv;
2007
2008         at76_dbg(DBG_MAC80211, "%s(): channel %d",
2009                  __func__, hw->conf.chandef.chan->hw_value);
2010         at76_dbg_dump(DBG_MAC80211, priv->bssid, ETH_ALEN, "bssid:");
2011
2012         mutex_lock(&priv->mtx);
2013
2014         priv->channel = hw->conf.chandef.chan->hw_value;
2015
2016         if (is_valid_ether_addr(priv->bssid))
2017                 at76_join(priv);
2018         else
2019                 at76_start_monitor(priv);
2020
2021         mutex_unlock(&priv->mtx);
2022
2023         return 0;
2024 }
2025
2026 static void at76_bss_info_changed(struct ieee80211_hw *hw,
2027                                   struct ieee80211_vif *vif,
2028                                   struct ieee80211_bss_conf *conf,
2029                                   u32 changed)
2030 {
2031         struct at76_priv *priv = hw->priv;
2032
2033         at76_dbg(DBG_MAC80211, "%s():", __func__);
2034
2035         if (!(changed & BSS_CHANGED_BSSID))
2036                 return;
2037
2038         at76_dbg_dump(DBG_MAC80211, conf->bssid, ETH_ALEN, "bssid:");
2039
2040         mutex_lock(&priv->mtx);
2041
2042         memcpy(priv->bssid, conf->bssid, ETH_ALEN);
2043
2044         if (is_valid_ether_addr(priv->bssid))
2045                 /* mac80211 is joining a bss */
2046                 at76_join(priv);
2047
2048         mutex_unlock(&priv->mtx);
2049 }
2050
2051 /* must be atomic */
2052 static void at76_configure_filter(struct ieee80211_hw *hw,
2053                                   unsigned int changed_flags,
2054                                   unsigned int *total_flags, u64 multicast)
2055 {
2056         struct at76_priv *priv = hw->priv;
2057         int flags;
2058
2059         at76_dbg(DBG_MAC80211, "%s(): changed_flags=0x%08x "
2060                  "total_flags=0x%08x",
2061                  __func__, changed_flags, *total_flags);
2062
2063         flags = changed_flags & AT76_SUPPORTED_FILTERS;
2064         *total_flags = AT76_SUPPORTED_FILTERS;
2065
2066         /* Bail out after updating flags to prevent a WARN_ON in mac80211. */
2067         if (priv->device_unplugged)
2068                 return;
2069
2070         /* FIXME: access to priv->promisc should be protected with
2071          * priv->mtx, but it's impossible because this function needs to be
2072          * atomic */
2073
2074         if (flags && !priv->promisc) {
2075                 /* mac80211 wants us to enable promiscuous mode */
2076                 priv->promisc = 1;
2077         } else if (!flags && priv->promisc) {
2078                 /* we need to disable promiscuous mode */
2079                 priv->promisc = 0;
2080         } else
2081                 return;
2082
2083         ieee80211_queue_work(hw, &priv->work_set_promisc);
2084 }
2085
2086 static int at76_set_wep(struct at76_priv *priv)
2087 {
2088         int ret = 0;
2089         struct mib_mac_wep *mib_data = &priv->mib_buf.data.wep_mib;
2090
2091         priv->mib_buf.type = MIB_MAC_WEP;
2092         priv->mib_buf.size = sizeof(struct mib_mac_wep);
2093         priv->mib_buf.index = 0;
2094
2095         memset(mib_data, 0, sizeof(*mib_data));
2096
2097         if (priv->wep_enabled) {
2098                 if (priv->wep_keys_len[priv->wep_key_id] > WEP_SMALL_KEY_LEN)
2099                         mib_data->encryption_level = 2;
2100                 else
2101                         mib_data->encryption_level = 1;
2102
2103                 /* always exclude unencrypted if WEP is active */
2104                 mib_data->exclude_unencrypted = 1;
2105         } else {
2106                 mib_data->exclude_unencrypted = 0;
2107                 mib_data->encryption_level = 0;
2108         }
2109
2110         mib_data->privacy_invoked = priv->wep_enabled;
2111         mib_data->wep_default_key_id = priv->wep_key_id;
2112         memcpy(mib_data->wep_default_keyvalue, priv->wep_keys,
2113                sizeof(priv->wep_keys));
2114
2115         ret = at76_set_mib(priv, &priv->mib_buf);
2116
2117         if (ret < 0)
2118                 wiphy_err(priv->hw->wiphy,
2119                           "set_mib (wep) failed: %d\n", ret);
2120
2121         return ret;
2122 }
2123
2124 static int at76_set_key(struct ieee80211_hw *hw, enum set_key_cmd cmd,
2125                         struct ieee80211_vif *vif, struct ieee80211_sta *sta,
2126                         struct ieee80211_key_conf *key)
2127 {
2128         struct at76_priv *priv = hw->priv;
2129
2130         int i;
2131
2132         at76_dbg(DBG_MAC80211, "%s(): cmd %d key->cipher %d key->keyidx %d "
2133                  "key->keylen %d",
2134                  __func__, cmd, key->cipher, key->keyidx, key->keylen);
2135
2136         if ((key->cipher != WLAN_CIPHER_SUITE_WEP40) &&
2137             (key->cipher != WLAN_CIPHER_SUITE_WEP104))
2138                 return -EOPNOTSUPP;
2139
2140         key->hw_key_idx = key->keyidx;
2141
2142         mutex_lock(&priv->mtx);
2143
2144         switch (cmd) {
2145         case SET_KEY:
2146                 memcpy(priv->wep_keys[key->keyidx], key->key, key->keylen);
2147                 priv->wep_keys_len[key->keyidx] = key->keylen;
2148
2149                 /* FIXME: find out how to do this properly */
2150                 priv->wep_key_id = key->keyidx;
2151
2152                 break;
2153         case DISABLE_KEY:
2154         default:
2155                 priv->wep_keys_len[key->keyidx] = 0;
2156                 break;
2157         }
2158
2159         priv->wep_enabled = 0;
2160
2161         for (i = 0; i < WEP_KEYS; i++) {
2162                 if (priv->wep_keys_len[i] != 0)
2163                         priv->wep_enabled = 1;
2164         }
2165
2166         at76_set_wep(priv);
2167
2168         mutex_unlock(&priv->mtx);
2169
2170         return 0;
2171 }
2172
2173 static const struct ieee80211_ops at76_ops = {
2174         .tx = at76_mac80211_tx,
2175         .add_interface = at76_add_interface,
2176         .remove_interface = at76_remove_interface,
2177         .config = at76_config,
2178         .bss_info_changed = at76_bss_info_changed,
2179         .configure_filter = at76_configure_filter,
2180         .start = at76_mac80211_start,
2181         .stop = at76_mac80211_stop,
2182         .hw_scan = at76_hw_scan,
2183         .set_key = at76_set_key,
2184 };
2185
2186 /* Allocate network device and initialize private data */
2187 static struct at76_priv *at76_alloc_new_device(struct usb_device *udev)
2188 {
2189         struct ieee80211_hw *hw;
2190         struct at76_priv *priv;
2191
2192         hw = ieee80211_alloc_hw(sizeof(struct at76_priv), &at76_ops);
2193         if (!hw) {
2194                 printk(KERN_ERR DRIVER_NAME ": could not register"
2195                        " ieee80211_hw\n");
2196                 return NULL;
2197         }
2198
2199         priv = hw->priv;
2200         priv->hw = hw;
2201
2202         priv->udev = udev;
2203
2204         mutex_init(&priv->mtx);
2205         INIT_WORK(&priv->work_set_promisc, at76_work_set_promisc);
2206         INIT_WORK(&priv->work_submit_rx, at76_work_submit_rx);
2207         INIT_WORK(&priv->work_join_bssid, at76_work_join_bssid);
2208         INIT_DELAYED_WORK(&priv->dwork_hw_scan, at76_dwork_hw_scan);
2209
2210         tasklet_setup(&priv->rx_tasklet, at76_rx_tasklet);
2211
2212         priv->pm_mode = AT76_PM_OFF;
2213         priv->pm_period = 0;
2214
2215         /* unit us */
2216
2217         return priv;
2218 }
2219
2220 static int at76_alloc_urbs(struct at76_priv *priv,
2221                            struct usb_interface *interface)
2222 {
2223         struct usb_endpoint_descriptor *endpoint, *ep_in, *ep_out;
2224         int i;
2225         int buffer_size;
2226         struct usb_host_interface *iface_desc;
2227
2228         at76_dbg(DBG_PROC_ENTRY, "%s: ENTER", __func__);
2229
2230         at76_dbg(DBG_URB, "%s: NumEndpoints %d ", __func__,
2231                  interface->cur_altsetting->desc.bNumEndpoints);
2232
2233         ep_in = NULL;
2234         ep_out = NULL;
2235         iface_desc = interface->cur_altsetting;
2236         for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) {
2237                 endpoint = &iface_desc->endpoint[i].desc;
2238
2239                 at76_dbg(DBG_URB, "%s: %d. endpoint: addr 0x%x attr 0x%x",
2240                          __func__, i, endpoint->bEndpointAddress,
2241                          endpoint->bmAttributes);
2242
2243                 if (!ep_in && usb_endpoint_is_bulk_in(endpoint))
2244                         ep_in = endpoint;
2245
2246                 if (!ep_out && usb_endpoint_is_bulk_out(endpoint))
2247                         ep_out = endpoint;
2248         }
2249
2250         if (!ep_in || !ep_out) {
2251                 dev_err(&interface->dev, "bulk endpoints missing\n");
2252                 return -ENXIO;
2253         }
2254
2255         priv->rx_pipe = usb_rcvbulkpipe(priv->udev, ep_in->bEndpointAddress);
2256         priv->tx_pipe = usb_sndbulkpipe(priv->udev, ep_out->bEndpointAddress);
2257
2258         priv->rx_urb = usb_alloc_urb(0, GFP_KERNEL);
2259         priv->tx_urb = usb_alloc_urb(0, GFP_KERNEL);
2260         if (!priv->rx_urb || !priv->tx_urb) {
2261                 dev_err(&interface->dev, "cannot allocate URB\n");
2262                 return -ENOMEM;
2263         }
2264
2265         buffer_size = sizeof(struct at76_tx_buffer) + MAX_PADDING_SIZE;
2266         priv->bulk_out_buffer = kmalloc(buffer_size, GFP_KERNEL);
2267         if (!priv->bulk_out_buffer)
2268                 return -ENOMEM;
2269
2270         at76_dbg(DBG_PROC_ENTRY, "%s: EXIT", __func__);
2271
2272         return 0;
2273 }
2274
2275 static struct ieee80211_rate at76_rates[] = {
2276         { .bitrate = 10, .hw_value = TX_RATE_1MBIT, },
2277         { .bitrate = 20, .hw_value = TX_RATE_2MBIT, },
2278         { .bitrate = 55, .hw_value = TX_RATE_5_5MBIT, },
2279         { .bitrate = 110, .hw_value = TX_RATE_11MBIT, },
2280 };
2281
2282 static struct ieee80211_channel at76_channels[] = {
2283         { .center_freq = 2412, .hw_value = 1 },
2284         { .center_freq = 2417, .hw_value = 2 },
2285         { .center_freq = 2422, .hw_value = 3 },
2286         { .center_freq = 2427, .hw_value = 4 },
2287         { .center_freq = 2432, .hw_value = 5 },
2288         { .center_freq = 2437, .hw_value = 6 },
2289         { .center_freq = 2442, .hw_value = 7 },
2290         { .center_freq = 2447, .hw_value = 8 },
2291         { .center_freq = 2452, .hw_value = 9 },
2292         { .center_freq = 2457, .hw_value = 10 },
2293         { .center_freq = 2462, .hw_value = 11 },
2294         { .center_freq = 2467, .hw_value = 12 },
2295         { .center_freq = 2472, .hw_value = 13 },
2296         { .center_freq = 2484, .hw_value = 14 }
2297 };
2298
2299 static struct ieee80211_supported_band at76_supported_band = {
2300         .channels = at76_channels,
2301         .n_channels = ARRAY_SIZE(at76_channels),
2302         .bitrates = at76_rates,
2303         .n_bitrates = ARRAY_SIZE(at76_rates),
2304 };
2305
2306 /* Register network device and initialize the hardware */
2307 static int at76_init_new_device(struct at76_priv *priv,
2308                                 struct usb_interface *interface)
2309 {
2310         struct wiphy *wiphy;
2311         size_t len;
2312         int ret;
2313
2314         /* set up the endpoint information */
2315         /* check out the endpoints */
2316
2317         at76_dbg(DBG_DEVSTART, "USB interface: %d endpoints",
2318                  interface->cur_altsetting->desc.bNumEndpoints);
2319
2320         ret = at76_alloc_urbs(priv, interface);
2321         if (ret < 0)
2322                 goto exit;
2323
2324         /* MAC address */
2325         ret = at76_get_hw_config(priv);
2326         if (ret < 0) {
2327                 dev_err(&interface->dev, "cannot get MAC address\n");
2328                 goto exit;
2329         }
2330
2331         priv->domain = at76_get_reg_domain(priv->regulatory_domain);
2332
2333         priv->channel = DEF_CHANNEL;
2334         priv->iw_mode = IW_MODE_INFRA;
2335         priv->rts_threshold = DEF_RTS_THRESHOLD;
2336         priv->frag_threshold = DEF_FRAG_THRESHOLD;
2337         priv->short_retry_limit = DEF_SHORT_RETRY_LIMIT;
2338         priv->txrate = TX_RATE_AUTO;
2339         priv->preamble_type = PREAMBLE_TYPE_LONG;
2340         priv->beacon_period = 100;
2341         priv->auth_mode = WLAN_AUTH_OPEN;
2342         priv->scan_min_time = DEF_SCAN_MIN_TIME;
2343         priv->scan_max_time = DEF_SCAN_MAX_TIME;
2344         priv->scan_mode = SCAN_TYPE_ACTIVE;
2345         priv->device_unplugged = 0;
2346
2347         /* mac80211 initialisation */
2348         wiphy = priv->hw->wiphy;
2349         priv->hw->wiphy->max_scan_ssids = 1;
2350         priv->hw->wiphy->max_scan_ie_len = 0;
2351         priv->hw->wiphy->interface_modes = BIT(NL80211_IFTYPE_STATION);
2352         priv->hw->wiphy->bands[NL80211_BAND_2GHZ] = &at76_supported_band;
2353         ieee80211_hw_set(priv->hw, RX_INCLUDES_FCS);
2354         ieee80211_hw_set(priv->hw, SIGNAL_UNSPEC);
2355         priv->hw->max_signal = 100;
2356
2357         SET_IEEE80211_DEV(priv->hw, &interface->dev);
2358         SET_IEEE80211_PERM_ADDR(priv->hw, priv->mac_addr);
2359
2360         len = sizeof(wiphy->fw_version);
2361         snprintf(wiphy->fw_version, len, "%d.%d.%d-%d",
2362                  priv->fw_version.major, priv->fw_version.minor,
2363                  priv->fw_version.patch, priv->fw_version.build);
2364
2365         wiphy->hw_version = priv->board_type;
2366
2367         wiphy_ext_feature_set(wiphy, NL80211_EXT_FEATURE_CQM_RSSI_LIST);
2368
2369         ret = ieee80211_register_hw(priv->hw);
2370         if (ret) {
2371                 printk(KERN_ERR "cannot register mac80211 hw (status %d)!\n",
2372                        ret);
2373                 goto exit;
2374         }
2375
2376         priv->mac80211_registered = 1;
2377
2378         wiphy_info(priv->hw->wiphy, "USB %s, MAC %pM, firmware %d.%d.%d-%d\n",
2379                    dev_name(&interface->dev), priv->mac_addr,
2380                    priv->fw_version.major, priv->fw_version.minor,
2381                    priv->fw_version.patch, priv->fw_version.build);
2382         wiphy_info(priv->hw->wiphy, "regulatory domain 0x%02x: %s\n",
2383                    priv->regulatory_domain, priv->domain->name);
2384
2385 exit:
2386         return ret;
2387 }
2388
2389 static void at76_delete_device(struct at76_priv *priv)
2390 {
2391         at76_dbg(DBG_PROC_ENTRY, "%s: ENTER", __func__);
2392
2393         /* The device is gone, don't bother turning it off */
2394         priv->device_unplugged = 1;
2395
2396         tasklet_kill(&priv->rx_tasklet);
2397
2398         if (priv->mac80211_registered)
2399                 ieee80211_unregister_hw(priv->hw);
2400
2401         if (priv->tx_urb) {
2402                 usb_kill_urb(priv->tx_urb);
2403                 usb_free_urb(priv->tx_urb);
2404         }
2405         if (priv->rx_urb) {
2406                 usb_kill_urb(priv->rx_urb);
2407                 usb_free_urb(priv->rx_urb);
2408         }
2409
2410         at76_dbg(DBG_PROC_ENTRY, "%s: unlinked urbs", __func__);
2411
2412         kfree(priv->bulk_out_buffer);
2413
2414         del_timer_sync(&ledtrig_tx_timer);
2415
2416         kfree_skb(priv->rx_skb);
2417
2418         at76_dbg(DBG_PROC_ENTRY, "%s: before freeing priv/ieee80211_hw",
2419                  __func__);
2420         ieee80211_free_hw(priv->hw);
2421
2422         at76_dbg(DBG_PROC_ENTRY, "%s: EXIT", __func__);
2423 }
2424
2425 static int at76_probe(struct usb_interface *interface,
2426                       const struct usb_device_id *id)
2427 {
2428         int ret;
2429         struct at76_priv *priv;
2430         struct fwentry *fwe;
2431         struct usb_device *udev;
2432         int op_mode;
2433         int need_ext_fw = 0;
2434         struct mib_fw_version *fwv = NULL;
2435         int board_type = (int)id->driver_info;
2436
2437         udev = usb_get_dev(interface_to_usbdev(interface));
2438
2439         fwv = kmalloc(sizeof(*fwv), GFP_KERNEL);
2440         if (!fwv) {
2441                 ret = -ENOMEM;
2442                 goto exit;
2443         }
2444
2445         /* Load firmware into kernel memory */
2446         fwe = at76_load_firmware(udev, board_type);
2447         if (!fwe) {
2448                 ret = -ENOENT;
2449                 goto exit;
2450         }
2451
2452         op_mode = at76_get_op_mode(udev);
2453
2454         at76_dbg(DBG_DEVSTART, "opmode %d", op_mode);
2455
2456         /* we get OPMODE_NONE with 2.4.23, SMC2662W-AR ???
2457            we get 204 with 2.4.23, Fiberline FL-WL240u (505A+RFMD2958) ??? */
2458
2459         if (op_mode == OPMODE_HW_CONFIG_MODE) {
2460                 dev_err(&interface->dev,
2461                         "cannot handle a device in HW_CONFIG_MODE\n");
2462                 ret = -EBUSY;
2463                 goto exit;
2464         }
2465
2466         if (op_mode != OPMODE_NORMAL_NIC_WITH_FLASH
2467             && op_mode != OPMODE_NORMAL_NIC_WITHOUT_FLASH) {
2468                 /* download internal firmware part */
2469                 dev_printk(KERN_DEBUG, &interface->dev,
2470                            "downloading internal firmware\n");
2471                 ret = at76_load_internal_fw(udev, fwe);
2472                 if (ret < 0) {
2473                         dev_err(&interface->dev,
2474                                 "error %d downloading internal firmware\n",
2475                                 ret);
2476                 }
2477                 goto exit;
2478         }
2479
2480         /* Internal firmware already inside the device.  Get firmware
2481          * version to test if external firmware is loaded.
2482          * This works only for newer firmware, e.g. the Intersil 0.90.x
2483          * says "control timeout on ep0in" and subsequent
2484          * at76_get_op_mode() fail too :-( */
2485
2486         /* if version >= 0.100.x.y or device with built-in flash we can
2487          * query the device for the fw version */
2488         if ((fwe->fw_version.major > 0 || fwe->fw_version.minor >= 100)
2489             || (op_mode == OPMODE_NORMAL_NIC_WITH_FLASH)) {
2490                 ret = at76_get_mib(udev, MIB_FW_VERSION, fwv, sizeof(*fwv));
2491                 if (ret < 0 || (fwv->major | fwv->minor) == 0)
2492                         need_ext_fw = 1;
2493         } else
2494                 /* No way to check firmware version, reload to be sure */
2495                 need_ext_fw = 1;
2496
2497         if (need_ext_fw) {
2498                 dev_printk(KERN_DEBUG, &interface->dev,
2499                            "downloading external firmware\n");
2500
2501                 ret = at76_load_external_fw(udev, fwe);
2502                 if (ret < 0)
2503                         goto exit;
2504
2505                 /* Re-check firmware version */
2506                 ret = at76_get_mib(udev, MIB_FW_VERSION, fwv, sizeof(*fwv));
2507                 if (ret < 0) {
2508                         dev_err(&interface->dev,
2509                                 "error %d getting firmware version\n", ret);
2510                         goto exit;
2511                 }
2512         }
2513
2514         priv = at76_alloc_new_device(udev);
2515         if (!priv) {
2516                 ret = -ENOMEM;
2517                 goto exit;
2518         }
2519
2520         usb_set_intfdata(interface, priv);
2521
2522         memcpy(&priv->fw_version, fwv, sizeof(struct mib_fw_version));
2523         priv->board_type = board_type;
2524
2525         ret = at76_init_new_device(priv, interface);
2526         if (ret < 0)
2527                 at76_delete_device(priv);
2528
2529 exit:
2530         kfree(fwv);
2531         if (ret < 0)
2532                 usb_put_dev(udev);
2533         return ret;
2534 }
2535
2536 static void at76_disconnect(struct usb_interface *interface)
2537 {
2538         struct at76_priv *priv;
2539
2540         priv = usb_get_intfdata(interface);
2541         usb_set_intfdata(interface, NULL);
2542
2543         /* Disconnect after loading internal firmware */
2544         if (!priv)
2545                 return;
2546
2547         wiphy_info(priv->hw->wiphy, "disconnecting\n");
2548         at76_delete_device(priv);
2549         usb_put_dev(priv->udev);
2550         dev_info(&interface->dev, "disconnected\n");
2551 }
2552
2553 /* Structure for registering this driver with the USB subsystem */
2554 static struct usb_driver at76_driver = {
2555         .name = DRIVER_NAME,
2556         .probe = at76_probe,
2557         .disconnect = at76_disconnect,
2558         .id_table = dev_table,
2559         .disable_hub_initiated_lpm = 1,
2560 };
2561
2562 static int __init at76_mod_init(void)
2563 {
2564         int result;
2565
2566         printk(KERN_INFO DRIVER_DESC " " DRIVER_VERSION " loading\n");
2567
2568         /* register this driver with the USB subsystem */
2569         result = usb_register(&at76_driver);
2570         if (result < 0)
2571                 printk(KERN_ERR DRIVER_NAME
2572                        ": usb_register failed (status %d)\n", result);
2573         else
2574                 led_trigger_register_simple("at76_usb-tx", &ledtrig_tx);
2575         return result;
2576 }
2577
2578 static void __exit at76_mod_exit(void)
2579 {
2580         int i;
2581
2582         printk(KERN_INFO DRIVER_DESC " " DRIVER_VERSION " unloading\n");
2583         usb_deregister(&at76_driver);
2584         for (i = 0; i < ARRAY_SIZE(firmwares); i++)
2585                 release_firmware(firmwares[i].fw);
2586         led_trigger_unregister_simple(ledtrig_tx);
2587 }
2588
2589 module_param_named(debug, at76_debug, uint, 0600);
2590 MODULE_PARM_DESC(debug, "Debugging level");
2591
2592 module_init(at76_mod_init);
2593 module_exit(at76_mod_exit);
2594
2595 MODULE_AUTHOR("Oliver Kurth <oku@masqmail.cx>");
2596 MODULE_AUTHOR("Joerg Albert <joerg.albert@gmx.de>");
2597 MODULE_AUTHOR("Alex <alex@foogod.com>");
2598 MODULE_AUTHOR("Nick Jones");
2599 MODULE_AUTHOR("Balint Seeber <n0_5p4m_p13453@hotmail.com>");
2600 MODULE_AUTHOR("Pavel Roskin <proski@gnu.org>");
2601 MODULE_AUTHOR("Guido Guenther <agx@sigxcpu.org>");
2602 MODULE_AUTHOR("Kalle Valo <kalle.valo@iki.fi>");
2603 MODULE_AUTHOR("Sebastian Smolorz <sesmo@gmx.net>");
2604 MODULE_DESCRIPTION(DRIVER_DESC);
2605 MODULE_LICENSE("GPL");