]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/usb/wlan/if_rum.c
MFC r306049:
[FreeBSD/FreeBSD.git] / sys / dev / usb / wlan / if_rum.c
1 /*      $FreeBSD$       */
2
3 /*-
4  * Copyright (c) 2005-2007 Damien Bergamini <damien.bergamini@free.fr>
5  * Copyright (c) 2006 Niall O'Higgins <niallo@openbsd.org>
6  * Copyright (c) 2007-2008 Hans Petter Selasky <hselasky@FreeBSD.org>
7  * Copyright (c) 2015 Andriy Voskoboinyk <avos@FreeBSD.org>
8  *
9  * Permission to use, copy, modify, and distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20  */
21
22 #include <sys/cdefs.h>
23 __FBSDID("$FreeBSD$");
24
25 /*-
26  * Ralink Technology RT2501USB/RT2601USB chipset driver
27  * http://www.ralinktech.com.tw/
28  */
29
30 #include <sys/param.h>
31 #include <sys/sockio.h>
32 #include <sys/sysctl.h>
33 #include <sys/lock.h>
34 #include <sys/mutex.h>
35 #include <sys/mbuf.h>
36 #include <sys/kernel.h>
37 #include <sys/socket.h>
38 #include <sys/systm.h>
39 #include <sys/malloc.h>
40 #include <sys/module.h>
41 #include <sys/bus.h>
42 #include <sys/endian.h>
43 #include <sys/kdb.h>
44
45 #include <net/bpf.h>
46 #include <net/if.h>
47 #include <net/if_var.h>
48 #include <net/if_arp.h>
49 #include <net/ethernet.h>
50 #include <net/if_dl.h>
51 #include <net/if_media.h>
52 #include <net/if_types.h>
53
54 #ifdef INET
55 #include <netinet/in.h>
56 #include <netinet/in_systm.h>
57 #include <netinet/in_var.h>
58 #include <netinet/if_ether.h>
59 #include <netinet/ip.h>
60 #endif
61
62 #include <net80211/ieee80211_var.h>
63 #include <net80211/ieee80211_regdomain.h>
64 #include <net80211/ieee80211_radiotap.h>
65 #include <net80211/ieee80211_ratectl.h>
66
67 #include <dev/usb/usb.h>
68 #include <dev/usb/usbdi.h>
69 #include "usbdevs.h"
70
71 #define USB_DEBUG_VAR rum_debug
72 #include <dev/usb/usb_debug.h>
73
74 #include <dev/usb/wlan/if_rumreg.h>
75 #include <dev/usb/wlan/if_rumvar.h>
76 #include <dev/usb/wlan/if_rumfw.h>
77
78 #ifdef USB_DEBUG
79 static int rum_debug = 0;
80
81 static SYSCTL_NODE(_hw_usb, OID_AUTO, rum, CTLFLAG_RW, 0, "USB rum");
82 SYSCTL_INT(_hw_usb_rum, OID_AUTO, debug, CTLFLAG_RWTUN, &rum_debug, 0,
83     "Debug level");
84 #endif
85
86 static const STRUCT_USB_HOST_ID rum_devs[] = {
87 #define RUM_DEV(v,p)  { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) }
88     RUM_DEV(ABOCOM, HWU54DM),
89     RUM_DEV(ABOCOM, RT2573_2),
90     RUM_DEV(ABOCOM, RT2573_3),
91     RUM_DEV(ABOCOM, RT2573_4),
92     RUM_DEV(ABOCOM, WUG2700),
93     RUM_DEV(AMIT, CGWLUSB2GO),
94     RUM_DEV(ASUS, RT2573_1),
95     RUM_DEV(ASUS, RT2573_2),
96     RUM_DEV(BELKIN, F5D7050A),
97     RUM_DEV(BELKIN, F5D9050V3),
98     RUM_DEV(CISCOLINKSYS, WUSB54GC),
99     RUM_DEV(CISCOLINKSYS, WUSB54GR),
100     RUM_DEV(CONCEPTRONIC2, C54RU2),
101     RUM_DEV(COREGA, CGWLUSB2GL),
102     RUM_DEV(COREGA, CGWLUSB2GPX),
103     RUM_DEV(DICKSMITH, CWD854F),
104     RUM_DEV(DICKSMITH, RT2573),
105     RUM_DEV(EDIMAX, EW7318USG),
106     RUM_DEV(DLINK2, DWLG122C1),
107     RUM_DEV(DLINK2, WUA1340),
108     RUM_DEV(DLINK2, DWA111),
109     RUM_DEV(DLINK2, DWA110),
110     RUM_DEV(GIGABYTE, GNWB01GS),
111     RUM_DEV(GIGABYTE, GNWI05GS),
112     RUM_DEV(GIGASET, RT2573),
113     RUM_DEV(GOODWAY, RT2573),
114     RUM_DEV(GUILLEMOT, HWGUSB254LB),
115     RUM_DEV(GUILLEMOT, HWGUSB254V2AP),
116     RUM_DEV(HUAWEI3COM, WUB320G),
117     RUM_DEV(MELCO, G54HP),
118     RUM_DEV(MELCO, SG54HP),
119     RUM_DEV(MELCO, SG54HG),
120     RUM_DEV(MELCO, WLIUCG),
121     RUM_DEV(MELCO, WLRUCG),
122     RUM_DEV(MELCO, WLRUCGAOSS),
123     RUM_DEV(MSI, RT2573_1),
124     RUM_DEV(MSI, RT2573_2),
125     RUM_DEV(MSI, RT2573_3),
126     RUM_DEV(MSI, RT2573_4),
127     RUM_DEV(NOVATECH, RT2573),
128     RUM_DEV(PLANEX2, GWUS54HP),
129     RUM_DEV(PLANEX2, GWUS54MINI2),
130     RUM_DEV(PLANEX2, GWUSMM),
131     RUM_DEV(QCOM, RT2573),
132     RUM_DEV(QCOM, RT2573_2),
133     RUM_DEV(QCOM, RT2573_3),
134     RUM_DEV(RALINK, RT2573),
135     RUM_DEV(RALINK, RT2573_2),
136     RUM_DEV(RALINK, RT2671),
137     RUM_DEV(SITECOMEU, WL113R2),
138     RUM_DEV(SITECOMEU, WL172),
139     RUM_DEV(SPARKLAN, RT2573),
140     RUM_DEV(SURECOM, RT2573),
141 #undef RUM_DEV
142 };
143
144 static device_probe_t rum_match;
145 static device_attach_t rum_attach;
146 static device_detach_t rum_detach;
147
148 static usb_callback_t rum_bulk_read_callback;
149 static usb_callback_t rum_bulk_write_callback;
150
151 static usb_error_t      rum_do_request(struct rum_softc *sc,
152                             struct usb_device_request *req, void *data);
153 static usb_error_t      rum_do_mcu_request(struct rum_softc *sc, int);
154 static struct ieee80211vap *rum_vap_create(struct ieee80211com *,
155                             const char [IFNAMSIZ], int, enum ieee80211_opmode,
156                             int, const uint8_t [IEEE80211_ADDR_LEN],
157                             const uint8_t [IEEE80211_ADDR_LEN]);
158 static void             rum_vap_delete(struct ieee80211vap *);
159 static void             rum_cmdq_cb(void *, int);
160 static int              rum_cmd_sleepable(struct rum_softc *, const void *,
161                             size_t, uint8_t, CMD_FUNC_PROTO);
162 static void             rum_tx_free(struct rum_tx_data *, int);
163 static void             rum_setup_tx_list(struct rum_softc *);
164 static void             rum_unsetup_tx_list(struct rum_softc *);
165 static void             rum_beacon_miss(struct ieee80211vap *);
166 static void             rum_sta_recv_mgmt(struct ieee80211_node *,
167                             struct mbuf *, int,
168                             const struct ieee80211_rx_stats *, int, int);
169 static int              rum_set_power_state(struct rum_softc *, int);
170 static int              rum_newstate(struct ieee80211vap *,
171                             enum ieee80211_state, int);
172 static uint8_t          rum_crypto_mode(struct rum_softc *, u_int, int);
173 static void             rum_setup_tx_desc(struct rum_softc *,
174                             struct rum_tx_desc *, struct ieee80211_key *,
175                             uint32_t, uint8_t, uint8_t, int, int, int);
176 static uint32_t         rum_tx_crypto_flags(struct rum_softc *,
177                             struct ieee80211_node *,
178                             const struct ieee80211_key *);
179 static int              rum_tx_mgt(struct rum_softc *, struct mbuf *,
180                             struct ieee80211_node *);
181 static int              rum_tx_raw(struct rum_softc *, struct mbuf *,
182                             struct ieee80211_node *, 
183                             const struct ieee80211_bpf_params *);
184 static int              rum_tx_data(struct rum_softc *, struct mbuf *,
185                             struct ieee80211_node *);
186 static int              rum_transmit(struct ieee80211com *, struct mbuf *);
187 static void             rum_start(struct rum_softc *);
188 static void             rum_parent(struct ieee80211com *);
189 static void             rum_eeprom_read(struct rum_softc *, uint16_t, void *,
190                             int);
191 static uint32_t         rum_read(struct rum_softc *, uint16_t);
192 static void             rum_read_multi(struct rum_softc *, uint16_t, void *,
193                             int);
194 static usb_error_t      rum_write(struct rum_softc *, uint16_t, uint32_t);
195 static usb_error_t      rum_write_multi(struct rum_softc *, uint16_t, void *,
196                             size_t);
197 static usb_error_t      rum_setbits(struct rum_softc *, uint16_t, uint32_t);
198 static usb_error_t      rum_clrbits(struct rum_softc *, uint16_t, uint32_t);
199 static usb_error_t      rum_modbits(struct rum_softc *, uint16_t, uint32_t,
200                             uint32_t);
201 static int              rum_bbp_busy(struct rum_softc *);
202 static void             rum_bbp_write(struct rum_softc *, uint8_t, uint8_t);
203 static uint8_t          rum_bbp_read(struct rum_softc *, uint8_t);
204 static void             rum_rf_write(struct rum_softc *, uint8_t, uint32_t);
205 static void             rum_select_antenna(struct rum_softc *);
206 static void             rum_enable_mrr(struct rum_softc *);
207 static void             rum_set_txpreamble(struct rum_softc *);
208 static void             rum_set_basicrates(struct rum_softc *);
209 static void             rum_select_band(struct rum_softc *,
210                             struct ieee80211_channel *);
211 static void             rum_set_chan(struct rum_softc *,
212                             struct ieee80211_channel *);
213 static void             rum_set_maxretry(struct rum_softc *,
214                             struct ieee80211vap *);
215 static int              rum_enable_tsf_sync(struct rum_softc *);
216 static void             rum_enable_tsf(struct rum_softc *);
217 static void             rum_abort_tsf_sync(struct rum_softc *);
218 static void             rum_get_tsf(struct rum_softc *, uint64_t *);
219 static void             rum_update_slot_cb(struct rum_softc *,
220                             union sec_param *, uint8_t);
221 static void             rum_update_slot(struct ieee80211com *);
222 static int              rum_wme_update(struct ieee80211com *);
223 static void             rum_set_bssid(struct rum_softc *, const uint8_t *);
224 static void             rum_set_macaddr(struct rum_softc *, const uint8_t *);
225 static void             rum_update_mcast(struct ieee80211com *);
226 static void             rum_update_promisc(struct ieee80211com *);
227 static void             rum_setpromisc(struct rum_softc *);
228 static const char       *rum_get_rf(int);
229 static void             rum_read_eeprom(struct rum_softc *);
230 static int              rum_bbp_wakeup(struct rum_softc *);
231 static int              rum_bbp_init(struct rum_softc *);
232 static void             rum_clr_shkey_regs(struct rum_softc *);
233 static int              rum_init(struct rum_softc *);
234 static void             rum_stop(struct rum_softc *);
235 static void             rum_load_microcode(struct rum_softc *, const uint8_t *,
236                             size_t);
237 static int              rum_set_sleep_time(struct rum_softc *, uint16_t);
238 static int              rum_reset(struct ieee80211vap *, u_long);
239 static int              rum_set_beacon(struct rum_softc *,
240                             struct ieee80211vap *);
241 static int              rum_alloc_beacon(struct rum_softc *,
242                             struct ieee80211vap *);
243 static void             rum_update_beacon_cb(struct rum_softc *,
244                             union sec_param *, uint8_t);
245 static void             rum_update_beacon(struct ieee80211vap *, int);
246 static int              rum_common_key_set(struct rum_softc *,
247                             struct ieee80211_key *, uint16_t);
248 static void             rum_group_key_set_cb(struct rum_softc *,
249                             union sec_param *, uint8_t);
250 static void             rum_group_key_del_cb(struct rum_softc *,
251                             union sec_param *, uint8_t);
252 static void             rum_pair_key_set_cb(struct rum_softc *,
253                             union sec_param *, uint8_t);
254 static void             rum_pair_key_del_cb(struct rum_softc *,
255                             union sec_param *, uint8_t);
256 static int              rum_key_alloc(struct ieee80211vap *,
257                             struct ieee80211_key *, ieee80211_keyix *,
258                             ieee80211_keyix *);
259 static int              rum_key_set(struct ieee80211vap *,
260                             const struct ieee80211_key *);
261 static int              rum_key_delete(struct ieee80211vap *,
262                             const struct ieee80211_key *);
263 static int              rum_raw_xmit(struct ieee80211_node *, struct mbuf *,
264                             const struct ieee80211_bpf_params *);
265 static void             rum_scan_start(struct ieee80211com *);
266 static void             rum_scan_end(struct ieee80211com *);
267 static void             rum_set_channel(struct ieee80211com *);
268 static void             rum_getradiocaps(struct ieee80211com *, int, int *,
269                             struct ieee80211_channel[]);
270 static int              rum_get_rssi(struct rum_softc *, uint8_t);
271 static void             rum_ratectl_start(struct rum_softc *,
272                             struct ieee80211_node *);
273 static void             rum_ratectl_timeout(void *);
274 static void             rum_ratectl_task(void *, int);
275 static int              rum_pause(struct rum_softc *, int);
276
277 static const struct {
278         uint32_t        reg;
279         uint32_t        val;
280 } rum_def_mac[] = {
281         { RT2573_TXRX_CSR0,  0x025fb032 },
282         { RT2573_TXRX_CSR1,  0x9eaa9eaf },
283         { RT2573_TXRX_CSR2,  0x8a8b8c8d }, 
284         { RT2573_TXRX_CSR3,  0x00858687 },
285         { RT2573_TXRX_CSR7,  0x2e31353b },
286         { RT2573_TXRX_CSR8,  0x2a2a2a2c },
287         { RT2573_TXRX_CSR15, 0x0000000f },
288         { RT2573_MAC_CSR6,   0x00000fff },
289         { RT2573_MAC_CSR8,   0x016c030a },
290         { RT2573_MAC_CSR10,  0x00000718 },
291         { RT2573_MAC_CSR12,  0x00000004 },
292         { RT2573_MAC_CSR13,  0x00007f00 },
293         { RT2573_SEC_CSR2,   0x00000000 },
294         { RT2573_SEC_CSR3,   0x00000000 },
295         { RT2573_SEC_CSR4,   0x00000000 },
296         { RT2573_PHY_CSR1,   0x000023b0 },
297         { RT2573_PHY_CSR5,   0x00040a06 },
298         { RT2573_PHY_CSR6,   0x00080606 },
299         { RT2573_PHY_CSR7,   0x00000408 },
300         { RT2573_AIFSN_CSR,  0x00002273 },
301         { RT2573_CWMIN_CSR,  0x00002344 },
302         { RT2573_CWMAX_CSR,  0x000034aa }
303 };
304
305 static const struct {
306         uint8_t reg;
307         uint8_t val;
308 } rum_def_bbp[] = {
309         {   3, 0x80 },
310         {  15, 0x30 },
311         {  17, 0x20 },
312         {  21, 0xc8 },
313         {  22, 0x38 },
314         {  23, 0x06 },
315         {  24, 0xfe },
316         {  25, 0x0a },
317         {  26, 0x0d },
318         {  32, 0x0b },
319         {  34, 0x12 },
320         {  37, 0x07 },
321         {  39, 0xf8 },
322         {  41, 0x60 },
323         {  53, 0x10 },
324         {  54, 0x18 },
325         {  60, 0x10 },
326         {  61, 0x04 },
327         {  62, 0x04 },
328         {  75, 0xfe },
329         {  86, 0xfe },
330         {  88, 0xfe },
331         {  90, 0x0f },
332         {  99, 0x00 },
333         { 102, 0x16 },
334         { 107, 0x04 }
335 };
336
337 static const uint8_t rum_chan_5ghz[] =
338         { 34, 36, 38, 40, 42, 44, 46, 48, 52, 56, 60, 64,
339           100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140,
340           149, 153, 157, 161, 165 };
341
342 static const struct rfprog {
343         uint8_t         chan;
344         uint32_t        r1, r2, r3, r4;
345 }  rum_rf5226[] = {
346         {   1, 0x00b03, 0x001e1, 0x1a014, 0x30282 },
347         {   2, 0x00b03, 0x001e1, 0x1a014, 0x30287 },
348         {   3, 0x00b03, 0x001e2, 0x1a014, 0x30282 },
349         {   4, 0x00b03, 0x001e2, 0x1a014, 0x30287 },
350         {   5, 0x00b03, 0x001e3, 0x1a014, 0x30282 },
351         {   6, 0x00b03, 0x001e3, 0x1a014, 0x30287 },
352         {   7, 0x00b03, 0x001e4, 0x1a014, 0x30282 },
353         {   8, 0x00b03, 0x001e4, 0x1a014, 0x30287 },
354         {   9, 0x00b03, 0x001e5, 0x1a014, 0x30282 },
355         {  10, 0x00b03, 0x001e5, 0x1a014, 0x30287 },
356         {  11, 0x00b03, 0x001e6, 0x1a014, 0x30282 },
357         {  12, 0x00b03, 0x001e6, 0x1a014, 0x30287 },
358         {  13, 0x00b03, 0x001e7, 0x1a014, 0x30282 },
359         {  14, 0x00b03, 0x001e8, 0x1a014, 0x30284 },
360
361         {  34, 0x00b03, 0x20266, 0x36014, 0x30282 },
362         {  38, 0x00b03, 0x20267, 0x36014, 0x30284 },
363         {  42, 0x00b03, 0x20268, 0x36014, 0x30286 },
364         {  46, 0x00b03, 0x20269, 0x36014, 0x30288 },
365
366         {  36, 0x00b03, 0x00266, 0x26014, 0x30288 },
367         {  40, 0x00b03, 0x00268, 0x26014, 0x30280 },
368         {  44, 0x00b03, 0x00269, 0x26014, 0x30282 },
369         {  48, 0x00b03, 0x0026a, 0x26014, 0x30284 },
370         {  52, 0x00b03, 0x0026b, 0x26014, 0x30286 },
371         {  56, 0x00b03, 0x0026c, 0x26014, 0x30288 },
372         {  60, 0x00b03, 0x0026e, 0x26014, 0x30280 },
373         {  64, 0x00b03, 0x0026f, 0x26014, 0x30282 },
374
375         { 100, 0x00b03, 0x0028a, 0x2e014, 0x30280 },
376         { 104, 0x00b03, 0x0028b, 0x2e014, 0x30282 },
377         { 108, 0x00b03, 0x0028c, 0x2e014, 0x30284 },
378         { 112, 0x00b03, 0x0028d, 0x2e014, 0x30286 },
379         { 116, 0x00b03, 0x0028e, 0x2e014, 0x30288 },
380         { 120, 0x00b03, 0x002a0, 0x2e014, 0x30280 },
381         { 124, 0x00b03, 0x002a1, 0x2e014, 0x30282 },
382         { 128, 0x00b03, 0x002a2, 0x2e014, 0x30284 },
383         { 132, 0x00b03, 0x002a3, 0x2e014, 0x30286 },
384         { 136, 0x00b03, 0x002a4, 0x2e014, 0x30288 },
385         { 140, 0x00b03, 0x002a6, 0x2e014, 0x30280 },
386
387         { 149, 0x00b03, 0x002a8, 0x2e014, 0x30287 },
388         { 153, 0x00b03, 0x002a9, 0x2e014, 0x30289 },
389         { 157, 0x00b03, 0x002ab, 0x2e014, 0x30281 },
390         { 161, 0x00b03, 0x002ac, 0x2e014, 0x30283 },
391         { 165, 0x00b03, 0x002ad, 0x2e014, 0x30285 }
392 }, rum_rf5225[] = {
393         {   1, 0x00b33, 0x011e1, 0x1a014, 0x30282 },
394         {   2, 0x00b33, 0x011e1, 0x1a014, 0x30287 },
395         {   3, 0x00b33, 0x011e2, 0x1a014, 0x30282 },
396         {   4, 0x00b33, 0x011e2, 0x1a014, 0x30287 },
397         {   5, 0x00b33, 0x011e3, 0x1a014, 0x30282 },
398         {   6, 0x00b33, 0x011e3, 0x1a014, 0x30287 },
399         {   7, 0x00b33, 0x011e4, 0x1a014, 0x30282 },
400         {   8, 0x00b33, 0x011e4, 0x1a014, 0x30287 },
401         {   9, 0x00b33, 0x011e5, 0x1a014, 0x30282 },
402         {  10, 0x00b33, 0x011e5, 0x1a014, 0x30287 },
403         {  11, 0x00b33, 0x011e6, 0x1a014, 0x30282 },
404         {  12, 0x00b33, 0x011e6, 0x1a014, 0x30287 },
405         {  13, 0x00b33, 0x011e7, 0x1a014, 0x30282 },
406         {  14, 0x00b33, 0x011e8, 0x1a014, 0x30284 },
407
408         {  34, 0x00b33, 0x01266, 0x26014, 0x30282 },
409         {  38, 0x00b33, 0x01267, 0x26014, 0x30284 },
410         {  42, 0x00b33, 0x01268, 0x26014, 0x30286 },
411         {  46, 0x00b33, 0x01269, 0x26014, 0x30288 },
412
413         {  36, 0x00b33, 0x01266, 0x26014, 0x30288 },
414         {  40, 0x00b33, 0x01268, 0x26014, 0x30280 },
415         {  44, 0x00b33, 0x01269, 0x26014, 0x30282 },
416         {  48, 0x00b33, 0x0126a, 0x26014, 0x30284 },
417         {  52, 0x00b33, 0x0126b, 0x26014, 0x30286 },
418         {  56, 0x00b33, 0x0126c, 0x26014, 0x30288 },
419         {  60, 0x00b33, 0x0126e, 0x26014, 0x30280 },
420         {  64, 0x00b33, 0x0126f, 0x26014, 0x30282 },
421
422         { 100, 0x00b33, 0x0128a, 0x2e014, 0x30280 },
423         { 104, 0x00b33, 0x0128b, 0x2e014, 0x30282 },
424         { 108, 0x00b33, 0x0128c, 0x2e014, 0x30284 },
425         { 112, 0x00b33, 0x0128d, 0x2e014, 0x30286 },
426         { 116, 0x00b33, 0x0128e, 0x2e014, 0x30288 },
427         { 120, 0x00b33, 0x012a0, 0x2e014, 0x30280 },
428         { 124, 0x00b33, 0x012a1, 0x2e014, 0x30282 },
429         { 128, 0x00b33, 0x012a2, 0x2e014, 0x30284 },
430         { 132, 0x00b33, 0x012a3, 0x2e014, 0x30286 },
431         { 136, 0x00b33, 0x012a4, 0x2e014, 0x30288 },
432         { 140, 0x00b33, 0x012a6, 0x2e014, 0x30280 },
433
434         { 149, 0x00b33, 0x012a8, 0x2e014, 0x30287 },
435         { 153, 0x00b33, 0x012a9, 0x2e014, 0x30289 },
436         { 157, 0x00b33, 0x012ab, 0x2e014, 0x30281 },
437         { 161, 0x00b33, 0x012ac, 0x2e014, 0x30283 },
438         { 165, 0x00b33, 0x012ad, 0x2e014, 0x30285 }
439 };
440
441 static const struct usb_config rum_config[RUM_N_TRANSFER] = {
442         [RUM_BULK_WR] = {
443                 .type = UE_BULK,
444                 .endpoint = UE_ADDR_ANY,
445                 .direction = UE_DIR_OUT,
446                 .bufsize = (MCLBYTES + RT2573_TX_DESC_SIZE + 8),
447                 .flags = {.pipe_bof = 1,.force_short_xfer = 1,},
448                 .callback = rum_bulk_write_callback,
449                 .timeout = 5000,        /* ms */
450         },
451         [RUM_BULK_RD] = {
452                 .type = UE_BULK,
453                 .endpoint = UE_ADDR_ANY,
454                 .direction = UE_DIR_IN,
455                 .bufsize = (MCLBYTES + RT2573_RX_DESC_SIZE),
456                 .flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
457                 .callback = rum_bulk_read_callback,
458         },
459 };
460
461 static int
462 rum_match(device_t self)
463 {
464         struct usb_attach_arg *uaa = device_get_ivars(self);
465
466         if (uaa->usb_mode != USB_MODE_HOST)
467                 return (ENXIO);
468         if (uaa->info.bConfigIndex != 0)
469                 return (ENXIO);
470         if (uaa->info.bIfaceIndex != RT2573_IFACE_INDEX)
471                 return (ENXIO);
472
473         return (usbd_lookup_id_by_uaa(rum_devs, sizeof(rum_devs), uaa));
474 }
475
476 static int
477 rum_attach(device_t self)
478 {
479         struct usb_attach_arg *uaa = device_get_ivars(self);
480         struct rum_softc *sc = device_get_softc(self);
481         struct ieee80211com *ic = &sc->sc_ic;
482         uint32_t tmp;
483         uint8_t iface_index;
484         int error, ntries;
485
486         device_set_usb_desc(self);
487         sc->sc_udev = uaa->device;
488         sc->sc_dev = self;
489
490         RUM_LOCK_INIT(sc);
491         RUM_CMDQ_LOCK_INIT(sc);
492         mbufq_init(&sc->sc_snd, ifqmaxlen);
493
494         iface_index = RT2573_IFACE_INDEX;
495         error = usbd_transfer_setup(uaa->device, &iface_index,
496             sc->sc_xfer, rum_config, RUM_N_TRANSFER, sc, &sc->sc_mtx);
497         if (error) {
498                 device_printf(self, "could not allocate USB transfers, "
499                     "err=%s\n", usbd_errstr(error));
500                 goto detach;
501         }
502
503         RUM_LOCK(sc);
504         /* retrieve RT2573 rev. no */
505         for (ntries = 0; ntries < 100; ntries++) {
506                 if ((tmp = rum_read(sc, RT2573_MAC_CSR0)) != 0)
507                         break;
508                 if (rum_pause(sc, hz / 100))
509                         break;
510         }
511         if (ntries == 100) {
512                 device_printf(sc->sc_dev, "timeout waiting for chip to settle\n");
513                 RUM_UNLOCK(sc);
514                 goto detach;
515         }
516
517         /* retrieve MAC address and various other things from EEPROM */
518         rum_read_eeprom(sc);
519
520         device_printf(sc->sc_dev, "MAC/BBP RT2573 (rev 0x%05x), RF %s\n",
521             tmp, rum_get_rf(sc->rf_rev));
522
523         rum_load_microcode(sc, rt2573_ucode, sizeof(rt2573_ucode));
524         RUM_UNLOCK(sc);
525
526         ic->ic_softc = sc;
527         ic->ic_name = device_get_nameunit(self);
528         ic->ic_phytype = IEEE80211_T_OFDM;      /* not only, but not used */
529
530         /* set device capabilities */
531         ic->ic_caps =
532               IEEE80211_C_STA           /* station mode supported */
533             | IEEE80211_C_IBSS          /* IBSS mode supported */
534             | IEEE80211_C_MONITOR       /* monitor mode supported */
535             | IEEE80211_C_HOSTAP        /* HostAp mode supported */
536             | IEEE80211_C_AHDEMO        /* adhoc demo mode */
537             | IEEE80211_C_TXPMGT        /* tx power management */
538             | IEEE80211_C_SHPREAMBLE    /* short preamble supported */
539             | IEEE80211_C_SHSLOT        /* short slot time supported */
540             | IEEE80211_C_BGSCAN        /* bg scanning supported */
541             | IEEE80211_C_WPA           /* 802.11i */
542             | IEEE80211_C_WME           /* 802.11e */
543             | IEEE80211_C_PMGT          /* Station-side power mgmt */
544             | IEEE80211_C_SWSLEEP       /* net80211 managed power mgmt */
545             ;
546
547         ic->ic_cryptocaps =
548             IEEE80211_CRYPTO_WEP |
549             IEEE80211_CRYPTO_AES_CCM |
550             IEEE80211_CRYPTO_TKIPMIC |
551             IEEE80211_CRYPTO_TKIP;
552
553         rum_getradiocaps(ic, IEEE80211_CHAN_MAX, &ic->ic_nchans,
554             ic->ic_channels);
555
556         ieee80211_ifattach(ic);
557         ic->ic_update_promisc = rum_update_promisc;
558         ic->ic_raw_xmit = rum_raw_xmit;
559         ic->ic_scan_start = rum_scan_start;
560         ic->ic_scan_end = rum_scan_end;
561         ic->ic_set_channel = rum_set_channel;
562         ic->ic_getradiocaps = rum_getradiocaps;
563         ic->ic_transmit = rum_transmit;
564         ic->ic_parent = rum_parent;
565         ic->ic_vap_create = rum_vap_create;
566         ic->ic_vap_delete = rum_vap_delete;
567         ic->ic_updateslot = rum_update_slot;
568         ic->ic_wme.wme_update = rum_wme_update;
569         ic->ic_update_mcast = rum_update_mcast;
570
571         ieee80211_radiotap_attach(ic,
572             &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
573                 RT2573_TX_RADIOTAP_PRESENT,
574             &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
575                 RT2573_RX_RADIOTAP_PRESENT);
576
577         TASK_INIT(&sc->cmdq_task, 0, rum_cmdq_cb, sc);
578
579         if (bootverbose)
580                 ieee80211_announce(ic);
581
582         return (0);
583
584 detach:
585         rum_detach(self);
586         return (ENXIO);                 /* failure */
587 }
588
589 static int
590 rum_detach(device_t self)
591 {
592         struct rum_softc *sc = device_get_softc(self);
593         struct ieee80211com *ic = &sc->sc_ic;
594
595         /* Prevent further ioctls */
596         RUM_LOCK(sc);
597         sc->sc_detached = 1;
598         RUM_UNLOCK(sc);
599
600         /* stop all USB transfers */
601         usbd_transfer_unsetup(sc->sc_xfer, RUM_N_TRANSFER);
602
603         /* free TX list, if any */
604         RUM_LOCK(sc);
605         rum_unsetup_tx_list(sc);
606         RUM_UNLOCK(sc);
607
608         if (ic->ic_softc == sc) {
609                 ieee80211_draintask(ic, &sc->cmdq_task);
610                 ieee80211_ifdetach(ic);
611         }
612
613         mbufq_drain(&sc->sc_snd);
614         RUM_CMDQ_LOCK_DESTROY(sc);
615         RUM_LOCK_DESTROY(sc);
616
617         return (0);
618 }
619
620 static usb_error_t
621 rum_do_request(struct rum_softc *sc,
622     struct usb_device_request *req, void *data)
623 {
624         usb_error_t err;
625         int ntries = 10;
626
627         while (ntries--) {
628                 err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
629                     req, data, 0, NULL, 250 /* ms */);
630                 if (err == 0)
631                         break;
632
633                 DPRINTFN(1, "Control request failed, %s (retrying)\n",
634                     usbd_errstr(err));
635                 if (rum_pause(sc, hz / 100))
636                         break;
637         }
638         return (err);
639 }
640
641 static usb_error_t
642 rum_do_mcu_request(struct rum_softc *sc, int request)
643 {
644         struct usb_device_request req;
645
646         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
647         req.bRequest = RT2573_MCU_CNTL;
648         USETW(req.wValue, request);
649         USETW(req.wIndex, 0);
650         USETW(req.wLength, 0);
651
652         return (rum_do_request(sc, &req, NULL));
653 }
654
655 static struct ieee80211vap *
656 rum_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
657     enum ieee80211_opmode opmode, int flags,
658     const uint8_t bssid[IEEE80211_ADDR_LEN],
659     const uint8_t mac[IEEE80211_ADDR_LEN])
660 {
661         struct rum_softc *sc = ic->ic_softc;
662         struct rum_vap *rvp;
663         struct ieee80211vap *vap;
664
665         if (!TAILQ_EMPTY(&ic->ic_vaps))         /* only one at a time */
666                 return NULL;
667         rvp = malloc(sizeof(struct rum_vap), M_80211_VAP, M_WAITOK | M_ZERO);
668         vap = &rvp->vap;
669         /* enable s/w bmiss handling for sta mode */
670
671         if (ieee80211_vap_setup(ic, vap, name, unit, opmode,
672             flags | IEEE80211_CLONE_NOBEACONS, bssid) != 0) {
673                 /* out of memory */
674                 free(rvp, M_80211_VAP);
675                 return (NULL);
676         }
677
678         /* override state transition machine */
679         rvp->newstate = vap->iv_newstate;
680         vap->iv_newstate = rum_newstate;
681         vap->iv_key_alloc = rum_key_alloc;
682         vap->iv_key_set = rum_key_set;
683         vap->iv_key_delete = rum_key_delete;
684         vap->iv_update_beacon = rum_update_beacon;
685         vap->iv_reset = rum_reset;
686         vap->iv_max_aid = RT2573_ADDR_MAX;
687
688         if (opmode == IEEE80211_M_STA) {
689                 /*
690                  * Move device to the sleep state when
691                  * beacon is received and there is no data for us.
692                  *
693                  * Used only for IEEE80211_S_SLEEP state.
694                  */
695                 rvp->recv_mgmt = vap->iv_recv_mgmt;
696                 vap->iv_recv_mgmt = rum_sta_recv_mgmt;
697
698                 /* Ignored while sleeping. */
699                 rvp->bmiss = vap->iv_bmiss;
700                 vap->iv_bmiss = rum_beacon_miss;
701         }
702
703         usb_callout_init_mtx(&rvp->ratectl_ch, &sc->sc_mtx, 0);
704         TASK_INIT(&rvp->ratectl_task, 0, rum_ratectl_task, rvp);
705         ieee80211_ratectl_init(vap);
706         ieee80211_ratectl_setinterval(vap, 1000 /* 1 sec */);
707         /* complete setup */
708         ieee80211_vap_attach(vap, ieee80211_media_change,
709             ieee80211_media_status, mac);
710         ic->ic_opmode = opmode;
711         return vap;
712 }
713
714 static void
715 rum_vap_delete(struct ieee80211vap *vap)
716 {
717         struct rum_vap *rvp = RUM_VAP(vap);
718         struct ieee80211com *ic = vap->iv_ic;
719
720         m_freem(rvp->bcn_mbuf);
721         usb_callout_drain(&rvp->ratectl_ch);
722         ieee80211_draintask(ic, &rvp->ratectl_task);
723         ieee80211_ratectl_deinit(vap);
724         ieee80211_vap_detach(vap);
725         free(rvp, M_80211_VAP);
726 }
727
728 static void
729 rum_cmdq_cb(void *arg, int pending)
730 {
731         struct rum_softc *sc = arg;
732         struct rum_cmdq *rc;
733
734         RUM_CMDQ_LOCK(sc);
735         while (sc->cmdq[sc->cmdq_first].func != NULL) {
736                 rc = &sc->cmdq[sc->cmdq_first];
737                 RUM_CMDQ_UNLOCK(sc);
738
739                 RUM_LOCK(sc);
740                 rc->func(sc, &rc->data, rc->rvp_id);
741                 RUM_UNLOCK(sc);
742
743                 RUM_CMDQ_LOCK(sc);
744                 memset(rc, 0, sizeof (*rc));
745                 sc->cmdq_first = (sc->cmdq_first + 1) % RUM_CMDQ_SIZE;
746         }
747         RUM_CMDQ_UNLOCK(sc);
748 }
749
750 static int
751 rum_cmd_sleepable(struct rum_softc *sc, const void *ptr, size_t len,
752     uint8_t rvp_id, CMD_FUNC_PROTO)
753 {
754         struct ieee80211com *ic = &sc->sc_ic;
755
756         KASSERT(len <= sizeof(union sec_param), ("buffer overflow"));
757
758         RUM_CMDQ_LOCK(sc);
759         if (sc->cmdq[sc->cmdq_last].func != NULL) {
760                 device_printf(sc->sc_dev, "%s: cmdq overflow\n", __func__);
761                 RUM_CMDQ_UNLOCK(sc);
762
763                 return EAGAIN;
764         }
765
766         if (ptr != NULL)
767                 memcpy(&sc->cmdq[sc->cmdq_last].data, ptr, len);
768         sc->cmdq[sc->cmdq_last].rvp_id = rvp_id;
769         sc->cmdq[sc->cmdq_last].func = func;
770         sc->cmdq_last = (sc->cmdq_last + 1) % RUM_CMDQ_SIZE;
771         RUM_CMDQ_UNLOCK(sc);
772
773         ieee80211_runtask(ic, &sc->cmdq_task);
774
775         return 0;
776 }
777
778 static void
779 rum_tx_free(struct rum_tx_data *data, int txerr)
780 {
781         struct rum_softc *sc = data->sc;
782
783         if (data->m != NULL) {
784                 ieee80211_tx_complete(data->ni, data->m, txerr);
785                 data->m = NULL;
786                 data->ni = NULL;
787         }
788         STAILQ_INSERT_TAIL(&sc->tx_free, data, next);
789         sc->tx_nfree++;
790 }
791
792 static void
793 rum_setup_tx_list(struct rum_softc *sc)
794 {
795         struct rum_tx_data *data;
796         int i;
797
798         sc->tx_nfree = 0;
799         STAILQ_INIT(&sc->tx_q);
800         STAILQ_INIT(&sc->tx_free);
801
802         for (i = 0; i < RUM_TX_LIST_COUNT; i++) {
803                 data = &sc->tx_data[i];
804
805                 data->sc = sc;
806                 STAILQ_INSERT_TAIL(&sc->tx_free, data, next);
807                 sc->tx_nfree++;
808         }
809 }
810
811 static void
812 rum_unsetup_tx_list(struct rum_softc *sc)
813 {
814         struct rum_tx_data *data;
815         int i;
816
817         /* make sure any subsequent use of the queues will fail */
818         sc->tx_nfree = 0;
819         STAILQ_INIT(&sc->tx_q);
820         STAILQ_INIT(&sc->tx_free);
821
822         /* free up all node references and mbufs */
823         for (i = 0; i < RUM_TX_LIST_COUNT; i++) {
824                 data = &sc->tx_data[i];
825
826                 if (data->m != NULL) {
827                         m_freem(data->m);
828                         data->m = NULL;
829                 }
830                 if (data->ni != NULL) {
831                         ieee80211_free_node(data->ni);
832                         data->ni = NULL;
833                 }
834         }
835 }
836
837 static void
838 rum_beacon_miss(struct ieee80211vap *vap)
839 {
840         struct ieee80211com *ic = vap->iv_ic;
841         struct rum_softc *sc = ic->ic_softc;
842         struct rum_vap *rvp = RUM_VAP(vap);
843         int sleep;
844
845         RUM_LOCK(sc);
846         if (sc->sc_sleeping && sc->sc_sleep_end < ticks) {
847                 DPRINTFN(12, "dropping 'sleeping' bit, "
848                     "device must be awake now\n");
849
850                 sc->sc_sleeping = 0;
851         }
852
853         sleep = sc->sc_sleeping;
854         RUM_UNLOCK(sc);
855
856         if (!sleep)
857                 rvp->bmiss(vap);
858 #ifdef USB_DEBUG
859         else
860                 DPRINTFN(13, "bmiss event is ignored whilst sleeping\n");
861 #endif
862 }
863
864 static void
865 rum_sta_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m, int subtype,
866     const struct ieee80211_rx_stats *rxs,
867     int rssi, int nf)
868 {
869         struct ieee80211vap *vap = ni->ni_vap;
870         struct rum_softc *sc = vap->iv_ic->ic_softc;
871         struct rum_vap *rvp = RUM_VAP(vap);
872
873         if (vap->iv_state == IEEE80211_S_SLEEP &&
874             subtype == IEEE80211_FC0_SUBTYPE_BEACON) {
875                 RUM_LOCK(sc);
876                 DPRINTFN(12, "beacon, mybss %d (flags %02X)\n",
877                     !!(sc->last_rx_flags & RT2573_RX_MYBSS),
878                     sc->last_rx_flags);
879
880                 if ((sc->last_rx_flags & (RT2573_RX_MYBSS | RT2573_RX_BC)) ==
881                     (RT2573_RX_MYBSS | RT2573_RX_BC)) {
882                         /*
883                          * Put it to sleep here; in case if there is a data
884                          * for us, iv_recv_mgmt() will wakeup the device via
885                          * SLEEP -> RUN state transition.
886                          */
887                         rum_set_power_state(sc, 1);
888                 }
889                 RUM_UNLOCK(sc);
890         }
891
892         rvp->recv_mgmt(ni, m, subtype, rxs, rssi, nf);
893 }
894
895 static int
896 rum_set_power_state(struct rum_softc *sc, int sleep)
897 {
898         usb_error_t uerror;
899
900         RUM_LOCK_ASSERT(sc);
901
902         DPRINTFN(12, "moving to %s state (sleep time %u)\n",
903             sleep ? "sleep" : "awake", sc->sc_sleep_time);
904
905         uerror = rum_do_mcu_request(sc,
906             sleep ? RT2573_MCU_SLEEP : RT2573_MCU_WAKEUP);
907         if (uerror != USB_ERR_NORMAL_COMPLETION) {
908                 device_printf(sc->sc_dev,
909                     "%s: could not change power state: %s\n",
910                     __func__, usbd_errstr(uerror));
911                 return (EIO);
912         }
913
914         sc->sc_sleeping = !!sleep;
915         sc->sc_sleep_end = sleep ? ticks + sc->sc_sleep_time : 0;
916
917         return (0);
918 }
919
920 static int
921 rum_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
922 {
923         struct rum_vap *rvp = RUM_VAP(vap);
924         struct ieee80211com *ic = vap->iv_ic;
925         struct rum_softc *sc = ic->ic_softc;
926         const struct ieee80211_txparam *tp;
927         enum ieee80211_state ostate;
928         struct ieee80211_node *ni;
929         usb_error_t uerror;
930         int ret = 0;
931
932         ostate = vap->iv_state;
933         DPRINTF("%s -> %s\n",
934                 ieee80211_state_name[ostate],
935                 ieee80211_state_name[nstate]);
936
937         IEEE80211_UNLOCK(ic);
938         RUM_LOCK(sc);
939         usb_callout_stop(&rvp->ratectl_ch);
940
941         if (ostate == IEEE80211_S_SLEEP && vap->iv_opmode == IEEE80211_M_STA) {
942                 rum_clrbits(sc, RT2573_TXRX_CSR4, RT2573_ACKCTS_PWRMGT);
943                 rum_clrbits(sc, RT2573_MAC_CSR11, RT2573_AUTO_WAKEUP);
944
945                 /*
946                  * Ignore any errors;
947                  * any subsequent TX will wakeup it anyway
948                  */
949                 (void) rum_set_power_state(sc, 0);
950         }
951
952         switch (nstate) {
953         case IEEE80211_S_INIT:
954                 if (ostate == IEEE80211_S_RUN)
955                         rum_abort_tsf_sync(sc);
956
957                 break;
958
959         case IEEE80211_S_RUN:
960                 if (ostate == IEEE80211_S_SLEEP)
961                         break;          /* already handled */
962
963                 ni = ieee80211_ref_node(vap->iv_bss);
964
965                 if (vap->iv_opmode != IEEE80211_M_MONITOR) {
966                         if (ic->ic_bsschan == IEEE80211_CHAN_ANYC ||
967                             ni->ni_chan == IEEE80211_CHAN_ANYC) {
968                                 ret = EINVAL;
969                                 goto run_fail;
970                         }
971                         rum_update_slot_cb(sc, NULL, 0);
972                         rum_enable_mrr(sc);
973                         rum_set_txpreamble(sc);
974                         rum_set_basicrates(sc);
975                         rum_set_maxretry(sc, vap);
976                         IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid);
977                         rum_set_bssid(sc, sc->sc_bssid);
978                 }
979
980                 if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
981                     vap->iv_opmode == IEEE80211_M_IBSS) {
982                         if ((ret = rum_alloc_beacon(sc, vap)) != 0)
983                                 goto run_fail;
984                 }
985
986                 if (vap->iv_opmode != IEEE80211_M_MONITOR &&
987                     vap->iv_opmode != IEEE80211_M_AHDEMO) {
988                         if ((ret = rum_enable_tsf_sync(sc)) != 0)
989                                 goto run_fail;
990                 } else
991                         rum_enable_tsf(sc);
992
993                 /* enable automatic rate adaptation */
994                 tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
995                 if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
996                         rum_ratectl_start(sc, ni);
997 run_fail:
998                 ieee80211_free_node(ni);
999                 break;
1000         case IEEE80211_S_SLEEP:
1001                 /* Implemented for STA mode only. */
1002                 if (vap->iv_opmode != IEEE80211_M_STA)
1003                         break;
1004
1005                 uerror = rum_setbits(sc, RT2573_MAC_CSR11, RT2573_AUTO_WAKEUP);
1006                 if (uerror != USB_ERR_NORMAL_COMPLETION) {
1007                         ret = EIO;
1008                         break;
1009                 }
1010
1011                 uerror = rum_setbits(sc, RT2573_TXRX_CSR4, RT2573_ACKCTS_PWRMGT);
1012                 if (uerror != USB_ERR_NORMAL_COMPLETION) {
1013                         ret = EIO;
1014                         break;
1015                 }
1016
1017                 ret = rum_set_power_state(sc, 1);
1018                 if (ret != 0) {
1019                         device_printf(sc->sc_dev,
1020                             "%s: could not move to the SLEEP state: %s\n",
1021                             __func__, usbd_errstr(uerror));
1022                 }
1023                 break;
1024         default:
1025                 break;
1026         }
1027         RUM_UNLOCK(sc);
1028         IEEE80211_LOCK(ic);
1029         return (ret == 0 ? rvp->newstate(vap, nstate, arg) : ret);
1030 }
1031
1032 static void
1033 rum_bulk_write_callback(struct usb_xfer *xfer, usb_error_t error)
1034 {
1035         struct rum_softc *sc = usbd_xfer_softc(xfer);
1036         struct ieee80211vap *vap;
1037         struct rum_tx_data *data;
1038         struct mbuf *m;
1039         struct usb_page_cache *pc;
1040         unsigned int len;
1041         int actlen, sumlen;
1042
1043         usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
1044
1045         switch (USB_GET_STATE(xfer)) {
1046         case USB_ST_TRANSFERRED:
1047                 DPRINTFN(11, "transfer complete, %d bytes\n", actlen);
1048
1049                 /* free resources */
1050                 data = usbd_xfer_get_priv(xfer);
1051                 rum_tx_free(data, 0);
1052                 usbd_xfer_set_priv(xfer, NULL);
1053
1054                 /* FALLTHROUGH */
1055         case USB_ST_SETUP:
1056 tr_setup:
1057                 data = STAILQ_FIRST(&sc->tx_q);
1058                 if (data) {
1059                         STAILQ_REMOVE_HEAD(&sc->tx_q, next);
1060                         m = data->m;
1061
1062                         if (m->m_pkthdr.len > (int)(MCLBYTES + RT2573_TX_DESC_SIZE)) {
1063                                 DPRINTFN(0, "data overflow, %u bytes\n",
1064                                     m->m_pkthdr.len);
1065                                 m->m_pkthdr.len = (MCLBYTES + RT2573_TX_DESC_SIZE);
1066                         }
1067                         pc = usbd_xfer_get_frame(xfer, 0);
1068                         usbd_copy_in(pc, 0, &data->desc, RT2573_TX_DESC_SIZE);
1069                         usbd_m_copy_in(pc, RT2573_TX_DESC_SIZE, m, 0,
1070                             m->m_pkthdr.len);
1071
1072                         vap = data->ni->ni_vap;
1073                         if (ieee80211_radiotap_active_vap(vap)) {
1074                                 struct rum_tx_radiotap_header *tap = &sc->sc_txtap;
1075
1076                                 tap->wt_flags = 0;
1077                                 tap->wt_rate = data->rate;
1078                                 tap->wt_antenna = sc->tx_ant;
1079
1080                                 ieee80211_radiotap_tx(vap, m);
1081                         }
1082
1083                         /* align end on a 4-bytes boundary */
1084                         len = (RT2573_TX_DESC_SIZE + m->m_pkthdr.len + 3) & ~3;
1085                         if ((len % 64) == 0)
1086                                 len += 4;
1087
1088                         DPRINTFN(11, "sending frame len=%u xferlen=%u\n",
1089                             m->m_pkthdr.len, len);
1090
1091                         usbd_xfer_set_frame_len(xfer, 0, len);
1092                         usbd_xfer_set_priv(xfer, data);
1093
1094                         usbd_transfer_submit(xfer);
1095                 }
1096                 rum_start(sc);
1097                 break;
1098
1099         default:                        /* Error */
1100                 DPRINTFN(11, "transfer error, %s\n",
1101                     usbd_errstr(error));
1102
1103                 counter_u64_add(sc->sc_ic.ic_oerrors, 1);
1104                 data = usbd_xfer_get_priv(xfer);
1105                 if (data != NULL) {
1106                         rum_tx_free(data, error);
1107                         usbd_xfer_set_priv(xfer, NULL);
1108                 }
1109
1110                 if (error != USB_ERR_CANCELLED) {
1111                         if (error == USB_ERR_TIMEOUT)
1112                                 device_printf(sc->sc_dev, "device timeout\n");
1113
1114                         /*
1115                          * Try to clear stall first, also if other
1116                          * errors occur, hence clearing stall
1117                          * introduces a 50 ms delay:
1118                          */
1119                         usbd_xfer_set_stall(xfer);
1120                         goto tr_setup;
1121                 }
1122                 break;
1123         }
1124 }
1125
1126 static void
1127 rum_bulk_read_callback(struct usb_xfer *xfer, usb_error_t error)
1128 {
1129         struct rum_softc *sc = usbd_xfer_softc(xfer);
1130         struct ieee80211com *ic = &sc->sc_ic;
1131         struct ieee80211_frame_min *wh;
1132         struct ieee80211_node *ni;
1133         struct mbuf *m = NULL;
1134         struct usb_page_cache *pc;
1135         uint32_t flags;
1136         uint8_t rssi = 0;
1137         int len;
1138
1139         usbd_xfer_status(xfer, &len, NULL, NULL, NULL);
1140
1141         switch (USB_GET_STATE(xfer)) {
1142         case USB_ST_TRANSFERRED:
1143
1144                 DPRINTFN(15, "rx done, actlen=%d\n", len);
1145
1146                 if (len < (int)(RT2573_RX_DESC_SIZE + IEEE80211_MIN_LEN)) {
1147                         DPRINTF("%s: xfer too short %d\n",
1148                             device_get_nameunit(sc->sc_dev), len);
1149                         counter_u64_add(ic->ic_ierrors, 1);
1150                         goto tr_setup;
1151                 }
1152
1153                 len -= RT2573_RX_DESC_SIZE;
1154                 pc = usbd_xfer_get_frame(xfer, 0);
1155                 usbd_copy_out(pc, 0, &sc->sc_rx_desc, RT2573_RX_DESC_SIZE);
1156
1157                 rssi = rum_get_rssi(sc, sc->sc_rx_desc.rssi);
1158                 flags = le32toh(sc->sc_rx_desc.flags);
1159                 sc->last_rx_flags = flags;
1160                 if (flags & RT2573_RX_CRC_ERROR) {
1161                         /*
1162                          * This should not happen since we did not
1163                          * request to receive those frames when we
1164                          * filled RUM_TXRX_CSR2:
1165                          */
1166                         DPRINTFN(5, "PHY or CRC error\n");
1167                         counter_u64_add(ic->ic_ierrors, 1);
1168                         goto tr_setup;
1169                 }
1170                 if ((flags & RT2573_RX_DEC_MASK) != RT2573_RX_DEC_OK) {
1171                         switch (flags & RT2573_RX_DEC_MASK) {
1172                         case RT2573_RX_IV_ERROR:
1173                                 DPRINTFN(5, "IV/EIV error\n");
1174                                 break;
1175                         case RT2573_RX_MIC_ERROR:
1176                                 DPRINTFN(5, "MIC error\n");
1177                                 break;
1178                         case RT2573_RX_KEY_ERROR:
1179                                 DPRINTFN(5, "Key error\n");
1180                                 break;
1181                         }
1182                         counter_u64_add(ic->ic_ierrors, 1);
1183                         goto tr_setup;
1184                 }
1185
1186                 m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1187                 if (m == NULL) {
1188                         DPRINTF("could not allocate mbuf\n");
1189                         counter_u64_add(ic->ic_ierrors, 1);
1190                         goto tr_setup;
1191                 }
1192                 usbd_copy_out(pc, RT2573_RX_DESC_SIZE,
1193                     mtod(m, uint8_t *), len);
1194
1195                 wh = mtod(m, struct ieee80211_frame_min *);
1196
1197                 if ((wh->i_fc[1] & IEEE80211_FC1_PROTECTED) &&
1198                     (flags & RT2573_RX_CIP_MASK) !=
1199                      RT2573_RX_CIP_MODE(RT2573_MODE_NOSEC)) {
1200                         wh->i_fc[1] &= ~IEEE80211_FC1_PROTECTED;
1201                         m->m_flags |= M_WEP;
1202                 }
1203
1204                 /* finalize mbuf */
1205                 m->m_pkthdr.len = m->m_len = (flags >> 16) & 0xfff;
1206
1207                 if (ieee80211_radiotap_active(ic)) {
1208                         struct rum_rx_radiotap_header *tap = &sc->sc_rxtap;
1209
1210                         tap->wr_flags = 0;
1211                         tap->wr_rate = ieee80211_plcp2rate(sc->sc_rx_desc.rate,
1212                             (flags & RT2573_RX_OFDM) ?
1213                             IEEE80211_T_OFDM : IEEE80211_T_CCK);
1214                         rum_get_tsf(sc, &tap->wr_tsf);
1215                         tap->wr_antsignal = RT2573_NOISE_FLOOR + rssi;
1216                         tap->wr_antnoise = RT2573_NOISE_FLOOR;
1217                         tap->wr_antenna = sc->rx_ant;
1218                 }
1219                 /* FALLTHROUGH */
1220         case USB_ST_SETUP:
1221 tr_setup:
1222                 usbd_xfer_set_frame_len(xfer, 0, usbd_xfer_max_len(xfer));
1223                 usbd_transfer_submit(xfer);
1224
1225                 /*
1226                  * At the end of a USB callback it is always safe to unlock
1227                  * the private mutex of a device! That is why we do the
1228                  * "ieee80211_input" here, and not some lines up!
1229                  */
1230                 RUM_UNLOCK(sc);
1231                 if (m) {
1232                         if (m->m_len >= sizeof(struct ieee80211_frame_min))
1233                                 ni = ieee80211_find_rxnode(ic, wh);
1234                         else
1235                                 ni = NULL;
1236
1237                         if (ni != NULL) {
1238                                 (void) ieee80211_input(ni, m, rssi,
1239                                     RT2573_NOISE_FLOOR);
1240                                 ieee80211_free_node(ni);
1241                         } else
1242                                 (void) ieee80211_input_all(ic, m, rssi,
1243                                     RT2573_NOISE_FLOOR);
1244                 }
1245                 RUM_LOCK(sc);
1246                 rum_start(sc);
1247                 return;
1248
1249         default:                        /* Error */
1250                 if (error != USB_ERR_CANCELLED) {
1251                         /* try to clear stall first */
1252                         usbd_xfer_set_stall(xfer);
1253                         goto tr_setup;
1254                 }
1255                 return;
1256         }
1257 }
1258
1259 static uint8_t
1260 rum_plcp_signal(int rate)
1261 {
1262         switch (rate) {
1263         /* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1264         case 12:        return 0xb;
1265         case 18:        return 0xf;
1266         case 24:        return 0xa;
1267         case 36:        return 0xe;
1268         case 48:        return 0x9;
1269         case 72:        return 0xd;
1270         case 96:        return 0x8;
1271         case 108:       return 0xc;
1272
1273         /* CCK rates (NB: not IEEE std, device-specific) */
1274         case 2:         return 0x0;
1275         case 4:         return 0x1;
1276         case 11:        return 0x2;
1277         case 22:        return 0x3;
1278         }
1279         return 0xff;            /* XXX unsupported/unknown rate */
1280 }
1281
1282 /*
1283  * Map net80211 cipher to RT2573 security mode.
1284  */
1285 static uint8_t
1286 rum_crypto_mode(struct rum_softc *sc, u_int cipher, int keylen)
1287 {
1288         switch (cipher) {
1289         case IEEE80211_CIPHER_WEP:
1290                 return (keylen < 8 ? RT2573_MODE_WEP40 : RT2573_MODE_WEP104);
1291         case IEEE80211_CIPHER_TKIP:
1292                 return RT2573_MODE_TKIP;
1293         case IEEE80211_CIPHER_AES_CCM:
1294                 return RT2573_MODE_AES_CCMP;
1295         default:
1296                 device_printf(sc->sc_dev, "unknown cipher %d\n", cipher);
1297                 return 0;
1298         }
1299 }
1300
1301 static void
1302 rum_setup_tx_desc(struct rum_softc *sc, struct rum_tx_desc *desc,
1303     struct ieee80211_key *k, uint32_t flags, uint8_t xflags, uint8_t qid,
1304     int hdrlen, int len, int rate)
1305 {
1306         struct ieee80211com *ic = &sc->sc_ic;
1307         struct wmeParams *wmep = &sc->wme_params[qid];
1308         uint16_t plcp_length;
1309         int remainder;
1310
1311         flags |= RT2573_TX_VALID;
1312         flags |= len << 16;
1313
1314         if (k != NULL && !(k->wk_flags & IEEE80211_KEY_SWCRYPT)) {
1315                 const struct ieee80211_cipher *cip = k->wk_cipher;
1316
1317                 len += cip->ic_header + cip->ic_trailer + cip->ic_miclen;
1318
1319                 desc->eiv = 0;          /* for WEP */
1320                 cip->ic_setiv(k, (uint8_t *)&desc->iv);
1321         }
1322
1323         /* setup PLCP fields */
1324         desc->plcp_signal  = rum_plcp_signal(rate);
1325         desc->plcp_service = 4;
1326
1327         len += IEEE80211_CRC_LEN;
1328         if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM) {
1329                 flags |= RT2573_TX_OFDM;
1330
1331                 plcp_length = len & 0xfff;
1332                 desc->plcp_length_hi = plcp_length >> 6;
1333                 desc->plcp_length_lo = plcp_length & 0x3f;
1334         } else {
1335                 if (rate == 0)
1336                         rate = 2;       /* avoid division by zero */
1337                 plcp_length = howmany(16 * len, rate);
1338                 if (rate == 22) {
1339                         remainder = (16 * len) % 22;
1340                         if (remainder != 0 && remainder < 7)
1341                                 desc->plcp_service |= RT2573_PLCP_LENGEXT;
1342                 }
1343                 desc->plcp_length_hi = plcp_length >> 8;
1344                 desc->plcp_length_lo = plcp_length & 0xff;
1345
1346                 if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1347                         desc->plcp_signal |= 0x08;
1348         }
1349
1350         desc->flags = htole32(flags);
1351         desc->hdrlen = hdrlen;
1352         desc->xflags = xflags;
1353
1354         desc->wme = htole16(RT2573_QID(qid) |
1355             RT2573_AIFSN(wmep->wmep_aifsn) |
1356             RT2573_LOGCWMIN(wmep->wmep_logcwmin) |
1357             RT2573_LOGCWMAX(wmep->wmep_logcwmax));
1358 }
1359
1360 static int
1361 rum_sendprot(struct rum_softc *sc,
1362     const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate)
1363 {
1364         struct ieee80211com *ic = ni->ni_ic;
1365         const struct ieee80211_frame *wh;
1366         struct rum_tx_data *data;
1367         struct mbuf *mprot;
1368         int protrate, pktlen, flags, isshort;
1369         uint16_t dur;
1370
1371         RUM_LOCK_ASSERT(sc);
1372         KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY,
1373             ("protection %d", prot));
1374
1375         wh = mtod(m, const struct ieee80211_frame *);
1376         pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN;
1377
1378         protrate = ieee80211_ctl_rate(ic->ic_rt, rate);
1379
1380         isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0;
1381         dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort)
1382             + ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1383         flags = 0;
1384         if (prot == IEEE80211_PROT_RTSCTS) {
1385                 /* NB: CTS is the same size as an ACK */
1386                 dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1387                 flags |= RT2573_TX_NEED_ACK;
1388                 mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur);
1389         } else {
1390                 mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur);
1391         }
1392         if (mprot == NULL) {
1393                 /* XXX stat + msg */
1394                 return (ENOBUFS);
1395         }
1396         data = STAILQ_FIRST(&sc->tx_free);
1397         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1398         sc->tx_nfree--;
1399
1400         data->m = mprot;
1401         data->ni = ieee80211_ref_node(ni);
1402         data->rate = protrate;
1403         rum_setup_tx_desc(sc, &data->desc, NULL, flags, 0, 0, 0,
1404             mprot->m_pkthdr.len, protrate);
1405
1406         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1407         usbd_transfer_start(sc->sc_xfer[RUM_BULK_WR]);
1408
1409         return 0;
1410 }
1411
1412 static uint32_t
1413 rum_tx_crypto_flags(struct rum_softc *sc, struct ieee80211_node *ni, 
1414     const struct ieee80211_key *k)
1415 {
1416         struct ieee80211vap *vap = ni->ni_vap;
1417         u_int cipher;
1418         uint32_t flags = 0;
1419         uint8_t mode, pos;
1420
1421         if (!(k->wk_flags & IEEE80211_KEY_SWCRYPT)) {
1422                 cipher = k->wk_cipher->ic_cipher;
1423                 pos = k->wk_keyix;
1424                 mode = rum_crypto_mode(sc, cipher, k->wk_keylen);
1425                 if (mode == 0)
1426                         return 0;
1427
1428                 flags |= RT2573_TX_CIP_MODE(mode);
1429
1430                 /* Do not trust GROUP flag */
1431                 if (!(k >= &vap->iv_nw_keys[0] &&
1432                       k < &vap->iv_nw_keys[IEEE80211_WEP_NKID]))
1433                         flags |= RT2573_TX_KEY_PAIR;
1434                 else
1435                         pos += 0 * RT2573_SKEY_MAX;     /* vap id */
1436
1437                 flags |= RT2573_TX_KEY_ID(pos);
1438
1439                 if (cipher == IEEE80211_CIPHER_TKIP)
1440                         flags |= RT2573_TX_TKIPMIC;
1441         }
1442
1443         return flags;
1444 }
1445
1446 static int
1447 rum_tx_mgt(struct rum_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1448 {
1449         struct ieee80211vap *vap = ni->ni_vap;
1450         struct ieee80211com *ic = &sc->sc_ic;
1451         struct rum_tx_data *data;
1452         struct ieee80211_frame *wh;
1453         const struct ieee80211_txparam *tp;
1454         struct ieee80211_key *k = NULL;
1455         uint32_t flags = 0;
1456         uint16_t dur;
1457         uint8_t ac, type, xflags = 0;
1458         int hdrlen;
1459
1460         RUM_LOCK_ASSERT(sc);
1461
1462         data = STAILQ_FIRST(&sc->tx_free);
1463         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1464         sc->tx_nfree--;
1465
1466         wh = mtod(m0, struct ieee80211_frame *);
1467         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1468         hdrlen = ieee80211_anyhdrsize(wh);
1469         ac = M_WME_GETAC(m0);
1470
1471         if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1472                 k = ieee80211_crypto_get_txkey(ni, m0);
1473                 if (k == NULL)
1474                         return (ENOENT);
1475
1476                 if ((k->wk_flags & IEEE80211_KEY_SWCRYPT) &&
1477                     !k->wk_cipher->ic_encap(k, m0))
1478                         return (ENOBUFS);
1479
1480                 wh = mtod(m0, struct ieee80211_frame *);
1481         }
1482
1483         tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1484
1485         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1486                 flags |= RT2573_TX_NEED_ACK;
1487
1488                 dur = ieee80211_ack_duration(ic->ic_rt, tp->mgmtrate, 
1489                     ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1490                 USETW(wh->i_dur, dur);
1491
1492                 /* tell hardware to add timestamp for probe responses */
1493                 if (type == IEEE80211_FC0_TYPE_MGT &&
1494                     (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1495                     IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1496                         flags |= RT2573_TX_TIMESTAMP;
1497         }
1498
1499         if (type != IEEE80211_FC0_TYPE_CTL && !IEEE80211_QOS_HAS_SEQ(wh))
1500                 xflags |= RT2573_TX_HWSEQ;
1501
1502         if (k != NULL)
1503                 flags |= rum_tx_crypto_flags(sc, ni, k);
1504
1505         data->m = m0;
1506         data->ni = ni;
1507         data->rate = tp->mgmtrate;
1508
1509         rum_setup_tx_desc(sc, &data->desc, k, flags, xflags, ac, hdrlen,
1510             m0->m_pkthdr.len, tp->mgmtrate);
1511
1512         DPRINTFN(10, "sending mgt frame len=%d rate=%d\n",
1513             m0->m_pkthdr.len + (int)RT2573_TX_DESC_SIZE, tp->mgmtrate);
1514
1515         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1516         usbd_transfer_start(sc->sc_xfer[RUM_BULK_WR]);
1517
1518         return (0);
1519 }
1520
1521 static int
1522 rum_tx_raw(struct rum_softc *sc, struct mbuf *m0, struct ieee80211_node *ni,
1523     const struct ieee80211_bpf_params *params)
1524 {
1525         struct ieee80211com *ic = ni->ni_ic;
1526         struct ieee80211_frame *wh;
1527         struct rum_tx_data *data;
1528         uint32_t flags;
1529         uint8_t ac, type, xflags = 0;
1530         int rate, error;
1531
1532         RUM_LOCK_ASSERT(sc);
1533
1534         wh = mtod(m0, struct ieee80211_frame *);
1535         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1536
1537         ac = params->ibp_pri & 3;
1538
1539         rate = params->ibp_rate0;
1540         if (!ieee80211_isratevalid(ic->ic_rt, rate))
1541                 return (EINVAL);
1542
1543         flags = 0;
1544         if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
1545                 flags |= RT2573_TX_NEED_ACK;
1546         if (params->ibp_flags & (IEEE80211_BPF_RTS|IEEE80211_BPF_CTS)) {
1547                 error = rum_sendprot(sc, m0, ni,
1548                     params->ibp_flags & IEEE80211_BPF_RTS ?
1549                          IEEE80211_PROT_RTSCTS : IEEE80211_PROT_CTSONLY,
1550                     rate);
1551                 if (error || sc->tx_nfree == 0)
1552                         return (ENOBUFS);
1553
1554                 flags |= RT2573_TX_LONG_RETRY | RT2573_TX_IFS_SIFS;
1555         }
1556
1557         if (type != IEEE80211_FC0_TYPE_CTL && !IEEE80211_QOS_HAS_SEQ(wh))
1558                 xflags |= RT2573_TX_HWSEQ;
1559
1560         data = STAILQ_FIRST(&sc->tx_free);
1561         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1562         sc->tx_nfree--;
1563
1564         data->m = m0;
1565         data->ni = ni;
1566         data->rate = rate;
1567
1568         /* XXX need to setup descriptor ourself */
1569         rum_setup_tx_desc(sc, &data->desc, NULL, flags, xflags, ac, 0,
1570             m0->m_pkthdr.len, rate);
1571
1572         DPRINTFN(10, "sending raw frame len=%u rate=%u\n",
1573             m0->m_pkthdr.len, rate);
1574
1575         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1576         usbd_transfer_start(sc->sc_xfer[RUM_BULK_WR]);
1577
1578         return 0;
1579 }
1580
1581 static int
1582 rum_tx_data(struct rum_softc *sc, struct mbuf *m0, struct ieee80211_node *ni)
1583 {
1584         struct ieee80211vap *vap = ni->ni_vap;
1585         struct ieee80211com *ic = &sc->sc_ic;
1586         struct rum_tx_data *data;
1587         struct ieee80211_frame *wh;
1588         const struct ieee80211_txparam *tp;
1589         struct ieee80211_key *k = NULL;
1590         uint32_t flags = 0;
1591         uint16_t dur;
1592         uint8_t ac, type, qos, xflags = 0;
1593         int error, hdrlen, rate;
1594
1595         RUM_LOCK_ASSERT(sc);
1596
1597         wh = mtod(m0, struct ieee80211_frame *);
1598         type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1599         hdrlen = ieee80211_anyhdrsize(wh);
1600
1601         if (IEEE80211_QOS_HAS_SEQ(wh))
1602                 qos = ((const struct ieee80211_qosframe *)wh)->i_qos[0];
1603         else
1604                 qos = 0;
1605         ac = M_WME_GETAC(m0);
1606
1607         tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
1608         if (IEEE80211_IS_MULTICAST(wh->i_addr1))
1609                 rate = tp->mcastrate;
1610         else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
1611                 rate = tp->ucastrate;
1612         else
1613                 rate = ni->ni_txrate;
1614
1615         if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1616                 k = ieee80211_crypto_get_txkey(ni, m0);
1617                 if (k == NULL) {
1618                         m_freem(m0);
1619                         return (ENOENT);
1620                 }
1621                 if ((k->wk_flags & IEEE80211_KEY_SWCRYPT) &&
1622                     !k->wk_cipher->ic_encap(k, m0)) {
1623                         m_freem(m0);
1624                         return (ENOBUFS);
1625                 }
1626
1627                 /* packet header may have moved, reset our local pointer */
1628                 wh = mtod(m0, struct ieee80211_frame *);
1629         }
1630
1631         if (type != IEEE80211_FC0_TYPE_CTL && !IEEE80211_QOS_HAS_SEQ(wh))
1632                 xflags |= RT2573_TX_HWSEQ;
1633
1634         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1635                 int prot = IEEE80211_PROT_NONE;
1636                 if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold)
1637                         prot = IEEE80211_PROT_RTSCTS;
1638                 else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1639                     ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM)
1640                         prot = ic->ic_protmode;
1641                 if (prot != IEEE80211_PROT_NONE) {
1642                         error = rum_sendprot(sc, m0, ni, prot, rate);
1643                         if (error || sc->tx_nfree == 0) {
1644                                 m_freem(m0);
1645                                 return ENOBUFS;
1646                         }
1647                         flags |= RT2573_TX_LONG_RETRY | RT2573_TX_IFS_SIFS;
1648                 }
1649         }
1650
1651         if (k != NULL)
1652                 flags |= rum_tx_crypto_flags(sc, ni, k);
1653
1654         data = STAILQ_FIRST(&sc->tx_free);
1655         STAILQ_REMOVE_HEAD(&sc->tx_free, next);
1656         sc->tx_nfree--;
1657
1658         data->m = m0;
1659         data->ni = ni;
1660         data->rate = rate;
1661
1662         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1663                 /* Unicast frame, check if an ACK is expected. */
1664                 if (!qos || (qos & IEEE80211_QOS_ACKPOLICY) !=
1665                     IEEE80211_QOS_ACKPOLICY_NOACK)
1666                         flags |= RT2573_TX_NEED_ACK;
1667
1668                 dur = ieee80211_ack_duration(ic->ic_rt, rate,
1669                     ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1670                 USETW(wh->i_dur, dur);
1671         }
1672
1673         rum_setup_tx_desc(sc, &data->desc, k, flags, xflags, ac, hdrlen,
1674             m0->m_pkthdr.len, rate);
1675
1676         DPRINTFN(10, "sending frame len=%d rate=%d\n",
1677             m0->m_pkthdr.len + (int)RT2573_TX_DESC_SIZE, rate);
1678
1679         STAILQ_INSERT_TAIL(&sc->tx_q, data, next);
1680         usbd_transfer_start(sc->sc_xfer[RUM_BULK_WR]);
1681
1682         return 0;
1683 }
1684
1685 static int
1686 rum_transmit(struct ieee80211com *ic, struct mbuf *m)
1687 {
1688         struct rum_softc *sc = ic->ic_softc;
1689         int error;
1690
1691         RUM_LOCK(sc);
1692         if (!sc->sc_running) {
1693                 RUM_UNLOCK(sc);
1694                 return (ENXIO);
1695         }
1696         error = mbufq_enqueue(&sc->sc_snd, m);
1697         if (error) {
1698                 RUM_UNLOCK(sc);
1699                 return (error);
1700         }
1701         rum_start(sc);
1702         RUM_UNLOCK(sc);
1703
1704         return (0);
1705 }
1706
1707 static void
1708 rum_start(struct rum_softc *sc)
1709 {
1710         struct ieee80211_node *ni;
1711         struct mbuf *m;
1712
1713         RUM_LOCK_ASSERT(sc);
1714
1715         if (!sc->sc_running)
1716                 return;
1717
1718         while (sc->tx_nfree >= RUM_TX_MINFREE &&
1719             (m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
1720                 ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1721                 if (rum_tx_data(sc, m, ni) != 0) {
1722                         if_inc_counter(ni->ni_vap->iv_ifp,
1723                             IFCOUNTER_OERRORS, 1);
1724                         ieee80211_free_node(ni);
1725                         break;
1726                 }
1727         }
1728 }
1729
1730 static void
1731 rum_parent(struct ieee80211com *ic)
1732 {
1733         struct rum_softc *sc = ic->ic_softc;
1734         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
1735
1736         RUM_LOCK(sc);
1737         if (sc->sc_detached) {
1738                 RUM_UNLOCK(sc);
1739                 return;
1740         }
1741         RUM_UNLOCK(sc);
1742
1743         if (ic->ic_nrunning > 0) {
1744                 if (rum_init(sc) == 0)
1745                         ieee80211_start_all(ic);
1746                 else
1747                         ieee80211_stop(vap);
1748         } else
1749                 rum_stop(sc);
1750 }
1751
1752 static void
1753 rum_eeprom_read(struct rum_softc *sc, uint16_t addr, void *buf, int len)
1754 {
1755         struct usb_device_request req;
1756         usb_error_t error;
1757
1758         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1759         req.bRequest = RT2573_READ_EEPROM;
1760         USETW(req.wValue, 0);
1761         USETW(req.wIndex, addr);
1762         USETW(req.wLength, len);
1763
1764         error = rum_do_request(sc, &req, buf);
1765         if (error != 0) {
1766                 device_printf(sc->sc_dev, "could not read EEPROM: %s\n",
1767                     usbd_errstr(error));
1768         }
1769 }
1770
1771 static uint32_t
1772 rum_read(struct rum_softc *sc, uint16_t reg)
1773 {
1774         uint32_t val;
1775
1776         rum_read_multi(sc, reg, &val, sizeof val);
1777
1778         return le32toh(val);
1779 }
1780
1781 static void
1782 rum_read_multi(struct rum_softc *sc, uint16_t reg, void *buf, int len)
1783 {
1784         struct usb_device_request req;
1785         usb_error_t error;
1786
1787         req.bmRequestType = UT_READ_VENDOR_DEVICE;
1788         req.bRequest = RT2573_READ_MULTI_MAC;
1789         USETW(req.wValue, 0);
1790         USETW(req.wIndex, reg);
1791         USETW(req.wLength, len);
1792
1793         error = rum_do_request(sc, &req, buf);
1794         if (error != 0) {
1795                 device_printf(sc->sc_dev,
1796                     "could not multi read MAC register: %s\n",
1797                     usbd_errstr(error));
1798         }
1799 }
1800
1801 static usb_error_t
1802 rum_write(struct rum_softc *sc, uint16_t reg, uint32_t val)
1803 {
1804         uint32_t tmp = htole32(val);
1805
1806         return (rum_write_multi(sc, reg, &tmp, sizeof tmp));
1807 }
1808
1809 static usb_error_t
1810 rum_write_multi(struct rum_softc *sc, uint16_t reg, void *buf, size_t len)
1811 {
1812         struct usb_device_request req;
1813         usb_error_t error;
1814         size_t offset;
1815
1816         req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1817         req.bRequest = RT2573_WRITE_MULTI_MAC;
1818         USETW(req.wValue, 0);
1819
1820         /* write at most 64 bytes at a time */
1821         for (offset = 0; offset < len; offset += 64) {
1822                 USETW(req.wIndex, reg + offset);
1823                 USETW(req.wLength, MIN(len - offset, 64));
1824
1825                 error = rum_do_request(sc, &req, (char *)buf + offset);
1826                 if (error != 0) {
1827                         device_printf(sc->sc_dev,
1828                             "could not multi write MAC register: %s\n",
1829                             usbd_errstr(error));
1830                         return (error);
1831                 }
1832         }
1833
1834         return (USB_ERR_NORMAL_COMPLETION);
1835 }
1836
1837 static usb_error_t
1838 rum_setbits(struct rum_softc *sc, uint16_t reg, uint32_t mask)
1839 {
1840         return (rum_write(sc, reg, rum_read(sc, reg) | mask));
1841 }
1842
1843 static usb_error_t
1844 rum_clrbits(struct rum_softc *sc, uint16_t reg, uint32_t mask)
1845 {
1846         return (rum_write(sc, reg, rum_read(sc, reg) & ~mask));
1847 }
1848
1849 static usb_error_t
1850 rum_modbits(struct rum_softc *sc, uint16_t reg, uint32_t set, uint32_t unset)
1851 {
1852         return (rum_write(sc, reg, (rum_read(sc, reg) & ~unset) | set));
1853 }
1854
1855 static int
1856 rum_bbp_busy(struct rum_softc *sc)
1857 {
1858         int ntries;
1859
1860         for (ntries = 0; ntries < 100; ntries++) {
1861                 if (!(rum_read(sc, RT2573_PHY_CSR3) & RT2573_BBP_BUSY))
1862                         break;
1863                 if (rum_pause(sc, hz / 100))
1864                         break;
1865         }
1866         if (ntries == 100)
1867                 return (ETIMEDOUT);
1868
1869         return (0);
1870 }
1871
1872 static void
1873 rum_bbp_write(struct rum_softc *sc, uint8_t reg, uint8_t val)
1874 {
1875         uint32_t tmp;
1876
1877         DPRINTFN(2, "reg=0x%08x\n", reg);
1878
1879         if (rum_bbp_busy(sc) != 0) {
1880                 device_printf(sc->sc_dev, "could not write to BBP\n");
1881                 return;
1882         }
1883
1884         tmp = RT2573_BBP_BUSY | (reg & 0x7f) << 8 | val;
1885         rum_write(sc, RT2573_PHY_CSR3, tmp);
1886 }
1887
1888 static uint8_t
1889 rum_bbp_read(struct rum_softc *sc, uint8_t reg)
1890 {
1891         uint32_t val;
1892         int ntries;
1893
1894         DPRINTFN(2, "reg=0x%08x\n", reg);
1895
1896         if (rum_bbp_busy(sc) != 0) {
1897                 device_printf(sc->sc_dev, "could not read BBP\n");
1898                 return 0;
1899         }
1900
1901         val = RT2573_BBP_BUSY | RT2573_BBP_READ | reg << 8;
1902         rum_write(sc, RT2573_PHY_CSR3, val);
1903
1904         for (ntries = 0; ntries < 100; ntries++) {
1905                 val = rum_read(sc, RT2573_PHY_CSR3);
1906                 if (!(val & RT2573_BBP_BUSY))
1907                         return val & 0xff;
1908                 if (rum_pause(sc, hz / 100))
1909                         break;
1910         }
1911
1912         device_printf(sc->sc_dev, "could not read BBP\n");
1913         return 0;
1914 }
1915
1916 static void
1917 rum_rf_write(struct rum_softc *sc, uint8_t reg, uint32_t val)
1918 {
1919         uint32_t tmp;
1920         int ntries;
1921
1922         for (ntries = 0; ntries < 100; ntries++) {
1923                 if (!(rum_read(sc, RT2573_PHY_CSR4) & RT2573_RF_BUSY))
1924                         break;
1925                 if (rum_pause(sc, hz / 100))
1926                         break;
1927         }
1928         if (ntries == 100) {
1929                 device_printf(sc->sc_dev, "could not write to RF\n");
1930                 return;
1931         }
1932
1933         tmp = RT2573_RF_BUSY | RT2573_RF_20BIT | (val & 0xfffff) << 2 |
1934             (reg & 3);
1935         rum_write(sc, RT2573_PHY_CSR4, tmp);
1936
1937         /* remember last written value in sc */
1938         sc->rf_regs[reg] = val;
1939
1940         DPRINTFN(15, "RF R[%u] <- 0x%05x\n", reg & 3, val & 0xfffff);
1941 }
1942
1943 static void
1944 rum_select_antenna(struct rum_softc *sc)
1945 {
1946         uint8_t bbp4, bbp77;
1947         uint32_t tmp;
1948
1949         bbp4  = rum_bbp_read(sc, 4);
1950         bbp77 = rum_bbp_read(sc, 77);
1951
1952         /* TBD */
1953
1954         /* make sure Rx is disabled before switching antenna */
1955         tmp = rum_read(sc, RT2573_TXRX_CSR0);
1956         rum_write(sc, RT2573_TXRX_CSR0, tmp | RT2573_DISABLE_RX);
1957
1958         rum_bbp_write(sc,  4, bbp4);
1959         rum_bbp_write(sc, 77, bbp77);
1960
1961         rum_write(sc, RT2573_TXRX_CSR0, tmp);
1962 }
1963
1964 /*
1965  * Enable multi-rate retries for frames sent at OFDM rates.
1966  * In 802.11b/g mode, allow fallback to CCK rates.
1967  */
1968 static void
1969 rum_enable_mrr(struct rum_softc *sc)
1970 {
1971         struct ieee80211com *ic = &sc->sc_ic;
1972
1973         if (!IEEE80211_IS_CHAN_5GHZ(ic->ic_bsschan)) {
1974                 rum_setbits(sc, RT2573_TXRX_CSR4,
1975                     RT2573_MRR_ENABLED | RT2573_MRR_CCK_FALLBACK);
1976         } else {
1977                 rum_modbits(sc, RT2573_TXRX_CSR4,
1978                     RT2573_MRR_ENABLED, RT2573_MRR_CCK_FALLBACK);
1979         }
1980 }
1981
1982 static void
1983 rum_set_txpreamble(struct rum_softc *sc)
1984 {
1985         struct ieee80211com *ic = &sc->sc_ic;
1986
1987         if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1988                 rum_setbits(sc, RT2573_TXRX_CSR4, RT2573_SHORT_PREAMBLE);
1989         else
1990                 rum_clrbits(sc, RT2573_TXRX_CSR4, RT2573_SHORT_PREAMBLE);
1991 }
1992
1993 static void
1994 rum_set_basicrates(struct rum_softc *sc)
1995 {
1996         struct ieee80211com *ic = &sc->sc_ic;
1997
1998         /* update basic rate set */
1999         if (ic->ic_curmode == IEEE80211_MODE_11B) {
2000                 /* 11b basic rates: 1, 2Mbps */
2001                 rum_write(sc, RT2573_TXRX_CSR5, 0x3);
2002         } else if (IEEE80211_IS_CHAN_5GHZ(ic->ic_bsschan)) {
2003                 /* 11a basic rates: 6, 12, 24Mbps */
2004                 rum_write(sc, RT2573_TXRX_CSR5, 0x150);
2005         } else {
2006                 /* 11b/g basic rates: 1, 2, 5.5, 11Mbps */
2007                 rum_write(sc, RT2573_TXRX_CSR5, 0xf);
2008         }
2009 }
2010
2011 /*
2012  * Reprogram MAC/BBP to switch to a new band.  Values taken from the reference
2013  * driver.
2014  */
2015 static void
2016 rum_select_band(struct rum_softc *sc, struct ieee80211_channel *c)
2017 {
2018         uint8_t bbp17, bbp35, bbp96, bbp97, bbp98, bbp104;
2019
2020         /* update all BBP registers that depend on the band */
2021         bbp17 = 0x20; bbp96 = 0x48; bbp104 = 0x2c;
2022         bbp35 = 0x50; bbp97 = 0x48; bbp98  = 0x48;
2023         if (IEEE80211_IS_CHAN_5GHZ(c)) {
2024                 bbp17 += 0x08; bbp96 += 0x10; bbp104 += 0x0c;
2025                 bbp35 += 0x10; bbp97 += 0x10; bbp98  += 0x10;
2026         }
2027         if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2028             (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2029                 bbp17 += 0x10; bbp96 += 0x10; bbp104 += 0x10;
2030         }
2031
2032         sc->bbp17 = bbp17;
2033         rum_bbp_write(sc,  17, bbp17);
2034         rum_bbp_write(sc,  96, bbp96);
2035         rum_bbp_write(sc, 104, bbp104);
2036
2037         if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2038             (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2039                 rum_bbp_write(sc, 75, 0x80);
2040                 rum_bbp_write(sc, 86, 0x80);
2041                 rum_bbp_write(sc, 88, 0x80);
2042         }
2043
2044         rum_bbp_write(sc, 35, bbp35);
2045         rum_bbp_write(sc, 97, bbp97);
2046         rum_bbp_write(sc, 98, bbp98);
2047
2048         if (IEEE80211_IS_CHAN_2GHZ(c)) {
2049                 rum_modbits(sc, RT2573_PHY_CSR0, RT2573_PA_PE_2GHZ,
2050                     RT2573_PA_PE_5GHZ);
2051         } else {
2052                 rum_modbits(sc, RT2573_PHY_CSR0, RT2573_PA_PE_5GHZ,
2053                     RT2573_PA_PE_2GHZ);
2054         }
2055 }
2056
2057 static void
2058 rum_set_chan(struct rum_softc *sc, struct ieee80211_channel *c)
2059 {
2060         struct ieee80211com *ic = &sc->sc_ic;
2061         const struct rfprog *rfprog;
2062         uint8_t bbp3, bbp94 = RT2573_BBPR94_DEFAULT;
2063         int8_t power;
2064         int i, chan;
2065
2066         chan = ieee80211_chan2ieee(ic, c);
2067         if (chan == 0 || chan == IEEE80211_CHAN_ANY)
2068                 return;
2069
2070         /* select the appropriate RF settings based on what EEPROM says */
2071         rfprog = (sc->rf_rev == RT2573_RF_5225 ||
2072                   sc->rf_rev == RT2573_RF_2527) ? rum_rf5225 : rum_rf5226;
2073
2074         /* find the settings for this channel (we know it exists) */
2075         for (i = 0; rfprog[i].chan != chan; i++);
2076
2077         power = sc->txpow[i];
2078         if (power < 0) {
2079                 bbp94 += power;
2080                 power = 0;
2081         } else if (power > 31) {
2082                 bbp94 += power - 31;
2083                 power = 31;
2084         }
2085
2086         /*
2087          * If we are switching from the 2GHz band to the 5GHz band or
2088          * vice-versa, BBP registers need to be reprogrammed.
2089          */
2090         if (c->ic_flags != ic->ic_curchan->ic_flags) {
2091                 rum_select_band(sc, c);
2092                 rum_select_antenna(sc);
2093         }
2094         ic->ic_curchan = c;
2095
2096         rum_rf_write(sc, RT2573_RF1, rfprog[i].r1);
2097         rum_rf_write(sc, RT2573_RF2, rfprog[i].r2);
2098         rum_rf_write(sc, RT2573_RF3, rfprog[i].r3 | power << 7);
2099         rum_rf_write(sc, RT2573_RF4, rfprog[i].r4 | sc->rffreq << 10);
2100
2101         rum_rf_write(sc, RT2573_RF1, rfprog[i].r1);
2102         rum_rf_write(sc, RT2573_RF2, rfprog[i].r2);
2103         rum_rf_write(sc, RT2573_RF3, rfprog[i].r3 | power << 7 | 1);
2104         rum_rf_write(sc, RT2573_RF4, rfprog[i].r4 | sc->rffreq << 10);
2105
2106         rum_rf_write(sc, RT2573_RF1, rfprog[i].r1);
2107         rum_rf_write(sc, RT2573_RF2, rfprog[i].r2);
2108         rum_rf_write(sc, RT2573_RF3, rfprog[i].r3 | power << 7);
2109         rum_rf_write(sc, RT2573_RF4, rfprog[i].r4 | sc->rffreq << 10);
2110
2111         rum_pause(sc, hz / 100);
2112
2113         /* enable smart mode for MIMO-capable RFs */
2114         bbp3 = rum_bbp_read(sc, 3);
2115
2116         bbp3 &= ~RT2573_SMART_MODE;
2117         if (sc->rf_rev == RT2573_RF_5225 || sc->rf_rev == RT2573_RF_2527)
2118                 bbp3 |= RT2573_SMART_MODE;
2119
2120         rum_bbp_write(sc, 3, bbp3);
2121
2122         if (bbp94 != RT2573_BBPR94_DEFAULT)
2123                 rum_bbp_write(sc, 94, bbp94);
2124
2125         /* give the chip some extra time to do the switchover */
2126         rum_pause(sc, hz / 100);
2127 }
2128
2129 static void
2130 rum_set_maxretry(struct rum_softc *sc, struct ieee80211vap *vap)
2131 {
2132         const struct ieee80211_txparam *tp;
2133         struct ieee80211_node *ni = vap->iv_bss;
2134         struct rum_vap *rvp = RUM_VAP(vap);
2135
2136         tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
2137         rvp->maxretry = tp->maxretry < 0xf ? tp->maxretry : 0xf;
2138
2139         rum_modbits(sc, RT2573_TXRX_CSR4, RT2573_SHORT_RETRY(rvp->maxretry) |
2140             RT2573_LONG_RETRY(rvp->maxretry),
2141             RT2573_SHORT_RETRY_MASK | RT2573_LONG_RETRY_MASK);
2142 }
2143
2144 /*
2145  * Enable TSF synchronization and tell h/w to start sending beacons for IBSS
2146  * and HostAP operating modes.
2147  */
2148 static int
2149 rum_enable_tsf_sync(struct rum_softc *sc)
2150 {
2151         struct ieee80211com *ic = &sc->sc_ic;
2152         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2153         uint32_t tmp;
2154         uint16_t bintval;
2155
2156         if (vap->iv_opmode != IEEE80211_M_STA) {
2157                 /*
2158                  * Change default 16ms TBTT adjustment to 8ms.
2159                  * Must be done before enabling beacon generation.
2160                  */
2161                 if (rum_write(sc, RT2573_TXRX_CSR10, 1 << 12 | 8) != 0)
2162                         return EIO;
2163         }
2164
2165         tmp = rum_read(sc, RT2573_TXRX_CSR9) & 0xff000000;
2166
2167         /* set beacon interval (in 1/16ms unit) */
2168         bintval = vap->iv_bss->ni_intval;
2169         tmp |= bintval * 16;
2170         tmp |= RT2573_TSF_TIMER_EN | RT2573_TBTT_TIMER_EN;
2171
2172         switch (vap->iv_opmode) {
2173         case IEEE80211_M_STA:
2174                 /*
2175                  * Local TSF is always updated with remote TSF on beacon
2176                  * reception.
2177                  */
2178                 tmp |= RT2573_TSF_SYNC_MODE(RT2573_TSF_SYNC_MODE_STA);
2179                 break;
2180         case IEEE80211_M_IBSS:
2181                 /*
2182                  * Local TSF is updated with remote TSF on beacon reception
2183                  * only if the remote TSF is greater than local TSF.
2184                  */
2185                 tmp |= RT2573_TSF_SYNC_MODE(RT2573_TSF_SYNC_MODE_IBSS);
2186                 tmp |= RT2573_BCN_TX_EN;
2187                 break;
2188         case IEEE80211_M_HOSTAP:
2189                 /* SYNC with nobody */
2190                 tmp |= RT2573_TSF_SYNC_MODE(RT2573_TSF_SYNC_MODE_HOSTAP);
2191                 tmp |= RT2573_BCN_TX_EN;
2192                 break;
2193         default:
2194                 device_printf(sc->sc_dev,
2195                     "Enabling TSF failed. undefined opmode %d\n",
2196                     vap->iv_opmode);
2197                 return EINVAL;
2198         }
2199
2200         if (rum_write(sc, RT2573_TXRX_CSR9, tmp) != 0)
2201                 return EIO;
2202
2203         /* refresh current sleep time */
2204         return (rum_set_sleep_time(sc, bintval));
2205 }
2206
2207 static void
2208 rum_enable_tsf(struct rum_softc *sc)
2209 {
2210         rum_modbits(sc, RT2573_TXRX_CSR9, RT2573_TSF_TIMER_EN |
2211             RT2573_TSF_SYNC_MODE(RT2573_TSF_SYNC_MODE_DIS), 0x00ffffff);
2212 }
2213
2214 static void
2215 rum_abort_tsf_sync(struct rum_softc *sc)
2216 {
2217         rum_clrbits(sc, RT2573_TXRX_CSR9, 0x00ffffff);
2218 }
2219
2220 static void
2221 rum_get_tsf(struct rum_softc *sc, uint64_t *buf)
2222 {
2223         rum_read_multi(sc, RT2573_TXRX_CSR12, buf, sizeof (*buf));
2224 }
2225
2226 static void
2227 rum_update_slot_cb(struct rum_softc *sc, union sec_param *data, uint8_t rvp_id)
2228 {
2229         struct ieee80211com *ic = &sc->sc_ic;
2230         uint8_t slottime;
2231
2232         slottime = IEEE80211_GET_SLOTTIME(ic);
2233
2234         rum_modbits(sc, RT2573_MAC_CSR9, slottime, 0xff);
2235
2236         DPRINTF("setting slot time to %uus\n", slottime);
2237 }
2238
2239 static void
2240 rum_update_slot(struct ieee80211com *ic)
2241 {
2242         rum_cmd_sleepable(ic->ic_softc, NULL, 0, 0, rum_update_slot_cb);
2243 }
2244
2245 static int
2246 rum_wme_update(struct ieee80211com *ic)
2247 {
2248         const struct wmeParams *chanp =
2249             ic->ic_wme.wme_chanParams.cap_wmeParams;
2250         struct rum_softc *sc = ic->ic_softc;
2251         int error = 0;
2252
2253         RUM_LOCK(sc);
2254         error = rum_write(sc, RT2573_AIFSN_CSR,
2255             chanp[WME_AC_VO].wmep_aifsn  << 12 |
2256             chanp[WME_AC_VI].wmep_aifsn  <<  8 |
2257             chanp[WME_AC_BK].wmep_aifsn  <<  4 |
2258             chanp[WME_AC_BE].wmep_aifsn);
2259         if (error)
2260                 goto print_err;
2261         error = rum_write(sc, RT2573_CWMIN_CSR,
2262             chanp[WME_AC_VO].wmep_logcwmin << 12 |
2263             chanp[WME_AC_VI].wmep_logcwmin <<  8 |
2264             chanp[WME_AC_BK].wmep_logcwmin <<  4 |
2265             chanp[WME_AC_BE].wmep_logcwmin);
2266         if (error)
2267                 goto print_err;
2268         error = rum_write(sc, RT2573_CWMAX_CSR,
2269             chanp[WME_AC_VO].wmep_logcwmax << 12 |
2270             chanp[WME_AC_VI].wmep_logcwmax <<  8 |
2271             chanp[WME_AC_BK].wmep_logcwmax <<  4 |
2272             chanp[WME_AC_BE].wmep_logcwmax);
2273         if (error)
2274                 goto print_err;
2275         error = rum_write(sc, RT2573_TXOP01_CSR,
2276             chanp[WME_AC_BK].wmep_txopLimit << 16 |
2277             chanp[WME_AC_BE].wmep_txopLimit);
2278         if (error)
2279                 goto print_err;
2280         error = rum_write(sc, RT2573_TXOP23_CSR,
2281             chanp[WME_AC_VO].wmep_txopLimit << 16 |
2282             chanp[WME_AC_VI].wmep_txopLimit);
2283         if (error)
2284                 goto print_err;
2285
2286         memcpy(sc->wme_params, chanp, sizeof(*chanp) * WME_NUM_AC);
2287
2288 print_err:
2289         RUM_UNLOCK(sc);
2290         if (error != 0) {
2291                 device_printf(sc->sc_dev, "%s: WME update failed, error %d\n",
2292                     __func__, error);
2293         }
2294
2295         return (error);
2296 }
2297
2298 static void
2299 rum_set_bssid(struct rum_softc *sc, const uint8_t *bssid)
2300 {
2301
2302         rum_write(sc, RT2573_MAC_CSR4,
2303             bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24);
2304         rum_write(sc, RT2573_MAC_CSR5,
2305             bssid[4] | bssid[5] << 8 | RT2573_NUM_BSSID_MSK(1));
2306 }
2307
2308 static void
2309 rum_set_macaddr(struct rum_softc *sc, const uint8_t *addr)
2310 {
2311
2312         rum_write(sc, RT2573_MAC_CSR2,
2313             addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24);
2314         rum_write(sc, RT2573_MAC_CSR3,
2315             addr[4] | addr[5] << 8 | 0xff << 16);
2316 }
2317
2318 static void
2319 rum_setpromisc(struct rum_softc *sc)
2320 {
2321         struct ieee80211com *ic = &sc->sc_ic;
2322
2323         if (ic->ic_promisc == 0)
2324                 rum_setbits(sc, RT2573_TXRX_CSR0, RT2573_DROP_NOT_TO_ME);
2325         else
2326                 rum_clrbits(sc, RT2573_TXRX_CSR0, RT2573_DROP_NOT_TO_ME);
2327
2328         DPRINTF("%s promiscuous mode\n", ic->ic_promisc > 0 ?
2329             "entering" : "leaving");
2330 }
2331
2332 static void
2333 rum_update_promisc(struct ieee80211com *ic)
2334 {
2335         struct rum_softc *sc = ic->ic_softc;
2336
2337         RUM_LOCK(sc);
2338         if (sc->sc_running)
2339                 rum_setpromisc(sc);
2340         RUM_UNLOCK(sc);
2341 }
2342
2343 static void
2344 rum_update_mcast(struct ieee80211com *ic)
2345 {
2346         /* Ignore. */
2347 }
2348
2349 static const char *
2350 rum_get_rf(int rev)
2351 {
2352         switch (rev) {
2353         case RT2573_RF_2527:    return "RT2527 (MIMO XR)";
2354         case RT2573_RF_2528:    return "RT2528";
2355         case RT2573_RF_5225:    return "RT5225 (MIMO XR)";
2356         case RT2573_RF_5226:    return "RT5226";
2357         default:                return "unknown";
2358         }
2359 }
2360
2361 static void
2362 rum_read_eeprom(struct rum_softc *sc)
2363 {
2364         uint16_t val;
2365 #ifdef RUM_DEBUG
2366         int i;
2367 #endif
2368
2369         /* read MAC address */
2370         rum_eeprom_read(sc, RT2573_EEPROM_ADDRESS, sc->sc_ic.ic_macaddr, 6);
2371
2372         rum_eeprom_read(sc, RT2573_EEPROM_ANTENNA, &val, 2);
2373         val = le16toh(val);
2374         sc->rf_rev =   (val >> 11) & 0x1f;
2375         sc->hw_radio = (val >> 10) & 0x1;
2376         sc->rx_ant =   (val >> 4)  & 0x3;
2377         sc->tx_ant =   (val >> 2)  & 0x3;
2378         sc->nb_ant =   val & 0x3;
2379
2380         DPRINTF("RF revision=%d\n", sc->rf_rev);
2381
2382         rum_eeprom_read(sc, RT2573_EEPROM_CONFIG2, &val, 2);
2383         val = le16toh(val);
2384         sc->ext_5ghz_lna = (val >> 6) & 0x1;
2385         sc->ext_2ghz_lna = (val >> 4) & 0x1;
2386
2387         DPRINTF("External 2GHz LNA=%d\nExternal 5GHz LNA=%d\n",
2388             sc->ext_2ghz_lna, sc->ext_5ghz_lna);
2389
2390         rum_eeprom_read(sc, RT2573_EEPROM_RSSI_2GHZ_OFFSET, &val, 2);
2391         val = le16toh(val);
2392         if ((val & 0xff) != 0xff)
2393                 sc->rssi_2ghz_corr = (int8_t)(val & 0xff);      /* signed */
2394
2395         /* Only [-10, 10] is valid */
2396         if (sc->rssi_2ghz_corr < -10 || sc->rssi_2ghz_corr > 10)
2397                 sc->rssi_2ghz_corr = 0;
2398
2399         rum_eeprom_read(sc, RT2573_EEPROM_RSSI_5GHZ_OFFSET, &val, 2);
2400         val = le16toh(val);
2401         if ((val & 0xff) != 0xff)
2402                 sc->rssi_5ghz_corr = (int8_t)(val & 0xff);      /* signed */
2403
2404         /* Only [-10, 10] is valid */
2405         if (sc->rssi_5ghz_corr < -10 || sc->rssi_5ghz_corr > 10)
2406                 sc->rssi_5ghz_corr = 0;
2407
2408         if (sc->ext_2ghz_lna)
2409                 sc->rssi_2ghz_corr -= 14;
2410         if (sc->ext_5ghz_lna)
2411                 sc->rssi_5ghz_corr -= 14;
2412
2413         DPRINTF("RSSI 2GHz corr=%d\nRSSI 5GHz corr=%d\n",
2414             sc->rssi_2ghz_corr, sc->rssi_5ghz_corr);
2415
2416         rum_eeprom_read(sc, RT2573_EEPROM_FREQ_OFFSET, &val, 2);
2417         val = le16toh(val);
2418         if ((val & 0xff) != 0xff)
2419                 sc->rffreq = val & 0xff;
2420
2421         DPRINTF("RF freq=%d\n", sc->rffreq);
2422
2423         /* read Tx power for all a/b/g channels */
2424         rum_eeprom_read(sc, RT2573_EEPROM_TXPOWER, sc->txpow, 14);
2425         /* XXX default Tx power for 802.11a channels */
2426         memset(sc->txpow + 14, 24, sizeof (sc->txpow) - 14);
2427 #ifdef RUM_DEBUG
2428         for (i = 0; i < 14; i++)
2429                 DPRINTF("Channel=%d Tx power=%d\n", i + 1,  sc->txpow[i]);
2430 #endif
2431
2432         /* read default values for BBP registers */
2433         rum_eeprom_read(sc, RT2573_EEPROM_BBP_BASE, sc->bbp_prom, 2 * 16);
2434 #ifdef RUM_DEBUG
2435         for (i = 0; i < 14; i++) {
2436                 if (sc->bbp_prom[i].reg == 0 || sc->bbp_prom[i].reg == 0xff)
2437                         continue;
2438                 DPRINTF("BBP R%d=%02x\n", sc->bbp_prom[i].reg,
2439                     sc->bbp_prom[i].val);
2440         }
2441 #endif
2442 }
2443
2444 static int
2445 rum_bbp_wakeup(struct rum_softc *sc)
2446 {
2447         unsigned int ntries;
2448
2449         for (ntries = 0; ntries < 100; ntries++) {
2450                 if (rum_read(sc, RT2573_MAC_CSR12) & 8)
2451                         break;
2452                 rum_write(sc, RT2573_MAC_CSR12, 4);     /* force wakeup */
2453                 if (rum_pause(sc, hz / 100))
2454                         break;
2455         }
2456         if (ntries == 100) {
2457                 device_printf(sc->sc_dev,
2458                     "timeout waiting for BBP/RF to wakeup\n");
2459                 return (ETIMEDOUT);
2460         }
2461
2462         return (0);
2463 }
2464
2465 static int
2466 rum_bbp_init(struct rum_softc *sc)
2467 {
2468         int i, ntries;
2469
2470         /* wait for BBP to be ready */
2471         for (ntries = 0; ntries < 100; ntries++) {
2472                 const uint8_t val = rum_bbp_read(sc, 0);
2473                 if (val != 0 && val != 0xff)
2474                         break;
2475                 if (rum_pause(sc, hz / 100))
2476                         break;
2477         }
2478         if (ntries == 100) {
2479                 device_printf(sc->sc_dev, "timeout waiting for BBP\n");
2480                 return EIO;
2481         }
2482
2483         /* initialize BBP registers to default values */
2484         for (i = 0; i < nitems(rum_def_bbp); i++)
2485                 rum_bbp_write(sc, rum_def_bbp[i].reg, rum_def_bbp[i].val);
2486
2487         /* write vendor-specific BBP values (from EEPROM) */
2488         for (i = 0; i < 16; i++) {
2489                 if (sc->bbp_prom[i].reg == 0 || sc->bbp_prom[i].reg == 0xff)
2490                         continue;
2491                 rum_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2492         }
2493
2494         return 0;
2495 }
2496
2497 static void
2498 rum_clr_shkey_regs(struct rum_softc *sc)
2499 {
2500         rum_write(sc, RT2573_SEC_CSR0, 0);
2501         rum_write(sc, RT2573_SEC_CSR1, 0);
2502         rum_write(sc, RT2573_SEC_CSR5, 0);
2503 }
2504
2505 static int
2506 rum_init(struct rum_softc *sc)
2507 {
2508         struct ieee80211com *ic = &sc->sc_ic;
2509         struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2510         uint32_t tmp;
2511         int i, ret;
2512
2513         RUM_LOCK(sc);
2514         if (sc->sc_running) {
2515                 ret = 0;
2516                 goto end;
2517         }
2518
2519         /* initialize MAC registers to default values */
2520         for (i = 0; i < nitems(rum_def_mac); i++)
2521                 rum_write(sc, rum_def_mac[i].reg, rum_def_mac[i].val);
2522
2523         /* reset some WME parameters to default values */
2524         sc->wme_params[0].wmep_aifsn = 2;
2525         sc->wme_params[0].wmep_logcwmin = 4;
2526         sc->wme_params[0].wmep_logcwmax = 10;
2527
2528         /* set host ready */
2529         rum_write(sc, RT2573_MAC_CSR1, RT2573_RESET_ASIC | RT2573_RESET_BBP);
2530         rum_write(sc, RT2573_MAC_CSR1, 0);
2531
2532         /* wait for BBP/RF to wakeup */
2533         if ((ret = rum_bbp_wakeup(sc)) != 0)
2534                 goto end;
2535
2536         if ((ret = rum_bbp_init(sc)) != 0)
2537                 goto end;
2538
2539         /* select default channel */
2540         rum_select_band(sc, ic->ic_curchan);
2541         rum_select_antenna(sc);
2542         rum_set_chan(sc, ic->ic_curchan);
2543
2544         /* clear STA registers */
2545         rum_read_multi(sc, RT2573_STA_CSR0, sc->sta, sizeof sc->sta);
2546
2547         /* clear security registers (if required) */
2548         if (sc->sc_clr_shkeys == 0) {
2549                 rum_clr_shkey_regs(sc);
2550                 sc->sc_clr_shkeys = 1;
2551         }
2552
2553         rum_set_macaddr(sc, vap ? vap->iv_myaddr : ic->ic_macaddr);
2554
2555         /* initialize ASIC */
2556         rum_write(sc, RT2573_MAC_CSR1, RT2573_HOST_READY);
2557
2558         /*
2559          * Allocate Tx and Rx xfer queues.
2560          */
2561         rum_setup_tx_list(sc);
2562
2563         /* update Rx filter */
2564         tmp = rum_read(sc, RT2573_TXRX_CSR0) & 0xffff;
2565
2566         tmp |= RT2573_DROP_PHY_ERROR | RT2573_DROP_CRC_ERROR;
2567         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2568                 tmp |= RT2573_DROP_CTL | RT2573_DROP_VER_ERROR |
2569                        RT2573_DROP_ACKCTS;
2570                 if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2571                         tmp |= RT2573_DROP_TODS;
2572                 if (ic->ic_promisc == 0)
2573                         tmp |= RT2573_DROP_NOT_TO_ME;
2574         }
2575         rum_write(sc, RT2573_TXRX_CSR0, tmp);
2576
2577         sc->sc_running = 1;
2578         usbd_xfer_set_stall(sc->sc_xfer[RUM_BULK_WR]);
2579         usbd_transfer_start(sc->sc_xfer[RUM_BULK_RD]);
2580
2581 end:    RUM_UNLOCK(sc);
2582
2583         if (ret != 0)
2584                 rum_stop(sc);
2585
2586         return ret;
2587 }
2588
2589 static void
2590 rum_stop(struct rum_softc *sc)
2591 {
2592
2593         RUM_LOCK(sc);
2594         if (!sc->sc_running) {
2595                 RUM_UNLOCK(sc);
2596                 return;
2597         }
2598         sc->sc_running = 0;
2599         RUM_UNLOCK(sc);
2600
2601         /*
2602          * Drain the USB transfers, if not already drained:
2603          */
2604         usbd_transfer_drain(sc->sc_xfer[RUM_BULK_WR]);
2605         usbd_transfer_drain(sc->sc_xfer[RUM_BULK_RD]);
2606
2607         RUM_LOCK(sc);
2608         rum_unsetup_tx_list(sc);
2609
2610         /* disable Rx */
2611         rum_setbits(sc, RT2573_TXRX_CSR0, RT2573_DISABLE_RX);
2612
2613         /* reset ASIC */
2614         rum_write(sc, RT2573_MAC_CSR1, RT2573_RESET_ASIC | RT2573_RESET_BBP);
2615         rum_write(sc, RT2573_MAC_CSR1, 0);
2616         RUM_UNLOCK(sc);
2617 }
2618
2619 static void
2620 rum_load_microcode(struct rum_softc *sc, const uint8_t *ucode, size_t size)
2621 {
2622         uint16_t reg = RT2573_MCU_CODE_BASE;
2623         usb_error_t err;
2624
2625         /* copy firmware image into NIC */
2626         for (; size >= 4; reg += 4, ucode += 4, size -= 4) {
2627                 err = rum_write(sc, reg, UGETDW(ucode));
2628                 if (err) {
2629                         /* firmware already loaded ? */
2630                         device_printf(sc->sc_dev, "Firmware load "
2631                             "failure! (ignored)\n");
2632                         break;
2633                 }
2634         }
2635
2636         err = rum_do_mcu_request(sc, RT2573_MCU_RUN);
2637         if (err != USB_ERR_NORMAL_COMPLETION) {
2638                 device_printf(sc->sc_dev, "could not run firmware: %s\n",
2639                     usbd_errstr(err));
2640         }
2641
2642         /* give the chip some time to boot */
2643         rum_pause(sc, hz / 8);
2644 }
2645
2646 static int
2647 rum_set_sleep_time(struct rum_softc *sc, uint16_t bintval)
2648 {
2649         struct ieee80211com *ic = &sc->sc_ic;
2650         usb_error_t uerror;
2651         int exp, delay;
2652
2653         RUM_LOCK_ASSERT(sc);
2654
2655         exp = ic->ic_lintval / bintval;
2656         delay = ic->ic_lintval % bintval;
2657
2658         if (exp > RT2573_TBCN_EXP_MAX)
2659                 exp = RT2573_TBCN_EXP_MAX;
2660         if (delay > RT2573_TBCN_DELAY_MAX)
2661                 delay = RT2573_TBCN_DELAY_MAX;
2662
2663         uerror = rum_modbits(sc, RT2573_MAC_CSR11,
2664             RT2573_TBCN_EXP(exp) |
2665             RT2573_TBCN_DELAY(delay),
2666             RT2573_TBCN_EXP(RT2573_TBCN_EXP_MAX) |
2667             RT2573_TBCN_DELAY(RT2573_TBCN_DELAY_MAX));
2668
2669         if (uerror != USB_ERR_NORMAL_COMPLETION)
2670                 return (EIO);
2671
2672         sc->sc_sleep_time = IEEE80211_TU_TO_TICKS(exp * bintval + delay);
2673
2674         return (0);
2675 }
2676
2677 static int
2678 rum_reset(struct ieee80211vap *vap, u_long cmd)
2679 {
2680         struct ieee80211com *ic = vap->iv_ic;
2681         struct ieee80211_node *ni;
2682         struct rum_softc *sc = ic->ic_softc;
2683         int error;
2684
2685         switch (cmd) {
2686         case IEEE80211_IOC_POWERSAVE:
2687                 error = 0;
2688                 break;
2689         case IEEE80211_IOC_POWERSAVESLEEP:
2690                 ni = ieee80211_ref_node(vap->iv_bss);
2691
2692                 RUM_LOCK(sc);
2693                 error = rum_set_sleep_time(sc, ni->ni_intval);
2694                 if (vap->iv_state == IEEE80211_S_SLEEP) {
2695                         /* Use new values for wakeup timer. */
2696                         rum_clrbits(sc, RT2573_MAC_CSR11, RT2573_AUTO_WAKEUP);
2697                         rum_setbits(sc, RT2573_MAC_CSR11, RT2573_AUTO_WAKEUP);
2698                 }
2699                 /* XXX send reassoc */
2700                 RUM_UNLOCK(sc);
2701
2702                 ieee80211_free_node(ni);
2703                 break;
2704         default:
2705                 error = ENETRESET;
2706                 break;
2707         }
2708
2709         return (error);
2710 }
2711
2712 static int
2713 rum_set_beacon(struct rum_softc *sc, struct ieee80211vap *vap)
2714 {
2715         struct ieee80211com *ic = vap->iv_ic;
2716         struct rum_vap *rvp = RUM_VAP(vap);
2717         struct mbuf *m = rvp->bcn_mbuf;
2718         const struct ieee80211_txparam *tp;
2719         struct rum_tx_desc desc;
2720
2721         RUM_LOCK_ASSERT(sc);
2722
2723         if (m == NULL)
2724                 return EINVAL;
2725         if (ic->ic_bsschan == IEEE80211_CHAN_ANYC)
2726                 return EINVAL;
2727
2728         tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_bsschan)];
2729         rum_setup_tx_desc(sc, &desc, NULL, RT2573_TX_TIMESTAMP,
2730             RT2573_TX_HWSEQ, 0, 0, m->m_pkthdr.len, tp->mgmtrate);
2731
2732         /* copy the Tx descriptor into NIC memory */
2733         if (rum_write_multi(sc, RT2573_HW_BCN_BASE(0), (uint8_t *)&desc,
2734             RT2573_TX_DESC_SIZE) != 0)
2735                 return EIO;
2736
2737         /* copy beacon header and payload into NIC memory */
2738         if (rum_write_multi(sc, RT2573_HW_BCN_BASE(0) + RT2573_TX_DESC_SIZE,
2739             mtod(m, uint8_t *), m->m_pkthdr.len) != 0)
2740                 return EIO;
2741
2742         return 0;
2743 }
2744
2745 static int
2746 rum_alloc_beacon(struct rum_softc *sc, struct ieee80211vap *vap)
2747 {
2748         struct rum_vap *rvp = RUM_VAP(vap);
2749         struct ieee80211_node *ni = vap->iv_bss;
2750         struct mbuf *m;
2751
2752         if (ni->ni_chan == IEEE80211_CHAN_ANYC)
2753                 return EINVAL;
2754
2755         m = ieee80211_beacon_alloc(ni);
2756         if (m == NULL)
2757                 return ENOMEM;
2758
2759         if (rvp->bcn_mbuf != NULL)
2760                 m_freem(rvp->bcn_mbuf);
2761
2762         rvp->bcn_mbuf = m;
2763
2764         return (rum_set_beacon(sc, vap));
2765 }
2766
2767 static void
2768 rum_update_beacon_cb(struct rum_softc *sc, union sec_param *data,
2769     uint8_t rvp_id)
2770 {
2771         struct ieee80211vap *vap = data->vap;
2772
2773         rum_set_beacon(sc, vap);
2774 }
2775
2776 static void
2777 rum_update_beacon(struct ieee80211vap *vap, int item)
2778 {
2779         struct ieee80211com *ic = vap->iv_ic;
2780         struct rum_softc *sc = ic->ic_softc;
2781         struct rum_vap *rvp = RUM_VAP(vap);
2782         struct ieee80211_beacon_offsets *bo = &vap->iv_bcn_off;
2783         struct ieee80211_node *ni = vap->iv_bss;
2784         struct mbuf *m = rvp->bcn_mbuf;
2785         int mcast = 0;
2786
2787         RUM_LOCK(sc);
2788         if (m == NULL) {
2789                 m = ieee80211_beacon_alloc(ni);
2790                 if (m == NULL) {
2791                         device_printf(sc->sc_dev,
2792                             "%s: could not allocate beacon frame\n", __func__);
2793                         RUM_UNLOCK(sc);
2794                         return;
2795                 }
2796                 rvp->bcn_mbuf = m;
2797         }
2798
2799         switch (item) {
2800         case IEEE80211_BEACON_ERP:
2801                 rum_update_slot(ic);
2802                 break;
2803         case IEEE80211_BEACON_TIM:
2804                 mcast = 1;      /*TODO*/
2805                 break;
2806         default:
2807                 break;
2808         }
2809         RUM_UNLOCK(sc);
2810
2811         setbit(bo->bo_flags, item);
2812         ieee80211_beacon_update(ni, m, mcast);
2813
2814         rum_cmd_sleepable(sc, &vap, sizeof(vap), 0, rum_update_beacon_cb);
2815 }
2816
2817 static int
2818 rum_common_key_set(struct rum_softc *sc, struct ieee80211_key *k,
2819     uint16_t base)
2820 {
2821
2822         if (rum_write_multi(sc, base, k->wk_key, k->wk_keylen))
2823                 return EIO;
2824
2825         if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP) {
2826                 if (rum_write_multi(sc, base + IEEE80211_KEYBUF_SIZE,
2827                     k->wk_txmic, 8))
2828                         return EIO;
2829                 if (rum_write_multi(sc, base + IEEE80211_KEYBUF_SIZE + 8,
2830                     k->wk_rxmic, 8))
2831                         return EIO;
2832         }
2833
2834         return 0;
2835 }
2836
2837 static void
2838 rum_group_key_set_cb(struct rum_softc *sc, union sec_param *data,
2839     uint8_t rvp_id) 
2840 {
2841         struct ieee80211_key *k = &data->key;
2842         uint8_t mode;
2843
2844         if (sc->sc_clr_shkeys == 0) {
2845                 rum_clr_shkey_regs(sc);
2846                 sc->sc_clr_shkeys = 1;
2847         }
2848
2849         mode = rum_crypto_mode(sc, k->wk_cipher->ic_cipher, k->wk_keylen);
2850         if (mode == 0)
2851                 goto print_err;
2852
2853         DPRINTFN(1, "setting group key %d for vap %d, mode %d "
2854             "(tx %s, rx %s)\n", k->wk_keyix, rvp_id, mode,
2855             (k->wk_flags & IEEE80211_KEY_XMIT) ? "on" : "off",
2856             (k->wk_flags & IEEE80211_KEY_RECV) ? "on" : "off");
2857
2858         /* Install the key. */
2859         if (rum_common_key_set(sc, k, RT2573_SKEY(rvp_id, k->wk_keyix)) != 0)
2860                 goto print_err;
2861
2862         /* Set cipher mode. */
2863         if (rum_modbits(sc, rvp_id < 2 ? RT2573_SEC_CSR1 : RT2573_SEC_CSR5,
2864               mode << (rvp_id % 2 + k->wk_keyix) * RT2573_SKEY_MAX,
2865               RT2573_MODE_MASK << (rvp_id % 2 + k->wk_keyix) * RT2573_SKEY_MAX)
2866             != 0)
2867                 goto print_err;
2868
2869         /* Mark this key as valid. */
2870         if (rum_setbits(sc, RT2573_SEC_CSR0,
2871               1 << (rvp_id * RT2573_SKEY_MAX + k->wk_keyix)) != 0)
2872                 goto print_err;
2873
2874         return;
2875
2876 print_err:
2877         device_printf(sc->sc_dev, "%s: cannot set group key %d for vap %d\n",
2878             __func__, k->wk_keyix, rvp_id);
2879 }
2880
2881 static void
2882 rum_group_key_del_cb(struct rum_softc *sc, union sec_param *data,
2883     uint8_t rvp_id)
2884 {
2885         struct ieee80211_key *k = &data->key;
2886
2887         DPRINTF("%s: removing group key %d for vap %d\n", __func__,
2888             k->wk_keyix, rvp_id);
2889         rum_clrbits(sc,
2890             rvp_id < 2 ? RT2573_SEC_CSR1 : RT2573_SEC_CSR5,
2891             RT2573_MODE_MASK << (rvp_id % 2 + k->wk_keyix) * RT2573_SKEY_MAX);
2892         rum_clrbits(sc, RT2573_SEC_CSR0,
2893             rvp_id * RT2573_SKEY_MAX + k->wk_keyix);
2894 }
2895
2896 static void
2897 rum_pair_key_set_cb(struct rum_softc *sc, union sec_param *data,
2898     uint8_t rvp_id)
2899 {
2900         struct ieee80211_key *k = &data->key;
2901         uint8_t buf[IEEE80211_ADDR_LEN + 1];
2902         uint8_t mode;
2903
2904         mode = rum_crypto_mode(sc, k->wk_cipher->ic_cipher, k->wk_keylen);
2905         if (mode == 0)
2906                 goto print_err;
2907
2908         DPRINTFN(1, "setting pairwise key %d for vap %d, mode %d "
2909             "(tx %s, rx %s)\n", k->wk_keyix, rvp_id, mode,
2910             (k->wk_flags & IEEE80211_KEY_XMIT) ? "on" : "off",
2911             (k->wk_flags & IEEE80211_KEY_RECV) ? "on" : "off");
2912
2913         /* Install the key. */
2914         if (rum_common_key_set(sc, k, RT2573_PKEY(k->wk_keyix)) != 0)
2915                 goto print_err;
2916
2917         IEEE80211_ADDR_COPY(buf, k->wk_macaddr);
2918         buf[IEEE80211_ADDR_LEN] = mode;
2919
2920         /* Set transmitter address and cipher mode. */
2921         if (rum_write_multi(sc, RT2573_ADDR_ENTRY(k->wk_keyix),
2922               buf, sizeof buf) != 0)
2923                 goto print_err;
2924
2925         /* Enable key table lookup for this vap. */
2926         if (sc->vap_key_count[rvp_id]++ == 0)
2927                 if (rum_setbits(sc, RT2573_SEC_CSR4, 1 << rvp_id) != 0)
2928                         goto print_err;
2929
2930         /* Mark this key as valid. */
2931         if (rum_setbits(sc,
2932               k->wk_keyix < 32 ? RT2573_SEC_CSR2 : RT2573_SEC_CSR3,
2933               1 << (k->wk_keyix % 32)) != 0)
2934                 goto print_err;
2935
2936         return;
2937
2938 print_err:
2939         device_printf(sc->sc_dev,
2940             "%s: cannot set pairwise key %d, vap %d\n", __func__, k->wk_keyix,
2941             rvp_id);
2942 }
2943
2944 static void
2945 rum_pair_key_del_cb(struct rum_softc *sc, union sec_param *data,
2946     uint8_t rvp_id)
2947 {
2948         struct ieee80211_key *k = &data->key;
2949
2950         DPRINTF("%s: removing key %d\n", __func__, k->wk_keyix);
2951         rum_clrbits(sc, (k->wk_keyix < 32) ? RT2573_SEC_CSR2 : RT2573_SEC_CSR3,
2952             1 << (k->wk_keyix % 32));
2953         sc->keys_bmap &= ~(1ULL << k->wk_keyix);
2954         if (--sc->vap_key_count[rvp_id] == 0)
2955                 rum_clrbits(sc, RT2573_SEC_CSR4, 1 << rvp_id);
2956 }
2957
2958 static int
2959 rum_key_alloc(struct ieee80211vap *vap, struct ieee80211_key *k,
2960     ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
2961 {
2962         struct rum_softc *sc = vap->iv_ic->ic_softc;
2963         uint8_t i;
2964
2965         if (!(&vap->iv_nw_keys[0] <= k &&
2966              k < &vap->iv_nw_keys[IEEE80211_WEP_NKID])) {
2967                 if (!(k->wk_flags & IEEE80211_KEY_SWCRYPT)) {
2968                         RUM_LOCK(sc);
2969                         for (i = 0; i < RT2573_ADDR_MAX; i++) {
2970                                 if ((sc->keys_bmap & (1ULL << i)) == 0) {
2971                                         sc->keys_bmap |= (1ULL << i);
2972                                         *keyix = i;
2973                                         break;
2974                                 }
2975                         }
2976                         RUM_UNLOCK(sc);
2977                         if (i == RT2573_ADDR_MAX) {
2978                                 device_printf(sc->sc_dev,
2979                                     "%s: no free space in the key table\n",
2980                                     __func__);
2981                                 return 0;
2982                         }
2983                 } else
2984                         *keyix = 0;
2985         } else {
2986                 *keyix = k - vap->iv_nw_keys;
2987         }
2988         *rxkeyix = *keyix;
2989         return 1;
2990 }
2991
2992 static int
2993 rum_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k)
2994 {
2995         struct rum_softc *sc = vap->iv_ic->ic_softc;
2996         int group;
2997
2998         if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
2999                 /* Not for us. */
3000                 return 1;
3001         }
3002
3003         group = k >= &vap->iv_nw_keys[0] && k < &vap->iv_nw_keys[IEEE80211_WEP_NKID];
3004
3005         return !rum_cmd_sleepable(sc, k, sizeof(*k), 0,
3006                    group ? rum_group_key_set_cb : rum_pair_key_set_cb);
3007 }
3008
3009 static int
3010 rum_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
3011 {
3012         struct rum_softc *sc = vap->iv_ic->ic_softc;
3013         int group;
3014
3015         if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
3016                 /* Not for us. */
3017                 return 1;
3018         }
3019
3020         group = k >= &vap->iv_nw_keys[0] && k < &vap->iv_nw_keys[IEEE80211_WEP_NKID];
3021
3022         return !rum_cmd_sleepable(sc, k, sizeof(*k), 0,
3023                    group ? rum_group_key_del_cb : rum_pair_key_del_cb);
3024 }
3025
3026 static int
3027 rum_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
3028     const struct ieee80211_bpf_params *params)
3029 {
3030         struct rum_softc *sc = ni->ni_ic->ic_softc;
3031         int ret;
3032
3033         RUM_LOCK(sc);
3034         /* prevent management frames from being sent if we're not ready */
3035         if (!sc->sc_running) {
3036                 ret = ENETDOWN;
3037                 goto bad;
3038         }
3039         if (sc->tx_nfree < RUM_TX_MINFREE) {
3040                 ret = EIO;
3041                 goto bad;
3042         }
3043
3044         if (params == NULL) {
3045                 /*
3046                  * Legacy path; interpret frame contents to decide
3047                  * precisely how to send the frame.
3048                  */
3049                 if ((ret = rum_tx_mgt(sc, m, ni)) != 0)
3050                         goto bad;
3051         } else {
3052                 /*
3053                  * Caller supplied explicit parameters to use in
3054                  * sending the frame.
3055                  */
3056                 if ((ret = rum_tx_raw(sc, m, ni, params)) != 0)
3057                         goto bad;
3058         }
3059         RUM_UNLOCK(sc);
3060
3061         return 0;
3062 bad:
3063         RUM_UNLOCK(sc);
3064         m_freem(m);
3065         return ret;
3066 }
3067
3068 static void
3069 rum_ratectl_start(struct rum_softc *sc, struct ieee80211_node *ni)
3070 {
3071         struct ieee80211vap *vap = ni->ni_vap;
3072         struct rum_vap *rvp = RUM_VAP(vap);
3073
3074         /* clear statistic registers (STA_CSR0 to STA_CSR5) */
3075         rum_read_multi(sc, RT2573_STA_CSR0, sc->sta, sizeof sc->sta);
3076
3077         usb_callout_reset(&rvp->ratectl_ch, hz, rum_ratectl_timeout, rvp);
3078 }
3079
3080 static void
3081 rum_ratectl_timeout(void *arg)
3082 {
3083         struct rum_vap *rvp = arg;
3084         struct ieee80211vap *vap = &rvp->vap;
3085         struct ieee80211com *ic = vap->iv_ic;
3086
3087         ieee80211_runtask(ic, &rvp->ratectl_task);
3088 }
3089
3090 static void
3091 rum_ratectl_task(void *arg, int pending)
3092 {
3093         struct rum_vap *rvp = arg;
3094         struct ieee80211vap *vap = &rvp->vap;
3095         struct rum_softc *sc = vap->iv_ic->ic_softc;
3096         struct ieee80211_node *ni;
3097         int ok[3], fail;
3098         int sum, success, retrycnt;
3099
3100         RUM_LOCK(sc);
3101         /* read and clear statistic registers (STA_CSR0 to STA_CSR5) */
3102         rum_read_multi(sc, RT2573_STA_CSR0, sc->sta, sizeof(sc->sta));
3103
3104         ok[0] = (le32toh(sc->sta[4]) & 0xffff); /* TX ok w/o retry */
3105         ok[1] = (le32toh(sc->sta[4]) >> 16);    /* TX ok w/ one retry */
3106         ok[2] = (le32toh(sc->sta[5]) & 0xffff); /* TX ok w/ multiple retries */
3107         fail =  (le32toh(sc->sta[5]) >> 16);    /* TX retry-fail count */
3108
3109         success = ok[0] + ok[1] + ok[2];
3110         sum = success + fail;
3111         /* XXX at least */
3112         retrycnt = ok[1] + ok[2] * 2 + fail * (rvp->maxretry + 1);
3113
3114         if (sum != 0) {
3115                 ni = ieee80211_ref_node(vap->iv_bss);
3116                 ieee80211_ratectl_tx_update(vap, ni, &sum, &ok, &retrycnt);
3117                 (void) ieee80211_ratectl_rate(ni, NULL, 0);
3118                 ieee80211_free_node(ni);
3119         }
3120
3121         /* count TX retry-fail as Tx errors */
3122         if_inc_counter(vap->iv_ifp, IFCOUNTER_OERRORS, fail);
3123
3124         usb_callout_reset(&rvp->ratectl_ch, hz, rum_ratectl_timeout, rvp);
3125         RUM_UNLOCK(sc);
3126 }
3127
3128 static void
3129 rum_scan_start(struct ieee80211com *ic)
3130 {
3131         struct rum_softc *sc = ic->ic_softc;
3132
3133         RUM_LOCK(sc);
3134         rum_abort_tsf_sync(sc);
3135         rum_set_bssid(sc, ieee80211broadcastaddr);
3136         RUM_UNLOCK(sc);
3137
3138 }
3139
3140 static void
3141 rum_scan_end(struct ieee80211com *ic)
3142 {
3143         struct rum_softc *sc = ic->ic_softc;
3144
3145         if (ic->ic_flags_ext & IEEE80211_FEXT_BGSCAN) {
3146                 RUM_LOCK(sc);
3147                 if (ic->ic_opmode != IEEE80211_M_AHDEMO)
3148                         rum_enable_tsf_sync(sc);
3149                 else
3150                         rum_enable_tsf(sc);
3151                 rum_set_bssid(sc, sc->sc_bssid);
3152                 RUM_UNLOCK(sc);
3153         }
3154 }
3155
3156 static void
3157 rum_set_channel(struct ieee80211com *ic)
3158 {
3159         struct rum_softc *sc = ic->ic_softc;
3160
3161         RUM_LOCK(sc);
3162         rum_set_chan(sc, ic->ic_curchan);
3163         RUM_UNLOCK(sc);
3164 }
3165
3166 static void
3167 rum_getradiocaps(struct ieee80211com *ic,
3168     int maxchans, int *nchans, struct ieee80211_channel chans[])
3169 {
3170         struct rum_softc *sc = ic->ic_softc;
3171         uint8_t bands[IEEE80211_MODE_BYTES];
3172
3173         memset(bands, 0, sizeof(bands));
3174         setbit(bands, IEEE80211_MODE_11B);
3175         setbit(bands, IEEE80211_MODE_11G);
3176         ieee80211_add_channels_default_2ghz(chans, maxchans, nchans, bands, 0);
3177
3178         if (sc->rf_rev == RT2573_RF_5225 || sc->rf_rev == RT2573_RF_5226) {
3179                 setbit(bands, IEEE80211_MODE_11A);
3180                 ieee80211_add_channel_list_5ghz(chans, maxchans, nchans,
3181                     rum_chan_5ghz, nitems(rum_chan_5ghz), bands, 0);
3182         }
3183 }
3184
3185 static int
3186 rum_get_rssi(struct rum_softc *sc, uint8_t raw)
3187 {
3188         struct ieee80211com *ic = &sc->sc_ic;
3189         int lna, agc, rssi;
3190
3191         lna = (raw >> 5) & 0x3;
3192         agc = raw & 0x1f;
3193
3194         if (lna == 0) {
3195                 /*
3196                  * No RSSI mapping
3197                  *
3198                  * NB: Since RSSI is relative to noise floor, -1 is
3199                  *     adequate for caller to know error happened.
3200                  */
3201                 return -1;
3202         }
3203
3204         rssi = (2 * agc) - RT2573_NOISE_FLOOR;
3205
3206         if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan)) {
3207                 rssi += sc->rssi_2ghz_corr;
3208
3209                 if (lna == 1)
3210                         rssi -= 64;
3211                 else if (lna == 2)
3212                         rssi -= 74;
3213                 else if (lna == 3)
3214                         rssi -= 90;
3215         } else {
3216                 rssi += sc->rssi_5ghz_corr;
3217
3218                 if (!sc->ext_5ghz_lna && lna != 1)
3219                         rssi += 4;
3220
3221                 if (lna == 1)
3222                         rssi -= 64;
3223                 else if (lna == 2)
3224                         rssi -= 86;
3225                 else if (lna == 3)
3226                         rssi -= 100;
3227         }
3228         return rssi;
3229 }
3230
3231 static int
3232 rum_pause(struct rum_softc *sc, int timeout)
3233 {
3234
3235         usb_pause_mtx(&sc->sc_mtx, timeout);
3236         return (0);
3237 }
3238
3239 static device_method_t rum_methods[] = {
3240         /* Device interface */
3241         DEVMETHOD(device_probe,         rum_match),
3242         DEVMETHOD(device_attach,        rum_attach),
3243         DEVMETHOD(device_detach,        rum_detach),
3244         DEVMETHOD_END
3245 };
3246
3247 static driver_t rum_driver = {
3248         .name = "rum",
3249         .methods = rum_methods,
3250         .size = sizeof(struct rum_softc),
3251 };
3252
3253 static devclass_t rum_devclass;
3254
3255 DRIVER_MODULE(rum, uhub, rum_driver, rum_devclass, NULL, 0);
3256 MODULE_DEPEND(rum, wlan, 1, 1, 1);
3257 MODULE_DEPEND(rum, usb, 1, 1, 1);
3258 MODULE_VERSION(rum, 1);
3259 USB_PNP_HOST_INFO(rum_devs);