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