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