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