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