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