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