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