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