xref: /openbsd-src/sys/dev/usb/if_run.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: if_run.c,v 1.17 2009/04/02 17:47:15 damien Exp $	*/
2 
3 /*-
4  * Copyright (c) 2008,2009 Damien Bergamini <damien.bergamini@free.fr>
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 /*-
20  * Ralink Technology RT2700U/RT2800U/RT3000U chipset driver.
21  * http://www.ralinktech.com/
22  */
23 
24 #include "bpfilter.h"
25 
26 #include <sys/param.h>
27 #include <sys/sockio.h>
28 #include <sys/sysctl.h>
29 #include <sys/mbuf.h>
30 #include <sys/kernel.h>
31 #include <sys/socket.h>
32 #include <sys/systm.h>
33 #include <sys/timeout.h>
34 #include <sys/conf.h>
35 #include <sys/device.h>
36 
37 #include <machine/bus.h>
38 #include <machine/endian.h>
39 #include <machine/intr.h>
40 
41 #if NBPFILTER > 0
42 #include <net/bpf.h>
43 #endif
44 #include <net/if.h>
45 #include <net/if_arp.h>
46 #include <net/if_dl.h>
47 #include <net/if_media.h>
48 #include <net/if_types.h>
49 
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h>
52 #include <netinet/in_var.h>
53 #include <netinet/if_ether.h>
54 #include <netinet/ip.h>
55 
56 #include <net80211/ieee80211_var.h>
57 #include <net80211/ieee80211_amrr.h>
58 #include <net80211/ieee80211_radiotap.h>
59 
60 #include <dev/usb/usb.h>
61 #include <dev/usb/usbdi.h>
62 #include <dev/usb/usbdi_util.h>
63 #include <dev/usb/usbdevs.h>
64 
65 #include <dev/ic/rt2860reg.h>		/* shared with ral(4) */
66 #include <dev/usb/if_runvar.h>
67 
68 #ifdef USB_DEBUG
69 #define RUN_DEBUG
70 #endif
71 
72 #ifdef RUN_DEBUG
73 #define DPRINTF(x)	do { if (run_debug) printf x; } while (0)
74 #define DPRINTFN(n, x)	do { if (run_debug >= (n)) printf x; } while (0)
75 int run_debug = 0;
76 #else
77 #define DPRINTF(x)
78 #define DPRINTFN(n, x)
79 #endif
80 
81 /*
82  * PLEASE keep this list sorted as is; this is to ease the sync with the
83  * Ralink Linux driver.  If you want to add new entries, add them at the
84  * end of the list.
85  */
86 #define USB_ID(v, p)	{ USB_VENDOR_##v, USB_PRODUCT_##v##_##p }
87 static const struct usb_devno run_devs[] = {
88 	/* Entries from the Ralink Linux driver. */
89 	/* AUTOMATICALLY GENERATED, DO NOT EDIT BY HAND. */
90 	USB_ID(RALINK,			RT2770),
91 	USB_ID(RALINK,			RT2870),
92 	USB_ID(RALINK,			RT3070),
93 	USB_ID(RALINK,			RT3071),
94 	USB_ID(RALINK,			RT3072),
95 	USB_ID(ASUS,			RT2870_1),
96 	USB_ID(ASUS,			RT2870_2),
97 	USB_ID(ASUS,			RT2870_3),
98 	USB_ID(SITECOMEU,		RT2870_1),
99 	USB_ID(SITECOMEU,		RT2870_2),
100 	USB_ID(SITECOMEU,		RT2870_3),
101 	USB_ID(SITECOMEU,		RT3070),
102 	USB_ID(SITECOMEU,		RT2870_4),
103 	USB_ID(SITECOMEU,		RT2770),
104 	USB_ID(CONCEPTRONIC2,		RT2870_1),
105 	USB_ID(CONCEPTRONIC2,		RT2870_6),
106 	USB_ID(PLANEX2,			RT2870),
107 	USB_ID(PLANEX2,			RT3070),
108 	USB_ID(DLINK2,			RT2870_1),
109 	USB_ID(DLINK2,			RT2870_2),
110 	USB_ID(DLINK,			RT2870),
111 	USB_ID(DLINK,			RT3072),
112 	USB_ID(CONCEPTRONIC2,		RT2870_2),
113 	USB_ID(CONCEPTRONIC2,		RT2870_8),
114 	USB_ID(BELKIN,			RT2870_1),
115 	USB_ID(CONCEPTRONIC2,		RT2870_3),
116 	USB_ID(CONCEPTRONIC2,		RT2870_5),
117 	USB_ID(COREGA,			RT2870_1),
118 	USB_ID(COREGA,			RT2870_2),
119 	USB_ID(COREGA,			RT2870_3),
120 	USB_ID(AMIT,			RT2870_1),
121 	USB_ID(GIGABYTE,		RT2870_1),
122 	USB_ID(GIGABYTE,		GNWB32L),
123 	USB_ID(SPARKLAN,		RT2870_1),
124 	USB_ID(ACCTON,			RT2870_1),
125 	USB_ID(ACCTON,			RT2870_4),
126 	USB_ID(ACCTON,			RT2870_5),
127 	USB_ID(ACCTON,			RT2770),
128 	USB_ID(ACCTON,			RT2870_3),
129 	USB_ID(ACCTON,			RT3070),
130 	USB_ID(ZCOM,			RT2870_1),
131 	USB_ID(ZYXEL,			RT2870_1),
132 	USB_ID(ZCOM,			RT2870_2),
133 	USB_ID(SENAO,			RT2870_1),
134 	USB_ID(SENAO,			RT2870_2),
135 	USB_ID(SENAO,			RT3070),
136 	USB_ID(PHILIPS,			RT2870),
137 	USB_ID(CONCEPTRONIC2,		RT2870_4),
138 	USB_ID(AZUREWAVE,		RT2870_1),
139 	USB_ID(AZUREWAVE,		RT3070),
140 	USB_ID(ACCTON,			RT2870_2),
141 	USB_ID(AMIT2,			RT2870),
142 	USB_ID(HAWKING,			RT2870_1),
143 	USB_ID(HAWKING,			RT2870_2),
144 	USB_ID(CYBERTAN,		RT2870),
145 	USB_ID(UMEDIA,			RT2870_1),
146 	USB_ID(BELKIN,			RT2870_2),
147 	USB_ID(ABOCOM2,			RT2870_1),
148 	USB_ID(CONCEPTRONIC2,		RT2870_7),
149 	USB_ID(SAMSUNG2,		RT2870_1),
150 	USB_ID(ABOCOM,			RT3070),
151 	USB_ID(ABOCOM,			RT3071),
152 	USB_ID(ABOCOM,			RT3072),
153 	USB_ID(EDIMAX,			RT2870_1),
154 	USB_ID(ZINWELL,			RT2870_1),
155 	USB_ID(ZINWELL,			RT2870_2),
156 	USB_ID(QUANTA,			RT3070),
157 	USB_ID(LOGITEC,			RT2870_1),
158 	USB_ID(LOGITEC,			RT2870_2),
159 	USB_ID(LOGITEC,			RT2870_3),
160 	USB_ID(AIRTIES,			RT3070),
161 
162 	/* Entries not in the Ralink Linux driver. */
163 	USB_ID(AMIT,			CGWLUSB2GNR),
164 	USB_ID(ASUS2,			USBN11),
165 	USB_ID(BELKIN,			F5D8053V3),
166 	USB_ID(BELKIN,			F5D8055),
167 	USB_ID(CONCEPTRONIC2,		VIGORN61),
168 	USB_ID(COREGA,			CGWLUSB300GNM),
169 	USB_ID(DLINK2,			DWA130),
170 	USB_ID(EDIMAX,			EW7717),
171 	USB_ID(EDIMAX,			EW7718),
172 	USB_ID(GIGABYTE,		GNWB31N),
173 	USB_ID(HAWKING,			HWUN2),
174 	USB_ID(LINKSYS4,		WUSB100),
175 	USB_ID(LINKSYS4,		WUSB600N),
176 	USB_ID(MELCO,			WLIUCAG300N),
177 	USB_ID(MELCO,			WLIUCG300N),
178 	USB_ID(MELCO,			WLIUCGN),
179 	USB_ID(PLANEX2,			GWUS300MINIS),
180 	USB_ID(PLANEX2,			GWUSMICRON),
181 	USB_ID(SWEEX2,			LW303),
182 	USB_ID(SWEEX2,			LW313)
183 };
184 
185 int		run_match(struct device *, void *, void *);
186 void		run_attach(struct device *, struct device *, void *);
187 int		run_detach(struct device *, int);
188 int		run_alloc_rx_ring(struct run_softc *);
189 void		run_free_rx_ring(struct run_softc *);
190 int		run_alloc_tx_ring(struct run_softc *, int);
191 void		run_free_tx_ring(struct run_softc *, int);
192 int		run_load_microcode(struct run_softc *);
193 int		run_reset(struct run_softc *);
194 int		run_read(struct run_softc *, uint16_t, uint32_t *);
195 int		run_read_region_1(struct run_softc *, uint16_t, uint8_t *,
196 		    int);
197 int		run_write_2(struct run_softc *, uint16_t, uint16_t);
198 int		run_write(struct run_softc *, uint16_t, uint32_t);
199 int		run_write_region_1(struct run_softc *, uint16_t,
200 		    const uint8_t *, int);
201 int		run_set_region_4(struct run_softc *, uint16_t, uint32_t, int);
202 int		run_efuse_read_2(struct run_softc *, uint16_t, uint16_t *);
203 int		run_eeprom_read_2(struct run_softc *, uint16_t, uint16_t *);
204 int		run_rt2870_rf_write(struct run_softc *, uint8_t, uint32_t);
205 int		run_rt3070_rf_read(struct run_softc *, uint8_t, uint8_t *);
206 int		run_rt3070_rf_write(struct run_softc *, uint8_t, uint8_t);
207 int		run_bbp_read(struct run_softc *, uint8_t, uint8_t *);
208 int		run_bbp_write(struct run_softc *, uint8_t, uint8_t);
209 int		run_mcu_cmd(struct run_softc *, uint8_t, uint16_t);
210 const char *	run_get_rf(int);
211 int		run_read_eeprom(struct run_softc *);
212 struct		ieee80211_node *run_node_alloc(struct ieee80211com *);
213 int		run_media_change(struct ifnet *);
214 void		run_next_scan(void *);
215 void		run_task(void *);
216 void		run_do_async(struct run_softc *, void (*)(struct run_softc *,
217 		    void *), void *, int);
218 int		run_newstate(struct ieee80211com *, enum ieee80211_state, int);
219 void		run_newstate_cb(struct run_softc *, void *);
220 void		run_updateedca(struct ieee80211com *);
221 void		run_updateedca_cb(struct run_softc *, void *);
222 int		run_set_key(struct ieee80211com *, struct ieee80211_node *,
223 		    struct ieee80211_key *);
224 void		run_set_key_cb(struct run_softc *, void *);
225 void		run_delete_key(struct ieee80211com *, struct ieee80211_node *,
226 		    struct ieee80211_key *);
227 void		run_delete_key_cb(struct run_softc *, void *);
228 void		run_calibrate_to(void *);
229 void		run_calibrate_cb(struct run_softc *, void *);
230 void		run_newassoc(struct ieee80211com *, struct ieee80211_node *,
231 		    int);
232 void		run_rx_frame(struct run_softc *, uint8_t *, int);
233 void		run_rxeof(usbd_xfer_handle, usbd_private_handle, usbd_status);
234 void		run_txeof(usbd_xfer_handle, usbd_private_handle, usbd_status);
235 int		run_tx(struct run_softc *, struct mbuf *,
236 		    struct ieee80211_node *);
237 void		run_start(struct ifnet *);
238 void		run_watchdog(struct ifnet *);
239 int		run_ioctl(struct ifnet *, u_long, caddr_t);
240 void		run_select_chan_group(struct run_softc *, int);
241 void		run_set_rx_antenna(struct run_softc *, int);
242 void		run_rt2870_set_chan(struct run_softc *, u_int);
243 void		run_rt3070_set_chan(struct run_softc *, u_int);
244 int		run_set_chan(struct run_softc *, struct ieee80211_channel *);
245 void		run_enable_tsf_sync(struct run_softc *);
246 void		run_enable_mrr(struct run_softc *);
247 void		run_set_txpreamble(struct run_softc *);
248 void		run_set_basicrates(struct run_softc *);
249 void		run_set_leds(struct run_softc *, uint16_t);
250 void		run_set_bssid(struct run_softc *, const uint8_t *);
251 void		run_set_macaddr(struct run_softc *, const uint8_t *);
252 void		run_updateslot(struct ieee80211com *);
253 void		run_updateslot_cb(struct run_softc *, void *);
254 #if NBPFILTER > 0
255 int8_t		run_rssi2dbm(struct run_softc *, uint8_t, uint8_t);
256 #endif
257 int		run_bbp_init(struct run_softc *);
258 int		run_rt3070_rf_init(struct run_softc *);
259 int		run_rt3070_filter_calib(struct run_softc *, uint8_t, uint8_t,
260 		    uint8_t *);
261 int		run_txrx_enable(struct run_softc *);
262 int		run_init(struct ifnet *);
263 void		run_stop(struct ifnet *, int);
264 
265 struct cfdriver run_cd = {
266 	NULL, "run", DV_IFNET
267 };
268 
269 const struct cfattach run_ca = {
270 	sizeof (struct run_softc), run_match, run_attach, run_detach
271 };
272 
273 static const struct {
274 	uint32_t	reg;
275 	uint32_t	val;
276 } rt2870_def_mac[] = {
277 	RT2870_DEF_MAC
278 };
279 
280 static const struct {
281 	uint8_t	reg;
282 	uint8_t	val;
283 } rt2860_def_bbp[] = {
284 	RT2860_DEF_BBP
285 };
286 
287 static const struct rfprog {
288 	uint8_t		chan;
289 	uint32_t	r1, r2, r3, r4;
290 } rt2860_rf2850[] = {
291 	RT2860_RF2850
292 };
293 
294 struct {
295 	uint8_t	n, r, k;
296 } run_rf3020_freqs[] = {
297 	RT3070_RF3020
298 };
299 
300 static const struct {
301 	uint8_t	reg;
302 	uint8_t	val;
303 } rt3070_def_rf[] = {
304 	RT3070_DEF_RF
305 };
306 
307 int
308 run_match(struct device *parent, void *match, void *aux)
309 {
310 	struct usb_attach_arg *uaa = aux;
311 
312 	if (uaa->iface != NULL)
313 		return UMATCH_NONE;
314 
315 	return (usb_lookup(run_devs, uaa->vendor, uaa->product) != NULL) ?
316 	    UMATCH_VENDOR_PRODUCT : UMATCH_NONE;
317 }
318 
319 void
320 run_attach(struct device *parent, struct device *self, void *aux)
321 {
322 	struct run_softc *sc = (struct run_softc *)self;
323 	struct usb_attach_arg *uaa = aux;
324 	struct ieee80211com *ic = &sc->sc_ic;
325 	struct ifnet *ifp = &ic->ic_if;
326 	usb_interface_descriptor_t *id;
327 	usb_endpoint_descriptor_t *ed;
328 	int i, nrx, ntx, ntries, error;
329 
330 	sc->sc_udev = uaa->device;
331 
332 	if (usbd_set_config_no(sc->sc_udev, 1, 0) != 0) {
333 		printf("%s: could not set configuration no\n",
334 		    sc->sc_dev.dv_xname);
335 		return;
336 	}
337 
338 	/* get the first interface handle */
339 	error = usbd_device2interface_handle(sc->sc_udev, 0, &sc->sc_iface);
340 	if (error != 0) {
341 		printf("%s: could not get interface handle\n",
342 		    sc->sc_dev.dv_xname);
343 		return;
344 	}
345 
346 	/*
347 	 * Find all bulk endpoints.  There are 7 bulk endpoints: 1 for RX
348 	 * and 6 for TX (4 EDCAs + HCCA + Prio).
349 	 * Update 03-14-2009:  some devices like the Planex GW-US300MiniS
350 	 * seem to have only 4 TX bulk endpoints (Fukaumi Naoki).
351 	 */
352 	nrx = ntx = 0;
353 	id = usbd_get_interface_descriptor(sc->sc_iface);
354 	for (i = 0; i < id->bNumEndpoints; i++) {
355 		ed = usbd_interface2endpoint_descriptor(sc->sc_iface, i);
356 		if (ed == NULL || UE_GET_XFERTYPE(ed->bmAttributes) != UE_BULK)
357 			continue;
358 
359 		if (UE_GET_DIR(ed->bEndpointAddress) == UE_DIR_IN) {
360 			sc->rxq.pipe_no = ed->bEndpointAddress;
361 			nrx++;
362 		} else if (ntx < 4) {
363 			sc->txq[ntx].pipe_no = ed->bEndpointAddress;
364 			ntx++;
365 		}
366 	}
367 	/* make sure we've got them all */
368 	if (nrx < 1 || ntx < 4) {
369 		printf("%s: missing endpoint\n", sc->sc_dev.dv_xname);
370 		return;
371 	}
372 
373 	usb_init_task(&sc->sc_task, run_task, sc);
374 	timeout_set(&sc->scan_to, run_next_scan, sc);
375 	timeout_set(&sc->calib_to, run_calibrate_to, sc);
376 
377 	sc->amrr.amrr_min_success_threshold =  1;
378 	sc->amrr.amrr_max_success_threshold = 10;
379 
380 	/* wait for the chip to settle */
381 	for (ntries = 0; ntries < 100; ntries++) {
382 		if (run_read(sc, RT2860_ASIC_VER_ID, &sc->mac_rev) != 0)
383 			return;
384 		if (sc->mac_rev != 0 && sc->mac_rev != 0xffffffff)
385 			break;
386 		DELAY(10);
387 	}
388 	if (ntries == 100) {
389 		printf("%s: timeout waiting for NIC to initialize\n",
390 		    sc->sc_dev.dv_xname);
391 		return;
392 	}
393 
394 	/* retrieve RF rev. no and various other things from EEPROM */
395 	run_read_eeprom(sc);
396 
397 	printf("%s: MAC/BBP RT%04X (rev 0x%04X), RF %s (MIMO %dT%dR), "
398 	    "address %s\n", sc->sc_dev.dv_xname, sc->mac_rev >> 16,
399 	    sc->mac_rev & 0xffff, run_get_rf(sc->rf_rev), sc->ntxchains,
400 	    sc->nrxchains, ether_sprintf(ic->ic_myaddr));
401 
402 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
403 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
404 	ic->ic_state = IEEE80211_S_INIT;
405 
406 	/* set device capabilities */
407 	ic->ic_caps =
408 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
409 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
410 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
411 	    IEEE80211_C_WEP |		/* WEP */
412 	    IEEE80211_C_RSN;		/* WPA/RSN */
413 
414 	if (sc->rf_rev == RT2860_RF_2750 || sc->rf_rev == RT2860_RF_2850) {
415 		/* set supported .11a rates */
416 		ic->ic_sup_rates[IEEE80211_MODE_11A] =
417 		    ieee80211_std_rateset_11a;
418 
419 		/* set supported .11a channels */
420 		for (i = 14; i < nitems(rt2860_rf2850); i++) {
421 			uint8_t chan = rt2860_rf2850[i].chan;
422 			ic->ic_channels[chan].ic_freq =
423 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_5GHZ);
424 			ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_A;
425 		}
426 	}
427 
428 	/* set supported .11b and .11g rates */
429 	ic->ic_sup_rates[IEEE80211_MODE_11B] = ieee80211_std_rateset_11b;
430 	ic->ic_sup_rates[IEEE80211_MODE_11G] = ieee80211_std_rateset_11g;
431 
432 	/* set supported .11b and .11g channels (1 through 14) */
433 	for (i = 1; i <= 14; i++) {
434 		ic->ic_channels[i].ic_freq =
435 		    ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
436 		ic->ic_channels[i].ic_flags =
437 		    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
438 		    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
439 	}
440 
441 	ifp->if_softc = sc;
442 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
443 	ifp->if_init = run_init;
444 	ifp->if_ioctl = run_ioctl;
445 	ifp->if_start = run_start;
446 	ifp->if_watchdog = run_watchdog;
447 	IFQ_SET_READY(&ifp->if_snd);
448 	memcpy(ifp->if_xname, sc->sc_dev.dv_xname, IFNAMSIZ);
449 
450 	if_attach(ifp);
451 	ieee80211_ifattach(ifp);
452 	ic->ic_node_alloc = run_node_alloc;
453 	ic->ic_newassoc = run_newassoc;
454 	ic->ic_updateslot = run_updateslot;
455 	ic->ic_updateedca = run_updateedca;
456 	ic->ic_set_key = run_set_key;
457 	ic->ic_delete_key = run_delete_key;
458 	/* override state transition machine */
459 	sc->sc_newstate = ic->ic_newstate;
460 	ic->ic_newstate = run_newstate;
461 	ieee80211_media_init(ifp, run_media_change, ieee80211_media_status);
462 
463 #if NBPFILTER > 0
464 	bpfattach(&sc->sc_drvbpf, ifp, DLT_IEEE802_11_RADIO,
465 	    sizeof (struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN);
466 
467 	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
468 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
469 	sc->sc_rxtap.wr_ihdr.it_present = htole32(RUN_RX_RADIOTAP_PRESENT);
470 
471 	sc->sc_txtap_len = sizeof sc->sc_txtapu;
472 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
473 	sc->sc_txtap.wt_ihdr.it_present = htole32(RUN_TX_RADIOTAP_PRESENT);
474 #endif
475 
476 	usbd_add_drv_event(USB_EVENT_DRIVER_ATTACH, sc->sc_udev, &sc->sc_dev);
477 }
478 
479 int
480 run_detach(struct device *self, int flags)
481 {
482 	struct run_softc *sc = (struct run_softc *)self;
483 	struct ifnet *ifp = &sc->sc_ic.ic_if;
484 	int qid, s;
485 
486 	s = splnet();
487 
488 	/* wait for all queued asynchronous commands to complete */
489 	while (sc->cmdq.queued > 0)
490 		tsleep(&sc->cmdq, 0, "cmdq", 0);
491 
492 	timeout_del(&sc->scan_to);
493 	timeout_del(&sc->calib_to);
494 
495 	if (ifp->if_flags != 0) {	/* if_attach() has been called */
496 		ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
497 		ieee80211_ifdetach(ifp);
498 		if_detach(ifp);
499 	}
500 
501 	for (qid = 0; qid < 4; qid++)
502 		run_free_tx_ring(sc, qid);
503 	run_free_rx_ring(sc);
504 
505 	splx(s);
506 
507 	usbd_add_drv_event(USB_EVENT_DRIVER_DETACH, sc->sc_udev, &sc->sc_dev);
508 
509 	return 0;
510 }
511 
512 int
513 run_alloc_rx_ring(struct run_softc *sc)
514 {
515 	struct run_rx_ring *rxq = &sc->rxq;
516 	int i, error;
517 
518 	error = usbd_open_pipe(sc->sc_iface, rxq->pipe_no, 0, &rxq->pipeh);
519 	if (error != 0)
520 		goto fail;
521 
522 	for (i = 0; i < RUN_RX_RING_COUNT; i++) {
523 		struct run_rx_data *data = &rxq->data[i];
524 
525 		data->sc = sc;	/* backpointer for callbacks */
526 
527 		data->xfer = usbd_alloc_xfer(sc->sc_udev);
528 		if (data->xfer == NULL) {
529 			error = ENOMEM;
530 			goto fail;
531 		}
532 		data->buf = usbd_alloc_buffer(data->xfer, RUN_MAX_RXSZ);
533 		if (data->buf == NULL) {
534 			error = ENOMEM;
535 			goto fail;
536 		}
537 	}
538 	if (error != 0)
539 fail:		run_free_rx_ring(sc);
540 	return error;
541 }
542 
543 void
544 run_free_rx_ring(struct run_softc *sc)
545 {
546 	struct run_rx_ring *rxq = &sc->rxq;
547 	int i;
548 
549 	if (rxq->pipeh != NULL) {
550 		usbd_abort_pipe(rxq->pipeh);
551 		usbd_close_pipe(rxq->pipeh);
552 		rxq->pipeh = NULL;
553 	}
554 	for (i = 0; i < RUN_RX_RING_COUNT; i++) {
555 		if (rxq->data[i].xfer != NULL)
556 			usbd_free_xfer(rxq->data[i].xfer);
557 		rxq->data[i].xfer = NULL;
558 	}
559 }
560 
561 int
562 run_alloc_tx_ring(struct run_softc *sc, int qid)
563 {
564 	struct run_tx_ring *txq = &sc->txq[qid];
565 	int i, error;
566 
567 	txq->cur = txq->queued = 0;
568 
569 	error = usbd_open_pipe(sc->sc_iface, txq->pipe_no, 0, &txq->pipeh);
570 	if (error != 0)
571 		goto fail;
572 
573 	for (i = 0; i < RUN_TX_RING_COUNT; i++) {
574 		struct run_tx_data *data = &txq->data[i];
575 
576 		data->sc = sc;	/* backpointer for callbacks */
577 		data->qid = qid;
578 
579 		data->xfer = usbd_alloc_xfer(sc->sc_udev);
580 		if (data->xfer == NULL) {
581 			error = ENOMEM;
582 			goto fail;
583 		}
584 		data->buf = usbd_alloc_buffer(data->xfer, RUN_MAX_TXSZ);
585 		if (data->buf == NULL) {
586 			error = ENOMEM;
587 			goto fail;
588 		}
589 		/* zeroize the TXD + TXWI part */
590 		memset(data->buf, 0, sizeof (struct rt2870_txd) +
591 		    sizeof (struct rt2860_txwi));
592 	}
593 	if (error != 0)
594 fail:		run_free_tx_ring(sc, qid);
595 	return error;
596 }
597 
598 void
599 run_free_tx_ring(struct run_softc *sc, int qid)
600 {
601 	struct run_tx_ring *txq = &sc->txq[qid];
602 	int i;
603 
604 	if (txq->pipeh != NULL) {
605 		usbd_abort_pipe(txq->pipeh);
606 		usbd_close_pipe(txq->pipeh);
607 		txq->pipeh = NULL;
608 	}
609 	for (i = 0; i < RUN_TX_RING_COUNT; i++) {
610 		if (txq->data[i].xfer != NULL)
611 			usbd_free_xfer(txq->data[i].xfer);
612 		txq->data[i].xfer = NULL;
613 	}
614 }
615 
616 int
617 run_load_microcode(struct run_softc *sc)
618 {
619 	usb_device_request_t req;
620 	u_char *ucode, *base;
621 	size_t size;
622 	uint32_t tmp;
623 	int ntries, error;
624 
625 	if ((error = loadfirmware("run-rt2870", &ucode, &size)) != 0) {
626 		printf("%s: failed loadfirmware of file %s (error %d)\n",
627 		    sc->sc_dev.dv_xname, "run-rt2870", error);
628 		return error;
629 	}
630 	if (size != 8192) {
631 		printf("%s: invalid firmware size (should be 8KB)\n",
632 		    sc->sc_dev.dv_xname);
633 		free(ucode, M_DEVBUF);
634 		return EINVAL;
635 	}
636 
637 	base = ucode;
638 	/* RT3071/RT3072 use a different firmware */
639 	if ((sc->mac_rev >> 16) != 0x2860 &&
640 	    (sc->mac_rev >> 16) != 0x2872 &&
641 	    (sc->mac_rev >> 16) != 0x3070)
642 		base += 4096;
643 
644 	run_read(sc, RT2860_ASIC_VER_ID, &tmp);
645 	/* write microcode image */
646 	run_write_region_1(sc, RT2870_FW_BASE, base, 4096);
647 	free(ucode, M_DEVBUF);
648 	run_write(sc, RT2860_H2M_MAILBOX_CID, 0xffffffff);
649 	run_write(sc, RT2860_H2M_MAILBOX_STATUS, 0xffffffff);
650 
651 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
652 	req.bRequest = RT2870_RESET;
653 	USETW(req.wValue, 8);
654 	USETW(req.wIndex, 0);
655 	USETW(req.wLength, 0);
656 	if ((error = usbd_do_request(sc->sc_udev, &req, NULL)) != 0)
657 		return error;
658 
659 	usbd_delay_ms(sc->sc_udev, 10);
660 	run_write(sc, RT2860_H2M_MAILBOX, 0);
661 	if ((error = run_mcu_cmd(sc, RT2860_MCU_CMD_BOOT, 0)) != 0)
662 		return error;
663 
664 	/* wait until microcontroller is ready */
665 	for (ntries = 0; ntries < 1000; ntries++) {
666 		if ((error = run_read(sc, RT2860_SYS_CTRL, &tmp)) != 0)
667 			return error;
668 		if (tmp & RT2860_MCU_READY)
669 			break;
670 		DELAY(1000);
671 	}
672 	if (ntries == 1000) {
673 		printf("%s: timeout waiting for MCU to initialize\n",
674 		    sc->sc_dev.dv_xname);
675 		return ETIMEDOUT;
676 	}
677 	DPRINTF(("microcode successfully loaded after %d tries\n", ntries));
678 	return 0;
679 }
680 
681 int
682 run_reset(struct run_softc *sc)
683 {
684 	usb_device_request_t req;
685 
686 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
687 	req.bRequest = RT2870_RESET;
688 	USETW(req.wValue, 1);
689 	USETW(req.wIndex, 0);
690 	USETW(req.wLength, 0);
691 	return usbd_do_request(sc->sc_udev, &req, NULL);
692 }
693 
694 int
695 run_read(struct run_softc *sc, uint16_t reg, uint32_t *val)
696 {
697 	uint32_t tmp;
698 	int error;
699 
700 	error = run_read_region_1(sc, reg, (uint8_t *)&tmp, sizeof tmp);
701 	if (error == 0)
702 		*val = letoh32(tmp);
703 	else
704 		*val = 0xffffffff;
705 	return error;
706 }
707 
708 int
709 run_read_region_1(struct run_softc *sc, uint16_t reg, uint8_t *buf, int len)
710 {
711 	usb_device_request_t req;
712 
713 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
714 	req.bRequest = RT2870_READ_REGION_1;
715 	USETW(req.wValue, 0);
716 	USETW(req.wIndex, reg);
717 	USETW(req.wLength, len);
718 	return usbd_do_request(sc->sc_udev, &req, buf);
719 }
720 
721 int
722 run_write_2(struct run_softc *sc, uint16_t reg, uint16_t val)
723 {
724 	usb_device_request_t req;
725 
726 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
727 	req.bRequest = RT2870_WRITE_2;
728 	USETW(req.wValue, val);
729 	USETW(req.wIndex, reg);
730 	USETW(req.wLength, 0);
731 	return usbd_do_request(sc->sc_udev, &req, NULL);
732 }
733 
734 int
735 run_write(struct run_softc *sc, uint16_t reg, uint32_t val)
736 {
737 	int error;
738 
739 	if ((error = run_write_2(sc, reg, val & 0xffff)) == 0)
740 		error = run_write_2(sc, reg + 2, val >> 16);
741 	return error;
742 }
743 
744 int
745 run_write_region_1(struct run_softc *sc, uint16_t reg, const uint8_t *buf,
746     int len)
747 {
748 #if 1
749 	int i, error = 0;
750 	/*
751 	 * NB: the WRITE_REGION_1 command is not stable on RT2860.
752 	 * We thus issue multiple WRITE_2 commands instead.
753 	 */
754 	KASSERT((len & 1) == 0);
755 	for (i = 0; i < len && error == 0; i += 2)
756 		error = run_write_2(sc, reg + i, buf[i] | buf[i + 1] << 8);
757 	return error;
758 #else
759 	usb_device_request_t req;
760 
761 	req.bmRequestType = UT_WRITE_VENDOR_DEVICE;
762 	req.bRequest = RT2870_WRITE_REGION_1;
763 	USETW(req.wValue, 0);
764 	USETW(req.wIndex, reg);
765 	USETW(req.wLength, len);
766 	return usbd_do_request(sc->sc_udev, &req, buf);
767 #endif
768 }
769 
770 int
771 run_set_region_4(struct run_softc *sc, uint16_t reg, uint32_t val, int len)
772 {
773 	int i, error = 0;
774 
775 	KASSERT((len & 3) == 0);
776 	for (i = 0; i < len && error == 0; i += 4)
777 		error = run_write(sc, reg + i, val);
778 	return error;
779 }
780 
781 /* Read 16-bit from eFUSE ROM (RT3070 only.) */
782 int
783 run_efuse_read_2(struct run_softc *sc, uint16_t addr, uint16_t *val)
784 {
785 	uint32_t tmp;
786 	uint16_t reg;
787 	int error, ntries;
788 
789 	if ((error = run_read(sc, RT3070_EFUSE_CTRL, &tmp)) != 0)
790 		return error;
791 
792 	addr *= 2;
793 	/*-
794 	 * Read one 16-byte block into registers EFUSE_DATA[0-3]:
795 	 * DATA0: F E D C
796 	 * DATA1: B A 9 8
797 	 * DATA2: 7 6 5 4
798 	 * DATA3: 3 2 1 0
799 	 */
800 	tmp &= ~RT3070_EFSROM_MODE_MASK;
801 	tmp |= (addr & ~0xf) << RT3070_EFSROM_AIN_SHIFT | RT3070_EFSROM_KICK;
802 	run_write(sc, RT3070_EFUSE_CTRL, tmp);
803 	for (ntries = 0; ntries < 100; ntries++) {
804 		if ((error = run_read(sc, RT3070_EFUSE_CTRL, &tmp)) != 0)
805 			return error;
806 		if (!(tmp & RT3070_EFSROM_KICK))
807 			break;
808 		DELAY(2);
809 	}
810 	if (ntries == 100)
811 		return ETIMEDOUT;
812 
813 	if ((tmp & RT3070_EFUSE_AOUT_MASK) == RT3070_EFUSE_AOUT_MASK) {
814 		*val = 0xffff;	/* address not found */
815 		return 0;
816 	}
817 	/* determine to which 32-bit register our 16-bit word belongs */
818 	reg = RT3070_EFUSE_DATA3 - (addr & 0xc);
819 	if ((error = run_read(sc, reg, &tmp)) != 0)
820 		return error;
821 
822 	*val = (addr & 2) ? tmp >> 16 : tmp & 0xffff;
823 	return 0;
824 }
825 
826 int
827 run_eeprom_read_2(struct run_softc *sc, uint16_t addr, uint16_t *val)
828 {
829 	usb_device_request_t req;
830 	uint16_t tmp;
831 	int error;
832 
833 	addr *= 2;
834 	req.bmRequestType = UT_READ_VENDOR_DEVICE;
835 	req.bRequest = RT2870_EEPROM_READ;
836 	USETW(req.wValue, 0);
837 	USETW(req.wIndex, addr);
838 	USETW(req.wLength, sizeof tmp);
839 	error = usbd_do_request(sc->sc_udev, &req, &tmp);
840 	if (error == 0)
841 		*val = letoh16(tmp);
842 	else
843 		*val = 0xffff;
844 	return error;
845 }
846 
847 static __inline int
848 run_srom_read(struct run_softc *sc, uint16_t addr, uint16_t *val)
849 {
850 	/* either eFUSE ROM or EEPROM */
851 	return sc->sc_srom_read(sc, addr, val);
852 }
853 
854 int
855 run_rt2870_rf_write(struct run_softc *sc, uint8_t reg, uint32_t val)
856 {
857 	uint32_t tmp;
858 	int error, ntries;
859 
860 	for (ntries = 0; ntries < 10; ntries++) {
861 		if ((error = run_read(sc, RT2860_RF_CSR_CFG0, &tmp)) != 0)
862 			return error;
863 		if (!(tmp & RT2860_RF_REG_CTRL))
864 			break;
865 	}
866 	if (ntries == 10)
867 		return ETIMEDOUT;
868 
869 	/* RF registers are 24-bit on the RT2860 */
870 	tmp = RT2860_RF_REG_CTRL | 24 << RT2860_RF_REG_WIDTH_SHIFT |
871 	    (val & 0x3fffff) << 2 | (reg & 3);
872 	return run_write(sc, RT2860_RF_CSR_CFG0, tmp);
873 }
874 
875 int
876 run_rt3070_rf_read(struct run_softc *sc, uint8_t reg, uint8_t *val)
877 {
878 	uint32_t tmp;
879 	int error, ntries;
880 
881 	for (ntries = 0; ntries < 100; ntries++) {
882 		if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0)
883 			return error;
884 		if (!(tmp & RT3070_RF_KICK))
885 			break;
886 	}
887 	if (ntries == 100)
888 		return ETIMEDOUT;
889 
890 	tmp = RT3070_RF_KICK | reg << 8;
891 	if ((error = run_write(sc, RT3070_RF_CSR_CFG, tmp)) != 0)
892 		return error;
893 
894 	for (ntries = 0; ntries < 100; ntries++) {
895 		if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0)
896 			return error;
897 		if (!(tmp & RT3070_RF_KICK))
898 			break;
899 	}
900 	if (ntries == 100)
901 		return ETIMEDOUT;
902 
903 	*val = tmp & 0xff;
904 	return 0;
905 }
906 
907 int
908 run_rt3070_rf_write(struct run_softc *sc, uint8_t reg, uint8_t val)
909 {
910 	uint32_t tmp;
911 	int error, ntries;
912 
913 	for (ntries = 0; ntries < 10; ntries++) {
914 		if ((error = run_read(sc, RT3070_RF_CSR_CFG, &tmp)) != 0)
915 			return error;
916 		if (!(tmp & RT3070_RF_KICK))
917 			break;
918 	}
919 	if (ntries == 10)
920 		return ETIMEDOUT;
921 
922 	tmp = RT3070_RF_WRITE | RT3070_RF_KICK | reg << 8 | val;
923 	return run_write(sc, RT3070_RF_CSR_CFG, tmp);
924 }
925 
926 int
927 run_bbp_read(struct run_softc *sc, uint8_t reg, uint8_t *val)
928 {
929 	uint32_t tmp;
930 	int ntries, error;
931 
932 	for (ntries = 0; ntries < 10; ntries++) {
933 		if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0)
934 			return error;
935 		if (!(tmp & RT2860_BBP_CSR_KICK))
936 			break;
937 	}
938 	if (ntries == 10)
939 		return ETIMEDOUT;
940 
941 	tmp = RT2860_BBP_CSR_READ | RT2860_BBP_CSR_KICK | reg << 8;
942 	if ((error = run_write(sc, RT2860_BBP_CSR_CFG, tmp)) != 0)
943 		return error;
944 
945 	for (ntries = 0; ntries < 10; ntries++) {
946 		if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0)
947 			return error;
948 		if (!(tmp & RT2860_BBP_CSR_KICK))
949 			break;
950 	}
951 	if (ntries == 10)
952 		return ETIMEDOUT;
953 
954 	*val = tmp & 0xff;
955 	return 0;
956 }
957 
958 int
959 run_bbp_write(struct run_softc *sc, uint8_t reg, uint8_t val)
960 {
961 	uint32_t tmp;
962 	int ntries, error;
963 
964 	for (ntries = 0; ntries < 10; ntries++) {
965 		if ((error = run_read(sc, RT2860_BBP_CSR_CFG, &tmp)) != 0)
966 			return error;
967 		if (!(tmp & RT2860_BBP_CSR_KICK))
968 			break;
969 	}
970 	if (ntries == 10)
971 		return ETIMEDOUT;
972 
973 	tmp = RT2860_BBP_CSR_KICK | reg << 8 | val;
974 	return run_write(sc, RT2860_BBP_CSR_CFG, tmp);
975 }
976 
977 /*
978  * Send a command to the 8051 microcontroller unit.
979  */
980 int
981 run_mcu_cmd(struct run_softc *sc, uint8_t cmd, uint16_t arg)
982 {
983 	uint32_t tmp;
984 	int error, ntries;
985 
986 	for (ntries = 0; ntries < 100; ntries++) {
987 		if ((error = run_read(sc, RT2860_H2M_MAILBOX, &tmp)) != 0)
988 			return error;
989 		if (!(tmp & RT2860_H2M_BUSY))
990 			break;
991 	}
992 	if (ntries == 100)
993 		return ETIMEDOUT;
994 
995 	tmp = RT2860_H2M_BUSY | RT2860_TOKEN_NO_INTR << 16 | arg;
996 	if ((error = run_write(sc, RT2860_H2M_MAILBOX, tmp)) == 0)
997 		error = run_write(sc, RT2860_HOST_CMD, cmd);
998 	return error;
999 }
1000 
1001 /*
1002  * Add `delta' (signed) to each 4-bit sub-word of a 32-bit word.
1003  * Used to adjust per-rate Tx power registers.
1004  */
1005 static __inline uint32_t
1006 b4inc(uint32_t b32, int8_t delta)
1007 {
1008 	int8_t i, b4;
1009 
1010 	for (i = 0; i < 8; i++) {
1011 		b4 = b32 & 0xf;
1012 		b4 += delta;
1013 		if (b4 < 0)
1014 			b4 = 0;
1015 		else if (b4 > 0xf)
1016 			b4 = 0xf;
1017 		b32 = b32 >> 4 | b4 << 28;
1018 	}
1019 	return b32;
1020 }
1021 
1022 const char *
1023 run_get_rf(int rev)
1024 {
1025 	switch (rev) {
1026 	case RT2860_RF_2820:	return "RT2820";
1027 	case RT2860_RF_2850:	return "RT2850";
1028 	case RT2860_RF_2720:	return "RT2720";
1029 	case RT2860_RF_2750:	return "RT2750";
1030 	case RT3070_RF_3020:	return "RT3020";
1031 	case RT3070_RF_2020:	return "RT2020";
1032 	case RT3070_RF_3021:	return "RT3021";
1033 	case RT3070_RF_3022:	return "RT3022";
1034 	}
1035 	return "unknown";
1036 }
1037 
1038 int
1039 run_read_eeprom(struct run_softc *sc)
1040 {
1041 	struct ieee80211com *ic = &sc->sc_ic;
1042 	int8_t delta_2ghz, delta_5ghz;
1043 	uint32_t tmp;
1044 	uint16_t val;
1045 	int ridx, ant, i;
1046 
1047 	/* check whether the ROM is eFUSE ROM or EEPROM */
1048 	sc->sc_srom_read = run_eeprom_read_2;
1049 	if ((sc->mac_rev & 0xfff00000) >= 0x30700000) {
1050 		run_read(sc, RT3070_EFUSE_CTRL, &tmp);
1051 		if (tmp & RT3070_SEL_EFUSE)
1052 			sc->sc_srom_read = run_efuse_read_2;
1053 	}
1054 
1055 	/* read SROM version */
1056 	run_srom_read(sc, RT2860_EEPROM_VERSION, &val);
1057 	DPRINTF(("EEPROM rev=%d, FAE=%d\n", val & 0xff, val >> 8));
1058 
1059 	/* read MAC address */
1060 	run_srom_read(sc, RT2860_EEPROM_MAC01, &val);
1061 	ic->ic_myaddr[0] = val & 0xff;
1062 	ic->ic_myaddr[1] = val >> 8;
1063 	run_srom_read(sc, RT2860_EEPROM_MAC23, &val);
1064 	ic->ic_myaddr[2] = val & 0xff;
1065 	ic->ic_myaddr[3] = val >> 8;
1066 	run_srom_read(sc, RT2860_EEPROM_MAC45, &val);
1067 	ic->ic_myaddr[4] = val & 0xff;
1068 	ic->ic_myaddr[5] = val >> 8;
1069 
1070 	/* read default BBP settings */
1071 	for (i = 0; i < 8; i++) {
1072 		run_srom_read(sc, RT2860_EEPROM_BBP_BASE + i, &val);
1073 		sc->bbp[i].val = val & 0xff;
1074 		sc->bbp[i].reg = val >> 8;
1075 		DPRINTF(("BBP%d=0x%02x\n", sc->bbp[i].reg, sc->bbp[i].val));
1076 	}
1077 
1078 	/* read RF frequency offset from EEPROM */
1079 	run_srom_read(sc, RT2860_EEPROM_FREQ_LEDS, &val);
1080 	sc->freq = ((val & 0xff) != 0xff) ? val & 0xff : 0;
1081 	DPRINTF(("EEPROM freq offset %d\n", sc->freq & 0xff));
1082 
1083 	if ((sc->leds = val >> 8) != 0xff) {
1084 		/* read LEDs operating mode */
1085 		run_srom_read(sc, RT2860_EEPROM_LED1, &sc->led[0]);
1086 		run_srom_read(sc, RT2860_EEPROM_LED2, &sc->led[1]);
1087 		run_srom_read(sc, RT2860_EEPROM_LED3, &sc->led[2]);
1088 	} else {
1089 		/* broken EEPROM, use default settings */
1090 		sc->leds = 0x01;
1091 		sc->led[0] = 0x5555;
1092 		sc->led[1] = 0x2221;
1093 		sc->led[2] = 0x5627;	/* differs from RT2860 */
1094 	}
1095 	DPRINTF(("EEPROM LED mode=0x%02x, LEDs=0x%04x/0x%04x/0x%04x\n",
1096 	    sc->leds, sc->led[0], sc->led[1], sc->led[2]));
1097 
1098 	/* read RF information */
1099 	run_srom_read(sc, RT2860_EEPROM_ANTENNA, &val);
1100 	if (val == 0xffff) {
1101 		DPRINTF(("invalid EEPROM antenna info, using default\n"));
1102 		if ((sc->mac_rev >> 16) >= 0x3070) {
1103 			/* default to RF3020 1T1R */
1104 			sc->rf_rev = RT3070_RF_3020;
1105 			sc->ntxchains = 1;
1106 			sc->nrxchains = 1;
1107 		} else {
1108 			/* default to RF2820 1T2R */
1109 			sc->rf_rev = RT2860_RF_2820;
1110 			sc->ntxchains = 1;
1111 			sc->nrxchains = 2;
1112 		}
1113 	} else {
1114 		sc->rf_rev = (val >> 8) & 0xf;
1115 		sc->ntxchains = (val >> 4) & 0xf;
1116 		sc->nrxchains = val & 0xf;
1117 	}
1118 	DPRINTF(("EEPROM RF rev=0x%02x chains=%dT%dR\n",
1119 	    sc->rf_rev, sc->ntxchains, sc->nrxchains));
1120 
1121 	/* check if RF supports automatic Tx access gain control */
1122 	run_srom_read(sc, RT2860_EEPROM_CONFIG, &val);
1123 	DPRINTF(("EEPROM CFG 0x%04x\n", val));
1124 	if ((val & 0xff) != 0xff) {
1125 		sc->ext_5ghz_lna = (val >> 3) & 1;
1126 		sc->ext_2ghz_lna = (val >> 2) & 1;
1127 		sc->calib_2ghz = sc->calib_5ghz = (val >> 1) & 1;
1128 	}
1129 
1130 	/* read power settings for 2GHz channels */
1131 	for (i = 0; i < 14; i += 2) {
1132 		run_srom_read(sc, RT2860_EEPROM_PWR2GHZ_BASE1 + i / 2, &val);
1133 		sc->txpow1[i + 0] = (int8_t)(val & 0xff);
1134 		sc->txpow1[i + 1] = (int8_t)(val >> 8);
1135 
1136 		run_srom_read(sc, RT2860_EEPROM_PWR2GHZ_BASE2 + i / 2, &val);
1137 		sc->txpow2[i + 0] = (int8_t)(val & 0xff);
1138 		sc->txpow2[i + 1] = (int8_t)(val >> 8);
1139 	}
1140 	/* fix broken Tx power entries */
1141 	for (i = 0; i < 14; i++) {
1142 		if (sc->txpow1[i] < 0 || sc->txpow1[i] > 31)
1143 			sc->txpow1[i] = 5;
1144 		if (sc->txpow2[i] < 0 || sc->txpow2[i] > 31)
1145 			sc->txpow2[i] = 5;
1146 		DPRINTF(("chan %d: power1=%d, power2=%d\n",
1147 		    rt2860_rf2850[i].chan, sc->txpow1[i], sc->txpow2[i]));
1148 	}
1149 	/* read power settings for 5GHz channels */
1150 	for (i = 0; i < 36; i += 2) {
1151 		run_srom_read(sc, RT2860_EEPROM_PWR5GHZ_BASE1 + i / 2, &val);
1152 		sc->txpow1[i + 14] = (int8_t)(val & 0xff);
1153 		sc->txpow1[i + 15] = (int8_t)(val >> 8);
1154 
1155 		run_srom_read(sc, RT2860_EEPROM_PWR5GHZ_BASE2 + i / 2, &val);
1156 		sc->txpow2[i + 14] = (int8_t)(val & 0xff);
1157 		sc->txpow2[i + 15] = (int8_t)(val >> 8);
1158 	}
1159 	/* fix broken Tx power entries */
1160 	for (i = 0; i < 36; i++) {
1161 		if (sc->txpow1[14 + i] < -7 || sc->txpow1[14 + i] > 15)
1162 			sc->txpow1[14 + i] = 5;
1163 		if (sc->txpow2[14 + i] < -7 || sc->txpow2[14 + i] > 15)
1164 			sc->txpow2[14 + i] = 5;
1165 		DPRINTF(("chan %d: power1=%d, power2=%d\n",
1166 		    rt2860_rf2850[14 + i].chan, sc->txpow1[14 + i],
1167 		    sc->txpow2[14 + i]));
1168 	}
1169 
1170 	/* read Tx power compensation for each Tx rate */
1171 	run_srom_read(sc, RT2860_EEPROM_DELTAPWR, &val);
1172 	delta_2ghz = delta_5ghz = 0;
1173 	if ((val & 0xff) != 0xff && (val & 0x80)) {
1174 		delta_2ghz = val & 0xf;
1175 		if (!(val & 0x40))	/* negative number */
1176 			delta_2ghz = -delta_2ghz;
1177 	}
1178 	val >>= 8;
1179 	if ((val & 0xff) != 0xff && (val & 0x80)) {
1180 		delta_5ghz = val & 0xf;
1181 		if (!(val & 0x40))	/* negative number */
1182 			delta_5ghz = -delta_5ghz;
1183 	}
1184 	DPRINTF(("power compensation=%d (2GHz), %d (5GHz)\n",
1185 	    delta_2ghz, delta_5ghz));
1186 
1187 	for (ridx = 0; ridx < 5; ridx++) {
1188 		uint32_t reg;
1189 
1190 		run_srom_read(sc, RT2860_EEPROM_RPWR + ridx, &val);
1191 		reg = (uint32_t)val << 16;
1192 		run_srom_read(sc, RT2860_EEPROM_RPWR + ridx + 1, &val);
1193 		reg |= val;
1194 
1195 		sc->txpow20mhz[ridx] = reg;
1196 		sc->txpow40mhz_2ghz[ridx] = b4inc(reg, delta_2ghz);
1197 		sc->txpow40mhz_5ghz[ridx] = b4inc(reg, delta_5ghz);
1198 
1199 		DPRINTF(("ridx %d: power 20MHz=0x%08x, 40MHz/2GHz=0x%08x, "
1200 		    "40MHz/5GHz=0x%08x\n", ridx, sc->txpow20mhz[ridx],
1201 		    sc->txpow40mhz_2ghz[ridx], sc->txpow40mhz_5ghz[ridx]));
1202 	}
1203 
1204 	/* read RSSI offsets and LNA gains from EEPROM */
1205 	run_srom_read(sc, RT2860_EEPROM_RSSI1_2GHZ, &val);
1206 	sc->rssi_2ghz[0] = val & 0xff;	/* Ant A */
1207 	sc->rssi_2ghz[1] = val >> 8;	/* Ant B */
1208 	run_srom_read(sc, RT2860_EEPROM_RSSI2_2GHZ, &val);
1209 	sc->rssi_2ghz[2] = val & 0xff;	/* Ant C */
1210 	sc->lna[2] = val >> 8;		/* channel group 2 */
1211 
1212 	run_srom_read(sc, RT2860_EEPROM_RSSI1_5GHZ, &val);
1213 	sc->rssi_5ghz[0] = val & 0xff;	/* Ant A */
1214 	sc->rssi_5ghz[1] = val >> 8;	/* Ant B */
1215 	run_srom_read(sc, RT2860_EEPROM_RSSI2_5GHZ, &val);
1216 	sc->rssi_5ghz[2] = val & 0xff;	/* Ant C */
1217 	sc->lna[3] = val >> 8;		/* channel group 3 */
1218 
1219 	run_srom_read(sc, RT2860_EEPROM_LNA, &val);
1220 	sc->lna[0] = val & 0xff;	/* channel group 0 */
1221 	sc->lna[1] = val >> 8;		/* channel group 1 */
1222 
1223 	/* fix broken 5GHz LNA entries */
1224 	if (sc->lna[2] == 0 || sc->lna[2] == 0xff) {
1225 		DPRINTF(("invalid LNA for channel group %d\n", 2));
1226 		sc->lna[2] = sc->lna[1];
1227 	}
1228 	if (sc->lna[3] == 0 || sc->lna[3] == 0xff) {
1229 		DPRINTF(("invalid LNA for channel group %d\n", 3));
1230 		sc->lna[3] = sc->lna[1];
1231 	}
1232 
1233 	/* fix broken RSSI offset entries */
1234 	for (ant = 0; ant < 3; ant++) {
1235 		if (sc->rssi_2ghz[ant] < -10 || sc->rssi_2ghz[ant] > 10) {
1236 			DPRINTF(("invalid RSSI%d offset: %d (2GHz)\n",
1237 			    ant + 1, sc->rssi_2ghz[ant]));
1238 			sc->rssi_2ghz[ant] = 0;
1239 		}
1240 		if (sc->rssi_5ghz[ant] < -10 || sc->rssi_5ghz[ant] > 10) {
1241 			DPRINTF(("invalid RSSI%d offset: %d (5GHz)\n",
1242 			    ant + 1, sc->rssi_5ghz[ant]));
1243 			sc->rssi_5ghz[ant] = 0;
1244 		}
1245 	}
1246 	return 0;
1247 }
1248 
1249 struct ieee80211_node *
1250 run_node_alloc(struct ieee80211com *ic)
1251 {
1252 	return malloc(sizeof (struct run_node), M_DEVBUF, M_NOWAIT | M_ZERO);
1253 }
1254 
1255 int
1256 run_media_change(struct ifnet *ifp)
1257 {
1258 	struct run_softc *sc = ifp->if_softc;
1259 	struct ieee80211com *ic = &sc->sc_ic;
1260 	uint8_t rate, ridx;
1261 	int error;
1262 
1263 	error = ieee80211_media_change(ifp);
1264 	if (error != ENETRESET)
1265 		return error;
1266 
1267 	if (ic->ic_fixed_rate != -1) {
1268 		rate = ic->ic_sup_rates[ic->ic_curmode].
1269 		    rs_rates[ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
1270 		for (ridx = 0; ridx <= RT2860_RIDX_MAX; ridx++)
1271 			if (rt2860_rates[ridx].rate == rate)
1272 				break;
1273 		sc->fixed_ridx = ridx;
1274 	}
1275 
1276 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
1277 		run_init(ifp);
1278 
1279 	return 0;
1280 }
1281 
1282 void
1283 run_next_scan(void *arg)
1284 {
1285 	struct run_softc *sc = arg;
1286 
1287 	if (sc->sc_ic.ic_state == IEEE80211_S_SCAN)
1288 		ieee80211_next_scan(&sc->sc_ic.ic_if);
1289 }
1290 
1291 void
1292 run_task(void *arg)
1293 {
1294 	struct run_softc *sc = arg;
1295 	struct run_host_cmd_ring *ring = &sc->cmdq;
1296 	struct run_host_cmd *cmd;
1297 	int s;
1298 
1299 	/* process host commands */
1300 	s = splusb();
1301 	while (ring->next != ring->cur) {
1302 		cmd = &ring->cmd[ring->next];
1303 		splx(s);
1304 		/* callback */
1305 		cmd->cb(sc, cmd->data);
1306 		s = splusb();
1307 		ring->queued--;
1308 		ring->next = (ring->next + 1) % RUN_HOST_CMD_RING_COUNT;
1309 	}
1310 	wakeup(ring);
1311 	splx(s);
1312 }
1313 
1314 void
1315 run_do_async(struct run_softc *sc, void (*cb)(struct run_softc *, void *),
1316     void *arg, int len)
1317 {
1318 	struct run_host_cmd_ring *ring = &sc->cmdq;
1319 	struct run_host_cmd *cmd;
1320 	int s;
1321 
1322 	s = splusb();
1323 	cmd = &ring->cmd[ring->cur];
1324 	cmd->cb = cb;
1325 	KASSERT(len <= sizeof (cmd->data));
1326 	memcpy(cmd->data, arg, len);
1327 	ring->cur = (ring->cur + 1) % RUN_HOST_CMD_RING_COUNT;
1328 
1329 	/* if there is no pending command already, schedule a task */
1330 	if (++ring->queued == 1)
1331 		usb_add_task(sc->sc_udev, &sc->sc_task);
1332 	splx(s);
1333 }
1334 
1335 int
1336 run_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
1337 {
1338 	struct run_softc *sc = ic->ic_softc;
1339 	struct run_cmd_newstate cmd;
1340 
1341 	/* do it in a process context */
1342 	cmd.state = nstate;
1343 	cmd.arg = arg;
1344 	run_do_async(sc, run_newstate_cb, &cmd, sizeof cmd);
1345 	return 0;
1346 }
1347 
1348 void
1349 run_newstate_cb(struct run_softc *sc, void *arg)
1350 {
1351 	struct run_cmd_newstate *cmd = arg;
1352 	struct ieee80211com *ic = &sc->sc_ic;
1353 	enum ieee80211_state ostate;
1354 	struct ieee80211_node *ni;
1355 	uint32_t tmp, sta[3];
1356 	uint8_t wcid;
1357 	int s;
1358 
1359 	s = splnet();
1360 	ostate = ic->ic_state;
1361 
1362 	if (ostate == IEEE80211_S_RUN) {
1363 		/* turn link LED off */
1364 		run_set_leds(sc, RT2860_LED_RADIO);
1365 	}
1366 
1367 	switch (cmd->state) {
1368 	case IEEE80211_S_INIT:
1369 		if (ostate == IEEE80211_S_RUN) {
1370 			/* abort TSF synchronization */
1371 			run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
1372 			run_write(sc, RT2860_BCN_TIME_CFG,
1373 			    tmp & ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN |
1374 			    RT2860_TBTT_TIMER_EN));
1375 		}
1376 		break;
1377 
1378 	case IEEE80211_S_SCAN:
1379 		run_set_chan(sc, ic->ic_bss->ni_chan);
1380 		timeout_add_msec(&sc->scan_to, 200);
1381 		break;
1382 
1383 	case IEEE80211_S_AUTH:
1384 	case IEEE80211_S_ASSOC:
1385 		run_set_chan(sc, ic->ic_bss->ni_chan);
1386 		break;
1387 
1388 	case IEEE80211_S_RUN:
1389 		run_set_chan(sc, ic->ic_bss->ni_chan);
1390 
1391 		ni = ic->ic_bss;
1392 
1393 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
1394 			run_updateslot(ic);
1395 			run_enable_mrr(sc);
1396 			run_set_txpreamble(sc);
1397 			run_set_basicrates(sc);
1398 			run_set_bssid(sc, ni->ni_bssid);
1399 		}
1400 		if (ic->ic_opmode == IEEE80211_M_STA) {
1401 			/* add BSS entry to the WCID table */
1402 			wcid = RUN_AID2WCID(ni->ni_associd);
1403 			run_write_region_1(sc, RT2860_WCID_ENTRY(wcid),
1404 			    ni->ni_macaddr, IEEE80211_ADDR_LEN);
1405 
1406 			/* fake a join to init the tx rate */
1407 			run_newassoc(ic, ni, 1);
1408 		}
1409 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
1410 			run_enable_tsf_sync(sc);
1411 
1412 			/* clear statistic registers used by AMRR */
1413 			run_read_region_1(sc, RT2860_TX_STA_CNT0,
1414 			    (uint8_t *)sta, sizeof sta);
1415 			/* start calibration timer */
1416 			timeout_add_sec(&sc->calib_to, 1);
1417 		}
1418 
1419 		/* turn link LED on */
1420 		run_set_leds(sc, RT2860_LED_RADIO |
1421 		    (IEEE80211_IS_CHAN_2GHZ(ic->ic_bss->ni_chan) ?
1422 		     RT2860_LED_LINK_2GHZ : RT2860_LED_LINK_5GHZ));
1423 		break;
1424 	}
1425 	(void)sc->sc_newstate(ic, cmd->state, cmd->arg);
1426 	splx(s);
1427 }
1428 
1429 void
1430 run_updateedca(struct ieee80211com *ic)
1431 {
1432 	/* do it in a process context */
1433 	run_do_async(ic->ic_softc, run_updateedca_cb, NULL, 0);
1434 }
1435 
1436 /* ARGSUSED */
1437 void
1438 run_updateedca_cb(struct run_softc *sc, void *arg)
1439 {
1440 	struct ieee80211com *ic = &sc->sc_ic;
1441 	int s, aci;
1442 
1443 	s = splnet();
1444 	/* update MAC TX configuration registers */
1445 	for (aci = 0; aci < EDCA_NUM_AC; aci++) {
1446 		run_write(sc, RT2860_EDCA_AC_CFG(aci),
1447 		    ic->ic_edca_ac[aci].ac_ecwmax << 16 |
1448 		    ic->ic_edca_ac[aci].ac_ecwmin << 12 |
1449 		    ic->ic_edca_ac[aci].ac_aifsn  <<  8 |
1450 		    ic->ic_edca_ac[aci].ac_txoplimit);
1451 	}
1452 
1453 	/* update SCH/DMA registers too */
1454 	run_write(sc, RT2860_WMM_AIFSN_CFG,
1455 	    ic->ic_edca_ac[EDCA_AC_VO].ac_aifsn  << 12 |
1456 	    ic->ic_edca_ac[EDCA_AC_VI].ac_aifsn  <<  8 |
1457 	    ic->ic_edca_ac[EDCA_AC_BK].ac_aifsn  <<  4 |
1458 	    ic->ic_edca_ac[EDCA_AC_BE].ac_aifsn);
1459 	run_write(sc, RT2860_WMM_CWMIN_CFG,
1460 	    ic->ic_edca_ac[EDCA_AC_VO].ac_ecwmin << 12 |
1461 	    ic->ic_edca_ac[EDCA_AC_VI].ac_ecwmin <<  8 |
1462 	    ic->ic_edca_ac[EDCA_AC_BK].ac_ecwmin <<  4 |
1463 	    ic->ic_edca_ac[EDCA_AC_BE].ac_ecwmin);
1464 	run_write(sc, RT2860_WMM_CWMAX_CFG,
1465 	    ic->ic_edca_ac[EDCA_AC_VO].ac_ecwmax << 12 |
1466 	    ic->ic_edca_ac[EDCA_AC_VI].ac_ecwmax <<  8 |
1467 	    ic->ic_edca_ac[EDCA_AC_BK].ac_ecwmax <<  4 |
1468 	    ic->ic_edca_ac[EDCA_AC_BE].ac_ecwmax);
1469 	run_write(sc, RT2860_WMM_TXOP0_CFG,
1470 	    ic->ic_edca_ac[EDCA_AC_BK].ac_txoplimit << 16 |
1471 	    ic->ic_edca_ac[EDCA_AC_BE].ac_txoplimit);
1472 	run_write(sc, RT2860_WMM_TXOP1_CFG,
1473 	    ic->ic_edca_ac[EDCA_AC_VO].ac_txoplimit << 16 |
1474 	    ic->ic_edca_ac[EDCA_AC_VI].ac_txoplimit);
1475 	splx(s);
1476 }
1477 
1478 int
1479 run_set_key(struct ieee80211com *ic, struct ieee80211_node *ni,
1480     struct ieee80211_key *k)
1481 {
1482 	struct run_softc *sc = ic->ic_softc;
1483 	struct run_cmd_key cmd;
1484 
1485 	/* do it in a process context */
1486 	cmd.key = *k;
1487 	cmd.associd = (ni != NULL) ? ni->ni_associd : 0;
1488 	run_do_async(sc, run_set_key_cb, &cmd, sizeof cmd);
1489 	return 0;
1490 }
1491 
1492 void
1493 run_set_key_cb(struct run_softc *sc, void *arg)
1494 {
1495 	struct run_cmd_key *cmd = arg;
1496 	struct ieee80211_key *k = &cmd->key;
1497 	uint32_t attr;
1498 	uint16_t base;
1499 	uint8_t mode, wcid, iv[8];
1500 
1501 	/* map net80211 cipher to RT2860 security mode */
1502 	switch (k->k_cipher) {
1503 	case IEEE80211_CIPHER_WEP40:
1504 		mode = RT2860_MODE_WEP40;
1505 		break;
1506 	case IEEE80211_CIPHER_WEP104:
1507 		mode = RT2860_MODE_WEP104;
1508 		break;
1509 	case IEEE80211_CIPHER_TKIP:
1510 		mode = RT2860_MODE_TKIP;
1511 		break;
1512 	case IEEE80211_CIPHER_CCMP:
1513 		mode = RT2860_MODE_AES_CCMP;
1514 		break;
1515 	default:
1516 		return;
1517 	}
1518 
1519 	if (k->k_flags & IEEE80211_KEY_GROUP) {
1520 		wcid = 0;	/* NB: update WCID0 for group keys */
1521 		base = RT2860_SKEY(0, k->k_id);
1522 	} else {
1523 		wcid = RUN_AID2WCID(cmd->associd);
1524 		base = RT2860_PKEY(wcid);
1525 	}
1526 
1527 	if (k->k_cipher == IEEE80211_CIPHER_TKIP) {
1528 		run_write_region_1(sc, base, k->k_key, 16);
1529 		run_write_region_1(sc, base + 16, &k->k_key[24], 8);
1530 		run_write_region_1(sc, base + 24, &k->k_key[16], 8);
1531 	} else {
1532 		/* roundup len to 16-bit: XXX fix write_region_1() instead */
1533 		run_write_region_1(sc, base, k->k_key, (k->k_len + 1) & ~1);
1534 	}
1535 
1536 	if (!(k->k_flags & IEEE80211_KEY_GROUP) ||
1537 	    (k->k_flags & IEEE80211_KEY_TX)) {
1538 		/* set initial packet number in IV+EIV */
1539 		if (k->k_cipher == IEEE80211_CIPHER_WEP40 ||
1540 		    k->k_cipher == IEEE80211_CIPHER_WEP104) {
1541 			memset(iv, 0, sizeof iv);
1542 			iv[3] = sc->sc_ic.ic_def_txkey << 6;
1543 		} else {
1544 			if (k->k_cipher == IEEE80211_CIPHER_TKIP) {
1545 				iv[0] = k->k_tsc >> 8;
1546 				iv[1] = (iv[0] | 0x20) & 0x7f;
1547 				iv[2] = k->k_tsc;
1548 			} else /* CCMP */ {
1549 				iv[0] = k->k_tsc;
1550 				iv[1] = k->k_tsc >> 8;
1551 				iv[2] = 0;
1552 			}
1553 			iv[3] = k->k_id << 6 | IEEE80211_WEP_EXTIV;
1554 			iv[4] = k->k_tsc >> 16;
1555 			iv[5] = k->k_tsc >> 24;
1556 			iv[6] = k->k_tsc >> 32;
1557 			iv[7] = k->k_tsc >> 40;
1558 		}
1559 		run_write_region_1(sc, RT2860_IVEIV(wcid), iv, 8);
1560 	}
1561 
1562 	if (k->k_flags & IEEE80211_KEY_GROUP) {
1563 		/* install group key */
1564 		run_read(sc, RT2860_SKEY_MODE_0_7, &attr);
1565 		attr &= ~(0xf << (k->k_id * 4));
1566 		attr |= mode << (k->k_id * 4);
1567 		run_write(sc, RT2860_SKEY_MODE_0_7, attr);
1568 	} else {
1569 		/* install pairwise key */
1570 		run_read(sc, RT2860_WCID_ATTR(wcid), &attr);
1571 		attr = (attr & ~0xf) | (mode << 1) | RT2860_RX_PKEY_EN;
1572 		run_write(sc, RT2860_WCID_ATTR(wcid), attr);
1573 	}
1574 }
1575 
1576 void
1577 run_delete_key(struct ieee80211com *ic, struct ieee80211_node *ni,
1578     struct ieee80211_key *k)
1579 {
1580 	struct run_softc *sc = ic->ic_softc;
1581 	struct run_cmd_key cmd;
1582 
1583 	if (!(ic->ic_if.if_flags & IFF_RUNNING) ||
1584 	    ic->ic_state != IEEE80211_S_RUN)
1585 		return;	/* nothing to do */
1586 
1587 	/* do it in a process context */
1588 	cmd.key = *k;
1589 	cmd.associd = (ni != NULL) ? ni->ni_associd : 0;
1590 	run_do_async(sc, run_delete_key_cb, &cmd, sizeof cmd);
1591 }
1592 
1593 void
1594 run_delete_key_cb(struct run_softc *sc, void *arg)
1595 {
1596 	struct run_cmd_key *cmd = arg;
1597 	struct ieee80211_key *k = &cmd->key;
1598 	uint32_t attr;
1599 	uint8_t wcid;
1600 
1601 	if (k->k_flags & IEEE80211_KEY_GROUP) {
1602 		/* remove group key */
1603 		run_read(sc, RT2860_SKEY_MODE_0_7, &attr);
1604 		attr &= ~(0xf << (k->k_id * 4));
1605 		run_write(sc, RT2860_SKEY_MODE_0_7, attr);
1606 
1607 	} else {
1608 		/* remove pairwise key */
1609 		wcid = RUN_AID2WCID(cmd->associd);
1610 		run_read(sc, RT2860_WCID_ATTR(wcid), &attr);
1611 		attr &= ~0xf;
1612 		run_write(sc, RT2860_WCID_ATTR(wcid), attr);
1613 	}
1614 }
1615 
1616 void
1617 run_calibrate_to(void *arg)
1618 {
1619 	/* do it in a process context */
1620 	run_do_async(arg, run_calibrate_cb, NULL, 0);
1621 	/* next timeout will be rescheduled in the calibration task */
1622 }
1623 
1624 /* ARGSUSED */
1625 void
1626 run_calibrate_cb(struct run_softc *sc, void *arg)
1627 {
1628 	struct ifnet *ifp = &sc->sc_ic.ic_if;
1629 	uint32_t sta[3];
1630 	int s, error;
1631 
1632 	/* read statistic counters (clear on read) and update AMRR state */
1633 	error = run_read_region_1(sc, RT2860_TX_STA_CNT0, (uint8_t *)sta,
1634 	    sizeof sta);
1635 	if (error != 0)
1636 		goto skip;
1637 
1638 	DPRINTF(("retrycnt=%d txcnt=%d failcnt=%d\n",
1639 	    letoh32(sta[1]) >> 16, letoh32(sta[1]) & 0xffff,
1640 	    letoh32(sta[0]) & 0xffff));
1641 
1642 	s = splnet();
1643 	/* count failed TX as errors */
1644 	ifp->if_oerrors += letoh32(sta[0]) & 0xffff;
1645 
1646 	sc->amn.amn_retrycnt =
1647 	    (letoh32(sta[0]) & 0xffff) +	/* failed TX count */
1648 	    (letoh32(sta[1]) >> 16);		/* TX retransmission count */
1649 
1650 	sc->amn.amn_txcnt =
1651 	    sc->amn.amn_retrycnt +
1652 	    (letoh32(sta[1]) & 0xffff);		/* successful TX count */
1653 
1654 	ieee80211_amrr_choose(&sc->amrr, sc->sc_ic.ic_bss, &sc->amn);
1655 	splx(s);
1656 
1657 skip:	timeout_add_sec(&sc->calib_to, 1);
1658 }
1659 
1660 void
1661 run_newassoc(struct ieee80211com *ic, struct ieee80211_node *ni, int isnew)
1662 {
1663 	struct run_softc *sc = ic->ic_softc;
1664 	struct run_node *rn = (void *)ni;
1665 	struct ieee80211_rateset *rs = &ni->ni_rates;
1666 	uint8_t rate;
1667 	int ridx, i, j;
1668 
1669 	DPRINTF(("new assoc isnew=%d addr=%s\n",
1670 	    isnew, ether_sprintf(ni->ni_macaddr)));
1671 
1672 	ieee80211_amrr_node_init(&sc->amrr, &sc->amn);
1673 	/* start at lowest available bit-rate, AMRR will raise */
1674 	ni->ni_txrate = 0;
1675 
1676 	for (i = 0; i < rs->rs_nrates; i++) {
1677 		rate = rs->rs_rates[i] & IEEE80211_RATE_VAL;
1678 		/* convert 802.11 rate to hardware rate index */
1679 		for (ridx = 0; ridx <= RT2860_RIDX_MAX; ridx++)
1680 			if (rt2860_rates[ridx].rate == rate)
1681 				break;
1682 		rn->ridx[i] = ridx;
1683 		/* determine rate of control response frames */
1684 		for (j = i; j >= 0; j--) {
1685 			if ((rs->rs_rates[j] & IEEE80211_RATE_BASIC) &&
1686 			    rt2860_rates[rn->ridx[i]].phy ==
1687 			    rt2860_rates[rn->ridx[j]].phy)
1688 				break;
1689 		}
1690 		if (j >= 0) {
1691 			rn->ctl_ridx[i] = rn->ridx[j];
1692 		} else {
1693 			/* no basic rate found, use mandatory one */
1694 			rn->ctl_ridx[i] = rt2860_rates[ridx].ctl_ridx;
1695 		}
1696 		DPRINTF(("rate=0x%02x ridx=%d ctl_ridx=%d\n",
1697 		    rs->rs_rates[i], rn->ridx[i], rn->ctl_ridx[i]));
1698 	}
1699 }
1700 
1701 /*
1702  * Return the Rx chain with the highest RSSI for a given frame.
1703  */
1704 static __inline uint8_t
1705 run_maxrssi_chain(struct run_softc *sc, const struct rt2860_rxwi *rxwi)
1706 {
1707 	uint8_t rxchain = 0;
1708 
1709 	if (sc->nrxchains > 1) {
1710 		if (rxwi->rssi[1] > rxwi->rssi[rxchain])
1711 			rxchain = 1;
1712 		if (sc->nrxchains > 2)
1713 			if (rxwi->rssi[2] > rxwi->rssi[rxchain])
1714 				rxchain = 2;
1715 	}
1716 	return rxchain;
1717 }
1718 
1719 void
1720 run_rx_frame(struct run_softc *sc, uint8_t *buf, int dmalen)
1721 {
1722 	struct ieee80211com *ic = &sc->sc_ic;
1723 	struct ifnet *ifp = &ic->ic_if;
1724 	struct ieee80211_frame *wh;
1725 	struct ieee80211_rxinfo rxi;
1726 	struct ieee80211_node *ni;
1727 	struct rt2870_rxd *rxd;
1728 	struct rt2860_rxwi *rxwi;
1729 	struct mbuf *m;
1730 	uint32_t flags;
1731 	uint16_t len, phy;
1732 	uint8_t ant, rssi;
1733 	int s;
1734 
1735 	rxwi = (struct rt2860_rxwi *)buf;
1736 	len = letoh16(rxwi->len) & 0xfff;
1737 	if (__predict_false(len > dmalen)) {
1738 		DPRINTF(("bad RXWI length %u > %u\n", len, dmalen));
1739 		return;
1740 	}
1741 	/* Rx descriptor is located at the end */
1742 	rxd = (struct rt2870_rxd *)(buf + dmalen);
1743 	flags = letoh32(rxd->flags);
1744 
1745 	if (__predict_false(flags & (RT2860_RX_CRCERR | RT2860_RX_ICVERR))) {
1746 		ifp->if_ierrors++;
1747 		return;
1748 	}
1749 
1750 	if (__predict_false((flags & RT2860_RX_MICERR))) {
1751 		/* report MIC failures to net80211 for TKIP */
1752 		ic->ic_stats.is_rx_locmicfail++;
1753 		ieee80211_michael_mic_failure(ic, 0/* XXX */);
1754 		ifp->if_ierrors++;
1755 		return;
1756 	}
1757 
1758 	wh = (struct ieee80211_frame *)(rxwi + 1);
1759 	rxi.rxi_flags = 0;
1760 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1761 		wh->i_fc[1] &= ~IEEE80211_FC1_PROTECTED;
1762 		rxi.rxi_flags |= IEEE80211_RXI_HWDEC;
1763 	}
1764 
1765 	if (rxd->flags & RT2860_RX_L2PAD) {
1766 		u_int hdrlen = ieee80211_get_hdrlen(wh);
1767 		ovbcopy(wh, (caddr_t)wh + 2, hdrlen);
1768 		wh = (struct ieee80211_frame *)((caddr_t)wh + 2);
1769 	}
1770 
1771 	/* could use m_devget buf net80211 wants contig mgmt frames */
1772 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1773 	if (__predict_false(m == NULL)) {
1774 		ifp->if_ierrors++;
1775 		return;
1776 	}
1777 	if (len > MHLEN) {
1778 		MCLGET(m, M_DONTWAIT);
1779 		if (__predict_false(!(m->m_flags & M_EXT))) {
1780 			ifp->if_ierrors++;
1781 			m_freem(m);
1782 			return;
1783 		}
1784 	}
1785 	/* finalize mbuf */
1786 	m->m_pkthdr.rcvif = ifp;
1787 	memcpy(mtod(m, caddr_t), wh, len);
1788 	m->m_pkthdr.len = m->m_len = len;
1789 
1790 	ant = run_maxrssi_chain(sc, rxwi);
1791 	rssi = rxwi->rssi[ant];
1792 
1793 #if NBPFILTER > 0
1794 	if (__predict_false(sc->sc_drvbpf != NULL)) {
1795 		struct run_rx_radiotap_header *tap = &sc->sc_rxtap;
1796 		struct mbuf mb;
1797 
1798 		tap->wr_flags = 0;
1799 		tap->wr_chan_freq = htole16(ic->ic_ibss_chan->ic_freq);
1800 		tap->wr_chan_flags = htole16(ic->ic_ibss_chan->ic_flags);
1801 		tap->wr_antsignal = rssi;
1802 		tap->wr_antenna = ant;
1803 		tap->wr_dbm_antsignal = run_rssi2dbm(sc, rssi, ant);
1804 		tap->wr_rate = 2;	/* in case it can't be found below */
1805 		phy = letoh16(rxwi->phy);
1806 		switch (phy & RT2860_PHY_MODE) {
1807 		case RT2860_PHY_CCK:
1808 			switch ((phy & RT2860_PHY_MCS) & ~RT2860_PHY_SHPRE) {
1809 			case 0:	tap->wr_rate =   2; break;
1810 			case 1:	tap->wr_rate =   4; break;
1811 			case 2:	tap->wr_rate =  11; break;
1812 			case 3:	tap->wr_rate =  22; break;
1813 			}
1814 			if (phy & RT2860_PHY_SHPRE)
1815 				tap->wr_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
1816 			break;
1817 		case RT2860_PHY_OFDM:
1818 			switch (phy & RT2860_PHY_MCS) {
1819 			case 0:	tap->wr_rate =  12; break;
1820 			case 1:	tap->wr_rate =  18; break;
1821 			case 2:	tap->wr_rate =  24; break;
1822 			case 3:	tap->wr_rate =  36; break;
1823 			case 4:	tap->wr_rate =  48; break;
1824 			case 5:	tap->wr_rate =  72; break;
1825 			case 6:	tap->wr_rate =  96; break;
1826 			case 7:	tap->wr_rate = 108; break;
1827 			}
1828 			break;
1829 		}
1830 		mb.m_data = (caddr_t)tap;
1831 		mb.m_len = sc->sc_rxtap_len;
1832 		mb.m_next = m;
1833 		mb.m_nextpkt = NULL;
1834 		mb.m_type = 0;
1835 		mb.m_flags = 0;
1836 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_IN);
1837 	}
1838 #endif
1839 
1840 	s = splnet();
1841 	ni = ieee80211_find_rxnode(ic, wh);
1842 	rxi.rxi_rssi = rssi;
1843 	rxi.rxi_tstamp = 0;	/* unused */
1844 	ieee80211_input(ifp, m, ni, &rxi);
1845 
1846 	/* node is no longer needed */
1847 	ieee80211_release_node(ic, ni);
1848 	splx(s);
1849 }
1850 
1851 void
1852 run_rxeof(usbd_xfer_handle xfer, usbd_private_handle priv, usbd_status status)
1853 {
1854 	struct run_rx_data *data = priv;
1855 	struct run_softc *sc = data->sc;
1856 	uint8_t *buf;
1857 	uint32_t dmalen;
1858 	int xferlen;
1859 
1860 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
1861 		DPRINTF(("RX status=%d\n", status));
1862 		if (status == USBD_STALLED)
1863 			usbd_clear_endpoint_stall_async(sc->rxq.pipeh);
1864 		if (status != USBD_CANCELLED)
1865 			goto skip;
1866 		return;
1867 	}
1868 	usbd_get_xfer_status(xfer, NULL, NULL, &xferlen, NULL);
1869 
1870 	if (__predict_false(xferlen < sizeof (uint32_t) +
1871 	    sizeof (struct rt2860_rxwi) + sizeof (struct rt2870_rxd))) {
1872 		DPRINTF(("xfer too short %d\n", xferlen));
1873 		goto skip;
1874 	}
1875 
1876 	/* HW can aggregate multiple 802.11 frames in a single USB xfer */
1877 	/* NB: can't happen yet because we disable USB RX aggregation */
1878 	buf = data->buf;
1879 	while (xferlen > 8) {
1880 		dmalen = letoh32(*(uint32_t *)buf) & 0xffff;
1881 
1882 		if (__predict_false(dmalen == 0 || (dmalen & 3) != 0)) {
1883 			DPRINTF(("bad DMA length %u (%x)\n", dmalen));
1884 			break;
1885 		}
1886 		if (__predict_false(dmalen + 8 > xferlen)) {
1887 			DPRINTF(("bad DMA length %u > %d\n",
1888 			    dmalen + 8, xferlen));
1889 			break;
1890 		}
1891 		run_rx_frame(sc, buf + sizeof (uint32_t), dmalen);
1892 		buf += dmalen + 8;
1893 		xferlen -= dmalen + 8;
1894 	}
1895 
1896 skip:	/* setup a new transfer */
1897 	usbd_setup_xfer(xfer, sc->rxq.pipeh, data, data->buf, RUN_MAX_RXSZ,
1898 	    USBD_SHORT_XFER_OK | USBD_NO_COPY, USBD_NO_TIMEOUT, run_rxeof);
1899 	(void)usbd_transfer(data->xfer);
1900 }
1901 
1902 void
1903 run_txeof(usbd_xfer_handle xfer, usbd_private_handle priv, usbd_status status)
1904 {
1905 	struct run_tx_data *data = priv;
1906 	struct run_softc *sc = data->sc;
1907 	struct run_tx_ring *txq = &sc->txq[data->qid];
1908 	struct ifnet *ifp = &sc->sc_ic.ic_if;
1909 	int s;
1910 
1911 	if (__predict_false(status != USBD_NORMAL_COMPLETION)) {
1912 		DPRINTF(("TX status=%d\n", status));
1913 		if (status == USBD_STALLED)
1914 			usbd_clear_endpoint_stall_async(txq->pipeh);
1915 		ifp->if_oerrors++;
1916 		return;
1917 	}
1918 
1919 	s = splnet();
1920 	sc->sc_tx_timer = 0;
1921 	ifp->if_opackets++;
1922 	if (--txq->queued < RUN_TX_RING_COUNT) {
1923 		sc->qfullmsk &= ~(1 << data->qid);
1924 		ifp->if_flags &= ~IFF_OACTIVE;
1925 		run_start(ifp);
1926 	}
1927 	splx(s);
1928 }
1929 
1930 int
1931 run_tx(struct run_softc *sc, struct mbuf *m, struct ieee80211_node *ni)
1932 {
1933 	struct ieee80211com *ic = &sc->sc_ic;
1934 	struct run_node *rn = (void *)ni;
1935 	struct ieee80211_frame *wh;
1936 	struct run_tx_ring *ring;
1937 	struct run_tx_data *data;
1938 	struct rt2870_txd *txd;
1939 	struct rt2860_txwi *txwi;
1940 	u_int hdrlen;
1941 	uint16_t qos, dur;
1942 	uint8_t type, mcs, tid, qid;
1943 	int error, hasqos, ridx, ctl_ridx, xferlen;
1944 
1945 	wh = mtod(m, struct ieee80211_frame *);
1946 	hdrlen = ieee80211_get_hdrlen(wh);
1947 	type = wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK;
1948 
1949 	if ((hasqos = ieee80211_has_qos(wh))) {
1950 		qos = ieee80211_get_qos(wh);
1951 		tid = qos & IEEE80211_QOS_TID;
1952 		qid = ieee80211_up_to_ac(ic, tid);
1953 	} else {
1954 		tid = 0;
1955 		qid = EDCA_AC_BE;
1956 	}
1957 	ring = &sc->txq[qid];
1958 	data = &ring->data[ring->cur];
1959 
1960 	/* pickup a rate index */
1961 	if (IEEE80211_IS_MULTICAST(wh->i_addr1) ||
1962 	    type != IEEE80211_FC0_TYPE_DATA) {
1963 		ridx = (ic->ic_curmode == IEEE80211_MODE_11A) ?
1964 		    RT2860_RIDX_OFDM6 : RT2860_RIDX_CCK1;
1965 		ctl_ridx = rt2860_rates[ridx].ctl_ridx;
1966 	} else if (ic->ic_fixed_rate != -1) {
1967 		ridx = sc->fixed_ridx;
1968 		ctl_ridx = rt2860_rates[ridx].ctl_ridx;
1969 	} else {
1970 		ridx = rn->ridx[ni->ni_txrate];
1971 		ctl_ridx = rn->ctl_ridx[ni->ni_txrate];
1972 	}
1973 
1974 	/* get MCS code from rate index */
1975 	mcs = rt2860_rates[ridx].mcs;
1976 
1977 	xferlen = sizeof (*txwi) + m->m_pkthdr.len;
1978 	/* roundup to 32-bit alignment */
1979 	xferlen = (xferlen + 3) & ~3;
1980 
1981 	txd = (struct rt2870_txd *)data->buf;
1982 	txd->flags = RT2860_TX_QSEL_EDCA;
1983 	txd->len = htole16(xferlen);
1984 
1985 	/* setup TX Wireless Information */
1986 	txwi = (struct rt2860_txwi *)(txd + 1);
1987 	txwi->flags = 0;
1988 	txwi->xflags = 0;
1989 	txwi->wcid = (type == IEEE80211_FC0_TYPE_DATA) ?
1990 	    RUN_AID2WCID(ni->ni_associd) : 0xff;
1991 	txwi->len = htole16(m->m_pkthdr.len);
1992 	if (rt2860_rates[ridx].phy == IEEE80211_T_DS) {
1993 		txwi->phy = htole16(RT2860_PHY_CCK);
1994 		if (ridx != RT2860_RIDX_CCK1 &&
1995 		    (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1996 			mcs |= RT2860_PHY_SHPRE;
1997 	} else
1998 		txwi->phy = htole16(RT2860_PHY_OFDM);
1999 	txwi->phy |= htole16(mcs);
2000 
2001 	txwi->txop = RT2860_TX_TXOP_BACKOFF;
2002 
2003 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
2004 	    (!hasqos || (qos & IEEE80211_QOS_ACK_POLICY_MASK) !=
2005 	     IEEE80211_QOS_ACK_POLICY_NOACK)) {
2006 		txwi->xflags |= RT2860_TX_ACK;
2007 		if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
2008 			dur = rt2860_rates[ctl_ridx].sp_ack_dur;
2009 		else
2010 			dur = rt2860_rates[ctl_ridx].lp_ack_dur;
2011 		*(uint16_t *)wh->i_dur = htole16(dur + sc->sifs);
2012 	}
2013 
2014 #if NBPFILTER > 0
2015 	if (__predict_false(sc->sc_drvbpf != NULL)) {
2016 		struct run_tx_radiotap_header *tap = &sc->sc_txtap;
2017 		struct mbuf mb;
2018 
2019 		tap->wt_flags = 0;
2020 		tap->wt_rate = rt2860_rates[ridx].rate;
2021 		tap->wt_chan_freq = htole16(ic->ic_bss->ni_chan->ic_freq);
2022 		tap->wt_chan_flags = htole16(ic->ic_bss->ni_chan->ic_flags);
2023 		tap->wt_hwqueue = qid;
2024 		if (mcs & RT2860_PHY_SHPRE)
2025 			tap->wt_flags |= IEEE80211_RADIOTAP_F_SHORTPRE;
2026 
2027 		mb.m_data = (caddr_t)tap;
2028 		mb.m_len = sc->sc_txtap_len;
2029 		mb.m_next = m;
2030 		mb.m_nextpkt = NULL;
2031 		mb.m_type = 0;
2032 		mb.m_flags = 0;
2033 		bpf_mtap(sc->sc_drvbpf, &mb, BPF_DIRECTION_OUT);
2034 	}
2035 #endif
2036 
2037 	m_copydata(m, 0, m->m_pkthdr.len, (caddr_t)(txwi + 1));
2038 	m_freem(m);
2039 	ieee80211_release_node(ic, ni);
2040 
2041 	xferlen += sizeof (*txd) + 4;
2042 
2043 	usbd_setup_xfer(data->xfer, ring->pipeh, data, data->buf, xferlen,
2044 	    USBD_FORCE_SHORT_XFER | USBD_NO_COPY, RUN_TX_TIMEOUT, run_txeof);
2045 	error = usbd_transfer(data->xfer);
2046 	if (__predict_false(error != USBD_IN_PROGRESS && error != 0))
2047 		return error;
2048 
2049 	ring->cur = (ring->cur + 1) % RUN_TX_RING_COUNT;
2050 	if (++ring->queued >= RUN_TX_RING_COUNT)
2051 		sc->qfullmsk |= 1 << qid;
2052 
2053 	return 0;
2054 }
2055 
2056 void
2057 run_start(struct ifnet *ifp)
2058 {
2059 	struct run_softc *sc = ifp->if_softc;
2060 	struct ieee80211com *ic = &sc->sc_ic;
2061 	struct ieee80211_node *ni;
2062 	struct mbuf *m;
2063 
2064 	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
2065 		return;
2066 
2067 	for (;;) {
2068 		if (sc->qfullmsk != 0) {
2069 			ifp->if_flags |= IFF_OACTIVE;
2070 			break;
2071 		}
2072 		/* send pending management frames first */
2073 		IF_DEQUEUE(&ic->ic_mgtq, m);
2074 		if (m != NULL) {
2075 			ni = (void *)m->m_pkthdr.rcvif;
2076 			goto sendit;
2077 		}
2078 		if (ic->ic_state != IEEE80211_S_RUN)
2079 			break;
2080 
2081 		/* encapsulate and send data frames */
2082 		IFQ_DEQUEUE(&ifp->if_snd, m);
2083 		if (m == NULL)
2084 			break;
2085 #if NBPFILTER > 0
2086 		if (ifp->if_bpf != NULL)
2087 			bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
2088 #endif
2089 		if ((m = ieee80211_encap(ifp, m, &ni)) == NULL)
2090 			continue;
2091 sendit:
2092 #if NBPFILTER > 0
2093 		if (ic->ic_rawbpf != NULL)
2094 			bpf_mtap(ic->ic_rawbpf, m, BPF_DIRECTION_OUT);
2095 #endif
2096 		if (run_tx(sc, m, ni) != 0) {
2097 			ieee80211_release_node(ic, ni);
2098 			ifp->if_oerrors++;
2099 			continue;
2100 		}
2101 
2102 		sc->sc_tx_timer = 5;
2103 		ifp->if_timer = 1;
2104 	}
2105 }
2106 
2107 void
2108 run_watchdog(struct ifnet *ifp)
2109 {
2110 	struct run_softc *sc = ifp->if_softc;
2111 
2112 	ifp->if_timer = 0;
2113 
2114 	if (sc->sc_tx_timer > 0) {
2115 		if (--sc->sc_tx_timer == 0) {
2116 			printf("%s: device timeout\n", sc->sc_dev.dv_xname);
2117 			/* run_init(ifp); XXX needs a process context! */
2118 			ifp->if_oerrors++;
2119 			return;
2120 		}
2121 		ifp->if_timer = 1;
2122 	}
2123 
2124 	ieee80211_watchdog(ifp);
2125 }
2126 
2127 int
2128 run_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
2129 {
2130 	struct run_softc *sc = ifp->if_softc;
2131 	struct ieee80211com *ic = &sc->sc_ic;
2132 	struct ifaddr *ifa;
2133 	struct ifreq *ifr;
2134 	int s, error = 0;
2135 
2136 	s = splnet();
2137 
2138 	switch (cmd) {
2139 	case SIOCSIFADDR:
2140 		ifa = (struct ifaddr *)data;
2141 		ifp->if_flags |= IFF_UP;
2142 #ifdef INET
2143 		if (ifa->ifa_addr->sa_family == AF_INET)
2144 			arp_ifinit(&ic->ic_ac, ifa);
2145 #endif
2146 		/* FALLTHROUGH */
2147 	case SIOCSIFFLAGS:
2148 		if (ifp->if_flags & IFF_UP) {
2149 			if (!(ifp->if_flags & IFF_RUNNING))
2150 				run_init(ifp);
2151 		} else {
2152 			if (ifp->if_flags & IFF_RUNNING)
2153 				run_stop(ifp, 1);
2154 		}
2155 		break;
2156 
2157 	case SIOCADDMULTI:
2158 	case SIOCDELMULTI:
2159 		ifr = (struct ifreq *)data;
2160 		error = (cmd == SIOCADDMULTI) ?
2161 		    ether_addmulti(ifr, &ic->ic_ac) :
2162 		    ether_delmulti(ifr, &ic->ic_ac);
2163 
2164 		if (error == ENETRESET)
2165 			error = 0;
2166 		break;
2167 
2168 	case SIOCS80211CHANNEL:
2169 		/*
2170 		 * This allows for fast channel switching in monitor mode
2171 		 * (used by kismet). In IBSS mode, we must explicitly reset
2172 		 * the interface to generate a new beacon frame.
2173 		 */
2174 		error = ieee80211_ioctl(ifp, cmd, data);
2175 		if (error == ENETRESET &&
2176 		    ic->ic_opmode == IEEE80211_M_MONITOR) {
2177 			if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
2178 			    (IFF_UP | IFF_RUNNING))
2179 				run_set_chan(sc, ic->ic_ibss_chan);
2180 			error = 0;
2181 		}
2182 		break;
2183 
2184 	default:
2185 		error = ieee80211_ioctl(ifp, cmd, data);
2186 	}
2187 
2188 	if (error == ENETRESET) {
2189 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
2190 		    (IFF_UP | IFF_RUNNING))
2191 			run_init(ifp);
2192 		error = 0;
2193 	}
2194 
2195 	splx(s);
2196 
2197 	return error;
2198 }
2199 
2200 void
2201 run_select_chan_group(struct run_softc *sc, int group)
2202 {
2203 	uint32_t tmp;
2204 
2205 	run_bbp_write(sc, 62, 0x37 - sc->lna[group]);
2206 	run_bbp_write(sc, 63, 0x37 - sc->lna[group]);
2207 	run_bbp_write(sc, 64, 0x37 - sc->lna[group]);
2208 	run_bbp_write(sc, 86, 0x00);
2209 
2210 	if (group == 0) {
2211 		if (sc->ext_2ghz_lna) {
2212 			run_bbp_write(sc, 82, 0x62);
2213 			run_bbp_write(sc, 75, 0x46);
2214 		} else {
2215 			run_bbp_write(sc, 82, 0x84);
2216 			run_bbp_write(sc, 75, 0x50);
2217 		}
2218 	} else {
2219 		if (sc->ext_5ghz_lna) {
2220 			run_bbp_write(sc, 82, 0xf2);
2221 			run_bbp_write(sc, 75, 0x46);
2222 		} else {
2223 			run_bbp_write(sc, 82, 0xf2);
2224 			run_bbp_write(sc, 75, 0x50);
2225 		}
2226 	}
2227 
2228 	run_read(sc, RT2860_TX_BAND_CFG, &tmp);
2229 	tmp &= ~(RT2860_5G_BAND_SEL_N | RT2860_5G_BAND_SEL_P);
2230 	tmp |= (group == 0) ? RT2860_5G_BAND_SEL_N : RT2860_5G_BAND_SEL_P;
2231 	run_write(sc, RT2860_TX_BAND_CFG, tmp);
2232 
2233 	/* enable appropriate Power Amplifiers and Low Noise Amplifiers */
2234 	tmp = RT2860_RFTR_EN | RT2860_TRSW_EN;
2235 	if (group == 0) {	/* 2GHz */
2236 		tmp |= RT2860_PA_PE_G0_EN | RT2860_LNA_PE_G0_EN;
2237 		if (sc->ntxchains > 1)
2238 			tmp |= RT2860_PA_PE_G1_EN;
2239 		if (sc->nrxchains > 1)
2240 			tmp |= RT2860_LNA_PE_G1_EN;
2241 	} else {		/* 5GHz */
2242 		tmp |= RT2860_PA_PE_A0_EN | RT2860_LNA_PE_A0_EN;
2243 		if (sc->ntxchains > 1)
2244 			tmp |= RT2860_PA_PE_A1_EN;
2245 		if (sc->nrxchains > 1)
2246 			tmp |= RT2860_LNA_PE_A1_EN;
2247 	}
2248 	run_write(sc, RT2860_TX_PIN_CFG, tmp);
2249 
2250 	/* set initial AGC value */
2251 	if (group == 0)
2252 		run_bbp_write(sc, 66, 0x2e + sc->lna[0]);
2253 	else
2254 		run_bbp_write(sc, 66, 0x32 + (sc->lna[group] * 5) / 3);
2255 }
2256 
2257 void
2258 run_rt2870_set_chan(struct run_softc *sc, u_int chan)
2259 {
2260 	const struct rfprog *rfprog = rt2860_rf2850;
2261 	uint32_t r2, r3, r4;
2262 	int8_t txpow1, txpow2;
2263 	int i;
2264 
2265 	/* find the settings for this channel (we know it exists) */
2266 	for (i = 0; rfprog[i].chan != chan; i++);
2267 
2268 	r2 = rfprog[i].r2;
2269 	if (sc->ntxchains == 1)
2270 		r2 |= 1 << 12;		/* 1T: disable Tx chain 2 */
2271 	if (sc->nrxchains == 1)
2272 		r2 |= 1 << 15 | 1 << 4;	/* 1R: disable Rx chains 2 & 3 */
2273 	else if (sc->nrxchains == 2)
2274 		r2 |= 1 << 4;		/* 2R: disable Rx chain 3 */
2275 
2276 	/* use Tx power values from EEPROM */
2277 	txpow1 = sc->txpow1[i];
2278 	txpow2 = sc->txpow2[i];
2279 	if (chan > 14) {
2280 		if (txpow1 >= 0)
2281 			txpow1 = txpow1 << 1;
2282 		else
2283 			txpow1 = (7 + txpow1) << 1 | 1;
2284 		if (txpow2 >= 0)
2285 			txpow2 = txpow2 << 1;
2286 		else
2287 			txpow2 = (7 + txpow2) << 1 | 1;
2288 	}
2289 	r3 = rfprog[i].r3 | txpow1 << 7;
2290 	r4 = rfprog[i].r4 | sc->freq << 13 | txpow2 << 4;
2291 
2292 	run_rt2870_rf_write(sc, RT2860_RF1, rfprog[i].r1);
2293 	run_rt2870_rf_write(sc, RT2860_RF2, r2);
2294 	run_rt2870_rf_write(sc, RT2860_RF3, r3);
2295 	run_rt2870_rf_write(sc, RT2860_RF4, r4);
2296 
2297 	DELAY(200);
2298 
2299 	run_rt2870_rf_write(sc, RT2860_RF1, rfprog[i].r1);
2300 	run_rt2870_rf_write(sc, RT2860_RF2, r2);
2301 	run_rt2870_rf_write(sc, RT2860_RF3, r3 | 1);
2302 	run_rt2870_rf_write(sc, RT2860_RF4, r4);
2303 
2304 	DELAY(200);
2305 
2306 	run_rt2870_rf_write(sc, RT2860_RF1, rfprog[i].r1);
2307 	run_rt2870_rf_write(sc, RT2860_RF2, r2);
2308 	run_rt2870_rf_write(sc, RT2860_RF3, r3);
2309 	run_rt2870_rf_write(sc, RT2860_RF4, r4);
2310 }
2311 
2312 void
2313 run_rt3070_set_chan(struct run_softc *sc, u_int chan)
2314 {
2315 	int8_t txpow1, txpow2;
2316 	uint8_t rf;
2317 
2318 	KASSERT(chan >= 1 && chan <= 14);	/* RT3070 is 2GHz only */
2319 
2320 	/* use Tx power values from EEPROM */
2321 	txpow1 = sc->txpow1[chan - 1];
2322 	txpow2 = sc->txpow2[chan - 1];
2323 
2324 	run_rt3070_rf_write(sc, 2, run_rf3020_freqs[chan - 1].n);
2325 	run_rt3070_rf_write(sc, 3, run_rf3020_freqs[chan - 1].k);
2326 	run_rt3070_rf_read(sc, 6, &rf);
2327 	rf = (rf & ~0x03) | run_rf3020_freqs[chan - 1].r;
2328 	run_rt3070_rf_write(sc, 6, rf);
2329 
2330 	/* set Tx0 power */
2331 	run_rt3070_rf_read(sc, 12, &rf);
2332 	rf = (rf & ~0x1f) | txpow1;
2333 	run_rt3070_rf_write(sc, 12, rf);
2334 
2335 	/* set Tx1 power */
2336 	run_rt3070_rf_read(sc, 13, &rf);
2337 	rf = (rf & ~0x1f) | txpow2;
2338 	run_rt3070_rf_write(sc, 13, rf);
2339 
2340 	run_rt3070_rf_read(sc, 1, &rf);
2341 	rf &= ~0xfc;
2342 	if (sc->ntxchains == 1)
2343 		rf |= 1 << 7 | 1 << 5;	/* 1T: disable Tx chains 2 & 3 */
2344 	else if (sc->ntxchains == 2)
2345 		rf |= 1 << 7;		/* 2T: disable Tx chain 3 */
2346 	if (sc->nrxchains == 1)
2347 		rf |= 1 << 6 | 1 << 4;	/* 1R: disable Rx chains 2 & 3 */
2348 	else if (sc->nrxchains == 2)
2349 		rf |= 1 << 6;		/* 2R: disable Rx chain 3 */
2350 	run_rt3070_rf_write(sc, 1, rf);
2351 
2352 	/* set RF offset */
2353 	run_rt3070_rf_read(sc, 23, &rf);
2354 	rf = (rf & ~0x7f) | sc->freq;
2355 	run_rt3070_rf_write(sc, 23, rf);
2356 
2357 	/* program RF filter */
2358 	run_rt3070_rf_write(sc, 24, sc->rf24_20mhz);
2359 	run_rt3070_rf_write(sc, 31, sc->rf24_20mhz);
2360 
2361 	/* enable RF tuning */
2362 	run_rt3070_rf_read(sc, 7, &rf);
2363 	run_rt3070_rf_write(sc, 7, rf | 0x01);
2364 }
2365 
2366 void
2367 run_set_rx_antenna(struct run_softc *sc, int aux)
2368 {
2369 	uint32_t tmp;
2370 
2371 	if (aux) {
2372 		run_read(sc, RT2860_PCI_EECTRL, &tmp);
2373 		run_write(sc, RT2860_PCI_EECTRL, tmp & ~RT2860_C);
2374 		run_read(sc, RT2860_GPIO_CTRL, &tmp);
2375 		run_write(sc, RT2860_GPIO_CTRL, (tmp & ~0x0808) | 0x08);
2376 	} else {
2377 		run_read(sc, RT2860_PCI_EECTRL, &tmp);
2378 		run_write(sc, RT2860_PCI_EECTRL, tmp | RT2860_C);
2379 		run_read(sc, RT2860_GPIO_CTRL, &tmp);
2380 		run_write(sc, RT2860_GPIO_CTRL, tmp & ~0x0808);
2381 	}
2382 }
2383 
2384 int
2385 run_set_chan(struct run_softc *sc, struct ieee80211_channel *c)
2386 {
2387 	struct ieee80211com *ic = &sc->sc_ic;
2388 	u_int chan, group;
2389 
2390 	chan = ieee80211_chan2ieee(ic, c);
2391 	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
2392 		return EINVAL;
2393 
2394 	if ((sc->mac_rev >> 16) >= 0x3070)
2395 		run_rt3070_set_chan(sc, chan);
2396 	else
2397 		run_rt2870_set_chan(sc, chan);
2398 
2399 	/* 802.11a uses a 16 microseconds short interframe space */
2400 	sc->sifs = IEEE80211_IS_CHAN_5GHZ(c) ? 16 : 10;
2401 
2402 	/* determine channel group */
2403 	if (chan <= 14)
2404 		group = 0;
2405 	else if (chan <= 64)
2406 		group = 1;
2407 	else if (chan <= 128)
2408 		group = 2;
2409 	else
2410 		group = 3;
2411 
2412 	/* XXX necessary only when group has changed! */
2413 	run_select_chan_group(sc, group);
2414 
2415 	DELAY(1000);
2416 	return 0;
2417 }
2418 
2419 void
2420 run_enable_tsf_sync(struct run_softc *sc)
2421 {
2422 	struct ieee80211com *ic = &sc->sc_ic;
2423 	uint32_t tmp;
2424 
2425 	run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
2426 	tmp &= ~0x1fffff;
2427 	tmp |= ic->ic_bss->ni_intval * 16;
2428 	tmp |= RT2860_TSF_TIMER_EN | RT2860_TBTT_TIMER_EN;
2429 	/* local TSF is always updated with remote TSF on beacon reception */
2430 	tmp |= 1 << RT2860_TSF_SYNC_MODE_SHIFT;
2431 	run_write(sc, RT2860_BCN_TIME_CFG, tmp);
2432 }
2433 
2434 void
2435 run_enable_mrr(struct run_softc *sc)
2436 {
2437 #define CCK(mcs)	(mcs)
2438 #define OFDM(mcs)	(1 << 3 | (mcs))
2439 	run_write(sc, RT2860_LG_FBK_CFG0,
2440 	    OFDM(6) << 28 |	/* 54->48 */
2441 	    OFDM(5) << 24 |	/* 48->36 */
2442 	    OFDM(4) << 20 |	/* 36->24 */
2443 	    OFDM(3) << 16 |	/* 24->18 */
2444 	    OFDM(2) << 12 |	/* 18->12 */
2445 	    OFDM(1) <<  8 |	/* 12-> 9 */
2446 	    OFDM(0) <<  4 |	/*  9-> 6 */
2447 	    OFDM(0));		/*  6-> 6 */
2448 
2449 	run_write(sc, RT2860_LG_FBK_CFG1,
2450 	    CCK(2) << 12 |	/* 11->5.5 */
2451 	    CCK(1) <<  8 |	/* 5.5-> 2 */
2452 	    CCK(0) <<  4 |	/*   2-> 1 */
2453 	    CCK(0));		/*   1-> 1 */
2454 #undef OFDM
2455 #undef CCK
2456 }
2457 
2458 void
2459 run_set_txpreamble(struct run_softc *sc)
2460 {
2461 	uint32_t tmp;
2462 
2463 	run_read(sc, RT2860_AUTO_RSP_CFG, &tmp);
2464 	if (sc->sc_ic.ic_flags & IEEE80211_F_SHPREAMBLE)
2465 		tmp |= RT2860_CCK_SHORT_EN;
2466 	else
2467 		tmp &= ~RT2860_CCK_SHORT_EN;
2468 	run_write(sc, RT2860_AUTO_RSP_CFG, tmp);
2469 }
2470 
2471 void
2472 run_set_basicrates(struct run_softc *sc)
2473 {
2474 	struct ieee80211com *ic = &sc->sc_ic;
2475 
2476 	/* set basic rates mask */
2477 	if (ic->ic_curmode == IEEE80211_MODE_11B)
2478 		run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x003);
2479 	else if (ic->ic_curmode == IEEE80211_MODE_11A)
2480 		run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x150);
2481 	else	/* 11g */
2482 		run_write(sc, RT2860_LEGACY_BASIC_RATE, 0x15f);
2483 }
2484 
2485 void
2486 run_set_leds(struct run_softc *sc, uint16_t which)
2487 {
2488 	(void)run_mcu_cmd(sc, RT2860_MCU_CMD_LEDS,
2489 	    which | (sc->leds & 0x7f));
2490 }
2491 
2492 void
2493 run_set_bssid(struct run_softc *sc, const uint8_t *bssid)
2494 {
2495 	run_write(sc, RT2860_MAC_BSSID_DW0,
2496 	    bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24);
2497 	run_write(sc, RT2860_MAC_BSSID_DW1,
2498 	    bssid[4] | bssid[5] << 8);
2499 }
2500 
2501 void
2502 run_set_macaddr(struct run_softc *sc, const uint8_t *addr)
2503 {
2504 	run_write(sc, RT2860_MAC_ADDR_DW0,
2505 	    addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24);
2506 	run_write(sc, RT2860_MAC_ADDR_DW1,
2507 	    addr[4] | addr[5] << 8);
2508 }
2509 
2510 void
2511 run_updateslot(struct ieee80211com *ic)
2512 {
2513 	/* do it in a process context */
2514 	run_do_async(ic->ic_softc, run_updateslot_cb, NULL, 0);
2515 }
2516 
2517 /* ARGSUSED */
2518 void
2519 run_updateslot_cb(struct run_softc *sc, void *arg)
2520 {
2521 	uint32_t tmp;
2522 
2523 	run_read(sc, RT2860_BKOFF_SLOT_CFG, &tmp);
2524 	tmp &= ~0xff;
2525 	tmp |= (sc->sc_ic.ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
2526 	run_write(sc, RT2860_BKOFF_SLOT_CFG, tmp);
2527 }
2528 
2529 #if NBPFILTER > 0
2530 int8_t
2531 run_rssi2dbm(struct run_softc *sc, uint8_t rssi, uint8_t rxchain)
2532 {
2533 	struct ieee80211com *ic = &sc->sc_ic;
2534 	struct ieee80211_channel *c = ic->ic_ibss_chan;
2535 	int delta;
2536 
2537 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
2538 		u_int chan = ieee80211_chan2ieee(ic, c);
2539 		delta = sc->rssi_5ghz[rxchain];
2540 
2541 		/* determine channel group */
2542 		if (chan <= 64)
2543 			delta -= sc->lna[1];
2544 		else if (chan <= 128)
2545 			delta -= sc->lna[2];
2546 		else
2547 			delta -= sc->lna[3];
2548 	} else
2549 		delta = sc->rssi_2ghz[rxchain] - sc->lna[0];
2550 
2551 	return -12 - delta - rssi;
2552 }
2553 #endif
2554 
2555 int
2556 run_bbp_init(struct run_softc *sc)
2557 {
2558 	int i, error, ntries;
2559 	uint8_t bbp0;
2560 
2561 	/* wait for BBP to wake up */
2562 	for (ntries = 0; ntries < 20; ntries++) {
2563 		if ((error = run_bbp_read(sc, 0, &bbp0)) != 0)
2564 			return error;
2565 		if (bbp0 != 0 && bbp0 != 0xff)
2566 			break;
2567 	}
2568 	if (ntries == 20)
2569 		return ETIMEDOUT;
2570 
2571 	/* initialize BBP registers to default values */
2572 	for (i = 0; i < nitems(rt2860_def_bbp); i++) {
2573 		run_bbp_write(sc, rt2860_def_bbp[i].reg,
2574 		    rt2860_def_bbp[i].val);
2575 	}
2576 
2577 	/* fix BBP84 for RT2860E */
2578 	if ((sc->mac_rev >> 16) == 0x2860 && (sc->mac_rev & 0xffff) != 0x0101)
2579 		run_bbp_write(sc,  84, 0x19);
2580 
2581 	if ((sc->mac_rev >> 16) >= 0x3070) {
2582 		run_bbp_write(sc, 79, 0x13);
2583 		run_bbp_write(sc, 80, 0x05);
2584 		run_bbp_write(sc, 81, 0x33);
2585 		/* XXX RT3090 needs more */
2586 	} else if (sc->mac_rev == 0x28600100) {
2587 		run_bbp_write(sc, 69, 0x16);
2588 		run_bbp_write(sc, 73, 0x12);
2589 	}
2590 	return 0;
2591 }
2592 
2593 int
2594 run_rt3070_rf_init(struct run_softc *sc)
2595 {
2596 	uint32_t tmp;
2597 	uint8_t rf, bbp4;
2598 	int i;
2599 
2600 	run_rt3070_rf_read(sc, 30, &rf);
2601 	/* toggle RF R30 bit 7 */
2602 	run_rt3070_rf_write(sc, 30, rf | 0x80);
2603 	DELAY(1000);
2604 	run_rt3070_rf_write(sc, 30, rf & ~0x80);
2605 
2606 	/* initialize RF registers to default value */
2607 	for (i = 0; i < nitems(rt3070_def_rf); i++) {
2608 		run_rt3070_rf_write(sc, rt3070_def_rf[i].reg,
2609 		    rt3070_def_rf[i].val);
2610 	}
2611 	if ((sc->mac_rev >> 16) == 0x3070) {
2612 		/* change voltage from 1.2V to 1.35V for RT3070 */
2613 		run_read(sc, RT3070_LDO_CFG0, &tmp);
2614 		tmp = (tmp & ~0x0f000000) | 0x0d000000;
2615 		run_write(sc, RT3070_LDO_CFG0, tmp);
2616 
2617 	} else if ((sc->mac_rev >> 16) == 0x3071) {
2618 		run_rt3070_rf_read(sc, 6, &rf);
2619 		run_rt3070_rf_write(sc, 6, rf | 0x40);
2620 		run_rt3070_rf_write(sc, 31, 0x14);
2621 
2622 		run_read(sc, RT3070_LDO_CFG0, &tmp);
2623 		tmp &= ~0x1f000000;
2624 		if ((sc->mac_rev & 0xffff) < 0x0211)
2625 			tmp |= 0x0d000000;
2626 		else
2627 			tmp |= 0x01000000;
2628 		run_write(sc, RT3070_LDO_CFG0, tmp);
2629 
2630 		/* patch LNA_PE_G1 */
2631 		run_read(sc, RT3070_GPIO_SWITCH, &tmp);
2632 		run_write(sc, RT3070_GPIO_SWITCH, tmp & ~0x20);
2633 	}
2634 
2635 	/* select 20MHz bandwidth */
2636 	run_rt3070_rf_read(sc, 31, &rf);
2637 	run_rt3070_rf_write(sc, 31, rf & ~0x20);
2638 
2639 	/* calibrate filter for 20MHz bandwidth */
2640 	sc->rf24_20mhz = 0x1f;	/* default value */
2641 	run_rt3070_filter_calib(sc, 0x07, 0x16, &sc->rf24_20mhz);
2642 
2643 	/* select 40MHz bandwidth */
2644 	run_bbp_read(sc, 4, &bbp4);
2645 	run_bbp_write(sc, 4, (bbp4 & ~0x08) | 0x10);
2646 
2647 	/* calibrate filter for 40MHz bandwidth */
2648 	sc->rf24_40mhz = 0x2f;	/* default value */
2649 	run_rt3070_filter_calib(sc, 0x27, 0x19, &sc->rf24_40mhz);
2650 
2651 	/* go back to 20MHz bandwidth */
2652 	run_bbp_read(sc, 4, &bbp4);
2653 	run_bbp_write(sc, 4, bbp4 & ~0x18);
2654 
2655 	if ((sc->mac_rev & 0xffff) < 0x0211)
2656 		run_rt3070_rf_write(sc, 27, 0x03);
2657 
2658 	run_read(sc, RT3070_OPT_14, &tmp);
2659 	run_write(sc, RT3070_OPT_14, tmp | 1);
2660 
2661 	if ((sc->mac_rev >> 16) == 0x3071) {
2662 		run_rt3070_rf_read(sc, 1, &rf);
2663 		rf &= ~(RT3070_RX0_PD | RT3070_TX0_PD);
2664 		rf |= RT3070_RF_BLOCK | RT3070_RX1_PD | RT3070_TX1_PD;
2665 		run_rt3070_rf_write(sc, 1, rf);
2666 
2667 		run_rt3070_rf_read(sc, 15, &rf);
2668 		run_rt3070_rf_write(sc, 15, rf & ~RT3070_TX_LO2);
2669 
2670 		run_rt3070_rf_read(sc, 17, &rf);
2671 		rf &= ~RT3070_TX_LO1;
2672 		if ((sc->mac_rev & 0xffff) >= 0x0211 && !sc->ext_2ghz_lna)
2673 			rf |= 0x20;	/* fix for long range Rx issue */
2674 		run_rt3070_rf_write(sc, 17, rf);
2675 
2676 		run_rt3070_rf_read(sc, 20, &rf);
2677 		run_rt3070_rf_write(sc, 20, rf & ~RT3070_RX_LO1);
2678 
2679 		run_rt3070_rf_read(sc, 21, &rf);
2680 		run_rt3070_rf_write(sc, 21, rf & ~RT3070_RX_LO2);
2681 
2682 		run_rt3070_rf_read(sc, 27, &rf);
2683 		rf &= ~0x77;
2684 		if ((sc->mac_rev & 0xffff) < 0x0211)
2685 			rf |= 0x03;
2686 		run_rt3070_rf_write(sc, 27, rf);
2687 	}
2688 	return 0;
2689 }
2690 
2691 int
2692 run_rt3070_filter_calib(struct run_softc *sc, uint8_t init, uint8_t target,
2693     uint8_t *val)
2694 {
2695 	uint8_t rf22, rf24;
2696 	uint8_t bbp55_pb, bbp55_sb, delta;
2697 	int ntries;
2698 
2699 	/* program filter */
2700 	rf24 = init;	/* initial filter value */
2701 	run_rt3070_rf_write(sc, 24, rf24);
2702 
2703 	/* enable baseband loopback mode */
2704 	run_rt3070_rf_read(sc, 22, &rf22);
2705 	run_rt3070_rf_write(sc, 22, rf22 | 0x01);
2706 
2707 	/* set power and frequency of passband test tone */
2708 	run_bbp_write(sc, 24, 0x00);
2709 	for (ntries = 0; ntries < 100; ntries++) {
2710 		/* transmit test tone */
2711 		run_bbp_write(sc, 25, 0x90);
2712 		DELAY(1000);
2713 		/* read received power */
2714 		run_bbp_read(sc, 55, &bbp55_pb);
2715 		if (bbp55_pb != 0)
2716 			break;
2717 	}
2718 	if (ntries == 100)
2719 		return ETIMEDOUT;
2720 
2721 	/* set power and frequency of stopband test tone */
2722 	run_bbp_write(sc, 24, 0x06);
2723 	for (ntries = 0; ntries < 100; ntries++) {
2724 		/* transmit test tone */
2725 		run_bbp_write(sc, 25, 0x90);
2726 		DELAY(1000);
2727 		/* read received power */
2728 		run_bbp_read(sc, 55, &bbp55_sb);
2729 
2730 		delta = bbp55_pb - bbp55_sb;
2731 		if (delta > target)
2732 			break;
2733 
2734 		/* reprogram filter */
2735 		rf24++;
2736 		run_rt3070_rf_write(sc, 24, rf24);
2737 	}
2738 	if (ntries < 100) {
2739 		if (rf24 != init)
2740 			rf24--;	/* backtrack */
2741 		*val = rf24;
2742 		run_rt3070_rf_write(sc, 24, rf24);
2743 	}
2744 
2745 	/* restore initial state */
2746 	run_bbp_write(sc, 24, 0x00);
2747 
2748 	/* disable baseband loopback mode */
2749 	run_rt3070_rf_read(sc, 22, &rf22);
2750 	run_rt3070_rf_write(sc, 22, rf22 & ~0x01);
2751 
2752 	return 0;
2753 }
2754 
2755 int
2756 run_txrx_enable(struct run_softc *sc)
2757 {
2758 	uint32_t tmp;
2759 	int error, ntries;
2760 
2761 	run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_MAC_TX_EN);
2762 	for (ntries = 0; ntries < 200; ntries++) {
2763 		if ((error = run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp)) != 0)
2764 			return error;
2765 		if ((tmp & (RT2860_TX_DMA_BUSY | RT2860_RX_DMA_BUSY)) == 0)
2766 			break;
2767 		DELAY(1000);
2768 	}
2769 	if (ntries == 200)
2770 		return ETIMEDOUT;
2771 
2772 	DELAY(50);
2773 
2774 	tmp |= RT2860_RX_DMA_EN | RT2860_TX_DMA_EN | RT2860_TX_WB_DDONE;
2775 	run_write(sc, RT2860_WPDMA_GLO_CFG, tmp);
2776 
2777 	tmp = RT2860_USB_TX_EN | RT2860_USB_RX_EN;
2778 #ifdef notyet
2779 	/* enable bulk aggregation */
2780 	tmp |= RT2860_USB_RX_AGG_EN | 0x80 << RT2860_USB_RX_AGG_TO_SHIFT |
2781 	    ((RUN_MAX_RXSZ / 1024) - 3) << RT2860_USB_RX_AGG_LMT_SHIFT;
2782 #endif
2783 	run_write(sc, RT2860_USB_DMA_CFG, tmp);
2784 
2785 	/* set Rx filter */
2786 	tmp = RT2860_DROP_CRC_ERR | RT2860_DROP_PHY_ERR;
2787 	if (sc->sc_ic.ic_opmode != IEEE80211_M_MONITOR) {
2788 		tmp |= RT2860_DROP_UC_NOME | RT2860_DROP_DUPL |
2789 		    RT2860_DROP_CTS | RT2860_DROP_BA | RT2860_DROP_ACK |
2790 		    RT2860_DROP_VER_ERR | RT2860_DROP_CTRL_RSV |
2791 		    RT2860_DROP_CFACK | RT2860_DROP_CFEND;
2792 		if (sc->sc_ic.ic_opmode == IEEE80211_M_STA)
2793 			tmp |= RT2860_DROP_RTS | RT2860_DROP_PSPOLL;
2794 	}
2795 	run_write(sc, RT2860_RX_FILTR_CFG, tmp);
2796 
2797 	run_write(sc, RT2860_MAC_SYS_CTRL,
2798 	    RT2860_MAC_RX_EN | RT2860_MAC_TX_EN);
2799 
2800 	return 0;
2801 }
2802 
2803 int
2804 run_init(struct ifnet *ifp)
2805 {
2806 	struct run_softc *sc = ifp->if_softc;
2807 	struct ieee80211com *ic = &sc->sc_ic;
2808 	uint32_t tmp;
2809 	uint8_t bbp1, bbp3;
2810 	int i, error, qid, ridx, ntries;
2811 
2812 	for (ntries = 0; ntries < 100; ntries++) {
2813 		if ((error = run_read(sc, RT2860_ASIC_VER_ID, &tmp)) != 0)
2814 			goto fail;
2815 		if (tmp != 0 && tmp != 0xffffffff)
2816 			break;
2817 		DELAY(10);
2818 	}
2819 	if (ntries == 100) {
2820 		error = ETIMEDOUT;
2821 		goto fail;
2822 	}
2823 
2824 	if ((error = run_load_microcode(sc)) != 0) {
2825 		printf("%s: could not load 8051 microcode\n",
2826 		    sc->sc_dev.dv_xname);
2827 		goto fail;
2828 	}
2829 
2830 	/* init host command ring */
2831 	sc->cmdq.cur = sc->cmdq.next = sc->cmdq.queued = 0;
2832 
2833 	/* init Tx rings (4 EDCAs) */
2834 	for (qid = 0; qid < 4; qid++) {
2835 		if ((error = run_alloc_tx_ring(sc, qid)) != 0)
2836 			goto fail;
2837 	}
2838 	/* init Rx ring */
2839 	if ((error = run_alloc_rx_ring(sc)) != 0)
2840 		goto fail;
2841 
2842 	IEEE80211_ADDR_COPY(ic->ic_myaddr, LLADDR(ifp->if_sadl));
2843 	run_set_macaddr(sc, ic->ic_myaddr);
2844 
2845 	for (ntries = 0; ntries < 100; ntries++) {
2846 		if ((error = run_read(sc, RT2860_WPDMA_GLO_CFG, &tmp)) != 0)
2847 			goto fail;
2848 		if ((tmp & (RT2860_TX_DMA_BUSY | RT2860_RX_DMA_BUSY)) == 0)
2849 			break;
2850 		DELAY(1000);
2851 	}
2852 	if (ntries == 100) {
2853 		printf("%s: timeout waiting for DMA engine\n",
2854 		    sc->sc_dev.dv_xname);
2855 		error = ETIMEDOUT;
2856 		goto fail;
2857 	}
2858 	tmp &= 0xff0;
2859 	tmp |= RT2860_TX_WB_DDONE;
2860 	run_write(sc, RT2860_WPDMA_GLO_CFG, tmp);
2861 
2862 	/* turn off PME_OEN to solve high-current issue */
2863 	run_read(sc, RT2860_SYS_CTRL, &tmp);
2864 	run_write(sc, RT2860_SYS_CTRL, tmp & ~RT2860_PME_OEN);
2865 
2866 	run_write(sc, RT2860_MAC_SYS_CTRL,
2867 	    RT2860_BBP_HRST | RT2860_MAC_SRST);
2868 	run_write(sc, RT2860_USB_DMA_CFG, 0);
2869 
2870 	if ((error = run_reset(sc)) != 0) {
2871 		printf("%s: could not reset chipset\n", sc->sc_dev.dv_xname);
2872 		goto fail;
2873 	}
2874 
2875 	run_write(sc, RT2860_MAC_SYS_CTRL, 0);
2876 
2877 	/* init Tx power for all Tx rates (from EEPROM) */
2878 	for (ridx = 0; ridx < 5; ridx++) {
2879 		if (sc->txpow20mhz[ridx] == 0xffffffff)
2880 			continue;
2881 		run_write(sc, RT2860_TX_PWR_CFG(ridx), sc->txpow20mhz[ridx]);
2882 	}
2883 
2884 	for (i = 0; i < nitems(rt2870_def_mac); i++)
2885 		run_write(sc, rt2870_def_mac[i].reg, rt2870_def_mac[i].val);
2886 	run_write(sc, RT2860_WMM_AIFSN_CFG, 0x00002273);
2887 	run_write(sc, RT2860_WMM_CWMIN_CFG, 0x00002344);
2888 	run_write(sc, RT2860_WMM_CWMAX_CFG, 0x000034aa);
2889 
2890 	if ((sc->mac_rev >> 16) >= 0x3070) {
2891 		/* set delay of PA_PE assertion to 1us (unit of 0.25us) */
2892 		run_write(sc, RT2860_TX_SW_CFG0,
2893 		    4 << RT2860_DLY_PAPE_EN_SHIFT);
2894 		run_write(sc, RT2860_TX_SW_CFG1, 0);
2895 		run_write(sc, RT2860_TX_SW_CFG2, 0x1f);
2896 	}
2897 
2898 	/* wait while MAC is busy */
2899 	for (ntries = 0; ntries < 100; ntries++) {
2900 		if ((error = run_read(sc, RT2860_MAC_STATUS_REG, &tmp)) != 0)
2901 			goto fail;
2902 		if (!(tmp & (RT2860_RX_STATUS_BUSY | RT2860_TX_STATUS_BUSY)))
2903 			break;
2904 		DELAY(1000);
2905 	}
2906 	if (ntries == 100) {
2907 		error = ETIMEDOUT;
2908 		goto fail;
2909 	}
2910 
2911 	/* clear Host to MCU mailbox */
2912 	run_write(sc, RT2860_H2M_BBPAGENT, 0);
2913 	run_write(sc, RT2860_H2M_MAILBOX, 0);
2914 	DELAY(1000);
2915 
2916 	if ((error = run_bbp_init(sc)) != 0) {
2917 		printf("%s: could not initialize BBP\n", sc->sc_dev.dv_xname);
2918 		goto fail;
2919 	}
2920 
2921 	run_read(sc, RT2860_BCN_TIME_CFG, &tmp);
2922 	tmp &= ~(RT2860_BCN_TX_EN | RT2860_TSF_TIMER_EN |
2923 	    RT2860_TBTT_TIMER_EN);
2924 	run_write(sc, RT2860_BCN_TIME_CFG, tmp);
2925 
2926 	/* clear RX WCID search table */
2927 	run_set_region_4(sc, RT2860_WCID_ENTRY(0), 0, 512);
2928 	/* clear WCID attribute table */
2929 	run_set_region_4(sc, RT2860_WCID_ATTR(0), 0, 8 * 32);
2930 	/* clear shared key table */
2931 	run_set_region_4(sc, RT2860_SKEY(0, 0), 0, 8 * 32);
2932 	/* clear shared key mode */
2933 	run_set_region_4(sc, RT2860_SKEY_MODE_0_7, 0, 4);
2934 
2935 	run_read(sc, RT2860_US_CYC_CNT, &tmp);
2936 	tmp = (tmp & ~0xff) | 0x1e;
2937 	run_write(sc, RT2860_US_CYC_CNT, tmp);
2938 
2939 	if ((sc->mac_rev >> 16) == 0x2860 && (sc->mac_rev & 0xffff) != 0x0101)
2940 		run_write(sc, RT2860_TXOP_CTRL_CFG, 0x0000583f);
2941 
2942 	run_write(sc, RT2860_WMM_TXOP0_CFG, 0);
2943 	run_write(sc, RT2860_WMM_TXOP1_CFG, 48 << 16 | 96);
2944 
2945 	/* write vendor-specific BBP values (from EEPROM) */
2946 	for (i = 0; i < 8; i++) {
2947 		if (sc->bbp[i].reg == 0 || sc->bbp[i].reg == 0xff)
2948 			continue;
2949 		run_bbp_write(sc, sc->bbp[i].reg, sc->bbp[i].val);
2950 	}
2951 
2952 	/* select Main antenna for 1T1R devices */
2953 	if (sc->rf_rev == RT3070_RF_3020)
2954 		run_set_rx_antenna(sc, 0);
2955 
2956 	/* send LEDs operating mode to microcontroller */
2957 	(void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED1, sc->led[0]);
2958 	(void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED2, sc->led[1]);
2959 	(void)run_mcu_cmd(sc, RT2860_MCU_CMD_LED3, sc->led[2]);
2960 
2961 	/* disable non-existing Rx chains */
2962 	run_bbp_read(sc, 3, &bbp3);
2963 	bbp3 &= ~(1 << 3 | 1 << 4);
2964 	if (sc->nrxchains == 2)
2965 		bbp3 |= 1 << 3;
2966 	else if (sc->nrxchains == 3)
2967 		bbp3 |= 1 << 4;
2968 	run_bbp_write(sc, 3, bbp3);
2969 
2970 	/* disable non-existing Tx chains */
2971 	run_bbp_read(sc, 1, &bbp1);
2972 	if (sc->ntxchains == 1)
2973 		bbp1 &= ~(1 << 3 | 1 << 4);
2974 	run_bbp_write(sc, 1, bbp1);
2975 
2976 	if ((sc->mac_rev >> 16) >= 0x3070)
2977 		run_rt3070_rf_init(sc);
2978 
2979 	/* select default channel */
2980 	ic->ic_bss->ni_chan = ic->ic_ibss_chan;
2981 	run_set_chan(sc, ic->ic_ibss_chan);
2982 
2983 	/* turn radio LED on */
2984 	run_set_leds(sc, RT2860_LED_RADIO);
2985 
2986 	if (ic->ic_flags & IEEE80211_F_WEPON) {
2987 		/* install WEP keys */
2988 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
2989 			(void)run_set_key(ic, NULL, &ic->ic_nw_keys[i]);
2990 	}
2991 
2992 	for (i = 0; i < RUN_RX_RING_COUNT; i++) {
2993 		struct run_rx_data *data = &sc->rxq.data[i];
2994 
2995 		usbd_setup_xfer(data->xfer, sc->rxq.pipeh, data, data->buf,
2996 		    RUN_MAX_RXSZ, USBD_SHORT_XFER_OK | USBD_NO_COPY,
2997 		    USBD_NO_TIMEOUT, run_rxeof);
2998 		error = usbd_transfer(data->xfer);
2999 		if (error != 0 && error != USBD_IN_PROGRESS)
3000 			goto fail;
3001 	}
3002 
3003 	if ((error = run_txrx_enable(sc)) != 0)
3004 		goto fail;
3005 
3006 	ifp->if_flags &= ~IFF_OACTIVE;
3007 	ifp->if_flags |= IFF_RUNNING;
3008 
3009 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
3010 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
3011 	else
3012 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
3013 
3014 	if (error != 0)
3015 fail:		run_stop(ifp, 1);
3016 	return error;
3017 }
3018 
3019 void
3020 run_stop(struct ifnet *ifp, int disable)
3021 {
3022 	struct run_softc *sc = ifp->if_softc;
3023 	struct ieee80211com *ic = &sc->sc_ic;
3024 	uint32_t tmp;
3025 	int s, ntries, qid;
3026 
3027 	if (ifp->if_flags & IFF_RUNNING)
3028 		run_set_leds(sc, 0);	/* turn all LEDs off */
3029 
3030 	sc->sc_tx_timer = 0;
3031 	ifp->if_timer = 0;
3032 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
3033 
3034 	timeout_del(&sc->scan_to);
3035 	timeout_del(&sc->calib_to);
3036 
3037 	s = splusb();
3038 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
3039 	/* wait for all queued asynchronous commands to complete */
3040 	while (sc->cmdq.queued > 0)
3041 		tsleep(&sc->cmdq, 0, "cmdq", 0);
3042 	splx(s);
3043 
3044 	/* disable Tx/Rx */
3045 	run_read(sc, RT2860_MAC_SYS_CTRL, &tmp);
3046 	tmp &= ~(RT2860_MAC_RX_EN | RT2860_MAC_TX_EN);
3047 	run_write(sc, RT2860_MAC_SYS_CTRL, tmp);
3048 
3049 	/* wait for pending Tx to complete */
3050 	for (ntries = 0; ntries < 100; ntries++) {
3051 		if (run_read(sc, RT2860_TXRXQ_PCNT, &tmp) != 0)
3052 			break;
3053 		if ((tmp & RT2860_TX2Q_PCNT_MASK) == 0)
3054 			break;
3055 	}
3056 	DELAY(1000);
3057 	run_write(sc, RT2860_USB_DMA_CFG, 0);
3058 
3059 	/* reset adapter */
3060 	run_write(sc, RT2860_MAC_SYS_CTRL, RT2860_BBP_HRST | RT2860_MAC_SRST);
3061 	run_write(sc, RT2860_MAC_SYS_CTRL, 0);
3062 
3063 	/* reset Tx and Rx rings */
3064 	sc->qfullmsk = 0;
3065 	for (qid = 0; qid < 4; qid++)
3066 		run_free_tx_ring(sc, qid);
3067 	run_free_rx_ring(sc);
3068 }
3069