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