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