xref: /freebsd/sys/dev/usb/wlan/if_run.c (revision 273c26a3c3bea87a241d6879abd4f991db180bf0)
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  * Copyright (c) 2013-2014 Kevin Lo
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/cdefs.h>
21 __FBSDID("$FreeBSD$");
22 
23 /*-
24  * Ralink Technology RT2700U/RT2800U/RT3000U/RT3900E chipset driver.
25  * http://www.ralinktech.com/
26  */
27 
28 #include <sys/param.h>
29 #include <sys/sockio.h>
30 #include <sys/sysctl.h>
31 #include <sys/lock.h>
32 #include <sys/mutex.h>
33 #include <sys/mbuf.h>
34 #include <sys/kernel.h>
35 #include <sys/socket.h>
36 #include <sys/systm.h>
37 #include <sys/malloc.h>
38 #include <sys/module.h>
39 #include <sys/bus.h>
40 #include <sys/endian.h>
41 #include <sys/linker.h>
42 #include <sys/firmware.h>
43 #include <sys/kdb.h>
44 
45 #include <machine/bus.h>
46 #include <machine/resource.h>
47 #include <sys/rman.h>
48 
49 #include <net/bpf.h>
50 #include <net/if.h>
51 #include <net/if_var.h>
52 #include <net/if_arp.h>
53 #include <net/ethernet.h>
54 #include <net/if_dl.h>
55 #include <net/if_media.h>
56 #include <net/if_types.h>
57 
58 #include <netinet/in.h>
59 #include <netinet/in_systm.h>
60 #include <netinet/in_var.h>
61 #include <netinet/if_ether.h>
62 #include <netinet/ip.h>
63 
64 #include <net80211/ieee80211_var.h>
65 #include <net80211/ieee80211_regdomain.h>
66 #include <net80211/ieee80211_radiotap.h>
67 #include <net80211/ieee80211_ratectl.h>
68 
69 #include <dev/usb/usb.h>
70 #include <dev/usb/usbdi.h>
71 #include "usbdevs.h"
72 
73 #define	USB_DEBUG_VAR	run_debug
74 #include <dev/usb/usb_debug.h>
75 #include <dev/usb/usb_msctest.h>
76 
77 #include <dev/usb/wlan/if_runreg.h>
78 #include <dev/usb/wlan/if_runvar.h>
79 
80 #ifdef	USB_DEBUG
81 #define	RUN_DEBUG
82 #endif
83 
84 #ifdef	RUN_DEBUG
85 int run_debug = 0;
86 static SYSCTL_NODE(_hw_usb, OID_AUTO, run, CTLFLAG_RW, 0, "USB run");
87 SYSCTL_INT(_hw_usb_run, OID_AUTO, debug, CTLFLAG_RWTUN, &run_debug, 0,
88     "run debug level");
89 #endif
90 
91 #define	IEEE80211_HAS_ADDR4(wh)	IEEE80211_IS_DSTODS(wh)
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 #define	RUN_DEV_EJECT(v,p)	\
102 	{ USB_VPI(USB_VENDOR_##v, USB_PRODUCT_##v##_##p, RUN_EJECT) }
103 #define	RUN_EJECT	1
104     RUN_DEV(ABOCOM,		RT2770),
105     RUN_DEV(ABOCOM,		RT2870),
106     RUN_DEV(ABOCOM,		RT3070),
107     RUN_DEV(ABOCOM,		RT3071),
108     RUN_DEV(ABOCOM,		RT3072),
109     RUN_DEV(ABOCOM2,		RT2870_1),
110     RUN_DEV(ACCTON,		RT2770),
111     RUN_DEV(ACCTON,		RT2870_1),
112     RUN_DEV(ACCTON,		RT2870_2),
113     RUN_DEV(ACCTON,		RT2870_3),
114     RUN_DEV(ACCTON,		RT2870_4),
115     RUN_DEV(ACCTON,		RT2870_5),
116     RUN_DEV(ACCTON,		RT3070),
117     RUN_DEV(ACCTON,		RT3070_1),
118     RUN_DEV(ACCTON,		RT3070_2),
119     RUN_DEV(ACCTON,		RT3070_3),
120     RUN_DEV(ACCTON,		RT3070_4),
121     RUN_DEV(ACCTON,		RT3070_5),
122     RUN_DEV(AIRTIES,		RT3070),
123     RUN_DEV(ALLWIN,		RT2070),
124     RUN_DEV(ALLWIN,		RT2770),
125     RUN_DEV(ALLWIN,		RT2870),
126     RUN_DEV(ALLWIN,		RT3070),
127     RUN_DEV(ALLWIN,		RT3071),
128     RUN_DEV(ALLWIN,		RT3072),
129     RUN_DEV(ALLWIN,		RT3572),
130     RUN_DEV(AMIGO,		RT2870_1),
131     RUN_DEV(AMIGO,		RT2870_2),
132     RUN_DEV(AMIT,		CGWLUSB2GNR),
133     RUN_DEV(AMIT,		RT2870_1),
134     RUN_DEV(AMIT2,		RT2870),
135     RUN_DEV(ASUS,		RT2870_1),
136     RUN_DEV(ASUS,		RT2870_2),
137     RUN_DEV(ASUS,		RT2870_3),
138     RUN_DEV(ASUS,		RT2870_4),
139     RUN_DEV(ASUS,		RT2870_5),
140     RUN_DEV(ASUS,		USBN13),
141     RUN_DEV(ASUS,		RT3070_1),
142     RUN_DEV(ASUS,		USBN66),
143     RUN_DEV(ASUS,		USB_N53),
144     RUN_DEV(ASUS2,		USBN11),
145     RUN_DEV(AZUREWAVE,		RT2870_1),
146     RUN_DEV(AZUREWAVE,		RT2870_2),
147     RUN_DEV(AZUREWAVE,		RT3070_1),
148     RUN_DEV(AZUREWAVE,		RT3070_2),
149     RUN_DEV(AZUREWAVE,		RT3070_3),
150     RUN_DEV(BELKIN,		F9L1103),
151     RUN_DEV(BELKIN,		F5D8053V3),
152     RUN_DEV(BELKIN,		F5D8055),
153     RUN_DEV(BELKIN,		F5D8055V2),
154     RUN_DEV(BELKIN,		F6D4050V1),
155     RUN_DEV(BELKIN,		F6D4050V2),
156     RUN_DEV(BELKIN,		RT2870_1),
157     RUN_DEV(BELKIN,		RT2870_2),
158     RUN_DEV(CISCOLINKSYS,	AE1000),
159     RUN_DEV(CISCOLINKSYS2,	RT3070),
160     RUN_DEV(CISCOLINKSYS3,	RT3070),
161     RUN_DEV(CONCEPTRONIC2,	RT2870_1),
162     RUN_DEV(CONCEPTRONIC2,	RT2870_2),
163     RUN_DEV(CONCEPTRONIC2,	RT2870_3),
164     RUN_DEV(CONCEPTRONIC2,	RT2870_4),
165     RUN_DEV(CONCEPTRONIC2,	RT2870_5),
166     RUN_DEV(CONCEPTRONIC2,	RT2870_6),
167     RUN_DEV(CONCEPTRONIC2,	RT2870_7),
168     RUN_DEV(CONCEPTRONIC2,	RT2870_8),
169     RUN_DEV(CONCEPTRONIC2,	RT3070_1),
170     RUN_DEV(CONCEPTRONIC2,	RT3070_2),
171     RUN_DEV(CONCEPTRONIC2,	VIGORN61),
172     RUN_DEV(COREGA,		CGWLUSB300GNM),
173     RUN_DEV(COREGA,		RT2870_1),
174     RUN_DEV(COREGA,		RT2870_2),
175     RUN_DEV(COREGA,		RT2870_3),
176     RUN_DEV(COREGA,		RT3070),
177     RUN_DEV(CYBERTAN,		RT2870),
178     RUN_DEV(DLINK,		RT2870),
179     RUN_DEV(DLINK,		RT3072),
180     RUN_DEV(DLINK,		DWA127),
181     RUN_DEV(DLINK,		DWA140B3),
182     RUN_DEV(DLINK,		DWA160B2),
183     RUN_DEV(DLINK,		DWA140D1),
184     RUN_DEV(DLINK,		DWA162),
185     RUN_DEV(DLINK2,		DWA130),
186     RUN_DEV(DLINK2,		RT2870_1),
187     RUN_DEV(DLINK2,		RT2870_2),
188     RUN_DEV(DLINK2,		RT3070_1),
189     RUN_DEV(DLINK2,		RT3070_2),
190     RUN_DEV(DLINK2,		RT3070_3),
191     RUN_DEV(DLINK2,		RT3070_4),
192     RUN_DEV(DLINK2,		RT3070_5),
193     RUN_DEV(DLINK2,		RT3072),
194     RUN_DEV(DLINK2,		RT3072_1),
195     RUN_DEV(EDIMAX,		EW7717),
196     RUN_DEV(EDIMAX,		EW7718),
197     RUN_DEV(EDIMAX,		EW7733UND),
198     RUN_DEV(EDIMAX,		RT2870_1),
199     RUN_DEV(ENCORE,		RT3070_1),
200     RUN_DEV(ENCORE,		RT3070_2),
201     RUN_DEV(ENCORE,		RT3070_3),
202     RUN_DEV(GIGABYTE,		GNWB31N),
203     RUN_DEV(GIGABYTE,		GNWB32L),
204     RUN_DEV(GIGABYTE,		RT2870_1),
205     RUN_DEV(GIGASET,		RT3070_1),
206     RUN_DEV(GIGASET,		RT3070_2),
207     RUN_DEV(GUILLEMOT,		HWNU300),
208     RUN_DEV(HAWKING,		HWUN2),
209     RUN_DEV(HAWKING,		RT2870_1),
210     RUN_DEV(HAWKING,		RT2870_2),
211     RUN_DEV(HAWKING,		RT3070),
212     RUN_DEV(IODATA,		RT3072_1),
213     RUN_DEV(IODATA,		RT3072_2),
214     RUN_DEV(IODATA,		RT3072_3),
215     RUN_DEV(IODATA,		RT3072_4),
216     RUN_DEV(LINKSYS4,		RT3070),
217     RUN_DEV(LINKSYS4,		WUSB100),
218     RUN_DEV(LINKSYS4,		WUSB54GCV3),
219     RUN_DEV(LINKSYS4,		WUSB600N),
220     RUN_DEV(LINKSYS4,		WUSB600NV2),
221     RUN_DEV(LOGITEC,		RT2870_1),
222     RUN_DEV(LOGITEC,		RT2870_2),
223     RUN_DEV(LOGITEC,		RT2870_3),
224     RUN_DEV(LOGITEC,		LANW300NU2),
225     RUN_DEV(LOGITEC,		LANW150NU2),
226     RUN_DEV(LOGITEC,		LANW300NU2S),
227     RUN_DEV(MELCO,		WLIUCG300HP),
228     RUN_DEV(MELCO,		RT2870_2),
229     RUN_DEV(MELCO,		WLIUCAG300N),
230     RUN_DEV(MELCO,		WLIUCG300N),
231     RUN_DEV(MELCO,		WLIUCG301N),
232     RUN_DEV(MELCO,		WLIUCGN),
233     RUN_DEV(MELCO,		WLIUCGNM),
234     RUN_DEV(MELCO,		WLIUCG300HPV1),
235     RUN_DEV(MELCO,		WLIUCGNM2),
236     RUN_DEV(MOTOROLA4,		RT2770),
237     RUN_DEV(MOTOROLA4,		RT3070),
238     RUN_DEV(MSI,		RT3070_1),
239     RUN_DEV(MSI,		RT3070_2),
240     RUN_DEV(MSI,		RT3070_3),
241     RUN_DEV(MSI,		RT3070_4),
242     RUN_DEV(MSI,		RT3070_5),
243     RUN_DEV(MSI,		RT3070_6),
244     RUN_DEV(MSI,		RT3070_7),
245     RUN_DEV(MSI,		RT3070_8),
246     RUN_DEV(MSI,		RT3070_9),
247     RUN_DEV(MSI,		RT3070_10),
248     RUN_DEV(MSI,		RT3070_11),
249     RUN_DEV(NETGEAR,		WNDA4100),
250     RUN_DEV(OVISLINK,		RT3072),
251     RUN_DEV(PARA,		RT3070),
252     RUN_DEV(PEGATRON,		RT2870),
253     RUN_DEV(PEGATRON,		RT3070),
254     RUN_DEV(PEGATRON,		RT3070_2),
255     RUN_DEV(PEGATRON,		RT3070_3),
256     RUN_DEV(PHILIPS,		RT2870),
257     RUN_DEV(PLANEX2,		GWUS300MINIS),
258     RUN_DEV(PLANEX2,		GWUSMICRON),
259     RUN_DEV(PLANEX2,		RT2870),
260     RUN_DEV(PLANEX2,		RT3070),
261     RUN_DEV(QCOM,		RT2870),
262     RUN_DEV(QUANTA,		RT3070),
263     RUN_DEV(RALINK,		RT2070),
264     RUN_DEV(RALINK,		RT2770),
265     RUN_DEV(RALINK,		RT2870),
266     RUN_DEV(RALINK,		RT3070),
267     RUN_DEV(RALINK,		RT3071),
268     RUN_DEV(RALINK,		RT3072),
269     RUN_DEV(RALINK,		RT3370),
270     RUN_DEV(RALINK,		RT3572),
271     RUN_DEV(RALINK,		RT3573),
272     RUN_DEV(RALINK,		RT5370),
273     RUN_DEV(RALINK,		RT5572),
274     RUN_DEV(RALINK,		RT8070),
275     RUN_DEV(SAMSUNG,		WIS09ABGN),
276     RUN_DEV(SAMSUNG2,		RT2870_1),
277     RUN_DEV(SENAO,		RT2870_1),
278     RUN_DEV(SENAO,		RT2870_2),
279     RUN_DEV(SENAO,		RT2870_3),
280     RUN_DEV(SENAO,		RT2870_4),
281     RUN_DEV(SENAO,		RT3070),
282     RUN_DEV(SENAO,		RT3071),
283     RUN_DEV(SENAO,		RT3072_1),
284     RUN_DEV(SENAO,		RT3072_2),
285     RUN_DEV(SENAO,		RT3072_3),
286     RUN_DEV(SENAO,		RT3072_4),
287     RUN_DEV(SENAO,		RT3072_5),
288     RUN_DEV(SITECOMEU,		RT2770),
289     RUN_DEV(SITECOMEU,		RT2870_1),
290     RUN_DEV(SITECOMEU,		RT2870_2),
291     RUN_DEV(SITECOMEU,		RT2870_3),
292     RUN_DEV(SITECOMEU,		RT2870_4),
293     RUN_DEV(SITECOMEU,		RT3070),
294     RUN_DEV(SITECOMEU,		RT3070_2),
295     RUN_DEV(SITECOMEU,		RT3070_3),
296     RUN_DEV(SITECOMEU,		RT3070_4),
297     RUN_DEV(SITECOMEU,		RT3071),
298     RUN_DEV(SITECOMEU,		RT3072_1),
299     RUN_DEV(SITECOMEU,		RT3072_2),
300     RUN_DEV(SITECOMEU,		RT3072_3),
301     RUN_DEV(SITECOMEU,		RT3072_4),
302     RUN_DEV(SITECOMEU,		RT3072_5),
303     RUN_DEV(SITECOMEU,		RT3072_6),
304     RUN_DEV(SITECOMEU,		WL608),
305     RUN_DEV(SPARKLAN,		RT2870_1),
306     RUN_DEV(SPARKLAN,		RT3070),
307     RUN_DEV(SWEEX2,		LW153),
308     RUN_DEV(SWEEX2,		LW303),
309     RUN_DEV(SWEEX2,		LW313),
310     RUN_DEV(TOSHIBA,		RT3070),
311     RUN_DEV(UMEDIA,		RT2870_1),
312     RUN_DEV(ZCOM,		RT2870_1),
313     RUN_DEV(ZCOM,		RT2870_2),
314     RUN_DEV(ZINWELL,		RT2870_1),
315     RUN_DEV(ZINWELL,		RT2870_2),
316     RUN_DEV(ZINWELL,		RT3070),
317     RUN_DEV(ZINWELL,		RT3072_1),
318     RUN_DEV(ZINWELL,		RT3072_2),
319     RUN_DEV(ZYXEL,		RT2870_1),
320     RUN_DEV(ZYXEL,		RT2870_2),
321     RUN_DEV(ZYXEL,		RT3070),
322     RUN_DEV_EJECT(ZYXEL,	NWD2705),
323     RUN_DEV_EJECT(RALINK,	RT_STOR),
324 #undef RUN_DEV_EJECT
325 #undef RUN_DEV
326 };
327 
328 static device_probe_t	run_match;
329 static device_attach_t	run_attach;
330 static device_detach_t	run_detach;
331 
332 static usb_callback_t	run_bulk_rx_callback;
333 static usb_callback_t	run_bulk_tx_callback0;
334 static usb_callback_t	run_bulk_tx_callback1;
335 static usb_callback_t	run_bulk_tx_callback2;
336 static usb_callback_t	run_bulk_tx_callback3;
337 static usb_callback_t	run_bulk_tx_callback4;
338 static usb_callback_t	run_bulk_tx_callback5;
339 
340 static void	run_autoinst(void *, struct usb_device *,
341 		    struct usb_attach_arg *);
342 static int	run_driver_loaded(struct module *, int, void *);
343 static void	run_bulk_tx_callbackN(struct usb_xfer *xfer,
344 		    usb_error_t error, u_int index);
345 static struct ieee80211vap *run_vap_create(struct ieee80211com *,
346 		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
347 		    const uint8_t [IEEE80211_ADDR_LEN],
348 		    const uint8_t [IEEE80211_ADDR_LEN]);
349 static void	run_vap_delete(struct ieee80211vap *);
350 static void	run_cmdq_cb(void *, int);
351 static void	run_setup_tx_list(struct run_softc *,
352 		    struct run_endpoint_queue *);
353 static void	run_unsetup_tx_list(struct run_softc *,
354 		    struct run_endpoint_queue *);
355 static int	run_load_microcode(struct run_softc *);
356 static int	run_reset(struct run_softc *);
357 static usb_error_t run_do_request(struct run_softc *,
358 		    struct usb_device_request *, void *);
359 static int	run_read(struct run_softc *, uint16_t, uint32_t *);
360 static int	run_read_region_1(struct run_softc *, uint16_t, uint8_t *, int);
361 static int	run_write_2(struct run_softc *, uint16_t, uint16_t);
362 static int	run_write(struct run_softc *, uint16_t, uint32_t);
363 static int	run_write_region_1(struct run_softc *, uint16_t,
364 		    const uint8_t *, int);
365 static int	run_set_region_4(struct run_softc *, uint16_t, uint32_t, int);
366 static int	run_efuse_read(struct run_softc *, uint16_t, uint16_t *, int);
367 static int	run_efuse_read_2(struct run_softc *, uint16_t, uint16_t *);
368 static int	run_eeprom_read_2(struct run_softc *, uint16_t, uint16_t *);
369 static int	run_rt2870_rf_write(struct run_softc *, uint32_t);
370 static int	run_rt3070_rf_read(struct run_softc *, uint8_t, uint8_t *);
371 static int	run_rt3070_rf_write(struct run_softc *, uint8_t, uint8_t);
372 static int	run_bbp_read(struct run_softc *, uint8_t, uint8_t *);
373 static int	run_bbp_write(struct run_softc *, uint8_t, uint8_t);
374 static int	run_mcu_cmd(struct run_softc *, uint8_t, uint16_t);
375 static const char *run_get_rf(uint16_t);
376 static void	run_rt3593_get_txpower(struct run_softc *);
377 static void	run_get_txpower(struct run_softc *);
378 static int	run_read_eeprom(struct run_softc *);
379 static struct ieee80211_node *run_node_alloc(struct ieee80211vap *,
380 			    const uint8_t mac[IEEE80211_ADDR_LEN]);
381 static int	run_media_change(struct ifnet *);
382 static int	run_newstate(struct ieee80211vap *, enum ieee80211_state, int);
383 static int	run_wme_update(struct ieee80211com *);
384 static void	run_key_set_cb(void *);
385 static int	run_key_set(struct ieee80211vap *, struct ieee80211_key *);
386 static void	run_key_delete_cb(void *);
387 static int	run_key_delete(struct ieee80211vap *, struct ieee80211_key *);
388 static void	run_ratectl_to(void *);
389 static void	run_ratectl_cb(void *, int);
390 static void	run_drain_fifo(void *);
391 static void	run_iter_func(void *, struct ieee80211_node *);
392 static void	run_newassoc_cb(void *);
393 static void	run_newassoc(struct ieee80211_node *, int);
394 static void	run_recv_mgmt(struct ieee80211_node *, struct mbuf *, int,
395 		    const struct ieee80211_rx_stats *, int, int);
396 static void	run_rx_frame(struct run_softc *, struct mbuf *, uint32_t);
397 static void	run_tx_free(struct run_endpoint_queue *pq,
398 		    struct run_tx_data *, int);
399 static void	run_set_tx_desc(struct run_softc *, struct run_tx_data *);
400 static int	run_tx(struct run_softc *, struct mbuf *,
401 		    struct ieee80211_node *);
402 static int	run_tx_mgt(struct run_softc *, struct mbuf *,
403 		    struct ieee80211_node *);
404 static int	run_sendprot(struct run_softc *, const struct mbuf *,
405 		    struct ieee80211_node *, int, int);
406 static int	run_tx_param(struct run_softc *, struct mbuf *,
407 		    struct ieee80211_node *,
408 		    const struct ieee80211_bpf_params *);
409 static int	run_raw_xmit(struct ieee80211_node *, struct mbuf *,
410 		    const struct ieee80211_bpf_params *);
411 static int	run_transmit(struct ieee80211com *, struct mbuf *);
412 static void	run_start(struct run_softc *);
413 static void	run_parent(struct ieee80211com *);
414 static void	run_iq_calib(struct run_softc *, u_int);
415 static void	run_set_agc(struct run_softc *, uint8_t);
416 static void	run_select_chan_group(struct run_softc *, int);
417 static void	run_set_rx_antenna(struct run_softc *, int);
418 static void	run_rt2870_set_chan(struct run_softc *, u_int);
419 static void	run_rt3070_set_chan(struct run_softc *, u_int);
420 static void	run_rt3572_set_chan(struct run_softc *, u_int);
421 static void	run_rt3593_set_chan(struct run_softc *, u_int);
422 static void	run_rt5390_set_chan(struct run_softc *, u_int);
423 static void	run_rt5592_set_chan(struct run_softc *, u_int);
424 static int	run_set_chan(struct run_softc *, struct ieee80211_channel *);
425 static void	run_set_channel(struct ieee80211com *);
426 static void	run_getradiocaps(struct ieee80211com *, int, int *,
427 		    struct ieee80211_channel[]);
428 static void	run_scan_start(struct ieee80211com *);
429 static void	run_scan_end(struct ieee80211com *);
430 static void	run_update_beacon(struct ieee80211vap *, int);
431 static void	run_update_beacon_cb(void *);
432 static void	run_updateprot(struct ieee80211com *);
433 static void	run_updateprot_cb(void *);
434 static void	run_usb_timeout_cb(void *);
435 static void	run_reset_livelock(struct run_softc *);
436 static void	run_enable_tsf_sync(struct run_softc *);
437 static void	run_enable_tsf(struct run_softc *);
438 static void	run_get_tsf(struct run_softc *, uint64_t *);
439 static void	run_enable_mrr(struct run_softc *);
440 static void	run_set_txpreamble(struct run_softc *);
441 static void	run_set_basicrates(struct run_softc *);
442 static void	run_set_leds(struct run_softc *, uint16_t);
443 static void	run_set_bssid(struct run_softc *, const uint8_t *);
444 static void	run_set_macaddr(struct run_softc *, const uint8_t *);
445 static void	run_updateslot(struct ieee80211com *);
446 static void	run_updateslot_cb(void *);
447 static void	run_update_mcast(struct ieee80211com *);
448 static int8_t	run_rssi2dbm(struct run_softc *, uint8_t, uint8_t);
449 static void	run_update_promisc_locked(struct run_softc *);
450 static void	run_update_promisc(struct ieee80211com *);
451 static void	run_rt5390_bbp_init(struct run_softc *);
452 static int	run_bbp_init(struct run_softc *);
453 static int	run_rt3070_rf_init(struct run_softc *);
454 static void	run_rt3593_rf_init(struct run_softc *);
455 static void	run_rt5390_rf_init(struct run_softc *);
456 static int	run_rt3070_filter_calib(struct run_softc *, uint8_t, uint8_t,
457 		    uint8_t *);
458 static void	run_rt3070_rf_setup(struct run_softc *);
459 static void	run_rt3593_rf_setup(struct run_softc *);
460 static void	run_rt5390_rf_setup(struct run_softc *);
461 static int	run_txrx_enable(struct run_softc *);
462 static void	run_adjust_freq_offset(struct run_softc *);
463 static void	run_init_locked(struct run_softc *);
464 static void	run_stop(void *);
465 static void	run_delay(struct run_softc *, u_int);
466 
467 static eventhandler_tag run_etag;
468 
469 static const struct rt2860_rate {
470 	uint8_t		rate;
471 	uint8_t		mcs;
472 	enum		ieee80211_phytype phy;
473 	uint8_t		ctl_ridx;
474 	uint16_t	sp_ack_dur;
475 	uint16_t	lp_ack_dur;
476 } rt2860_rates[] = {
477 	{   2, 0, IEEE80211_T_DS,   0, 314, 314 },
478 	{   4, 1, IEEE80211_T_DS,   1, 258, 162 },
479 	{  11, 2, IEEE80211_T_DS,   2, 223, 127 },
480 	{  22, 3, IEEE80211_T_DS,   3, 213, 117 },
481 	{  12, 0, IEEE80211_T_OFDM, 4,  60,  60 },
482 	{  18, 1, IEEE80211_T_OFDM, 4,  52,  52 },
483 	{  24, 2, IEEE80211_T_OFDM, 6,  48,  48 },
484 	{  36, 3, IEEE80211_T_OFDM, 6,  44,  44 },
485 	{  48, 4, IEEE80211_T_OFDM, 8,  44,  44 },
486 	{  72, 5, IEEE80211_T_OFDM, 8,  40,  40 },
487 	{  96, 6, IEEE80211_T_OFDM, 8,  40,  40 },
488 	{ 108, 7, IEEE80211_T_OFDM, 8,  40,  40 }
489 };
490 
491 static const struct {
492 	uint16_t	reg;
493 	uint32_t	val;
494 } rt2870_def_mac[] = {
495 	RT2870_DEF_MAC
496 };
497 
498 static const struct {
499 	uint8_t	reg;
500 	uint8_t	val;
501 } rt2860_def_bbp[] = {
502 	RT2860_DEF_BBP
503 },rt5390_def_bbp[] = {
504 	RT5390_DEF_BBP
505 },rt5592_def_bbp[] = {
506 	RT5592_DEF_BBP
507 };
508 
509 /*
510  * Default values for BBP register R196 for RT5592.
511  */
512 static const uint8_t rt5592_bbp_r196[] = {
513 	0xe0, 0x1f, 0x38, 0x32, 0x08, 0x28, 0x19, 0x0a, 0xff, 0x00,
514 	0x16, 0x10, 0x10, 0x0b, 0x36, 0x2c, 0x26, 0x24, 0x42, 0x36,
515 	0x30, 0x2d, 0x4c, 0x46, 0x3d, 0x40, 0x3e, 0x42, 0x3d, 0x40,
516 	0x3c, 0x34, 0x2c, 0x2f, 0x3c, 0x35, 0x2e, 0x2a, 0x49, 0x41,
517 	0x36, 0x31, 0x30, 0x30, 0x0e, 0x0d, 0x28, 0x21, 0x1c, 0x16,
518 	0x50, 0x4a, 0x43, 0x40, 0x10, 0x10, 0x10, 0x10, 0x00, 0x00,
519 	0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
520 	0x00, 0x00, 0x7d, 0x14, 0x32, 0x2c, 0x36, 0x4c, 0x43, 0x2c,
521 	0x2e, 0x36, 0x30, 0x6e
522 };
523 
524 static const struct rfprog {
525 	uint8_t		chan;
526 	uint32_t	r1, r2, r3, r4;
527 } rt2860_rf2850[] = {
528 	RT2860_RF2850
529 };
530 
531 struct {
532 	uint8_t	n, r, k;
533 } rt3070_freqs[] = {
534 	RT3070_RF3052
535 };
536 
537 static const struct rt5592_freqs {
538 	uint16_t	n;
539 	uint8_t		k, m, r;
540 } rt5592_freqs_20mhz[] = {
541 	RT5592_RF5592_20MHZ
542 },rt5592_freqs_40mhz[] = {
543 	RT5592_RF5592_40MHZ
544 };
545 
546 static const struct {
547 	uint8_t	reg;
548 	uint8_t	val;
549 } rt3070_def_rf[] = {
550 	RT3070_DEF_RF
551 },rt3572_def_rf[] = {
552 	RT3572_DEF_RF
553 },rt3593_def_rf[] = {
554 	RT3593_DEF_RF
555 },rt5390_def_rf[] = {
556 	RT5390_DEF_RF
557 },rt5392_def_rf[] = {
558 	RT5392_DEF_RF
559 },rt5592_def_rf[] = {
560 	RT5592_DEF_RF
561 },rt5592_2ghz_def_rf[] = {
562 	RT5592_2GHZ_DEF_RF
563 },rt5592_5ghz_def_rf[] = {
564 	RT5592_5GHZ_DEF_RF
565 };
566 
567 static const struct {
568 	u_int	firstchan;
569 	u_int	lastchan;
570 	uint8_t	reg;
571 	uint8_t	val;
572 } rt5592_chan_5ghz[] = {
573 	RT5592_CHAN_5GHZ
574 };
575 
576 static const struct usb_config run_config[RUN_N_XFER] = {
577     [RUN_BULK_TX_BE] = {
578 	.type = UE_BULK,
579 	.endpoint = UE_ADDR_ANY,
580 	.ep_index = 0,
581 	.direction = UE_DIR_OUT,
582 	.bufsize = RUN_MAX_TXSZ,
583 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
584 	.callback = run_bulk_tx_callback0,
585 	.timeout = 5000,	/* ms */
586     },
587     [RUN_BULK_TX_BK] = {
588 	.type = UE_BULK,
589 	.endpoint = UE_ADDR_ANY,
590 	.direction = UE_DIR_OUT,
591 	.ep_index = 1,
592 	.bufsize = RUN_MAX_TXSZ,
593 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
594 	.callback = run_bulk_tx_callback1,
595 	.timeout = 5000,	/* ms */
596     },
597     [RUN_BULK_TX_VI] = {
598 	.type = UE_BULK,
599 	.endpoint = UE_ADDR_ANY,
600 	.direction = UE_DIR_OUT,
601 	.ep_index = 2,
602 	.bufsize = RUN_MAX_TXSZ,
603 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
604 	.callback = run_bulk_tx_callback2,
605 	.timeout = 5000,	/* ms */
606     },
607     [RUN_BULK_TX_VO] = {
608 	.type = UE_BULK,
609 	.endpoint = UE_ADDR_ANY,
610 	.direction = UE_DIR_OUT,
611 	.ep_index = 3,
612 	.bufsize = RUN_MAX_TXSZ,
613 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,},
614 	.callback = run_bulk_tx_callback3,
615 	.timeout = 5000,	/* ms */
616     },
617     [RUN_BULK_TX_HCCA] = {
618 	.type = UE_BULK,
619 	.endpoint = UE_ADDR_ANY,
620 	.direction = UE_DIR_OUT,
621 	.ep_index = 4,
622 	.bufsize = RUN_MAX_TXSZ,
623 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,},
624 	.callback = run_bulk_tx_callback4,
625 	.timeout = 5000,	/* ms */
626     },
627     [RUN_BULK_TX_PRIO] = {
628 	.type = UE_BULK,
629 	.endpoint = UE_ADDR_ANY,
630 	.direction = UE_DIR_OUT,
631 	.ep_index = 5,
632 	.bufsize = RUN_MAX_TXSZ,
633 	.flags = {.pipe_bof = 1,.force_short_xfer = 1,.no_pipe_ok = 1,},
634 	.callback = run_bulk_tx_callback5,
635 	.timeout = 5000,	/* ms */
636     },
637     [RUN_BULK_RX] = {
638 	.type = UE_BULK,
639 	.endpoint = UE_ADDR_ANY,
640 	.direction = UE_DIR_IN,
641 	.bufsize = RUN_MAX_RXSZ,
642 	.flags = {.pipe_bof = 1,.short_xfer_ok = 1,},
643 	.callback = run_bulk_rx_callback,
644     }
645 };
646 
647 static void
648 run_autoinst(void *arg, struct usb_device *udev,
649     struct usb_attach_arg *uaa)
650 {
651 	struct usb_interface *iface;
652 	struct usb_interface_descriptor *id;
653 
654 	if (uaa->dev_state != UAA_DEV_READY)
655 		return;
656 
657 	iface = usbd_get_iface(udev, 0);
658 	if (iface == NULL)
659 		return;
660 	id = iface->idesc;
661 	if (id == NULL || id->bInterfaceClass != UICLASS_MASS)
662 		return;
663 	if (usbd_lookup_id_by_uaa(run_devs, sizeof(run_devs), uaa))
664 		return;
665 
666 	if (usb_msc_eject(udev, 0, MSC_EJECT_STOPUNIT) == 0)
667 		uaa->dev_state = UAA_DEV_EJECTING;
668 }
669 
670 static int
671 run_driver_loaded(struct module *mod, int what, void *arg)
672 {
673 	switch (what) {
674 	case MOD_LOAD:
675 		run_etag = EVENTHANDLER_REGISTER(usb_dev_configured,
676 		    run_autoinst, NULL, EVENTHANDLER_PRI_ANY);
677 		break;
678 	case MOD_UNLOAD:
679 		EVENTHANDLER_DEREGISTER(usb_dev_configured, run_etag);
680 		break;
681 	default:
682 		return (EOPNOTSUPP);
683 	}
684 	return (0);
685 }
686 
687 static int
688 run_match(device_t self)
689 {
690 	struct usb_attach_arg *uaa = device_get_ivars(self);
691 
692 	if (uaa->usb_mode != USB_MODE_HOST)
693 		return (ENXIO);
694 	if (uaa->info.bConfigIndex != 0)
695 		return (ENXIO);
696 	if (uaa->info.bIfaceIndex != RT2860_IFACE_INDEX)
697 		return (ENXIO);
698 
699 	return (usbd_lookup_id_by_uaa(run_devs, sizeof(run_devs), uaa));
700 }
701 
702 static int
703 run_attach(device_t self)
704 {
705 	struct run_softc *sc = device_get_softc(self);
706 	struct usb_attach_arg *uaa = device_get_ivars(self);
707 	struct ieee80211com *ic = &sc->sc_ic;
708 	uint32_t ver;
709 	uint8_t iface_index;
710 	int ntries, error;
711 
712 	device_set_usb_desc(self);
713 	sc->sc_udev = uaa->device;
714 	sc->sc_dev = self;
715 	if (USB_GET_DRIVER_INFO(uaa) != RUN_EJECT)
716 		sc->sc_flags |= RUN_FLAG_FWLOAD_NEEDED;
717 
718 	mtx_init(&sc->sc_mtx, device_get_nameunit(sc->sc_dev),
719 	    MTX_NETWORK_LOCK, MTX_DEF);
720 	mbufq_init(&sc->sc_snd, ifqmaxlen);
721 
722 	iface_index = RT2860_IFACE_INDEX;
723 
724 	error = usbd_transfer_setup(uaa->device, &iface_index,
725 	    sc->sc_xfer, run_config, RUN_N_XFER, sc, &sc->sc_mtx);
726 	if (error) {
727 		device_printf(self, "could not allocate USB transfers, "
728 		    "err=%s\n", usbd_errstr(error));
729 		goto detach;
730 	}
731 
732 	RUN_LOCK(sc);
733 
734 	/* wait for the chip to settle */
735 	for (ntries = 0; ntries < 100; ntries++) {
736 		if (run_read(sc, RT2860_ASIC_VER_ID, &ver) != 0) {
737 			RUN_UNLOCK(sc);
738 			goto detach;
739 		}
740 		if (ver != 0 && ver != 0xffffffff)
741 			break;
742 		run_delay(sc, 10);
743 	}
744 	if (ntries == 100) {
745 		device_printf(sc->sc_dev,
746 		    "timeout waiting for NIC to initialize\n");
747 		RUN_UNLOCK(sc);
748 		goto detach;
749 	}
750 	sc->mac_ver = ver >> 16;
751 	sc->mac_rev = ver & 0xffff;
752 
753 	/* retrieve RF rev. no and various other things from EEPROM */
754 	run_read_eeprom(sc);
755 
756 	device_printf(sc->sc_dev,
757 	    "MAC/BBP RT%04X (rev 0x%04X), RF %s (MIMO %dT%dR), address %s\n",
758 	    sc->mac_ver, sc->mac_rev, run_get_rf(sc->rf_rev),
759 	    sc->ntxchains, sc->nrxchains, ether_sprintf(ic->ic_macaddr));
760 
761 	RUN_UNLOCK(sc);
762 
763 	ic->ic_softc = sc;
764 	ic->ic_name = device_get_nameunit(self);
765 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
766 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
767 
768 	/* set device capabilities */
769 	ic->ic_caps =
770 	    IEEE80211_C_STA |		/* station mode supported */
771 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
772 	    IEEE80211_C_IBSS |
773 	    IEEE80211_C_HOSTAP |
774 	    IEEE80211_C_WDS |		/* 4-address traffic works */
775 	    IEEE80211_C_MBSS |
776 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
777 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
778 	    IEEE80211_C_WME |		/* WME */
779 	    IEEE80211_C_WPA;		/* WPA1|WPA2(RSN) */
780 
781 	ic->ic_cryptocaps =
782 	    IEEE80211_CRYPTO_WEP |
783 	    IEEE80211_CRYPTO_AES_CCM |
784 	    IEEE80211_CRYPTO_TKIPMIC |
785 	    IEEE80211_CRYPTO_TKIP;
786 
787 	ic->ic_flags |= IEEE80211_F_DATAPAD;
788 	ic->ic_flags_ext |= IEEE80211_FEXT_SWBMISS;
789 
790 	run_getradiocaps(ic, IEEE80211_CHAN_MAX, &ic->ic_nchans,
791 	    ic->ic_channels);
792 
793 	ieee80211_ifattach(ic);
794 
795 	ic->ic_scan_start = run_scan_start;
796 	ic->ic_scan_end = run_scan_end;
797 	ic->ic_set_channel = run_set_channel;
798 	ic->ic_getradiocaps = run_getradiocaps;
799 	ic->ic_node_alloc = run_node_alloc;
800 	ic->ic_newassoc = run_newassoc;
801 	ic->ic_updateslot = run_updateslot;
802 	ic->ic_update_mcast = run_update_mcast;
803 	ic->ic_wme.wme_update = run_wme_update;
804 	ic->ic_raw_xmit = run_raw_xmit;
805 	ic->ic_update_promisc = run_update_promisc;
806 	ic->ic_vap_create = run_vap_create;
807 	ic->ic_vap_delete = run_vap_delete;
808 	ic->ic_transmit = run_transmit;
809 	ic->ic_parent = run_parent;
810 
811 	ieee80211_radiotap_attach(ic,
812 	    &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
813 		RUN_TX_RADIOTAP_PRESENT,
814 	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
815 		RUN_RX_RADIOTAP_PRESENT);
816 
817 	TASK_INIT(&sc->cmdq_task, 0, run_cmdq_cb, sc);
818 	TASK_INIT(&sc->ratectl_task, 0, run_ratectl_cb, sc);
819 	usb_callout_init_mtx(&sc->ratectl_ch, &sc->sc_mtx, 0);
820 
821 	if (bootverbose)
822 		ieee80211_announce(ic);
823 
824 	return (0);
825 
826 detach:
827 	run_detach(self);
828 	return (ENXIO);
829 }
830 
831 static void
832 run_drain_mbufq(struct run_softc *sc)
833 {
834 	struct mbuf *m;
835 	struct ieee80211_node *ni;
836 
837 	RUN_LOCK_ASSERT(sc, MA_OWNED);
838 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
839 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
840 		m->m_pkthdr.rcvif = NULL;
841 		ieee80211_free_node(ni);
842 		m_freem(m);
843 	}
844 }
845 
846 static int
847 run_detach(device_t self)
848 {
849 	struct run_softc *sc = device_get_softc(self);
850 	struct ieee80211com *ic = &sc->sc_ic;
851 	int i;
852 
853 	RUN_LOCK(sc);
854 	sc->sc_detached = 1;
855 	RUN_UNLOCK(sc);
856 
857 	/* stop all USB transfers */
858 	usbd_transfer_unsetup(sc->sc_xfer, RUN_N_XFER);
859 
860 	RUN_LOCK(sc);
861 	sc->ratectl_run = RUN_RATECTL_OFF;
862 	sc->cmdq_run = sc->cmdq_key_set = RUN_CMDQ_ABORT;
863 
864 	/* free TX list, if any */
865 	for (i = 0; i != RUN_EP_QUEUES; i++)
866 		run_unsetup_tx_list(sc, &sc->sc_epq[i]);
867 
868 	/* Free TX queue */
869 	run_drain_mbufq(sc);
870 	RUN_UNLOCK(sc);
871 
872 	if (sc->sc_ic.ic_softc == sc) {
873 		/* drain tasks */
874 		usb_callout_drain(&sc->ratectl_ch);
875 		ieee80211_draintask(ic, &sc->cmdq_task);
876 		ieee80211_draintask(ic, &sc->ratectl_task);
877 		ieee80211_ifdetach(ic);
878 	}
879 
880 	mtx_destroy(&sc->sc_mtx);
881 
882 	return (0);
883 }
884 
885 static struct ieee80211vap *
886 run_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
887     enum ieee80211_opmode opmode, int flags,
888     const uint8_t bssid[IEEE80211_ADDR_LEN],
889     const uint8_t mac[IEEE80211_ADDR_LEN])
890 {
891 	struct run_softc *sc = ic->ic_softc;
892 	struct run_vap *rvp;
893 	struct ieee80211vap *vap;
894 	int i;
895 
896 	if (sc->rvp_cnt >= RUN_VAP_MAX) {
897 		device_printf(sc->sc_dev, "number of VAPs maxed out\n");
898 		return (NULL);
899 	}
900 
901 	switch (opmode) {
902 	case IEEE80211_M_STA:
903 		/* enable s/w bmiss handling for sta mode */
904 		flags |= IEEE80211_CLONE_NOBEACONS;
905 		/* fall though */
906 	case IEEE80211_M_IBSS:
907 	case IEEE80211_M_MONITOR:
908 	case IEEE80211_M_HOSTAP:
909 	case IEEE80211_M_MBSS:
910 		/* other than WDS vaps, only one at a time */
911 		if (!TAILQ_EMPTY(&ic->ic_vaps))
912 			return (NULL);
913 		break;
914 	case IEEE80211_M_WDS:
915 		TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next){
916 			if(vap->iv_opmode != IEEE80211_M_HOSTAP)
917 				continue;
918 			/* WDS vap's always share the local mac address. */
919 			flags &= ~IEEE80211_CLONE_BSSID;
920 			break;
921 		}
922 		if (vap == NULL) {
923 			device_printf(sc->sc_dev,
924 			    "wds only supported in ap mode\n");
925 			return (NULL);
926 		}
927 		break;
928 	default:
929 		device_printf(sc->sc_dev, "unknown opmode %d\n", opmode);
930 		return (NULL);
931 	}
932 
933 	rvp = malloc(sizeof(struct run_vap), M_80211_VAP, M_WAITOK | M_ZERO);
934 	vap = &rvp->vap;
935 
936 	if (ieee80211_vap_setup(ic, vap, name, unit, opmode, flags,
937 	    bssid) != 0) {
938 		/* out of memory */
939 		free(rvp, M_80211_VAP);
940 		return (NULL);
941 	}
942 
943 	vap->iv_update_beacon = run_update_beacon;
944 	vap->iv_max_aid = RT2870_WCID_MAX;
945 	/*
946 	 * To delete the right key from h/w, we need wcid.
947 	 * Luckily, there is unused space in ieee80211_key{}, wk_pad,
948 	 * and matching wcid will be written into there. So, cast
949 	 * some spells to remove 'const' from ieee80211_key{}
950 	 */
951 	vap->iv_key_delete = (void *)run_key_delete;
952 	vap->iv_key_set = (void *)run_key_set;
953 
954 	/* override state transition machine */
955 	rvp->newstate = vap->iv_newstate;
956 	vap->iv_newstate = run_newstate;
957 	if (opmode == IEEE80211_M_IBSS) {
958 		rvp->recv_mgmt = vap->iv_recv_mgmt;
959 		vap->iv_recv_mgmt = run_recv_mgmt;
960 	}
961 
962 	ieee80211_ratectl_init(vap);
963 	ieee80211_ratectl_setinterval(vap, 1000 /* 1 sec */);
964 
965 	/* complete setup */
966 	ieee80211_vap_attach(vap, run_media_change, ieee80211_media_status,
967 	    mac);
968 
969 	/* make sure id is always unique */
970 	for (i = 0; i < RUN_VAP_MAX; i++) {
971 		if((sc->rvp_bmap & 1 << i) == 0){
972 			sc->rvp_bmap |= 1 << i;
973 			rvp->rvp_id = i;
974 			break;
975 		}
976 	}
977 	if (sc->rvp_cnt++ == 0)
978 		ic->ic_opmode = opmode;
979 
980 	if (opmode == IEEE80211_M_HOSTAP)
981 		sc->cmdq_run = RUN_CMDQ_GO;
982 
983 	DPRINTF("rvp_id=%d bmap=%x rvp_cnt=%d\n",
984 	    rvp->rvp_id, sc->rvp_bmap, sc->rvp_cnt);
985 
986 	return (vap);
987 }
988 
989 static void
990 run_vap_delete(struct ieee80211vap *vap)
991 {
992 	struct run_vap *rvp = RUN_VAP(vap);
993 	struct ieee80211com *ic;
994 	struct run_softc *sc;
995 	uint8_t rvp_id;
996 
997 	if (vap == NULL)
998 		return;
999 
1000 	ic = vap->iv_ic;
1001 	sc = ic->ic_softc;
1002 
1003 	RUN_LOCK(sc);
1004 
1005 	m_freem(rvp->beacon_mbuf);
1006 	rvp->beacon_mbuf = NULL;
1007 
1008 	rvp_id = rvp->rvp_id;
1009 	sc->ratectl_run &= ~(1 << rvp_id);
1010 	sc->rvp_bmap &= ~(1 << rvp_id);
1011 	run_set_region_4(sc, RT2860_SKEY(rvp_id, 0), 0, 128);
1012 	run_set_region_4(sc, RT2860_BCN_BASE(rvp_id), 0, 512);
1013 	--sc->rvp_cnt;
1014 
1015 	DPRINTF("vap=%p rvp_id=%d bmap=%x rvp_cnt=%d\n",
1016 	    vap, rvp_id, sc->rvp_bmap, sc->rvp_cnt);
1017 
1018 	RUN_UNLOCK(sc);
1019 
1020 	ieee80211_ratectl_deinit(vap);
1021 	ieee80211_vap_detach(vap);
1022 	free(rvp, M_80211_VAP);
1023 }
1024 
1025 /*
1026  * There are numbers of functions need to be called in context thread.
1027  * Rather than creating taskqueue event for each of those functions,
1028  * here is all-for-one taskqueue callback function. This function
1029  * guarantees deferred functions are executed in the same order they
1030  * were enqueued.
1031  * '& RUN_CMDQ_MASQ' is to loop cmdq[].
1032  */
1033 static void
1034 run_cmdq_cb(void *arg, int pending)
1035 {
1036 	struct run_softc *sc = arg;
1037 	uint8_t i;
1038 
1039 	/* call cmdq[].func locked */
1040 	RUN_LOCK(sc);
1041 	for (i = sc->cmdq_exec; sc->cmdq[i].func && pending;
1042 	    i = sc->cmdq_exec, pending--) {
1043 		DPRINTFN(6, "cmdq_exec=%d pending=%d\n", i, pending);
1044 		if (sc->cmdq_run == RUN_CMDQ_GO) {
1045 			/*
1046 			 * If arg0 is NULL, callback func needs more
1047 			 * than one arg. So, pass ptr to cmdq struct.
1048 			 */
1049 			if (sc->cmdq[i].arg0)
1050 				sc->cmdq[i].func(sc->cmdq[i].arg0);
1051 			else
1052 				sc->cmdq[i].func(&sc->cmdq[i]);
1053 		}
1054 		sc->cmdq[i].arg0 = NULL;
1055 		sc->cmdq[i].func = NULL;
1056 		sc->cmdq_exec++;
1057 		sc->cmdq_exec &= RUN_CMDQ_MASQ;
1058 	}
1059 	RUN_UNLOCK(sc);
1060 }
1061 
1062 static void
1063 run_setup_tx_list(struct run_softc *sc, struct run_endpoint_queue *pq)
1064 {
1065 	struct run_tx_data *data;
1066 
1067 	memset(pq, 0, sizeof(*pq));
1068 
1069 	STAILQ_INIT(&pq->tx_qh);
1070 	STAILQ_INIT(&pq->tx_fh);
1071 
1072 	for (data = &pq->tx_data[0];
1073 	    data < &pq->tx_data[RUN_TX_RING_COUNT]; data++) {
1074 		data->sc = sc;
1075 		STAILQ_INSERT_TAIL(&pq->tx_fh, data, next);
1076 	}
1077 	pq->tx_nfree = RUN_TX_RING_COUNT;
1078 }
1079 
1080 static void
1081 run_unsetup_tx_list(struct run_softc *sc, struct run_endpoint_queue *pq)
1082 {
1083 	struct run_tx_data *data;
1084 
1085 	/* make sure any subsequent use of the queues will fail */
1086 	pq->tx_nfree = 0;
1087 	STAILQ_INIT(&pq->tx_fh);
1088 	STAILQ_INIT(&pq->tx_qh);
1089 
1090 	/* free up all node references and mbufs */
1091 	for (data = &pq->tx_data[0];
1092 	    data < &pq->tx_data[RUN_TX_RING_COUNT]; data++) {
1093 		if (data->m != NULL) {
1094 			m_freem(data->m);
1095 			data->m = NULL;
1096 		}
1097 		if (data->ni != NULL) {
1098 			ieee80211_free_node(data->ni);
1099 			data->ni = NULL;
1100 		}
1101 	}
1102 }
1103 
1104 static int
1105 run_load_microcode(struct run_softc *sc)
1106 {
1107 	usb_device_request_t req;
1108 	const struct firmware *fw;
1109 	const u_char *base;
1110 	uint32_t tmp;
1111 	int ntries, error;
1112 	const uint64_t *temp;
1113 	uint64_t bytes;
1114 
1115 	RUN_UNLOCK(sc);
1116 	fw = firmware_get("runfw");
1117 	RUN_LOCK(sc);
1118 	if (fw == NULL) {
1119 		device_printf(sc->sc_dev,
1120 		    "failed loadfirmware of file %s\n", "runfw");
1121 		return ENOENT;
1122 	}
1123 
1124 	if (fw->datasize != 8192) {
1125 		device_printf(sc->sc_dev,
1126 		    "invalid firmware size (should be 8KB)\n");
1127 		error = EINVAL;
1128 		goto fail;
1129 	}
1130 
1131 	/*
1132 	 * RT3071/RT3072 use a different firmware
1133 	 * run-rt2870 (8KB) contains both,
1134 	 * first half (4KB) is for rt2870,
1135 	 * last half is for rt3071.
1136 	 */
1137 	base = fw->data;
1138 	if ((sc->mac_ver) != 0x2860 &&
1139 	    (sc->mac_ver) != 0x2872 &&
1140 	    (sc->mac_ver) != 0x3070) {
1141 		base += 4096;
1142 	}
1143 
1144 	/* cheap sanity check */
1145 	temp = fw->data;
1146 	bytes = *temp;
1147 	if (bytes != be64toh(0xffffff0210280210ULL)) {
1148 		device_printf(sc->sc_dev, "firmware checksum failed\n");
1149 		error = EINVAL;
1150 		goto fail;
1151 	}
1152 
1153 	/* write microcode image */
1154 	if (sc->sc_flags & RUN_FLAG_FWLOAD_NEEDED) {
1155 		run_write_region_1(sc, RT2870_FW_BASE, base, 4096);
1156 		run_write(sc, RT2860_H2M_MAILBOX_CID, 0xffffffff);
1157 		run_write(sc, RT2860_H2M_MAILBOX_STATUS, 0xffffffff);
1158 	}
1159 
1160 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1161 	req.bRequest = RT2870_RESET;
1162 	USETW(req.wValue, 8);
1163 	USETW(req.wIndex, 0);
1164 	USETW(req.wLength, 0);
1165 	if ((error = usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, NULL))
1166 	    != 0) {
1167 		device_printf(sc->sc_dev, "firmware reset failed\n");
1168 		goto fail;
1169 	}
1170 
1171 	run_delay(sc, 10);
1172 
1173 	run_write(sc, RT2860_H2M_BBPAGENT, 0);
1174 	run_write(sc, RT2860_H2M_MAILBOX, 0);
1175 	run_write(sc, RT2860_H2M_INTSRC, 0);
1176 	if ((error = run_mcu_cmd(sc, RT2860_MCU_CMD_RFRESET, 0)) != 0)
1177 		goto fail;
1178 
1179 	/* wait until microcontroller is ready */
1180 	for (ntries = 0; ntries < 1000; ntries++) {
1181 		if ((error = run_read(sc, RT2860_SYS_CTRL, &tmp)) != 0)
1182 			goto fail;
1183 		if (tmp & RT2860_MCU_READY)
1184 			break;
1185 		run_delay(sc, 10);
1186 	}
1187 	if (ntries == 1000) {
1188 		device_printf(sc->sc_dev,
1189 		    "timeout waiting for MCU to initialize\n");
1190 		error = ETIMEDOUT;
1191 		goto fail;
1192 	}
1193 	device_printf(sc->sc_dev, "firmware %s ver. %u.%u loaded\n",
1194 	    (base == fw->data) ? "RT2870" : "RT3071",
1195 	    *(base + 4092), *(base + 4093));
1196 
1197 fail:
1198 	firmware_put(fw, FIRMWARE_UNLOAD);
1199 	return (error);
1200 }
1201 
1202 static int
1203 run_reset(struct run_softc *sc)
1204 {
1205 	usb_device_request_t req;
1206 
1207 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1208 	req.bRequest = RT2870_RESET;
1209 	USETW(req.wValue, 1);
1210 	USETW(req.wIndex, 0);
1211 	USETW(req.wLength, 0);
1212 	return (usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, NULL));
1213 }
1214 
1215 static usb_error_t
1216 run_do_request(struct run_softc *sc,
1217     struct usb_device_request *req, void *data)
1218 {
1219 	usb_error_t err;
1220 	int ntries = 10;
1221 
1222 	RUN_LOCK_ASSERT(sc, MA_OWNED);
1223 
1224 	while (ntries--) {
1225 		err = usbd_do_request_flags(sc->sc_udev, &sc->sc_mtx,
1226 		    req, data, 0, NULL, 250 /* ms */);
1227 		if (err == 0)
1228 			break;
1229 		DPRINTFN(1, "Control request failed, %s (retrying)\n",
1230 		    usbd_errstr(err));
1231 		run_delay(sc, 10);
1232 	}
1233 	return (err);
1234 }
1235 
1236 static int
1237 run_read(struct run_softc *sc, uint16_t reg, uint32_t *val)
1238 {
1239 	uint32_t tmp;
1240 	int error;
1241 
1242 	error = run_read_region_1(sc, reg, (uint8_t *)&tmp, sizeof tmp);
1243 	if (error == 0)
1244 		*val = le32toh(tmp);
1245 	else
1246 		*val = 0xffffffff;
1247 	return (error);
1248 }
1249 
1250 static int
1251 run_read_region_1(struct run_softc *sc, uint16_t reg, uint8_t *buf, int len)
1252 {
1253 	usb_device_request_t req;
1254 
1255 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1256 	req.bRequest = RT2870_READ_REGION_1;
1257 	USETW(req.wValue, 0);
1258 	USETW(req.wIndex, reg);
1259 	USETW(req.wLength, len);
1260 
1261 	return (run_do_request(sc, &req, buf));
1262 }
1263 
1264 static int
1265 run_write_2(struct run_softc *sc, uint16_t reg, uint16_t val)
1266 {
1267 	usb_device_request_t req;
1268 
1269 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1270 	req.bRequest = RT2870_WRITE_2;
1271 	USETW(req.wValue, val);
1272 	USETW(req.wIndex, reg);
1273 	USETW(req.wLength, 0);
1274 
1275 	return (run_do_request(sc, &req, NULL));
1276 }
1277 
1278 static int
1279 run_write(struct run_softc *sc, uint16_t reg, uint32_t val)
1280 {
1281 	int error;
1282 
1283 	if ((error = run_write_2(sc, reg, val & 0xffff)) == 0)
1284 		error = run_write_2(sc, reg + 2, val >> 16);
1285 	return (error);
1286 }
1287 
1288 static int
1289 run_write_region_1(struct run_softc *sc, uint16_t reg, const uint8_t *buf,
1290     int len)
1291 {
1292 #if 1
1293 	int i, error = 0;
1294 	/*
1295 	 * NB: the WRITE_REGION_1 command is not stable on RT2860.
1296 	 * We thus issue multiple WRITE_2 commands instead.
1297 	 */
1298 	KASSERT((len & 1) == 0, ("run_write_region_1: Data too long.\n"));
1299 	for (i = 0; i < len && error == 0; i += 2)
1300 		error = run_write_2(sc, reg + i, buf[i] | buf[i + 1] << 8);
1301 	return (error);
1302 #else
1303 	usb_device_request_t req;
1304 	int error = 0;
1305 
1306 	/*
1307 	 * NOTE: It appears the WRITE_REGION_1 command cannot be
1308 	 * passed a huge amount of data, which will crash the
1309 	 * firmware. Limit amount of data passed to 64-bytes at a
1310 	 * time.
1311 	 */
1312 	while (len > 0) {
1313 		int delta = 64;
1314 		if (delta > len)
1315 			delta = len;
1316 
1317 		req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
1318 		req.bRequest = RT2870_WRITE_REGION_1;
1319 		USETW(req.wValue, 0);
1320 		USETW(req.wIndex, reg);
1321 		USETW(req.wLength, delta);
1322 		error = run_do_request(sc, &req, __DECONST(uint8_t *, buf));
1323 		if (error != 0)
1324 			break;
1325 		reg += delta;
1326 		buf += delta;
1327 		len -= delta;
1328 	}
1329 	return (error);
1330 #endif
1331 }
1332 
1333 static int
1334 run_set_region_4(struct run_softc *sc, uint16_t reg, uint32_t val, int len)
1335 {
1336 	int i, error = 0;
1337 
1338 	KASSERT((len & 3) == 0, ("run_set_region_4: Invalid data length.\n"));
1339 	for (i = 0; i < len && error == 0; i += 4)
1340 		error = run_write(sc, reg + i, val);
1341 	return (error);
1342 }
1343 
1344 static int
1345 run_efuse_read(struct run_softc *sc, uint16_t addr, uint16_t *val, int count)
1346 {
1347 	uint32_t tmp;
1348 	uint16_t reg;
1349 	int error, ntries;
1350 
1351 	if ((error = run_read(sc, RT3070_EFUSE_CTRL, &tmp)) != 0)
1352 		return (error);
1353 
1354 	if (count == 2)
1355 		addr *= 2;
1356 	/*-
1357 	 * Read one 16-byte block into registers EFUSE_DATA[0-3]:
1358 	 * DATA0: F E D C
1359 	 * DATA1: B A 9 8
1360 	 * DATA2: 7 6 5 4
1361 	 * DATA3: 3 2 1 0
1362 	 */
1363 	tmp &= ~(RT3070_EFSROM_MODE_MASK | RT3070_EFSROM_AIN_MASK);
1364 	tmp |= (addr & ~0xf) << RT3070_EFSROM_AIN_SHIFT | RT3070_EFSROM_KICK;
1365 	run_write(sc, RT3070_EFUSE_CTRL, tmp);
1366 	for (ntries = 0; ntries < 100; ntries++) {
1367 		if ((error = run_read(sc, RT3070_EFUSE_CTRL, &tmp)) != 0)
1368 			return (error);
1369 		if (!(tmp & RT3070_EFSROM_KICK))
1370 			break;
1371 		run_delay(sc, 2);
1372 	}
1373 	if (ntries == 100)
1374 		return (ETIMEDOUT);
1375 
1376 	if ((tmp & RT3070_EFUSE_AOUT_MASK) == RT3070_EFUSE_AOUT_MASK) {
1377 		*val = 0xffff;	/* address not found */
1378 		return (0);
1379 	}
1380 	/* determine to which 32-bit register our 16-bit word belongs */
1381 	reg = RT3070_EFUSE_DATA3 - (addr & 0xc);
1382 	if ((error = run_read(sc, reg, &tmp)) != 0)
1383 		return (error);
1384 
1385 	tmp >>= (8 * (addr & 0x3));
1386 	*val = (addr & 1) ? tmp >> 16 : tmp & 0xffff;
1387 
1388 	return (0);
1389 }
1390 
1391 /* Read 16-bit from eFUSE ROM for RT3xxx. */
1392 static int
1393 run_efuse_read_2(struct run_softc *sc, uint16_t addr, uint16_t *val)
1394 {
1395 	return (run_efuse_read(sc, addr, val, 2));
1396 }
1397 
1398 static int
1399 run_eeprom_read_2(struct run_softc *sc, uint16_t addr, uint16_t *val)
1400 {
1401 	usb_device_request_t req;
1402 	uint16_t tmp;
1403 	int error;
1404 
1405 	addr *= 2;
1406 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
1407 	req.bRequest = RT2870_EEPROM_READ;
1408 	USETW(req.wValue, 0);
1409 	USETW(req.wIndex, addr);
1410 	USETW(req.wLength, sizeof(tmp));
1411 
1412 	error = usbd_do_request(sc->sc_udev, &sc->sc_mtx, &req, &tmp);
1413 	if (error == 0)
1414 		*val = le16toh(tmp);
1415 	else
1416 		*val = 0xffff;
1417 	return (error);
1418 }
1419 
1420 static __inline int
1421 run_srom_read(struct run_softc *sc, uint16_t addr, uint16_t *val)
1422 {
1423 	/* either eFUSE ROM or EEPROM */
1424 	return sc->sc_srom_read(sc, addr, val);
1425 }
1426 
1427 static int
1428 run_rt2870_rf_write(struct run_softc *sc, uint32_t val)
1429 {
1430 	uint32_t tmp;
1431 	int error, ntries;
1432 
1433 	for (ntries = 0; ntries < 10; ntries++) {
1434 		if ((error = run_read(sc, RT2860_RF_CSR_CFG0, &tmp)) != 0)
1435 			return (error);
1436 		if (!(tmp & RT2860_RF_REG_CTRL))
1437 			break;
1438 	}
1439 	if (ntries == 10)
1440 		return (ETIMEDOUT);
1441 
1442 	return (run_write(sc, RT2860_RF_CSR_CFG0, val));
1443 }
1444 
1445 static int
1446 run_rt3070_rf_read(struct run_softc *sc, uint8_t reg, uint8_t *val)
1447 {
1448 	uint32_t tmp;
1449 	int error, ntries;
1450 
1451 	for (ntries = 0; ntries < 100; ntries++) {
1452 		if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0)
1453 			return (error);
1454 		if (!(tmp & RT3070_RF_KICK))
1455 			break;
1456 	}
1457 	if (ntries == 100)
1458 		return (ETIMEDOUT);
1459 
1460 	tmp = RT3070_RF_KICK | reg << 8;
1461 	if ((error = run_write(sc, RT3070_RF_CSR_CFG, tmp)) != 0)
1462 		return (error);
1463 
1464 	for (ntries = 0; ntries < 100; ntries++) {
1465 		if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0)
1466 			return (error);
1467 		if (!(tmp & RT3070_RF_KICK))
1468 			break;
1469 	}
1470 	if (ntries == 100)
1471 		return (ETIMEDOUT);
1472 
1473 	*val = tmp & 0xff;
1474 	return (0);
1475 }
1476 
1477 static int
1478 run_rt3070_rf_write(struct run_softc *sc, uint8_t reg, uint8_t val)
1479 {
1480 	uint32_t tmp;
1481 	int error, ntries;
1482 
1483 	for (ntries = 0; ntries < 10; ntries++) {
1484 		if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0)
1485 			return (error);
1486 		if (!(tmp & RT3070_RF_KICK))
1487 			break;
1488 	}
1489 	if (ntries == 10)
1490 		return (ETIMEDOUT);
1491 
1492 	tmp = RT3070_RF_WRITE | RT3070_RF_KICK | reg << 8 | val;
1493 	return (run_write(sc, RT3070_RF_CSR_CFG, tmp));
1494 }
1495 
1496 static int
1497 run_bbp_read(struct run_softc *sc, uint8_t reg, uint8_t *val)
1498 {
1499 	uint32_t tmp;
1500 	int ntries, error;
1501 
1502 	for (ntries = 0; ntries < 10; ntries++) {
1503 		if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0)
1504 			return (error);
1505 		if (!(tmp & RT2860_BBP_CSR_KICK))
1506 			break;
1507 	}
1508 	if (ntries == 10)
1509 		return (ETIMEDOUT);
1510 
1511 	tmp = RT2860_BBP_CSR_READ | RT2860_BBP_CSR_KICK | reg << 8;
1512 	if ((error = run_write(sc, RT2860_BBP_CSR_CFG, tmp)) != 0)
1513 		return (error);
1514 
1515 	for (ntries = 0; ntries < 10; ntries++) {
1516 		if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0)
1517 			return (error);
1518 		if (!(tmp & RT2860_BBP_CSR_KICK))
1519 			break;
1520 	}
1521 	if (ntries == 10)
1522 		return (ETIMEDOUT);
1523 
1524 	*val = tmp & 0xff;
1525 	return (0);
1526 }
1527 
1528 static int
1529 run_bbp_write(struct run_softc *sc, uint8_t reg, uint8_t val)
1530 {
1531 	uint32_t tmp;
1532 	int ntries, error;
1533 
1534 	for (ntries = 0; ntries < 10; ntries++) {
1535 		if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0)
1536 			return (error);
1537 		if (!(tmp & RT2860_BBP_CSR_KICK))
1538 			break;
1539 	}
1540 	if (ntries == 10)
1541 		return (ETIMEDOUT);
1542 
1543 	tmp = RT2860_BBP_CSR_KICK | reg << 8 | val;
1544 	return (run_write(sc, RT2860_BBP_CSR_CFG, tmp));
1545 }
1546 
1547 /*
1548  * Send a command to the 8051 microcontroller unit.
1549  */
1550 static int
1551 run_mcu_cmd(struct run_softc *sc, uint8_t cmd, uint16_t arg)
1552 {
1553 	uint32_t tmp;
1554 	int error, ntries;
1555 
1556 	for (ntries = 0; ntries < 100; ntries++) {
1557 		if ((error = run_read(sc, RT2860_H2M_MAILBOX, &tmp)) != 0)
1558 			return error;
1559 		if (!(tmp & RT2860_H2M_BUSY))
1560 			break;
1561 	}
1562 	if (ntries == 100)
1563 		return ETIMEDOUT;
1564 
1565 	tmp = RT2860_H2M_BUSY | RT2860_TOKEN_NO_INTR << 16 | arg;
1566 	if ((error = run_write(sc, RT2860_H2M_MAILBOX, tmp)) == 0)
1567 		error = run_write(sc, RT2860_HOST_CMD, cmd);
1568 	return (error);
1569 }
1570 
1571 /*
1572  * Add `delta' (signed) to each 4-bit sub-word of a 32-bit word.
1573  * Used to adjust per-rate Tx power registers.
1574  */
1575 static __inline uint32_t
1576 b4inc(uint32_t b32, int8_t delta)
1577 {
1578 	int8_t i, b4;
1579 
1580 	for (i = 0; i < 8; i++) {
1581 		b4 = b32 & 0xf;
1582 		b4 += delta;
1583 		if (b4 < 0)
1584 			b4 = 0;
1585 		else if (b4 > 0xf)
1586 			b4 = 0xf;
1587 		b32 = b32 >> 4 | b4 << 28;
1588 	}
1589 	return (b32);
1590 }
1591 
1592 static const char *
1593 run_get_rf(uint16_t rev)
1594 {
1595 	switch (rev) {
1596 	case RT2860_RF_2820:	return "RT2820";
1597 	case RT2860_RF_2850:	return "RT2850";
1598 	case RT2860_RF_2720:	return "RT2720";
1599 	case RT2860_RF_2750:	return "RT2750";
1600 	case RT3070_RF_3020:	return "RT3020";
1601 	case RT3070_RF_2020:	return "RT2020";
1602 	case RT3070_RF_3021:	return "RT3021";
1603 	case RT3070_RF_3022:	return "RT3022";
1604 	case RT3070_RF_3052:	return "RT3052";
1605 	case RT3593_RF_3053:	return "RT3053";
1606 	case RT5592_RF_5592:	return "RT5592";
1607 	case RT5390_RF_5370:	return "RT5370";
1608 	case RT5390_RF_5372:	return "RT5372";
1609 	}
1610 	return ("unknown");
1611 }
1612 
1613 static void
1614 run_rt3593_get_txpower(struct run_softc *sc)
1615 {
1616 	uint16_t addr, val;
1617 	int i;
1618 
1619 	/* Read power settings for 2GHz channels. */
1620 	for (i = 0; i < 14; i += 2) {
1621 		addr = (sc->ntxchains == 3) ? RT3593_EEPROM_PWR2GHZ_BASE1 :
1622 		    RT2860_EEPROM_PWR2GHZ_BASE1;
1623 		run_srom_read(sc, addr + i / 2, &val);
1624 		sc->txpow1[i + 0] = (int8_t)(val & 0xff);
1625 		sc->txpow1[i + 1] = (int8_t)(val >> 8);
1626 
1627 		addr = (sc->ntxchains == 3) ? RT3593_EEPROM_PWR2GHZ_BASE2 :
1628 		    RT2860_EEPROM_PWR2GHZ_BASE2;
1629 		run_srom_read(sc, addr + i / 2, &val);
1630 		sc->txpow2[i + 0] = (int8_t)(val & 0xff);
1631 		sc->txpow2[i + 1] = (int8_t)(val >> 8);
1632 
1633 		if (sc->ntxchains == 3) {
1634 			run_srom_read(sc, RT3593_EEPROM_PWR2GHZ_BASE3 + i / 2,
1635 			    &val);
1636 			sc->txpow3[i + 0] = (int8_t)(val & 0xff);
1637 			sc->txpow3[i + 1] = (int8_t)(val >> 8);
1638 		}
1639 	}
1640 	/* Fix broken Tx power entries. */
1641 	for (i = 0; i < 14; i++) {
1642 		if (sc->txpow1[i] > 31)
1643 			sc->txpow1[i] = 5;
1644 		if (sc->txpow2[i] > 31)
1645 			sc->txpow2[i] = 5;
1646 		if (sc->ntxchains == 3) {
1647 			if (sc->txpow3[i] > 31)
1648 				sc->txpow3[i] = 5;
1649 		}
1650 	}
1651 	/* Read power settings for 5GHz channels. */
1652 	for (i = 0; i < 40; i += 2) {
1653 		run_srom_read(sc, RT3593_EEPROM_PWR5GHZ_BASE1 + i / 2, &val);
1654 		sc->txpow1[i + 14] = (int8_t)(val & 0xff);
1655 		sc->txpow1[i + 15] = (int8_t)(val >> 8);
1656 
1657 		run_srom_read(sc, RT3593_EEPROM_PWR5GHZ_BASE2 + i / 2, &val);
1658 		sc->txpow2[i + 14] = (int8_t)(val & 0xff);
1659 		sc->txpow2[i + 15] = (int8_t)(val >> 8);
1660 
1661 		if (sc->ntxchains == 3) {
1662 			run_srom_read(sc, RT3593_EEPROM_PWR5GHZ_BASE3 + i / 2,
1663 			    &val);
1664 			sc->txpow3[i + 14] = (int8_t)(val & 0xff);
1665 			sc->txpow3[i + 15] = (int8_t)(val >> 8);
1666 		}
1667 	}
1668 }
1669 
1670 static void
1671 run_get_txpower(struct run_softc *sc)
1672 {
1673 	uint16_t val;
1674 	int i;
1675 
1676 	/* Read power settings for 2GHz channels. */
1677 	for (i = 0; i < 14; i += 2) {
1678 		run_srom_read(sc, RT2860_EEPROM_PWR2GHZ_BASE1 + i / 2, &val);
1679 		sc->txpow1[i + 0] = (int8_t)(val & 0xff);
1680 		sc->txpow1[i + 1] = (int8_t)(val >> 8);
1681 
1682 		if (sc->mac_ver != 0x5390) {
1683 			run_srom_read(sc,
1684 			    RT2860_EEPROM_PWR2GHZ_BASE2 + i / 2, &val);
1685 			sc->txpow2[i + 0] = (int8_t)(val & 0xff);
1686 			sc->txpow2[i + 1] = (int8_t)(val >> 8);
1687 		}
1688 	}
1689 	/* Fix broken Tx power entries. */
1690 	for (i = 0; i < 14; i++) {
1691 		if (sc->mac_ver >= 0x5390) {
1692 			if (sc->txpow1[i] < 0 || sc->txpow1[i] > 39)
1693 				sc->txpow1[i] = 5;
1694 		} else {
1695 			if (sc->txpow1[i] < 0 || sc->txpow1[i] > 31)
1696 				sc->txpow1[i] = 5;
1697 		}
1698 		if (sc->mac_ver > 0x5390) {
1699 			if (sc->txpow2[i] < 0 || sc->txpow2[i] > 39)
1700 				sc->txpow2[i] = 5;
1701 		} else if (sc->mac_ver < 0x5390) {
1702 			if (sc->txpow2[i] < 0 || sc->txpow2[i] > 31)
1703 				sc->txpow2[i] = 5;
1704 		}
1705 		DPRINTF("chan %d: power1=%d, power2=%d\n",
1706 		    rt2860_rf2850[i].chan, sc->txpow1[i], sc->txpow2[i]);
1707 	}
1708 	/* Read power settings for 5GHz channels. */
1709 	for (i = 0; i < 40; i += 2) {
1710 		run_srom_read(sc, RT2860_EEPROM_PWR5GHZ_BASE1 + i / 2, &val);
1711 		sc->txpow1[i + 14] = (int8_t)(val & 0xff);
1712 		sc->txpow1[i + 15] = (int8_t)(val >> 8);
1713 
1714 		run_srom_read(sc, RT2860_EEPROM_PWR5GHZ_BASE2 + i / 2, &val);
1715 		sc->txpow2[i + 14] = (int8_t)(val & 0xff);
1716 		sc->txpow2[i + 15] = (int8_t)(val >> 8);
1717 	}
1718 	/* Fix broken Tx power entries. */
1719 	for (i = 0; i < 40; i++ ) {
1720 		if (sc->mac_ver != 0x5592) {
1721 			if (sc->txpow1[14 + i] < -7 || sc->txpow1[14 + i] > 15)
1722 				sc->txpow1[14 + i] = 5;
1723 			if (sc->txpow2[14 + i] < -7 || sc->txpow2[14 + i] > 15)
1724 				sc->txpow2[14 + i] = 5;
1725 		}
1726 		DPRINTF("chan %d: power1=%d, power2=%d\n",
1727 		    rt2860_rf2850[14 + i].chan, sc->txpow1[14 + i],
1728 		    sc->txpow2[14 + i]);
1729 	}
1730 }
1731 
1732 static int
1733 run_read_eeprom(struct run_softc *sc)
1734 {
1735 	struct ieee80211com *ic = &sc->sc_ic;
1736 	int8_t delta_2ghz, delta_5ghz;
1737 	uint32_t tmp;
1738 	uint16_t val;
1739 	int ridx, ant, i;
1740 
1741 	/* check whether the ROM is eFUSE ROM or EEPROM */
1742 	sc->sc_srom_read = run_eeprom_read_2;
1743 	if (sc->mac_ver >= 0x3070) {
1744 		run_read(sc, RT3070_EFUSE_CTRL, &tmp);
1745 		DPRINTF("EFUSE_CTRL=0x%08x\n", tmp);
1746 		if ((tmp & RT3070_SEL_EFUSE) || sc->mac_ver == 0x3593)
1747 			sc->sc_srom_read = run_efuse_read_2;
1748 	}
1749 
1750 	/* read ROM version */
1751 	run_srom_read(sc, RT2860_EEPROM_VERSION, &val);
1752 	DPRINTF("EEPROM rev=%d, FAE=%d\n", val >> 8, val & 0xff);
1753 
1754 	/* read MAC address */
1755 	run_srom_read(sc, RT2860_EEPROM_MAC01, &val);
1756 	ic->ic_macaddr[0] = val & 0xff;
1757 	ic->ic_macaddr[1] = val >> 8;
1758 	run_srom_read(sc, RT2860_EEPROM_MAC23, &val);
1759 	ic->ic_macaddr[2] = val & 0xff;
1760 	ic->ic_macaddr[3] = val >> 8;
1761 	run_srom_read(sc, RT2860_EEPROM_MAC45, &val);
1762 	ic->ic_macaddr[4] = val & 0xff;
1763 	ic->ic_macaddr[5] = val >> 8;
1764 
1765 	if (sc->mac_ver < 0x3593) {
1766 		/* read vender BBP settings */
1767 		for (i = 0; i < 10; i++) {
1768 			run_srom_read(sc, RT2860_EEPROM_BBP_BASE + i, &val);
1769 			sc->bbp[i].val = val & 0xff;
1770 			sc->bbp[i].reg = val >> 8;
1771 			DPRINTF("BBP%d=0x%02x\n", sc->bbp[i].reg,
1772 			    sc->bbp[i].val);
1773 		}
1774 		if (sc->mac_ver >= 0x3071) {
1775 			/* read vendor RF settings */
1776 			for (i = 0; i < 10; i++) {
1777 				run_srom_read(sc, RT3071_EEPROM_RF_BASE + i,
1778 				   &val);
1779 				sc->rf[i].val = val & 0xff;
1780 				sc->rf[i].reg = val >> 8;
1781 				DPRINTF("RF%d=0x%02x\n", sc->rf[i].reg,
1782 				    sc->rf[i].val);
1783 			}
1784 		}
1785 	}
1786 
1787 	/* read RF frequency offset from EEPROM */
1788 	run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_FREQ_LEDS :
1789 	    RT3593_EEPROM_FREQ, &val);
1790 	sc->freq = ((val & 0xff) != 0xff) ? val & 0xff : 0;
1791 	DPRINTF("EEPROM freq offset %d\n", sc->freq & 0xff);
1792 
1793 	run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_FREQ_LEDS :
1794 	    RT3593_EEPROM_FREQ_LEDS, &val);
1795 	if (val >> 8 != 0xff) {
1796 		/* read LEDs operating mode */
1797 		sc->leds = val >> 8;
1798 		run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_LED1 :
1799 		    RT3593_EEPROM_LED1, &sc->led[0]);
1800 		run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_LED2 :
1801 		    RT3593_EEPROM_LED2, &sc->led[1]);
1802 		run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_LED3 :
1803 		    RT3593_EEPROM_LED3, &sc->led[2]);
1804 	} else {
1805 		/* broken EEPROM, use default settings */
1806 		sc->leds = 0x01;
1807 		sc->led[0] = 0x5555;
1808 		sc->led[1] = 0x2221;
1809 		sc->led[2] = 0x5627;	/* differs from RT2860 */
1810 	}
1811 	DPRINTF("EEPROM LED mode=0x%02x, LEDs=0x%04x/0x%04x/0x%04x\n",
1812 	    sc->leds, sc->led[0], sc->led[1], sc->led[2]);
1813 
1814 	/* read RF information */
1815 	if (sc->mac_ver == 0x5390 || sc->mac_ver ==0x5392)
1816 		run_srom_read(sc, 0x00, &val);
1817 	else
1818 		run_srom_read(sc, RT2860_EEPROM_ANTENNA, &val);
1819 
1820 	if (val == 0xffff) {
1821 		device_printf(sc->sc_dev,
1822 		    "invalid EEPROM antenna info, using default\n");
1823 		DPRINTF("invalid EEPROM antenna info, using default\n");
1824 		if (sc->mac_ver == 0x3572) {
1825 			/* default to RF3052 2T2R */
1826 			sc->rf_rev = RT3070_RF_3052;
1827 			sc->ntxchains = 2;
1828 			sc->nrxchains = 2;
1829 		} else if (sc->mac_ver >= 0x3070) {
1830 			/* default to RF3020 1T1R */
1831 			sc->rf_rev = RT3070_RF_3020;
1832 			sc->ntxchains = 1;
1833 			sc->nrxchains = 1;
1834 		} else {
1835 			/* default to RF2820 1T2R */
1836 			sc->rf_rev = RT2860_RF_2820;
1837 			sc->ntxchains = 1;
1838 			sc->nrxchains = 2;
1839 		}
1840 	} else {
1841 		if (sc->mac_ver == 0x5390 || sc->mac_ver ==0x5392) {
1842 			sc->rf_rev = val;
1843 			run_srom_read(sc, RT2860_EEPROM_ANTENNA, &val);
1844 		} else
1845 			sc->rf_rev = (val >> 8) & 0xf;
1846 		sc->ntxchains = (val >> 4) & 0xf;
1847 		sc->nrxchains = val & 0xf;
1848 	}
1849 	DPRINTF("EEPROM RF rev=0x%04x chains=%dT%dR\n",
1850 	    sc->rf_rev, sc->ntxchains, sc->nrxchains);
1851 
1852 	/* check if RF supports automatic Tx access gain control */
1853 	run_srom_read(sc, RT2860_EEPROM_CONFIG, &val);
1854 	DPRINTF("EEPROM CFG 0x%04x\n", val);
1855 	/* check if driver should patch the DAC issue */
1856 	if ((val >> 8) != 0xff)
1857 		sc->patch_dac = (val >> 15) & 1;
1858 	if ((val & 0xff) != 0xff) {
1859 		sc->ext_5ghz_lna = (val >> 3) & 1;
1860 		sc->ext_2ghz_lna = (val >> 2) & 1;
1861 		/* check if RF supports automatic Tx access gain control */
1862 		sc->calib_2ghz = sc->calib_5ghz = (val >> 1) & 1;
1863 		/* check if we have a hardware radio switch */
1864 		sc->rfswitch = val & 1;
1865 	}
1866 
1867 	/* Read Tx power settings. */
1868 	if (sc->mac_ver == 0x3593)
1869 		run_rt3593_get_txpower(sc);
1870 	else
1871 		run_get_txpower(sc);
1872 
1873 	/* read Tx power compensation for each Tx rate */
1874 	run_srom_read(sc, RT2860_EEPROM_DELTAPWR, &val);
1875 	delta_2ghz = delta_5ghz = 0;
1876 	if ((val & 0xff) != 0xff && (val & 0x80)) {
1877 		delta_2ghz = val & 0xf;
1878 		if (!(val & 0x40))	/* negative number */
1879 			delta_2ghz = -delta_2ghz;
1880 	}
1881 	val >>= 8;
1882 	if ((val & 0xff) != 0xff && (val & 0x80)) {
1883 		delta_5ghz = val & 0xf;
1884 		if (!(val & 0x40))	/* negative number */
1885 			delta_5ghz = -delta_5ghz;
1886 	}
1887 	DPRINTF("power compensation=%d (2GHz), %d (5GHz)\n",
1888 	    delta_2ghz, delta_5ghz);
1889 
1890 	for (ridx = 0; ridx < 5; ridx++) {
1891 		uint32_t reg;
1892 
1893 		run_srom_read(sc, RT2860_EEPROM_RPWR + ridx * 2, &val);
1894 		reg = val;
1895 		run_srom_read(sc, RT2860_EEPROM_RPWR + ridx * 2 + 1, &val);
1896 		reg |= (uint32_t)val << 16;
1897 
1898 		sc->txpow20mhz[ridx] = reg;
1899 		sc->txpow40mhz_2ghz[ridx] = b4inc(reg, delta_2ghz);
1900 		sc->txpow40mhz_5ghz[ridx] = b4inc(reg, delta_5ghz);
1901 
1902 		DPRINTF("ridx %d: power 20MHz=0x%08x, 40MHz/2GHz=0x%08x, "
1903 		    "40MHz/5GHz=0x%08x\n", ridx, sc->txpow20mhz[ridx],
1904 		    sc->txpow40mhz_2ghz[ridx], sc->txpow40mhz_5ghz[ridx]);
1905 	}
1906 
1907 	/* Read RSSI offsets and LNA gains from EEPROM. */
1908 	run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_RSSI1_2GHZ :
1909 	    RT3593_EEPROM_RSSI1_2GHZ, &val);
1910 	sc->rssi_2ghz[0] = val & 0xff;	/* Ant A */
1911 	sc->rssi_2ghz[1] = val >> 8;	/* Ant B */
1912 	run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_RSSI2_2GHZ :
1913 	    RT3593_EEPROM_RSSI2_2GHZ, &val);
1914 	if (sc->mac_ver >= 0x3070) {
1915 		if (sc->mac_ver == 0x3593) {
1916 			sc->txmixgain_2ghz = 0;
1917 			sc->rssi_2ghz[2] = val & 0xff;	/* Ant C */
1918 		} else {
1919 			/*
1920 			 * On RT3070 chips (limited to 2 Rx chains), this ROM
1921 			 * field contains the Tx mixer gain for the 2GHz band.
1922 			 */
1923 			if ((val & 0xff) != 0xff)
1924 				sc->txmixgain_2ghz = val & 0x7;
1925 		}
1926 		DPRINTF("tx mixer gain=%u (2GHz)\n", sc->txmixgain_2ghz);
1927 	} else
1928 		sc->rssi_2ghz[2] = val & 0xff;	/* Ant C */
1929 	if (sc->mac_ver == 0x3593)
1930 		run_srom_read(sc, RT3593_EEPROM_LNA_5GHZ, &val);
1931 	sc->lna[2] = val >> 8;		/* channel group 2 */
1932 
1933 	run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_RSSI1_5GHZ :
1934 	    RT3593_EEPROM_RSSI1_5GHZ, &val);
1935 	sc->rssi_5ghz[0] = val & 0xff;	/* Ant A */
1936 	sc->rssi_5ghz[1] = val >> 8;	/* Ant B */
1937 	run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_RSSI2_5GHZ :
1938 	    RT3593_EEPROM_RSSI2_5GHZ, &val);
1939 	if (sc->mac_ver == 0x3572) {
1940 		/*
1941 		 * On RT3572 chips (limited to 2 Rx chains), this ROM
1942 		 * field contains the Tx mixer gain for the 5GHz band.
1943 		 */
1944 		if ((val & 0xff) != 0xff)
1945 			sc->txmixgain_5ghz = val & 0x7;
1946 		DPRINTF("tx mixer gain=%u (5GHz)\n", sc->txmixgain_5ghz);
1947 	} else
1948 		sc->rssi_5ghz[2] = val & 0xff;	/* Ant C */
1949 	if (sc->mac_ver == 0x3593) {
1950 		sc->txmixgain_5ghz = 0;
1951 		run_srom_read(sc, RT3593_EEPROM_LNA_5GHZ, &val);
1952 	}
1953 	sc->lna[3] = val >> 8;		/* channel group 3 */
1954 
1955 	run_srom_read(sc, (sc->mac_ver != 0x3593) ? RT2860_EEPROM_LNA :
1956 	    RT3593_EEPROM_LNA, &val);
1957 	sc->lna[0] = val & 0xff;	/* channel group 0 */
1958 	sc->lna[1] = val >> 8;		/* channel group 1 */
1959 
1960 	/* fix broken 5GHz LNA entries */
1961 	if (sc->lna[2] == 0 || sc->lna[2] == 0xff) {
1962 		DPRINTF("invalid LNA for channel group %d\n", 2);
1963 		sc->lna[2] = sc->lna[1];
1964 	}
1965 	if (sc->lna[3] == 0 || sc->lna[3] == 0xff) {
1966 		DPRINTF("invalid LNA for channel group %d\n", 3);
1967 		sc->lna[3] = sc->lna[1];
1968 	}
1969 
1970 	/* fix broken RSSI offset entries */
1971 	for (ant = 0; ant < 3; ant++) {
1972 		if (sc->rssi_2ghz[ant] < -10 || sc->rssi_2ghz[ant] > 10) {
1973 			DPRINTF("invalid RSSI%d offset: %d (2GHz)\n",
1974 			    ant + 1, sc->rssi_2ghz[ant]);
1975 			sc->rssi_2ghz[ant] = 0;
1976 		}
1977 		if (sc->rssi_5ghz[ant] < -10 || sc->rssi_5ghz[ant] > 10) {
1978 			DPRINTF("invalid RSSI%d offset: %d (5GHz)\n",
1979 			    ant + 1, sc->rssi_5ghz[ant]);
1980 			sc->rssi_5ghz[ant] = 0;
1981 		}
1982 	}
1983 	return (0);
1984 }
1985 
1986 static struct ieee80211_node *
1987 run_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
1988 {
1989 	return malloc(sizeof (struct run_node), M_DEVBUF, M_NOWAIT | M_ZERO);
1990 }
1991 
1992 static int
1993 run_media_change(struct ifnet *ifp)
1994 {
1995 	struct ieee80211vap *vap = ifp->if_softc;
1996 	struct ieee80211com *ic = vap->iv_ic;
1997 	const struct ieee80211_txparam *tp;
1998 	struct run_softc *sc = ic->ic_softc;
1999 	uint8_t rate, ridx;
2000 	int error;
2001 
2002 	RUN_LOCK(sc);
2003 
2004 	error = ieee80211_media_change(ifp);
2005 	if (error != ENETRESET) {
2006 		RUN_UNLOCK(sc);
2007 		return (error);
2008 	}
2009 
2010 	tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
2011 	if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
2012 		struct ieee80211_node *ni;
2013 		struct run_node	*rn;
2014 
2015 		rate = ic->ic_sup_rates[ic->ic_curmode].
2016 		    rs_rates[tp->ucastrate] & IEEE80211_RATE_VAL;
2017 		for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
2018 			if (rt2860_rates[ridx].rate == rate)
2019 				break;
2020 		ni = ieee80211_ref_node(vap->iv_bss);
2021 		rn = RUN_NODE(ni);
2022 		rn->fix_ridx = ridx;
2023 		DPRINTF("rate=%d, fix_ridx=%d\n", rate, rn->fix_ridx);
2024 		ieee80211_free_node(ni);
2025 	}
2026 
2027 #if 0
2028 	if ((ifp->if_flags & IFF_UP) &&
2029 	    (ifp->if_drv_flags &  RUN_RUNNING)){
2030 		run_init_locked(sc);
2031 	}
2032 #endif
2033 
2034 	RUN_UNLOCK(sc);
2035 
2036 	return (0);
2037 }
2038 
2039 static int
2040 run_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
2041 {
2042 	const struct ieee80211_txparam *tp;
2043 	struct ieee80211com *ic = vap->iv_ic;
2044 	struct run_softc *sc = ic->ic_softc;
2045 	struct run_vap *rvp = RUN_VAP(vap);
2046 	enum ieee80211_state ostate;
2047 	uint32_t sta[3];
2048 	uint32_t tmp;
2049 	uint8_t ratectl;
2050 	uint8_t restart_ratectl = 0;
2051 	uint8_t bid = 1 << rvp->rvp_id;
2052 
2053 	ostate = vap->iv_state;
2054 	DPRINTF("%s -> %s\n",
2055 		ieee80211_state_name[ostate],
2056 		ieee80211_state_name[nstate]);
2057 
2058 	IEEE80211_UNLOCK(ic);
2059 	RUN_LOCK(sc);
2060 
2061 	ratectl = sc->ratectl_run; /* remember current state */
2062 	sc->ratectl_run = RUN_RATECTL_OFF;
2063 	usb_callout_stop(&sc->ratectl_ch);
2064 
2065 	if (ostate == IEEE80211_S_RUN) {
2066 		/* turn link LED off */
2067 		run_set_leds(sc, RT2860_LED_RADIO);
2068 	}
2069 
2070 	switch (nstate) {
2071 	case IEEE80211_S_INIT:
2072 		restart_ratectl = 1;
2073 
2074 		if (ostate != IEEE80211_S_RUN)
2075 			break;
2076 
2077 		ratectl &= ~bid;
2078 		sc->runbmap &= ~bid;
2079 
2080 		/* abort TSF synchronization if there is no vap running */
2081 		if (--sc->running == 0) {
2082 			run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
2083 			run_write(sc, RT2860_BCN_TIME_CFG,
2084 			    tmp & ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN |
2085 			    RT2860_TBTT_TIMER_EN));
2086 		}
2087 		break;
2088 
2089 	case IEEE80211_S_RUN:
2090 		if (!(sc->runbmap & bid)) {
2091 			if(sc->running++)
2092 				restart_ratectl = 1;
2093 			sc->runbmap |= bid;
2094 		}
2095 
2096 		m_freem(rvp->beacon_mbuf);
2097 		rvp->beacon_mbuf = NULL;
2098 
2099 		switch (vap->iv_opmode) {
2100 		case IEEE80211_M_HOSTAP:
2101 		case IEEE80211_M_MBSS:
2102 			sc->ap_running |= bid;
2103 			ic->ic_opmode = vap->iv_opmode;
2104 			run_update_beacon_cb(vap);
2105 			break;
2106 		case IEEE80211_M_IBSS:
2107 			sc->adhoc_running |= bid;
2108 			if (!sc->ap_running)
2109 				ic->ic_opmode = vap->iv_opmode;
2110 			run_update_beacon_cb(vap);
2111 			break;
2112 		case IEEE80211_M_STA:
2113 			sc->sta_running |= bid;
2114 			if (!sc->ap_running && !sc->adhoc_running)
2115 				ic->ic_opmode = vap->iv_opmode;
2116 
2117 			/* read statistic counters (clear on read) */
2118 			run_read_region_1(sc, RT2860_TX_STA_CNT0,
2119 			    (uint8_t *)sta, sizeof sta);
2120 
2121 			break;
2122 		default:
2123 			ic->ic_opmode = vap->iv_opmode;
2124 			break;
2125 		}
2126 
2127 		if (vap->iv_opmode != IEEE80211_M_MONITOR) {
2128 			struct ieee80211_node *ni;
2129 
2130 			if (ic->ic_bsschan == IEEE80211_CHAN_ANYC) {
2131 				RUN_UNLOCK(sc);
2132 				IEEE80211_LOCK(ic);
2133 				return (-1);
2134 			}
2135 			run_updateslot(ic);
2136 			run_enable_mrr(sc);
2137 			run_set_txpreamble(sc);
2138 			run_set_basicrates(sc);
2139 			ni = ieee80211_ref_node(vap->iv_bss);
2140 			IEEE80211_ADDR_COPY(sc->sc_bssid, ni->ni_bssid);
2141 			run_set_bssid(sc, sc->sc_bssid);
2142 			ieee80211_free_node(ni);
2143 			run_enable_tsf_sync(sc);
2144 
2145 			/* enable automatic rate adaptation */
2146 			tp = &vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)];
2147 			if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE)
2148 				ratectl |= bid;
2149 		} else
2150 			run_enable_tsf(sc);
2151 
2152 		/* turn link LED on */
2153 		run_set_leds(sc, RT2860_LED_RADIO |
2154 		    (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan) ?
2155 		     RT2860_LED_LINK_2GHZ : RT2860_LED_LINK_5GHZ));
2156 
2157 		break;
2158 	default:
2159 		DPRINTFN(6, "undefined case\n");
2160 		break;
2161 	}
2162 
2163 	/* restart amrr for running VAPs */
2164 	if ((sc->ratectl_run = ratectl) && restart_ratectl)
2165 		usb_callout_reset(&sc->ratectl_ch, hz, run_ratectl_to, sc);
2166 
2167 	RUN_UNLOCK(sc);
2168 	IEEE80211_LOCK(ic);
2169 
2170 	return(rvp->newstate(vap, nstate, arg));
2171 }
2172 
2173 static int
2174 run_wme_update(struct ieee80211com *ic)
2175 {
2176 	struct run_softc *sc = ic->ic_softc;
2177 	const struct wmeParams *ac =
2178 	    ic->ic_wme.wme_chanParams.cap_wmeParams;
2179 	int aci, error = 0;
2180 
2181 	/* update MAC TX configuration registers */
2182 	RUN_LOCK(sc);
2183 	for (aci = 0; aci < WME_NUM_AC; aci++) {
2184 		error = run_write(sc, RT2860_EDCA_AC_CFG(aci),
2185 		    ac[aci].wmep_logcwmax << 16 |
2186 		    ac[aci].wmep_logcwmin << 12 |
2187 		    ac[aci].wmep_aifsn    <<  8 |
2188 		    ac[aci].wmep_txopLimit);
2189 		if (error) goto err;
2190 	}
2191 
2192 	/* update SCH/DMA registers too */
2193 	error = run_write(sc, RT2860_WMM_AIFSN_CFG,
2194 	    ac[WME_AC_VO].wmep_aifsn  << 12 |
2195 	    ac[WME_AC_VI].wmep_aifsn  <<  8 |
2196 	    ac[WME_AC_BK].wmep_aifsn  <<  4 |
2197 	    ac[WME_AC_BE].wmep_aifsn);
2198 	if (error) goto err;
2199 	error = run_write(sc, RT2860_WMM_CWMIN_CFG,
2200 	    ac[WME_AC_VO].wmep_logcwmin << 12 |
2201 	    ac[WME_AC_VI].wmep_logcwmin <<  8 |
2202 	    ac[WME_AC_BK].wmep_logcwmin <<  4 |
2203 	    ac[WME_AC_BE].wmep_logcwmin);
2204 	if (error) goto err;
2205 	error = run_write(sc, RT2860_WMM_CWMAX_CFG,
2206 	    ac[WME_AC_VO].wmep_logcwmax << 12 |
2207 	    ac[WME_AC_VI].wmep_logcwmax <<  8 |
2208 	    ac[WME_AC_BK].wmep_logcwmax <<  4 |
2209 	    ac[WME_AC_BE].wmep_logcwmax);
2210 	if (error) goto err;
2211 	error = run_write(sc, RT2860_WMM_TXOP0_CFG,
2212 	    ac[WME_AC_BK].wmep_txopLimit << 16 |
2213 	    ac[WME_AC_BE].wmep_txopLimit);
2214 	if (error) goto err;
2215 	error = run_write(sc, RT2860_WMM_TXOP1_CFG,
2216 	    ac[WME_AC_VO].wmep_txopLimit << 16 |
2217 	    ac[WME_AC_VI].wmep_txopLimit);
2218 
2219 err:
2220 	RUN_UNLOCK(sc);
2221 	if (error)
2222 		DPRINTF("WME update failed\n");
2223 
2224 	return (error);
2225 }
2226 
2227 static void
2228 run_key_set_cb(void *arg)
2229 {
2230 	struct run_cmdq *cmdq = arg;
2231 	struct ieee80211vap *vap = cmdq->arg1;
2232 	struct ieee80211_key *k = cmdq->k;
2233 	struct ieee80211com *ic = vap->iv_ic;
2234 	struct run_softc *sc = ic->ic_softc;
2235 	struct ieee80211_node *ni;
2236 	u_int cipher = k->wk_cipher->ic_cipher;
2237 	uint32_t attr;
2238 	uint16_t base, associd;
2239 	uint8_t mode, wcid, iv[8];
2240 
2241 	RUN_LOCK_ASSERT(sc, MA_OWNED);
2242 
2243 	if (vap->iv_opmode == IEEE80211_M_HOSTAP)
2244 		ni = ieee80211_find_vap_node(&ic->ic_sta, vap, cmdq->mac);
2245 	else
2246 		ni = vap->iv_bss;
2247 	associd = (ni != NULL) ? ni->ni_associd : 0;
2248 
2249 	/* map net80211 cipher to RT2860 security mode */
2250 	switch (cipher) {
2251 	case IEEE80211_CIPHER_WEP:
2252 		if(k->wk_keylen < 8)
2253 			mode = RT2860_MODE_WEP40;
2254 		else
2255 			mode = RT2860_MODE_WEP104;
2256 		break;
2257 	case IEEE80211_CIPHER_TKIP:
2258 		mode = RT2860_MODE_TKIP;
2259 		break;
2260 	case IEEE80211_CIPHER_AES_CCM:
2261 		mode = RT2860_MODE_AES_CCMP;
2262 		break;
2263 	default:
2264 		DPRINTF("undefined case\n");
2265 		return;
2266 	}
2267 
2268 	DPRINTFN(1, "associd=%x, keyix=%d, mode=%x, type=%s, tx=%s, rx=%s\n",
2269 	    associd, k->wk_keyix, mode,
2270 	    (k->wk_flags & IEEE80211_KEY_GROUP) ? "group" : "pairwise",
2271 	    (k->wk_flags & IEEE80211_KEY_XMIT) ? "on" : "off",
2272 	    (k->wk_flags & IEEE80211_KEY_RECV) ? "on" : "off");
2273 
2274 	if (k->wk_flags & IEEE80211_KEY_GROUP) {
2275 		wcid = 0;	/* NB: update WCID0 for group keys */
2276 		base = RT2860_SKEY(RUN_VAP(vap)->rvp_id, k->wk_keyix);
2277 	} else {
2278 		wcid = (vap->iv_opmode == IEEE80211_M_STA) ?
2279 		    1 : RUN_AID2WCID(associd);
2280 		base = RT2860_PKEY(wcid);
2281 	}
2282 
2283 	if (cipher == IEEE80211_CIPHER_TKIP) {
2284 		if(run_write_region_1(sc, base, k->wk_key, 16))
2285 			return;
2286 		if(run_write_region_1(sc, base + 16, &k->wk_key[16], 8))	/* wk_txmic */
2287 			return;
2288 		if(run_write_region_1(sc, base + 24, &k->wk_key[24], 8))	/* wk_rxmic */
2289 			return;
2290 	} else {
2291 		/* roundup len to 16-bit: XXX fix write_region_1() instead */
2292 		if(run_write_region_1(sc, base, k->wk_key, (k->wk_keylen + 1) & ~1))
2293 			return;
2294 	}
2295 
2296 	if (!(k->wk_flags & IEEE80211_KEY_GROUP) ||
2297 	    (k->wk_flags & (IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV))) {
2298 		/* set initial packet number in IV+EIV */
2299 		if (cipher == IEEE80211_CIPHER_WEP) {
2300 			memset(iv, 0, sizeof iv);
2301 			iv[3] = vap->iv_def_txkey << 6;
2302 		} else {
2303 			if (cipher == IEEE80211_CIPHER_TKIP) {
2304 				iv[0] = k->wk_keytsc >> 8;
2305 				iv[1] = (iv[0] | 0x20) & 0x7f;
2306 				iv[2] = k->wk_keytsc;
2307 			} else /* CCMP */ {
2308 				iv[0] = k->wk_keytsc;
2309 				iv[1] = k->wk_keytsc >> 8;
2310 				iv[2] = 0;
2311 			}
2312 			iv[3] = k->wk_keyix << 6 | IEEE80211_WEP_EXTIV;
2313 			iv[4] = k->wk_keytsc >> 16;
2314 			iv[5] = k->wk_keytsc >> 24;
2315 			iv[6] = k->wk_keytsc >> 32;
2316 			iv[7] = k->wk_keytsc >> 40;
2317 		}
2318 		if (run_write_region_1(sc, RT2860_IVEIV(wcid), iv, 8))
2319 			return;
2320 	}
2321 
2322 	if (k->wk_flags & IEEE80211_KEY_GROUP) {
2323 		/* install group key */
2324 		if (run_read(sc, RT2860_SKEY_MODE_0_7, &attr))
2325 			return;
2326 		attr &= ~(0xf << (k->wk_keyix * 4));
2327 		attr |= mode << (k->wk_keyix * 4);
2328 		if (run_write(sc, RT2860_SKEY_MODE_0_7, attr))
2329 			return;
2330 	} else {
2331 		/* install pairwise key */
2332 		if (run_read(sc, RT2860_WCID_ATTR(wcid), &attr))
2333 			return;
2334 		attr = (attr & ~0xf) | (mode << 1) | RT2860_RX_PKEY_EN;
2335 		if (run_write(sc, RT2860_WCID_ATTR(wcid), attr))
2336 			return;
2337 	}
2338 
2339 	/* TODO create a pass-thru key entry? */
2340 
2341 	/* need wcid to delete the right key later */
2342 	k->wk_pad = wcid;
2343 }
2344 
2345 /*
2346  * Don't have to be deferred, but in order to keep order of
2347  * execution, i.e. with run_key_delete(), defer this and let
2348  * run_cmdq_cb() maintain the order.
2349  *
2350  * return 0 on error
2351  */
2352 static int
2353 run_key_set(struct ieee80211vap *vap, struct ieee80211_key *k)
2354 {
2355 	struct ieee80211com *ic = vap->iv_ic;
2356 	struct run_softc *sc = ic->ic_softc;
2357 	uint32_t i;
2358 
2359 	i = RUN_CMDQ_GET(&sc->cmdq_store);
2360 	DPRINTF("cmdq_store=%d\n", i);
2361 	sc->cmdq[i].func = run_key_set_cb;
2362 	sc->cmdq[i].arg0 = NULL;
2363 	sc->cmdq[i].arg1 = vap;
2364 	sc->cmdq[i].k = k;
2365 	IEEE80211_ADDR_COPY(sc->cmdq[i].mac, k->wk_macaddr);
2366 	ieee80211_runtask(ic, &sc->cmdq_task);
2367 
2368 	/*
2369 	 * To make sure key will be set when hostapd
2370 	 * calls iv_key_set() before if_init().
2371 	 */
2372 	if (vap->iv_opmode == IEEE80211_M_HOSTAP) {
2373 		RUN_LOCK(sc);
2374 		sc->cmdq_key_set = RUN_CMDQ_GO;
2375 		RUN_UNLOCK(sc);
2376 	}
2377 
2378 	return (1);
2379 }
2380 
2381 /*
2382  * If wlan is destroyed without being brought down i.e. without
2383  * wlan down or wpa_cli terminate, this function is called after
2384  * vap is gone. Don't refer it.
2385  */
2386 static void
2387 run_key_delete_cb(void *arg)
2388 {
2389 	struct run_cmdq *cmdq = arg;
2390 	struct run_softc *sc = cmdq->arg1;
2391 	struct ieee80211_key *k = &cmdq->key;
2392 	uint32_t attr;
2393 	uint8_t wcid;
2394 
2395 	RUN_LOCK_ASSERT(sc, MA_OWNED);
2396 
2397 	if (k->wk_flags & IEEE80211_KEY_GROUP) {
2398 		/* remove group key */
2399 		DPRINTF("removing group key\n");
2400 		run_read(sc, RT2860_SKEY_MODE_0_7, &attr);
2401 		attr &= ~(0xf << (k->wk_keyix * 4));
2402 		run_write(sc, RT2860_SKEY_MODE_0_7, attr);
2403 	} else {
2404 		/* remove pairwise key */
2405 		DPRINTF("removing key for wcid %x\n", k->wk_pad);
2406 		/* matching wcid was written to wk_pad in run_key_set() */
2407 		wcid = k->wk_pad;
2408 		run_read(sc, RT2860_WCID_ATTR(wcid), &attr);
2409 		attr &= ~0xf;
2410 		run_write(sc, RT2860_WCID_ATTR(wcid), attr);
2411 		run_set_region_4(sc, RT2860_WCID_ENTRY(wcid), 0, 8);
2412 	}
2413 
2414 	k->wk_pad = 0;
2415 }
2416 
2417 /*
2418  * return 0 on error
2419  */
2420 static int
2421 run_key_delete(struct ieee80211vap *vap, struct ieee80211_key *k)
2422 {
2423 	struct ieee80211com *ic = vap->iv_ic;
2424 	struct run_softc *sc = ic->ic_softc;
2425 	struct ieee80211_key *k0;
2426 	uint32_t i;
2427 
2428 	/*
2429 	 * When called back, key might be gone. So, make a copy
2430 	 * of some values need to delete keys before deferring.
2431 	 * But, because of LOR with node lock, cannot use lock here.
2432 	 * So, use atomic instead.
2433 	 */
2434 	i = RUN_CMDQ_GET(&sc->cmdq_store);
2435 	DPRINTF("cmdq_store=%d\n", i);
2436 	sc->cmdq[i].func = run_key_delete_cb;
2437 	sc->cmdq[i].arg0 = NULL;
2438 	sc->cmdq[i].arg1 = sc;
2439 	k0 = &sc->cmdq[i].key;
2440 	k0->wk_flags = k->wk_flags;
2441 	k0->wk_keyix = k->wk_keyix;
2442 	/* matching wcid was written to wk_pad in run_key_set() */
2443 	k0->wk_pad = k->wk_pad;
2444 	ieee80211_runtask(ic, &sc->cmdq_task);
2445 	return (1);	/* return fake success */
2446 
2447 }
2448 
2449 static void
2450 run_ratectl_to(void *arg)
2451 {
2452 	struct run_softc *sc = arg;
2453 
2454 	/* do it in a process context, so it can go sleep */
2455 	ieee80211_runtask(&sc->sc_ic, &sc->ratectl_task);
2456 	/* next timeout will be rescheduled in the callback task */
2457 }
2458 
2459 /* ARGSUSED */
2460 static void
2461 run_ratectl_cb(void *arg, int pending)
2462 {
2463 	struct run_softc *sc = arg;
2464 	struct ieee80211com *ic = &sc->sc_ic;
2465 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2466 
2467 	if (vap == NULL)
2468 		return;
2469 
2470 	if (sc->rvp_cnt > 1 || vap->iv_opmode != IEEE80211_M_STA) {
2471 		/*
2472 		 * run_reset_livelock() doesn't do anything with AMRR,
2473 		 * but Ralink wants us to call it every 1 sec. So, we
2474 		 * piggyback here rather than creating another callout.
2475 		 * Livelock may occur only in HOSTAP or IBSS mode
2476 		 * (when h/w is sending beacons).
2477 		 */
2478 		RUN_LOCK(sc);
2479 		run_reset_livelock(sc);
2480 		/* just in case, there are some stats to drain */
2481 		run_drain_fifo(sc);
2482 		RUN_UNLOCK(sc);
2483 	}
2484 
2485 	ieee80211_iterate_nodes(&ic->ic_sta, run_iter_func, sc);
2486 
2487 	RUN_LOCK(sc);
2488 	if(sc->ratectl_run != RUN_RATECTL_OFF)
2489 		usb_callout_reset(&sc->ratectl_ch, hz, run_ratectl_to, sc);
2490 	RUN_UNLOCK(sc);
2491 }
2492 
2493 static void
2494 run_drain_fifo(void *arg)
2495 {
2496 	struct run_softc *sc = arg;
2497 	uint32_t stat;
2498 	uint16_t (*wstat)[3];
2499 	uint8_t wcid, mcs, pid;
2500 	int8_t retry;
2501 
2502 	RUN_LOCK_ASSERT(sc, MA_OWNED);
2503 
2504 	for (;;) {
2505 		/* drain Tx status FIFO (maxsize = 16) */
2506 		run_read(sc, RT2860_TX_STAT_FIFO, &stat);
2507 		DPRINTFN(4, "tx stat 0x%08x\n", stat);
2508 		if (!(stat & RT2860_TXQ_VLD))
2509 			break;
2510 
2511 		wcid = (stat >> RT2860_TXQ_WCID_SHIFT) & 0xff;
2512 
2513 		/* if no ACK was requested, no feedback is available */
2514 		if (!(stat & RT2860_TXQ_ACKREQ) || wcid > RT2870_WCID_MAX ||
2515 		    wcid == 0)
2516 			continue;
2517 
2518 		/*
2519 		 * Even though each stat is Tx-complete-status like format,
2520 		 * the device can poll stats. Because there is no guarantee
2521 		 * that the referring node is still around when read the stats.
2522 		 * So that, if we use ieee80211_ratectl_tx_update(), we will
2523 		 * have hard time not to refer already freed node.
2524 		 *
2525 		 * To eliminate such page faults, we poll stats in softc.
2526 		 * Then, update the rates later with ieee80211_ratectl_tx_update().
2527 		 */
2528 		wstat = &(sc->wcid_stats[wcid]);
2529 		(*wstat)[RUN_TXCNT]++;
2530 		if (stat & RT2860_TXQ_OK)
2531 			(*wstat)[RUN_SUCCESS]++;
2532 		else
2533 			counter_u64_add(sc->sc_ic.ic_oerrors, 1);
2534 		/*
2535 		 * Check if there were retries, ie if the Tx success rate is
2536 		 * different from the requested rate. Note that it works only
2537 		 * because we do not allow rate fallback from OFDM to CCK.
2538 		 */
2539 		mcs = (stat >> RT2860_TXQ_MCS_SHIFT) & 0x7f;
2540 		pid = (stat >> RT2860_TXQ_PID_SHIFT) & 0xf;
2541 		if ((retry = pid -1 - mcs) > 0) {
2542 			(*wstat)[RUN_TXCNT] += retry;
2543 			(*wstat)[RUN_RETRY] += retry;
2544 		}
2545 	}
2546 	DPRINTFN(3, "count=%d\n", sc->fifo_cnt);
2547 
2548 	sc->fifo_cnt = 0;
2549 }
2550 
2551 static void
2552 run_iter_func(void *arg, struct ieee80211_node *ni)
2553 {
2554 	struct run_softc *sc = arg;
2555 	struct ieee80211vap *vap = ni->ni_vap;
2556 	struct run_node *rn = RUN_NODE(ni);
2557 	union run_stats sta[2];
2558 	uint16_t (*wstat)[3];
2559 	int txcnt, success, retrycnt, error;
2560 
2561 	RUN_LOCK(sc);
2562 
2563 	/* Check for special case */
2564 	if (sc->rvp_cnt <= 1 && vap->iv_opmode == IEEE80211_M_STA &&
2565 	    ni != vap->iv_bss)
2566 		goto fail;
2567 
2568 	if (sc->rvp_cnt <= 1 && (vap->iv_opmode == IEEE80211_M_IBSS ||
2569 	    vap->iv_opmode == IEEE80211_M_STA)) {
2570 		/* read statistic counters (clear on read) and update AMRR state */
2571 		error = run_read_region_1(sc, RT2860_TX_STA_CNT0, (uint8_t *)sta,
2572 		    sizeof sta);
2573 		if (error != 0)
2574 			goto fail;
2575 
2576 		/* count failed TX as errors */
2577 		if_inc_counter(vap->iv_ifp, IFCOUNTER_OERRORS,
2578 		    le16toh(sta[0].error.fail));
2579 
2580 		retrycnt = le16toh(sta[1].tx.retry);
2581 		success = le16toh(sta[1].tx.success);
2582 		txcnt = retrycnt + success + le16toh(sta[0].error.fail);
2583 
2584 		DPRINTFN(3, "retrycnt=%d success=%d failcnt=%d\n",
2585 			retrycnt, success, le16toh(sta[0].error.fail));
2586 	} else {
2587 		wstat = &(sc->wcid_stats[RUN_AID2WCID(ni->ni_associd)]);
2588 
2589 		if (wstat == &(sc->wcid_stats[0]) ||
2590 		    wstat > &(sc->wcid_stats[RT2870_WCID_MAX]))
2591 			goto fail;
2592 
2593 		txcnt = (*wstat)[RUN_TXCNT];
2594 		success = (*wstat)[RUN_SUCCESS];
2595 		retrycnt = (*wstat)[RUN_RETRY];
2596 		DPRINTFN(3, "retrycnt=%d txcnt=%d success=%d\n",
2597 		    retrycnt, txcnt, success);
2598 
2599 		memset(wstat, 0, sizeof(*wstat));
2600 	}
2601 
2602 	ieee80211_ratectl_tx_update(vap, ni, &txcnt, &success, &retrycnt);
2603 	rn->amrr_ridx = ieee80211_ratectl_rate(ni, NULL, 0);
2604 
2605 fail:
2606 	RUN_UNLOCK(sc);
2607 
2608 	DPRINTFN(3, "ridx=%d\n", rn->amrr_ridx);
2609 }
2610 
2611 static void
2612 run_newassoc_cb(void *arg)
2613 {
2614 	struct run_cmdq *cmdq = arg;
2615 	struct ieee80211_node *ni = cmdq->arg1;
2616 	struct run_softc *sc = ni->ni_vap->iv_ic->ic_softc;
2617 	uint8_t wcid = cmdq->wcid;
2618 
2619 	RUN_LOCK_ASSERT(sc, MA_OWNED);
2620 
2621 	run_write_region_1(sc, RT2860_WCID_ENTRY(wcid),
2622 	    ni->ni_macaddr, IEEE80211_ADDR_LEN);
2623 
2624 	memset(&(sc->wcid_stats[wcid]), 0, sizeof(sc->wcid_stats[wcid]));
2625 }
2626 
2627 static void
2628 run_newassoc(struct ieee80211_node *ni, int isnew)
2629 {
2630 	struct run_node *rn = RUN_NODE(ni);
2631 	struct ieee80211_rateset *rs = &ni->ni_rates;
2632 	struct ieee80211vap *vap = ni->ni_vap;
2633 	struct ieee80211com *ic = vap->iv_ic;
2634 	struct run_softc *sc = ic->ic_softc;
2635 	uint8_t rate;
2636 	uint8_t ridx;
2637 	uint8_t wcid;
2638 	int i, j;
2639 
2640 	wcid = (vap->iv_opmode == IEEE80211_M_STA) ?
2641 	    1 : RUN_AID2WCID(ni->ni_associd);
2642 
2643 	if (wcid > RT2870_WCID_MAX) {
2644 		device_printf(sc->sc_dev, "wcid=%d out of range\n", wcid);
2645 		return;
2646 	}
2647 
2648 	/* only interested in true associations */
2649 	if (isnew && ni->ni_associd != 0) {
2650 
2651 		/*
2652 		 * This function could is called though timeout function.
2653 		 * Need to defer.
2654 		 */
2655 		uint32_t cnt = RUN_CMDQ_GET(&sc->cmdq_store);
2656 		DPRINTF("cmdq_store=%d\n", cnt);
2657 		sc->cmdq[cnt].func = run_newassoc_cb;
2658 		sc->cmdq[cnt].arg0 = NULL;
2659 		sc->cmdq[cnt].arg1 = ni;
2660 		sc->cmdq[cnt].wcid = wcid;
2661 		ieee80211_runtask(ic, &sc->cmdq_task);
2662 	}
2663 
2664 	DPRINTF("new assoc isnew=%d associd=%x addr=%s\n",
2665 	    isnew, ni->ni_associd, ether_sprintf(ni->ni_macaddr));
2666 
2667 	for (i = 0; i < rs->rs_nrates; i++) {
2668 		rate = rs->rs_rates[i] & IEEE80211_RATE_VAL;
2669 		/* convert 802.11 rate to hardware rate index */
2670 		for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
2671 			if (rt2860_rates[ridx].rate == rate)
2672 				break;
2673 		rn->ridx[i] = ridx;
2674 		/* determine rate of control response frames */
2675 		for (j = i; j >= 0; j--) {
2676 			if ((rs->rs_rates[j] & IEEE80211_RATE_BASIC) &&
2677 			    rt2860_rates[rn->ridx[i]].phy ==
2678 			    rt2860_rates[rn->ridx[j]].phy)
2679 				break;
2680 		}
2681 		if (j >= 0) {
2682 			rn->ctl_ridx[i] = rn->ridx[j];
2683 		} else {
2684 			/* no basic rate found, use mandatory one */
2685 			rn->ctl_ridx[i] = rt2860_rates[ridx].ctl_ridx;
2686 		}
2687 		DPRINTF("rate=0x%02x ridx=%d ctl_ridx=%d\n",
2688 		    rs->rs_rates[i], rn->ridx[i], rn->ctl_ridx[i]);
2689 	}
2690 	rate = vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)].mgmtrate;
2691 	for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
2692 		if (rt2860_rates[ridx].rate == rate)
2693 			break;
2694 	rn->mgt_ridx = ridx;
2695 	DPRINTF("rate=%d, mgmt_ridx=%d\n", rate, rn->mgt_ridx);
2696 
2697 	RUN_LOCK(sc);
2698 	if(sc->ratectl_run != RUN_RATECTL_OFF)
2699 		usb_callout_reset(&sc->ratectl_ch, hz, run_ratectl_to, sc);
2700 	RUN_UNLOCK(sc);
2701 }
2702 
2703 /*
2704  * Return the Rx chain with the highest RSSI for a given frame.
2705  */
2706 static __inline uint8_t
2707 run_maxrssi_chain(struct run_softc *sc, const struct rt2860_rxwi *rxwi)
2708 {
2709 	uint8_t rxchain = 0;
2710 
2711 	if (sc->nrxchains > 1) {
2712 		if (rxwi->rssi[1] > rxwi->rssi[rxchain])
2713 			rxchain = 1;
2714 		if (sc->nrxchains > 2)
2715 			if (rxwi->rssi[2] > rxwi->rssi[rxchain])
2716 				rxchain = 2;
2717 	}
2718 	return (rxchain);
2719 }
2720 
2721 static void
2722 run_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m, int subtype,
2723     const struct ieee80211_rx_stats *rxs, int rssi, int nf)
2724 {
2725 	struct ieee80211vap *vap = ni->ni_vap;
2726 	struct run_softc *sc = vap->iv_ic->ic_softc;
2727 	struct run_vap *rvp = RUN_VAP(vap);
2728 	uint64_t ni_tstamp, rx_tstamp;
2729 
2730 	rvp->recv_mgmt(ni, m, subtype, rxs, rssi, nf);
2731 
2732 	if (vap->iv_state == IEEE80211_S_RUN &&
2733 	    (subtype == IEEE80211_FC0_SUBTYPE_BEACON ||
2734 	    subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)) {
2735 		ni_tstamp = le64toh(ni->ni_tstamp.tsf);
2736 		RUN_LOCK(sc);
2737 		run_get_tsf(sc, &rx_tstamp);
2738 		RUN_UNLOCK(sc);
2739 		rx_tstamp = le64toh(rx_tstamp);
2740 
2741 		if (ni_tstamp >= rx_tstamp) {
2742 			DPRINTF("ibss merge, tsf %ju tstamp %ju\n",
2743 			    (uintmax_t)rx_tstamp, (uintmax_t)ni_tstamp);
2744 			(void) ieee80211_ibss_merge(ni);
2745 		}
2746 	}
2747 }
2748 
2749 static void
2750 run_rx_frame(struct run_softc *sc, struct mbuf *m, uint32_t dmalen)
2751 {
2752 	struct ieee80211com *ic = &sc->sc_ic;
2753 	struct ieee80211_frame *wh;
2754 	struct ieee80211_node *ni;
2755 	struct rt2870_rxd *rxd;
2756 	struct rt2860_rxwi *rxwi;
2757 	uint32_t flags;
2758 	uint16_t len, rxwisize;
2759 	uint8_t ant, rssi;
2760 	int8_t nf;
2761 
2762 	rxwi = mtod(m, struct rt2860_rxwi *);
2763 	len = le16toh(rxwi->len) & 0xfff;
2764 	rxwisize = sizeof(struct rt2860_rxwi);
2765 	if (sc->mac_ver == 0x5592)
2766 		rxwisize += sizeof(uint64_t);
2767 	else if (sc->mac_ver == 0x3593)
2768 		rxwisize += sizeof(uint32_t);
2769 	if (__predict_false(len > dmalen)) {
2770 		m_freem(m);
2771 		counter_u64_add(ic->ic_ierrors, 1);
2772 		DPRINTF("bad RXWI length %u > %u\n", len, dmalen);
2773 		return;
2774 	}
2775 	/* Rx descriptor is located at the end */
2776 	rxd = (struct rt2870_rxd *)(mtod(m, caddr_t) + dmalen);
2777 	flags = le32toh(rxd->flags);
2778 
2779 	if (__predict_false(flags & (RT2860_RX_CRCERR | RT2860_RX_ICVERR))) {
2780 		m_freem(m);
2781 		counter_u64_add(ic->ic_ierrors, 1);
2782 		DPRINTF("%s error.\n", (flags & RT2860_RX_CRCERR)?"CRC":"ICV");
2783 		return;
2784 	}
2785 
2786 	m->m_data += rxwisize;
2787 	m->m_pkthdr.len = m->m_len -= rxwisize;
2788 
2789 	wh = mtod(m, struct ieee80211_frame *);
2790 
2791 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
2792 		wh->i_fc[1] &= ~IEEE80211_FC1_PROTECTED;
2793 		m->m_flags |= M_WEP;
2794 	}
2795 
2796 	if (flags & RT2860_RX_L2PAD) {
2797 		DPRINTFN(8, "received RT2860_RX_L2PAD frame\n");
2798 		len += 2;
2799 	}
2800 
2801 	ni = ieee80211_find_rxnode(ic,
2802 	    mtod(m, struct ieee80211_frame_min *));
2803 
2804 	if (__predict_false(flags & RT2860_RX_MICERR)) {
2805 		/* report MIC failures to net80211 for TKIP */
2806 		if (ni != NULL)
2807 			ieee80211_notify_michael_failure(ni->ni_vap, wh,
2808 			    rxwi->keyidx);
2809 		m_freem(m);
2810 		counter_u64_add(ic->ic_ierrors, 1);
2811 		DPRINTF("MIC error. Someone is lying.\n");
2812 		return;
2813 	}
2814 
2815 	ant = run_maxrssi_chain(sc, rxwi);
2816 	rssi = rxwi->rssi[ant];
2817 	nf = run_rssi2dbm(sc, rssi, ant);
2818 
2819 	m->m_pkthdr.len = m->m_len = len;
2820 
2821 	if (__predict_false(ieee80211_radiotap_active(ic))) {
2822 		struct run_rx_radiotap_header *tap = &sc->sc_rxtap;
2823 		uint16_t phy;
2824 
2825 		tap->wr_flags = 0;
2826 		tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
2827 		tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
2828 		tap->wr_antsignal = rssi;
2829 		tap->wr_antenna = ant;
2830 		tap->wr_dbm_antsignal = run_rssi2dbm(sc, rssi, ant);
2831 		tap->wr_rate = 2;	/* in case it can't be found below */
2832 		RUN_LOCK(sc);
2833 		run_get_tsf(sc, &tap->wr_tsf);
2834 		RUN_UNLOCK(sc);
2835 		phy = le16toh(rxwi->phy);
2836 		switch (phy & RT2860_PHY_MODE) {
2837 		case RT2860_PHY_CCK:
2838 			switch ((phy & RT2860_PHY_MCS) & ~RT2860_PHY_SHPRE) {
2839 			case 0:	tap->wr_rate =   2; break;
2840 			case 1:	tap->wr_rate =   4; break;
2841 			case 2:	tap->wr_rate =  11; break;
2842 			case 3:	tap->wr_rate =  22; break;
2843 			}
2844 			if (phy & RT2860_PHY_SHPRE)
2845 				tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
2846 			break;
2847 		case RT2860_PHY_OFDM:
2848 			switch (phy & RT2860_PHY_MCS) {
2849 			case 0:	tap->wr_rate =  12; break;
2850 			case 1:	tap->wr_rate =  18; break;
2851 			case 2:	tap->wr_rate =  24; break;
2852 			case 3:	tap->wr_rate =  36; break;
2853 			case 4:	tap->wr_rate =  48; break;
2854 			case 5:	tap->wr_rate =  72; break;
2855 			case 6:	tap->wr_rate =  96; break;
2856 			case 7:	tap->wr_rate = 108; break;
2857 			}
2858 			break;
2859 		}
2860 	}
2861 
2862 	if (ni != NULL) {
2863 		(void)ieee80211_input(ni, m, rssi, nf);
2864 		ieee80211_free_node(ni);
2865 	} else {
2866 		(void)ieee80211_input_all(ic, m, rssi, nf);
2867 	}
2868 }
2869 
2870 static void
2871 run_bulk_rx_callback(struct usb_xfer *xfer, usb_error_t error)
2872 {
2873 	struct run_softc *sc = usbd_xfer_softc(xfer);
2874 	struct ieee80211com *ic = &sc->sc_ic;
2875 	struct mbuf *m = NULL;
2876 	struct mbuf *m0;
2877 	uint32_t dmalen;
2878 	uint16_t rxwisize;
2879 	int xferlen;
2880 
2881 	rxwisize = sizeof(struct rt2860_rxwi);
2882 	if (sc->mac_ver == 0x5592)
2883 		rxwisize += sizeof(uint64_t);
2884 	else if (sc->mac_ver == 0x3593)
2885 		rxwisize += sizeof(uint32_t);
2886 
2887 	usbd_xfer_status(xfer, &xferlen, NULL, NULL, NULL);
2888 
2889 	switch (USB_GET_STATE(xfer)) {
2890 	case USB_ST_TRANSFERRED:
2891 
2892 		DPRINTFN(15, "rx done, actlen=%d\n", xferlen);
2893 
2894 		if (xferlen < (int)(sizeof(uint32_t) + rxwisize +
2895 		    sizeof(struct rt2870_rxd))) {
2896 			DPRINTF("xfer too short %d\n", xferlen);
2897 			goto tr_setup;
2898 		}
2899 
2900 		m = sc->rx_m;
2901 		sc->rx_m = NULL;
2902 
2903 		/* FALLTHROUGH */
2904 	case USB_ST_SETUP:
2905 tr_setup:
2906 		if (sc->rx_m == NULL) {
2907 			sc->rx_m = m_getjcl(M_NOWAIT, MT_DATA, M_PKTHDR,
2908 			    MJUMPAGESIZE /* xfer can be bigger than MCLBYTES */);
2909 		}
2910 		if (sc->rx_m == NULL) {
2911 			DPRINTF("could not allocate mbuf - idle with stall\n");
2912 			counter_u64_add(ic->ic_ierrors, 1);
2913 			usbd_xfer_set_stall(xfer);
2914 			usbd_xfer_set_frames(xfer, 0);
2915 		} else {
2916 			/*
2917 			 * Directly loading a mbuf cluster into DMA to
2918 			 * save some data copying. This works because
2919 			 * there is only one cluster.
2920 			 */
2921 			usbd_xfer_set_frame_data(xfer, 0,
2922 			    mtod(sc->rx_m, caddr_t), RUN_MAX_RXSZ);
2923 			usbd_xfer_set_frames(xfer, 1);
2924 		}
2925 		usbd_transfer_submit(xfer);
2926 		break;
2927 
2928 	default:	/* Error */
2929 		if (error != USB_ERR_CANCELLED) {
2930 			/* try to clear stall first */
2931 			usbd_xfer_set_stall(xfer);
2932 			if (error == USB_ERR_TIMEOUT)
2933 				device_printf(sc->sc_dev, "device timeout\n");
2934 			counter_u64_add(ic->ic_ierrors, 1);
2935 			goto tr_setup;
2936 		}
2937 		if (sc->rx_m != NULL) {
2938 			m_freem(sc->rx_m);
2939 			sc->rx_m = NULL;
2940 		}
2941 		break;
2942 	}
2943 
2944 	if (m == NULL)
2945 		return;
2946 
2947 	/* inputting all the frames must be last */
2948 
2949 	RUN_UNLOCK(sc);
2950 
2951 	m->m_pkthdr.len = m->m_len = xferlen;
2952 
2953 	/* HW can aggregate multiple 802.11 frames in a single USB xfer */
2954 	for(;;) {
2955 		dmalen = le32toh(*mtod(m, uint32_t *)) & 0xffff;
2956 
2957 		if ((dmalen >= (uint32_t)-8) || (dmalen == 0) ||
2958 		    ((dmalen & 3) != 0)) {
2959 			DPRINTF("bad DMA length %u\n", dmalen);
2960 			break;
2961 		}
2962 		if ((dmalen + 8) > (uint32_t)xferlen) {
2963 			DPRINTF("bad DMA length %u > %d\n",
2964 			dmalen + 8, xferlen);
2965 			break;
2966 		}
2967 
2968 		/* If it is the last one or a single frame, we won't copy. */
2969 		if ((xferlen -= dmalen + 8) <= 8) {
2970 			/* trim 32-bit DMA-len header */
2971 			m->m_data += 4;
2972 			m->m_pkthdr.len = m->m_len -= 4;
2973 			run_rx_frame(sc, m, dmalen);
2974 			m = NULL;	/* don't free source buffer */
2975 			break;
2976 		}
2977 
2978 		/* copy aggregated frames to another mbuf */
2979 		m0 = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
2980 		if (__predict_false(m0 == NULL)) {
2981 			DPRINTF("could not allocate mbuf\n");
2982 			counter_u64_add(ic->ic_ierrors, 1);
2983 			break;
2984 		}
2985 		m_copydata(m, 4 /* skip 32-bit DMA-len header */,
2986 		    dmalen + sizeof(struct rt2870_rxd), mtod(m0, caddr_t));
2987 		m0->m_pkthdr.len = m0->m_len =
2988 		    dmalen + sizeof(struct rt2870_rxd);
2989 		run_rx_frame(sc, m0, dmalen);
2990 
2991 		/* update data ptr */
2992 		m->m_data += dmalen + 8;
2993 		m->m_pkthdr.len = m->m_len -= dmalen + 8;
2994 	}
2995 
2996 	/* make sure we free the source buffer, if any */
2997 	m_freem(m);
2998 
2999 	RUN_LOCK(sc);
3000 }
3001 
3002 static void
3003 run_tx_free(struct run_endpoint_queue *pq,
3004     struct run_tx_data *data, int txerr)
3005 {
3006 
3007 	ieee80211_tx_complete(data->ni, data->m, txerr);
3008 
3009 	data->m = NULL;
3010 	data->ni = NULL;
3011 
3012 	STAILQ_INSERT_TAIL(&pq->tx_fh, data, next);
3013 	pq->tx_nfree++;
3014 }
3015 
3016 static void
3017 run_bulk_tx_callbackN(struct usb_xfer *xfer, usb_error_t error, u_int index)
3018 {
3019 	struct run_softc *sc = usbd_xfer_softc(xfer);
3020 	struct ieee80211com *ic = &sc->sc_ic;
3021 	struct run_tx_data *data;
3022 	struct ieee80211vap *vap = NULL;
3023 	struct usb_page_cache *pc;
3024 	struct run_endpoint_queue *pq = &sc->sc_epq[index];
3025 	struct mbuf *m;
3026 	usb_frlength_t size;
3027 	int actlen;
3028 	int sumlen;
3029 
3030 	usbd_xfer_status(xfer, &actlen, &sumlen, NULL, NULL);
3031 
3032 	switch (USB_GET_STATE(xfer)) {
3033 	case USB_ST_TRANSFERRED:
3034 		DPRINTFN(11, "transfer complete: %d "
3035 		    "bytes @ index %d\n", actlen, index);
3036 
3037 		data = usbd_xfer_get_priv(xfer);
3038 		run_tx_free(pq, data, 0);
3039 		usbd_xfer_set_priv(xfer, NULL);
3040 
3041 		/* FALLTHROUGH */
3042 	case USB_ST_SETUP:
3043 tr_setup:
3044 		data = STAILQ_FIRST(&pq->tx_qh);
3045 		if (data == NULL)
3046 			break;
3047 
3048 		STAILQ_REMOVE_HEAD(&pq->tx_qh, next);
3049 
3050 		m = data->m;
3051 		size = (sc->mac_ver == 0x5592) ?
3052 		    sizeof(data->desc) + sizeof(uint32_t) : sizeof(data->desc);
3053 		if ((m->m_pkthdr.len +
3054 		    size + 3 + 8) > RUN_MAX_TXSZ) {
3055 			DPRINTF("data overflow, %u bytes\n",
3056 			    m->m_pkthdr.len);
3057 			run_tx_free(pq, data, 1);
3058 			goto tr_setup;
3059 		}
3060 
3061 		pc = usbd_xfer_get_frame(xfer, 0);
3062 		usbd_copy_in(pc, 0, &data->desc, size);
3063 		usbd_m_copy_in(pc, size, m, 0, m->m_pkthdr.len);
3064 		size += m->m_pkthdr.len;
3065 		/*
3066 		 * Align end on a 4-byte boundary, pad 8 bytes (CRC +
3067 		 * 4-byte padding), and be sure to zero those trailing
3068 		 * bytes:
3069 		 */
3070 		usbd_frame_zero(pc, size, ((-size) & 3) + 8);
3071 		size += ((-size) & 3) + 8;
3072 
3073 		vap = data->ni->ni_vap;
3074 		if (ieee80211_radiotap_active_vap(vap)) {
3075 			struct run_tx_radiotap_header *tap = &sc->sc_txtap;
3076 			struct rt2860_txwi *txwi =
3077 			    (struct rt2860_txwi *)(&data->desc + sizeof(struct rt2870_txd));
3078 			tap->wt_flags = 0;
3079 			tap->wt_rate = rt2860_rates[data->ridx].rate;
3080 			tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
3081 			tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
3082 			tap->wt_hwqueue = index;
3083 			if (le16toh(txwi->phy) & RT2860_PHY_SHPRE)
3084 				tap->wt_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
3085 
3086 			ieee80211_radiotap_tx(vap, m);
3087 		}
3088 
3089 		DPRINTFN(11, "sending frame len=%u/%u  @ index %d\n",
3090 		    m->m_pkthdr.len, size, index);
3091 
3092 		usbd_xfer_set_frame_len(xfer, 0, size);
3093 		usbd_xfer_set_priv(xfer, data);
3094 		usbd_transfer_submit(xfer);
3095 		run_start(sc);
3096 
3097 		break;
3098 
3099 	default:
3100 		DPRINTF("USB transfer error, %s\n",
3101 		    usbd_errstr(error));
3102 
3103 		data = usbd_xfer_get_priv(xfer);
3104 
3105 		if (data != NULL) {
3106 			if(data->ni != NULL)
3107 				vap = data->ni->ni_vap;
3108 			run_tx_free(pq, data, error);
3109 			usbd_xfer_set_priv(xfer, NULL);
3110 		}
3111 
3112 		if (vap == NULL)
3113 			vap = TAILQ_FIRST(&ic->ic_vaps);
3114 
3115 		if (error != USB_ERR_CANCELLED) {
3116 			if (error == USB_ERR_TIMEOUT) {
3117 				device_printf(sc->sc_dev, "device timeout\n");
3118 				uint32_t i = RUN_CMDQ_GET(&sc->cmdq_store);
3119 				DPRINTF("cmdq_store=%d\n", i);
3120 				sc->cmdq[i].func = run_usb_timeout_cb;
3121 				sc->cmdq[i].arg0 = vap;
3122 				ieee80211_runtask(ic, &sc->cmdq_task);
3123 			}
3124 
3125 			/*
3126 			 * Try to clear stall first, also if other
3127 			 * errors occur, hence clearing stall
3128 			 * introduces a 50 ms delay:
3129 			 */
3130 			usbd_xfer_set_stall(xfer);
3131 			goto tr_setup;
3132 		}
3133 		break;
3134 	}
3135 }
3136 
3137 static void
3138 run_bulk_tx_callback0(struct usb_xfer *xfer, usb_error_t error)
3139 {
3140 	run_bulk_tx_callbackN(xfer, error, 0);
3141 }
3142 
3143 static void
3144 run_bulk_tx_callback1(struct usb_xfer *xfer, usb_error_t error)
3145 {
3146 	run_bulk_tx_callbackN(xfer, error, 1);
3147 }
3148 
3149 static void
3150 run_bulk_tx_callback2(struct usb_xfer *xfer, usb_error_t error)
3151 {
3152 	run_bulk_tx_callbackN(xfer, error, 2);
3153 }
3154 
3155 static void
3156 run_bulk_tx_callback3(struct usb_xfer *xfer, usb_error_t error)
3157 {
3158 	run_bulk_tx_callbackN(xfer, error, 3);
3159 }
3160 
3161 static void
3162 run_bulk_tx_callback4(struct usb_xfer *xfer, usb_error_t error)
3163 {
3164 	run_bulk_tx_callbackN(xfer, error, 4);
3165 }
3166 
3167 static void
3168 run_bulk_tx_callback5(struct usb_xfer *xfer, usb_error_t error)
3169 {
3170 	run_bulk_tx_callbackN(xfer, error, 5);
3171 }
3172 
3173 static void
3174 run_set_tx_desc(struct run_softc *sc, struct run_tx_data *data)
3175 {
3176 	struct mbuf *m = data->m;
3177 	struct ieee80211com *ic = &sc->sc_ic;
3178 	struct ieee80211vap *vap = data->ni->ni_vap;
3179 	struct ieee80211_frame *wh;
3180 	struct rt2870_txd *txd;
3181 	struct rt2860_txwi *txwi;
3182 	uint16_t xferlen, txwisize;
3183 	uint16_t mcs;
3184 	uint8_t ridx = data->ridx;
3185 	uint8_t pad;
3186 
3187 	/* get MCS code from rate index */
3188 	mcs = rt2860_rates[ridx].mcs;
3189 
3190 	txwisize = (sc->mac_ver == 0x5592) ?
3191 	    sizeof(*txwi) + sizeof(uint32_t) : sizeof(*txwi);
3192 	xferlen = txwisize + m->m_pkthdr.len;
3193 
3194 	/* roundup to 32-bit alignment */
3195 	xferlen = (xferlen + 3) & ~3;
3196 
3197 	txd = (struct rt2870_txd *)&data->desc;
3198 	txd->len = htole16(xferlen);
3199 
3200 	wh = mtod(m, struct ieee80211_frame *);
3201 
3202 	/*
3203 	 * Ether both are true or both are false, the header
3204 	 * are nicely aligned to 32-bit. So, no L2 padding.
3205 	 */
3206 	if(IEEE80211_HAS_ADDR4(wh) == IEEE80211_QOS_HAS_SEQ(wh))
3207 		pad = 0;
3208 	else
3209 		pad = 2;
3210 
3211 	/* setup TX Wireless Information */
3212 	txwi = (struct rt2860_txwi *)(txd + 1);
3213 	txwi->len = htole16(m->m_pkthdr.len - pad);
3214 	if (rt2860_rates[ridx].phy == IEEE80211_T_DS) {
3215 		mcs |= RT2860_PHY_CCK;
3216 		if (ridx != RT2860_RIDX_CCK1 &&
3217 		    (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
3218 			mcs |= RT2860_PHY_SHPRE;
3219 	} else
3220 		mcs |= RT2860_PHY_OFDM;
3221 	txwi->phy = htole16(mcs);
3222 
3223 	/* check if RTS/CTS or CTS-to-self protection is required */
3224 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
3225 	    (m->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold ||
3226 	     ((ic->ic_flags & IEEE80211_F_USEPROT) &&
3227 	      rt2860_rates[ridx].phy == IEEE80211_T_OFDM)))
3228 		txwi->txop |= RT2860_TX_TXOP_HT;
3229 	else
3230 		txwi->txop |= RT2860_TX_TXOP_BACKOFF;
3231 
3232 	if (vap->iv_opmode != IEEE80211_M_STA && !IEEE80211_QOS_HAS_SEQ(wh))
3233 		txwi->xflags |= RT2860_TX_NSEQ;
3234 }
3235 
3236 /* This function must be called locked */
3237 static int
3238 run_tx(struct run_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
3239 {
3240 	struct ieee80211com *ic = &sc->sc_ic;
3241 	struct ieee80211vap *vap = ni->ni_vap;
3242 	struct ieee80211_frame *wh;
3243 	struct ieee80211_channel *chan;
3244 	const struct ieee80211_txparam *tp;
3245 	struct run_node *rn = RUN_NODE(ni);
3246 	struct run_tx_data *data;
3247 	struct rt2870_txd *txd;
3248 	struct rt2860_txwi *txwi;
3249 	uint16_t qos;
3250 	uint16_t dur;
3251 	uint16_t qid;
3252 	uint8_t type;
3253 	uint8_t tid;
3254 	uint8_t ridx;
3255 	uint8_t ctl_ridx;
3256 	uint8_t qflags;
3257 	uint8_t xflags = 0;
3258 	int hasqos;
3259 
3260 	RUN_LOCK_ASSERT(sc, MA_OWNED);
3261 
3262 	wh = mtod(m, struct ieee80211_frame *);
3263 
3264 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3265 
3266 	/*
3267 	 * There are 7 bulk endpoints: 1 for RX
3268 	 * and 6 for TX (4 EDCAs + HCCA + Prio).
3269 	 * Update 03-14-2009:  some devices like the Planex GW-US300MiniS
3270 	 * seem to have only 4 TX bulk endpoints (Fukaumi Naoki).
3271 	 */
3272 	if ((hasqos = IEEE80211_QOS_HAS_SEQ(wh))) {
3273 		uint8_t *frm;
3274 
3275 		if(IEEE80211_HAS_ADDR4(wh))
3276 			frm = ((struct ieee80211_qosframe_addr4 *)wh)->i_qos;
3277 		else
3278 			frm =((struct ieee80211_qosframe *)wh)->i_qos;
3279 
3280 		qos = le16toh(*(const uint16_t *)frm);
3281 		tid = qos & IEEE80211_QOS_TID;
3282 		qid = TID_TO_WME_AC(tid);
3283 	} else {
3284 		qos = 0;
3285 		tid = 0;
3286 		qid = WME_AC_BE;
3287 	}
3288 	qflags = (qid < 4) ? RT2860_TX_QSEL_EDCA : RT2860_TX_QSEL_HCCA;
3289 
3290 	DPRINTFN(8, "qos %d\tqid %d\ttid %d\tqflags %x\n",
3291 	    qos, qid, tid, qflags);
3292 
3293 	chan = (ni->ni_chan != IEEE80211_CHAN_ANYC)?ni->ni_chan:ic->ic_curchan;
3294 	tp = &vap->iv_txparms[ieee80211_chan2mode(chan)];
3295 
3296 	/* pickup a rate index */
3297 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
3298 	    type != IEEE80211_FC0_TYPE_DATA || m->m_flags & M_EAPOL) {
3299 		ridx = (ic->ic_curmode == IEEE80211_MODE_11A) ?
3300 		    RT2860_RIDX_OFDM6 : RT2860_RIDX_CCK1;
3301 		ctl_ridx = rt2860_rates[ridx].ctl_ridx;
3302 	} else {
3303 		if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
3304 			ridx = rn->fix_ridx;
3305 		else
3306 			ridx = rn->amrr_ridx;
3307 		ctl_ridx = rt2860_rates[ridx].ctl_ridx;
3308 	}
3309 
3310 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
3311 	    (!hasqos || (qos & IEEE80211_QOS_ACKPOLICY) !=
3312 	     IEEE80211_QOS_ACKPOLICY_NOACK)) {
3313 		xflags |= RT2860_TX_ACK;
3314 		if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
3315 			dur = rt2860_rates[ctl_ridx].sp_ack_dur;
3316 		else
3317 			dur = rt2860_rates[ctl_ridx].lp_ack_dur;
3318 		USETW(wh->i_dur, dur);
3319 	}
3320 
3321 	/* reserve slots for mgmt packets, just in case */
3322 	if (sc->sc_epq[qid].tx_nfree < 3) {
3323 		DPRINTFN(10, "tx ring %d is full\n", qid);
3324 		return (-1);
3325 	}
3326 
3327 	data = STAILQ_FIRST(&sc->sc_epq[qid].tx_fh);
3328 	STAILQ_REMOVE_HEAD(&sc->sc_epq[qid].tx_fh, next);
3329 	sc->sc_epq[qid].tx_nfree--;
3330 
3331 	txd = (struct rt2870_txd *)&data->desc;
3332 	txd->flags = qflags;
3333 	txwi = (struct rt2860_txwi *)(txd + 1);
3334 	txwi->xflags = xflags;
3335 	if (IEEE80211_IS_MULTICAST(wh->i_addr1))
3336 		txwi->wcid = 0;
3337 	else
3338 		txwi->wcid = (vap->iv_opmode == IEEE80211_M_STA) ?
3339 		    1 : RUN_AID2WCID(ni->ni_associd);
3340 
3341 	/* clear leftover garbage bits */
3342 	txwi->flags = 0;
3343 	txwi->txop = 0;
3344 
3345 	data->m = m;
3346 	data->ni = ni;
3347 	data->ridx = ridx;
3348 
3349 	run_set_tx_desc(sc, data);
3350 
3351 	/*
3352 	 * The chip keeps track of 2 kind of Tx stats,
3353 	 *  * TX_STAT_FIFO, for per WCID stats, and
3354 	 *  * TX_STA_CNT0 for all-TX-in-one stats.
3355 	 *
3356 	 * To use FIFO stats, we need to store MCS into the driver-private
3357  	 * PacketID field. So that, we can tell whose stats when we read them.
3358  	 * We add 1 to the MCS because setting the PacketID field to 0 means
3359  	 * that we don't want feedback in TX_STAT_FIFO.
3360  	 * And, that's what we want for STA mode, since TX_STA_CNT0 does the job.
3361  	 *
3362  	 * FIFO stats doesn't count Tx with WCID 0xff, so we do this in run_tx().
3363  	 */
3364 	if (sc->rvp_cnt > 1 || vap->iv_opmode == IEEE80211_M_HOSTAP ||
3365 	    vap->iv_opmode == IEEE80211_M_MBSS) {
3366 		uint16_t pid = (rt2860_rates[ridx].mcs + 1) & 0xf;
3367 		txwi->len |= htole16(pid << RT2860_TX_PID_SHIFT);
3368 
3369 		/*
3370 		 * Unlike PCI based devices, we don't get any interrupt from
3371 		 * USB devices, so we simulate FIFO-is-full interrupt here.
3372 		 * Ralink recommends to drain FIFO stats every 100 ms, but 16 slots
3373 		 * quickly get fulled. To prevent overflow, increment a counter on
3374 		 * every FIFO stat request, so we know how many slots are left.
3375 		 * We do this only in HOSTAP or multiple vap mode since FIFO stats
3376 		 * are used only in those modes.
3377 		 * We just drain stats. AMRR gets updated every 1 sec by
3378 		 * run_ratectl_cb() via callout.
3379 		 * Call it early. Otherwise overflow.
3380 		 */
3381 		if (sc->fifo_cnt++ == 10) {
3382 			/*
3383 			 * With multiple vaps or if_bridge, if_start() is called
3384 			 * with a non-sleepable lock, tcpinp. So, need to defer.
3385 			 */
3386 			uint32_t i = RUN_CMDQ_GET(&sc->cmdq_store);
3387 			DPRINTFN(6, "cmdq_store=%d\n", i);
3388 			sc->cmdq[i].func = run_drain_fifo;
3389 			sc->cmdq[i].arg0 = sc;
3390 			ieee80211_runtask(ic, &sc->cmdq_task);
3391 		}
3392 	}
3393 
3394         STAILQ_INSERT_TAIL(&sc->sc_epq[qid].tx_qh, data, next);
3395 
3396 	usbd_transfer_start(sc->sc_xfer[qid]);
3397 
3398 	DPRINTFN(8, "sending data frame len=%d rate=%d qid=%d\n",
3399 	    m->m_pkthdr.len + (int)(sizeof(struct rt2870_txd) +
3400 	    sizeof(struct rt2860_txwi)), rt2860_rates[ridx].rate, qid);
3401 
3402 	return (0);
3403 }
3404 
3405 static int
3406 run_tx_mgt(struct run_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
3407 {
3408 	struct ieee80211com *ic = &sc->sc_ic;
3409 	struct run_node *rn = RUN_NODE(ni);
3410 	struct run_tx_data *data;
3411 	struct ieee80211_frame *wh;
3412 	struct rt2870_txd *txd;
3413 	struct rt2860_txwi *txwi;
3414 	uint16_t dur;
3415 	uint8_t ridx = rn->mgt_ridx;
3416 	uint8_t type;
3417 	uint8_t xflags = 0;
3418 	uint8_t wflags = 0;
3419 
3420 	RUN_LOCK_ASSERT(sc, MA_OWNED);
3421 
3422 	wh = mtod(m, struct ieee80211_frame *);
3423 
3424 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3425 
3426 	/* tell hardware to add timestamp for probe responses */
3427 	if ((wh->i_fc[0] &
3428 	    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
3429 	    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
3430 		wflags |= RT2860_TX_TS;
3431 	else if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
3432 		xflags |= RT2860_TX_ACK;
3433 
3434 		dur = ieee80211_ack_duration(ic->ic_rt, rt2860_rates[ridx].rate,
3435 		    ic->ic_flags & IEEE80211_F_SHPREAMBLE);
3436 		USETW(wh->i_dur, dur);
3437 	}
3438 
3439 	if (sc->sc_epq[0].tx_nfree == 0)
3440 		/* let caller free mbuf */
3441 		return (EIO);
3442 	data = STAILQ_FIRST(&sc->sc_epq[0].tx_fh);
3443 	STAILQ_REMOVE_HEAD(&sc->sc_epq[0].tx_fh, next);
3444 	sc->sc_epq[0].tx_nfree--;
3445 
3446 	txd = (struct rt2870_txd *)&data->desc;
3447 	txd->flags = RT2860_TX_QSEL_EDCA;
3448 	txwi = (struct rt2860_txwi *)(txd + 1);
3449 	txwi->wcid = 0xff;
3450 	txwi->flags = wflags;
3451 	txwi->xflags = xflags;
3452 	txwi->txop = 0;	/* clear leftover garbage bits */
3453 
3454 	data->m = m;
3455 	data->ni = ni;
3456 	data->ridx = ridx;
3457 
3458 	run_set_tx_desc(sc, data);
3459 
3460 	DPRINTFN(10, "sending mgt frame len=%d rate=%d\n", m->m_pkthdr.len +
3461 	    (int)(sizeof(struct rt2870_txd) + sizeof(struct rt2860_txwi)),
3462 	    rt2860_rates[ridx].rate);
3463 
3464 	STAILQ_INSERT_TAIL(&sc->sc_epq[0].tx_qh, data, next);
3465 
3466 	usbd_transfer_start(sc->sc_xfer[0]);
3467 
3468 	return (0);
3469 }
3470 
3471 static int
3472 run_sendprot(struct run_softc *sc,
3473     const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate)
3474 {
3475 	struct ieee80211com *ic = ni->ni_ic;
3476 	struct ieee80211_frame *wh;
3477 	struct run_tx_data *data;
3478 	struct rt2870_txd *txd;
3479 	struct rt2860_txwi *txwi;
3480 	struct mbuf *mprot;
3481 	int ridx;
3482 	int protrate;
3483 	int ackrate;
3484 	int pktlen;
3485 	int isshort;
3486 	uint16_t dur;
3487 	uint8_t type;
3488 	uint8_t wflags = 0;
3489 	uint8_t xflags = 0;
3490 
3491 	RUN_LOCK_ASSERT(sc, MA_OWNED);
3492 
3493 	KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY,
3494 	    ("protection %d", prot));
3495 
3496 	wh = mtod(m, struct ieee80211_frame *);
3497 	pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN;
3498 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3499 
3500 	protrate = ieee80211_ctl_rate(ic->ic_rt, rate);
3501 	ackrate = ieee80211_ack_rate(ic->ic_rt, rate);
3502 
3503 	isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0;
3504 	dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort)
3505 	    + ieee80211_ack_duration(ic->ic_rt, rate, isshort);
3506 	wflags = RT2860_TX_FRAG;
3507 
3508 	/* check that there are free slots before allocating the mbuf */
3509 	if (sc->sc_epq[0].tx_nfree == 0)
3510 		/* let caller free mbuf */
3511 		return (ENOBUFS);
3512 
3513 	if (prot == IEEE80211_PROT_RTSCTS) {
3514 		/* NB: CTS is the same size as an ACK */
3515 		dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort);
3516 		xflags |= RT2860_TX_ACK;
3517 		mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur);
3518 	} else {
3519 		mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur);
3520 	}
3521 	if (mprot == NULL) {
3522 		if_inc_counter(ni->ni_vap->iv_ifp, IFCOUNTER_OERRORS, 1);
3523 		DPRINTF("could not allocate mbuf\n");
3524 		return (ENOBUFS);
3525 	}
3526 
3527         data = STAILQ_FIRST(&sc->sc_epq[0].tx_fh);
3528         STAILQ_REMOVE_HEAD(&sc->sc_epq[0].tx_fh, next);
3529         sc->sc_epq[0].tx_nfree--;
3530 
3531 	txd = (struct rt2870_txd *)&data->desc;
3532 	txd->flags = RT2860_TX_QSEL_EDCA;
3533 	txwi = (struct rt2860_txwi *)(txd + 1);
3534 	txwi->wcid = 0xff;
3535 	txwi->flags = wflags;
3536 	txwi->xflags = xflags;
3537 	txwi->txop = 0;	/* clear leftover garbage bits */
3538 
3539 	data->m = mprot;
3540 	data->ni = ieee80211_ref_node(ni);
3541 
3542 	for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
3543 		if (rt2860_rates[ridx].rate == protrate)
3544 			break;
3545 	data->ridx = ridx;
3546 
3547 	run_set_tx_desc(sc, data);
3548 
3549         DPRINTFN(1, "sending prot len=%u rate=%u\n",
3550             m->m_pkthdr.len, rate);
3551 
3552         STAILQ_INSERT_TAIL(&sc->sc_epq[0].tx_qh, data, next);
3553 
3554 	usbd_transfer_start(sc->sc_xfer[0]);
3555 
3556 	return (0);
3557 }
3558 
3559 static int
3560 run_tx_param(struct run_softc *sc, struct mbuf *m, struct ieee80211_node *ni,
3561     const struct ieee80211_bpf_params *params)
3562 {
3563 	struct ieee80211com *ic = ni->ni_ic;
3564 	struct ieee80211_frame *wh;
3565 	struct run_tx_data *data;
3566 	struct rt2870_txd *txd;
3567 	struct rt2860_txwi *txwi;
3568 	uint8_t type;
3569 	uint8_t ridx;
3570 	uint8_t rate;
3571 	uint8_t opflags = 0;
3572 	uint8_t xflags = 0;
3573 	int error;
3574 
3575 	RUN_LOCK_ASSERT(sc, MA_OWNED);
3576 
3577 	KASSERT(params != NULL, ("no raw xmit params"));
3578 
3579 	wh = mtod(m, struct ieee80211_frame *);
3580 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
3581 
3582 	rate = params->ibp_rate0;
3583 	if (!ieee80211_isratevalid(ic->ic_rt, rate)) {
3584 		/* let caller free mbuf */
3585 		return (EINVAL);
3586 	}
3587 
3588 	if ((params->ibp_flags & IEEE80211_BPF_NOACK) == 0)
3589 		xflags |= RT2860_TX_ACK;
3590 	if (params->ibp_flags & (IEEE80211_BPF_RTS|IEEE80211_BPF_CTS)) {
3591 		error = run_sendprot(sc, m, ni,
3592 		    params->ibp_flags & IEEE80211_BPF_RTS ?
3593 			IEEE80211_PROT_RTSCTS : IEEE80211_PROT_CTSONLY,
3594 		    rate);
3595 		if (error) {
3596 			/* let caller free mbuf */
3597 			return error;
3598 		}
3599 		opflags |= /*XXX RT2573_TX_LONG_RETRY |*/ RT2860_TX_TXOP_SIFS;
3600 	}
3601 
3602 	if (sc->sc_epq[0].tx_nfree == 0) {
3603 		/* let caller free mbuf */
3604 		DPRINTF("sending raw frame, but tx ring is full\n");
3605 		return (EIO);
3606 	}
3607         data = STAILQ_FIRST(&sc->sc_epq[0].tx_fh);
3608         STAILQ_REMOVE_HEAD(&sc->sc_epq[0].tx_fh, next);
3609         sc->sc_epq[0].tx_nfree--;
3610 
3611 	txd = (struct rt2870_txd *)&data->desc;
3612 	txd->flags = RT2860_TX_QSEL_EDCA;
3613 	txwi = (struct rt2860_txwi *)(txd + 1);
3614 	txwi->wcid = 0xff;
3615 	txwi->xflags = xflags;
3616 	txwi->txop = opflags;
3617 	txwi->flags = 0;	/* clear leftover garbage bits */
3618 
3619         data->m = m;
3620         data->ni = ni;
3621 	for (ridx = 0; ridx < RT2860_RIDX_MAX; ridx++)
3622 		if (rt2860_rates[ridx].rate == rate)
3623 			break;
3624 	data->ridx = ridx;
3625 
3626         run_set_tx_desc(sc, data);
3627 
3628         DPRINTFN(10, "sending raw frame len=%u rate=%u\n",
3629             m->m_pkthdr.len, rate);
3630 
3631         STAILQ_INSERT_TAIL(&sc->sc_epq[0].tx_qh, data, next);
3632 
3633 	usbd_transfer_start(sc->sc_xfer[0]);
3634 
3635         return (0);
3636 }
3637 
3638 static int
3639 run_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
3640     const struct ieee80211_bpf_params *params)
3641 {
3642 	struct run_softc *sc = ni->ni_ic->ic_softc;
3643 	int error = 0;
3644 
3645 	RUN_LOCK(sc);
3646 
3647 	/* prevent management frames from being sent if we're not ready */
3648 	if (!(sc->sc_flags & RUN_RUNNING)) {
3649 		error = ENETDOWN;
3650 		goto done;
3651 	}
3652 
3653 	if (params == NULL) {
3654 		/* tx mgt packet */
3655 		if ((error = run_tx_mgt(sc, m, ni)) != 0) {
3656 			DPRINTF("mgt tx failed\n");
3657 			goto done;
3658 		}
3659 	} else {
3660 		/* tx raw packet with param */
3661 		if ((error = run_tx_param(sc, m, ni, params)) != 0) {
3662 			DPRINTF("tx with param failed\n");
3663 			goto done;
3664 		}
3665 	}
3666 
3667 done:
3668 	RUN_UNLOCK(sc);
3669 
3670 	if (error != 0) {
3671 		if(m != NULL)
3672 			m_freem(m);
3673 	}
3674 
3675 	return (error);
3676 }
3677 
3678 static int
3679 run_transmit(struct ieee80211com *ic, struct mbuf *m)
3680 {
3681 	struct run_softc *sc = ic->ic_softc;
3682 	int error;
3683 
3684 	RUN_LOCK(sc);
3685 	if ((sc->sc_flags & RUN_RUNNING) == 0) {
3686 		RUN_UNLOCK(sc);
3687 		return (ENXIO);
3688 	}
3689 	error = mbufq_enqueue(&sc->sc_snd, m);
3690 	if (error) {
3691 		RUN_UNLOCK(sc);
3692 		return (error);
3693 	}
3694 	run_start(sc);
3695 	RUN_UNLOCK(sc);
3696 
3697 	return (0);
3698 }
3699 
3700 static void
3701 run_start(struct run_softc *sc)
3702 {
3703 	struct ieee80211_node *ni;
3704 	struct mbuf *m;
3705 
3706 	RUN_LOCK_ASSERT(sc, MA_OWNED);
3707 
3708 	if ((sc->sc_flags & RUN_RUNNING) == 0)
3709 		return;
3710 
3711 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
3712 		ni = (struct ieee80211_node *)m->m_pkthdr.rcvif;
3713 		if (run_tx(sc, m, ni) != 0) {
3714 			mbufq_prepend(&sc->sc_snd, m);
3715 			break;
3716 		}
3717 	}
3718 }
3719 
3720 static void
3721 run_parent(struct ieee80211com *ic)
3722 {
3723 	struct run_softc *sc = ic->ic_softc;
3724 	int startall = 0;
3725 
3726 	RUN_LOCK(sc);
3727 	if (sc->sc_detached) {
3728 		RUN_UNLOCK(sc);
3729 		return;
3730 	}
3731 
3732 	if (ic->ic_nrunning > 0) {
3733 		if (!(sc->sc_flags & RUN_RUNNING)) {
3734 			startall = 1;
3735 			run_init_locked(sc);
3736 		} else
3737 			run_update_promisc_locked(sc);
3738 	} else if ((sc->sc_flags & RUN_RUNNING) && sc->rvp_cnt <= 1)
3739 		run_stop(sc);
3740 	RUN_UNLOCK(sc);
3741 	if (startall)
3742 		ieee80211_start_all(ic);
3743 }
3744 
3745 static void
3746 run_iq_calib(struct run_softc *sc, u_int chan)
3747 {
3748 	uint16_t val;
3749 
3750 	/* Tx0 IQ gain. */
3751 	run_bbp_write(sc, 158, 0x2c);
3752 	if (chan <= 14)
3753 		run_efuse_read(sc, RT5390_EEPROM_IQ_GAIN_CAL_TX0_2GHZ, &val, 1);
3754 	else if (chan <= 64) {
3755 		run_efuse_read(sc,
3756 		    RT5390_EEPROM_IQ_GAIN_CAL_TX0_CH36_TO_CH64_5GHZ,
3757 		    &val, 1);
3758 	} else if (chan <= 138) {
3759 		run_efuse_read(sc,
3760 		    RT5390_EEPROM_IQ_GAIN_CAL_TX0_CH100_TO_CH138_5GHZ,
3761 		    &val, 1);
3762 	} else if (chan <= 165) {
3763 		run_efuse_read(sc,
3764 	    RT5390_EEPROM_IQ_GAIN_CAL_TX0_CH140_TO_CH165_5GHZ,
3765 		    &val, 1);
3766 	} else
3767 		val = 0;
3768 	run_bbp_write(sc, 159, val);
3769 
3770 	/* Tx0 IQ phase. */
3771 	run_bbp_write(sc, 158, 0x2d);
3772 	if (chan <= 14) {
3773 		run_efuse_read(sc, RT5390_EEPROM_IQ_PHASE_CAL_TX0_2GHZ,
3774 		    &val, 1);
3775 	} else if (chan <= 64) {
3776 		run_efuse_read(sc,
3777 		    RT5390_EEPROM_IQ_PHASE_CAL_TX0_CH36_TO_CH64_5GHZ,
3778 		    &val, 1);
3779 	} else if (chan <= 138) {
3780 		run_efuse_read(sc,
3781 		    RT5390_EEPROM_IQ_PHASE_CAL_TX0_CH100_TO_CH138_5GHZ,
3782 		    &val, 1);
3783 	} else if (chan <= 165) {
3784 		run_efuse_read(sc,
3785 		    RT5390_EEPROM_IQ_PHASE_CAL_TX0_CH140_TO_CH165_5GHZ,
3786 		    &val, 1);
3787 	} else
3788 		val = 0;
3789 	run_bbp_write(sc, 159, val);
3790 
3791 	/* Tx1 IQ gain. */
3792 	run_bbp_write(sc, 158, 0x4a);
3793 	if (chan <= 14) {
3794 		run_efuse_read(sc, RT5390_EEPROM_IQ_GAIN_CAL_TX1_2GHZ,
3795 		    &val, 1);
3796 	} else if (chan <= 64) {
3797 		run_efuse_read(sc,
3798 		    RT5390_EEPROM_IQ_GAIN_CAL_TX1_CH36_TO_CH64_5GHZ,
3799 		    &val, 1);
3800 	} else if (chan <= 138) {
3801 		run_efuse_read(sc,
3802 		    RT5390_EEPROM_IQ_GAIN_CAL_TX1_CH100_TO_CH138_5GHZ,
3803 		    &val, 1);
3804 	} else if (chan <= 165) {
3805 		run_efuse_read(sc,
3806 		    RT5390_EEPROM_IQ_GAIN_CAL_TX1_CH140_TO_CH165_5GHZ,
3807 		    &val, 1);
3808 	} else
3809 		val = 0;
3810 	run_bbp_write(sc, 159, val);
3811 
3812 	/* Tx1 IQ phase. */
3813 	run_bbp_write(sc, 158, 0x4b);
3814 	if (chan <= 14) {
3815 		run_efuse_read(sc, RT5390_EEPROM_IQ_PHASE_CAL_TX1_2GHZ,
3816 		    &val, 1);
3817 	} else if (chan <= 64) {
3818 		run_efuse_read(sc,
3819 		    RT5390_EEPROM_IQ_PHASE_CAL_TX1_CH36_TO_CH64_5GHZ,
3820 		    &val, 1);
3821 	} else if (chan <= 138) {
3822 		run_efuse_read(sc,
3823 		    RT5390_EEPROM_IQ_PHASE_CAL_TX1_CH100_TO_CH138_5GHZ,
3824 		    &val, 1);
3825 	} else if (chan <= 165) {
3826 		run_efuse_read(sc,
3827 		    RT5390_EEPROM_IQ_PHASE_CAL_TX1_CH140_TO_CH165_5GHZ,
3828 		    &val, 1);
3829 	} else
3830 		val = 0;
3831 	run_bbp_write(sc, 159, val);
3832 
3833 	/* RF IQ compensation control. */
3834 	run_bbp_write(sc, 158, 0x04);
3835 	run_efuse_read(sc, RT5390_EEPROM_RF_IQ_COMPENSATION_CTL,
3836 	    &val, 1);
3837 	run_bbp_write(sc, 159, val);
3838 
3839 	/* RF IQ imbalance compensation control. */
3840 	run_bbp_write(sc, 158, 0x03);
3841 	run_efuse_read(sc,
3842 	    RT5390_EEPROM_RF_IQ_IMBALANCE_COMPENSATION_CTL, &val, 1);
3843 	run_bbp_write(sc, 159, val);
3844 }
3845 
3846 static void
3847 run_set_agc(struct run_softc *sc, uint8_t agc)
3848 {
3849 	uint8_t bbp;
3850 
3851 	if (sc->mac_ver == 0x3572) {
3852 		run_bbp_read(sc, 27, &bbp);
3853 		bbp &= ~(0x3 << 5);
3854 		run_bbp_write(sc, 27, bbp | 0 << 5);	/* select Rx0 */
3855 		run_bbp_write(sc, 66, agc);
3856 		run_bbp_write(sc, 27, bbp | 1 << 5);	/* select Rx1 */
3857 		run_bbp_write(sc, 66, agc);
3858 	} else
3859 		run_bbp_write(sc, 66, agc);
3860 }
3861 
3862 static void
3863 run_select_chan_group(struct run_softc *sc, int group)
3864 {
3865 	uint32_t tmp;
3866 	uint8_t agc;
3867 
3868 	run_bbp_write(sc, 62, 0x37 - sc->lna[group]);
3869 	run_bbp_write(sc, 63, 0x37 - sc->lna[group]);
3870 	run_bbp_write(sc, 64, 0x37 - sc->lna[group]);
3871 	if (sc->mac_ver < 0x3572)
3872 		run_bbp_write(sc, 86, 0x00);
3873 
3874 	if (sc->mac_ver == 0x3593) {
3875 		run_bbp_write(sc, 77, 0x98);
3876 		run_bbp_write(sc, 83, (group == 0) ? 0x8a : 0x9a);
3877 	}
3878 
3879 	if (group == 0) {
3880 		if (sc->ext_2ghz_lna) {
3881 			if (sc->mac_ver >= 0x5390)
3882 				run_bbp_write(sc, 75, 0x52);
3883 			else {
3884 				run_bbp_write(sc, 82, 0x62);
3885 				run_bbp_write(sc, 75, 0x46);
3886 			}
3887 		} else {
3888 			if (sc->mac_ver == 0x5592) {
3889 				run_bbp_write(sc, 79, 0x1c);
3890 				run_bbp_write(sc, 80, 0x0e);
3891 				run_bbp_write(sc, 81, 0x3a);
3892 				run_bbp_write(sc, 82, 0x62);
3893 
3894 				run_bbp_write(sc, 195, 0x80);
3895 				run_bbp_write(sc, 196, 0xe0);
3896 				run_bbp_write(sc, 195, 0x81);
3897 				run_bbp_write(sc, 196, 0x1f);
3898 				run_bbp_write(sc, 195, 0x82);
3899 				run_bbp_write(sc, 196, 0x38);
3900 				run_bbp_write(sc, 195, 0x83);
3901 				run_bbp_write(sc, 196, 0x32);
3902 				run_bbp_write(sc, 195, 0x85);
3903 				run_bbp_write(sc, 196, 0x28);
3904 				run_bbp_write(sc, 195, 0x86);
3905 				run_bbp_write(sc, 196, 0x19);
3906 			} else if (sc->mac_ver >= 0x5390)
3907 				run_bbp_write(sc, 75, 0x50);
3908 			else {
3909 				run_bbp_write(sc, 82,
3910 				    (sc->mac_ver == 0x3593) ? 0x62 : 0x84);
3911 				run_bbp_write(sc, 75, 0x50);
3912 			}
3913 		}
3914 	} else {
3915 		if (sc->mac_ver == 0x5592) {
3916 			run_bbp_write(sc, 79, 0x18);
3917 			run_bbp_write(sc, 80, 0x08);
3918 			run_bbp_write(sc, 81, 0x38);
3919 			run_bbp_write(sc, 82, 0x92);
3920 
3921 			run_bbp_write(sc, 195, 0x80);
3922 			run_bbp_write(sc, 196, 0xf0);
3923 			run_bbp_write(sc, 195, 0x81);
3924 			run_bbp_write(sc, 196, 0x1e);
3925 			run_bbp_write(sc, 195, 0x82);
3926 			run_bbp_write(sc, 196, 0x28);
3927 			run_bbp_write(sc, 195, 0x83);
3928 			run_bbp_write(sc, 196, 0x20);
3929 			run_bbp_write(sc, 195, 0x85);
3930 			run_bbp_write(sc, 196, 0x7f);
3931 			run_bbp_write(sc, 195, 0x86);
3932 			run_bbp_write(sc, 196, 0x7f);
3933 		} else if (sc->mac_ver == 0x3572)
3934 			run_bbp_write(sc, 82, 0x94);
3935 		else
3936 			run_bbp_write(sc, 82,
3937 			    (sc->mac_ver == 0x3593) ? 0x82 : 0xf2);
3938 		if (sc->ext_5ghz_lna)
3939 			run_bbp_write(sc, 75, 0x46);
3940 		else
3941 			run_bbp_write(sc, 75, 0x50);
3942 	}
3943 
3944 	run_read(sc, RT2860_TX_BAND_CFG, &tmp);
3945 	tmp &= ~(RT2860_5G_BAND_SEL_N | RT2860_5G_BAND_SEL_P);
3946 	tmp |= (group == 0) ? RT2860_5G_BAND_SEL_N : RT2860_5G_BAND_SEL_P;
3947 	run_write(sc, RT2860_TX_BAND_CFG, tmp);
3948 
3949 	/* enable appropriate Power Amplifiers and Low Noise Amplifiers */
3950 	tmp = RT2860_RFTR_EN | RT2860_TRSW_EN | RT2860_LNA_PE0_EN;
3951 	if (sc->mac_ver == 0x3593)
3952 		tmp |= 1 << 29 | 1 << 28;
3953 	if (sc->nrxchains > 1)
3954 		tmp |= RT2860_LNA_PE1_EN;
3955 	if (group == 0) {	/* 2GHz */
3956 		tmp |= RT2860_PA_PE_G0_EN;
3957 		if (sc->ntxchains > 1)
3958 			tmp |= RT2860_PA_PE_G1_EN;
3959 		if (sc->mac_ver == 0x3593) {
3960 			if (sc->ntxchains > 2)
3961 				tmp |= 1 << 25;
3962 		}
3963 	} else {		/* 5GHz */
3964 		tmp |= RT2860_PA_PE_A0_EN;
3965 		if (sc->ntxchains > 1)
3966 			tmp |= RT2860_PA_PE_A1_EN;
3967 	}
3968 	if (sc->mac_ver == 0x3572) {
3969 		run_rt3070_rf_write(sc, 8, 0x00);
3970 		run_write(sc, RT2860_TX_PIN_CFG, tmp);
3971 		run_rt3070_rf_write(sc, 8, 0x80);
3972 	} else
3973 		run_write(sc, RT2860_TX_PIN_CFG, tmp);
3974 
3975 	if (sc->mac_ver == 0x5592) {
3976 		run_bbp_write(sc, 195, 0x8d);
3977 		run_bbp_write(sc, 196, 0x1a);
3978 	}
3979 
3980 	if (sc->mac_ver == 0x3593) {
3981 		run_read(sc, RT2860_GPIO_CTRL, &tmp);
3982 		tmp &= ~0x01010000;
3983 		if (group == 0)
3984 			tmp |= 0x00010000;
3985 		tmp = (tmp & ~0x00009090) | 0x00000090;
3986 		run_write(sc, RT2860_GPIO_CTRL, tmp);
3987 	}
3988 
3989 	/* set initial AGC value */
3990 	if (group == 0) {	/* 2GHz band */
3991 		if (sc->mac_ver >= 0x3070)
3992 			agc = 0x1c + sc->lna[0] * 2;
3993 		else
3994 			agc = 0x2e + sc->lna[0];
3995 	} else {		/* 5GHz band */
3996 		if (sc->mac_ver == 0x5592)
3997 			agc = 0x24 + sc->lna[group] * 2;
3998 		else if (sc->mac_ver == 0x3572 || sc->mac_ver == 0x3593)
3999 			agc = 0x22 + (sc->lna[group] * 5) / 3;
4000 		else
4001 			agc = 0x32 + (sc->lna[group] * 5) / 3;
4002 	}
4003 	run_set_agc(sc, agc);
4004 }
4005 
4006 static void
4007 run_rt2870_set_chan(struct run_softc *sc, u_int chan)
4008 {
4009 	const struct rfprog *rfprog = rt2860_rf2850;
4010 	uint32_t r2, r3, r4;
4011 	int8_t txpow1, txpow2;
4012 	int i;
4013 
4014 	/* find the settings for this channel (we know it exists) */
4015 	for (i = 0; rfprog[i].chan != chan; i++);
4016 
4017 	r2 = rfprog[i].r2;
4018 	if (sc->ntxchains == 1)
4019 		r2 |= 1 << 14;		/* 1T: disable Tx chain 2 */
4020 	if (sc->nrxchains == 1)
4021 		r2 |= 1 << 17 | 1 << 6;	/* 1R: disable Rx chains 2 & 3 */
4022 	else if (sc->nrxchains == 2)
4023 		r2 |= 1 << 6;		/* 2R: disable Rx chain 3 */
4024 
4025 	/* use Tx power values from EEPROM */
4026 	txpow1 = sc->txpow1[i];
4027 	txpow2 = sc->txpow2[i];
4028 
4029 	/* Initialize RF R3 and R4. */
4030 	r3 = rfprog[i].r3 & 0xffffc1ff;
4031 	r4 = (rfprog[i].r4 & ~(0x001f87c0)) | (sc->freq << 15);
4032 	if (chan > 14) {
4033 		if (txpow1 >= 0) {
4034 			txpow1 = (txpow1 > 0xf) ? (0xf) : (txpow1);
4035 			r3 |= (txpow1 << 10) | (1 << 9);
4036 		} else {
4037 			txpow1 += 7;
4038 
4039 			/* txpow1 is not possible larger than 15. */
4040 			r3 |= (txpow1 << 10);
4041 		}
4042 		if (txpow2 >= 0) {
4043 			txpow2 = (txpow2 > 0xf) ? (0xf) : (txpow2);
4044 			r4 |= (txpow2 << 7) | (1 << 6);
4045 		} else {
4046 			txpow2 += 7;
4047 			r4 |= (txpow2 << 7);
4048 		}
4049 	} else {
4050 		/* Set Tx0 power. */
4051 		r3 |= (txpow1 << 9);
4052 
4053 		/* Set frequency offset and Tx1 power. */
4054 		r4 |= (txpow2 << 6);
4055 	}
4056 
4057 	run_rt2870_rf_write(sc, rfprog[i].r1);
4058 	run_rt2870_rf_write(sc, r2);
4059 	run_rt2870_rf_write(sc, r3 & ~(1 << 2));
4060 	run_rt2870_rf_write(sc, r4);
4061 
4062 	run_delay(sc, 10);
4063 
4064 	run_rt2870_rf_write(sc, rfprog[i].r1);
4065 	run_rt2870_rf_write(sc, r2);
4066 	run_rt2870_rf_write(sc, r3 | (1 << 2));
4067 	run_rt2870_rf_write(sc, r4);
4068 
4069 	run_delay(sc, 10);
4070 
4071 	run_rt2870_rf_write(sc, rfprog[i].r1);
4072 	run_rt2870_rf_write(sc, r2);
4073 	run_rt2870_rf_write(sc, r3 & ~(1 << 2));
4074 	run_rt2870_rf_write(sc, r4);
4075 }
4076 
4077 static void
4078 run_rt3070_set_chan(struct run_softc *sc, u_int chan)
4079 {
4080 	int8_t txpow1, txpow2;
4081 	uint8_t rf;
4082 	int i;
4083 
4084 	/* find the settings for this channel (we know it exists) */
4085 	for (i = 0; rt2860_rf2850[i].chan != chan; i++);
4086 
4087 	/* use Tx power values from EEPROM */
4088 	txpow1 = sc->txpow1[i];
4089 	txpow2 = sc->txpow2[i];
4090 
4091 	run_rt3070_rf_write(sc, 2, rt3070_freqs[i].n);
4092 
4093 	/* RT3370/RT3390: RF R3 [7:4] is not reserved bits. */
4094 	run_rt3070_rf_read(sc, 3, &rf);
4095 	rf = (rf & ~0x0f) | rt3070_freqs[i].k;
4096 	run_rt3070_rf_write(sc, 3, rf);
4097 
4098 	run_rt3070_rf_read(sc, 6, &rf);
4099 	rf = (rf & ~0x03) | rt3070_freqs[i].r;
4100 	run_rt3070_rf_write(sc, 6, rf);
4101 
4102 	/* set Tx0 power */
4103 	run_rt3070_rf_read(sc, 12, &rf);
4104 	rf = (rf & ~0x1f) | txpow1;
4105 	run_rt3070_rf_write(sc, 12, rf);
4106 
4107 	/* set Tx1 power */
4108 	run_rt3070_rf_read(sc, 13, &rf);
4109 	rf = (rf & ~0x1f) | txpow2;
4110 	run_rt3070_rf_write(sc, 13, rf);
4111 
4112 	run_rt3070_rf_read(sc, 1, &rf);
4113 	rf &= ~0xfc;
4114 	if (sc->ntxchains == 1)
4115 		rf |= 1 << 7 | 1 << 5;	/* 1T: disable Tx chains 2 & 3 */
4116 	else if (sc->ntxchains == 2)
4117 		rf |= 1 << 7;		/* 2T: disable Tx chain 3 */
4118 	if (sc->nrxchains == 1)
4119 		rf |= 1 << 6 | 1 << 4;	/* 1R: disable Rx chains 2 & 3 */
4120 	else if (sc->nrxchains == 2)
4121 		rf |= 1 << 6;		/* 2R: disable Rx chain 3 */
4122 	run_rt3070_rf_write(sc, 1, rf);
4123 
4124 	/* set RF offset */
4125 	run_rt3070_rf_read(sc, 23, &rf);
4126 	rf = (rf & ~0x7f) | sc->freq;
4127 	run_rt3070_rf_write(sc, 23, rf);
4128 
4129 	/* program RF filter */
4130 	run_rt3070_rf_read(sc, 24, &rf);	/* Tx */
4131 	rf = (rf & ~0x3f) | sc->rf24_20mhz;
4132 	run_rt3070_rf_write(sc, 24, rf);
4133 	run_rt3070_rf_read(sc, 31, &rf);	/* Rx */
4134 	rf = (rf & ~0x3f) | sc->rf24_20mhz;
4135 	run_rt3070_rf_write(sc, 31, rf);
4136 
4137 	/* enable RF tuning */
4138 	run_rt3070_rf_read(sc, 7, &rf);
4139 	run_rt3070_rf_write(sc, 7, rf | 0x01);
4140 }
4141 
4142 static void
4143 run_rt3572_set_chan(struct run_softc *sc, u_int chan)
4144 {
4145 	int8_t txpow1, txpow2;
4146 	uint32_t tmp;
4147 	uint8_t rf;
4148 	int i;
4149 
4150 	/* find the settings for this channel (we know it exists) */
4151 	for (i = 0; rt2860_rf2850[i].chan != chan; i++);
4152 
4153 	/* use Tx power values from EEPROM */
4154 	txpow1 = sc->txpow1[i];
4155 	txpow2 = sc->txpow2[i];
4156 
4157 	if (chan <= 14) {
4158 		run_bbp_write(sc, 25, sc->bbp25);
4159 		run_bbp_write(sc, 26, sc->bbp26);
4160 	} else {
4161 		/* enable IQ phase correction */
4162 		run_bbp_write(sc, 25, 0x09);
4163 		run_bbp_write(sc, 26, 0xff);
4164 	}
4165 
4166 	run_rt3070_rf_write(sc, 2, rt3070_freqs[i].n);
4167 	run_rt3070_rf_write(sc, 3, rt3070_freqs[i].k);
4168 	run_rt3070_rf_read(sc, 6, &rf);
4169 	rf  = (rf & ~0x0f) | rt3070_freqs[i].r;
4170 	rf |= (chan <= 14) ? 0x08 : 0x04;
4171 	run_rt3070_rf_write(sc, 6, rf);
4172 
4173 	/* set PLL mode */
4174 	run_rt3070_rf_read(sc, 5, &rf);
4175 	rf &= ~(0x08 | 0x04);
4176 	rf |= (chan <= 14) ? 0x04 : 0x08;
4177 	run_rt3070_rf_write(sc, 5, rf);
4178 
4179 	/* set Tx power for chain 0 */
4180 	if (chan <= 14)
4181 		rf = 0x60 | txpow1;
4182 	else
4183 		rf = 0xe0 | (txpow1 & 0xc) << 1 | (txpow1 & 0x3);
4184 	run_rt3070_rf_write(sc, 12, rf);
4185 
4186 	/* set Tx power for chain 1 */
4187 	if (chan <= 14)
4188 		rf = 0x60 | txpow2;
4189 	else
4190 		rf = 0xe0 | (txpow2 & 0xc) << 1 | (txpow2 & 0x3);
4191 	run_rt3070_rf_write(sc, 13, rf);
4192 
4193 	/* set Tx/Rx streams */
4194 	run_rt3070_rf_read(sc, 1, &rf);
4195 	rf &= ~0xfc;
4196 	if (sc->ntxchains == 1)
4197 		rf |= 1 << 7 | 1 << 5;  /* 1T: disable Tx chains 2 & 3 */
4198 	else if (sc->ntxchains == 2)
4199 		rf |= 1 << 7;           /* 2T: disable Tx chain 3 */
4200 	if (sc->nrxchains == 1)
4201 		rf |= 1 << 6 | 1 << 4;  /* 1R: disable Rx chains 2 & 3 */
4202 	else if (sc->nrxchains == 2)
4203 		rf |= 1 << 6;           /* 2R: disable Rx chain 3 */
4204 	run_rt3070_rf_write(sc, 1, rf);
4205 
4206 	/* set RF offset */
4207 	run_rt3070_rf_read(sc, 23, &rf);
4208 	rf = (rf & ~0x7f) | sc->freq;
4209 	run_rt3070_rf_write(sc, 23, rf);
4210 
4211 	/* program RF filter */
4212 	rf = sc->rf24_20mhz;
4213 	run_rt3070_rf_write(sc, 24, rf);	/* Tx */
4214 	run_rt3070_rf_write(sc, 31, rf);	/* Rx */
4215 
4216 	/* enable RF tuning */
4217 	run_rt3070_rf_read(sc, 7, &rf);
4218 	rf = (chan <= 14) ? 0xd8 : ((rf & ~0xc8) | 0x14);
4219 	run_rt3070_rf_write(sc, 7, rf);
4220 
4221 	/* TSSI */
4222 	rf = (chan <= 14) ? 0xc3 : 0xc0;
4223 	run_rt3070_rf_write(sc, 9, rf);
4224 
4225 	/* set loop filter 1 */
4226 	run_rt3070_rf_write(sc, 10, 0xf1);
4227 	/* set loop filter 2 */
4228 	run_rt3070_rf_write(sc, 11, (chan <= 14) ? 0xb9 : 0x00);
4229 
4230 	/* set tx_mx2_ic */
4231 	run_rt3070_rf_write(sc, 15, (chan <= 14) ? 0x53 : 0x43);
4232 	/* set tx_mx1_ic */
4233 	if (chan <= 14)
4234 		rf = 0x48 | sc->txmixgain_2ghz;
4235 	else
4236 		rf = 0x78 | sc->txmixgain_5ghz;
4237 	run_rt3070_rf_write(sc, 16, rf);
4238 
4239 	/* set tx_lo1 */
4240 	run_rt3070_rf_write(sc, 17, 0x23);
4241 	/* set tx_lo2 */
4242 	if (chan <= 14)
4243 		rf = 0x93;
4244 	else if (chan <= 64)
4245 		rf = 0xb7;
4246 	else if (chan <= 128)
4247 		rf = 0x74;
4248 	else
4249 		rf = 0x72;
4250 	run_rt3070_rf_write(sc, 19, rf);
4251 
4252 	/* set rx_lo1 */
4253 	if (chan <= 14)
4254 		rf = 0xb3;
4255 	else if (chan <= 64)
4256 		rf = 0xf6;
4257 	else if (chan <= 128)
4258 		rf = 0xf4;
4259 	else
4260 		rf = 0xf3;
4261 	run_rt3070_rf_write(sc, 20, rf);
4262 
4263 	/* set pfd_delay */
4264 	if (chan <= 14)
4265 		rf = 0x15;
4266 	else if (chan <= 64)
4267 		rf = 0x3d;
4268 	else
4269 		rf = 0x01;
4270 	run_rt3070_rf_write(sc, 25, rf);
4271 
4272 	/* set rx_lo2 */
4273 	run_rt3070_rf_write(sc, 26, (chan <= 14) ? 0x85 : 0x87);
4274 	/* set ldo_rf_vc */
4275 	run_rt3070_rf_write(sc, 27, (chan <= 14) ? 0x00 : 0x01);
4276 	/* set drv_cc */
4277 	run_rt3070_rf_write(sc, 29, (chan <= 14) ? 0x9b : 0x9f);
4278 
4279 	run_read(sc, RT2860_GPIO_CTRL, &tmp);
4280 	tmp &= ~0x8080;
4281 	if (chan <= 14)
4282 		tmp |= 0x80;
4283 	run_write(sc, RT2860_GPIO_CTRL, tmp);
4284 
4285 	/* enable RF tuning */
4286 	run_rt3070_rf_read(sc, 7, &rf);
4287 	run_rt3070_rf_write(sc, 7, rf | 0x01);
4288 
4289 	run_delay(sc, 2);
4290 }
4291 
4292 static void
4293 run_rt3593_set_chan(struct run_softc *sc, u_int chan)
4294 {
4295 	int8_t txpow1, txpow2, txpow3;
4296 	uint8_t h20mhz, rf;
4297 	int i;
4298 
4299 	/* find the settings for this channel (we know it exists) */
4300 	for (i = 0; rt2860_rf2850[i].chan != chan; i++);
4301 
4302 	/* use Tx power values from EEPROM */
4303 	txpow1 = sc->txpow1[i];
4304 	txpow2 = sc->txpow2[i];
4305 	txpow3 = (sc->ntxchains == 3) ? sc->txpow3[i] : 0;
4306 
4307 	if (chan <= 14) {
4308 		run_bbp_write(sc, 25, sc->bbp25);
4309 		run_bbp_write(sc, 26, sc->bbp26);
4310 	} else {
4311 		/* Enable IQ phase correction. */
4312 		run_bbp_write(sc, 25, 0x09);
4313 		run_bbp_write(sc, 26, 0xff);
4314 	}
4315 
4316 	run_rt3070_rf_write(sc, 8, rt3070_freqs[i].n);
4317 	run_rt3070_rf_write(sc, 9, rt3070_freqs[i].k & 0x0f);
4318 	run_rt3070_rf_read(sc, 11, &rf);
4319 	rf = (rf & ~0x03) | (rt3070_freqs[i].r & 0x03);
4320 	run_rt3070_rf_write(sc, 11, rf);
4321 
4322 	/* Set pll_idoh. */
4323 	run_rt3070_rf_read(sc, 11, &rf);
4324 	rf &= ~0x4c;
4325 	rf |= (chan <= 14) ? 0x44 : 0x48;
4326 	run_rt3070_rf_write(sc, 11, rf);
4327 
4328 	if (chan <= 14)
4329 		rf = txpow1 & 0x1f;
4330 	else
4331 		rf = 0x40 | ((txpow1 & 0x18) << 1) | (txpow1 & 0x07);
4332 	run_rt3070_rf_write(sc, 53, rf);
4333 
4334 	if (chan <= 14)
4335 		rf = txpow2 & 0x1f;
4336 	else
4337 		rf = 0x40 | ((txpow2 & 0x18) << 1) | (txpow2 & 0x07);
4338 	run_rt3070_rf_write(sc, 55, rf);
4339 
4340 	if (chan <= 14)
4341 		rf = txpow3 & 0x1f;
4342 	else
4343 		rf = 0x40 | ((txpow3 & 0x18) << 1) | (txpow3 & 0x07);
4344 	run_rt3070_rf_write(sc, 54, rf);
4345 
4346 	rf = RT3070_RF_BLOCK | RT3070_PLL_PD;
4347 	if (sc->ntxchains == 3)
4348 		rf |= RT3070_TX0_PD | RT3070_TX1_PD | RT3070_TX2_PD;
4349 	else
4350 		rf |= RT3070_TX0_PD | RT3070_TX1_PD;
4351 	rf |= RT3070_RX0_PD | RT3070_RX1_PD | RT3070_RX2_PD;
4352 	run_rt3070_rf_write(sc, 1, rf);
4353 
4354 	run_adjust_freq_offset(sc);
4355 
4356 	run_rt3070_rf_write(sc, 31, (chan <= 14) ? 0xa0 : 0x80);
4357 
4358 	h20mhz = (sc->rf24_20mhz & 0x20) >> 5;
4359 	run_rt3070_rf_read(sc, 30, &rf);
4360 	rf = (rf & ~0x06) | (h20mhz << 1) | (h20mhz << 2);
4361 	run_rt3070_rf_write(sc, 30, rf);
4362 
4363 	run_rt3070_rf_read(sc, 36, &rf);
4364 	if (chan <= 14)
4365 		rf |= 0x80;
4366 	else
4367 		rf &= ~0x80;
4368 	run_rt3070_rf_write(sc, 36, rf);
4369 
4370 	/* Set vcolo_bs. */
4371 	run_rt3070_rf_write(sc, 34, (chan <= 14) ? 0x3c : 0x20);
4372 	/* Set pfd_delay. */
4373 	run_rt3070_rf_write(sc, 12, (chan <= 14) ? 0x1a : 0x12);
4374 
4375 	/* Set vco bias current control. */
4376 	run_rt3070_rf_read(sc, 6, &rf);
4377 	rf &= ~0xc0;
4378 	if (chan <= 14)
4379 		rf |= 0x40;
4380 	else if (chan <= 128)
4381 		rf |= 0x80;
4382 	else
4383 		rf |= 0x40;
4384 	run_rt3070_rf_write(sc, 6, rf);
4385 
4386 	run_rt3070_rf_read(sc, 30, &rf);
4387 	rf = (rf & ~0x18) | 0x10;
4388 	run_rt3070_rf_write(sc, 30, rf);
4389 
4390 	run_rt3070_rf_write(sc, 10, (chan <= 14) ? 0xd3 : 0xd8);
4391 	run_rt3070_rf_write(sc, 13, (chan <= 14) ? 0x12 : 0x23);
4392 
4393 	run_rt3070_rf_read(sc, 51, &rf);
4394 	rf = (rf & ~0x03) | 0x01;
4395 	run_rt3070_rf_write(sc, 51, rf);
4396 	/* Set tx_mx1_cc. */
4397 	run_rt3070_rf_read(sc, 51, &rf);
4398 	rf &= ~0x1c;
4399 	rf |= (chan <= 14) ? 0x14 : 0x10;
4400 	run_rt3070_rf_write(sc, 51, rf);
4401 	/* Set tx_mx1_ic. */
4402 	run_rt3070_rf_read(sc, 51, &rf);
4403 	rf &= ~0xe0;
4404 	rf |= (chan <= 14) ? 0x60 : 0x40;
4405 	run_rt3070_rf_write(sc, 51, rf);
4406 	/* Set tx_lo1_ic. */
4407 	run_rt3070_rf_read(sc, 49, &rf);
4408 	rf &= ~0x1c;
4409 	rf |= (chan <= 14) ? 0x0c : 0x08;
4410 	run_rt3070_rf_write(sc, 49, rf);
4411 	/* Set tx_lo1_en. */
4412 	run_rt3070_rf_read(sc, 50, &rf);
4413 	run_rt3070_rf_write(sc, 50, rf & ~0x20);
4414 	/* Set drv_cc. */
4415 	run_rt3070_rf_read(sc, 57, &rf);
4416 	rf &= ~0xfc;
4417 	rf |= (chan <= 14) ?  0x6c : 0x3c;
4418 	run_rt3070_rf_write(sc, 57, rf);
4419 	/* Set rx_mix1_ic, rxa_lnactr, lna_vc, lna_inbias_en and lna_en. */
4420 	run_rt3070_rf_write(sc, 44, (chan <= 14) ? 0x93 : 0x9b);
4421 	/* Set drv_gnd_a, tx_vga_cc_a and tx_mx2_gain. */
4422 	run_rt3070_rf_write(sc, 52, (chan <= 14) ? 0x45 : 0x05);
4423 	/* Enable VCO calibration. */
4424 	run_rt3070_rf_read(sc, 3, &rf);
4425 	rf &= ~RT5390_VCOCAL;
4426 	rf |= (chan <= 14) ? RT5390_VCOCAL : 0xbe;
4427 	run_rt3070_rf_write(sc, 3, rf);
4428 
4429 	if (chan <= 14)
4430 		rf = 0x23;
4431 	else if (chan <= 64)
4432 		rf = 0x36;
4433 	else if (chan <= 128)
4434 		rf = 0x32;
4435 	else
4436 		rf = 0x30;
4437 	run_rt3070_rf_write(sc, 39, rf);
4438 	if (chan <= 14)
4439 		rf = 0xbb;
4440 	else if (chan <= 64)
4441 		rf = 0xeb;
4442 	else if (chan <= 128)
4443 		rf = 0xb3;
4444 	else
4445 		rf = 0x9b;
4446 	run_rt3070_rf_write(sc, 45, rf);
4447 
4448 	/* Set FEQ/AEQ control. */
4449 	run_bbp_write(sc, 105, 0x34);
4450 }
4451 
4452 static void
4453 run_rt5390_set_chan(struct run_softc *sc, u_int chan)
4454 {
4455 	int8_t txpow1, txpow2;
4456 	uint8_t rf;
4457 	int i;
4458 
4459 	/* find the settings for this channel (we know it exists) */
4460 	for (i = 0; rt2860_rf2850[i].chan != chan; i++);
4461 
4462 	/* use Tx power values from EEPROM */
4463 	txpow1 = sc->txpow1[i];
4464 	txpow2 = sc->txpow2[i];
4465 
4466 	run_rt3070_rf_write(sc, 8, rt3070_freqs[i].n);
4467 	run_rt3070_rf_write(sc, 9, rt3070_freqs[i].k & 0x0f);
4468 	run_rt3070_rf_read(sc, 11, &rf);
4469 	rf = (rf & ~0x03) | (rt3070_freqs[i].r & 0x03);
4470 	run_rt3070_rf_write(sc, 11, rf);
4471 
4472 	run_rt3070_rf_read(sc, 49, &rf);
4473 	rf = (rf & ~0x3f) | (txpow1 & 0x3f);
4474 	/* The valid range of the RF R49 is 0x00 to 0x27. */
4475 	if ((rf & 0x3f) > 0x27)
4476 		rf = (rf & ~0x3f) | 0x27;
4477 	run_rt3070_rf_write(sc, 49, rf);
4478 
4479 	if (sc->mac_ver == 0x5392) {
4480 		run_rt3070_rf_read(sc, 50, &rf);
4481 		rf = (rf & ~0x3f) | (txpow2 & 0x3f);
4482 		/* The valid range of the RF R50 is 0x00 to 0x27. */
4483 		if ((rf & 0x3f) > 0x27)
4484 			rf = (rf & ~0x3f) | 0x27;
4485 		run_rt3070_rf_write(sc, 50, rf);
4486 	}
4487 
4488 	run_rt3070_rf_read(sc, 1, &rf);
4489 	rf |= RT3070_RF_BLOCK | RT3070_PLL_PD | RT3070_RX0_PD | RT3070_TX0_PD;
4490 	if (sc->mac_ver == 0x5392)
4491 		rf |= RT3070_RX1_PD | RT3070_TX1_PD;
4492 	run_rt3070_rf_write(sc, 1, rf);
4493 
4494 	if (sc->mac_ver != 0x5392) {
4495 		run_rt3070_rf_read(sc, 2, &rf);
4496 		rf |= 0x80;
4497 		run_rt3070_rf_write(sc, 2, rf);
4498 		run_delay(sc, 10);
4499 		rf &= 0x7f;
4500 		run_rt3070_rf_write(sc, 2, rf);
4501 	}
4502 
4503 	run_adjust_freq_offset(sc);
4504 
4505 	if (sc->mac_ver == 0x5392) {
4506 		/* Fix for RT5392C. */
4507 		if (sc->mac_rev >= 0x0223) {
4508 			if (chan <= 4)
4509 				rf = 0x0f;
4510 			else if (chan >= 5 && chan <= 7)
4511 				rf = 0x0e;
4512 			else
4513 				rf = 0x0d;
4514 			run_rt3070_rf_write(sc, 23, rf);
4515 
4516 			if (chan <= 4)
4517 				rf = 0x0c;
4518 			else if (chan == 5)
4519 				rf = 0x0b;
4520 			else if (chan >= 6 && chan <= 7)
4521 				rf = 0x0a;
4522 			else if (chan >= 8 && chan <= 10)
4523 				rf = 0x09;
4524 			else
4525 				rf = 0x08;
4526 			run_rt3070_rf_write(sc, 59, rf);
4527 		} else {
4528 			if (chan <= 11)
4529 				rf = 0x0f;
4530 			else
4531 				rf = 0x0b;
4532 			run_rt3070_rf_write(sc, 59, rf);
4533 		}
4534 	} else {
4535 		/* Fix for RT5390F. */
4536 		if (sc->mac_rev >= 0x0502) {
4537 			if (chan <= 11)
4538 				rf = 0x43;
4539 			else
4540 				rf = 0x23;
4541 			run_rt3070_rf_write(sc, 55, rf);
4542 
4543 			if (chan <= 11)
4544 				rf = 0x0f;
4545 			else if (chan == 12)
4546 				rf = 0x0d;
4547 			else
4548 				rf = 0x0b;
4549 			run_rt3070_rf_write(sc, 59, rf);
4550 		} else {
4551 			run_rt3070_rf_write(sc, 55, 0x44);
4552 			run_rt3070_rf_write(sc, 59, 0x8f);
4553 		}
4554 	}
4555 
4556 	/* Enable VCO calibration. */
4557 	run_rt3070_rf_read(sc, 3, &rf);
4558 	rf |= RT5390_VCOCAL;
4559 	run_rt3070_rf_write(sc, 3, rf);
4560 }
4561 
4562 static void
4563 run_rt5592_set_chan(struct run_softc *sc, u_int chan)
4564 {
4565 	const struct rt5592_freqs *freqs;
4566 	uint32_t tmp;
4567 	uint8_t reg, rf, txpow_bound;
4568 	int8_t txpow1, txpow2;
4569 	int i;
4570 
4571 	run_read(sc, RT5592_DEBUG_INDEX, &tmp);
4572 	freqs = (tmp & RT5592_SEL_XTAL) ?
4573 	    rt5592_freqs_40mhz : rt5592_freqs_20mhz;
4574 
4575 	/* find the settings for this channel (we know it exists) */
4576 	for (i = 0; rt2860_rf2850[i].chan != chan; i++, freqs++);
4577 
4578 	/* use Tx power values from EEPROM */
4579 	txpow1 = sc->txpow1[i];
4580 	txpow2 = sc->txpow2[i];
4581 
4582 	run_read(sc, RT3070_LDO_CFG0, &tmp);
4583 	tmp &= ~0x1c000000;
4584 	if (chan > 14)
4585 		tmp |= 0x14000000;
4586 	run_write(sc, RT3070_LDO_CFG0, tmp);
4587 
4588 	/* N setting. */
4589 	run_rt3070_rf_write(sc, 8, freqs->n & 0xff);
4590 	run_rt3070_rf_read(sc, 9, &rf);
4591 	rf &= ~(1 << 4);
4592 	rf |= ((freqs->n & 0x0100) >> 8) << 4;
4593 	run_rt3070_rf_write(sc, 9, rf);
4594 
4595 	/* K setting. */
4596 	run_rt3070_rf_read(sc, 9, &rf);
4597 	rf &= ~0x0f;
4598 	rf |= (freqs->k & 0x0f);
4599 	run_rt3070_rf_write(sc, 9, rf);
4600 
4601 	/* Mode setting. */
4602 	run_rt3070_rf_read(sc, 11, &rf);
4603 	rf &= ~0x0c;
4604 	rf |= ((freqs->m - 0x8) & 0x3) << 2;
4605 	run_rt3070_rf_write(sc, 11, rf);
4606 	run_rt3070_rf_read(sc, 9, &rf);
4607 	rf &= ~(1 << 7);
4608 	rf |= (((freqs->m - 0x8) & 0x4) >> 2) << 7;
4609 	run_rt3070_rf_write(sc, 9, rf);
4610 
4611 	/* R setting. */
4612 	run_rt3070_rf_read(sc, 11, &rf);
4613 	rf &= ~0x03;
4614 	rf |= (freqs->r - 0x1);
4615 	run_rt3070_rf_write(sc, 11, rf);
4616 
4617 	if (chan <= 14) {
4618 		/* Initialize RF registers for 2GHZ. */
4619 		for (i = 0; i < nitems(rt5592_2ghz_def_rf); i++) {
4620 			run_rt3070_rf_write(sc, rt5592_2ghz_def_rf[i].reg,
4621 			    rt5592_2ghz_def_rf[i].val);
4622 		}
4623 
4624 		rf = (chan <= 10) ? 0x07 : 0x06;
4625 		run_rt3070_rf_write(sc, 23, rf);
4626 		run_rt3070_rf_write(sc, 59, rf);
4627 
4628 		run_rt3070_rf_write(sc, 55, 0x43);
4629 
4630 		/*
4631 		 * RF R49/R50 Tx power ALC code.
4632 		 * G-band bit<7:6>=1:0, bit<5:0> range from 0x0 ~ 0x27.
4633 		 */
4634 		reg = 2;
4635 		txpow_bound = 0x27;
4636 	} else {
4637 		/* Initialize RF registers for 5GHZ. */
4638 		for (i = 0; i < nitems(rt5592_5ghz_def_rf); i++) {
4639 			run_rt3070_rf_write(sc, rt5592_5ghz_def_rf[i].reg,
4640 			    rt5592_5ghz_def_rf[i].val);
4641 		}
4642 		for (i = 0; i < nitems(rt5592_chan_5ghz); i++) {
4643 			if (chan >= rt5592_chan_5ghz[i].firstchan &&
4644 			    chan <= rt5592_chan_5ghz[i].lastchan) {
4645 				run_rt3070_rf_write(sc, rt5592_chan_5ghz[i].reg,
4646 				    rt5592_chan_5ghz[i].val);
4647 			}
4648 		}
4649 
4650 		/*
4651 		 * RF R49/R50 Tx power ALC code.
4652 		 * A-band bit<7:6>=1:1, bit<5:0> range from 0x0 ~ 0x2b.
4653 		 */
4654 		reg = 3;
4655 		txpow_bound = 0x2b;
4656 	}
4657 
4658 	/* RF R49 ch0 Tx power ALC code. */
4659 	run_rt3070_rf_read(sc, 49, &rf);
4660 	rf &= ~0xc0;
4661 	rf |= (reg << 6);
4662 	rf = (rf & ~0x3f) | (txpow1 & 0x3f);
4663 	if ((rf & 0x3f) > txpow_bound)
4664 		rf = (rf & ~0x3f) | txpow_bound;
4665 	run_rt3070_rf_write(sc, 49, rf);
4666 
4667 	/* RF R50 ch1 Tx power ALC code. */
4668 	run_rt3070_rf_read(sc, 50, &rf);
4669 	rf &= ~(1 << 7 | 1 << 6);
4670 	rf |= (reg << 6);
4671 	rf = (rf & ~0x3f) | (txpow2 & 0x3f);
4672 	if ((rf & 0x3f) > txpow_bound)
4673 		rf = (rf & ~0x3f) | txpow_bound;
4674 	run_rt3070_rf_write(sc, 50, rf);
4675 
4676 	/* Enable RF_BLOCK, PLL_PD, RX0_PD, and TX0_PD. */
4677 	run_rt3070_rf_read(sc, 1, &rf);
4678 	rf |= (RT3070_RF_BLOCK | RT3070_PLL_PD | RT3070_RX0_PD | RT3070_TX0_PD);
4679 	if (sc->ntxchains > 1)
4680 		rf |= RT3070_TX1_PD;
4681 	if (sc->nrxchains > 1)
4682 		rf |= RT3070_RX1_PD;
4683 	run_rt3070_rf_write(sc, 1, rf);
4684 
4685 	run_rt3070_rf_write(sc, 6, 0xe4);
4686 
4687 	run_rt3070_rf_write(sc, 30, 0x10);
4688 	run_rt3070_rf_write(sc, 31, 0x80);
4689 	run_rt3070_rf_write(sc, 32, 0x80);
4690 
4691 	run_adjust_freq_offset(sc);
4692 
4693 	/* Enable VCO calibration. */
4694 	run_rt3070_rf_read(sc, 3, &rf);
4695 	rf |= RT5390_VCOCAL;
4696 	run_rt3070_rf_write(sc, 3, rf);
4697 }
4698 
4699 static void
4700 run_set_rx_antenna(struct run_softc *sc, int aux)
4701 {
4702 	uint32_t tmp;
4703 	uint8_t bbp152;
4704 
4705 	if (aux) {
4706 		if (sc->rf_rev == RT5390_RF_5370) {
4707 			run_bbp_read(sc, 152, &bbp152);
4708 			run_bbp_write(sc, 152, bbp152 & ~0x80);
4709 		} else {
4710 			run_mcu_cmd(sc, RT2860_MCU_CMD_ANTSEL, 0);
4711 			run_read(sc, RT2860_GPIO_CTRL, &tmp);
4712 			run_write(sc, RT2860_GPIO_CTRL, (tmp & ~0x0808) | 0x08);
4713 		}
4714 	} else {
4715 		if (sc->rf_rev == RT5390_RF_5370) {
4716 			run_bbp_read(sc, 152, &bbp152);
4717 			run_bbp_write(sc, 152, bbp152 | 0x80);
4718 		} else {
4719 			run_mcu_cmd(sc, RT2860_MCU_CMD_ANTSEL, 1);
4720 			run_read(sc, RT2860_GPIO_CTRL, &tmp);
4721 			run_write(sc, RT2860_GPIO_CTRL, tmp & ~0x0808);
4722 		}
4723 	}
4724 }
4725 
4726 static int
4727 run_set_chan(struct run_softc *sc, struct ieee80211_channel *c)
4728 {
4729 	struct ieee80211com *ic = &sc->sc_ic;
4730 	u_int chan, group;
4731 
4732 	chan = ieee80211_chan2ieee(ic, c);
4733 	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
4734 		return (EINVAL);
4735 
4736 	if (sc->mac_ver == 0x5592)
4737 		run_rt5592_set_chan(sc, chan);
4738 	else if (sc->mac_ver >= 0x5390)
4739 		run_rt5390_set_chan(sc, chan);
4740 	else if (sc->mac_ver == 0x3593)
4741 		run_rt3593_set_chan(sc, chan);
4742 	else if (sc->mac_ver == 0x3572)
4743 		run_rt3572_set_chan(sc, chan);
4744 	else if (sc->mac_ver >= 0x3070)
4745 		run_rt3070_set_chan(sc, chan);
4746 	else
4747 		run_rt2870_set_chan(sc, chan);
4748 
4749 	/* determine channel group */
4750 	if (chan <= 14)
4751 		group = 0;
4752 	else if (chan <= 64)
4753 		group = 1;
4754 	else if (chan <= 128)
4755 		group = 2;
4756 	else
4757 		group = 3;
4758 
4759 	/* XXX necessary only when group has changed! */
4760 	run_select_chan_group(sc, group);
4761 
4762 	run_delay(sc, 10);
4763 
4764 	/* Perform IQ calibration. */
4765 	if (sc->mac_ver >= 0x5392)
4766 		run_iq_calib(sc, chan);
4767 
4768 	return (0);
4769 }
4770 
4771 static void
4772 run_set_channel(struct ieee80211com *ic)
4773 {
4774 	struct run_softc *sc = ic->ic_softc;
4775 
4776 	RUN_LOCK(sc);
4777 	run_set_chan(sc, ic->ic_curchan);
4778 	RUN_UNLOCK(sc);
4779 
4780 	return;
4781 }
4782 
4783 static void
4784 run_getradiocaps(struct ieee80211com *ic,
4785     int maxchans, int *nchans, struct ieee80211_channel chans[])
4786 {
4787 	struct run_softc *sc = ic->ic_softc;
4788 	uint8_t bands[IEEE80211_MODE_BYTES];
4789 
4790 	memset(bands, 0, sizeof(bands));
4791 	setbit(bands, IEEE80211_MODE_11B);
4792 	setbit(bands, IEEE80211_MODE_11G);
4793 	ieee80211_add_channel_list_2ghz(chans, maxchans, nchans,
4794 	    run_chan_2ghz, nitems(run_chan_2ghz), bands, 0);
4795 
4796 	if (sc->rf_rev == RT2860_RF_2750 || sc->rf_rev == RT2860_RF_2850 ||
4797 	    sc->rf_rev == RT3070_RF_3052 || sc->rf_rev == RT3593_RF_3053 ||
4798 	    sc->rf_rev == RT5592_RF_5592) {
4799 		setbit(bands, IEEE80211_MODE_11A);
4800 		ieee80211_add_channel_list_5ghz(chans, maxchans, nchans,
4801 		    run_chan_5ghz, nitems(run_chan_5ghz), bands, 0);
4802 	}
4803 }
4804 
4805 static void
4806 run_scan_start(struct ieee80211com *ic)
4807 {
4808 	struct run_softc *sc = ic->ic_softc;
4809 	uint32_t tmp;
4810 
4811 	RUN_LOCK(sc);
4812 
4813 	/* abort TSF synchronization */
4814 	run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
4815 	run_write(sc, RT2860_BCN_TIME_CFG,
4816 	    tmp & ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN |
4817 	    RT2860_TBTT_TIMER_EN));
4818 	run_set_bssid(sc, ieee80211broadcastaddr);
4819 
4820 	RUN_UNLOCK(sc);
4821 
4822 	return;
4823 }
4824 
4825 static void
4826 run_scan_end(struct ieee80211com *ic)
4827 {
4828 	struct run_softc *sc = ic->ic_softc;
4829 
4830 	RUN_LOCK(sc);
4831 
4832 	run_enable_tsf_sync(sc);
4833 	run_set_bssid(sc, sc->sc_bssid);
4834 
4835 	RUN_UNLOCK(sc);
4836 
4837 	return;
4838 }
4839 
4840 /*
4841  * Could be called from ieee80211_node_timeout()
4842  * (non-sleepable thread)
4843  */
4844 static void
4845 run_update_beacon(struct ieee80211vap *vap, int item)
4846 {
4847 	struct ieee80211com *ic = vap->iv_ic;
4848 	struct ieee80211_beacon_offsets *bo = &vap->iv_bcn_off;
4849 	struct ieee80211_node *ni = vap->iv_bss;
4850 	struct run_softc *sc = ic->ic_softc;
4851 	struct run_vap *rvp = RUN_VAP(vap);
4852 	int mcast = 0;
4853 	uint32_t i;
4854 
4855 	switch (item) {
4856 	case IEEE80211_BEACON_ERP:
4857 		run_updateslot(ic);
4858 		break;
4859 	case IEEE80211_BEACON_HTINFO:
4860 		run_updateprot(ic);
4861 		break;
4862 	case IEEE80211_BEACON_TIM:
4863 		mcast = 1;	/*TODO*/
4864 		break;
4865 	default:
4866 		break;
4867 	}
4868 
4869 	setbit(bo->bo_flags, item);
4870 	if (rvp->beacon_mbuf == NULL) {
4871 		rvp->beacon_mbuf = ieee80211_beacon_alloc(ni);
4872 		if (rvp->beacon_mbuf == NULL)
4873 			return;
4874 	}
4875 	ieee80211_beacon_update(ni, rvp->beacon_mbuf, mcast);
4876 
4877 	i = RUN_CMDQ_GET(&sc->cmdq_store);
4878 	DPRINTF("cmdq_store=%d\n", i);
4879 	sc->cmdq[i].func = run_update_beacon_cb;
4880 	sc->cmdq[i].arg0 = vap;
4881 	ieee80211_runtask(ic, &sc->cmdq_task);
4882 
4883 	return;
4884 }
4885 
4886 static void
4887 run_update_beacon_cb(void *arg)
4888 {
4889 	struct ieee80211vap *vap = arg;
4890 	struct ieee80211_node *ni = vap->iv_bss;
4891 	struct run_vap *rvp = RUN_VAP(vap);
4892 	struct ieee80211com *ic = vap->iv_ic;
4893 	struct run_softc *sc = ic->ic_softc;
4894 	struct rt2860_txwi txwi;
4895 	struct mbuf *m;
4896 	uint16_t txwisize;
4897 	uint8_t ridx;
4898 
4899 	if (ni->ni_chan == IEEE80211_CHAN_ANYC)
4900 		return;
4901 	if (ic->ic_bsschan == IEEE80211_CHAN_ANYC)
4902 		return;
4903 
4904 	/*
4905 	 * No need to call ieee80211_beacon_update(), run_update_beacon()
4906 	 * is taking care of appropriate calls.
4907 	 */
4908 	if (rvp->beacon_mbuf == NULL) {
4909 		rvp->beacon_mbuf = ieee80211_beacon_alloc(ni);
4910 		if (rvp->beacon_mbuf == NULL)
4911 			return;
4912 	}
4913 	m = rvp->beacon_mbuf;
4914 
4915 	memset(&txwi, 0, sizeof(txwi));
4916 	txwi.wcid = 0xff;
4917 	txwi.len = htole16(m->m_pkthdr.len);
4918 
4919 	/* send beacons at the lowest available rate */
4920 	ridx = (ic->ic_curmode == IEEE80211_MODE_11A) ?
4921 	    RT2860_RIDX_OFDM6 : RT2860_RIDX_CCK1;
4922 	txwi.phy = htole16(rt2860_rates[ridx].mcs);
4923 	if (rt2860_rates[ridx].phy == IEEE80211_T_OFDM)
4924 		txwi.phy |= htole16(RT2860_PHY_OFDM);
4925 	txwi.txop = RT2860_TX_TXOP_HT;
4926 	txwi.flags = RT2860_TX_TS;
4927 	txwi.xflags = RT2860_TX_NSEQ;
4928 
4929 	txwisize = (sc->mac_ver == 0x5592) ?
4930 	    sizeof(txwi) + sizeof(uint32_t) : sizeof(txwi);
4931 	run_write_region_1(sc, RT2860_BCN_BASE(rvp->rvp_id), (uint8_t *)&txwi,
4932 	    txwisize);
4933 	run_write_region_1(sc, RT2860_BCN_BASE(rvp->rvp_id) + txwisize,
4934 	    mtod(m, uint8_t *), (m->m_pkthdr.len + 1) & ~1);
4935 }
4936 
4937 static void
4938 run_updateprot(struct ieee80211com *ic)
4939 {
4940 	struct run_softc *sc = ic->ic_softc;
4941 	uint32_t i;
4942 
4943 	i = RUN_CMDQ_GET(&sc->cmdq_store);
4944 	DPRINTF("cmdq_store=%d\n", i);
4945 	sc->cmdq[i].func = run_updateprot_cb;
4946 	sc->cmdq[i].arg0 = ic;
4947 	ieee80211_runtask(ic, &sc->cmdq_task);
4948 }
4949 
4950 static void
4951 run_updateprot_cb(void *arg)
4952 {
4953 	struct ieee80211com *ic = arg;
4954 	struct run_softc *sc = ic->ic_softc;
4955 	uint32_t tmp;
4956 
4957 	tmp = RT2860_RTSTH_EN | RT2860_PROT_NAV_SHORT | RT2860_TXOP_ALLOW_ALL;
4958 	/* setup protection frame rate (MCS code) */
4959 	tmp |= (ic->ic_curmode == IEEE80211_MODE_11A) ?
4960 	    rt2860_rates[RT2860_RIDX_OFDM6].mcs | RT2860_PHY_OFDM :
4961 	    rt2860_rates[RT2860_RIDX_CCK11].mcs;
4962 
4963 	/* CCK frames don't require protection */
4964 	run_write(sc, RT2860_CCK_PROT_CFG, tmp);
4965 	if (ic->ic_flags & IEEE80211_F_USEPROT) {
4966 		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
4967 			tmp |= RT2860_PROT_CTRL_RTS_CTS;
4968 		else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
4969 			tmp |= RT2860_PROT_CTRL_CTS;
4970 	}
4971 	run_write(sc, RT2860_OFDM_PROT_CFG, tmp);
4972 }
4973 
4974 static void
4975 run_usb_timeout_cb(void *arg)
4976 {
4977 	struct ieee80211vap *vap = arg;
4978 	struct run_softc *sc = vap->iv_ic->ic_softc;
4979 
4980 	RUN_LOCK_ASSERT(sc, MA_OWNED);
4981 
4982 	if(vap->iv_state == IEEE80211_S_RUN &&
4983 	    vap->iv_opmode != IEEE80211_M_STA)
4984 		run_reset_livelock(sc);
4985 	else if (vap->iv_state == IEEE80211_S_SCAN) {
4986 		DPRINTF("timeout caused by scan\n");
4987 		/* cancel bgscan */
4988 		ieee80211_cancel_scan(vap);
4989 	} else
4990 		DPRINTF("timeout by unknown cause\n");
4991 }
4992 
4993 static void
4994 run_reset_livelock(struct run_softc *sc)
4995 {
4996 	uint32_t tmp;
4997 
4998 	RUN_LOCK_ASSERT(sc, MA_OWNED);
4999 
5000 	/*
5001 	 * In IBSS or HostAP modes (when the hardware sends beacons), the MAC
5002 	 * can run into a livelock and start sending CTS-to-self frames like
5003 	 * crazy if protection is enabled.  Reset MAC/BBP for a while
5004 	 */
5005 	run_read(sc, RT2860_DEBUG, &tmp);
5006 	DPRINTFN(3, "debug reg %08x\n", tmp);
5007 	if ((tmp & (1 << 29)) && (tmp & (1 << 7 | 1 << 5))) {
5008 		DPRINTF("CTS-to-self livelock detected\n");
5009 		run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_MAC_SRST);
5010 		run_delay(sc, 1);
5011 		run_write(sc, RT2860_MAC_SYS_CTRL,
5012 		    RT2860_MAC_RX_EN | RT2860_MAC_TX_EN);
5013 	}
5014 }
5015 
5016 static void
5017 run_update_promisc_locked(struct run_softc *sc)
5018 {
5019         uint32_t tmp;
5020 
5021 	run_read(sc, RT2860_RX_FILTR_CFG, &tmp);
5022 
5023 	tmp |= RT2860_DROP_UC_NOME;
5024         if (sc->sc_ic.ic_promisc > 0)
5025 		tmp &= ~RT2860_DROP_UC_NOME;
5026 
5027 	run_write(sc, RT2860_RX_FILTR_CFG, tmp);
5028 
5029         DPRINTF("%s promiscuous mode\n", (sc->sc_ic.ic_promisc > 0) ?
5030             "entering" : "leaving");
5031 }
5032 
5033 static void
5034 run_update_promisc(struct ieee80211com *ic)
5035 {
5036 	struct run_softc *sc = ic->ic_softc;
5037 
5038 	if ((sc->sc_flags & RUN_RUNNING) == 0)
5039 		return;
5040 
5041 	RUN_LOCK(sc);
5042 	run_update_promisc_locked(sc);
5043 	RUN_UNLOCK(sc);
5044 }
5045 
5046 static void
5047 run_enable_tsf_sync(struct run_softc *sc)
5048 {
5049 	struct ieee80211com *ic = &sc->sc_ic;
5050 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5051 	uint32_t tmp;
5052 
5053 	DPRINTF("rvp_id=%d ic_opmode=%d\n", RUN_VAP(vap)->rvp_id,
5054 	    ic->ic_opmode);
5055 
5056 	run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
5057 	tmp &= ~0x1fffff;
5058 	tmp |= vap->iv_bss->ni_intval * 16;
5059 	tmp |= RT2860_TSF_TIMER_EN | RT2860_TBTT_TIMER_EN;
5060 
5061 	if (ic->ic_opmode == IEEE80211_M_STA) {
5062 		/*
5063 		 * Local TSF is always updated with remote TSF on beacon
5064 		 * reception.
5065 		 */
5066 		tmp |= 1 << RT2860_TSF_SYNC_MODE_SHIFT;
5067 	} else if (ic->ic_opmode == IEEE80211_M_IBSS) {
5068 	        tmp |= RT2860_BCN_TX_EN;
5069 	        /*
5070 	         * Local TSF is updated with remote TSF on beacon reception
5071 	         * only if the remote TSF is greater than local TSF.
5072 	         */
5073 	        tmp |= 2 << RT2860_TSF_SYNC_MODE_SHIFT;
5074 	} else if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
5075 		    ic->ic_opmode == IEEE80211_M_MBSS) {
5076 	        tmp |= RT2860_BCN_TX_EN;
5077 	        /* SYNC with nobody */
5078 	        tmp |= 3 << RT2860_TSF_SYNC_MODE_SHIFT;
5079 	} else {
5080 		DPRINTF("Enabling TSF failed. undefined opmode\n");
5081 		return;
5082 	}
5083 
5084 	run_write(sc, RT2860_BCN_TIME_CFG, tmp);
5085 }
5086 
5087 static void
5088 run_enable_tsf(struct run_softc *sc)
5089 {
5090 	uint32_t tmp;
5091 
5092 	if (run_read(sc, RT2860_BCN_TIME_CFG, &tmp) == 0) {
5093 		tmp &= ~(RT2860_BCN_TX_EN | RT2860_TBTT_TIMER_EN);
5094 		tmp |= RT2860_TSF_TIMER_EN;
5095 		run_write(sc, RT2860_BCN_TIME_CFG, tmp);
5096 	}
5097 }
5098 
5099 static void
5100 run_get_tsf(struct run_softc *sc, uint64_t *buf)
5101 {
5102 	run_read_region_1(sc, RT2860_TSF_TIMER_DW0, (uint8_t *)buf,
5103 	    sizeof(*buf));
5104 }
5105 
5106 static void
5107 run_enable_mrr(struct run_softc *sc)
5108 {
5109 #define	CCK(mcs)	(mcs)
5110 #define	OFDM(mcs)	(1 << 3 | (mcs))
5111 	run_write(sc, RT2860_LG_FBK_CFG0,
5112 	    OFDM(6) << 28 |	/* 54->48 */
5113 	    OFDM(5) << 24 |	/* 48->36 */
5114 	    OFDM(4) << 20 |	/* 36->24 */
5115 	    OFDM(3) << 16 |	/* 24->18 */
5116 	    OFDM(2) << 12 |	/* 18->12 */
5117 	    OFDM(1) <<  8 |	/* 12-> 9 */
5118 	    OFDM(0) <<  4 |	/*  9-> 6 */
5119 	    OFDM(0));		/*  6-> 6 */
5120 
5121 	run_write(sc, RT2860_LG_FBK_CFG1,
5122 	    CCK(2) << 12 |	/* 11->5.5 */
5123 	    CCK(1) <<  8 |	/* 5.5-> 2 */
5124 	    CCK(0) <<  4 |	/*   2-> 1 */
5125 	    CCK(0));		/*   1-> 1 */
5126 #undef OFDM
5127 #undef CCK
5128 }
5129 
5130 static void
5131 run_set_txpreamble(struct run_softc *sc)
5132 {
5133 	struct ieee80211com *ic = &sc->sc_ic;
5134 	uint32_t tmp;
5135 
5136 	run_read(sc, RT2860_AUTO_RSP_CFG, &tmp);
5137 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
5138 		tmp |= RT2860_CCK_SHORT_EN;
5139 	else
5140 		tmp &= ~RT2860_CCK_SHORT_EN;
5141 	run_write(sc, RT2860_AUTO_RSP_CFG, tmp);
5142 }
5143 
5144 static void
5145 run_set_basicrates(struct run_softc *sc)
5146 {
5147 	struct ieee80211com *ic = &sc->sc_ic;
5148 
5149 	/* set basic rates mask */
5150 	if (ic->ic_curmode == IEEE80211_MODE_11B)
5151 		run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x003);
5152 	else if (ic->ic_curmode == IEEE80211_MODE_11A)
5153 		run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x150);
5154 	else	/* 11g */
5155 		run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x15f);
5156 }
5157 
5158 static void
5159 run_set_leds(struct run_softc *sc, uint16_t which)
5160 {
5161 	(void)run_mcu_cmd(sc, RT2860_MCU_CMD_LEDS,
5162 	    which | (sc->leds & 0x7f));
5163 }
5164 
5165 static void
5166 run_set_bssid(struct run_softc *sc, const uint8_t *bssid)
5167 {
5168 	run_write(sc, RT2860_MAC_BSSID_DW0,
5169 	    bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24);
5170 	run_write(sc, RT2860_MAC_BSSID_DW1,
5171 	    bssid[4] | bssid[5] << 8);
5172 }
5173 
5174 static void
5175 run_set_macaddr(struct run_softc *sc, const uint8_t *addr)
5176 {
5177 	run_write(sc, RT2860_MAC_ADDR_DW0,
5178 	    addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24);
5179 	run_write(sc, RT2860_MAC_ADDR_DW1,
5180 	    addr[4] | addr[5] << 8 | 0xff << 16);
5181 }
5182 
5183 static void
5184 run_updateslot(struct ieee80211com *ic)
5185 {
5186 	struct run_softc *sc = ic->ic_softc;
5187 	uint32_t i;
5188 
5189 	i = RUN_CMDQ_GET(&sc->cmdq_store);
5190 	DPRINTF("cmdq_store=%d\n", i);
5191 	sc->cmdq[i].func = run_updateslot_cb;
5192 	sc->cmdq[i].arg0 = ic;
5193 	ieee80211_runtask(ic, &sc->cmdq_task);
5194 
5195 	return;
5196 }
5197 
5198 /* ARGSUSED */
5199 static void
5200 run_updateslot_cb(void *arg)
5201 {
5202 	struct ieee80211com *ic = arg;
5203 	struct run_softc *sc = ic->ic_softc;
5204 	uint32_t tmp;
5205 
5206 	run_read(sc, RT2860_BKOFF_SLOT_CFG, &tmp);
5207 	tmp &= ~0xff;
5208 	tmp |= IEEE80211_GET_SLOTTIME(ic);
5209 	run_write(sc, RT2860_BKOFF_SLOT_CFG, tmp);
5210 }
5211 
5212 static void
5213 run_update_mcast(struct ieee80211com *ic)
5214 {
5215 }
5216 
5217 static int8_t
5218 run_rssi2dbm(struct run_softc *sc, uint8_t rssi, uint8_t rxchain)
5219 {
5220 	struct ieee80211com *ic = &sc->sc_ic;
5221 	struct ieee80211_channel *c = ic->ic_curchan;
5222 	int delta;
5223 
5224 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
5225 		u_int chan = ieee80211_chan2ieee(ic, c);
5226 		delta = sc->rssi_5ghz[rxchain];
5227 
5228 		/* determine channel group */
5229 		if (chan <= 64)
5230 			delta -= sc->lna[1];
5231 		else if (chan <= 128)
5232 			delta -= sc->lna[2];
5233 		else
5234 			delta -= sc->lna[3];
5235 	} else
5236 		delta = sc->rssi_2ghz[rxchain] - sc->lna[0];
5237 
5238 	return (-12 - delta - rssi);
5239 }
5240 
5241 static void
5242 run_rt5390_bbp_init(struct run_softc *sc)
5243 {
5244 	u_int i;
5245 	uint8_t bbp;
5246 
5247 	/* Apply maximum likelihood detection for 2 stream case. */
5248 	run_bbp_read(sc, 105, &bbp);
5249 	if (sc->nrxchains > 1)
5250 		run_bbp_write(sc, 105, bbp | RT5390_MLD);
5251 
5252 	/* Avoid data lost and CRC error. */
5253 	run_bbp_read(sc, 4, &bbp);
5254 	run_bbp_write(sc, 4, bbp | RT5390_MAC_IF_CTRL);
5255 
5256 	if (sc->mac_ver == 0x5592) {
5257 		for (i = 0; i < nitems(rt5592_def_bbp); i++) {
5258 			run_bbp_write(sc, rt5592_def_bbp[i].reg,
5259 			    rt5592_def_bbp[i].val);
5260 		}
5261 		for (i = 0; i < nitems(rt5592_bbp_r196); i++) {
5262 			run_bbp_write(sc, 195, i + 0x80);
5263 			run_bbp_write(sc, 196, rt5592_bbp_r196[i]);
5264 		}
5265 	} else {
5266 		for (i = 0; i < nitems(rt5390_def_bbp); i++) {
5267 			run_bbp_write(sc, rt5390_def_bbp[i].reg,
5268 			    rt5390_def_bbp[i].val);
5269 		}
5270 	}
5271 	if (sc->mac_ver == 0x5392) {
5272 		run_bbp_write(sc, 88, 0x90);
5273 		run_bbp_write(sc, 95, 0x9a);
5274 		run_bbp_write(sc, 98, 0x12);
5275 		run_bbp_write(sc, 106, 0x12);
5276 		run_bbp_write(sc, 134, 0xd0);
5277 		run_bbp_write(sc, 135, 0xf6);
5278 		run_bbp_write(sc, 148, 0x84);
5279 	}
5280 
5281 	run_bbp_read(sc, 152, &bbp);
5282 	run_bbp_write(sc, 152, bbp | 0x80);
5283 
5284 	/* Fix BBP254 for RT5592C. */
5285 	if (sc->mac_ver == 0x5592 && sc->mac_rev >= 0x0221) {
5286 		run_bbp_read(sc, 254, &bbp);
5287 		run_bbp_write(sc, 254, bbp | 0x80);
5288 	}
5289 
5290 	/* Disable hardware antenna diversity. */
5291 	if (sc->mac_ver == 0x5390)
5292 		run_bbp_write(sc, 154, 0);
5293 
5294 	/* Initialize Rx CCK/OFDM frequency offset report. */
5295 	run_bbp_write(sc, 142, 1);
5296 	run_bbp_write(sc, 143, 57);
5297 }
5298 
5299 static int
5300 run_bbp_init(struct run_softc *sc)
5301 {
5302 	int i, error, ntries;
5303 	uint8_t bbp0;
5304 
5305 	/* wait for BBP to wake up */
5306 	for (ntries = 0; ntries < 20; ntries++) {
5307 		if ((error = run_bbp_read(sc, 0, &bbp0)) != 0)
5308 			return error;
5309 		if (bbp0 != 0 && bbp0 != 0xff)
5310 			break;
5311 	}
5312 	if (ntries == 20)
5313 		return (ETIMEDOUT);
5314 
5315 	/* initialize BBP registers to default values */
5316 	if (sc->mac_ver >= 0x5390)
5317 		run_rt5390_bbp_init(sc);
5318 	else {
5319 		for (i = 0; i < nitems(rt2860_def_bbp); i++) {
5320 			run_bbp_write(sc, rt2860_def_bbp[i].reg,
5321 			    rt2860_def_bbp[i].val);
5322 		}
5323 	}
5324 
5325 	if (sc->mac_ver == 0x3593) {
5326 		run_bbp_write(sc, 79, 0x13);
5327 		run_bbp_write(sc, 80, 0x05);
5328 		run_bbp_write(sc, 81, 0x33);
5329 		run_bbp_write(sc, 86, 0x46);
5330 		run_bbp_write(sc, 137, 0x0f);
5331 	}
5332 
5333 	/* fix BBP84 for RT2860E */
5334 	if (sc->mac_ver == 0x2860 && sc->mac_rev != 0x0101)
5335 		run_bbp_write(sc, 84, 0x19);
5336 
5337 	if (sc->mac_ver >= 0x3070 && (sc->mac_ver != 0x3593 &&
5338 	    sc->mac_ver != 0x5592)) {
5339 		run_bbp_write(sc, 79, 0x13);
5340 		run_bbp_write(sc, 80, 0x05);
5341 		run_bbp_write(sc, 81, 0x33);
5342 	} else if (sc->mac_ver == 0x2860 && sc->mac_rev == 0x0100) {
5343 		run_bbp_write(sc, 69, 0x16);
5344 		run_bbp_write(sc, 73, 0x12);
5345 	}
5346 	return (0);
5347 }
5348 
5349 static int
5350 run_rt3070_rf_init(struct run_softc *sc)
5351 {
5352 	uint32_t tmp;
5353 	uint8_t bbp4, mingain, rf, target;
5354 	u_int i;
5355 
5356 	run_rt3070_rf_read(sc, 30, &rf);
5357 	/* toggle RF R30 bit 7 */
5358 	run_rt3070_rf_write(sc, 30, rf | 0x80);
5359 	run_delay(sc, 10);
5360 	run_rt3070_rf_write(sc, 30, rf & ~0x80);
5361 
5362 	/* initialize RF registers to default value */
5363 	if (sc->mac_ver == 0x3572) {
5364 		for (i = 0; i < nitems(rt3572_def_rf); i++) {
5365 			run_rt3070_rf_write(sc, rt3572_def_rf[i].reg,
5366 			    rt3572_def_rf[i].val);
5367 		}
5368 	} else {
5369 		for (i = 0; i < nitems(rt3070_def_rf); i++) {
5370 			run_rt3070_rf_write(sc, rt3070_def_rf[i].reg,
5371 			    rt3070_def_rf[i].val);
5372 		}
5373 	}
5374 
5375 	if (sc->mac_ver == 0x3070 && sc->mac_rev < 0x0201) {
5376 		/*
5377 		 * Change voltage from 1.2V to 1.35V for RT3070.
5378 		 * The DAC issue (RT3070_LDO_CFG0) has been fixed
5379 		 * in RT3070(F).
5380 		 */
5381 		run_read(sc, RT3070_LDO_CFG0, &tmp);
5382 		tmp = (tmp & ~0x0f000000) | 0x0d000000;
5383 		run_write(sc, RT3070_LDO_CFG0, tmp);
5384 
5385 	} else if (sc->mac_ver == 0x3071) {
5386 		run_rt3070_rf_read(sc, 6, &rf);
5387 		run_rt3070_rf_write(sc, 6, rf | 0x40);
5388 		run_rt3070_rf_write(sc, 31, 0x14);
5389 
5390 		run_read(sc, RT3070_LDO_CFG0, &tmp);
5391 		tmp &= ~0x1f000000;
5392 		if (sc->mac_rev < 0x0211)
5393 			tmp |= 0x0d000000;	/* 1.3V */
5394 		else
5395 			tmp |= 0x01000000;	/* 1.2V */
5396 		run_write(sc, RT3070_LDO_CFG0, tmp);
5397 
5398 		/* patch LNA_PE_G1 */
5399 		run_read(sc, RT3070_GPIO_SWITCH, &tmp);
5400 		run_write(sc, RT3070_GPIO_SWITCH, tmp & ~0x20);
5401 
5402 	} else if (sc->mac_ver == 0x3572) {
5403 		run_rt3070_rf_read(sc, 6, &rf);
5404 		run_rt3070_rf_write(sc, 6, rf | 0x40);
5405 
5406 		/* increase voltage from 1.2V to 1.35V */
5407 		run_read(sc, RT3070_LDO_CFG0, &tmp);
5408 		tmp = (tmp & ~0x1f000000) | 0x0d000000;
5409 		run_write(sc, RT3070_LDO_CFG0, tmp);
5410 
5411 		if (sc->mac_rev < 0x0211 || !sc->patch_dac) {
5412 			run_delay(sc, 1);	/* wait for 1msec */
5413 			/* decrease voltage back to 1.2V */
5414 			tmp = (tmp & ~0x1f000000) | 0x01000000;
5415 			run_write(sc, RT3070_LDO_CFG0, tmp);
5416 		}
5417 	}
5418 
5419 	/* select 20MHz bandwidth */
5420 	run_rt3070_rf_read(sc, 31, &rf);
5421 	run_rt3070_rf_write(sc, 31, rf & ~0x20);
5422 
5423 	/* calibrate filter for 20MHz bandwidth */
5424 	sc->rf24_20mhz = 0x1f;	/* default value */
5425 	target = (sc->mac_ver < 0x3071) ? 0x16 : 0x13;
5426 	run_rt3070_filter_calib(sc, 0x07, target, &sc->rf24_20mhz);
5427 
5428 	/* select 40MHz bandwidth */
5429 	run_bbp_read(sc, 4, &bbp4);
5430 	run_bbp_write(sc, 4, (bbp4 & ~0x18) | 0x10);
5431 	run_rt3070_rf_read(sc, 31, &rf);
5432 	run_rt3070_rf_write(sc, 31, rf | 0x20);
5433 
5434 	/* calibrate filter for 40MHz bandwidth */
5435 	sc->rf24_40mhz = 0x2f;	/* default value */
5436 	target = (sc->mac_ver < 0x3071) ? 0x19 : 0x15;
5437 	run_rt3070_filter_calib(sc, 0x27, target, &sc->rf24_40mhz);
5438 
5439 	/* go back to 20MHz bandwidth */
5440 	run_bbp_read(sc, 4, &bbp4);
5441 	run_bbp_write(sc, 4, bbp4 & ~0x18);
5442 
5443 	if (sc->mac_ver == 0x3572) {
5444 		/* save default BBP registers 25 and 26 values */
5445 		run_bbp_read(sc, 25, &sc->bbp25);
5446 		run_bbp_read(sc, 26, &sc->bbp26);
5447 	} else if (sc->mac_rev < 0x0201 || sc->mac_rev < 0x0211)
5448 		run_rt3070_rf_write(sc, 27, 0x03);
5449 
5450 	run_read(sc, RT3070_OPT_14, &tmp);
5451 	run_write(sc, RT3070_OPT_14, tmp | 1);
5452 
5453 	if (sc->mac_ver == 0x3070 || sc->mac_ver == 0x3071) {
5454 		run_rt3070_rf_read(sc, 17, &rf);
5455 		rf &= ~RT3070_TX_LO1;
5456 		if ((sc->mac_ver == 0x3070 ||
5457 		     (sc->mac_ver == 0x3071 && sc->mac_rev >= 0x0211)) &&
5458 		    !sc->ext_2ghz_lna)
5459 			rf |= 0x20;	/* fix for long range Rx issue */
5460 		mingain = (sc->mac_ver == 0x3070) ? 1 : 2;
5461 		if (sc->txmixgain_2ghz >= mingain)
5462 			rf = (rf & ~0x7) | sc->txmixgain_2ghz;
5463 		run_rt3070_rf_write(sc, 17, rf);
5464 	}
5465 
5466 	if (sc->mac_ver == 0x3071) {
5467 		run_rt3070_rf_read(sc, 1, &rf);
5468 		rf &= ~(RT3070_RX0_PD | RT3070_TX0_PD);
5469 		rf |= RT3070_RF_BLOCK | RT3070_RX1_PD | RT3070_TX1_PD;
5470 		run_rt3070_rf_write(sc, 1, rf);
5471 
5472 		run_rt3070_rf_read(sc, 15, &rf);
5473 		run_rt3070_rf_write(sc, 15, rf & ~RT3070_TX_LO2);
5474 
5475 		run_rt3070_rf_read(sc, 20, &rf);
5476 		run_rt3070_rf_write(sc, 20, rf & ~RT3070_RX_LO1);
5477 
5478 		run_rt3070_rf_read(sc, 21, &rf);
5479 		run_rt3070_rf_write(sc, 21, rf & ~RT3070_RX_LO2);
5480 	}
5481 
5482 	if (sc->mac_ver == 0x3070 || sc->mac_ver == 0x3071) {
5483 		/* fix Tx to Rx IQ glitch by raising RF voltage */
5484 		run_rt3070_rf_read(sc, 27, &rf);
5485 		rf &= ~0x77;
5486 		if (sc->mac_rev < 0x0211)
5487 			rf |= 0x03;
5488 		run_rt3070_rf_write(sc, 27, rf);
5489 	}
5490 	return (0);
5491 }
5492 
5493 static void
5494 run_rt3593_rf_init(struct run_softc *sc)
5495 {
5496 	uint32_t tmp;
5497 	uint8_t rf;
5498 	u_int i;
5499 
5500 	/* Disable the GPIO bits 4 and 7 for LNA PE control. */
5501 	run_read(sc, RT3070_GPIO_SWITCH, &tmp);
5502 	tmp &= ~(1 << 4 | 1 << 7);
5503 	run_write(sc, RT3070_GPIO_SWITCH, tmp);
5504 
5505 	/* Initialize RF registers to default value. */
5506 	for (i = 0; i < nitems(rt3593_def_rf); i++) {
5507 		run_rt3070_rf_write(sc, rt3593_def_rf[i].reg,
5508 		    rt3593_def_rf[i].val);
5509 	}
5510 
5511 	/* Toggle RF R2 to initiate calibration. */
5512 	run_rt3070_rf_write(sc, 2, RT5390_RESCAL);
5513 
5514 	/* Initialize RF frequency offset. */
5515 	run_adjust_freq_offset(sc);
5516 
5517 	run_rt3070_rf_read(sc, 18, &rf);
5518 	run_rt3070_rf_write(sc, 18, rf | RT3593_AUTOTUNE_BYPASS);
5519 
5520 	/*
5521 	 * Increase voltage from 1.2V to 1.35V, wait for 1 msec to
5522 	 * decrease voltage back to 1.2V.
5523 	 */
5524 	run_read(sc, RT3070_LDO_CFG0, &tmp);
5525 	tmp = (tmp & ~0x1f000000) | 0x0d000000;
5526 	run_write(sc, RT3070_LDO_CFG0, tmp);
5527 	run_delay(sc, 1);
5528 	tmp = (tmp & ~0x1f000000) | 0x01000000;
5529 	run_write(sc, RT3070_LDO_CFG0, tmp);
5530 
5531 	sc->rf24_20mhz = 0x1f;
5532 	sc->rf24_40mhz = 0x2f;
5533 
5534 	/* Save default BBP registers 25 and 26 values. */
5535 	run_bbp_read(sc, 25, &sc->bbp25);
5536 	run_bbp_read(sc, 26, &sc->bbp26);
5537 
5538 	run_read(sc, RT3070_OPT_14, &tmp);
5539 	run_write(sc, RT3070_OPT_14, tmp | 1);
5540 }
5541 
5542 static void
5543 run_rt5390_rf_init(struct run_softc *sc)
5544 {
5545 	uint32_t tmp;
5546 	uint8_t rf;
5547 	u_int i;
5548 
5549 	/* Toggle RF R2 to initiate calibration. */
5550 	if (sc->mac_ver == 0x5390) {
5551 		run_rt3070_rf_read(sc, 2, &rf);
5552 		run_rt3070_rf_write(sc, 2, rf | RT5390_RESCAL);
5553 		run_delay(sc, 10);
5554 		run_rt3070_rf_write(sc, 2, rf & ~RT5390_RESCAL);
5555 	} else {
5556 		run_rt3070_rf_write(sc, 2, RT5390_RESCAL);
5557 		run_delay(sc, 10);
5558 	}
5559 
5560 	/* Initialize RF registers to default value. */
5561 	if (sc->mac_ver == 0x5592) {
5562 		for (i = 0; i < nitems(rt5592_def_rf); i++) {
5563 			run_rt3070_rf_write(sc, rt5592_def_rf[i].reg,
5564 			    rt5592_def_rf[i].val);
5565 		}
5566 		/* Initialize RF frequency offset. */
5567 		run_adjust_freq_offset(sc);
5568 	} else if (sc->mac_ver == 0x5392) {
5569 		for (i = 0; i < nitems(rt5392_def_rf); i++) {
5570 			run_rt3070_rf_write(sc, rt5392_def_rf[i].reg,
5571 			    rt5392_def_rf[i].val);
5572 		}
5573 		if (sc->mac_rev >= 0x0223) {
5574 			run_rt3070_rf_write(sc, 23, 0x0f);
5575 			run_rt3070_rf_write(sc, 24, 0x3e);
5576 			run_rt3070_rf_write(sc, 51, 0x32);
5577 			run_rt3070_rf_write(sc, 53, 0x22);
5578 			run_rt3070_rf_write(sc, 56, 0xc1);
5579 			run_rt3070_rf_write(sc, 59, 0x0f);
5580 		}
5581 	} else {
5582 		for (i = 0; i < nitems(rt5390_def_rf); i++) {
5583 			run_rt3070_rf_write(sc, rt5390_def_rf[i].reg,
5584 			    rt5390_def_rf[i].val);
5585 		}
5586 		if (sc->mac_rev >= 0x0502) {
5587 			run_rt3070_rf_write(sc, 6, 0xe0);
5588 			run_rt3070_rf_write(sc, 25, 0x80);
5589 			run_rt3070_rf_write(sc, 46, 0x73);
5590 			run_rt3070_rf_write(sc, 53, 0x00);
5591 			run_rt3070_rf_write(sc, 56, 0x42);
5592 			run_rt3070_rf_write(sc, 61, 0xd1);
5593 		}
5594 	}
5595 
5596 	sc->rf24_20mhz = 0x1f;	/* default value */
5597 	sc->rf24_40mhz = (sc->mac_ver == 0x5592) ? 0 : 0x2f;
5598 
5599 	if (sc->mac_rev < 0x0211)
5600 		run_rt3070_rf_write(sc, 27, 0x3);
5601 
5602 	run_read(sc, RT3070_OPT_14, &tmp);
5603 	run_write(sc, RT3070_OPT_14, tmp | 1);
5604 }
5605 
5606 static int
5607 run_rt3070_filter_calib(struct run_softc *sc, uint8_t init, uint8_t target,
5608     uint8_t *val)
5609 {
5610 	uint8_t rf22, rf24;
5611 	uint8_t bbp55_pb, bbp55_sb, delta;
5612 	int ntries;
5613 
5614 	/* program filter */
5615 	run_rt3070_rf_read(sc, 24, &rf24);
5616 	rf24 = (rf24 & 0xc0) | init;	/* initial filter value */
5617 	run_rt3070_rf_write(sc, 24, rf24);
5618 
5619 	/* enable baseband loopback mode */
5620 	run_rt3070_rf_read(sc, 22, &rf22);
5621 	run_rt3070_rf_write(sc, 22, rf22 | 0x01);
5622 
5623 	/* set power and frequency of passband test tone */
5624 	run_bbp_write(sc, 24, 0x00);
5625 	for (ntries = 0; ntries < 100; ntries++) {
5626 		/* transmit test tone */
5627 		run_bbp_write(sc, 25, 0x90);
5628 		run_delay(sc, 10);
5629 		/* read received power */
5630 		run_bbp_read(sc, 55, &bbp55_pb);
5631 		if (bbp55_pb != 0)
5632 			break;
5633 	}
5634 	if (ntries == 100)
5635 		return (ETIMEDOUT);
5636 
5637 	/* set power and frequency of stopband test tone */
5638 	run_bbp_write(sc, 24, 0x06);
5639 	for (ntries = 0; ntries < 100; ntries++) {
5640 		/* transmit test tone */
5641 		run_bbp_write(sc, 25, 0x90);
5642 		run_delay(sc, 10);
5643 		/* read received power */
5644 		run_bbp_read(sc, 55, &bbp55_sb);
5645 
5646 		delta = bbp55_pb - bbp55_sb;
5647 		if (delta > target)
5648 			break;
5649 
5650 		/* reprogram filter */
5651 		rf24++;
5652 		run_rt3070_rf_write(sc, 24, rf24);
5653 	}
5654 	if (ntries < 100) {
5655 		if (rf24 != init)
5656 			rf24--;	/* backtrack */
5657 		*val = rf24;
5658 		run_rt3070_rf_write(sc, 24, rf24);
5659 	}
5660 
5661 	/* restore initial state */
5662 	run_bbp_write(sc, 24, 0x00);
5663 
5664 	/* disable baseband loopback mode */
5665 	run_rt3070_rf_read(sc, 22, &rf22);
5666 	run_rt3070_rf_write(sc, 22, rf22 & ~0x01);
5667 
5668 	return (0);
5669 }
5670 
5671 static void
5672 run_rt3070_rf_setup(struct run_softc *sc)
5673 {
5674 	uint8_t bbp, rf;
5675 	int i;
5676 
5677 	if (sc->mac_ver == 0x3572) {
5678 		/* enable DC filter */
5679 		if (sc->mac_rev >= 0x0201)
5680 			run_bbp_write(sc, 103, 0xc0);
5681 
5682 		run_bbp_read(sc, 138, &bbp);
5683 		if (sc->ntxchains == 1)
5684 			bbp |= 0x20;	/* turn off DAC1 */
5685 		if (sc->nrxchains == 1)
5686 			bbp &= ~0x02;	/* turn off ADC1 */
5687 		run_bbp_write(sc, 138, bbp);
5688 
5689 		if (sc->mac_rev >= 0x0211) {
5690 			/* improve power consumption */
5691 			run_bbp_read(sc, 31, &bbp);
5692 			run_bbp_write(sc, 31, bbp & ~0x03);
5693 		}
5694 
5695 		run_rt3070_rf_read(sc, 16, &rf);
5696 		rf = (rf & ~0x07) | sc->txmixgain_2ghz;
5697 		run_rt3070_rf_write(sc, 16, rf);
5698 
5699 	} else if (sc->mac_ver == 0x3071) {
5700 		if (sc->mac_rev >= 0x0211) {
5701 			/* enable DC filter */
5702 			run_bbp_write(sc, 103, 0xc0);
5703 
5704 			/* improve power consumption */
5705 			run_bbp_read(sc, 31, &bbp);
5706 			run_bbp_write(sc, 31, bbp & ~0x03);
5707 		}
5708 
5709 		run_bbp_read(sc, 138, &bbp);
5710 		if (sc->ntxchains == 1)
5711 			bbp |= 0x20;	/* turn off DAC1 */
5712 		if (sc->nrxchains == 1)
5713 			bbp &= ~0x02;	/* turn off ADC1 */
5714 		run_bbp_write(sc, 138, bbp);
5715 
5716 		run_write(sc, RT2860_TX_SW_CFG1, 0);
5717 		if (sc->mac_rev < 0x0211) {
5718 			run_write(sc, RT2860_TX_SW_CFG2,
5719 			    sc->patch_dac ? 0x2c : 0x0f);
5720 		} else
5721 			run_write(sc, RT2860_TX_SW_CFG2, 0);
5722 
5723 	} else if (sc->mac_ver == 0x3070) {
5724 		if (sc->mac_rev >= 0x0201) {
5725 			/* enable DC filter */
5726 			run_bbp_write(sc, 103, 0xc0);
5727 
5728 			/* improve power consumption */
5729 			run_bbp_read(sc, 31, &bbp);
5730 			run_bbp_write(sc, 31, bbp & ~0x03);
5731 		}
5732 
5733 		if (sc->mac_rev < 0x0201) {
5734 			run_write(sc, RT2860_TX_SW_CFG1, 0);
5735 			run_write(sc, RT2860_TX_SW_CFG2, 0x2c);
5736 		} else
5737 			run_write(sc, RT2860_TX_SW_CFG2, 0);
5738 	}
5739 
5740 	/* initialize RF registers from ROM for >=RT3071*/
5741 	if (sc->mac_ver >= 0x3071) {
5742 		for (i = 0; i < 10; i++) {
5743 			if (sc->rf[i].reg == 0 || sc->rf[i].reg == 0xff)
5744 				continue;
5745 			run_rt3070_rf_write(sc, sc->rf[i].reg, sc->rf[i].val);
5746 		}
5747 	}
5748 }
5749 
5750 static void
5751 run_rt3593_rf_setup(struct run_softc *sc)
5752 {
5753 	uint8_t bbp, rf;
5754 
5755 	if (sc->mac_rev >= 0x0211) {
5756 		/* Enable DC filter. */
5757 		run_bbp_write(sc, 103, 0xc0);
5758 	}
5759 	run_write(sc, RT2860_TX_SW_CFG1, 0);
5760 	if (sc->mac_rev < 0x0211) {
5761 		run_write(sc, RT2860_TX_SW_CFG2,
5762 		    sc->patch_dac ? 0x2c : 0x0f);
5763 	} else
5764 		run_write(sc, RT2860_TX_SW_CFG2, 0);
5765 
5766 	run_rt3070_rf_read(sc, 50, &rf);
5767 	run_rt3070_rf_write(sc, 50, rf & ~RT3593_TX_LO2);
5768 
5769 	run_rt3070_rf_read(sc, 51, &rf);
5770 	rf = (rf & ~(RT3593_TX_LO1 | 0x0c)) |
5771 	    ((sc->txmixgain_2ghz & 0x07) << 2);
5772 	run_rt3070_rf_write(sc, 51, rf);
5773 
5774 	run_rt3070_rf_read(sc, 38, &rf);
5775 	run_rt3070_rf_write(sc, 38, rf & ~RT5390_RX_LO1);
5776 
5777 	run_rt3070_rf_read(sc, 39, &rf);
5778 	run_rt3070_rf_write(sc, 39, rf & ~RT5390_RX_LO2);
5779 
5780 	run_rt3070_rf_read(sc, 1, &rf);
5781 	run_rt3070_rf_write(sc, 1, rf & ~(RT3070_RF_BLOCK | RT3070_PLL_PD));
5782 
5783 	run_rt3070_rf_read(sc, 30, &rf);
5784 	rf = (rf & ~0x18) | 0x10;
5785 	run_rt3070_rf_write(sc, 30, rf);
5786 
5787 	/* Apply maximum likelihood detection for 2 stream case. */
5788 	run_bbp_read(sc, 105, &bbp);
5789 	if (sc->nrxchains > 1)
5790 		run_bbp_write(sc, 105, bbp | RT5390_MLD);
5791 
5792 	/* Avoid data lost and CRC error. */
5793 	run_bbp_read(sc, 4, &bbp);
5794 	run_bbp_write(sc, 4, bbp | RT5390_MAC_IF_CTRL);
5795 
5796 	run_bbp_write(sc, 92, 0x02);
5797 	run_bbp_write(sc, 82, 0x82);
5798 	run_bbp_write(sc, 106, 0x05);
5799 	run_bbp_write(sc, 104, 0x92);
5800 	run_bbp_write(sc, 88, 0x90);
5801 	run_bbp_write(sc, 148, 0xc8);
5802 	run_bbp_write(sc, 47, 0x48);
5803 	run_bbp_write(sc, 120, 0x50);
5804 
5805 	run_bbp_write(sc, 163, 0x9d);
5806 
5807 	/* SNR mapping. */
5808 	run_bbp_write(sc, 142, 0x06);
5809 	run_bbp_write(sc, 143, 0xa0);
5810 	run_bbp_write(sc, 142, 0x07);
5811 	run_bbp_write(sc, 143, 0xa1);
5812 	run_bbp_write(sc, 142, 0x08);
5813 	run_bbp_write(sc, 143, 0xa2);
5814 
5815 	run_bbp_write(sc, 31, 0x08);
5816 	run_bbp_write(sc, 68, 0x0b);
5817 	run_bbp_write(sc, 105, 0x04);
5818 }
5819 
5820 static void
5821 run_rt5390_rf_setup(struct run_softc *sc)
5822 {
5823 	uint8_t bbp, rf;
5824 
5825 	if (sc->mac_rev >= 0x0211) {
5826 		/* Enable DC filter. */
5827 		run_bbp_write(sc, 103, 0xc0);
5828 
5829 		if (sc->mac_ver != 0x5592) {
5830 			/* Improve power consumption. */
5831 			run_bbp_read(sc, 31, &bbp);
5832 			run_bbp_write(sc, 31, bbp & ~0x03);
5833 		}
5834 	}
5835 
5836 	run_bbp_read(sc, 138, &bbp);
5837 	if (sc->ntxchains == 1)
5838 		bbp |= 0x20;	/* turn off DAC1 */
5839 	if (sc->nrxchains == 1)
5840 		bbp &= ~0x02;	/* turn off ADC1 */
5841 	run_bbp_write(sc, 138, bbp);
5842 
5843 	run_rt3070_rf_read(sc, 38, &rf);
5844 	run_rt3070_rf_write(sc, 38, rf & ~RT5390_RX_LO1);
5845 
5846 	run_rt3070_rf_read(sc, 39, &rf);
5847 	run_rt3070_rf_write(sc, 39, rf & ~RT5390_RX_LO2);
5848 
5849 	/* Avoid data lost and CRC error. */
5850 	run_bbp_read(sc, 4, &bbp);
5851 	run_bbp_write(sc, 4, bbp | RT5390_MAC_IF_CTRL);
5852 
5853 	run_rt3070_rf_read(sc, 30, &rf);
5854 	rf = (rf & ~0x18) | 0x10;
5855 	run_rt3070_rf_write(sc, 30, rf);
5856 
5857 	if (sc->mac_ver != 0x5592) {
5858 		run_write(sc, RT2860_TX_SW_CFG1, 0);
5859 		if (sc->mac_rev < 0x0211) {
5860 			run_write(sc, RT2860_TX_SW_CFG2,
5861 			    sc->patch_dac ? 0x2c : 0x0f);
5862 		} else
5863 			run_write(sc, RT2860_TX_SW_CFG2, 0);
5864 	}
5865 }
5866 
5867 static int
5868 run_txrx_enable(struct run_softc *sc)
5869 {
5870 	struct ieee80211com *ic = &sc->sc_ic;
5871 	uint32_t tmp;
5872 	int error, ntries;
5873 
5874 	run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_MAC_TX_EN);
5875 	for (ntries = 0; ntries < 200; ntries++) {
5876 		if ((error = run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp)) != 0)
5877 			return (error);
5878 		if ((tmp & (RT2860_TX_DMA_BUSY | RT2860_RX_DMA_BUSY)) == 0)
5879 			break;
5880 		run_delay(sc, 50);
5881 	}
5882 	if (ntries == 200)
5883 		return (ETIMEDOUT);
5884 
5885 	run_delay(sc, 50);
5886 
5887 	tmp |= RT2860_RX_DMA_EN | RT2860_TX_DMA_EN | RT2860_TX_WB_DDONE;
5888 	run_write(sc, RT2860_WPDMA_GLO_CFG, tmp);
5889 
5890 	/* enable Rx bulk aggregation (set timeout and limit) */
5891 	tmp = RT2860_USB_TX_EN | RT2860_USB_RX_EN | RT2860_USB_RX_AGG_EN |
5892 	    RT2860_USB_RX_AGG_TO(128) | RT2860_USB_RX_AGG_LMT(2);
5893 	run_write(sc, RT2860_USB_DMA_CFG, tmp);
5894 
5895 	/* set Rx filter */
5896 	tmp = RT2860_DROP_CRC_ERR | RT2860_DROP_PHY_ERR;
5897 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
5898 		tmp |= RT2860_DROP_UC_NOME | RT2860_DROP_DUPL |
5899 		    RT2860_DROP_CTS | RT2860_DROP_BA | RT2860_DROP_ACK |
5900 		    RT2860_DROP_VER_ERR | RT2860_DROP_CTRL_RSV |
5901 		    RT2860_DROP_CFACK | RT2860_DROP_CFEND;
5902 		if (ic->ic_opmode == IEEE80211_M_STA)
5903 			tmp |= RT2860_DROP_RTS | RT2860_DROP_PSPOLL;
5904 	}
5905 	run_write(sc, RT2860_RX_FILTR_CFG, tmp);
5906 
5907 	run_write(sc, RT2860_MAC_SYS_CTRL,
5908 	    RT2860_MAC_RX_EN | RT2860_MAC_TX_EN);
5909 
5910 	return (0);
5911 }
5912 
5913 static void
5914 run_adjust_freq_offset(struct run_softc *sc)
5915 {
5916 	uint8_t rf, tmp;
5917 
5918 	run_rt3070_rf_read(sc, 17, &rf);
5919 	tmp = rf;
5920 	rf = (rf & ~0x7f) | (sc->freq & 0x7f);
5921 	rf = MIN(rf, 0x5f);
5922 
5923 	if (tmp != rf)
5924 		run_mcu_cmd(sc, 0x74, (tmp << 8 ) | rf);
5925 }
5926 
5927 static void
5928 run_init_locked(struct run_softc *sc)
5929 {
5930 	struct ieee80211com *ic = &sc->sc_ic;
5931 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
5932 	uint32_t tmp;
5933 	uint8_t bbp1, bbp3;
5934 	int i;
5935 	int ridx;
5936 	int ntries;
5937 
5938 	if (ic->ic_nrunning > 1)
5939 		return;
5940 
5941 	run_stop(sc);
5942 
5943 	if (run_load_microcode(sc) != 0) {
5944 		device_printf(sc->sc_dev, "could not load 8051 microcode\n");
5945 		goto fail;
5946 	}
5947 
5948 	for (ntries = 0; ntries < 100; ntries++) {
5949 		if (run_read(sc, RT2860_ASIC_VER_ID, &tmp) != 0)
5950 			goto fail;
5951 		if (tmp != 0 && tmp != 0xffffffff)
5952 			break;
5953 		run_delay(sc, 10);
5954 	}
5955 	if (ntries == 100)
5956 		goto fail;
5957 
5958 	for (i = 0; i != RUN_EP_QUEUES; i++)
5959 		run_setup_tx_list(sc, &sc->sc_epq[i]);
5960 
5961 	run_set_macaddr(sc, vap ? vap->iv_myaddr : ic->ic_macaddr);
5962 
5963 	for (ntries = 0; ntries < 100; ntries++) {
5964 		if (run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp) != 0)
5965 			goto fail;
5966 		if ((tmp & (RT2860_TX_DMA_BUSY | RT2860_RX_DMA_BUSY)) == 0)
5967 			break;
5968 		run_delay(sc, 10);
5969 	}
5970 	if (ntries == 100) {
5971 		device_printf(sc->sc_dev, "timeout waiting for DMA engine\n");
5972 		goto fail;
5973 	}
5974 	tmp &= 0xff0;
5975 	tmp |= RT2860_TX_WB_DDONE;
5976 	run_write(sc, RT2860_WPDMA_GLO_CFG, tmp);
5977 
5978 	/* turn off PME_OEN to solve high-current issue */
5979 	run_read(sc, RT2860_SYS_CTRL, &tmp);
5980 	run_write(sc, RT2860_SYS_CTRL, tmp & ~RT2860_PME_OEN);
5981 
5982 	run_write(sc, RT2860_MAC_SYS_CTRL,
5983 	    RT2860_BBP_HRST | RT2860_MAC_SRST);
5984 	run_write(sc, RT2860_USB_DMA_CFG, 0);
5985 
5986 	if (run_reset(sc) != 0) {
5987 		device_printf(sc->sc_dev, "could not reset chipset\n");
5988 		goto fail;
5989 	}
5990 
5991 	run_write(sc, RT2860_MAC_SYS_CTRL, 0);
5992 
5993 	/* init Tx power for all Tx rates (from EEPROM) */
5994 	for (ridx = 0; ridx < 5; ridx++) {
5995 		if (sc->txpow20mhz[ridx] == 0xffffffff)
5996 			continue;
5997 		run_write(sc, RT2860_TX_PWR_CFG(ridx), sc->txpow20mhz[ridx]);
5998 	}
5999 
6000 	for (i = 0; i < nitems(rt2870_def_mac); i++)
6001 		run_write(sc, rt2870_def_mac[i].reg, rt2870_def_mac[i].val);
6002 	run_write(sc, RT2860_WMM_AIFSN_CFG, 0x00002273);
6003 	run_write(sc, RT2860_WMM_CWMIN_CFG, 0x00002344);
6004 	run_write(sc, RT2860_WMM_CWMAX_CFG, 0x000034aa);
6005 
6006 	if (sc->mac_ver >= 0x5390) {
6007 		run_write(sc, RT2860_TX_SW_CFG0,
6008 		    4 << RT2860_DLY_PAPE_EN_SHIFT | 4);
6009 		if (sc->mac_ver >= 0x5392) {
6010 			run_write(sc, RT2860_MAX_LEN_CFG, 0x00002fff);
6011 			if (sc->mac_ver == 0x5592) {
6012 				run_write(sc, RT2860_HT_FBK_CFG1, 0xedcba980);
6013 				run_write(sc, RT2860_TXOP_HLDR_ET, 0x00000082);
6014 			} else {
6015 				run_write(sc, RT2860_HT_FBK_CFG1, 0xedcb4980);
6016 				run_write(sc, RT2860_LG_FBK_CFG0, 0xedcba322);
6017 			}
6018 		}
6019 	} else if (sc->mac_ver == 0x3593) {
6020 		run_write(sc, RT2860_TX_SW_CFG0,
6021 		    4 << RT2860_DLY_PAPE_EN_SHIFT | 2);
6022 	} else if (sc->mac_ver >= 0x3070) {
6023 		/* set delay of PA_PE assertion to 1us (unit of 0.25us) */
6024 		run_write(sc, RT2860_TX_SW_CFG0,
6025 		    4 << RT2860_DLY_PAPE_EN_SHIFT);
6026 	}
6027 
6028 	/* wait while MAC is busy */
6029 	for (ntries = 0; ntries < 100; ntries++) {
6030 		if (run_read(sc, RT2860_MAC_STATUS_REG, &tmp) != 0)
6031 			goto fail;
6032 		if (!(tmp & (RT2860_RX_STATUS_BUSY | RT2860_TX_STATUS_BUSY)))
6033 			break;
6034 		run_delay(sc, 10);
6035 	}
6036 	if (ntries == 100)
6037 		goto fail;
6038 
6039 	/* clear Host to MCU mailbox */
6040 	run_write(sc, RT2860_H2M_BBPAGENT, 0);
6041 	run_write(sc, RT2860_H2M_MAILBOX, 0);
6042 	run_delay(sc, 10);
6043 
6044 	if (run_bbp_init(sc) != 0) {
6045 		device_printf(sc->sc_dev, "could not initialize BBP\n");
6046 		goto fail;
6047 	}
6048 
6049 	/* abort TSF synchronization */
6050 	run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
6051 	tmp &= ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN |
6052 	    RT2860_TBTT_TIMER_EN);
6053 	run_write(sc, RT2860_BCN_TIME_CFG, tmp);
6054 
6055 	/* clear RX WCID search table */
6056 	run_set_region_4(sc, RT2860_WCID_ENTRY(0), 0, 512);
6057 	/* clear WCID attribute table */
6058 	run_set_region_4(sc, RT2860_WCID_ATTR(0), 0, 8 * 32);
6059 
6060 	/* hostapd sets a key before init. So, don't clear it. */
6061 	if (sc->cmdq_key_set != RUN_CMDQ_GO) {
6062 		/* clear shared key table */
6063 		run_set_region_4(sc, RT2860_SKEY(0, 0), 0, 8 * 32);
6064 		/* clear shared key mode */
6065 		run_set_region_4(sc, RT2860_SKEY_MODE_0_7, 0, 4);
6066 	}
6067 
6068 	run_read(sc, RT2860_US_CYC_CNT, &tmp);
6069 	tmp = (tmp & ~0xff) | 0x1e;
6070 	run_write(sc, RT2860_US_CYC_CNT, tmp);
6071 
6072 	if (sc->mac_rev != 0x0101)
6073 		run_write(sc, RT2860_TXOP_CTRL_CFG, 0x0000583f);
6074 
6075 	run_write(sc, RT2860_WMM_TXOP0_CFG, 0);
6076 	run_write(sc, RT2860_WMM_TXOP1_CFG, 48 << 16 | 96);
6077 
6078 	/* write vendor-specific BBP values (from EEPROM) */
6079 	if (sc->mac_ver < 0x3593) {
6080 		for (i = 0; i < 10; i++) {
6081 			if (sc->bbp[i].reg == 0 || sc->bbp[i].reg == 0xff)
6082 				continue;
6083 			run_bbp_write(sc, sc->bbp[i].reg, sc->bbp[i].val);
6084 		}
6085 	}
6086 
6087 	/* select Main antenna for 1T1R devices */
6088 	if (sc->rf_rev == RT3070_RF_3020 || sc->rf_rev == RT5390_RF_5370)
6089 		run_set_rx_antenna(sc, 0);
6090 
6091 	/* send LEDs operating mode to microcontroller */
6092 	(void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED1, sc->led[0]);
6093 	(void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED2, sc->led[1]);
6094 	(void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED3, sc->led[2]);
6095 
6096 	if (sc->mac_ver >= 0x5390)
6097 		run_rt5390_rf_init(sc);
6098 	else if (sc->mac_ver == 0x3593)
6099 		run_rt3593_rf_init(sc);
6100 	else if (sc->mac_ver >= 0x3070)
6101 		run_rt3070_rf_init(sc);
6102 
6103 	/* disable non-existing Rx chains */
6104 	run_bbp_read(sc, 3, &bbp3);
6105 	bbp3 &= ~(1 << 3 | 1 << 4);
6106 	if (sc->nrxchains == 2)
6107 		bbp3 |= 1 << 3;
6108 	else if (sc->nrxchains == 3)
6109 		bbp3 |= 1 << 4;
6110 	run_bbp_write(sc, 3, bbp3);
6111 
6112 	/* disable non-existing Tx chains */
6113 	run_bbp_read(sc, 1, &bbp1);
6114 	if (sc->ntxchains == 1)
6115 		bbp1 &= ~(1 << 3 | 1 << 4);
6116 	run_bbp_write(sc, 1, bbp1);
6117 
6118 	if (sc->mac_ver >= 0x5390)
6119 		run_rt5390_rf_setup(sc);
6120 	else if (sc->mac_ver == 0x3593)
6121 		run_rt3593_rf_setup(sc);
6122 	else if (sc->mac_ver >= 0x3070)
6123 		run_rt3070_rf_setup(sc);
6124 
6125 	/* select default channel */
6126 	run_set_chan(sc, ic->ic_curchan);
6127 
6128 	/* setup initial protection mode */
6129 	run_updateprot_cb(ic);
6130 
6131 	/* turn radio LED on */
6132 	run_set_leds(sc, RT2860_LED_RADIO);
6133 
6134 	sc->sc_flags |= RUN_RUNNING;
6135 	sc->cmdq_run = RUN_CMDQ_GO;
6136 
6137 	for (i = 0; i != RUN_N_XFER; i++)
6138 		usbd_xfer_set_stall(sc->sc_xfer[i]);
6139 
6140 	usbd_transfer_start(sc->sc_xfer[RUN_BULK_RX]);
6141 
6142 	if (run_txrx_enable(sc) != 0)
6143 		goto fail;
6144 
6145 	return;
6146 
6147 fail:
6148 	run_stop(sc);
6149 }
6150 
6151 static void
6152 run_stop(void *arg)
6153 {
6154 	struct run_softc *sc = (struct run_softc *)arg;
6155 	uint32_t tmp;
6156 	int i;
6157 	int ntries;
6158 
6159 	RUN_LOCK_ASSERT(sc, MA_OWNED);
6160 
6161 	if (sc->sc_flags & RUN_RUNNING)
6162 		run_set_leds(sc, 0);	/* turn all LEDs off */
6163 
6164 	sc->sc_flags &= ~RUN_RUNNING;
6165 
6166 	sc->ratectl_run = RUN_RATECTL_OFF;
6167 	sc->cmdq_run = sc->cmdq_key_set;
6168 
6169 	RUN_UNLOCK(sc);
6170 
6171 	for(i = 0; i < RUN_N_XFER; i++)
6172 		usbd_transfer_drain(sc->sc_xfer[i]);
6173 
6174 	RUN_LOCK(sc);
6175 
6176 	run_drain_mbufq(sc);
6177 
6178 	if (sc->rx_m != NULL) {
6179 		m_free(sc->rx_m);
6180 		sc->rx_m = NULL;
6181 	}
6182 
6183 	/* Disable Tx/Rx DMA. */
6184 	if (run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp) != 0)
6185 		return;
6186 	tmp &= ~(RT2860_RX_DMA_EN | RT2860_TX_DMA_EN);
6187 	run_write(sc, RT2860_WPDMA_GLO_CFG, tmp);
6188 
6189 	for (ntries = 0; ntries < 100; ntries++) {
6190 		if (run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp) != 0)
6191 			return;
6192 		if ((tmp & (RT2860_TX_DMA_BUSY | RT2860_RX_DMA_BUSY)) == 0)
6193 				break;
6194 		run_delay(sc, 10);
6195 	}
6196 	if (ntries == 100) {
6197 		device_printf(sc->sc_dev, "timeout waiting for DMA engine\n");
6198 		return;
6199 	}
6200 
6201 	/* disable Tx/Rx */
6202 	run_read(sc, RT2860_MAC_SYS_CTRL, &tmp);
6203 	tmp &= ~(RT2860_MAC_RX_EN | RT2860_MAC_TX_EN);
6204 	run_write(sc, RT2860_MAC_SYS_CTRL, tmp);
6205 
6206 	/* wait for pending Tx to complete */
6207 	for (ntries = 0; ntries < 100; ntries++) {
6208 		if (run_read(sc, RT2860_TXRXQ_PCNT, &tmp) != 0) {
6209 			DPRINTF("Cannot read Tx queue count\n");
6210 			break;
6211 		}
6212 		if ((tmp & RT2860_TX2Q_PCNT_MASK) == 0) {
6213 			DPRINTF("All Tx cleared\n");
6214 			break;
6215 		}
6216 		run_delay(sc, 10);
6217 	}
6218 	if (ntries >= 100)
6219 		DPRINTF("There are still pending Tx\n");
6220 	run_delay(sc, 10);
6221 	run_write(sc, RT2860_USB_DMA_CFG, 0);
6222 
6223 	run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_BBP_HRST | RT2860_MAC_SRST);
6224 	run_write(sc, RT2860_MAC_SYS_CTRL, 0);
6225 
6226 	for (i = 0; i != RUN_EP_QUEUES; i++)
6227 		run_unsetup_tx_list(sc, &sc->sc_epq[i]);
6228 }
6229 
6230 static void
6231 run_delay(struct run_softc *sc, u_int ms)
6232 {
6233 	usb_pause_mtx(mtx_owned(&sc->sc_mtx) ?
6234 	    &sc->sc_mtx : NULL, USB_MS_TO_TICKS(ms));
6235 }
6236 
6237 static device_method_t run_methods[] = {
6238 	/* Device interface */
6239 	DEVMETHOD(device_probe,		run_match),
6240 	DEVMETHOD(device_attach,	run_attach),
6241 	DEVMETHOD(device_detach,	run_detach),
6242 	DEVMETHOD_END
6243 };
6244 
6245 static driver_t run_driver = {
6246 	.name = "run",
6247 	.methods = run_methods,
6248 	.size = sizeof(struct run_softc)
6249 };
6250 
6251 static devclass_t run_devclass;
6252 
6253 DRIVER_MODULE(run, uhub, run_driver, run_devclass, run_driver_loaded, NULL);
6254 MODULE_DEPEND(run, wlan, 1, 1, 1);
6255 MODULE_DEPEND(run, usb, 1, 1, 1);
6256 MODULE_DEPEND(run, firmware, 1, 1, 1);
6257 MODULE_VERSION(run, 1);
6258 USB_PNP_HOST_INFO(run_devs);
6259