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