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