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