xref: /freebsd/sys/dev/usb/wlan/if_run.c (revision 7750ad47a9a7dbc83f87158464170c8640723293)
1 /*-
2  * Copyright (c) 2008,2010 Damien Bergamini <damien.bergamini@free.fr>
3  * ported to FreeBSD by Akinori Furukoshi <moonlightakkiy@yahoo.ca>
4  * USB Consulting, Hans Petter Selasky <hselasky@freebsd.org>
5  *
6  * Permission to use, copy, modify, and distribute this software for any
7  * purpose with or without fee is hereby granted, provided that the above
8  * copyright notice and this permission notice appear in all copies.
9  *
10  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17  */
18 
19 #include <sys/cdefs.h>
20 __FBSDID("$FreeBSD$");
21 
22 /*-
23  * Ralink Technology RT2700U/RT2800U/RT3000U chipset driver.
24  * http://www.ralinktech.com/
25  */
26 
27 #include <sys/param.h>
28 #include <sys/sockio.h>
29 #include <sys/sysctl.h>
30 #include <sys/lock.h>
31 #include <sys/mutex.h>
32 #include <sys/mbuf.h>
33 #include <sys/kernel.h>
34 #include <sys/socket.h>
35 #include <sys/systm.h>
36 #include <sys/malloc.h>
37 #include <sys/module.h>
38 #include <sys/bus.h>
39 #include <sys/endian.h>
40 #include <sys/linker.h>
41 #include <sys/firmware.h>
42 #include <sys/kdb.h>
43 
44 #include <machine/bus.h>
45 #include <machine/resource.h>
46 #include <sys/rman.h>
47 
48 #include <net/bpf.h>
49 #include <net/if.h>
50 #include <net/if_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 #include <netinet/in.h>
57 #include <netinet/in_systm.h>
58 #include <netinet/in_var.h>
59 #include <netinet/if_ether.h>
60 #include <netinet/ip.h>
61 
62 #include <net80211/ieee80211_var.h>
63 #include <net80211/ieee80211_regdomain.h>
64 #include <net80211/ieee80211_radiotap.h>
65 #include <net80211/ieee80211_ratectl.h>
66 
67 #include <dev/usb/usb.h>
68 #include <dev/usb/usbdi.h>
69 #include "usbdevs.h"
70 
71 #define USB_DEBUG_VAR run_debug
72 #include <dev/usb/usb_debug.h>
73 
74 #include <dev/usb/wlan/if_runreg.h>
75 #include <dev/usb/wlan/if_runvar.h>
76 
77 #define	N(_a) ((int)(sizeof((_a)) / sizeof((_a)[0])))
78 
79 #ifdef	USB_DEBUG
80 #define RUN_DEBUG
81 #endif
82 
83 #ifdef	RUN_DEBUG
84 int run_debug = 0;
85 static SYSCTL_NODE(_hw_usb, OID_AUTO, run, CTLFLAG_RW, 0, "USB run");
86 SYSCTL_INT(_hw_usb_run, OID_AUTO, debug, CTLFLAG_RW, &run_debug, 0,
87     "run debug level");
88 #endif
89 
90 #define IEEE80211_HAS_ADDR4(wh) \
91 	(((wh)->i_fc[1] & IEEE80211_FC1_DIR_MASK) == IEEE80211_FC1_DIR_DSTODS)
92 
93 /*
94  * Because of LOR in run_key_delete(), use atomic instead.
95  * '& RUN_CMDQ_MASQ' is to loop cmdq[].
96  */
97 #define RUN_CMDQ_GET(c)	(atomic_fetchadd_32((c), 1) & RUN_CMDQ_MASQ)
98 
99 static const STRUCT_USB_HOST_ID run_devs[] = {
100 #define RUN_DEV(v,p) { USB_VP(USB_VENDOR_##v, USB_PRODUCT_##v##_##p) }
101     RUN_DEV(ABOCOM,		RT2770),
102     RUN_DEV(ABOCOM,		RT2870),
103     RUN_DEV(ABOCOM,		RT3070),
104     RUN_DEV(ABOCOM,		RT3071),
105     RUN_DEV(ABOCOM,		RT3072),
106     RUN_DEV(ABOCOM2,		RT2870_1),
107     RUN_DEV(ACCTON,		RT2770),
108     RUN_DEV(ACCTON,		RT2870_1),
109     RUN_DEV(ACCTON,		RT2870_2),
110     RUN_DEV(ACCTON,		RT2870_3),
111     RUN_DEV(ACCTON,		RT2870_4),
112     RUN_DEV(ACCTON,		RT2870_5),
113     RUN_DEV(ACCTON,		RT3070),
114     RUN_DEV(ACCTON,		RT3070_1),
115     RUN_DEV(ACCTON,		RT3070_2),
116     RUN_DEV(ACCTON,		RT3070_3),
117     RUN_DEV(ACCTON,		RT3070_4),
118     RUN_DEV(ACCTON,		RT3070_5),
119     RUN_DEV(AIRTIES,		RT3070),
120     RUN_DEV(ALLWIN,		RT2070),
121     RUN_DEV(ALLWIN,		RT2770),
122     RUN_DEV(ALLWIN,		RT2870),
123     RUN_DEV(ALLWIN,		RT3070),
124     RUN_DEV(ALLWIN,		RT3071),
125     RUN_DEV(ALLWIN,		RT3072),
126     RUN_DEV(ALLWIN,		RT3572),
127     RUN_DEV(AMIGO,		RT2870_1),
128     RUN_DEV(AMIGO,		RT2870_2),
129     RUN_DEV(AMIT,		CGWLUSB2GNR),
130     RUN_DEV(AMIT,		RT2870_1),
131     RUN_DEV(AMIT2,		RT2870),
132     RUN_DEV(ASUS,		RT2870_1),
133     RUN_DEV(ASUS,		RT2870_2),
134     RUN_DEV(ASUS,		RT2870_3),
135     RUN_DEV(ASUS,		RT2870_4),
136     RUN_DEV(ASUS,		RT2870_5),
137     RUN_DEV(ASUS,		USBN13),
138     RUN_DEV(ASUS,		RT3070_1),
139     RUN_DEV(ASUS2,		USBN11),
140     RUN_DEV(AZUREWAVE,		RT2870_1),
141     RUN_DEV(AZUREWAVE,		RT2870_2),
142     RUN_DEV(AZUREWAVE,		RT3070_1),
143     RUN_DEV(AZUREWAVE,		RT3070_2),
144     RUN_DEV(AZUREWAVE,		RT3070_3),
145     RUN_DEV(BELKIN,		F5D8053V3),
146     RUN_DEV(BELKIN,		F5D8055),
147     RUN_DEV(BELKIN,		F5D8055V2),
148     RUN_DEV(BELKIN,		F6D4050V1),
149     RUN_DEV(BELKIN,		RT2870_1),
150     RUN_DEV(BELKIN,		RT2870_2),
151     RUN_DEV(CISCOLINKSYS,	AE1000),
152     RUN_DEV(CISCOLINKSYS2,	RT3070),
153     RUN_DEV(CISCOLINKSYS3,	RT3070),
154     RUN_DEV(CONCEPTRONIC2,	RT2870_1),
155     RUN_DEV(CONCEPTRONIC2,	RT2870_2),
156     RUN_DEV(CONCEPTRONIC2,	RT2870_3),
157     RUN_DEV(CONCEPTRONIC2,	RT2870_4),
158     RUN_DEV(CONCEPTRONIC2,	RT2870_5),
159     RUN_DEV(CONCEPTRONIC2,	RT2870_6),
160     RUN_DEV(CONCEPTRONIC2,	RT2870_7),
161     RUN_DEV(CONCEPTRONIC2,	RT2870_8),
162     RUN_DEV(CONCEPTRONIC2,	RT3070_1),
163     RUN_DEV(CONCEPTRONIC2,	RT3070_2),
164     RUN_DEV(CONCEPTRONIC2,	VIGORN61),
165     RUN_DEV(COREGA,		CGWLUSB300GNM),
166     RUN_DEV(COREGA,		RT2870_1),
167     RUN_DEV(COREGA,		RT2870_2),
168     RUN_DEV(COREGA,		RT2870_3),
169     RUN_DEV(COREGA,		RT3070),
170     RUN_DEV(CYBERTAN,		RT2870),
171     RUN_DEV(DLINK,		RT2870),
172     RUN_DEV(DLINK,		RT3072),
173     RUN_DEV(DLINK2,		DWA130),
174     RUN_DEV(DLINK2,		RT2870_1),
175     RUN_DEV(DLINK2,		RT2870_2),
176     RUN_DEV(DLINK2,		RT3070_1),
177     RUN_DEV(DLINK2,		RT3070_2),
178     RUN_DEV(DLINK2,		RT3070_3),
179     RUN_DEV(DLINK2,		RT3070_4),
180     RUN_DEV(DLINK2,		RT3070_5),
181     RUN_DEV(DLINK2,		RT3072),
182     RUN_DEV(DLINK2,		RT3072_1),
183     RUN_DEV(EDIMAX,		EW7717),
184     RUN_DEV(EDIMAX,		EW7718),
185     RUN_DEV(EDIMAX,		RT2870_1),
186     RUN_DEV(ENCORE,		RT3070_1),
187     RUN_DEV(ENCORE,		RT3070_2),
188     RUN_DEV(ENCORE,		RT3070_3),
189     RUN_DEV(GIGABYTE,		GNWB31N),
190     RUN_DEV(GIGABYTE,		GNWB32L),
191     RUN_DEV(GIGABYTE,		RT2870_1),
192     RUN_DEV(GIGASET,		RT3070_1),
193     RUN_DEV(GIGASET,		RT3070_2),
194     RUN_DEV(GUILLEMOT,		HWNU300),
195     RUN_DEV(HAWKING,		HWUN2),
196     RUN_DEV(HAWKING,		RT2870_1),
197     RUN_DEV(HAWKING,		RT2870_2),
198     RUN_DEV(HAWKING,		RT3070),
199     RUN_DEV(IODATA,		RT3072_1),
200     RUN_DEV(IODATA,		RT3072_2),
201     RUN_DEV(IODATA,		RT3072_3),
202     RUN_DEV(IODATA,		RT3072_4),
203     RUN_DEV(LINKSYS4,		RT3070),
204     RUN_DEV(LINKSYS4,		WUSB100),
205     RUN_DEV(LINKSYS4,		WUSB54GCV3),
206     RUN_DEV(LINKSYS4,		WUSB600N),
207     RUN_DEV(LINKSYS4,		WUSB600NV2),
208     RUN_DEV(LOGITEC,		RT2870_1),
209     RUN_DEV(LOGITEC,		RT2870_2),
210     RUN_DEV(LOGITEC,		RT2870_3),
211     RUN_DEV(LOGITEC,		LANW300NU2),
212     RUN_DEV(MELCO,		RT2870_1),
213     RUN_DEV(MELCO,		RT2870_2),
214     RUN_DEV(MELCO,		WLIUCAG300N),
215     RUN_DEV(MELCO,		WLIUCG300N),
216     RUN_DEV(MELCO,		WLIUCG301N),
217     RUN_DEV(MELCO,		WLIUCGN),
218     RUN_DEV(MELCO,		WLIUCGNM),
219     RUN_DEV(MOTOROLA4,		RT2770),
220     RUN_DEV(MOTOROLA4,		RT3070),
221     RUN_DEV(MSI,		RT3070_1),
222     RUN_DEV(MSI,		RT3070_2),
223     RUN_DEV(MSI,		RT3070_3),
224     RUN_DEV(MSI,		RT3070_4),
225     RUN_DEV(MSI,		RT3070_5),
226     RUN_DEV(MSI,		RT3070_6),
227     RUN_DEV(MSI,		RT3070_7),
228     RUN_DEV(MSI,		RT3070_8),
229     RUN_DEV(MSI,		RT3070_9),
230     RUN_DEV(MSI,		RT3070_10),
231     RUN_DEV(MSI,		RT3070_11),
232     RUN_DEV(OVISLINK,		RT3072),
233     RUN_DEV(PARA,		RT3070),
234     RUN_DEV(PEGATRON,		RT2870),
235     RUN_DEV(PEGATRON,		RT3070),
236     RUN_DEV(PEGATRON,		RT3070_2),
237     RUN_DEV(PEGATRON,		RT3070_3),
238     RUN_DEV(PHILIPS,		RT2870),
239     RUN_DEV(PLANEX2,		GWUS300MINIS),
240     RUN_DEV(PLANEX2,		GWUSMICRON),
241     RUN_DEV(PLANEX2,		RT2870),
242     RUN_DEV(PLANEX2,		RT3070),
243     RUN_DEV(QCOM,		RT2870),
244     RUN_DEV(QUANTA,		RT3070),
245     RUN_DEV(RALINK,		RT2070),
246     RUN_DEV(RALINK,		RT2770),
247     RUN_DEV(RALINK,		RT2870),
248     RUN_DEV(RALINK,		RT3070),
249     RUN_DEV(RALINK,		RT3071),
250     RUN_DEV(RALINK,		RT3072),
251     RUN_DEV(RALINK,		RT3370),
252     RUN_DEV(RALINK,		RT3572),
253     RUN_DEV(RALINK,		RT8070),
254     RUN_DEV(SAMSUNG,		WIS09ABGN),
255     RUN_DEV(SAMSUNG2,		RT2870_1),
256     RUN_DEV(SENAO,		RT2870_1),
257     RUN_DEV(SENAO,		RT2870_2),
258     RUN_DEV(SENAO,		RT2870_3),
259     RUN_DEV(SENAO,		RT2870_4),
260     RUN_DEV(SENAO,		RT3070),
261     RUN_DEV(SENAO,		RT3071),
262     RUN_DEV(SENAO,		RT3072_1),
263     RUN_DEV(SENAO,		RT3072_2),
264     RUN_DEV(SENAO,		RT3072_3),
265     RUN_DEV(SENAO,		RT3072_4),
266     RUN_DEV(SENAO,		RT3072_5),
267     RUN_DEV(SITECOMEU,		RT2770),
268     RUN_DEV(SITECOMEU,		RT2870_1),
269     RUN_DEV(SITECOMEU,		RT2870_2),
270     RUN_DEV(SITECOMEU,		RT2870_3),
271     RUN_DEV(SITECOMEU,		RT2870_4),
272     RUN_DEV(SITECOMEU,		RT3070),
273     RUN_DEV(SITECOMEU,		RT3070_2),
274     RUN_DEV(SITECOMEU,		RT3070_3),
275     RUN_DEV(SITECOMEU,		RT3070_4),
276     RUN_DEV(SITECOMEU,		RT3071),
277     RUN_DEV(SITECOMEU,		RT3072_1),
278     RUN_DEV(SITECOMEU,		RT3072_2),
279     RUN_DEV(SITECOMEU,		RT3072_3),
280     RUN_DEV(SITECOMEU,		RT3072_4),
281     RUN_DEV(SITECOMEU,		RT3072_5),
282     RUN_DEV(SITECOMEU,		RT3072_6),
283     RUN_DEV(SITECOMEU,		WL608),
284     RUN_DEV(SPARKLAN,		RT2870_1),
285     RUN_DEV(SPARKLAN,		RT3070),
286     RUN_DEV(SWEEX2,		LW153),
287     RUN_DEV(SWEEX2,		LW303),
288     RUN_DEV(SWEEX2,		LW313),
289     RUN_DEV(TOSHIBA,		RT3070),
290     RUN_DEV(UMEDIA,		RT2870_1),
291     RUN_DEV(ZCOM,		RT2870_1),
292     RUN_DEV(ZCOM,		RT2870_2),
293     RUN_DEV(ZINWELL,		RT2870_1),
294     RUN_DEV(ZINWELL,		RT2870_2),
295     RUN_DEV(ZINWELL,		RT3070),
296     RUN_DEV(ZINWELL,		RT3072_1),
297     RUN_DEV(ZINWELL,		RT3072_2),
298     RUN_DEV(ZYXEL,		RT2870_1),
299     RUN_DEV(ZYXEL,		RT2870_2),
300 #undef RUN_DEV
301 };
302 
303 static device_probe_t	run_match;
304 static device_attach_t	run_attach;
305 static device_detach_t	run_detach;
306 
307 static usb_callback_t	run_bulk_rx_callback;
308 static usb_callback_t	run_bulk_tx_callback0;
309 static usb_callback_t	run_bulk_tx_callback1;
310 static usb_callback_t	run_bulk_tx_callback2;
311 static usb_callback_t	run_bulk_tx_callback3;
312 static usb_callback_t	run_bulk_tx_callback4;
313 static usb_callback_t	run_bulk_tx_callback5;
314 
315 static void	run_bulk_tx_callbackN(struct usb_xfer *xfer,
316 		    usb_error_t error, unsigned int index);
317 static struct ieee80211vap *run_vap_create(struct ieee80211com *,
318 		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
319 		    const uint8_t [IEEE80211_ADDR_LEN],
320 		    const uint8_t [IEEE80211_ADDR_LEN]);
321 static void	run_vap_delete(struct ieee80211vap *);
322 static void	run_cmdq_cb(void *, int);
323 static void	run_setup_tx_list(struct run_softc *,
324 		    struct run_endpoint_queue *);
325 static void	run_unsetup_tx_list(struct run_softc *,
326 		    struct run_endpoint_queue *);
327 static int	run_load_microcode(struct run_softc *);
328 static int	run_reset(struct run_softc *);
329 static usb_error_t run_do_request(struct run_softc *,
330 		    struct usb_device_request *, void *);
331 static int	run_read(struct run_softc *, uint16_t, uint32_t *);
332 static int	run_read_region_1(struct run_softc *, uint16_t, uint8_t *, int);
333 static int	run_write_2(struct run_softc *, uint16_t, uint16_t);
334 static int	run_write(struct run_softc *, uint16_t, uint32_t);
335 static int	run_write_region_1(struct run_softc *, uint16_t,
336 		    const uint8_t *, int);
337 static int	run_set_region_4(struct run_softc *, uint16_t, uint32_t, int);
338 static int	run_efuse_read_2(struct run_softc *, uint16_t, uint16_t *);
339 static int	run_eeprom_read_2(struct run_softc *, uint16_t, uint16_t *);
340 static int	run_rt2870_rf_write(struct run_softc *, uint8_t, uint32_t);
341 static int	run_rt3070_rf_read(struct run_softc *, uint8_t, uint8_t *);
342 static int	run_rt3070_rf_write(struct run_softc *, uint8_t, uint8_t);
343 static int	run_bbp_read(struct run_softc *, uint8_t, uint8_t *);
344 static int	run_bbp_write(struct run_softc *, uint8_t, uint8_t);
345 static int	run_mcu_cmd(struct run_softc *, uint8_t, uint16_t);
346 static const char *run_get_rf(int);
347 static int	run_read_eeprom(struct run_softc *);
348 static struct ieee80211_node *run_node_alloc(struct ieee80211vap *,
349 			    const uint8_t mac[IEEE80211_ADDR_LEN]);
350 static int	run_media_change(struct ifnet *);
351 static int	run_newstate(struct ieee80211vap *, enum ieee80211_state, int);
352 static int	run_wme_update(struct ieee80211com *);
353 static void	run_wme_update_cb(void *);
354 static void	run_key_update_begin(struct ieee80211vap *);
355 static void	run_key_update_end(struct ieee80211vap *);
356 static void	run_key_set_cb(void *);
357 static int	run_key_set(struct ieee80211vap *, struct ieee80211_key *,
358 			    const uint8_t mac[IEEE80211_ADDR_LEN]);
359 static void	run_key_delete_cb(void *);
360 static int	run_key_delete(struct ieee80211vap *, struct ieee80211_key *);
361 static void	run_ratectl_to(void *);
362 static void	run_ratectl_cb(void *, int);
363 static void	run_drain_fifo(void *);
364 static void	run_iter_func(void *, struct ieee80211_node *);
365 static void	run_newassoc_cb(void *);
366 static void	run_newassoc(struct ieee80211_node *, int);
367 static void	run_rx_frame(struct run_softc *, struct mbuf *, uint32_t);
368 static void	run_tx_free(struct run_endpoint_queue *pq,
369 		    struct run_tx_data *, int);
370 static void	run_set_tx_desc(struct run_softc *, struct run_tx_data *);
371 static int	run_tx(struct run_softc *, struct mbuf *,
372 		    struct ieee80211_node *);
373 static int	run_tx_mgt(struct run_softc *, struct mbuf *,
374 		    struct ieee80211_node *);
375 static int	run_sendprot(struct run_softc *, const struct mbuf *,
376 		    struct ieee80211_node *, int, int);
377 static int	run_tx_param(struct run_softc *, struct mbuf *,
378 		    struct ieee80211_node *,
379 		    const struct ieee80211_bpf_params *);
380 static int	run_raw_xmit(struct ieee80211_node *, struct mbuf *,
381 		    const struct ieee80211_bpf_params *);
382 static void	run_start(struct ifnet *);
383 static int	run_ioctl(struct ifnet *, u_long, caddr_t);
384 static void	run_set_agc(struct run_softc *, uint8_t);
385 static void	run_select_chan_group(struct run_softc *, int);
386 static void	run_set_rx_antenna(struct run_softc *, int);
387 static void	run_rt2870_set_chan(struct run_softc *, u_int);
388 static void	run_rt3070_set_chan(struct run_softc *, u_int);
389 static void	run_rt3572_set_chan(struct run_softc *, u_int);
390 static int	run_set_chan(struct run_softc *, struct ieee80211_channel *);
391 static void	run_set_channel(struct ieee80211com *);
392 static void	run_scan_start(struct ieee80211com *);
393 static void	run_scan_end(struct ieee80211com *);
394 static void	run_update_beacon(struct ieee80211vap *, int);
395 static void	run_update_beacon_cb(void *);
396 static void	run_updateprot(struct ieee80211com *);
397 static void	run_updateprot_cb(void *);
398 static void	run_usb_timeout_cb(void *);
399 static void	run_reset_livelock(struct run_softc *);
400 static void	run_enable_tsf_sync(struct run_softc *);
401 static void	run_enable_mrr(struct run_softc *);
402 static void	run_set_txpreamble(struct run_softc *);
403 static void	run_set_basicrates(struct run_softc *);
404 static void	run_set_leds(struct run_softc *, uint16_t);
405 static void	run_set_bssid(struct run_softc *, const uint8_t *);
406 static void	run_set_macaddr(struct run_softc *, const uint8_t *);
407 static void	run_updateslot(struct ifnet *);
408 static void	run_updateslot_cb(void *);
409 static void	run_update_mcast(struct ifnet *);
410 static int8_t	run_rssi2dbm(struct run_softc *, uint8_t, uint8_t);
411 static void	run_update_promisc_locked(struct ifnet *);
412 static void	run_update_promisc(struct ifnet *);
413 static int	run_bbp_init(struct run_softc *);
414 static int	run_rt3070_rf_init(struct run_softc *);
415 static int	run_rt3070_filter_calib(struct run_softc *, uint8_t, uint8_t,
416 		    uint8_t *);
417 static void	run_rt3070_rf_setup(struct run_softc *);
418 static int	run_txrx_enable(struct run_softc *);
419 static void	run_init(void *);
420 static void	run_init_locked(struct run_softc *);
421 static void	run_stop(void *);
422 static void	run_delay(struct run_softc *, unsigned int);
423 
424 static const struct {
425 	uint16_t	reg;
426 	uint32_t	val;
427 } rt2870_def_mac[] = {
428 	RT2870_DEF_MAC
429 };
430 
431 static const struct {
432 	uint8_t	reg;
433 	uint8_t	val;
434 } rt2860_def_bbp[] = {
435 	RT2860_DEF_BBP
436 };
437 
438 static const struct rfprog {
439 	uint8_t		chan;
440 	uint32_t	r1, r2, r3, r4;
441 } rt2860_rf2850[] = {
442 	RT2860_RF2850
443 };
444 
445 struct {
446 	uint8_t	n, r, k;
447 } rt3070_freqs[] = {
448 	RT3070_RF3052
449 };
450 
451 static const struct {
452 	uint8_t	reg;
453 	uint8_t	val;
454 } rt3070_def_rf[] = {
455 	RT3070_DEF_RF
456 },rt3572_def_rf[] = {
457 	RT3572_DEF_RF
458 };
459 
460 static const struct usb_config run_config[RUN_N_XFER] = {
461     [RUN_BULK_TX_BE] = {
462 	.type = UE_BULK,
463 	.endpoint = UE_ADDR_ANY,
464 	.ep_index = 0,
465 	.direction = UE_DIR_OUT,
466 	.bufsize = RUN_MAX_TXSZ,
467 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
468 	.callback = run_bulk_tx_callback0,
469 	.timeout = 5000,	/* ms */
470     },
471     [RUN_BULK_TX_BK] = {
472 	.type = UE_BULK,
473 	.endpoint = UE_ADDR_ANY,
474 	.direction = UE_DIR_OUT,
475 	.ep_index = 1,
476 	.bufsize = RUN_MAX_TXSZ,
477 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
478 	.callback = run_bulk_tx_callback1,
479 	.timeout = 5000,	/* ms */
480     },
481     [RUN_BULK_TX_VI] = {
482 	.type = UE_BULK,
483 	.endpoint = UE_ADDR_ANY,
484 	.direction = UE_DIR_OUT,
485 	.ep_index = 2,
486 	.bufsize = RUN_MAX_TXSZ,
487 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
488 	.callback = run_bulk_tx_callback2,
489 	.timeout = 5000,	/* ms */
490     },
491     [RUN_BULK_TX_VO] = {
492 	.type = UE_BULK,
493 	.endpoint = UE_ADDR_ANY,
494 	.direction = UE_DIR_OUT,
495 	.ep_index = 3,
496 	.bufsize = RUN_MAX_TXSZ,
497 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
498 	.callback = run_bulk_tx_callback3,
499 	.timeout = 5000,	/* ms */
500     },
501     [RUN_BULK_TX_HCCA] = {
502 	.type = UE_BULK,
503 	.endpoint = UE_ADDR_ANY,
504 	.direction = UE_DIR_OUT,
505 	.ep_index = 4,
506 	.bufsize = RUN_MAX_TXSZ,
507 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,},
508 	.callback = run_bulk_tx_callback4,
509 	.timeout = 5000,	/* ms */
510     },
511     [RUN_BULK_TX_PRIO] = {
512 	.type = UE_BULK,
513 	.endpoint = UE_ADDR_ANY,
514 	.direction = UE_DIR_OUT,
515 	.ep_index = 5,
516 	.bufsize = RUN_MAX_TXSZ,
517 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,},
518 	.callback = run_bulk_tx_callback5,
519 	.timeout = 5000,	/* ms */
520     },
521     [RUN_BULK_RX] = {
522 	.type = UE_BULK,
523 	.endpoint = UE_ADDR_ANY,
524 	.direction = UE_DIR_IN,
525 	.bufsize = RUN_MAX_RXSZ,
526 	.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
527 	.callback = run_bulk_rx_callback,
528     }
529 };
530 
531 static int
532 run_match(device_t self)
533 {
534 	struct usb_attach_arg *uaa = device_get_ivars(self);
535 
536 	if (uaa->usb_mode != USB_MODE_HOST)
537 		return (ENXIO);
538 	if (uaa->info.bConfigIndex != 0)
539 		return (ENXIO);
540 	if (uaa->info.bIfaceIndex != RT2860_IFACE_INDEX)
541 		return (ENXIO);
542 
543 	return (usbd_lookup_id_by_uaa(run_devs, sizeof(run_devs), uaa));
544 }
545 
546 static int
547 run_attach(device_t self)
548 {
549 	struct run_softc *sc = device_get_softc(self);
550 	struct usb_attach_arg *uaa = device_get_ivars(self);
551 	struct ieee80211com *ic;
552 	struct ifnet *ifp;
553 	uint32_t ver;
554 	int i, ntries, error;
555 	uint8_t iface_index, bands;
556 
557 	device_set_usb_desc(self);
558 	sc->sc_udev = uaa->device;
559 	sc->sc_dev = self;
560 
561 	mtx_init(&sc->sc_mtx, device_get_nameunit(sc->sc_dev),
562 	    MTX_NETWORK_LOCK, MTX_DEF);
563 
564 	iface_index = RT2860_IFACE_INDEX;
565 
566 	error = usbd_transfer_setup(uaa->device, &iface_index,
567 	    sc->sc_xfer, run_config, RUN_N_XFER, sc, &sc->sc_mtx);
568 	if (error) {
569 		device_printf(self, "could not allocate USB transfers, "
570 		    "err=%s\n", usbd_errstr(error));
571 		goto detach;
572 	}
573 
574 	RUN_LOCK(sc);
575 
576 	/* wait for the chip to settle */
577 	for (ntries = 0; ntries < 100; ntries++) {
578 		if (run_read(sc, RT2860_ASIC_VER_ID, &ver) != 0) {
579 			RUN_UNLOCK(sc);
580 			goto detach;
581 		}
582 		if (ver != 0 && ver != 0xffffffff)
583 			break;
584 		run_delay(sc, 10);
585 	}
586 	if (ntries == 100) {
587 		device_printf(sc->sc_dev,
588 		    "timeout waiting for NIC to initialize\n");
589 		RUN_UNLOCK(sc);
590 		goto detach;
591 	}
592 	sc->mac_ver = ver >> 16;
593 	sc->mac_rev = ver & 0xffff;
594 
595 	/* retrieve RF rev. no and various other things from EEPROM */
596 	run_read_eeprom(sc);
597 
598 	device_printf(sc->sc_dev,
599 	    "MAC/BBP RT%04X (rev 0x%04X), RF %s (MIMO %dT%dR), address %s\n",
600 	    sc->mac_ver, sc->mac_rev, run_get_rf(sc->rf_rev),
601 	    sc->ntxchains, sc->nrxchains, ether_sprintf(sc->sc_bssid));
602 
603 	RUN_UNLOCK(sc);
604 
605 	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
606 	if (ifp == NULL) {
607 		device_printf(sc->sc_dev, "can not if_alloc()\n");
608 		goto detach;
609 	}
610 	ic = ifp->if_l2com;
611 
612 	ifp->if_softc = sc;
613 	if_initname(ifp, "run", device_get_unit(sc->sc_dev));
614 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
615 	ifp->if_init = run_init;
616 	ifp->if_ioctl = run_ioctl;
617 	ifp->if_start = run_start;
618 	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
619 	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
620 	IFQ_SET_READY(&ifp->if_snd);
621 
622 	ic->ic_ifp = ifp;
623 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
624 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
625 
626 	/* set device capabilities */
627 	ic->ic_caps =
628 	    IEEE80211_C_STA |		/* station mode supported */
629 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
630 	    IEEE80211_C_IBSS |
631 	    IEEE80211_C_HOSTAP |
632 	    IEEE80211_C_WDS |		/* 4-address traffic works */
633 	    IEEE80211_C_MBSS |
634 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
635 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
636 	    IEEE80211_C_WME |		/* WME */
637 	    IEEE80211_C_WPA;		/* WPA1|WPA2(RSN) */
638 
639 	ic->ic_cryptocaps =
640 	    IEEE80211_CRYPTO_WEP |
641 	    IEEE80211_CRYPTO_AES_CCM |
642 	    IEEE80211_CRYPTO_TKIPMIC |
643 	    IEEE80211_CRYPTO_TKIP;
644 
645 	ic->ic_flags |= IEEE80211_F_DATAPAD;
646 	ic->ic_flags_ext |= IEEE80211_FEXT_SWBMISS;
647 
648 	bands = 0;
649 	setbit(&bands, IEEE80211_MODE_11B);
650 	setbit(&bands, IEEE80211_MODE_11G);
651 	ieee80211_init_channels(ic, NULL, &bands);
652 
653 	/*
654 	 * Do this by own because h/w supports
655 	 * more channels than ieee80211_init_channels()
656 	 */
657 	if (sc->rf_rev == RT2860_RF_2750 ||
658 	    sc->rf_rev == RT2860_RF_2850 ||
659 	    sc->rf_rev == RT3070_RF_3052) {
660 		/* set supported .11a rates */
661 		for (i = 14; i < N(rt2860_rf2850); i++) {
662 			uint8_t chan = rt2860_rf2850[i].chan;
663 			ic->ic_channels[ic->ic_nchans].ic_freq =
664 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_A);
665 			ic->ic_channels[ic->ic_nchans].ic_ieee = chan;
666 			ic->ic_channels[ic->ic_nchans].ic_flags = IEEE80211_CHAN_A;
667 			ic->ic_channels[ic->ic_nchans].ic_extieee = 0;
668 			ic->ic_nchans++;
669 		}
670 	}
671 
672 	ieee80211_ifattach(ic, sc->sc_bssid);
673 
674 	ic->ic_scan_start = run_scan_start;
675 	ic->ic_scan_end = run_scan_end;
676 	ic->ic_set_channel = run_set_channel;
677 	ic->ic_node_alloc = run_node_alloc;
678 	ic->ic_newassoc = run_newassoc;
679 	ic->ic_updateslot = run_updateslot;
680 	ic->ic_update_mcast = run_update_mcast;
681 	ic->ic_wme.wme_update = run_wme_update;
682 	ic->ic_raw_xmit = run_raw_xmit;
683 	ic->ic_update_promisc = run_update_promisc;
684 
685 	ic->ic_vap_create = run_vap_create;
686 	ic->ic_vap_delete = run_vap_delete;
687 
688 	ieee80211_radiotap_attach(ic,
689 	    &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
690 		RUN_TX_RADIOTAP_PRESENT,
691 	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
692 		RUN_RX_RADIOTAP_PRESENT);
693 
694 	TASK_INIT(&sc->cmdq_task, 0, run_cmdq_cb, sc);
695 	TASK_INIT(&sc->ratectl_task, 0, run_ratectl_cb, sc);
696 	callout_init((struct callout *)&sc->ratectl_ch, 1);
697 
698 	if (bootverbose)
699 		ieee80211_announce(ic);
700 
701 	return (0);
702 
703 detach:
704 	run_detach(self);
705 	return (ENXIO);
706 }
707 
708 static int
709 run_detach(device_t self)
710 {
711 	struct run_softc *sc = device_get_softc(self);
712 	struct ifnet *ifp = sc->sc_ifp;
713 	struct ieee80211com *ic;
714 	int i;
715 
716 	/* stop all USB transfers */
717 	usbd_transfer_unsetup(sc->sc_xfer, RUN_N_XFER);
718 
719 	RUN_LOCK(sc);
720 
721 	sc->ratectl_run = RUN_RATECTL_OFF;
722 	sc->cmdq_run = sc->cmdq_key_set = RUN_CMDQ_ABORT;
723 
724 	/* free TX list, if any */
725 	for (i = 0; i != RUN_EP_QUEUES; i++)
726 		run_unsetup_tx_list(sc, &sc->sc_epq[i]);
727 	RUN_UNLOCK(sc);
728 
729 	if (ifp) {
730 		ic = ifp->if_l2com;
731 		/* drain tasks */
732 		usb_callout_drain(&sc->ratectl_ch);
733 		ieee80211_draintask(ic, &sc->cmdq_task);
734 		ieee80211_draintask(ic, &sc->ratectl_task);
735 		ieee80211_ifdetach(ic);
736 		if_free(ifp);
737 	}
738 
739 	mtx_destroy(&sc->sc_mtx);
740 
741 	return (0);
742 }
743 
744 static struct ieee80211vap *
745 run_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
746     enum ieee80211_opmode opmode, int flags,
747     const uint8_t bssid[IEEE80211_ADDR_LEN],
748     const uint8_t mac[IEEE80211_ADDR_LEN])
749 {
750 	struct ifnet *ifp = ic->ic_ifp;
751 	struct run_softc *sc = ifp->if_softc;
752 	struct run_vap *rvp;
753 	struct ieee80211vap *vap;
754 	int i;
755 
756 	if (sc->rvp_cnt >= RUN_VAP_MAX) {
757 		if_printf(ifp, "number of VAPs maxed out\n");
758 		return (NULL);
759 	}
760 
761 	switch (opmode) {
762 	case IEEE80211_M_STA:
763 		/* enable s/w bmiss handling for sta mode */
764 		flags |= IEEE80211_CLONE_NOBEACONS;
765 		/* fall though */
766 	case IEEE80211_M_IBSS:
767 	case IEEE80211_M_MONITOR:
768 	case IEEE80211_M_HOSTAP:
769 	case IEEE80211_M_MBSS:
770 		/* other than WDS vaps, only one at a time */
771 		if (!TAILQ_EMPTY(&ic->ic_vaps))
772 			return (NULL);
773 		break;
774 	case IEEE80211_M_WDS:
775 		TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next){
776 			if(vap->iv_opmode != IEEE80211_M_HOSTAP)
777 				continue;
778 			/* WDS vap's always share the local mac address. */
779 			flags &= ~IEEE80211_CLONE_BSSID;
780 			break;
781 		}
782 		if (vap == NULL) {
783 			if_printf(ifp, "wds only supported in ap mode\n");
784 			return (NULL);
785 		}
786 		break;
787 	default:
788 		if_printf(ifp, "unknown opmode %d\n", opmode);
789 		return (NULL);
790 	}
791 
792 	rvp = (struct run_vap *) malloc(sizeof(struct run_vap),
793 	    M_80211_VAP, M_NOWAIT | M_ZERO);
794 	if (rvp == NULL)
795 		return (NULL);
796 	vap = &rvp->vap;
797 	ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac);
798 
799 	vap->iv_key_update_begin = run_key_update_begin;
800 	vap->iv_key_update_end = run_key_update_end;
801 	vap->iv_update_beacon = run_update_beacon;
802 	vap->iv_max_aid = RT2870_WCID_MAX;
803 	/*
804 	 * To delete the right key from h/w, we need wcid.
805 	 * Luckily, there is unused space in ieee80211_key{}, wk_pad,
806 	 * and matching wcid will be written into there. So, cast
807 	 * some spells to remove 'const' from ieee80211_key{}
808 	 */
809 	vap->iv_key_delete = (void *)run_key_delete;
810 	vap->iv_key_set = (void *)run_key_set;
811 
812 	/* override state transition machine */
813 	rvp->newstate = vap->iv_newstate;
814 	vap->iv_newstate = run_newstate;
815 
816 	ieee80211_ratectl_init(vap);
817 	ieee80211_ratectl_setinterval(vap, 1000 /* 1 sec */);
818 
819 	/* complete setup */
820 	ieee80211_vap_attach(vap, run_media_change, ieee80211_media_status);
821 
822 	/* make sure id is always unique */
823 	for (i = 0; i < RUN_VAP_MAX; i++) {
824 		if((sc->rvp_bmap & 1 << i) == 0){
825 			sc->rvp_bmap |= 1 << i;
826 			rvp->rvp_id = i;
827 			break;
828 		}
829 	}
830 	if (sc->rvp_cnt++ == 0)
831 		ic->ic_opmode = opmode;
832 
833 	if (opmode == IEEE80211_M_HOSTAP)
834 		sc->cmdq_run = RUN_CMDQ_GO;
835 
836 	DPRINTF("rvp_id=%d bmap=%x rvp_cnt=%d\n",
837 	    rvp->rvp_id, sc->rvp_bmap, sc->rvp_cnt);
838 
839 	return (vap);
840 }
841 
842 static void
843 run_vap_delete(struct ieee80211vap *vap)
844 {
845 	struct run_vap *rvp = RUN_VAP(vap);
846 	struct ifnet *ifp;
847 	struct ieee80211com *ic;
848 	struct run_softc *sc;
849 	uint8_t rvp_id;
850 
851 	if (vap == NULL)
852 		return;
853 
854 	ic = vap->iv_ic;
855 	ifp = ic->ic_ifp;
856 
857 	sc = ifp->if_softc;
858 
859 	RUN_LOCK(sc);
860 
861 	m_freem(rvp->beacon_mbuf);
862 	rvp->beacon_mbuf = NULL;
863 
864 	rvp_id = rvp->rvp_id;
865 	sc->ratectl_run &= ~(1 << rvp_id);
866 	sc->rvp_bmap &= ~(1 << rvp_id);
867 	run_set_region_4(sc, RT2860_SKEY(rvp_id, 0), 0, 128);
868 	run_set_region_4(sc, RT2860_BCN_BASE(rvp_id), 0, 512);
869 	--sc->rvp_cnt;
870 
871 	DPRINTF("vap=%p rvp_id=%d bmap=%x rvp_cnt=%d\n",
872 	    vap, rvp_id, sc->rvp_bmap, sc->rvp_cnt);
873 
874 	RUN_UNLOCK(sc);
875 
876 	ieee80211_ratectl_deinit(vap);
877 	ieee80211_vap_detach(vap);
878 	free(rvp, M_80211_VAP);
879 }
880 
881 /*
882  * There are numbers of functions need to be called in context thread.
883  * Rather than creating taskqueue event for each of those functions,
884  * here is all-for-one taskqueue callback function. This function
885  * gurantees deferred functions are executed in the same order they
886  * were enqueued.
887  * '& RUN_CMDQ_MASQ' is to loop cmdq[].
888  */
889 static void
890 run_cmdq_cb(void *arg, int pending)
891 {
892 	struct run_softc *sc = arg;
893 	uint8_t i;
894 
895 	/* call cmdq[].func locked */
896 	RUN_LOCK(sc);
897 	for (i = sc->cmdq_exec; sc->cmdq[i].func && pending;
898 	    i = sc->cmdq_exec, pending--) {
899 		DPRINTFN(6, "cmdq_exec=%d pending=%d\n", i, pending);
900 		if (sc->cmdq_run == RUN_CMDQ_GO) {
901 			/*
902 			 * If arg0 is NULL, callback func needs more
903 			 * than one arg. So, pass ptr to cmdq struct.
904 			 */
905 			if (sc->cmdq[i].arg0)
906 				sc->cmdq[i].func(sc->cmdq[i].arg0);
907 			else
908 				sc->cmdq[i].func(&sc->cmdq[i]);
909 		}
910 		sc->cmdq[i].arg0 = NULL;
911 		sc->cmdq[i].func = NULL;
912 		sc->cmdq_exec++;
913 		sc->cmdq_exec &= RUN_CMDQ_MASQ;
914 	}
915 	RUN_UNLOCK(sc);
916 }
917 
918 static void
919 run_setup_tx_list(struct run_softc *sc, struct run_endpoint_queue *pq)
920 {
921 	struct run_tx_data *data;
922 
923 	memset(pq, 0, sizeof(*pq));
924 
925 	STAILQ_INIT(&pq->tx_qh);
926 	STAILQ_INIT(&pq->tx_fh);
927 
928 	for (data = &pq->tx_data[0];
929 	    data < &pq->tx_data[RUN_TX_RING_COUNT]; data++) {
930 		data->sc = sc;
931 		STAILQ_INSERT_TAIL(&pq->tx_fh, data, next);
932 	}
933 	pq->tx_nfree = RUN_TX_RING_COUNT;
934 }
935 
936 static void
937 run_unsetup_tx_list(struct run_softc *sc, struct run_endpoint_queue *pq)
938 {
939 	struct run_tx_data *data;
940 
941 	/* make sure any subsequent use of the queues will fail */
942 	pq->tx_nfree = 0;
943 	STAILQ_INIT(&pq->tx_fh);
944 	STAILQ_INIT(&pq->tx_qh);
945 
946 	/* free up all node references and mbufs */
947 	for (data = &pq->tx_data[0];
948 	    data < &pq->tx_data[RUN_TX_RING_COUNT]; data++) {
949 		if (data->m != NULL) {
950 			m_freem(data->m);
951 			data->m = NULL;
952 		}
953 		if (data->ni != NULL) {
954 			ieee80211_free_node(data->ni);
955 			data->ni = NULL;
956 		}
957 	}
958 }
959 
960 static int
961 run_load_microcode(struct run_softc *sc)
962 {
963 	usb_device_request_t req;
964 	const struct firmware *fw;
965 	const u_char *base;
966 	uint32_t tmp;
967 	int ntries, error;
968 	const uint64_t *temp;
969 	uint64_t bytes;
970 
971 	RUN_UNLOCK(sc);
972 	fw = firmware_get("runfw");
973 	RUN_LOCK(sc);
974 	if (fw == NULL) {
975 		device_printf(sc->sc_dev,
976 		    "failed loadfirmware of file %s\n", "runfw");
977 		return ENOENT;
978 	}
979 
980 	if (fw->datasize != 8192) {
981 		device_printf(sc->sc_dev,
982 		    "invalid firmware size (should be 8KB)\n");
983 		error = EINVAL;
984 		goto fail;
985 	}
986 
987 	/*
988 	 * RT3071/RT3072 use a different firmware
989 	 * run-rt2870 (8KB) contains both,
990 	 * first half (4KB) is for rt2870,
991 	 * last half is for rt3071.
992 	 */
993 	base = fw->data;
994 	if ((sc->mac_ver) != 0x2860 &&
995 	    (sc->mac_ver) != 0x2872 &&
996 	    (sc->mac_ver) != 0x3070) {
997 		base += 4096;
998 	}
999 
1000 	/* cheap sanity check */
1001 	temp = fw->data;
1002 	bytes = *temp;
1003 	if (bytes != be64toh(0xffffff0210280210)) {
1004 		device_printf(sc->sc_dev, "firmware checksum failed\n");
1005 		error = EINVAL;
1006 		goto fail;
1007 	}
1008 
1009 	run_read(sc, RT2860_ASIC_VER_ID, &tmp);
1010 	/* write microcode image */
1011 	run_write_region_1(sc, RT2870_FW_BASE, base, 4096);
1012 	run_write(sc, RT2860_H2M_MAILBOX_CID, 0xffffffff);
1013 	run_write(sc, RT2860_H2M_MAILBOX_STATUS, 0xffffffff);
1014 
1015 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1016 	req.bRequest = RT2870_RESET;
1017 	USETW(req.wValue, 8);
1018 	USETW(req.wIndex, 0);
1019 	USETW(req.wLength, 0);
1020 	if ((error = usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, NULL))
1021 	    != 0) {
1022 		device_printf(sc->sc_dev, "firmware reset failed\n");
1023 		goto fail;
1024 	}
1025 
1026 	run_delay(sc, 10);
1027 
1028 	run_write(sc, RT2860_H2M_MAILBOX, 0);
1029 	if ((error = run_mcu_cmd(sc, RT2860_MCU_CMD_RFRESET, 0)) != 0)
1030 		goto fail;
1031 
1032 	/* wait until microcontroller is ready */
1033 	for (ntries = 0; ntries < 1000; ntries++) {
1034 		if ((error = run_read(sc, RT2860_SYS_CTRL, &tmp)) != 0) {
1035 			goto fail;
1036 		}
1037 		if (tmp & RT2860_MCU_READY)
1038 			break;
1039 		run_delay(sc, 10);
1040 	}
1041 	if (ntries == 1000) {
1042 		device_printf(sc->sc_dev,
1043 		    "timeout waiting for MCU to initialize\n");
1044 		error = ETIMEDOUT;
1045 		goto fail;
1046 	}
1047 	device_printf(sc->sc_dev, "firmware %s ver. %u.%u loaded\n",
1048 	    (base == fw->data) ? "RT2870" : "RT3071",
1049 	    *(base + 4092), *(base + 4093));
1050 
1051 fail:
1052 	firmware_put(fw, FIRMWARE_UNLOAD);
1053 	return (error);
1054 }
1055 
1056 int
1057 run_reset(struct run_softc *sc)
1058 {
1059 	usb_device_request_t req;
1060 
1061 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1062 	req.bRequest = RT2870_RESET;
1063 	USETW(req.wValue, 1);
1064 	USETW(req.wIndex, 0);
1065 	USETW(req.wLength, 0);
1066 	return (usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, NULL));
1067 }
1068 
1069 static usb_error_t
1070 run_do_request(struct run_softc *sc,
1071     struct usb_device_request *req, void *data)
1072 {
1073 	usb_error_t err;
1074 	int ntries = 10;
1075 
1076 	RUN_LOCK_ASSERT(sc, MA_OWNED);
1077 
1078 	while (ntries--) {
1079 		err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
1080 		    req, data, 0, NULL, 250 /* ms */);
1081 		if (err == 0)
1082 			break;
1083 		DPRINTFN(1, "Control request failed, %s (retrying)\n",
1084 		    usbd_errstr(err));
1085 		run_delay(sc, 10);
1086 	}
1087 	return (err);
1088 }
1089 
1090 static int
1091 run_read(struct run_softc *sc, uint16_t reg, uint32_t *val)
1092 {
1093 	uint32_t tmp;
1094 	int error;
1095 
1096 	error = run_read_region_1(sc, reg, (uint8_t *)&tmp, sizeof tmp);
1097 	if (error == 0)
1098 		*val = le32toh(tmp);
1099 	else
1100 		*val = 0xffffffff;
1101 	return (error);
1102 }
1103 
1104 static int
1105 run_read_region_1(struct run_softc *sc, uint16_t reg, uint8_t *buf, int len)
1106 {
1107 	usb_device_request_t req;
1108 
1109 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1110 	req.bRequest = RT2870_READ_REGION_1;
1111 	USETW(req.wValue, 0);
1112 	USETW(req.wIndex, reg);
1113 	USETW(req.wLength, len);
1114 
1115 	return (run_do_request(sc, &req, buf));
1116 }
1117 
1118 static int
1119 run_write_2(struct run_softc *sc, uint16_t reg, uint16_t val)
1120 {
1121 	usb_device_request_t req;
1122 
1123 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1124 	req.bRequest = RT2870_WRITE_2;
1125 	USETW(req.wValue, val);
1126 	USETW(req.wIndex, reg);
1127 	USETW(req.wLength, 0);
1128 
1129 	return (run_do_request(sc, &req, NULL));
1130 }
1131 
1132 static int
1133 run_write(struct run_softc *sc, uint16_t reg, uint32_t val)
1134 {
1135 	int error;
1136 
1137 	if ((error = run_write_2(sc, reg, val & 0xffff)) == 0)
1138 		error = run_write_2(sc, reg + 2, val >> 16);
1139 	return (error);
1140 }
1141 
1142 static int
1143 run_write_region_1(struct run_softc *sc, uint16_t reg, const uint8_t *buf,
1144     int len)
1145 {
1146 #if 1
1147 	int i, error = 0;
1148 	/*
1149 	 * NB: the WRITE_REGION_1 command is not stable on RT2860.
1150 	 * We thus issue multiple WRITE_2 commands instead.
1151 	 */
1152 	KASSERT((len & 1) == 0, ("run_write_region_1: Data too long.\n"));
1153 	for (i = 0; i < len && error == 0; i += 2)
1154 		error = run_write_2(sc, reg + i, buf[i] | buf[i + 1] << 8);
1155 	return (error);
1156 #else
1157 	usb_device_request_t req;
1158 
1159 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1160 	req.bRequest = RT2870_WRITE_REGION_1;
1161 	USETW(req.wValue, 0);
1162 	USETW(req.wIndex, reg);
1163 	USETW(req.wLength, len);
1164 	return (run_do_request(sc, &req, buf));
1165 #endif
1166 }
1167 
1168 static int
1169 run_set_region_4(struct run_softc *sc, uint16_t reg, uint32_t val, int len)
1170 {
1171 	int i, error = 0;
1172 
1173 	KASSERT((len & 3) == 0, ("run_set_region_4: Invalid data length.\n"));
1174 	for (i = 0; i < len && error == 0; i += 4)
1175 		error = run_write(sc, reg + i, val);
1176 	return (error);
1177 }
1178 
1179 /* Read 16-bit from eFUSE ROM (RT3070 only.) */
1180 static int
1181 run_efuse_read_2(struct run_softc *sc, uint16_t addr, uint16_t *val)
1182 {
1183 	uint32_t tmp;
1184 	uint16_t reg;
1185 	int error, ntries;
1186 
1187 	if ((error = run_read(sc, RT3070_EFUSE_CTRL, &tmp)) != 0)
1188 		return (error);
1189 
1190 	addr *= 2;
1191 	/*-
1192 	 * Read one 16-byte block into registers EFUSE_DATA[0-3]:
1193 	 * DATA0: F E D C
1194 	 * DATA1: B A 9 8
1195 	 * DATA2: 7 6 5 4
1196 	 * DATA3: 3 2 1 0
1197 	 */
1198 	tmp &= ~(RT3070_EFSROM_MODE_MASK | RT3070_EFSROM_AIN_MASK);
1199 	tmp |= (addr & ~0xf) << RT3070_EFSROM_AIN_SHIFT | RT3070_EFSROM_KICK;
1200 	run_write(sc, RT3070_EFUSE_CTRL, tmp);
1201 	for (ntries = 0; ntries < 100; ntries++) {
1202 		if ((error = run_read(sc, RT3070_EFUSE_CTRL, &tmp)) != 0)
1203 			return (error);
1204 		if (!(tmp & RT3070_EFSROM_KICK))
1205 			break;
1206 		run_delay(sc, 2);
1207 	}
1208 	if (ntries == 100)
1209 		return (ETIMEDOUT);
1210 
1211 	if ((tmp & RT3070_EFUSE_AOUT_MASK) == RT3070_EFUSE_AOUT_MASK) {
1212 		*val = 0xffff;	/* address not found */
1213 		return (0);
1214 	}
1215 	/* determine to which 32-bit register our 16-bit word belongs */
1216 	reg = RT3070_EFUSE_DATA3 - (addr & 0xc);
1217 	if ((error = run_read(sc, reg, &tmp)) != 0)
1218 		return (error);
1219 
1220 	*val = (addr & 2) ? tmp >> 16 : tmp & 0xffff;
1221 	return (0);
1222 }
1223 
1224 static int
1225 run_eeprom_read_2(struct run_softc *sc, uint16_t addr, uint16_t *val)
1226 {
1227 	usb_device_request_t req;
1228 	uint16_t tmp;
1229 	int error;
1230 
1231 	addr *= 2;
1232 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1233 	req.bRequest = RT2870_EEPROM_READ;
1234 	USETW(req.wValue, 0);
1235 	USETW(req.wIndex, addr);
1236 	USETW(req.wLength, sizeof tmp);
1237 
1238 	error = usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, &tmp);
1239 	if (error == 0)
1240 		*val = le16toh(tmp);
1241 	else
1242 		*val = 0xffff;
1243 	return (error);
1244 }
1245 
1246 static __inline int
1247 run_srom_read(struct run_softc *sc, uint16_t addr, uint16_t *val)
1248 {
1249 	/* either eFUSE ROM or EEPROM */
1250 	return sc->sc_srom_read(sc, addr, val);
1251 }
1252 
1253 static int
1254 run_rt2870_rf_write(struct run_softc *sc, uint8_t reg, uint32_t val)
1255 {
1256 	uint32_t tmp;
1257 	int error, ntries;
1258 
1259 	for (ntries = 0; ntries < 10; ntries++) {
1260 		if ((error = run_read(sc, RT2860_RF_CSR_CFG0, &tmp)) != 0)
1261 			return (error);
1262 		if (!(tmp & RT2860_RF_REG_CTRL))
1263 			break;
1264 	}
1265 	if (ntries == 10)
1266 		return (ETIMEDOUT);
1267 
1268 	/* RF registers are 24-bit on the RT2860 */
1269 	tmp = RT2860_RF_REG_CTRL | 24 << RT2860_RF_REG_WIDTH_SHIFT |
1270 	    (val & 0x3fffff) << 2 | (reg & 3);
1271 	return (run_write(sc, RT2860_RF_CSR_CFG0, tmp));
1272 }
1273 
1274 static int
1275 run_rt3070_rf_read(struct run_softc *sc, uint8_t reg, uint8_t *val)
1276 {
1277 	uint32_t tmp;
1278 	int error, ntries;
1279 
1280 	for (ntries = 0; ntries < 100; ntries++) {
1281 		if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0)
1282 			return (error);
1283 		if (!(tmp & RT3070_RF_KICK))
1284 			break;
1285 	}
1286 	if (ntries == 100)
1287 		return (ETIMEDOUT);
1288 
1289 	tmp = RT3070_RF_KICK | reg << 8;
1290 	if ((error = run_write(sc, RT3070_RF_CSR_CFG, tmp)) != 0)
1291 		return (error);
1292 
1293 	for (ntries = 0; ntries < 100; ntries++) {
1294 		if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0)
1295 			return (error);
1296 		if (!(tmp & RT3070_RF_KICK))
1297 			break;
1298 	}
1299 	if (ntries == 100)
1300 		return (ETIMEDOUT);
1301 
1302 	*val = tmp & 0xff;
1303 	return (0);
1304 }
1305 
1306 static int
1307 run_rt3070_rf_write(struct run_softc *sc, uint8_t reg, uint8_t val)
1308 {
1309 	uint32_t tmp;
1310 	int error, ntries;
1311 
1312 	for (ntries = 0; ntries < 10; ntries++) {
1313 		if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0)
1314 			return (error);
1315 		if (!(tmp & RT3070_RF_KICK))
1316 			break;
1317 	}
1318 	if (ntries == 10)
1319 		return (ETIMEDOUT);
1320 
1321 	tmp = RT3070_RF_WRITE | RT3070_RF_KICK | reg << 8 | val;
1322 	return (run_write(sc, RT3070_RF_CSR_CFG, tmp));
1323 }
1324 
1325 static int
1326 run_bbp_read(struct run_softc *sc, uint8_t reg, uint8_t *val)
1327 {
1328 	uint32_t tmp;
1329 	int ntries, error;
1330 
1331 	for (ntries = 0; ntries < 10; ntries++) {
1332 		if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0)
1333 			return (error);
1334 		if (!(tmp & RT2860_BBP_CSR_KICK))
1335 			break;
1336 	}
1337 	if (ntries == 10)
1338 		return (ETIMEDOUT);
1339 
1340 	tmp = RT2860_BBP_CSR_READ | RT2860_BBP_CSR_KICK | reg << 8;
1341 	if ((error = run_write(sc, RT2860_BBP_CSR_CFG, tmp)) != 0)
1342 		return (error);
1343 
1344 	for (ntries = 0; ntries < 10; ntries++) {
1345 		if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0)
1346 			return (error);
1347 		if (!(tmp & RT2860_BBP_CSR_KICK))
1348 			break;
1349 	}
1350 	if (ntries == 10)
1351 		return (ETIMEDOUT);
1352 
1353 	*val = tmp & 0xff;
1354 	return (0);
1355 }
1356 
1357 static int
1358 run_bbp_write(struct run_softc *sc, uint8_t reg, uint8_t val)
1359 {
1360 	uint32_t tmp;
1361 	int ntries, error;
1362 
1363 	for (ntries = 0; ntries < 10; ntries++) {
1364 		if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0)
1365 			return (error);
1366 		if (!(tmp & RT2860_BBP_CSR_KICK))
1367 			break;
1368 	}
1369 	if (ntries == 10)
1370 		return (ETIMEDOUT);
1371 
1372 	tmp = RT2860_BBP_CSR_KICK | reg << 8 | val;
1373 	return (run_write(sc, RT2860_BBP_CSR_CFG, tmp));
1374 }
1375 
1376 /*
1377  * Send a command to the 8051 microcontroller unit.
1378  */
1379 static int
1380 run_mcu_cmd(struct run_softc *sc, uint8_t cmd, uint16_t arg)
1381 {
1382 	uint32_t tmp;
1383 	int error, ntries;
1384 
1385 	for (ntries = 0; ntries < 100; ntries++) {
1386 		if ((error = run_read(sc, RT2860_H2M_MAILBOX, &tmp)) != 0)
1387 			return error;
1388 		if (!(tmp & RT2860_H2M_BUSY))
1389 			break;
1390 	}
1391 	if (ntries == 100)
1392 		return ETIMEDOUT;
1393 
1394 	tmp = RT2860_H2M_BUSY | RT2860_TOKEN_NO_INTR << 16 | arg;
1395 	if ((error = run_write(sc, RT2860_H2M_MAILBOX, tmp)) == 0)
1396 		error = run_write(sc, RT2860_HOST_CMD, cmd);
1397 	return (error);
1398 }
1399 
1400 /*
1401  * Add `delta' (signed) to each 4-bit sub-word of a 32-bit word.
1402  * Used to adjust per-rate Tx power registers.
1403  */
1404 static __inline uint32_t
1405 b4inc(uint32_t b32, int8_t delta)
1406 {
1407 	int8_t i, b4;
1408 
1409 	for (i = 0; i < 8; i++) {
1410 		b4 = b32 & 0xf;
1411 		b4 += delta;
1412 		if (b4 < 0)
1413 			b4 = 0;
1414 		else if (b4 > 0xf)
1415 			b4 = 0xf;
1416 		b32 = b32 >> 4 | b4 << 28;
1417 	}
1418 	return (b32);
1419 }
1420 
1421 static const char *
1422 run_get_rf(int rev)
1423 {
1424 	switch (rev) {
1425 	case RT2860_RF_2820:	return "RT2820";
1426 	case RT2860_RF_2850:	return "RT2850";
1427 	case RT2860_RF_2720:	return "RT2720";
1428 	case RT2860_RF_2750:	return "RT2750";
1429 	case RT3070_RF_3020:	return "RT3020";
1430 	case RT3070_RF_2020:	return "RT2020";
1431 	case RT3070_RF_3021:	return "RT3021";
1432 	case RT3070_RF_3022:	return "RT3022";
1433 	case RT3070_RF_3052:	return "RT3052";
1434 	}
1435 	return ("unknown");
1436 }
1437 
1438 int
1439 run_read_eeprom(struct run_softc *sc)
1440 {
1441 	int8_t delta_2ghz, delta_5ghz;
1442 	uint32_t tmp;
1443 	uint16_t val;
1444 	int ridx, ant, i;
1445 
1446 	/* check whether the ROM is eFUSE ROM or EEPROM */
1447 	sc->sc_srom_read = run_eeprom_read_2;
1448 	if (sc->mac_ver >= 0x3070) {
1449 		run_read(sc, RT3070_EFUSE_CTRL, &tmp);
1450 		DPRINTF("EFUSE_CTRL=0x%08x\n", tmp);
1451 		if (tmp & RT3070_SEL_EFUSE)
1452 			sc->sc_srom_read = run_efuse_read_2;
1453 	}
1454 
1455 	/* read ROM version */
1456 	run_srom_read(sc, RT2860_EEPROM_VERSION, &val);
1457 	DPRINTF("EEPROM rev=%d, FAE=%d\n", val & 0xff, val >> 8);
1458 
1459 	/* read MAC address */
1460 	run_srom_read(sc, RT2860_EEPROM_MAC01, &val);
1461 	sc->sc_bssid[0] = val & 0xff;
1462 	sc->sc_bssid[1] = val >> 8;
1463 	run_srom_read(sc, RT2860_EEPROM_MAC23, &val);
1464 	sc->sc_bssid[2] = val & 0xff;
1465 	sc->sc_bssid[3] = val >> 8;
1466 	run_srom_read(sc, RT2860_EEPROM_MAC45, &val);
1467 	sc->sc_bssid[4] = val & 0xff;
1468 	sc->sc_bssid[5] = val >> 8;
1469 
1470 	/* read vender BBP settings */
1471 	for (i = 0; i < 10; i++) {
1472 		run_srom_read(sc, RT2860_EEPROM_BBP_BASE + i, &val);
1473 		sc->bbp[i].val = val & 0xff;
1474 		sc->bbp[i].reg = val >> 8;
1475 		DPRINTF("BBP%d=0x%02x\n", sc->bbp[i].reg, sc->bbp[i].val);
1476 	}
1477 	if (sc->mac_ver >= 0x3071) {
1478 		/* read vendor RF settings */
1479 		for (i = 0; i < 10; i++) {
1480 			run_srom_read(sc, RT3071_EEPROM_RF_BASE + i, &val);
1481 			sc->rf[i].val = val & 0xff;
1482 			sc->rf[i].reg = val >> 8;
1483 			DPRINTF("RF%d=0x%02x\n", sc->rf[i].reg,
1484 			    sc->rf[i].val);
1485 		}
1486 	}
1487 
1488 	/* read RF frequency offset from EEPROM */
1489 	run_srom_read(sc, RT2860_EEPROM_FREQ_LEDS, &val);
1490 	sc->freq = ((val & 0xff) != 0xff) ? val & 0xff : 0;
1491 	DPRINTF("EEPROM freq offset %d\n", sc->freq & 0xff);
1492 
1493 	if (val >> 8 != 0xff) {
1494 		/* read LEDs operating mode */
1495 		sc->leds = val >> 8;
1496 		run_srom_read(sc, RT2860_EEPROM_LED1, &sc->led[0]);
1497 		run_srom_read(sc, RT2860_EEPROM_LED2, &sc->led[1]);
1498 		run_srom_read(sc, RT2860_EEPROM_LED3, &sc->led[2]);
1499 	} else {
1500 		/* broken EEPROM, use default settings */
1501 		sc->leds = 0x01;
1502 		sc->led[0] = 0x5555;
1503 		sc->led[1] = 0x2221;
1504 		sc->led[2] = 0x5627;	/* differs from RT2860 */
1505 	}
1506 	DPRINTF("EEPROM LED mode=0x%02x, LEDs=0x%04x/0x%04x/0x%04x\n",
1507 	    sc->leds, sc->led[0], sc->led[1], sc->led[2]);
1508 
1509 	/* read RF information */
1510 	run_srom_read(sc, RT2860_EEPROM_ANTENNA, &val);
1511 	if (val == 0xffff) {
1512 		DPRINTF("invalid EEPROM antenna info, using default\n");
1513 		if (sc->mac_ver == 0x3572) {
1514 			/* default to RF3052 2T2R */
1515 			sc->rf_rev = RT3070_RF_3052;
1516 			sc->ntxchains = 2;
1517 			sc->nrxchains = 2;
1518 		} else if (sc->mac_ver >= 0x3070) {
1519 			/* default to RF3020 1T1R */
1520 			sc->rf_rev = RT3070_RF_3020;
1521 			sc->ntxchains = 1;
1522 			sc->nrxchains = 1;
1523 		} else {
1524 			/* default to RF2820 1T2R */
1525 			sc->rf_rev = RT2860_RF_2820;
1526 			sc->ntxchains = 1;
1527 			sc->nrxchains = 2;
1528 		}
1529 	} else {
1530 		sc->rf_rev = (val >> 8) & 0xf;
1531 		sc->ntxchains = (val >> 4) & 0xf;
1532 		sc->nrxchains = val & 0xf;
1533 	}
1534 	DPRINTF("EEPROM RF rev=0x%02x chains=%dT%dR\n",
1535 	    sc->rf_rev, sc->ntxchains, sc->nrxchains);
1536 
1537 	/* check if RF supports automatic Tx access gain control */
1538 	run_srom_read(sc, RT2860_EEPROM_CONFIG, &val);
1539 	DPRINTF("EEPROM CFG 0x%04x\n", val);
1540 	/* check if driver should patch the DAC issue */
1541 	if ((val >> 8) != 0xff)
1542 		sc->patch_dac = (val >> 15) & 1;
1543 	if ((val & 0xff) != 0xff) {
1544 		sc->ext_5ghz_lna = (val >> 3) & 1;
1545 		sc->ext_2ghz_lna = (val >> 2) & 1;
1546 		/* check if RF supports automatic Tx access gain control */
1547 		sc->calib_2ghz = sc->calib_5ghz = (val >> 1) & 1;
1548 		/* check if we have a hardware radio switch */
1549 		sc->rfswitch = val & 1;
1550 	}
1551 
1552 	/* read power settings for 2GHz channels */
1553 	for (i = 0; i < 14; i += 2) {
1554 		run_srom_read(sc, RT2860_EEPROM_PWR2GHZ_BASE1 + i / 2, &val);
1555 		sc->txpow1[i + 0] = (int8_t)(val & 0xff);
1556 		sc->txpow1[i + 1] = (int8_t)(val >> 8);
1557 
1558 		run_srom_read(sc, RT2860_EEPROM_PWR2GHZ_BASE2 + i / 2, &val);
1559 		sc->txpow2[i + 0] = (int8_t)(val & 0xff);
1560 		sc->txpow2[i + 1] = (int8_t)(val >> 8);
1561 	}
1562 	/* fix broken Tx power entries */
1563 	for (i = 0; i < 14; i++) {
1564 		if (sc->txpow1[i] < 0 || sc->txpow1[i] > 31)
1565 			sc->txpow1[i] = 5;
1566 		if (sc->txpow2[i] < 0 || sc->txpow2[i] > 31)
1567 			sc->txpow2[i] = 5;
1568 		DPRINTF("chan %d: power1=%d, power2=%d\n",
1569 		    rt2860_rf2850[i].chan, sc->txpow1[i], sc->txpow2[i]);
1570 	}
1571 	/* read power settings for 5GHz channels */
1572 	for (i = 0; i < 40; i += 2) {
1573 		run_srom_read(sc, RT2860_EEPROM_PWR5GHZ_BASE1 + i / 2, &val);
1574 		sc->txpow1[i + 14] = (int8_t)(val & 0xff);
1575 		sc->txpow1[i + 15] = (int8_t)(val >> 8);
1576 
1577 		run_srom_read(sc, RT2860_EEPROM_PWR5GHZ_BASE2 + i / 2, &val);
1578 		sc->txpow2[i + 14] = (int8_t)(val & 0xff);
1579 		sc->txpow2[i + 15] = (int8_t)(val >> 8);
1580 	}
1581 	/* fix broken Tx power entries */
1582 	for (i = 0; i < 40; i++) {
1583 		if (sc->txpow1[14 + i] < -7 || sc->txpow1[14 + i] > 15)
1584 			sc->txpow1[14 + i] = 5;
1585 		if (sc->txpow2[14 + i] < -7 || sc->txpow2[14 + i] > 15)
1586 			sc->txpow2[14 + i] = 5;
1587 		DPRINTF("chan %d: power1=%d, power2=%d\n",
1588 		    rt2860_rf2850[14 + i].chan, sc->txpow1[14 + i],
1589 		    sc->txpow2[14 + i]);
1590 	}
1591 
1592 	/* read Tx power compensation for each Tx rate */
1593 	run_srom_read(sc, RT2860_EEPROM_DELTAPWR, &val);
1594 	delta_2ghz = delta_5ghz = 0;
1595 	if ((val & 0xff) != 0xff && (val & 0x80)) {
1596 		delta_2ghz = val & 0xf;
1597 		if (!(val & 0x40))	/* negative number */
1598 			delta_2ghz = -delta_2ghz;
1599 	}
1600 	val >>= 8;
1601 	if ((val & 0xff) != 0xff && (val & 0x80)) {
1602 		delta_5ghz = val & 0xf;
1603 		if (!(val & 0x40))	/* negative number */
1604 			delta_5ghz = -delta_5ghz;
1605 	}
1606 	DPRINTF("power compensation=%d (2GHz), %d (5GHz)\n",
1607 	    delta_2ghz, delta_5ghz);
1608 
1609 	for (ridx = 0; ridx < 5; ridx++) {
1610 		uint32_t reg;
1611 
1612 		run_srom_read(sc, RT2860_EEPROM_RPWR + ridx * 2, &val);
1613 		reg = val;
1614 		run_srom_read(sc, RT2860_EEPROM_RPWR + ridx * 2 + 1, &val);
1615 		reg |= (uint32_t)val << 16;
1616 
1617 		sc->txpow20mhz[ridx] = reg;
1618 		sc->txpow40mhz_2ghz[ridx] = b4inc(reg, delta_2ghz);
1619 		sc->txpow40mhz_5ghz[ridx] = b4inc(reg, delta_5ghz);
1620 
1621 		DPRINTF("ridx %d: power 20MHz=0x%08x, 40MHz/2GHz=0x%08x, "
1622 		    "40MHz/5GHz=0x%08x\n", ridx, sc->txpow20mhz[ridx],
1623 		    sc->txpow40mhz_2ghz[ridx], sc->txpow40mhz_5ghz[ridx]);
1624 	}
1625 
1626 	/* read RSSI offsets and LNA gains from EEPROM */
1627 	run_srom_read(sc, RT2860_EEPROM_RSSI1_2GHZ, &val);
1628 	sc->rssi_2ghz[0] = val & 0xff;	/* Ant A */
1629 	sc->rssi_2ghz[1] = val >> 8;	/* Ant B */
1630 	run_srom_read(sc, RT2860_EEPROM_RSSI2_2GHZ, &val);
1631 	if (sc->mac_ver >= 0x3070) {
1632 		/*
1633 		 * On RT3070 chips (limited to 2 Rx chains), this ROM
1634 		 * field contains the Tx mixer gain for the 2GHz band.
1635 		 */
1636 		if ((val & 0xff) != 0xff)
1637 			sc->txmixgain_2ghz = val & 0x7;
1638 		DPRINTF("tx mixer gain=%u (2GHz)\n", sc->txmixgain_2ghz);
1639 	} else
1640 		sc->rssi_2ghz[2] = val & 0xff;	/* Ant C */
1641 	sc->lna[2] = val >> 8;		/* channel group 2 */
1642 
1643 	run_srom_read(sc, RT2860_EEPROM_RSSI1_5GHZ, &val);
1644 	sc->rssi_5ghz[0] = val & 0xff;	/* Ant A */
1645 	sc->rssi_5ghz[1] = val >> 8;	/* Ant B */
1646 	run_srom_read(sc, RT2860_EEPROM_RSSI2_5GHZ, &val);
1647 	if (sc->mac_ver == 0x3572) {
1648 		/*
1649 		 * On RT3572 chips (limited to 2 Rx chains), this ROM
1650 		 * field contains the Tx mixer gain for the 5GHz band.
1651 		 */
1652 		if ((val & 0xff) != 0xff)
1653 			sc->txmixgain_5ghz = val & 0x7;
1654 		DPRINTF("tx mixer gain=%u (5GHz)\n", sc->txmixgain_5ghz);
1655 	} else
1656 		sc->rssi_5ghz[2] = val & 0xff;	/* Ant C */
1657 	sc->lna[3] = val >> 8;		/* channel group 3 */
1658 
1659 	run_srom_read(sc, RT2860_EEPROM_LNA, &val);
1660 	sc->lna[0] = val & 0xff;	/* channel group 0 */
1661 	sc->lna[1] = val >> 8;		/* channel group 1 */
1662 
1663 	/* fix broken 5GHz LNA entries */
1664 	if (sc->lna[2] == 0 || sc->lna[2] == 0xff) {
1665 		DPRINTF("invalid LNA for channel group %d\n", 2);
1666 		sc->lna[2] = sc->lna[1];
1667 	}
1668 	if (sc->lna[3] == 0 || sc->lna[3] == 0xff) {
1669 		DPRINTF("invalid LNA for channel group %d\n", 3);
1670 		sc->lna[3] = sc->lna[1];
1671 	}
1672 
1673 	/* fix broken RSSI offset entries */
1674 	for (ant = 0; ant < 3; ant++) {
1675 		if (sc->rssi_2ghz[ant] < -10 || sc->rssi_2ghz[ant] > 10) {
1676 			DPRINTF("invalid RSSI%d offset: %d (2GHz)\n",
1677 			    ant + 1, sc->rssi_2ghz[ant]);
1678 			sc->rssi_2ghz[ant] = 0;
1679 		}
1680 		if (sc->rssi_5ghz[ant] < -10 || sc->rssi_5ghz[ant] > 10) {
1681 			DPRINTF("invalid RSSI%d offset: %d (5GHz)\n",
1682 			    ant + 1, sc->rssi_5ghz[ant]);
1683 			sc->rssi_5ghz[ant] = 0;
1684 		}
1685 	}
1686 	return (0);
1687 }
1688 
1689 static struct ieee80211_node *
1690 run_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
1691 {
1692 	return malloc(sizeof (struct run_node), M_DEVBUF, M_NOWAIT | M_ZERO);
1693 }
1694 
1695 static int
1696 run_media_change(struct ifnet *ifp)
1697 {
1698 	struct ieee80211vap *vap = ifp->if_softc;
1699 	struct ieee80211com *ic = vap->iv_ic;
1700 	const struct ieee80211_txparam *tp;
1701 	struct run_softc *sc = ic->ic_ifp->if_softc;
1702 	uint8_t rate, ridx;
1703 	int error;
1704 
1705 	RUN_LOCK(sc);
1706 
1707 	error = ieee80211_media_change(ifp);
1708 	if (error != ENETRESET) {
1709 		RUN_UNLOCK(sc);
1710 		return (error);
1711 	}
1712 
1713 	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1714 	if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
1715 		struct ieee80211_node *ni;
1716 		struct run_node	*rn;
1717 
1718 		rate = ic->ic_sup_rates[ic->ic_curmode].
1719 		    rs_rates[tp->ucastrate] & IEEE80211_RATE_VAL;
1720 		for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
1721 			if (rt2860_rates[ridx].rate == rate)
1722 				break;
1723 		ni = ieee80211_ref_node(vap->iv_bss);
1724 		rn = (struct run_node *)ni;
1725 		rn->fix_ridx = ridx;
1726 		DPRINTF("rate=%d, fix_ridx=%d\n", rate, rn->fix_ridx);
1727 		ieee80211_free_node(ni);
1728 	}
1729 
1730 #if 0
1731 	if ((ifp->if_flags & IFF_UP) &&
1732 	    (ifp->if_drv_flags &  IFF_DRV_RUNNING)){
1733 		run_init_locked(sc);
1734 	}
1735 #endif
1736 
1737 	RUN_UNLOCK(sc);
1738 
1739 	return (0);
1740 }
1741 
1742 static int
1743 run_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
1744 {
1745 	const struct ieee80211_txparam *tp;
1746 	struct ieee80211com *ic = vap->iv_ic;
1747 	struct run_softc *sc = ic->ic_ifp->if_softc;
1748 	struct run_vap *rvp = RUN_VAP(vap);
1749 	enum ieee80211_state ostate;
1750 	uint32_t sta[3];
1751 	uint32_t tmp;
1752 	uint8_t ratectl;
1753 	uint8_t restart_ratectl = 0;
1754 	uint8_t bid = 1 << rvp->rvp_id;
1755 
1756 	ostate = vap->iv_state;
1757 	DPRINTF("%s -> %s\n",
1758 		ieee80211_state_name[ostate],
1759 		ieee80211_state_name[nstate]);
1760 
1761 	IEEE80211_UNLOCK(ic);
1762 	RUN_LOCK(sc);
1763 
1764 	ratectl = sc->ratectl_run; /* remember current state */
1765 	sc->ratectl_run = RUN_RATECTL_OFF;
1766 	usb_callout_stop(&sc->ratectl_ch);
1767 
1768 	if (ostate == IEEE80211_S_RUN) {
1769 		/* turn link LED off */
1770 		run_set_leds(sc, RT2860_LED_RADIO);
1771 	}
1772 
1773 	switch (nstate) {
1774 	case IEEE80211_S_INIT:
1775 		restart_ratectl = 1;
1776 
1777 		if (ostate != IEEE80211_S_RUN)
1778 			break;
1779 
1780 		ratectl &= ~bid;
1781 		sc->runbmap &= ~bid;
1782 
1783 		/* abort TSF synchronization if there is no vap running */
1784 		if (--sc->running == 0) {
1785 			run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
1786 			run_write(sc, RT2860_BCN_TIME_CFG,
1787 			    tmp & ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN |
1788 			    RT2860_TBTT_TIMER_EN));
1789 		}
1790 		break;
1791 
1792 	case IEEE80211_S_RUN:
1793 		if (!(sc->runbmap & bid)) {
1794 			if(sc->running++)
1795 				restart_ratectl = 1;
1796 			sc->runbmap |= bid;
1797 		}
1798 
1799 		m_freem(rvp->beacon_mbuf);
1800 		rvp->beacon_mbuf = NULL;
1801 
1802 		switch (vap->iv_opmode) {
1803 		case IEEE80211_M_HOSTAP:
1804 		case IEEE80211_M_MBSS:
1805 			sc->ap_running |= bid;
1806 			ic->ic_opmode = vap->iv_opmode;
1807 			run_update_beacon_cb(vap);
1808 			break;
1809 		case IEEE80211_M_IBSS:
1810 			sc->adhoc_running |= bid;
1811 			if (!sc->ap_running)
1812 				ic->ic_opmode = vap->iv_opmode;
1813 			run_update_beacon_cb(vap);
1814 			break;
1815 		case IEEE80211_M_STA:
1816 			sc->sta_running |= bid;
1817 			if (!sc->ap_running && !sc->adhoc_running)
1818 				ic->ic_opmode = vap->iv_opmode;
1819 
1820 			/* read statistic counters (clear on read) */
1821 			run_read_region_1(sc, RT2860_TX_STA_CNT0,
1822 			    (uint8_t *)sta, sizeof sta);
1823 
1824 			break;
1825 		default:
1826 			ic->ic_opmode = vap->iv_opmode;
1827 			break;
1828 		}
1829 
1830 		if (vap->iv_opmode != IEEE80211_M_MONITOR) {
1831 			struct ieee80211_node *ni;
1832 
1833 			run_updateslot(ic->ic_ifp);
1834 			run_enable_mrr(sc);
1835 			run_set_txpreamble(sc);
1836 			run_set_basicrates(sc);
1837 			ni = ieee80211_ref_node(vap->iv_bss);
1838 			IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid);
1839 			run_set_bssid(sc, ni->ni_bssid);
1840 			ieee80211_free_node(ni);
1841 			run_enable_tsf_sync(sc);
1842 
1843 			/* enable automatic rate adaptation */
1844 			tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
1845 			if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
1846 				ratectl |= bid;
1847 		}
1848 
1849 		/* turn link LED on */
1850 		run_set_leds(sc, RT2860_LED_RADIO |
1851 		    (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan) ?
1852 		     RT2860_LED_LINK_2GHZ : RT2860_LED_LINK_5GHZ));
1853 
1854 		break;
1855 	default:
1856 		DPRINTFN(6, "undefined case\n");
1857 		break;
1858 	}
1859 
1860 	/* restart amrr for running VAPs */
1861 	if ((sc->ratectl_run = ratectl) && restart_ratectl)
1862 		usb_callout_reset(&sc->ratectl_ch, hz, run_ratectl_to, sc);
1863 
1864 	RUN_UNLOCK(sc);
1865 	IEEE80211_LOCK(ic);
1866 
1867 	return(rvp->newstate(vap, nstate, arg));
1868 }
1869 
1870 /* ARGSUSED */
1871 static void
1872 run_wme_update_cb(void *arg)
1873 {
1874 	struct ieee80211com *ic = arg;
1875 	struct run_softc *sc = ic->ic_ifp->if_softc;
1876 	struct ieee80211_wme_state *wmesp = &ic->ic_wme;
1877 	int aci, error = 0;
1878 
1879 	RUN_LOCK_ASSERT(sc, MA_OWNED);
1880 
1881 	/* update MAC TX configuration registers */
1882 	for (aci = 0; aci < WME_NUM_AC; aci++) {
1883 		error = run_write(sc, RT2860_EDCA_AC_CFG(aci),
1884 		    wmesp->wme_params[aci].wmep_logcwmax << 16 |
1885 		    wmesp->wme_params[aci].wmep_logcwmin << 12 |
1886 		    wmesp->wme_params[aci].wmep_aifsn  <<  8 |
1887 		    wmesp->wme_params[aci].wmep_txopLimit);
1888 		if (error) goto err;
1889 	}
1890 
1891 	/* update SCH/DMA registers too */
1892 	error = run_write(sc, RT2860_WMM_AIFSN_CFG,
1893 	    wmesp->wme_params[WME_AC_VO].wmep_aifsn  << 12 |
1894 	    wmesp->wme_params[WME_AC_VI].wmep_aifsn  <<  8 |
1895 	    wmesp->wme_params[WME_AC_BK].wmep_aifsn  <<  4 |
1896 	    wmesp->wme_params[WME_AC_BE].wmep_aifsn);
1897 	if (error) goto err;
1898 	error = run_write(sc, RT2860_WMM_CWMIN_CFG,
1899 	    wmesp->wme_params[WME_AC_VO].wmep_logcwmin << 12 |
1900 	    wmesp->wme_params[WME_AC_VI].wmep_logcwmin <<  8 |
1901 	    wmesp->wme_params[WME_AC_BK].wmep_logcwmin <<  4 |
1902 	    wmesp->wme_params[WME_AC_BE].wmep_logcwmin);
1903 	if (error) goto err;
1904 	error = run_write(sc, RT2860_WMM_CWMAX_CFG,
1905 	    wmesp->wme_params[WME_AC_VO].wmep_logcwmax << 12 |
1906 	    wmesp->wme_params[WME_AC_VI].wmep_logcwmax <<  8 |
1907 	    wmesp->wme_params[WME_AC_BK].wmep_logcwmax <<  4 |
1908 	    wmesp->wme_params[WME_AC_BE].wmep_logcwmax);
1909 	if (error) goto err;
1910 	error = run_write(sc, RT2860_WMM_TXOP0_CFG,
1911 	    wmesp->wme_params[WME_AC_BK].wmep_txopLimit << 16 |
1912 	    wmesp->wme_params[WME_AC_BE].wmep_txopLimit);
1913 	if (error) goto err;
1914 	error = run_write(sc, RT2860_WMM_TXOP1_CFG,
1915 	    wmesp->wme_params[WME_AC_VO].wmep_txopLimit << 16 |
1916 	    wmesp->wme_params[WME_AC_VI].wmep_txopLimit);
1917 
1918 err:
1919 	if (error)
1920 		DPRINTF("WME update failed\n");
1921 
1922 	return;
1923 }
1924 
1925 static int
1926 run_wme_update(struct ieee80211com *ic)
1927 {
1928 	struct run_softc *sc = ic->ic_ifp->if_softc;
1929 
1930 	/* sometime called wothout lock */
1931 	if (mtx_owned(&ic->ic_comlock.mtx)) {
1932 		uint32_t i = RUN_CMDQ_GET(&sc->cmdq_store);
1933 		DPRINTF("cmdq_store=%d\n", i);
1934 		sc->cmdq[i].func = run_wme_update_cb;
1935 		sc->cmdq[i].arg0 = ic;
1936 		ieee80211_runtask(ic, &sc->cmdq_task);
1937 		return (0);
1938 	}
1939 
1940 	RUN_LOCK(sc);
1941 	run_wme_update_cb(ic);
1942 	RUN_UNLOCK(sc);
1943 
1944 	/* return whatever, upper layer desn't care anyway */
1945 	return (0);
1946 }
1947 
1948 static void
1949 run_key_update_begin(struct ieee80211vap *vap)
1950 {
1951 	/*
1952 	 * To avoid out-of-order events, both run_key_set() and
1953 	 * _delete() are deferred and handled by run_cmdq_cb().
1954 	 * So, there is nothing we need to do here.
1955 	 */
1956 }
1957 
1958 static void
1959 run_key_update_end(struct ieee80211vap *vap)
1960 {
1961 	/* null */
1962 }
1963 
1964 static void
1965 run_key_set_cb(void *arg)
1966 {
1967 	struct run_cmdq *cmdq = arg;
1968 	struct ieee80211vap *vap = cmdq->arg1;
1969 	struct ieee80211_key *k = cmdq->k;
1970 	struct ieee80211com *ic = vap->iv_ic;
1971 	struct run_softc *sc = ic->ic_ifp->if_softc;
1972 	struct ieee80211_node *ni;
1973 	uint32_t attr;
1974 	uint16_t base, associd;
1975 	uint8_t mode, wcid, iv[8];
1976 
1977 	RUN_LOCK_ASSERT(sc, MA_OWNED);
1978 
1979 	if (vap->iv_opmode == IEEE80211_M_HOSTAP)
1980 		ni = ieee80211_find_vap_node(&ic->ic_sta, vap, cmdq->mac);
1981 	else
1982 		ni = vap->iv_bss;
1983 	associd = (ni != NULL) ? ni->ni_associd : 0;
1984 
1985 	/* map net80211 cipher to RT2860 security mode */
1986 	switch (k->wk_cipher->ic_cipher) {
1987 	case IEEE80211_CIPHER_WEP:
1988 		if(k->wk_keylen < 8)
1989 			mode = RT2860_MODE_WEP40;
1990 		else
1991 			mode = RT2860_MODE_WEP104;
1992 		break;
1993 	case IEEE80211_CIPHER_TKIP:
1994 		mode = RT2860_MODE_TKIP;
1995 		break;
1996 	case IEEE80211_CIPHER_AES_CCM:
1997 		mode = RT2860_MODE_AES_CCMP;
1998 		break;
1999 	default:
2000 		DPRINTF("undefined case\n");
2001 		return;
2002 	}
2003 
2004 	DPRINTFN(1, "associd=%x, keyix=%d, mode=%x, type=%s, tx=%s, rx=%s\n",
2005 	    associd, k->wk_keyix, mode,
2006 	    (k->wk_flags & IEEE80211_KEY_GROUP) ? "group" : "pairwise",
2007 	    (k->wk_flags & IEEE80211_KEY_XMIT) ? "on" : "off",
2008 	    (k->wk_flags & IEEE80211_KEY_RECV) ? "on" : "off");
2009 
2010 	if (k->wk_flags & IEEE80211_KEY_GROUP) {
2011 		wcid = 0;	/* NB: update WCID0 for group keys */
2012 		base = RT2860_SKEY(RUN_VAP(vap)->rvp_id, k->wk_keyix);
2013 	} else {
2014 		wcid = RUN_AID2WCID(associd);
2015 		base = RT2860_PKEY(wcid);
2016 	}
2017 
2018 	if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP) {
2019 		if(run_write_region_1(sc, base, k->wk_key, 16))
2020 			return;
2021 		if(run_write_region_1(sc, base + 16, &k->wk_key[16], 8))	/* wk_txmic */
2022 			return;
2023 		if(run_write_region_1(sc, base + 24, &k->wk_key[24], 8))	/* wk_rxmic */
2024 			return;
2025 	} else {
2026 		/* roundup len to 16-bit: XXX fix write_region_1() instead */
2027 		if(run_write_region_1(sc, base, k->wk_key, (k->wk_keylen + 1) & ~1))
2028 			return;
2029 	}
2030 
2031 	if (!(k->wk_flags & IEEE80211_KEY_GROUP) ||
2032 	    (k->wk_flags & (IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV))) {
2033 		/* set initial packet number in IV+EIV */
2034 		if (k->wk_cipher == IEEE80211_CIPHER_WEP) {
2035 			memset(iv, 0, sizeof iv);
2036 			iv[3] = vap->iv_def_txkey << 6;
2037 		} else {
2038 			if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP) {
2039 				iv[0] = k->wk_keytsc >> 8;
2040 				iv[1] = (iv[0] | 0x20) & 0x7f;
2041 				iv[2] = k->wk_keytsc;
2042 			} else /* CCMP */ {
2043 				iv[0] = k->wk_keytsc;
2044 				iv[1] = k->wk_keytsc >> 8;
2045 				iv[2] = 0;
2046 			}
2047 			iv[3] = k->wk_keyix << 6 | IEEE80211_WEP_EXTIV;
2048 			iv[4] = k->wk_keytsc >> 16;
2049 			iv[5] = k->wk_keytsc >> 24;
2050 			iv[6] = k->wk_keytsc >> 32;
2051 			iv[7] = k->wk_keytsc >> 40;
2052 		}
2053 		if (run_write_region_1(sc, RT2860_IVEIV(wcid), iv, 8))
2054 			return;
2055 	}
2056 
2057 	if (k->wk_flags & IEEE80211_KEY_GROUP) {
2058 		/* install group key */
2059 		if (run_read(sc, RT2860_SKEY_MODE_0_7, &attr))
2060 			return;
2061 		attr &= ~(0xf << (k->wk_keyix * 4));
2062 		attr |= mode << (k->wk_keyix * 4);
2063 		if (run_write(sc, RT2860_SKEY_MODE_0_7, attr))
2064 			return;
2065 	} else {
2066 		/* install pairwise key */
2067 		if (run_read(sc, RT2860_WCID_ATTR(wcid), &attr))
2068 			return;
2069 		attr = (attr & ~0xf) | (mode << 1) | RT2860_RX_PKEY_EN;
2070 		if (run_write(sc, RT2860_WCID_ATTR(wcid), attr))
2071 			return;
2072 	}
2073 
2074 	/* TODO create a pass-thru key entry? */
2075 
2076 	/* need wcid to delete the right key later */
2077 	k->wk_pad = wcid;
2078 }
2079 
2080 /*
2081  * Don't have to be deferred, but in order to keep order of
2082  * execution, i.e. with run_key_delete(), defer this and let
2083  * run_cmdq_cb() maintain the order.
2084  *
2085  * return 0 on error
2086  */
2087 static int
2088 run_key_set(struct ieee80211vap *vap, struct ieee80211_key *k,
2089 		const uint8_t mac[IEEE80211_ADDR_LEN])
2090 {
2091 	struct ieee80211com *ic = vap->iv_ic;
2092 	struct run_softc *sc = ic->ic_ifp->if_softc;
2093 	uint32_t i;
2094 
2095 	i = RUN_CMDQ_GET(&sc->cmdq_store);
2096 	DPRINTF("cmdq_store=%d\n", i);
2097 	sc->cmdq[i].func = run_key_set_cb;
2098 	sc->cmdq[i].arg0 = NULL;
2099 	sc->cmdq[i].arg1 = vap;
2100 	sc->cmdq[i].k = k;
2101 	IEEE80211_ADDR_COPY(sc->cmdq[i].mac, mac);
2102 	ieee80211_runtask(ic, &sc->cmdq_task);
2103 
2104 	/*
2105 	 * To make sure key will be set when hostapd
2106 	 * calls iv_key_set() before if_init().
2107 	 */
2108 	if (vap->iv_opmode == IEEE80211_M_HOSTAP) {
2109 		RUN_LOCK(sc);
2110 		sc->cmdq_key_set = RUN_CMDQ_GO;
2111 		RUN_UNLOCK(sc);
2112 	}
2113 
2114 	return (1);
2115 }
2116 
2117 /*
2118  * If wlan is destroyed without being brought down i.e. without
2119  * wlan down or wpa_cli terminate, this function is called after
2120  * vap is gone. Don't refer it.
2121  */
2122 static void
2123 run_key_delete_cb(void *arg)
2124 {
2125 	struct run_cmdq *cmdq = arg;
2126 	struct run_softc *sc = cmdq->arg1;
2127 	struct ieee80211_key *k = &cmdq->key;
2128 	uint32_t attr;
2129 	uint8_t wcid;
2130 
2131 	RUN_LOCK_ASSERT(sc, MA_OWNED);
2132 
2133 	if (k->wk_flags & IEEE80211_KEY_GROUP) {
2134 		/* remove group key */
2135 		DPRINTF("removing group key\n");
2136 		run_read(sc, RT2860_SKEY_MODE_0_7, &attr);
2137 		attr &= ~(0xf << (k->wk_keyix * 4));
2138 		run_write(sc, RT2860_SKEY_MODE_0_7, attr);
2139 	} else {
2140 		/* remove pairwise key */
2141 		DPRINTF("removing key for wcid %x\n", k->wk_pad);
2142 		/* matching wcid was written to wk_pad in run_key_set() */
2143 		wcid = k->wk_pad;
2144 		run_read(sc, RT2860_WCID_ATTR(wcid), &attr);
2145 		attr &= ~0xf;
2146 		run_write(sc, RT2860_WCID_ATTR(wcid), attr);
2147 		run_set_region_4(sc, RT2860_WCID_ENTRY(wcid), 0, 8);
2148 	}
2149 
2150 	k->wk_pad = 0;
2151 }
2152 
2153 /*
2154  * return 0 on error
2155  */
2156 static int
2157 run_key_delete(struct ieee80211vap *vap, struct ieee80211_key *k)
2158 {
2159 	struct ieee80211com *ic = vap->iv_ic;
2160 	struct run_softc *sc = ic->ic_ifp->if_softc;
2161 	struct ieee80211_key *k0;
2162 	uint32_t i;
2163 
2164 	/*
2165 	 * When called back, key might be gone. So, make a copy
2166 	 * of some values need to delete keys before deferring.
2167 	 * But, because of LOR with node lock, cannot use lock here.
2168 	 * So, use atomic instead.
2169 	 */
2170 	i = RUN_CMDQ_GET(&sc->cmdq_store);
2171 	DPRINTF("cmdq_store=%d\n", i);
2172 	sc->cmdq[i].func = run_key_delete_cb;
2173 	sc->cmdq[i].arg0 = NULL;
2174 	sc->cmdq[i].arg1 = sc;
2175 	k0 = &sc->cmdq[i].key;
2176 	k0->wk_flags = k->wk_flags;
2177 	k0->wk_keyix = k->wk_keyix;
2178 	/* matching wcid was written to wk_pad in run_key_set() */
2179 	k0->wk_pad = k->wk_pad;
2180 	ieee80211_runtask(ic, &sc->cmdq_task);
2181 	return (1);	/* return fake success */
2182 
2183 }
2184 
2185 static void
2186 run_ratectl_to(void *arg)
2187 {
2188 	struct run_softc *sc = arg;
2189 
2190 	/* do it in a process context, so it can go sleep */
2191 	ieee80211_runtask(sc->sc_ifp->if_l2com, &sc->ratectl_task);
2192 	/* next timeout will be rescheduled in the callback task */
2193 }
2194 
2195 /* ARGSUSED */
2196 static void
2197 run_ratectl_cb(void *arg, int pending)
2198 {
2199 	struct run_softc *sc = arg;
2200 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2201 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2202 
2203 	if (vap == NULL)
2204 		return;
2205 
2206 	if (sc->rvp_cnt <= 1 && vap->iv_opmode == IEEE80211_M_STA)
2207 		run_iter_func(sc, vap->iv_bss);
2208 	else {
2209 		/*
2210 		 * run_reset_livelock() doesn't do anything with AMRR,
2211 		 * but Ralink wants us to call it every 1 sec. So, we
2212 		 * piggyback here rather than creating another callout.
2213 		 * Livelock may occur only in HOSTAP or IBSS mode
2214 		 * (when h/w is sending beacons).
2215 		 */
2216 		RUN_LOCK(sc);
2217 		run_reset_livelock(sc);
2218 		/* just in case, there are some stats to drain */
2219 		run_drain_fifo(sc);
2220 		RUN_UNLOCK(sc);
2221 		ieee80211_iterate_nodes(&ic->ic_sta, run_iter_func, sc);
2222 	}
2223 
2224 	if(sc->ratectl_run != RUN_RATECTL_OFF)
2225 		usb_callout_reset(&sc->ratectl_ch, hz, run_ratectl_to, sc);
2226 }
2227 
2228 static void
2229 run_drain_fifo(void *arg)
2230 {
2231 	struct run_softc *sc = arg;
2232 	struct ifnet *ifp = sc->sc_ifp;
2233 	uint32_t stat;
2234 	uint16_t (*wstat)[3];
2235 	uint8_t wcid, mcs, pid;
2236 	int8_t retry;
2237 
2238 	RUN_LOCK_ASSERT(sc, MA_OWNED);
2239 
2240 	for (;;) {
2241 		/* drain Tx status FIFO (maxsize = 16) */
2242 		run_read(sc, RT2860_TX_STAT_FIFO, &stat);
2243 		DPRINTFN(4, "tx stat 0x%08x\n", stat);
2244 		if (!(stat & RT2860_TXQ_VLD))
2245 			break;
2246 
2247 		wcid = (stat >> RT2860_TXQ_WCID_SHIFT) & 0xff;
2248 
2249 		/* if no ACK was requested, no feedback is available */
2250 		if (!(stat & RT2860_TXQ_ACKREQ) || wcid > RT2870_WCID_MAX ||
2251 		    wcid == 0)
2252 			continue;
2253 
2254 		/*
2255 		 * Even though each stat is Tx-complete-status like format,
2256 		 * the device can poll stats. Because there is no guarantee
2257 		 * that the referring node is still around when read the stats.
2258 		 * So that, if we use ieee80211_ratectl_tx_update(), we will
2259 		 * have hard time not to refer already freed node.
2260 		 *
2261 		 * To eliminate such page faults, we poll stats in softc.
2262 		 * Then, update the rates later with ieee80211_ratectl_tx_update().
2263 		 */
2264 		wstat = &(sc->wcid_stats[wcid]);
2265 		(*wstat)[RUN_TXCNT]++;
2266 		if (stat & RT2860_TXQ_OK)
2267 			(*wstat)[RUN_SUCCESS]++;
2268 		else
2269 			ifp->if_oerrors++;
2270 		/*
2271 		 * Check if there were retries, ie if the Tx success rate is
2272 		 * different from the requested rate. Note that it works only
2273 		 * because we do not allow rate fallback from OFDM to CCK.
2274 		 */
2275 		mcs = (stat >> RT2860_TXQ_MCS_SHIFT) & 0x7f;
2276 		pid = (stat >> RT2860_TXQ_PID_SHIFT) & 0xf;
2277 		if ((retry = pid -1 - mcs) > 0) {
2278 			(*wstat)[RUN_TXCNT] += retry;
2279 			(*wstat)[RUN_RETRY] += retry;
2280 		}
2281 	}
2282 	DPRINTFN(3, "count=%d\n", sc->fifo_cnt);
2283 
2284 	sc->fifo_cnt = 0;
2285 }
2286 
2287 static void
2288 run_iter_func(void *arg, struct ieee80211_node *ni)
2289 {
2290 	struct run_softc *sc = arg;
2291 	struct ieee80211vap *vap = ni->ni_vap;
2292 	struct ieee80211com *ic = ni->ni_ic;
2293 	struct ifnet *ifp = ic->ic_ifp;
2294 	struct run_node *rn = (void *)ni;
2295 	union run_stats sta[2];
2296 	uint16_t (*wstat)[3];
2297 	int txcnt, success, retrycnt, error;
2298 
2299 	RUN_LOCK(sc);
2300 
2301 	if (sc->rvp_cnt <= 1 && (vap->iv_opmode == IEEE80211_M_IBSS ||
2302 	    vap->iv_opmode == IEEE80211_M_STA)) {
2303 		/* read statistic counters (clear on read) and update AMRR state */
2304 		error = run_read_region_1(sc, RT2860_TX_STA_CNT0, (uint8_t *)sta,
2305 		    sizeof sta);
2306 		if (error != 0)
2307 			goto fail;
2308 
2309 		/* count failed TX as errors */
2310 		ifp->if_oerrors += le16toh(sta[0].error.fail);
2311 
2312 		retrycnt = le16toh(sta[1].tx.retry);
2313 		success = le16toh(sta[1].tx.success);
2314 		txcnt = retrycnt + success + le16toh(sta[0].error.fail);
2315 
2316 		DPRINTFN(3, "retrycnt=%d success=%d failcnt=%d\n",
2317 			retrycnt, success, le16toh(sta[0].error.fail));
2318 	} else {
2319 		wstat = &(sc->wcid_stats[RUN_AID2WCID(ni->ni_associd)]);
2320 
2321 		if (wstat == &(sc->wcid_stats[0]) ||
2322 		    wstat > &(sc->wcid_stats[RT2870_WCID_MAX]))
2323 			goto fail;
2324 
2325 		txcnt = (*wstat)[RUN_TXCNT];
2326 		success = (*wstat)[RUN_SUCCESS];
2327 		retrycnt = (*wstat)[RUN_RETRY];
2328 		DPRINTFN(3, "retrycnt=%d txcnt=%d success=%d\n",
2329 		    retrycnt, txcnt, success);
2330 
2331 		memset(wstat, 0, sizeof(*wstat));
2332 	}
2333 
2334 	ieee80211_ratectl_tx_update(vap, ni, &txcnt, &success, &retrycnt);
2335 	rn->amrr_ridx = ieee80211_ratectl_rate(ni, NULL, 0);
2336 
2337 fail:
2338 	RUN_UNLOCK(sc);
2339 
2340 	DPRINTFN(3, "ridx=%d\n", rn->amrr_ridx);
2341 }
2342 
2343 static void
2344 run_newassoc_cb(void *arg)
2345 {
2346 	struct run_cmdq *cmdq = arg;
2347 	struct ieee80211_node *ni = cmdq->arg1;
2348 	struct run_softc *sc = ni->ni_vap->iv_ic->ic_ifp->if_softc;
2349 	uint8_t wcid = cmdq->wcid;
2350 
2351 	RUN_LOCK_ASSERT(sc, MA_OWNED);
2352 
2353 	run_write_region_1(sc, RT2860_WCID_ENTRY(wcid),
2354 	    ni->ni_macaddr, IEEE80211_ADDR_LEN);
2355 
2356 	memset(&(sc->wcid_stats[wcid]), 0, sizeof(sc->wcid_stats[wcid]));
2357 }
2358 
2359 static void
2360 run_newassoc(struct ieee80211_node *ni, int isnew)
2361 {
2362 	struct run_node *rn = (void *)ni;
2363 	struct ieee80211_rateset *rs = &ni->ni_rates;
2364 	struct ieee80211vap *vap = ni->ni_vap;
2365 	struct ieee80211com *ic = vap->iv_ic;
2366 	struct run_softc *sc = ic->ic_ifp->if_softc;
2367 	uint8_t rate;
2368 	uint8_t ridx;
2369 	uint8_t wcid = RUN_AID2WCID(ni->ni_associd);
2370 	int i, j;
2371 
2372 	if (wcid > RT2870_WCID_MAX) {
2373 		device_printf(sc->sc_dev, "wcid=%d out of range\n", wcid);
2374 		return;
2375 	}
2376 
2377 	/* only interested in true associations */
2378 	if (isnew && ni->ni_associd != 0) {
2379 
2380 		/*
2381 		 * This function could is called though timeout function.
2382 		 * Need to defer.
2383 		 */
2384 		uint32_t cnt = RUN_CMDQ_GET(&sc->cmdq_store);
2385 		DPRINTF("cmdq_store=%d\n", cnt);
2386 		sc->cmdq[cnt].func = run_newassoc_cb;
2387 		sc->cmdq[cnt].arg0 = NULL;
2388 		sc->cmdq[cnt].arg1 = ni;
2389 		sc->cmdq[cnt].wcid = wcid;
2390 		ieee80211_runtask(ic, &sc->cmdq_task);
2391 	}
2392 
2393 	DPRINTF("new assoc isnew=%d associd=%x addr=%s\n",
2394 	    isnew, ni->ni_associd, ether_sprintf(ni->ni_macaddr));
2395 
2396 	for (i = 0; i < rs->rs_nrates; i++) {
2397 		rate = rs->rs_rates[i] & IEEE80211_RATE_VAL;
2398 		/* convert 802.11 rate to hardware rate index */
2399 		for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
2400 			if (rt2860_rates[ridx].rate == rate)
2401 				break;
2402 		rn->ridx[i] = ridx;
2403 		/* determine rate of control response frames */
2404 		for (j = i; j >= 0; j--) {
2405 			if ((rs->rs_rates[j] & IEEE80211_RATE_BASIC) &&
2406 			    rt2860_rates[rn->ridx[i]].phy ==
2407 			    rt2860_rates[rn->ridx[j]].phy)
2408 				break;
2409 		}
2410 		if (j >= 0) {
2411 			rn->ctl_ridx[i] = rn->ridx[j];
2412 		} else {
2413 			/* no basic rate found, use mandatory one */
2414 			rn->ctl_ridx[i] = rt2860_rates[ridx].ctl_ridx;
2415 		}
2416 		DPRINTF("rate=0x%02x ridx=%d ctl_ridx=%d\n",
2417 		    rs->rs_rates[i], rn->ridx[i], rn->ctl_ridx[i]);
2418 	}
2419 	rate = vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)].mgmtrate;
2420 	for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
2421 		if (rt2860_rates[ridx].rate == rate)
2422 			break;
2423 	rn->mgt_ridx = ridx;
2424 	DPRINTF("rate=%d, mgmt_ridx=%d\n", rate, rn->mgt_ridx);
2425 
2426 	usb_callout_reset(&sc->ratectl_ch, hz, run_ratectl_to, sc);
2427 }
2428 
2429 /*
2430  * Return the Rx chain with the highest RSSI for a given frame.
2431  */
2432 static __inline uint8_t
2433 run_maxrssi_chain(struct run_softc *sc, const struct rt2860_rxwi *rxwi)
2434 {
2435 	uint8_t rxchain = 0;
2436 
2437 	if (sc->nrxchains > 1) {
2438 		if (rxwi->rssi[1] > rxwi->rssi[rxchain])
2439 			rxchain = 1;
2440 		if (sc->nrxchains > 2)
2441 			if (rxwi->rssi[2] > rxwi->rssi[rxchain])
2442 				rxchain = 2;
2443 	}
2444 	return (rxchain);
2445 }
2446 
2447 static void
2448 run_rx_frame(struct run_softc *sc, struct mbuf *m, uint32_t dmalen)
2449 {
2450 	struct ifnet *ifp = sc->sc_ifp;
2451 	struct ieee80211com *ic = ifp->if_l2com;
2452 	struct ieee80211_frame *wh;
2453 	struct ieee80211_node *ni;
2454 	struct rt2870_rxd *rxd;
2455 	struct rt2860_rxwi *rxwi;
2456 	uint32_t flags;
2457 	uint16_t len, phy;
2458 	uint8_t ant, rssi;
2459 	int8_t nf;
2460 
2461 	rxwi = mtod(m, struct rt2860_rxwi *);
2462 	len = le16toh(rxwi->len) & 0xfff;
2463 	if (__predict_false(len > dmalen)) {
2464 		m_freem(m);
2465 		ifp->if_ierrors++;
2466 		DPRINTF("bad RXWI length %u > %u\n", len, dmalen);
2467 		return;
2468 	}
2469 	/* Rx descriptor is located at the end */
2470 	rxd = (struct rt2870_rxd *)(mtod(m, caddr_t) + dmalen);
2471 	flags = le32toh(rxd->flags);
2472 
2473 	if (__predict_false(flags & (RT2860_RX_CRCERR | RT2860_RX_ICVERR))) {
2474 		m_freem(m);
2475 		ifp->if_ierrors++;
2476 		DPRINTF("%s error.\n", (flags & RT2860_RX_CRCERR)?"CRC":"ICV");
2477 		return;
2478 	}
2479 
2480 	m->m_data += sizeof(struct rt2860_rxwi);
2481 	m->m_pkthdr.len = m->m_len -= sizeof(struct rt2860_rxwi);
2482 
2483 	wh = mtod(m, struct ieee80211_frame *);
2484 
2485 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
2486 		wh->i_fc[1] &= ~IEEE80211_FC1_WEP;
2487 		m->m_flags |= M_WEP;
2488 	}
2489 
2490 	if (flags & RT2860_RX_L2PAD) {
2491 		DPRINTFN(8, "received RT2860_RX_L2PAD frame\n");
2492 		len += 2;
2493 	}
2494 
2495 	ni = ieee80211_find_rxnode(ic,
2496 	    mtod(m, struct ieee80211_frame_min *));
2497 
2498 	if (__predict_false(flags & RT2860_RX_MICERR)) {
2499 		/* report MIC failures to net80211 for TKIP */
2500 		if (ni != NULL)
2501 			ieee80211_notify_michael_failure(ni->ni_vap, wh, rxwi->keyidx);
2502 		m_freem(m);
2503 		ifp->if_ierrors++;
2504 		DPRINTF("MIC error. Someone is lying.\n");
2505 		return;
2506 	}
2507 
2508 	ant = run_maxrssi_chain(sc, rxwi);
2509 	rssi = rxwi->rssi[ant];
2510 	nf = run_rssi2dbm(sc, rssi, ant);
2511 
2512 	m->m_pkthdr.rcvif = ifp;
2513 	m->m_pkthdr.len = m->m_len = len;
2514 
2515 	if (ni != NULL) {
2516 		(void)ieee80211_input(ni, m, rssi, nf);
2517 		ieee80211_free_node(ni);
2518 	} else {
2519 		(void)ieee80211_input_all(ic, m, rssi, nf);
2520 	}
2521 
2522 	if (__predict_false(ieee80211_radiotap_active(ic))) {
2523 		struct run_rx_radiotap_header *tap = &sc->sc_rxtap;
2524 
2525 		tap->wr_flags = 0;
2526 		tap->wr_chan_freq = htole16(ic->ic_bsschan->ic_freq);
2527 		tap->wr_chan_flags = htole16(ic->ic_bsschan->ic_flags);
2528 		tap->wr_antsignal = rssi;
2529 		tap->wr_antenna = ant;
2530 		tap->wr_dbm_antsignal = run_rssi2dbm(sc, rssi, ant);
2531 		tap->wr_rate = 2;	/* in case it can't be found below */
2532 		phy = le16toh(rxwi->phy);
2533 		switch (phy & RT2860_PHY_MODE) {
2534 		case RT2860_PHY_CCK:
2535 			switch ((phy & RT2860_PHY_MCS) & ~RT2860_PHY_SHPRE) {
2536 			case 0:	tap->wr_rate =   2; break;
2537 			case 1:	tap->wr_rate =   4; break;
2538 			case 2:	tap->wr_rate =  11; break;
2539 			case 3:	tap->wr_rate =  22; break;
2540 			}
2541 			if (phy & RT2860_PHY_SHPRE)
2542 				tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
2543 			break;
2544 		case RT2860_PHY_OFDM:
2545 			switch (phy & RT2860_PHY_MCS) {
2546 			case 0:	tap->wr_rate =  12; break;
2547 			case 1:	tap->wr_rate =  18; break;
2548 			case 2:	tap->wr_rate =  24; break;
2549 			case 3:	tap->wr_rate =  36; break;
2550 			case 4:	tap->wr_rate =  48; break;
2551 			case 5:	tap->wr_rate =  72; break;
2552 			case 6:	tap->wr_rate =  96; break;
2553 			case 7:	tap->wr_rate = 108; break;
2554 			}
2555 			break;
2556 		}
2557 	}
2558 }
2559 
2560 static void
2561 run_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
2562 {
2563 	struct run_softc *sc = usbd_xfer_softc(xfer);
2564 	struct ifnet *ifp = sc->sc_ifp;
2565 	struct mbuf *m = NULL;
2566 	struct mbuf *m0;
2567 	uint32_t dmalen;
2568 	int xferlen;
2569 
2570 	usbd_xfer_status(xfer, &xferlen, NULL, NULL, NULL);
2571 
2572 	switch (USB_GET_STATE(xfer)) {
2573 	case USB_ST_TRANSFERRED:
2574 
2575 		DPRINTFN(15, "rx done, actlen=%d\n", xferlen);
2576 
2577 		if (xferlen < (int)(sizeof(uint32_t) +
2578 		    sizeof(struct rt2860_rxwi) + sizeof(struct rt2870_rxd))) {
2579 			DPRINTF("xfer too short %d\n", xferlen);
2580 			goto tr_setup;
2581 		}
2582 
2583 		m = sc->rx_m;
2584 		sc->rx_m = NULL;
2585 
2586 		/* FALLTHROUGH */
2587 	case USB_ST_SETUP:
2588 tr_setup:
2589 		if (sc->rx_m == NULL) {
2590 			sc->rx_m = m_getjcl(M_DONTWAIT, MT_DATA, M_PKTHDR,
2591 			    MJUMPAGESIZE /* xfer can be bigger than MCLBYTES */);
2592 		}
2593 		if (sc->rx_m == NULL) {
2594 			DPRINTF("could not allocate mbuf - idle with stall\n");
2595 			ifp->if_ierrors++;
2596 			usbd_xfer_set_stall(xfer);
2597 			usbd_xfer_set_frames(xfer, 0);
2598 		} else {
2599 			/*
2600 			 * Directly loading a mbuf cluster into DMA to
2601 			 * save some data copying. This works because
2602 			 * there is only one cluster.
2603 			 */
2604 			usbd_xfer_set_frame_data(xfer, 0,
2605 			    mtod(sc->rx_m, caddr_t), RUN_MAX_RXSZ);
2606 			usbd_xfer_set_frames(xfer, 1);
2607 		}
2608 		usbd_transfer_submit(xfer);
2609 		break;
2610 
2611 	default:	/* Error */
2612 		if (error != USB_ERR_CANCELLED) {
2613 			/* try to clear stall first */
2614 			usbd_xfer_set_stall(xfer);
2615 
2616 			if (error == USB_ERR_TIMEOUT)
2617 				device_printf(sc->sc_dev, "device timeout\n");
2618 
2619 			ifp->if_ierrors++;
2620 
2621 			goto tr_setup;
2622 		}
2623 		if (sc->rx_m != NULL) {
2624 			m_freem(sc->rx_m);
2625 			sc->rx_m = NULL;
2626 		}
2627 		break;
2628 	}
2629 
2630 	if (m == NULL)
2631 		return;
2632 
2633 	/* inputting all the frames must be last */
2634 
2635 	RUN_UNLOCK(sc);
2636 
2637 	m->m_pkthdr.len = m->m_len = xferlen;
2638 
2639 	/* HW can aggregate multiple 802.11 frames in a single USB xfer */
2640 	for(;;) {
2641 		dmalen = le32toh(*mtod(m, uint32_t *)) & 0xffff;
2642 
2643 		if ((dmalen >= (uint32_t)-8) || (dmalen == 0) ||
2644 		    ((dmalen & 3) != 0)) {
2645 			DPRINTF("bad DMA length %u\n", dmalen);
2646 			break;
2647 		}
2648 		if ((dmalen + 8) > (uint32_t)xferlen) {
2649 			DPRINTF("bad DMA length %u > %d\n",
2650 			dmalen + 8, xferlen);
2651 			break;
2652 		}
2653 
2654 		/* If it is the last one or a single frame, we won't copy. */
2655 		if ((xferlen -= dmalen + 8) <= 8) {
2656 			/* trim 32-bit DMA-len header */
2657 			m->m_data += 4;
2658 			m->m_pkthdr.len = m->m_len -= 4;
2659 			run_rx_frame(sc, m, dmalen);
2660 			break;
2661 		}
2662 
2663 		/* copy aggregated frames to another mbuf */
2664 		m0 = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
2665 		if (__predict_false(m0 == NULL)) {
2666 			DPRINTF("could not allocate mbuf\n");
2667 			ifp->if_ierrors++;
2668 			break;
2669 		}
2670 		m_copydata(m, 4 /* skip 32-bit DMA-len header */,
2671 		    dmalen + sizeof(struct rt2870_rxd), mtod(m0, caddr_t));
2672 		m0->m_pkthdr.len = m0->m_len =
2673 		    dmalen + sizeof(struct rt2870_rxd);
2674 		run_rx_frame(sc, m0, dmalen);
2675 
2676 		/* update data ptr */
2677 		m->m_data += dmalen + 8;
2678 		m->m_pkthdr.len = m->m_len -= dmalen + 8;
2679 	}
2680 
2681 	RUN_LOCK(sc);
2682 }
2683 
2684 static void
2685 run_tx_free(struct run_endpoint_queue *pq,
2686     struct run_tx_data *data, int txerr)
2687 {
2688 	if (data->m != NULL) {
2689 		if (data->m->m_flags & M_TXCB)
2690 			ieee80211_process_callback(data->ni, data->m,
2691 			    txerr ? ETIMEDOUT : 0);
2692 		m_freem(data->m);
2693 		data->m = NULL;
2694 
2695 		if (data->ni == NULL) {
2696 			DPRINTF("no node\n");
2697 		} else {
2698 			ieee80211_free_node(data->ni);
2699 			data->ni = NULL;
2700 		}
2701 	}
2702 
2703 	STAILQ_INSERT_TAIL(&pq->tx_fh, data, next);
2704 	pq->tx_nfree++;
2705 }
2706 
2707 static void
2708 run_bulk_tx_callbackN(struct usb_xfer *xfer, usb_error_t error, unsigned int index)
2709 {
2710 	struct run_softc *sc = usbd_xfer_softc(xfer);
2711 	struct ifnet *ifp = sc->sc_ifp;
2712 	struct ieee80211com *ic = ifp->if_l2com;
2713 	struct run_tx_data *data;
2714 	struct ieee80211vap *vap = NULL;
2715 	struct usb_page_cache *pc;
2716 	struct run_endpoint_queue *pq = &sc->sc_epq[index];
2717 	struct mbuf *m;
2718 	usb_frlength_t size;
2719 	int actlen;
2720 	int sumlen;
2721 
2722 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
2723 
2724 	switch (USB_GET_STATE(xfer)) {
2725 	case USB_ST_TRANSFERRED:
2726 		DPRINTFN(11, "transfer complete: %d "
2727 		    "bytes @ index %d\n", actlen, index);
2728 
2729 		data = usbd_xfer_get_priv(xfer);
2730 
2731 		run_tx_free(pq, data, 0);
2732 		ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2733 
2734 		usbd_xfer_set_priv(xfer, NULL);
2735 
2736 		ifp->if_opackets++;
2737 
2738 		/* FALLTHROUGH */
2739 	case USB_ST_SETUP:
2740 tr_setup:
2741 		data = STAILQ_FIRST(&pq->tx_qh);
2742 		if (data == NULL)
2743 			break;
2744 
2745 		STAILQ_REMOVE_HEAD(&pq->tx_qh, next);
2746 
2747 		m = data->m;
2748 		if ((m->m_pkthdr.len +
2749 		    sizeof(data->desc) + 3 + 8) > RUN_MAX_TXSZ) {
2750 			DPRINTF("data overflow, %u bytes\n",
2751 			    m->m_pkthdr.len);
2752 
2753 			ifp->if_oerrors++;
2754 
2755 			run_tx_free(pq, data, 1);
2756 
2757 			goto tr_setup;
2758 		}
2759 
2760 		pc = usbd_xfer_get_frame(xfer, 0);
2761 		size = sizeof(data->desc);
2762 		usbd_copy_in(pc, 0, &data->desc, size);
2763 		usbd_m_copy_in(pc, size, m, 0, m->m_pkthdr.len);
2764 		size += m->m_pkthdr.len;
2765 		/*
2766 		 * Align end on a 4-byte boundary, pad 8 bytes (CRC +
2767 		 * 4-byte padding), and be sure to zero those trailing
2768 		 * bytes:
2769 		 */
2770 		usbd_frame_zero(pc, size, ((-size) & 3) + 8);
2771 		size += ((-size) & 3) + 8;
2772 
2773 		vap = data->ni->ni_vap;
2774 		if (ieee80211_radiotap_active_vap(vap)) {
2775 			struct run_tx_radiotap_header *tap = &sc->sc_txtap;
2776 			struct rt2860_txwi *txwi =
2777 			    (struct rt2860_txwi *)(&data->desc + sizeof(struct rt2870_txd));
2778 
2779 			tap->wt_flags = 0;
2780 			tap->wt_rate = rt2860_rates[data->ridx].rate;
2781 			tap->wt_chan_freq = htole16(vap->iv_bss->ni_chan->ic_freq);
2782 			tap->wt_chan_flags = htole16(vap->iv_bss->ni_chan->ic_flags);
2783 			tap->wt_hwqueue = index;
2784 			if (le16toh(txwi->phy) & RT2860_PHY_SHPRE)
2785 				tap->wt_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
2786 
2787 			ieee80211_radiotap_tx(vap, m);
2788 		}
2789 
2790 		DPRINTFN(11, "sending frame len=%u/%u  @ index %d\n",
2791 		    m->m_pkthdr.len, size, index);
2792 
2793 		usbd_xfer_set_frame_len(xfer, 0, size);
2794 		usbd_xfer_set_priv(xfer, data);
2795 
2796 		usbd_transfer_submit(xfer);
2797 
2798 		RUN_UNLOCK(sc);
2799 		run_start(ifp);
2800 		RUN_LOCK(sc);
2801 
2802 		break;
2803 
2804 	default:
2805 		DPRINTF("USB transfer error, %s\n",
2806 		    usbd_errstr(error));
2807 
2808 		data = usbd_xfer_get_priv(xfer);
2809 
2810 		ifp->if_oerrors++;
2811 
2812 		if (data != NULL) {
2813 			if(data->ni != NULL)
2814 				vap = data->ni->ni_vap;
2815 			run_tx_free(pq, data, error);
2816 			usbd_xfer_set_priv(xfer, NULL);
2817 		}
2818 		if (vap == NULL)
2819 			vap = TAILQ_FIRST(&ic->ic_vaps);
2820 
2821 		if (error != USB_ERR_CANCELLED) {
2822 			if (error == USB_ERR_TIMEOUT) {
2823 				device_printf(sc->sc_dev, "device timeout\n");
2824 				uint32_t i = RUN_CMDQ_GET(&sc->cmdq_store);
2825 				DPRINTF("cmdq_store=%d\n", i);
2826 				sc->cmdq[i].func = run_usb_timeout_cb;
2827 				sc->cmdq[i].arg0 = vap;
2828 				ieee80211_runtask(ic, &sc->cmdq_task);
2829 			}
2830 
2831 			/*
2832 			 * Try to clear stall first, also if other
2833 			 * errors occur, hence clearing stall
2834 			 * introduces a 50 ms delay:
2835 			 */
2836 			usbd_xfer_set_stall(xfer);
2837 			goto tr_setup;
2838 		}
2839 		break;
2840 	}
2841 }
2842 
2843 static void
2844 run_bulk_tx_callback0(struct usb_xfer *xfer, usb_error_t error)
2845 {
2846 	run_bulk_tx_callbackN(xfer, error, 0);
2847 }
2848 
2849 static void
2850 run_bulk_tx_callback1(struct usb_xfer *xfer, usb_error_t error)
2851 {
2852 	run_bulk_tx_callbackN(xfer, error, 1);
2853 }
2854 
2855 static void
2856 run_bulk_tx_callback2(struct usb_xfer *xfer, usb_error_t error)
2857 {
2858 	run_bulk_tx_callbackN(xfer, error, 2);
2859 }
2860 
2861 static void
2862 run_bulk_tx_callback3(struct usb_xfer *xfer, usb_error_t error)
2863 {
2864 	run_bulk_tx_callbackN(xfer, error, 3);
2865 }
2866 
2867 static void
2868 run_bulk_tx_callback4(struct usb_xfer *xfer, usb_error_t error)
2869 {
2870 	run_bulk_tx_callbackN(xfer, error, 4);
2871 }
2872 
2873 static void
2874 run_bulk_tx_callback5(struct usb_xfer *xfer, usb_error_t error)
2875 {
2876 	run_bulk_tx_callbackN(xfer, error, 5);
2877 }
2878 
2879 static void
2880 run_set_tx_desc(struct run_softc *sc, struct run_tx_data *data)
2881 {
2882 	struct mbuf *m = data->m;
2883 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2884 	struct ieee80211vap *vap = data->ni->ni_vap;
2885 	struct ieee80211_frame *wh;
2886 	struct rt2870_txd *txd;
2887 	struct rt2860_txwi *txwi;
2888 	uint16_t xferlen;
2889 	uint16_t mcs;
2890 	uint8_t ridx = data->ridx;
2891 	uint8_t pad;
2892 
2893 	/* get MCS code from rate index */
2894 	mcs = rt2860_rates[ridx].mcs;
2895 
2896 	xferlen = sizeof(*txwi) + m->m_pkthdr.len;
2897 
2898 	/* roundup to 32-bit alignment */
2899 	xferlen = (xferlen + 3) & ~3;
2900 
2901 	txd = (struct rt2870_txd *)&data->desc;
2902 	txd->len = htole16(xferlen);
2903 
2904 	wh = mtod(m, struct ieee80211_frame *);
2905 
2906 	/*
2907 	 * Ether both are true or both are false, the header
2908 	 * are nicely aligned to 32-bit. So, no L2 padding.
2909 	 */
2910 	if(IEEE80211_HAS_ADDR4(wh) == IEEE80211_QOS_HAS_SEQ(wh))
2911 		pad = 0;
2912 	else
2913 		pad = 2;
2914 
2915 	/* setup TX Wireless Information */
2916 	txwi = (struct rt2860_txwi *)(txd + 1);
2917 	txwi->len = htole16(m->m_pkthdr.len - pad);
2918 	if (rt2860_rates[ridx].phy == IEEE80211_T_DS) {
2919 		txwi->phy = htole16(RT2860_PHY_CCK);
2920 		if (ridx != RT2860_RIDX_CCK1 &&
2921 		    (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
2922 			mcs |= RT2860_PHY_SHPRE;
2923 	} else
2924 		txwi->phy = htole16(RT2860_PHY_OFDM);
2925 	txwi->phy |= htole16(mcs);
2926 
2927 	/* check if RTS/CTS or CTS-to-self protection is required */
2928 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
2929 	    (m->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold ||
2930 	     ((ic->ic_flags & IEEE80211_F_USEPROT) &&
2931 	      rt2860_rates[ridx].phy == IEEE80211_T_OFDM)))
2932 		txwi->txop |= RT2860_TX_TXOP_HT;
2933 	else
2934 		txwi->txop |= RT2860_TX_TXOP_BACKOFF;
2935 
2936 	if (vap->iv_opmode != IEEE80211_M_STA && !IEEE80211_QOS_HAS_SEQ(wh))
2937 		txwi->xflags |= RT2860_TX_NSEQ;
2938 }
2939 
2940 /* This function must be called locked */
2941 static int
2942 run_tx(struct run_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
2943 {
2944 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2945 	struct ieee80211vap *vap = ni->ni_vap;
2946 	struct ieee80211_frame *wh;
2947 	struct ieee80211_channel *chan;
2948 	const struct ieee80211_txparam *tp;
2949 	struct run_node *rn = (void *)ni;
2950 	struct run_tx_data *data;
2951 	struct rt2870_txd *txd;
2952 	struct rt2860_txwi *txwi;
2953 	uint16_t qos;
2954 	uint16_t dur;
2955 	uint16_t qid;
2956 	uint8_t type;
2957 	uint8_t tid;
2958 	uint8_t ridx;
2959 	uint8_t ctl_ridx;
2960 	uint8_t qflags;
2961 	uint8_t xflags = 0;
2962 	int hasqos;
2963 
2964 	RUN_LOCK_ASSERT(sc, MA_OWNED);
2965 
2966 	wh = mtod(m, struct ieee80211_frame *);
2967 
2968 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
2969 
2970 	/*
2971 	 * There are 7 bulk endpoints: 1 for RX
2972 	 * and 6 for TX (4 EDCAs + HCCA + Prio).
2973 	 * Update 03-14-2009:  some devices like the Planex GW-US300MiniS
2974 	 * seem to have only 4 TX bulk endpoints (Fukaumi Naoki).
2975 	 */
2976 	if ((hasqos = IEEE80211_QOS_HAS_SEQ(wh))) {
2977 		uint8_t *frm;
2978 
2979 		if(IEEE80211_HAS_ADDR4(wh))
2980 			frm = ((struct ieee80211_qosframe_addr4 *)wh)->i_qos;
2981 		else
2982 			frm =((struct ieee80211_qosframe *)wh)->i_qos;
2983 
2984 		qos = le16toh(*(const uint16_t *)frm);
2985 		tid = qos & IEEE80211_QOS_TID;
2986 		qid = TID_TO_WME_AC(tid);
2987 	} else {
2988 		qos = 0;
2989 		tid = 0;
2990 		qid = WME_AC_BE;
2991 	}
2992 	qflags = (qid < 4) ? RT2860_TX_QSEL_EDCA : RT2860_TX_QSEL_HCCA;
2993 
2994 	DPRINTFN(8, "qos %d\tqid %d\ttid %d\tqflags %x\n",
2995 	    qos, qid, tid, qflags);
2996 
2997 	chan = (ni->ni_chan != IEEE80211_CHAN_ANYC)?ni->ni_chan:ic->ic_curchan;
2998 	tp = &vap->iv_txparms[ieee80211_chan2mode(chan)];
2999 
3000 	/* pickup a rate index */
3001 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
3002 	    type != IEEE80211_FC0_TYPE_DATA) {
3003 		ridx = (ic->ic_curmode == IEEE80211_MODE_11A) ?
3004 		    RT2860_RIDX_OFDM6 : RT2860_RIDX_CCK1;
3005 		ctl_ridx = rt2860_rates[ridx].ctl_ridx;
3006 	} else {
3007 		if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
3008 			ridx = rn->fix_ridx;
3009 		else
3010 			ridx = rn->amrr_ridx;
3011 		ctl_ridx = rt2860_rates[ridx].ctl_ridx;
3012 	}
3013 
3014 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
3015 	    (!hasqos || (qos & IEEE80211_QOS_ACKPOLICY) !=
3016 	     IEEE80211_QOS_ACKPOLICY_NOACK)) {
3017 		xflags |= RT2860_TX_ACK;
3018 		if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
3019 			dur = rt2860_rates[ctl_ridx].sp_ack_dur;
3020 		else
3021 			dur = rt2860_rates[ctl_ridx].lp_ack_dur;
3022 		*(uint16_t *)wh->i_dur = htole16(dur);
3023 	}
3024 
3025 	/* reserve slots for mgmt packets, just in case */
3026 	if (sc->sc_epq[qid].tx_nfree < 3) {
3027 		DPRINTFN(10, "tx ring %d is full\n", qid);
3028 		return (-1);
3029 	}
3030 
3031 	data = STAILQ_FIRST(&sc->sc_epq[qid].tx_fh);
3032 	STAILQ_REMOVE_HEAD(&sc->sc_epq[qid].tx_fh, next);
3033 	sc->sc_epq[qid].tx_nfree--;
3034 
3035 	txd = (struct rt2870_txd *)&data->desc;
3036 	txd->flags = qflags;
3037 	txwi = (struct rt2860_txwi *)(txd + 1);
3038 	txwi->xflags = xflags;
3039 	txwi->wcid = IEEE80211_IS_MULTICAST(wh->i_addr1) ?
3040 	    0 : RUN_AID2WCID(ni->ni_associd);
3041 	/* clear leftover garbage bits */
3042 	txwi->flags = 0;
3043 	txwi->txop = 0;
3044 
3045 	data->m = m;
3046 	data->ni = ni;
3047 	data->ridx = ridx;
3048 
3049 	run_set_tx_desc(sc, data);
3050 
3051 	/*
3052 	 * The chip keeps track of 2 kind of Tx stats,
3053 	 *  * TX_STAT_FIFO, for per WCID stats, and
3054 	 *  * TX_STA_CNT0 for all-TX-in-one stats.
3055 	 *
3056 	 * To use FIFO stats, we need to store MCS into the driver-private
3057  	 * PacketID field. So that, we can tell whose stats when we read them.
3058  	 * We add 1 to the MCS because setting the PacketID field to 0 means
3059  	 * that we don't want feedback in TX_STAT_FIFO.
3060  	 * And, that's what we want for STA mode, since TX_STA_CNT0 does the job.
3061  	 *
3062  	 * FIFO stats doesn't count Tx with WCID 0xff, so we do this in run_tx().
3063  	 */
3064 	if (sc->rvp_cnt > 1 || vap->iv_opmode == IEEE80211_M_HOSTAP ||
3065 	    vap->iv_opmode == IEEE80211_M_MBSS) {
3066 		uint16_t pid = (rt2860_rates[ridx].mcs + 1) & 0xf;
3067 		txwi->len |= htole16(pid << RT2860_TX_PID_SHIFT);
3068 
3069 		/*
3070 		 * Unlike PCI based devices, we don't get any interrupt from
3071 		 * USB devices, so we simulate FIFO-is-full interrupt here.
3072 		 * Ralink recomends to drain FIFO stats every 100 ms, but 16 slots
3073 		 * quickly get fulled. To prevent overflow, increment a counter on
3074 		 * every FIFO stat request, so we know how many slots are left.
3075 		 * We do this only in HOSTAP or multiple vap mode since FIFO stats
3076 		 * are used only in those modes.
3077 		 * We just drain stats. AMRR gets updated every 1 sec by
3078 		 * run_ratectl_cb() via callout.
3079 		 * Call it early. Otherwise overflow.
3080 		 */
3081 		if (sc->fifo_cnt++ == 10) {
3082 			/*
3083 			 * With multiple vaps or if_bridge, if_start() is called
3084 			 * with a non-sleepable lock, tcpinp. So, need to defer.
3085 			 */
3086 			uint32_t i = RUN_CMDQ_GET(&sc->cmdq_store);
3087 			DPRINTFN(6, "cmdq_store=%d\n", i);
3088 			sc->cmdq[i].func = run_drain_fifo;
3089 			sc->cmdq[i].arg0 = sc;
3090 			ieee80211_runtask(ic, &sc->cmdq_task);
3091 		}
3092 	}
3093 
3094         STAILQ_INSERT_TAIL(&sc->sc_epq[qid].tx_qh, data, next);
3095 
3096 	usbd_transfer_start(sc->sc_xfer[qid]);
3097 
3098 	DPRINTFN(8, "sending data frame len=%d rate=%d qid=%d\n", m->m_pkthdr.len +
3099 	    (int)(sizeof (struct rt2870_txd) + sizeof (struct rt2860_rxwi)),
3100 	    rt2860_rates[ridx].rate, qid);
3101 
3102 	return (0);
3103 }
3104 
3105 static int
3106 run_tx_mgt(struct run_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
3107 {
3108 	struct ifnet *ifp = sc->sc_ifp;
3109 	struct ieee80211com *ic = ifp->if_l2com;
3110 	struct run_node *rn = (void *)ni;
3111 	struct run_tx_data *data;
3112 	struct ieee80211_frame *wh;
3113 	struct rt2870_txd *txd;
3114 	struct rt2860_txwi *txwi;
3115 	uint16_t dur;
3116 	uint8_t ridx = rn->mgt_ridx;
3117 	uint8_t type;
3118 	uint8_t xflags = 0;
3119 	uint8_t wflags = 0;
3120 
3121 	RUN_LOCK_ASSERT(sc, MA_OWNED);
3122 
3123 	wh = mtod(m, struct ieee80211_frame *);
3124 
3125 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3126 
3127 	/* tell hardware to add timestamp for probe responses */
3128 	if ((wh->i_fc[0] &
3129 	    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
3130 	    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
3131 		wflags |= RT2860_TX_TS;
3132 	else if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
3133 		xflags |= RT2860_TX_ACK;
3134 
3135 		dur = ieee80211_ack_duration(ic->ic_rt, rt2860_rates[ridx].rate,
3136 		    ic->ic_flags & IEEE80211_F_SHPREAMBLE);
3137 		*(uint16_t *)wh->i_dur = htole16(dur);
3138 	}
3139 
3140 	if (sc->sc_epq[0].tx_nfree == 0) {
3141 		/* let caller free mbuf */
3142 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3143 		return (EIO);
3144 	}
3145 	data = STAILQ_FIRST(&sc->sc_epq[0].tx_fh);
3146 	STAILQ_REMOVE_HEAD(&sc->sc_epq[0].tx_fh, next);
3147 	sc->sc_epq[0].tx_nfree--;
3148 
3149 	txd = (struct rt2870_txd *)&data->desc;
3150 	txd->flags = RT2860_TX_QSEL_EDCA;
3151 	txwi = (struct rt2860_txwi *)(txd + 1);
3152 	txwi->wcid = 0xff;
3153 	txwi->flags = wflags;
3154 	txwi->xflags = xflags;
3155 	txwi->txop = 0;	/* clear leftover garbage bits */
3156 
3157 	data->m = m;
3158 	data->ni = ni;
3159 	data->ridx = ridx;
3160 
3161 	run_set_tx_desc(sc, data);
3162 
3163 	DPRINTFN(10, "sending mgt frame len=%d rate=%d\n", m->m_pkthdr.len +
3164 	    (int)(sizeof (struct rt2870_txd) + sizeof (struct rt2860_rxwi)),
3165 	    rt2860_rates[ridx].rate);
3166 
3167 	STAILQ_INSERT_TAIL(&sc->sc_epq[0].tx_qh, data, next);
3168 
3169 	usbd_transfer_start(sc->sc_xfer[0]);
3170 
3171 	return (0);
3172 }
3173 
3174 static int
3175 run_sendprot(struct run_softc *sc,
3176     const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate)
3177 {
3178 	struct ieee80211com *ic = ni->ni_ic;
3179 	struct ieee80211_frame *wh;
3180 	struct run_tx_data *data;
3181 	struct rt2870_txd *txd;
3182 	struct rt2860_txwi *txwi;
3183 	struct mbuf *mprot;
3184 	int ridx;
3185 	int protrate;
3186 	int ackrate;
3187 	int pktlen;
3188 	int isshort;
3189 	uint16_t dur;
3190 	uint8_t type;
3191 	uint8_t wflags = 0;
3192 	uint8_t xflags = 0;
3193 
3194 	RUN_LOCK_ASSERT(sc, MA_OWNED);
3195 
3196 	KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY,
3197 	    ("protection %d", prot));
3198 
3199 	wh = mtod(m, struct ieee80211_frame *);
3200 	pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN;
3201 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3202 
3203 	protrate = ieee80211_ctl_rate(ic->ic_rt, rate);
3204 	ackrate = ieee80211_ack_rate(ic->ic_rt, rate);
3205 
3206 	isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0;
3207 	dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort)
3208 	    + ieee80211_ack_duration(ic->ic_rt, rate, isshort);
3209 	wflags = RT2860_TX_FRAG;
3210 
3211 	/* check that there are free slots before allocating the mbuf */
3212 	if (sc->sc_epq[0].tx_nfree == 0) {
3213 		/* let caller free mbuf */
3214 		sc->sc_ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3215 		return (ENOBUFS);
3216 	}
3217 
3218 	if (prot == IEEE80211_PROT_RTSCTS) {
3219 		/* NB: CTS is the same size as an ACK */
3220 		dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort);
3221 		xflags |= RT2860_TX_ACK;
3222 		mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur);
3223 	} else {
3224 		mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur);
3225 	}
3226 	if (mprot == NULL) {
3227 		sc->sc_ifp->if_oerrors++;
3228 		DPRINTF("could not allocate mbuf\n");
3229 		return (ENOBUFS);
3230 	}
3231 
3232         data = STAILQ_FIRST(&sc->sc_epq[0].tx_fh);
3233         STAILQ_REMOVE_HEAD(&sc->sc_epq[0].tx_fh, next);
3234         sc->sc_epq[0].tx_nfree--;
3235 
3236 	txd = (struct rt2870_txd *)&data->desc;
3237 	txd->flags = RT2860_TX_QSEL_EDCA;
3238 	txwi = (struct rt2860_txwi *)(txd + 1);
3239 	txwi->wcid = 0xff;
3240 	txwi->flags = wflags;
3241 	txwi->xflags = xflags;
3242 	txwi->txop = 0;	/* clear leftover garbage bits */
3243 
3244 	data->m = mprot;
3245 	data->ni = ieee80211_ref_node(ni);
3246 
3247 	for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
3248 		if (rt2860_rates[ridx].rate == protrate)
3249 			break;
3250 	data->ridx = ridx;
3251 
3252 	run_set_tx_desc(sc, data);
3253 
3254         DPRINTFN(1, "sending prot len=%u rate=%u\n",
3255             m->m_pkthdr.len, rate);
3256 
3257         STAILQ_INSERT_TAIL(&sc->sc_epq[0].tx_qh, data, next);
3258 
3259 	usbd_transfer_start(sc->sc_xfer[0]);
3260 
3261 	return (0);
3262 }
3263 
3264 static int
3265 run_tx_param(struct run_softc *sc, struct mbuf *m, struct ieee80211_node *ni,
3266     const struct ieee80211_bpf_params *params)
3267 {
3268 	struct ieee80211com *ic = ni->ni_ic;
3269 	struct ieee80211_frame *wh;
3270 	struct run_tx_data *data;
3271 	struct rt2870_txd *txd;
3272 	struct rt2860_txwi *txwi;
3273 	uint8_t type;
3274 	uint8_t ridx;
3275 	uint8_t rate;
3276 	uint8_t opflags = 0;
3277 	uint8_t xflags = 0;
3278 	int error;
3279 
3280 	RUN_LOCK_ASSERT(sc, MA_OWNED);
3281 
3282 	KASSERT(params != NULL, ("no raw xmit params"));
3283 
3284 	wh = mtod(m, struct ieee80211_frame *);
3285 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3286 
3287 	rate = params->ibp_rate0;
3288 	if (!ieee80211_isratevalid(ic->ic_rt, rate)) {
3289 		/* let caller free mbuf */
3290 		return (EINVAL);
3291 	}
3292 
3293 	if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
3294 		xflags |= RT2860_TX_ACK;
3295 	if (params->ibp_flags & (IEEE80211_BPF_RTS|IEEE80211_BPF_CTS)) {
3296 		error = run_sendprot(sc, m, ni,
3297 		    params->ibp_flags & IEEE80211_BPF_RTS ?
3298 			IEEE80211_PROT_RTSCTS : IEEE80211_PROT_CTSONLY,
3299 		    rate);
3300 		if (error) {
3301 			/* let caller free mbuf */
3302 			return error;
3303 		}
3304 		opflags |= /*XXX RT2573_TX_LONG_RETRY |*/ RT2860_TX_TXOP_SIFS;
3305 	}
3306 
3307 	if (sc->sc_epq[0].tx_nfree == 0) {
3308 		/* let caller free mbuf */
3309 		sc->sc_ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3310 		DPRINTF("sending raw frame, but tx ring is full\n");
3311 		return (EIO);
3312 	}
3313         data = STAILQ_FIRST(&sc->sc_epq[0].tx_fh);
3314         STAILQ_REMOVE_HEAD(&sc->sc_epq[0].tx_fh, next);
3315         sc->sc_epq[0].tx_nfree--;
3316 
3317 	txd = (struct rt2870_txd *)&data->desc;
3318 	txd->flags = RT2860_TX_QSEL_EDCA;
3319 	txwi = (struct rt2860_txwi *)(txd + 1);
3320 	txwi->wcid = 0xff;
3321 	txwi->xflags = xflags;
3322 	txwi->txop = opflags;
3323 	txwi->flags = 0;	/* clear leftover garbage bits */
3324 
3325         data->m = m;
3326         data->ni = ni;
3327 	for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
3328 		if (rt2860_rates[ridx].rate == rate)
3329 			break;
3330 	data->ridx = ridx;
3331 
3332         run_set_tx_desc(sc, data);
3333 
3334         DPRINTFN(10, "sending raw frame len=%u rate=%u\n",
3335             m->m_pkthdr.len, rate);
3336 
3337         STAILQ_INSERT_TAIL(&sc->sc_epq[0].tx_qh, data, next);
3338 
3339 	usbd_transfer_start(sc->sc_xfer[0]);
3340 
3341         return (0);
3342 }
3343 
3344 static int
3345 run_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
3346     const struct ieee80211_bpf_params *params)
3347 {
3348 	struct ifnet *ifp = ni->ni_ic->ic_ifp;
3349 	struct run_softc *sc = ifp->if_softc;
3350 	int error = 0;
3351 
3352 	RUN_LOCK(sc);
3353 
3354 	/* prevent management frames from being sent if we're not ready */
3355 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
3356 		error =  ENETDOWN;
3357 		goto done;
3358 	}
3359 
3360 	if (params == NULL) {
3361 		/* tx mgt packet */
3362 		if ((error = run_tx_mgt(sc, m, ni)) != 0) {
3363 			ifp->if_oerrors++;
3364 			DPRINTF("mgt tx failed\n");
3365 			goto done;
3366 		}
3367 	} else {
3368 		/* tx raw packet with param */
3369 		if ((error = run_tx_param(sc, m, ni, params)) != 0) {
3370 			ifp->if_oerrors++;
3371 			DPRINTF("tx with param failed\n");
3372 			goto done;
3373 		}
3374 	}
3375 
3376 	ifp->if_opackets++;
3377 
3378 done:
3379 	RUN_UNLOCK(sc);
3380 
3381 	if (error != 0) {
3382 		if(m != NULL)
3383 			m_freem(m);
3384 		ieee80211_free_node(ni);
3385 	}
3386 
3387 	return (error);
3388 }
3389 
3390 static void
3391 run_start(struct ifnet *ifp)
3392 {
3393 	struct run_softc *sc = ifp->if_softc;
3394 	struct ieee80211_node *ni;
3395 	struct mbuf *m;
3396 
3397 	RUN_LOCK(sc);
3398 
3399 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
3400 		RUN_UNLOCK(sc);
3401 		return;
3402 	}
3403 
3404 	for (;;) {
3405 		/* send data frames */
3406 		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
3407 		if (m == NULL)
3408 			break;
3409 
3410 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
3411 		if (run_tx(sc, m, ni) != 0) {
3412 			IFQ_DRV_PREPEND(&ifp->if_snd, m);
3413 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3414 			break;
3415 		}
3416 	}
3417 
3418 	RUN_UNLOCK(sc);
3419 }
3420 
3421 static int
3422 run_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
3423 {
3424 	struct run_softc *sc = ifp->if_softc;
3425 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3426 	struct ifreq *ifr = (struct ifreq *) data;
3427 	int startall = 0;
3428 	int error = 0;
3429 
3430 	switch (cmd) {
3431 	case SIOCSIFFLAGS:
3432 		RUN_LOCK(sc);
3433 		if (ifp->if_flags & IFF_UP) {
3434 			if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)){
3435 				startall = 1;
3436 				run_init_locked(sc);
3437 			} else
3438 				run_update_promisc_locked(ifp);
3439 		} else {
3440 			if (ifp->if_drv_flags & IFF_DRV_RUNNING &&
3441 			    (ic->ic_nrunning == 0 || sc->rvp_cnt <= 1)) {
3442 					run_stop(sc);
3443 			}
3444 		}
3445 		RUN_UNLOCK(sc);
3446 		if (startall)
3447 			ieee80211_start_all(ic);
3448 		break;
3449 	case SIOCGIFMEDIA:
3450 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
3451 		break;
3452 	case SIOCGIFADDR:
3453 		error = ether_ioctl(ifp, cmd, data);
3454 		break;
3455 	default:
3456 		error = EINVAL;
3457 		break;
3458 	}
3459 
3460 	return (error);
3461 }
3462 
3463 static void
3464 run_set_agc(struct run_softc *sc, uint8_t agc)
3465 {
3466 	uint8_t bbp;
3467 
3468 	if (sc->mac_ver == 0x3572) {
3469 		run_bbp_read(sc, 27, &bbp);
3470 		bbp &= ~(0x3 << 5);
3471 		run_bbp_write(sc, 27, bbp | 0 << 5);	/* select Rx0 */
3472 		run_bbp_write(sc, 66, agc);
3473 		run_bbp_write(sc, 27, bbp | 1 << 5);	/* select Rx1 */
3474 		run_bbp_write(sc, 66, agc);
3475 	} else
3476 		run_bbp_write(sc, 66, agc);
3477 }
3478 
3479 static void
3480 run_select_chan_group(struct run_softc *sc, int group)
3481 {
3482 	uint32_t tmp;
3483 	uint8_t agc;
3484 
3485 	run_bbp_write(sc, 62, 0x37 - sc->lna[group]);
3486 	run_bbp_write(sc, 63, 0x37 - sc->lna[group]);
3487 	run_bbp_write(sc, 64, 0x37 - sc->lna[group]);
3488 	run_bbp_write(sc, 86, 0x00);
3489 
3490 	if (group == 0) {
3491 		if (sc->ext_2ghz_lna) {
3492 			run_bbp_write(sc, 82, 0x62);
3493 			run_bbp_write(sc, 75, 0x46);
3494 		} else {
3495 			run_bbp_write(sc, 82, 0x84);
3496 			run_bbp_write(sc, 75, 0x50);
3497 		}
3498 	} else {
3499 		if (sc->mac_ver == 0x3572)
3500 			run_bbp_write(sc, 82, 0x94);
3501 		else
3502 			run_bbp_write(sc, 82, 0xf2);
3503 		if (sc->ext_5ghz_lna)
3504 			run_bbp_write(sc, 75, 0x46);
3505 		else
3506 			run_bbp_write(sc, 75, 0x50);
3507 	}
3508 
3509 	run_read(sc, RT2860_TX_BAND_CFG, &tmp);
3510 	tmp &= ~(RT2860_5G_BAND_SEL_N | RT2860_5G_BAND_SEL_P);
3511 	tmp |= (group == 0) ? RT2860_5G_BAND_SEL_N : RT2860_5G_BAND_SEL_P;
3512 	run_write(sc, RT2860_TX_BAND_CFG, tmp);
3513 
3514 	/* enable appropriate Power Amplifiers and Low Noise Amplifiers */
3515 	tmp = RT2860_RFTR_EN | RT2860_TRSW_EN | RT2860_LNA_PE0_EN;
3516 	if (sc->nrxchains > 1)
3517 		tmp |= RT2860_LNA_PE1_EN;
3518 	if (group == 0) {	/* 2GHz */
3519 		tmp |= RT2860_PA_PE_G0_EN;
3520 		if (sc->ntxchains > 1)
3521 			tmp |= RT2860_PA_PE_G1_EN;
3522 	} else {		/* 5GHz */
3523 		tmp |= RT2860_PA_PE_A0_EN;
3524 		if (sc->ntxchains > 1)
3525 			tmp |= RT2860_PA_PE_A1_EN;
3526 	}
3527 	if (sc->mac_ver == 0x3572) {
3528 		run_rt3070_rf_write(sc, 8, 0x00);
3529 		run_write(sc, RT2860_TX_PIN_CFG, tmp);
3530 		run_rt3070_rf_write(sc, 8, 0x80);
3531 	} else
3532 		run_write(sc, RT2860_TX_PIN_CFG, tmp);
3533 
3534 	/* set initial AGC value */
3535 	if (group == 0) {	/* 2GHz band */
3536 		if (sc->mac_ver >= 0x3070)
3537 			agc = 0x1c + sc->lna[0] * 2;
3538 		else
3539 			agc = 0x2e + sc->lna[0];
3540 	} else {		/* 5GHz band */
3541 		if (sc->mac_ver == 0x3572)
3542 			agc = 0x22 + (sc->lna[group] * 5) / 3;
3543 		else
3544 			agc = 0x32 + (sc->lna[group] * 5) / 3;
3545 	}
3546 	run_set_agc(sc, agc);
3547 }
3548 
3549 static void
3550 run_rt2870_set_chan(struct run_softc *sc, uint32_t chan)
3551 {
3552 	const struct rfprog *rfprog = rt2860_rf2850;
3553 	uint32_t r2, r3, r4;
3554 	int8_t txpow1, txpow2;
3555 	int i;
3556 
3557 	/* find the settings for this channel (we know it exists) */
3558 	for (i = 0; rfprog[i].chan != chan; i++);
3559 
3560 	r2 = rfprog[i].r2;
3561 	if (sc->ntxchains == 1)
3562 		r2 |= 1 << 12;		/* 1T: disable Tx chain 2 */
3563 	if (sc->nrxchains == 1)
3564 		r2 |= 1 << 15 | 1 << 4;	/* 1R: disable Rx chains 2 & 3 */
3565 	else if (sc->nrxchains == 2)
3566 		r2 |= 1 << 4;		/* 2R: disable Rx chain 3 */
3567 
3568 	/* use Tx power values from EEPROM */
3569 	txpow1 = sc->txpow1[i];
3570 	txpow2 = sc->txpow2[i];
3571 	if (chan > 14) {
3572 		if (txpow1 >= 0)
3573 			txpow1 = txpow1 << 1 | 1;
3574 		else
3575 			txpow1 = (7 + txpow1) << 1;
3576 		if (txpow2 >= 0)
3577 			txpow2 = txpow2 << 1 | 1;
3578 		else
3579 			txpow2 = (7 + txpow2) << 1;
3580 	}
3581 	r3 = rfprog[i].r3 | txpow1 << 7;
3582 	r4 = rfprog[i].r4 | sc->freq << 13 | txpow2 << 4;
3583 
3584 	run_rt2870_rf_write(sc, RT2860_RF1, rfprog[i].r1);
3585 	run_rt2870_rf_write(sc, RT2860_RF2, r2);
3586 	run_rt2870_rf_write(sc, RT2860_RF3, r3);
3587 	run_rt2870_rf_write(sc, RT2860_RF4, r4);
3588 
3589 	run_delay(sc, 10);
3590 
3591 	run_rt2870_rf_write(sc, RT2860_RF1, rfprog[i].r1);
3592 	run_rt2870_rf_write(sc, RT2860_RF2, r2);
3593 	run_rt2870_rf_write(sc, RT2860_RF3, r3 | 1);
3594 	run_rt2870_rf_write(sc, RT2860_RF4, r4);
3595 
3596 	run_delay(sc, 10);
3597 
3598 	run_rt2870_rf_write(sc, RT2860_RF1, rfprog[i].r1);
3599 	run_rt2870_rf_write(sc, RT2860_RF2, r2);
3600 	run_rt2870_rf_write(sc, RT2860_RF3, r3);
3601 	run_rt2870_rf_write(sc, RT2860_RF4, r4);
3602 }
3603 
3604 static void
3605 run_rt3070_set_chan(struct run_softc *sc, uint32_t chan)
3606 {
3607 	int8_t txpow1, txpow2;
3608 	uint8_t rf;
3609 	int i;
3610 
3611 	/* RT3070 is 2GHz only */
3612 	KASSERT(chan >= 1 && chan <= 14, ("wrong channel selected\n"));
3613 
3614 	/* find the settings for this channel (we know it exists) */
3615 	for (i = 0; rt2860_rf2850[i].chan != chan; i++);
3616 
3617 	/* use Tx power values from EEPROM */
3618 	txpow1 = sc->txpow1[i];
3619 	txpow2 = sc->txpow2[i];
3620 
3621 	run_rt3070_rf_write(sc, 2, rt3070_freqs[i].n);
3622 	run_rt3070_rf_write(sc, 3, rt3070_freqs[i].k);
3623 	run_rt3070_rf_read(sc, 6, &rf);
3624 	rf = (rf & ~0x03) | rt3070_freqs[i].r;
3625 	run_rt3070_rf_write(sc, 6, rf);
3626 
3627 	/* set Tx0 power */
3628 	run_rt3070_rf_read(sc, 12, &rf);
3629 	rf = (rf & ~0x1f) | txpow1;
3630 	run_rt3070_rf_write(sc, 12, rf);
3631 
3632 	/* set Tx1 power */
3633 	run_rt3070_rf_read(sc, 13, &rf);
3634 	rf = (rf & ~0x1f) | txpow2;
3635 	run_rt3070_rf_write(sc, 13, rf);
3636 
3637 	run_rt3070_rf_read(sc, 1, &rf);
3638 	rf &= ~0xfc;
3639 	if (sc->ntxchains == 1)
3640 		rf |= 1 << 7 | 1 << 5;	/* 1T: disable Tx chains 2 & 3 */
3641 	else if (sc->ntxchains == 2)
3642 		rf |= 1 << 7;		/* 2T: disable Tx chain 3 */
3643 	if (sc->nrxchains == 1)
3644 		rf |= 1 << 6 | 1 << 4;	/* 1R: disable Rx chains 2 & 3 */
3645 	else if (sc->nrxchains == 2)
3646 		rf |= 1 << 6;		/* 2R: disable Rx chain 3 */
3647 	run_rt3070_rf_write(sc, 1, rf);
3648 
3649 	/* set RF offset */
3650 	run_rt3070_rf_read(sc, 23, &rf);
3651 	rf = (rf & ~0x7f) | sc->freq;
3652 	run_rt3070_rf_write(sc, 23, rf);
3653 
3654 	/* program RF filter */
3655 	run_rt3070_rf_read(sc, 24, &rf);	/* Tx */
3656 	rf = (rf & ~0x3f) | sc->rf24_20mhz;
3657 	run_rt3070_rf_write(sc, 24, rf);
3658 	run_rt3070_rf_read(sc, 31, &rf);	/* Rx */
3659 	rf = (rf & ~0x3f) | sc->rf24_20mhz;
3660 	run_rt3070_rf_write(sc, 31, rf);
3661 
3662 	/* enable RF tuning */
3663 	run_rt3070_rf_read(sc, 7, &rf);
3664 	run_rt3070_rf_write(sc, 7, rf | 0x01);
3665 }
3666 
3667 static void
3668 run_rt3572_set_chan(struct run_softc *sc, u_int chan)
3669 {
3670 	int8_t txpow1, txpow2;
3671 	uint32_t tmp;
3672 	uint8_t rf;
3673 	int i;
3674 
3675 	/* find the settings for this channel (we know it exists) */
3676 	for (i = 0; rt2860_rf2850[i].chan != chan; i++);
3677 
3678 	/* use Tx power values from EEPROM */
3679 	txpow1 = sc->txpow1[i];
3680 	txpow2 = sc->txpow2[i];
3681 
3682 	if (chan <= 14) {
3683 		run_bbp_write(sc, 25, sc->bbp25);
3684 		run_bbp_write(sc, 26, sc->bbp26);
3685 	} else {
3686 		/* enable IQ phase correction */
3687 		run_bbp_write(sc, 25, 0x09);
3688 		run_bbp_write(sc, 26, 0xff);
3689 	}
3690 
3691 	run_rt3070_rf_write(sc, 2, rt3070_freqs[i].n);
3692 	run_rt3070_rf_write(sc, 3, rt3070_freqs[i].k);
3693 	run_rt3070_rf_read(sc, 6, &rf);
3694 	rf  = (rf & ~0x0f) | rt3070_freqs[i].r;
3695 	rf |= (chan <= 14) ? 0x08 : 0x04;
3696 	run_rt3070_rf_write(sc, 6, rf);
3697 
3698 	/* set PLL mode */
3699 	run_rt3070_rf_read(sc, 5, &rf);
3700 	rf &= ~(0x08 | 0x04);
3701 	rf |= (chan <= 14) ? 0x04 : 0x08;
3702 	run_rt3070_rf_write(sc, 5, rf);
3703 
3704 	/* set Tx power for chain 0 */
3705 	if (chan <= 14)
3706 		rf = 0x60 | txpow1;
3707 	else
3708 		rf = 0xe0 | (txpow1 & 0xc) << 1 | (txpow1 & 0x3);
3709 	run_rt3070_rf_write(sc, 12, rf);
3710 
3711 	/* set Tx power for chain 1 */
3712 	if (chan <= 14)
3713 		rf = 0x60 | txpow2;
3714 	else
3715 		rf = 0xe0 | (txpow2 & 0xc) << 1 | (txpow2 & 0x3);
3716 	run_rt3070_rf_write(sc, 13, rf);
3717 
3718 	/* set Tx/Rx streams */
3719 	run_rt3070_rf_read(sc, 1, &rf);
3720 	rf &= ~0xfc;
3721 	if (sc->ntxchains == 1)
3722 		rf |= 1 << 7 | 1 << 5;  /* 1T: disable Tx chains 2 & 3 */
3723 	else if (sc->ntxchains == 2)
3724 		rf |= 1 << 7;           /* 2T: disable Tx chain 3 */
3725 	if (sc->nrxchains == 1)
3726 		rf |= 1 << 6 | 1 << 4;  /* 1R: disable Rx chains 2 & 3 */
3727 	else if (sc->nrxchains == 2)
3728 		rf |= 1 << 6;           /* 2R: disable Rx chain 3 */
3729 	run_rt3070_rf_write(sc, 1, rf);
3730 
3731 	/* set RF offset */
3732 	run_rt3070_rf_read(sc, 23, &rf);
3733 	rf = (rf & ~0x7f) | sc->freq;
3734 	run_rt3070_rf_write(sc, 23, rf);
3735 
3736 	/* program RF filter */
3737 	rf = sc->rf24_20mhz;
3738 	run_rt3070_rf_write(sc, 24, rf);	/* Tx */
3739 	run_rt3070_rf_write(sc, 31, rf);	/* Rx */
3740 
3741 	/* enable RF tuning */
3742 	run_rt3070_rf_read(sc, 7, &rf);
3743 	rf = (chan <= 14) ? 0xd8 : ((rf & ~0xc8) | 0x14);
3744 	run_rt3070_rf_write(sc, 7, rf);
3745 
3746 	/* TSSI */
3747 	rf = (chan <= 14) ? 0xc3 : 0xc0;
3748 	run_rt3070_rf_write(sc, 9, rf);
3749 
3750 	/* set loop filter 1 */
3751 	run_rt3070_rf_write(sc, 10, 0xf1);
3752 	/* set loop filter 2 */
3753 	run_rt3070_rf_write(sc, 11, (chan <= 14) ? 0xb9 : 0x00);
3754 
3755 	/* set tx_mx2_ic */
3756 	run_rt3070_rf_write(sc, 15, (chan <= 14) ? 0x53 : 0x43);
3757 	/* set tx_mx1_ic */
3758 	if (chan <= 14)
3759 		rf = 0x48 | sc->txmixgain_2ghz;
3760 	else
3761 		rf = 0x78 | sc->txmixgain_5ghz;
3762 	run_rt3070_rf_write(sc, 16, rf);
3763 
3764 	/* set tx_lo1 */
3765 	run_rt3070_rf_write(sc, 17, 0x23);
3766 	/* set tx_lo2 */
3767 	if (chan <= 14)
3768 		rf = 0x93;
3769 	else if (chan <= 64)
3770 		rf = 0xb7;
3771 	else if (chan <= 128)
3772 		rf = 0x74;
3773 	else
3774 		rf = 0x72;
3775 	run_rt3070_rf_write(sc, 19, rf);
3776 
3777 	/* set rx_lo1 */
3778 	if (chan <= 14)
3779 		rf = 0xb3;
3780 	else if (chan <= 64)
3781 		rf = 0xf6;
3782 	else if (chan <= 128)
3783 		rf = 0xf4;
3784 	else
3785 		rf = 0xf3;
3786 	run_rt3070_rf_write(sc, 20, rf);
3787 
3788 	/* set pfd_delay */
3789 	if (chan <= 14)
3790 		rf = 0x15;
3791 	else if (chan <= 64)
3792 		rf = 0x3d;
3793 	else
3794 		rf = 0x01;
3795 	run_rt3070_rf_write(sc, 25, rf);
3796 
3797 	/* set rx_lo2 */
3798 	run_rt3070_rf_write(sc, 26, (chan <= 14) ? 0x85 : 0x87);
3799 	/* set ldo_rf_vc */
3800 	run_rt3070_rf_write(sc, 27, (chan <= 14) ? 0x00 : 0x01);
3801 	/* set drv_cc */
3802 	run_rt3070_rf_write(sc, 29, (chan <= 14) ? 0x9b : 0x9f);
3803 
3804 	run_read(sc, RT2860_GPIO_CTRL, &tmp);
3805 	tmp &= ~0x8080;
3806 	if (chan <= 14)
3807 		tmp |= 0x80;
3808 	run_write(sc, RT2860_GPIO_CTRL, tmp);
3809 
3810 	/* enable RF tuning */
3811 	run_rt3070_rf_read(sc, 7, &rf);
3812 	run_rt3070_rf_write(sc, 7, rf | 0x01);
3813 
3814 	run_delay(sc, 2);
3815 }
3816 
3817 static void
3818 run_set_rx_antenna(struct run_softc *sc, int aux)
3819 {
3820 	uint32_t tmp;
3821 
3822 	if (aux) {
3823 		run_mcu_cmd(sc, RT2860_MCU_CMD_ANTSEL, 0);
3824 		run_read(sc, RT2860_GPIO_CTRL, &tmp);
3825 		run_write(sc, RT2860_GPIO_CTRL, (tmp & ~0x0808) | 0x08);
3826 	} else {
3827 		run_mcu_cmd(sc, RT2860_MCU_CMD_ANTSEL, 1);
3828 		run_read(sc, RT2860_GPIO_CTRL, &tmp);
3829 		run_write(sc, RT2860_GPIO_CTRL, tmp & ~0x0808);
3830 	}
3831 }
3832 
3833 static int
3834 run_set_chan(struct run_softc *sc, struct ieee80211_channel *c)
3835 {
3836 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3837 	uint32_t chan, group;
3838 
3839 	chan = ieee80211_chan2ieee(ic, c);
3840 	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
3841 		return (EINVAL);
3842 
3843 	if (sc->mac_ver == 0x3572)
3844 		run_rt3572_set_chan(sc, chan);
3845 	else if (sc->mac_ver >= 0x3070)
3846 		run_rt3070_set_chan(sc, chan);
3847 	else
3848 		run_rt2870_set_chan(sc, chan);
3849 
3850 	/* determine channel group */
3851 	if (chan <= 14)
3852 		group = 0;
3853 	else if (chan <= 64)
3854 		group = 1;
3855 	else if (chan <= 128)
3856 		group = 2;
3857 	else
3858 		group = 3;
3859 
3860 	/* XXX necessary only when group has changed! */
3861 	run_select_chan_group(sc, group);
3862 
3863 	run_delay(sc, 10);
3864 
3865 	return (0);
3866 }
3867 
3868 static void
3869 run_set_channel(struct ieee80211com *ic)
3870 {
3871 	struct run_softc *sc = ic->ic_ifp->if_softc;
3872 
3873 	RUN_LOCK(sc);
3874 	run_set_chan(sc, ic->ic_curchan);
3875 	RUN_UNLOCK(sc);
3876 
3877 	return;
3878 }
3879 
3880 static void
3881 run_scan_start(struct ieee80211com *ic)
3882 {
3883 	struct run_softc *sc = ic->ic_ifp->if_softc;
3884 	uint32_t tmp;
3885 
3886 	RUN_LOCK(sc);
3887 
3888 	/* abort TSF synchronization */
3889 	run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
3890 	run_write(sc, RT2860_BCN_TIME_CFG,
3891 	    tmp & ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN |
3892 	    RT2860_TBTT_TIMER_EN));
3893 	run_set_bssid(sc, sc->sc_ifp->if_broadcastaddr);
3894 
3895 	RUN_UNLOCK(sc);
3896 
3897 	return;
3898 }
3899 
3900 static void
3901 run_scan_end(struct ieee80211com *ic)
3902 {
3903 	struct run_softc *sc = ic->ic_ifp->if_softc;
3904 
3905 	RUN_LOCK(sc);
3906 
3907 	run_enable_tsf_sync(sc);
3908 	/* XXX keep local copy */
3909 	run_set_bssid(sc, sc->sc_bssid);
3910 
3911 	RUN_UNLOCK(sc);
3912 
3913 	return;
3914 }
3915 
3916 /*
3917  * Could be called from ieee80211_node_timeout()
3918  * (non-sleepable thread)
3919  */
3920 static void
3921 run_update_beacon(struct ieee80211vap *vap, int item)
3922 {
3923 	struct ieee80211com *ic = vap->iv_ic;
3924 	struct run_softc *sc = ic->ic_ifp->if_softc;
3925 	struct run_vap *rvp = RUN_VAP(vap);
3926 	int mcast = 0;
3927 	uint32_t i;
3928 
3929 	KASSERT(vap != NULL, ("no beacon"));
3930 
3931 	switch (item) {
3932 	case IEEE80211_BEACON_ERP:
3933 		run_updateslot(ic->ic_ifp);
3934 		break;
3935 	case IEEE80211_BEACON_HTINFO:
3936 		run_updateprot(ic);
3937 		break;
3938 	case IEEE80211_BEACON_TIM:
3939 		mcast = 1;	/*TODO*/
3940 		break;
3941 	default:
3942 		break;
3943 	}
3944 
3945 	setbit(rvp->bo.bo_flags, item);
3946 	ieee80211_beacon_update(vap->iv_bss, &rvp->bo, rvp->beacon_mbuf, mcast);
3947 
3948 	i = RUN_CMDQ_GET(&sc->cmdq_store);
3949 	DPRINTF("cmdq_store=%d\n", i);
3950 	sc->cmdq[i].func = run_update_beacon_cb;
3951 	sc->cmdq[i].arg0 = vap;
3952 	ieee80211_runtask(ic, &sc->cmdq_task);
3953 
3954 	return;
3955 }
3956 
3957 static void
3958 run_update_beacon_cb(void *arg)
3959 {
3960 	struct ieee80211vap *vap = arg;
3961 	struct run_vap *rvp = RUN_VAP(vap);
3962 	struct ieee80211com *ic = vap->iv_ic;
3963 	struct run_softc *sc = ic->ic_ifp->if_softc;
3964 	struct rt2860_txwi txwi;
3965 	struct mbuf *m;
3966 	uint8_t ridx;
3967 
3968 	if (vap->iv_bss->ni_chan == IEEE80211_CHAN_ANYC)
3969 		return;
3970 
3971 	/*
3972 	 * No need to call ieee80211_beacon_update(), run_update_beacon()
3973 	 * is taking care of apropriate calls.
3974 	 */
3975 	if (rvp->beacon_mbuf == NULL) {
3976 		rvp->beacon_mbuf = ieee80211_beacon_alloc(vap->iv_bss,
3977 		    &rvp->bo);
3978 		if (rvp->beacon_mbuf == NULL)
3979 			return;
3980 	}
3981 	m = rvp->beacon_mbuf;
3982 
3983 	memset(&txwi, 0, sizeof txwi);
3984 	txwi.wcid = 0xff;
3985 	txwi.len = htole16(m->m_pkthdr.len);
3986 	/* send beacons at the lowest available rate */
3987 	ridx = (ic->ic_curmode == IEEE80211_MODE_11A) ?
3988 	    RT2860_RIDX_OFDM6 : RT2860_RIDX_CCK1;
3989 	txwi.phy = htole16(rt2860_rates[ridx].mcs);
3990 	if (rt2860_rates[ridx].phy == IEEE80211_T_OFDM)
3991 	        txwi.phy |= htole16(RT2860_PHY_OFDM);
3992 	txwi.txop = RT2860_TX_TXOP_HT;
3993 	txwi.flags = RT2860_TX_TS;
3994 	txwi.xflags = RT2860_TX_NSEQ;
3995 
3996 	run_write_region_1(sc, RT2860_BCN_BASE(rvp->rvp_id),
3997 	    (uint8_t *)&txwi, sizeof txwi);
3998 	run_write_region_1(sc, RT2860_BCN_BASE(rvp->rvp_id) + sizeof txwi,
3999 	    mtod(m, uint8_t *), (m->m_pkthdr.len + 1) & ~1);	/* roundup len */
4000 
4001 	return;
4002 }
4003 
4004 static void
4005 run_updateprot(struct ieee80211com *ic)
4006 {
4007 	struct run_softc *sc = ic->ic_ifp->if_softc;
4008 	uint32_t i;
4009 
4010 	i = RUN_CMDQ_GET(&sc->cmdq_store);
4011 	DPRINTF("cmdq_store=%d\n", i);
4012 	sc->cmdq[i].func = run_updateprot_cb;
4013 	sc->cmdq[i].arg0 = ic;
4014 	ieee80211_runtask(ic, &sc->cmdq_task);
4015 }
4016 
4017 static void
4018 run_updateprot_cb(void *arg)
4019 {
4020 	struct ieee80211com *ic = arg;
4021 	struct run_softc *sc = ic->ic_ifp->if_softc;
4022 	uint32_t tmp;
4023 
4024 	tmp = RT2860_RTSTH_EN | RT2860_PROT_NAV_SHORT | RT2860_TXOP_ALLOW_ALL;
4025 	/* setup protection frame rate (MCS code) */
4026 	tmp |= (ic->ic_curmode == IEEE80211_MODE_11A) ?
4027 	    rt2860_rates[RT2860_RIDX_OFDM6].mcs :
4028 	    rt2860_rates[RT2860_RIDX_CCK11].mcs;
4029 
4030 	/* CCK frames don't require protection */
4031 	run_write(sc, RT2860_CCK_PROT_CFG, tmp);
4032 	if (ic->ic_flags & IEEE80211_F_USEPROT) {
4033 		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
4034 			tmp |= RT2860_PROT_CTRL_RTS_CTS;
4035 		else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
4036 			tmp |= RT2860_PROT_CTRL_CTS;
4037 	}
4038 	run_write(sc, RT2860_OFDM_PROT_CFG, tmp);
4039 }
4040 
4041 static void
4042 run_usb_timeout_cb(void *arg)
4043 {
4044 	struct ieee80211vap *vap = arg;
4045 	struct run_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4046 
4047 	RUN_LOCK_ASSERT(sc, MA_OWNED);
4048 
4049 	if(vap->iv_state == IEEE80211_S_RUN &&
4050 	    vap->iv_opmode != IEEE80211_M_STA)
4051 		run_reset_livelock(sc);
4052 	else if (vap->iv_state == IEEE80211_S_SCAN) {
4053 		DPRINTF("timeout caused by scan\n");
4054 		/* cancel bgscan */
4055 		ieee80211_cancel_scan(vap);
4056 	} else
4057 		DPRINTF("timeout by unknown cause\n");
4058 }
4059 
4060 static void
4061 run_reset_livelock(struct run_softc *sc)
4062 {
4063 	uint32_t tmp;
4064 
4065 	RUN_LOCK_ASSERT(sc, MA_OWNED);
4066 
4067 	/*
4068 	 * In IBSS or HostAP modes (when the hardware sends beacons), the MAC
4069 	 * can run into a livelock and start sending CTS-to-self frames like
4070 	 * crazy if protection is enabled.  Reset MAC/BBP for a while
4071 	 */
4072 	run_read(sc, RT2860_DEBUG, &tmp);
4073 	DPRINTFN(3, "debug reg %08x\n", tmp);
4074 	if ((tmp & (1 << 29)) && (tmp & (1 << 7 | 1 << 5))) {
4075 		DPRINTF("CTS-to-self livelock detected\n");
4076 		run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_MAC_SRST);
4077 		run_delay(sc, 1);
4078 		run_write(sc, RT2860_MAC_SYS_CTRL,
4079 		    RT2860_MAC_RX_EN | RT2860_MAC_TX_EN);
4080 	}
4081 }
4082 
4083 static void
4084 run_update_promisc_locked(struct ifnet *ifp)
4085 {
4086 	struct run_softc *sc = ifp->if_softc;
4087         uint32_t tmp;
4088 
4089 	run_read(sc, RT2860_RX_FILTR_CFG, &tmp);
4090 
4091 	tmp |= RT2860_DROP_UC_NOME;
4092         if (ifp->if_flags & IFF_PROMISC)
4093 		tmp &= ~RT2860_DROP_UC_NOME;
4094 
4095 	run_write(sc, RT2860_RX_FILTR_CFG, tmp);
4096 
4097         DPRINTF("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
4098             "entering" : "leaving");
4099 }
4100 
4101 static void
4102 run_update_promisc(struct ifnet *ifp)
4103 {
4104 	struct run_softc *sc = ifp->if_softc;
4105 
4106 	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0)
4107 		return;
4108 
4109 	RUN_LOCK(sc);
4110 	run_update_promisc_locked(ifp);
4111 	RUN_UNLOCK(sc);
4112 }
4113 
4114 static void
4115 run_enable_tsf_sync(struct run_softc *sc)
4116 {
4117 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4118 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
4119 	uint32_t tmp;
4120 
4121 	DPRINTF("rvp_id=%d ic_opmode=%d\n", RUN_VAP(vap)->rvp_id, ic->ic_opmode);
4122 
4123 	run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
4124 	tmp &= ~0x1fffff;
4125 	tmp |= vap->iv_bss->ni_intval * 16;
4126 	tmp |= RT2860_TSF_TIMER_EN | RT2860_TBTT_TIMER_EN;
4127 
4128 	if (ic->ic_opmode == IEEE80211_M_STA) {
4129 		/*
4130 		 * Local TSF is always updated with remote TSF on beacon
4131 		 * reception.
4132 		 */
4133 		tmp |= 1 << RT2860_TSF_SYNC_MODE_SHIFT;
4134 	} else if (ic->ic_opmode == IEEE80211_M_IBSS) {
4135 	        tmp |= RT2860_BCN_TX_EN;
4136 	        /*
4137 	         * Local TSF is updated with remote TSF on beacon reception
4138 	         * only if the remote TSF is greater than local TSF.
4139 	         */
4140 	        tmp |= 2 << RT2860_TSF_SYNC_MODE_SHIFT;
4141 	} else if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
4142 		    ic->ic_opmode == IEEE80211_M_MBSS) {
4143 	        tmp |= RT2860_BCN_TX_EN;
4144 	        /* SYNC with nobody */
4145 	        tmp |= 3 << RT2860_TSF_SYNC_MODE_SHIFT;
4146 	} else {
4147 		DPRINTF("Enabling TSF failed. undefined opmode\n");
4148 		return;
4149 	}
4150 
4151 	run_write(sc, RT2860_BCN_TIME_CFG, tmp);
4152 }
4153 
4154 static void
4155 run_enable_mrr(struct run_softc *sc)
4156 {
4157 #define CCK(mcs)	(mcs)
4158 #define OFDM(mcs)	(1 << 3 | (mcs))
4159 	run_write(sc, RT2860_LG_FBK_CFG0,
4160 	    OFDM(6) << 28 |	/* 54->48 */
4161 	    OFDM(5) << 24 |	/* 48->36 */
4162 	    OFDM(4) << 20 |	/* 36->24 */
4163 	    OFDM(3) << 16 |	/* 24->18 */
4164 	    OFDM(2) << 12 |	/* 18->12 */
4165 	    OFDM(1) <<  8 |	/* 12-> 9 */
4166 	    OFDM(0) <<  4 |	/*  9-> 6 */
4167 	    OFDM(0));		/*  6-> 6 */
4168 
4169 	run_write(sc, RT2860_LG_FBK_CFG1,
4170 	    CCK(2) << 12 |	/* 11->5.5 */
4171 	    CCK(1) <<  8 |	/* 5.5-> 2 */
4172 	    CCK(0) <<  4 |	/*   2-> 1 */
4173 	    CCK(0));		/*   1-> 1 */
4174 #undef OFDM
4175 #undef CCK
4176 }
4177 
4178 static void
4179 run_set_txpreamble(struct run_softc *sc)
4180 {
4181 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4182 	uint32_t tmp;
4183 
4184 	run_read(sc, RT2860_AUTO_RSP_CFG, &tmp);
4185 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
4186 		tmp |= RT2860_CCK_SHORT_EN;
4187 	else
4188 		tmp &= ~RT2860_CCK_SHORT_EN;
4189 	run_write(sc, RT2860_AUTO_RSP_CFG, tmp);
4190 }
4191 
4192 static void
4193 run_set_basicrates(struct run_softc *sc)
4194 {
4195 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4196 
4197 	/* set basic rates mask */
4198 	if (ic->ic_curmode == IEEE80211_MODE_11B)
4199 		run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x003);
4200 	else if (ic->ic_curmode == IEEE80211_MODE_11A)
4201 		run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x150);
4202 	else	/* 11g */
4203 		run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x15f);
4204 }
4205 
4206 static void
4207 run_set_leds(struct run_softc *sc, uint16_t which)
4208 {
4209 	(void)run_mcu_cmd(sc, RT2860_MCU_CMD_LEDS,
4210 	    which | (sc->leds & 0x7f));
4211 }
4212 
4213 static void
4214 run_set_bssid(struct run_softc *sc, const uint8_t *bssid)
4215 {
4216 	run_write(sc, RT2860_MAC_BSSID_DW0,
4217 	    bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24);
4218 	run_write(sc, RT2860_MAC_BSSID_DW1,
4219 	    bssid[4] | bssid[5] << 8);
4220 }
4221 
4222 static void
4223 run_set_macaddr(struct run_softc *sc, const uint8_t *addr)
4224 {
4225 	run_write(sc, RT2860_MAC_ADDR_DW0,
4226 	    addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24);
4227 	run_write(sc, RT2860_MAC_ADDR_DW1,
4228 	    addr[4] | addr[5] << 8 | 0xff << 16);
4229 }
4230 
4231 static void
4232 run_updateslot(struct ifnet *ifp)
4233 {
4234 	struct run_softc *sc = ifp->if_softc;
4235 	struct ieee80211com *ic = ifp->if_l2com;
4236 	uint32_t i;
4237 
4238 	i = RUN_CMDQ_GET(&sc->cmdq_store);
4239 	DPRINTF("cmdq_store=%d\n", i);
4240 	sc->cmdq[i].func = run_updateslot_cb;
4241 	sc->cmdq[i].arg0 = ifp;
4242 	ieee80211_runtask(ic, &sc->cmdq_task);
4243 
4244 	return;
4245 }
4246 
4247 /* ARGSUSED */
4248 static void
4249 run_updateslot_cb(void *arg)
4250 {
4251 	struct ifnet *ifp = arg;
4252 	struct run_softc *sc = ifp->if_softc;
4253 	struct ieee80211com *ic = ifp->if_l2com;
4254 	uint32_t tmp;
4255 
4256 	run_read(sc, RT2860_BKOFF_SLOT_CFG, &tmp);
4257 	tmp &= ~0xff;
4258 	tmp |= (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
4259 	run_write(sc, RT2860_BKOFF_SLOT_CFG, tmp);
4260 }
4261 
4262 static void
4263 run_update_mcast(struct ifnet *ifp)
4264 {
4265 	/* h/w filter supports getting everything or nothing */
4266 	ifp->if_flags |= IFF_ALLMULTI;
4267 }
4268 
4269 static int8_t
4270 run_rssi2dbm(struct run_softc *sc, uint8_t rssi, uint8_t rxchain)
4271 {
4272 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4273 	struct ieee80211_channel *c = ic->ic_curchan;
4274 	int delta;
4275 
4276 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
4277 		uint32_t chan = ieee80211_chan2ieee(ic, c);
4278 		delta = sc->rssi_5ghz[rxchain];
4279 
4280 		/* determine channel group */
4281 		if (chan <= 64)
4282 			delta -= sc->lna[1];
4283 		else if (chan <= 128)
4284 			delta -= sc->lna[2];
4285 		else
4286 			delta -= sc->lna[3];
4287 	} else
4288 		delta = sc->rssi_2ghz[rxchain] - sc->lna[0];
4289 
4290 	return (-12 - delta - rssi);
4291 }
4292 
4293 static int
4294 run_bbp_init(struct run_softc *sc)
4295 {
4296 	int i, error, ntries;
4297 	uint8_t bbp0;
4298 
4299 	/* wait for BBP to wake up */
4300 	for (ntries = 0; ntries < 20; ntries++) {
4301 		if ((error = run_bbp_read(sc, 0, &bbp0)) != 0)
4302 			return error;
4303 		if (bbp0 != 0 && bbp0 != 0xff)
4304 			break;
4305 	}
4306 	if (ntries == 20)
4307 		return (ETIMEDOUT);
4308 
4309 	/* initialize BBP registers to default values */
4310 	for (i = 0; i < N(rt2860_def_bbp); i++) {
4311 		run_bbp_write(sc, rt2860_def_bbp[i].reg,
4312 		    rt2860_def_bbp[i].val);
4313 	}
4314 
4315 	/* fix BBP84 for RT2860E */
4316 	if (sc->mac_ver == 0x2860 && sc->mac_rev != 0x0101)
4317 		run_bbp_write(sc, 84, 0x19);
4318 
4319 	if (sc->mac_ver >= 0x3070) {
4320 		run_bbp_write(sc, 79, 0x13);
4321 		run_bbp_write(sc, 80, 0x05);
4322 		run_bbp_write(sc, 81, 0x33);
4323 	} else if (sc->mac_ver == 0x2860 && sc->mac_rev == 0x0100) {
4324 		run_bbp_write(sc, 69, 0x16);
4325 		run_bbp_write(sc, 73, 0x12);
4326 	}
4327 	return (0);
4328 }
4329 
4330 static int
4331 run_rt3070_rf_init(struct run_softc *sc)
4332 {
4333 	uint32_t tmp;
4334 	uint8_t rf, target, bbp4;
4335 	int i;
4336 
4337 	run_rt3070_rf_read(sc, 30, &rf);
4338 	/* toggle RF R30 bit 7 */
4339 	run_rt3070_rf_write(sc, 30, rf | 0x80);
4340 	run_delay(sc, 10);
4341 	run_rt3070_rf_write(sc, 30, rf & ~0x80);
4342 
4343 	/* initialize RF registers to default value */
4344 	if (sc->mac_ver == 0x3572) {
4345 		for (i = 0; i < N(rt3572_def_rf); i++) {
4346 			run_rt3070_rf_write(sc, rt3572_def_rf[i].reg,
4347 			    rt3572_def_rf[i].val);
4348 		}
4349 	} else {
4350 		for (i = 0; i < N(rt3070_def_rf); i++) {
4351 			run_rt3070_rf_write(sc, rt3070_def_rf[i].reg,
4352 			    rt3070_def_rf[i].val);
4353 		}
4354 	}
4355 
4356 	if (sc->mac_ver == 0x3070) {
4357 		/* change voltage from 1.2V to 1.35V for RT3070 */
4358 		run_read(sc, RT3070_LDO_CFG0, &tmp);
4359 		tmp = (tmp & ~0x0f000000) | 0x0d000000;
4360 		run_write(sc, RT3070_LDO_CFG0, tmp);
4361 
4362 	} else if (sc->mac_ver == 0x3071) {
4363 		run_rt3070_rf_read(sc, 6, &rf);
4364 		run_rt3070_rf_write(sc, 6, rf | 0x40);
4365 		run_rt3070_rf_write(sc, 31, 0x14);
4366 
4367 		run_read(sc, RT3070_LDO_CFG0, &tmp);
4368 		tmp &= ~0x1f000000;
4369 		if (sc->mac_rev < 0x0211)
4370 			tmp |= 0x0d000000;	/* 1.3V */
4371 		else
4372 			tmp |= 0x01000000;	/* 1.2V */
4373 		run_write(sc, RT3070_LDO_CFG0, tmp);
4374 
4375 		/* patch LNA_PE_G1 */
4376 		run_read(sc, RT3070_GPIO_SWITCH, &tmp);
4377 		run_write(sc, RT3070_GPIO_SWITCH, tmp & ~0x20);
4378 
4379 	} else if (sc->mac_ver == 0x3572) {
4380 		run_rt3070_rf_read(sc, 6, &rf);
4381 		run_rt3070_rf_write(sc, 6, rf | 0x40);
4382 
4383 		/* increase voltage from 1.2V to 1.35V */
4384 		run_read(sc, RT3070_LDO_CFG0, &tmp);
4385 		tmp = (tmp & ~0x1f000000) | 0x0d000000;
4386 		run_write(sc, RT3070_LDO_CFG0, tmp);
4387 
4388 		if (sc->mac_rev < 0x0211 || !sc->patch_dac) {
4389 			run_delay(sc, 1);	/* wait for 1msec */
4390 			/* decrease voltage back to 1.2V */
4391 			tmp = (tmp & ~0x1f000000) | 0x01000000;
4392 			run_write(sc, RT3070_LDO_CFG0, tmp);
4393 		}
4394 	}
4395 
4396 	/* select 20MHz bandwidth */
4397 	run_rt3070_rf_read(sc, 31, &rf);
4398 	run_rt3070_rf_write(sc, 31, rf & ~0x20);
4399 
4400 	/* calibrate filter for 20MHz bandwidth */
4401 	sc->rf24_20mhz = 0x1f;	/* default value */
4402 	target = (sc->mac_ver < 0x3071) ? 0x16 : 0x13;
4403 	run_rt3070_filter_calib(sc, 0x07, target, &sc->rf24_20mhz);
4404 
4405 	/* select 40MHz bandwidth */
4406 	run_bbp_read(sc, 4, &bbp4);
4407 	run_bbp_write(sc, 4, (bbp4 & ~0x08) | 0x10);
4408 	run_rt3070_rf_read(sc, 31, &rf);
4409 	run_rt3070_rf_write(sc, 31, rf | 0x20);
4410 
4411 	/* calibrate filter for 40MHz bandwidth */
4412 	sc->rf24_40mhz = 0x2f;	/* default value */
4413 	target = (sc->mac_ver < 0x3071) ? 0x19 : 0x15;
4414 	run_rt3070_filter_calib(sc, 0x27, target, &sc->rf24_40mhz);
4415 
4416 	/* go back to 20MHz bandwidth */
4417 	run_bbp_read(sc, 4, &bbp4);
4418 	run_bbp_write(sc, 4, bbp4 & ~0x18);
4419 
4420 	if (sc->mac_ver == 0x3572) {
4421 		/* save default BBP registers 25 and 26 values */
4422 		run_bbp_read(sc, 25, &sc->bbp25);
4423 		run_bbp_read(sc, 26, &sc->bbp26);
4424 	} else if (sc->mac_rev < 0x0211)
4425 		run_rt3070_rf_write(sc, 27, 0x03);
4426 
4427 	run_read(sc, RT3070_OPT_14, &tmp);
4428 	run_write(sc, RT3070_OPT_14, tmp | 1);
4429 
4430 	if (sc->mac_ver == 0x3070 || sc->mac_ver == 0x3071) {
4431 		run_rt3070_rf_read(sc, 17, &rf);
4432 		rf &= ~RT3070_TX_LO1;
4433 		if ((sc->mac_ver == 0x3070 ||
4434 		     (sc->mac_ver == 0x3071 && sc->mac_rev >= 0x0211)) &&
4435 		    !sc->ext_2ghz_lna)
4436 			rf |= 0x20;	/* fix for long range Rx issue */
4437 		if (sc->txmixgain_2ghz >= 1)
4438 			rf = (rf & ~0x7) | sc->txmixgain_2ghz;
4439 		run_rt3070_rf_write(sc, 17, rf);
4440 	}
4441 
4442 	if (sc->mac_rev == 0x3071) {
4443 		run_rt3070_rf_read(sc, 1, &rf);
4444 		rf &= ~(RT3070_RX0_PD | RT3070_TX0_PD);
4445 		rf |= RT3070_RF_BLOCK | RT3070_RX1_PD | RT3070_TX1_PD;
4446 		run_rt3070_rf_write(sc, 1, rf);
4447 
4448 		run_rt3070_rf_read(sc, 15, &rf);
4449 		run_rt3070_rf_write(sc, 15, rf & ~RT3070_TX_LO2);
4450 
4451 		run_rt3070_rf_read(sc, 20, &rf);
4452 		run_rt3070_rf_write(sc, 20, rf & ~RT3070_RX_LO1);
4453 
4454 		run_rt3070_rf_read(sc, 21, &rf);
4455 		run_rt3070_rf_write(sc, 21, rf & ~RT3070_RX_LO2);
4456 	}
4457 
4458 	if (sc->mac_ver == 0x3070 || sc->mac_ver == 0x3071) {
4459 		/* fix Tx to Rx IQ glitch by raising RF voltage */
4460 		run_rt3070_rf_read(sc, 27, &rf);
4461 		rf &= ~0x77;
4462 		if (sc->mac_rev < 0x0211)
4463 			rf |= 0x03;
4464 		run_rt3070_rf_write(sc, 27, rf);
4465 	}
4466 	return (0);
4467 }
4468 
4469 static int
4470 run_rt3070_filter_calib(struct run_softc *sc, uint8_t init, uint8_t target,
4471     uint8_t *val)
4472 {
4473 	uint8_t rf22, rf24;
4474 	uint8_t bbp55_pb, bbp55_sb, delta;
4475 	int ntries;
4476 
4477 	/* program filter */
4478 	run_rt3070_rf_read(sc, 24, &rf24);
4479 	rf24 = (rf24 & 0xc0) | init;	/* initial filter value */
4480 	run_rt3070_rf_write(sc, 24, rf24);
4481 
4482 	/* enable baseband loopback mode */
4483 	run_rt3070_rf_read(sc, 22, &rf22);
4484 	run_rt3070_rf_write(sc, 22, rf22 | 0x01);
4485 
4486 	/* set power and frequency of passband test tone */
4487 	run_bbp_write(sc, 24, 0x00);
4488 	for (ntries = 0; ntries < 100; ntries++) {
4489 		/* transmit test tone */
4490 		run_bbp_write(sc, 25, 0x90);
4491 		run_delay(sc, 10);
4492 		/* read received power */
4493 		run_bbp_read(sc, 55, &bbp55_pb);
4494 		if (bbp55_pb != 0)
4495 			break;
4496 	}
4497 	if (ntries == 100)
4498 		return ETIMEDOUT;
4499 
4500 	/* set power and frequency of stopband test tone */
4501 	run_bbp_write(sc, 24, 0x06);
4502 	for (ntries = 0; ntries < 100; ntries++) {
4503 		/* transmit test tone */
4504 		run_bbp_write(sc, 25, 0x90);
4505 		run_delay(sc, 10);
4506 		/* read received power */
4507 		run_bbp_read(sc, 55, &bbp55_sb);
4508 
4509 		delta = bbp55_pb - bbp55_sb;
4510 		if (delta > target)
4511 			break;
4512 
4513 		/* reprogram filter */
4514 		rf24++;
4515 		run_rt3070_rf_write(sc, 24, rf24);
4516 	}
4517 	if (ntries < 100) {
4518 		if (rf24 != init)
4519 			rf24--;	/* backtrack */
4520 		*val = rf24;
4521 		run_rt3070_rf_write(sc, 24, rf24);
4522 	}
4523 
4524 	/* restore initial state */
4525 	run_bbp_write(sc, 24, 0x00);
4526 
4527 	/* disable baseband loopback mode */
4528 	run_rt3070_rf_read(sc, 22, &rf22);
4529 	run_rt3070_rf_write(sc, 22, rf22 & ~0x01);
4530 
4531 	return (0);
4532 }
4533 
4534 static void
4535 run_rt3070_rf_setup(struct run_softc *sc)
4536 {
4537 	uint8_t bbp, rf;
4538 	int i;
4539 
4540 	if (sc->mac_ver == 0x3572) {
4541 		/* enable DC filter */
4542 		if (sc->mac_rev >= 0x0201)
4543 			run_bbp_write(sc, 103, 0xc0);
4544 
4545 		run_bbp_read(sc, 138, &bbp);
4546 		if (sc->ntxchains == 1)
4547 			bbp |= 0x20;	/* turn off DAC1 */
4548 		if (sc->nrxchains == 1)
4549 			bbp &= ~0x02;	/* turn off ADC1 */
4550 		run_bbp_write(sc, 138, bbp);
4551 
4552 		if (sc->mac_rev >= 0x0211) {
4553 			/* improve power consumption */
4554 			run_bbp_read(sc, 31, &bbp);
4555 			run_bbp_write(sc, 31, bbp & ~0x03);
4556 		}
4557 
4558 		run_rt3070_rf_read(sc, 16, &rf);
4559 		rf = (rf & ~0x07) | sc->txmixgain_2ghz;
4560 		run_rt3070_rf_write(sc, 16, rf);
4561 
4562 	} else if (sc->mac_ver == 0x3071) {
4563 		/* enable DC filter */
4564 		if (sc->mac_rev >= 0x0201)
4565 			run_bbp_write(sc, 103, 0xc0);
4566 
4567 		run_bbp_read(sc, 138, &bbp);
4568 		if (sc->ntxchains == 1)
4569 			bbp |= 0x20;	/* turn off DAC1 */
4570 		if (sc->nrxchains == 1)
4571 			bbp &= ~0x02;	/* turn off ADC1 */
4572 		run_bbp_write(sc, 138, bbp);
4573 
4574 		if (sc->mac_rev >= 0x0211) {
4575 			/* improve power consumption */
4576 			run_bbp_read(sc, 31, &bbp);
4577 			run_bbp_write(sc, 31, bbp & ~0x03);
4578 		}
4579 
4580 		run_write(sc, RT2860_TX_SW_CFG1, 0);
4581 		if (sc->mac_rev < 0x0211) {
4582 			run_write(sc, RT2860_TX_SW_CFG2,
4583 			    sc->patch_dac ? 0x2c : 0x0f);
4584 		} else
4585 			run_write(sc, RT2860_TX_SW_CFG2, 0);
4586 
4587 	} else if (sc->mac_ver == 0x3070) {
4588 		if (sc->mac_rev >= 0x0201) {
4589 			/* enable DC filter */
4590 			run_bbp_write(sc, 103, 0xc0);
4591 
4592 			/* improve power consumption */
4593 			run_bbp_read(sc, 31, &bbp);
4594 			run_bbp_write(sc, 31, bbp & ~0x03);
4595 		}
4596 
4597 		if (sc->mac_rev < 0x0211) {
4598 			run_write(sc, RT2860_TX_SW_CFG1, 0);
4599 			run_write(sc, RT2860_TX_SW_CFG2, 0x2c);
4600 		} else
4601 			run_write(sc, RT2860_TX_SW_CFG2, 0);
4602 	}
4603 
4604 	/* initialize RF registers from ROM for >=RT3071*/
4605 	if (sc->mac_ver >= 0x3071) {
4606 		for (i = 0; i < 10; i++) {
4607 			if (sc->rf[i].reg == 0 || sc->rf[i].reg == 0xff)
4608 				continue;
4609 			run_rt3070_rf_write(sc, sc->rf[i].reg, sc->rf[i].val);
4610 		}
4611 	}
4612 }
4613 
4614 static int
4615 run_txrx_enable(struct run_softc *sc)
4616 {
4617 	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4618 	uint32_t tmp;
4619 	int error, ntries;
4620 
4621 	run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_MAC_TX_EN);
4622 	for (ntries = 0; ntries < 200; ntries++) {
4623 		if ((error = run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp)) != 0)
4624 			return error;
4625 		if ((tmp & (RT2860_TX_DMA_BUSY | RT2860_RX_DMA_BUSY)) == 0)
4626 			break;
4627 		run_delay(sc, 50);
4628 	}
4629 	if (ntries == 200)
4630 		return ETIMEDOUT;
4631 
4632 	run_delay(sc, 50);
4633 
4634 	tmp |= RT2860_RX_DMA_EN | RT2860_TX_DMA_EN | RT2860_TX_WB_DDONE;
4635 	run_write(sc, RT2860_WPDMA_GLO_CFG, tmp);
4636 
4637 	/* enable Rx bulk aggregation (set timeout and limit) */
4638 	tmp = RT2860_USB_TX_EN | RT2860_USB_RX_EN | RT2860_USB_RX_AGG_EN |
4639 	    RT2860_USB_RX_AGG_TO(128) | RT2860_USB_RX_AGG_LMT(2);
4640 	run_write(sc, RT2860_USB_DMA_CFG, tmp);
4641 
4642 	/* set Rx filter */
4643 	tmp = RT2860_DROP_CRC_ERR | RT2860_DROP_PHY_ERR;
4644 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
4645 		tmp |= RT2860_DROP_UC_NOME | RT2860_DROP_DUPL |
4646 		    RT2860_DROP_CTS | RT2860_DROP_BA | RT2860_DROP_ACK |
4647 		    RT2860_DROP_VER_ERR | RT2860_DROP_CTRL_RSV |
4648 		    RT2860_DROP_CFACK | RT2860_DROP_CFEND;
4649 		if (ic->ic_opmode == IEEE80211_M_STA)
4650 			tmp |= RT2860_DROP_RTS | RT2860_DROP_PSPOLL;
4651 	}
4652 	run_write(sc, RT2860_RX_FILTR_CFG, tmp);
4653 
4654 	run_write(sc, RT2860_MAC_SYS_CTRL,
4655 	    RT2860_MAC_RX_EN | RT2860_MAC_TX_EN);
4656 
4657 	return (0);
4658 }
4659 
4660 static void
4661 run_init_locked(struct run_softc *sc)
4662 {
4663 	struct ifnet *ifp = sc->sc_ifp;
4664 	struct ieee80211com *ic = ifp->if_l2com;
4665 	uint32_t tmp;
4666 	uint8_t bbp1, bbp3;
4667 	int i;
4668 	int ridx;
4669 	int ntries;
4670 
4671 	if (ic->ic_nrunning > 1)
4672 		return;
4673 
4674 	run_stop(sc);
4675 
4676 	if (run_load_microcode(sc) != 0) {
4677 		device_printf(sc->sc_dev, "could not load 8051 microcode\n");
4678 		goto fail;
4679 	}
4680 
4681 	for (ntries = 0; ntries < 100; ntries++) {
4682 		if (run_read(sc, RT2860_ASIC_VER_ID, &tmp) != 0)
4683 			goto fail;
4684 		if (tmp != 0 && tmp != 0xffffffff)
4685 			break;
4686 		run_delay(sc, 10);
4687 	}
4688 	if (ntries == 100)
4689 		goto fail;
4690 
4691 	for (i = 0; i != RUN_EP_QUEUES; i++)
4692 		run_setup_tx_list(sc, &sc->sc_epq[i]);
4693 
4694 	run_set_macaddr(sc, IF_LLADDR(ifp));
4695 
4696 	for (ntries = 0; ntries < 100; ntries++) {
4697 		if (run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp) != 0)
4698 			goto fail;
4699 		if ((tmp & (RT2860_TX_DMA_BUSY | RT2860_RX_DMA_BUSY)) == 0)
4700 			break;
4701 		run_delay(sc, 10);
4702 	}
4703 	if (ntries == 100) {
4704 		device_printf(sc->sc_dev, "timeout waiting for DMA engine\n");
4705 		goto fail;
4706 	}
4707 	tmp &= 0xff0;
4708 	tmp |= RT2860_TX_WB_DDONE;
4709 	run_write(sc, RT2860_WPDMA_GLO_CFG, tmp);
4710 
4711 	/* turn off PME_OEN to solve high-current issue */
4712 	run_read(sc, RT2860_SYS_CTRL, &tmp);
4713 	run_write(sc, RT2860_SYS_CTRL, tmp & ~RT2860_PME_OEN);
4714 
4715 	run_write(sc, RT2860_MAC_SYS_CTRL,
4716 	    RT2860_BBP_HRST | RT2860_MAC_SRST);
4717 	run_write(sc, RT2860_USB_DMA_CFG, 0);
4718 
4719 	if (run_reset(sc) != 0) {
4720 		device_printf(sc->sc_dev, "could not reset chipset\n");
4721 		goto fail;
4722 	}
4723 
4724 	run_write(sc, RT2860_MAC_SYS_CTRL, 0);
4725 
4726 	/* init Tx power for all Tx rates (from EEPROM) */
4727 	for (ridx = 0; ridx < 5; ridx++) {
4728 		if (sc->txpow20mhz[ridx] == 0xffffffff)
4729 			continue;
4730 		run_write(sc, RT2860_TX_PWR_CFG(ridx), sc->txpow20mhz[ridx]);
4731 	}
4732 
4733 	for (i = 0; i < N(rt2870_def_mac); i++)
4734 		run_write(sc, rt2870_def_mac[i].reg, rt2870_def_mac[i].val);
4735 	run_write(sc, RT2860_WMM_AIFSN_CFG, 0x00002273);
4736 	run_write(sc, RT2860_WMM_CWMIN_CFG, 0x00002344);
4737 	run_write(sc, RT2860_WMM_CWMAX_CFG, 0x000034aa);
4738 
4739 	if (sc->mac_ver >= 0x3070) {
4740 		/* set delay of PA_PE assertion to 1us (unit of 0.25us) */
4741 		run_write(sc, RT2860_TX_SW_CFG0,
4742 		    4 << RT2860_DLY_PAPE_EN_SHIFT);
4743 	}
4744 
4745 	/* wait while MAC is busy */
4746 	for (ntries = 0; ntries < 100; ntries++) {
4747 		if (run_read(sc, RT2860_MAC_STATUS_REG, &tmp) != 0)
4748 			goto fail;
4749 		if (!(tmp & (RT2860_RX_STATUS_BUSY | RT2860_TX_STATUS_BUSY)))
4750 			break;
4751 		run_delay(sc, 10);
4752 	}
4753 	if (ntries == 100)
4754 		goto fail;
4755 
4756 	/* clear Host to MCU mailbox */
4757 	run_write(sc, RT2860_H2M_BBPAGENT, 0);
4758 	run_write(sc, RT2860_H2M_MAILBOX, 0);
4759 	run_delay(sc, 10);
4760 
4761 	if (run_bbp_init(sc) != 0) {
4762 		device_printf(sc->sc_dev, "could not initialize BBP\n");
4763 		goto fail;
4764 	}
4765 
4766 	/* abort TSF synchronization */
4767 	run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
4768 	tmp &= ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN |
4769 	    RT2860_TBTT_TIMER_EN);
4770 	run_write(sc, RT2860_BCN_TIME_CFG, tmp);
4771 
4772 	/* clear RX WCID search table */
4773 	run_set_region_4(sc, RT2860_WCID_ENTRY(0), 0, 512);
4774 	/* clear WCID attribute table */
4775 	run_set_region_4(sc, RT2860_WCID_ATTR(0), 0, 8 * 32);
4776 
4777 	/* hostapd sets a key before init. So, don't clear it. */
4778 	if (sc->cmdq_key_set != RUN_CMDQ_GO) {
4779 		/* clear shared key table */
4780 		run_set_region_4(sc, RT2860_SKEY(0, 0), 0, 8 * 32);
4781 		/* clear shared key mode */
4782 		run_set_region_4(sc, RT2860_SKEY_MODE_0_7, 0, 4);
4783 	}
4784 
4785 	run_read(sc, RT2860_US_CYC_CNT, &tmp);
4786 	tmp = (tmp & ~0xff) | 0x1e;
4787 	run_write(sc, RT2860_US_CYC_CNT, tmp);
4788 
4789 	if (sc->mac_rev != 0x0101)
4790 		run_write(sc, RT2860_TXOP_CTRL_CFG, 0x0000583f);
4791 
4792 	run_write(sc, RT2860_WMM_TXOP0_CFG, 0);
4793 	run_write(sc, RT2860_WMM_TXOP1_CFG, 48 << 16 | 96);
4794 
4795 	/* write vendor-specific BBP values (from EEPROM) */
4796 	for (i = 0; i < 10; i++) {
4797 		if (sc->bbp[i].reg == 0 || sc->bbp[i].reg == 0xff)
4798 			continue;
4799 		run_bbp_write(sc, sc->bbp[i].reg, sc->bbp[i].val);
4800 	}
4801 
4802 	/* select Main antenna for 1T1R devices */
4803 	if (sc->rf_rev == RT3070_RF_3020)
4804 		run_set_rx_antenna(sc, 0);
4805 
4806 	/* send LEDs operating mode to microcontroller */
4807 	(void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED1, sc->led[0]);
4808 	(void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED2, sc->led[1]);
4809 	(void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED3, sc->led[2]);
4810 
4811 	if (sc->mac_ver >= 0x3070)
4812 		run_rt3070_rf_init(sc);
4813 
4814 	/* disable non-existing Rx chains */
4815 	run_bbp_read(sc, 3, &bbp3);
4816 	bbp3 &= ~(1 << 3 | 1 << 4);
4817 	if (sc->nrxchains == 2)
4818 		bbp3 |= 1 << 3;
4819 	else if (sc->nrxchains == 3)
4820 		bbp3 |= 1 << 4;
4821 	run_bbp_write(sc, 3, bbp3);
4822 
4823 	/* disable non-existing Tx chains */
4824 	run_bbp_read(sc, 1, &bbp1);
4825 	if (sc->ntxchains == 1)
4826 		bbp1 &= ~(1 << 3 | 1 << 4);
4827 	run_bbp_write(sc, 1, bbp1);
4828 
4829 	if (sc->mac_ver >= 0x3070)
4830 		run_rt3070_rf_setup(sc);
4831 
4832 	/* select default channel */
4833 	run_set_chan(sc, ic->ic_curchan);
4834 
4835 	/* setup initial protection mode */
4836 	run_updateprot_cb(ic);
4837 
4838 	/* turn radio LED on */
4839 	run_set_leds(sc, RT2860_LED_RADIO);
4840 
4841 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4842 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
4843 	sc->cmdq_run = RUN_CMDQ_GO;
4844 
4845 	for (i = 0; i != RUN_N_XFER; i++)
4846 		usbd_xfer_set_stall(sc->sc_xfer[i]);
4847 
4848 	usbd_transfer_start(sc->sc_xfer[RUN_BULK_RX]);
4849 
4850 	if (run_txrx_enable(sc) != 0)
4851 		goto fail;
4852 
4853 	return;
4854 
4855 fail:
4856 	run_stop(sc);
4857 }
4858 
4859 static void
4860 run_init(void *arg)
4861 {
4862 	struct run_softc *sc = arg;
4863 	struct ifnet *ifp = sc->sc_ifp;
4864 	struct ieee80211com *ic = ifp->if_l2com;
4865 
4866 	RUN_LOCK(sc);
4867 	run_init_locked(sc);
4868 	RUN_UNLOCK(sc);
4869 
4870 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
4871 		ieee80211_start_all(ic);
4872 }
4873 
4874 static void
4875 run_stop(void *arg)
4876 {
4877 	struct run_softc *sc = (struct run_softc *)arg;
4878 	struct ifnet *ifp = sc->sc_ifp;
4879 	uint32_t tmp;
4880 	int i;
4881 	int ntries;
4882 
4883 	RUN_LOCK_ASSERT(sc, MA_OWNED);
4884 
4885 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
4886 		run_set_leds(sc, 0);	/* turn all LEDs off */
4887 
4888 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
4889 
4890 	sc->ratectl_run = RUN_RATECTL_OFF;
4891 	sc->cmdq_run = sc->cmdq_key_set;
4892 
4893 	RUN_UNLOCK(sc);
4894 
4895 	for(i = 0; i < RUN_N_XFER; i++)
4896 		usbd_transfer_drain(sc->sc_xfer[i]);
4897 
4898 	RUN_LOCK(sc);
4899 
4900 	if (sc->rx_m != NULL) {
4901 		m_free(sc->rx_m);
4902 		sc->rx_m = NULL;
4903 	}
4904 
4905 	/* disable Tx/Rx */
4906 	run_read(sc, RT2860_MAC_SYS_CTRL, &tmp);
4907 	tmp &= ~(RT2860_MAC_RX_EN | RT2860_MAC_TX_EN);
4908 	run_write(sc, RT2860_MAC_SYS_CTRL, tmp);
4909 
4910 	/* wait for pending Tx to complete */
4911 	for (ntries = 0; ntries < 100; ntries++) {
4912 		if (run_read(sc, RT2860_TXRXQ_PCNT, &tmp) != 0) {
4913 			DPRINTF("Cannot read Tx queue count\n");
4914 			break;
4915 		}
4916 		if ((tmp & RT2860_TX2Q_PCNT_MASK) == 0) {
4917 			DPRINTF("All Tx cleared\n");
4918 			break;
4919 		}
4920 		run_delay(sc, 10);
4921 	}
4922 	if (ntries >= 100)
4923 		DPRINTF("There are still pending Tx\n");
4924 	run_delay(sc, 10);
4925 	run_write(sc, RT2860_USB_DMA_CFG, 0);
4926 
4927 	run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_BBP_HRST | RT2860_MAC_SRST);
4928 	run_write(sc, RT2860_MAC_SYS_CTRL, 0);
4929 
4930 	for (i = 0; i != RUN_EP_QUEUES; i++)
4931 		run_unsetup_tx_list(sc, &sc->sc_epq[i]);
4932 
4933 	return;
4934 }
4935 
4936 static void
4937 run_delay(struct run_softc *sc, unsigned int ms)
4938 {
4939 	usb_pause_mtx(mtx_owned(&sc->sc_mtx) ?
4940 	    &sc->sc_mtx : NULL, USB_MS_TO_TICKS(ms));
4941 }
4942 
4943 static device_method_t run_methods[] = {
4944 	/* Device interface */
4945 	DEVMETHOD(device_probe,		run_match),
4946 	DEVMETHOD(device_attach,	run_attach),
4947 	DEVMETHOD(device_detach,	run_detach),
4948 
4949 	{ 0, 0 }
4950 };
4951 
4952 static driver_t run_driver = {
4953 	.name = "run",
4954 	.methods = run_methods,
4955 	.size = sizeof(struct run_softc)
4956 };
4957 
4958 static devclass_t run_devclass;
4959 
4960 DRIVER_MODULE(run, uhub, run_driver, run_devclass, NULL, 0);
4961 MODULE_DEPEND(run, wlan, 1, 1, 1);
4962 MODULE_DEPEND(run, usb, 1, 1, 1);
4963 MODULE_DEPEND(run, firmware, 1, 1, 1);
4964 MODULE_VERSION(run, 1);
4965