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