xref: /freebsd/sys/dev/ral/rt2661.c (revision c0020399a650364d0134f79f3fa319f84064372d)
1 /*	$FreeBSD$	*/
2 
3 /*-
4  * Copyright (c) 2006
5  *	Damien Bergamini <damien.bergamini@free.fr>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/cdefs.h>
21 __FBSDID("$FreeBSD$");
22 
23 /*-
24  * Ralink Technology RT2561, RT2561S and RT2661 chipset driver
25  * http://www.ralinktech.com/
26  */
27 
28 #include <sys/param.h>
29 #include <sys/sysctl.h>
30 #include <sys/sockio.h>
31 #include <sys/mbuf.h>
32 #include <sys/kernel.h>
33 #include <sys/socket.h>
34 #include <sys/systm.h>
35 #include <sys/malloc.h>
36 #include <sys/lock.h>
37 #include <sys/mutex.h>
38 #include <sys/module.h>
39 #include <sys/bus.h>
40 #include <sys/endian.h>
41 #include <sys/firmware.h>
42 
43 #include <machine/bus.h>
44 #include <machine/resource.h>
45 #include <sys/rman.h>
46 
47 #include <net/bpf.h>
48 #include <net/if.h>
49 #include <net/if_arp.h>
50 #include <net/ethernet.h>
51 #include <net/if_dl.h>
52 #include <net/if_media.h>
53 #include <net/if_types.h>
54 
55 #include <net80211/ieee80211_var.h>
56 #include <net80211/ieee80211_radiotap.h>
57 #include <net80211/ieee80211_regdomain.h>
58 #include <net80211/ieee80211_amrr.h>
59 
60 #include <netinet/in.h>
61 #include <netinet/in_systm.h>
62 #include <netinet/in_var.h>
63 #include <netinet/ip.h>
64 #include <netinet/if_ether.h>
65 
66 #include <dev/ral/rt2661reg.h>
67 #include <dev/ral/rt2661var.h>
68 
69 #define RAL_DEBUG
70 #ifdef RAL_DEBUG
71 #define DPRINTF(sc, fmt, ...) do {				\
72 	if (sc->sc_debug > 0)					\
73 		printf(fmt, __VA_ARGS__);			\
74 } while (0)
75 #define DPRINTFN(sc, n, fmt, ...) do {				\
76 	if (sc->sc_debug >= (n))				\
77 		printf(fmt, __VA_ARGS__);			\
78 } while (0)
79 #else
80 #define DPRINTF(sc, fmt, ...)
81 #define DPRINTFN(sc, n, fmt, ...)
82 #endif
83 
84 static struct ieee80211vap *rt2661_vap_create(struct ieee80211com *,
85 			    const char name[IFNAMSIZ], int unit, int opmode,
86 			    int flags, const uint8_t bssid[IEEE80211_ADDR_LEN],
87 			    const uint8_t mac[IEEE80211_ADDR_LEN]);
88 static void		rt2661_vap_delete(struct ieee80211vap *);
89 static void		rt2661_dma_map_addr(void *, bus_dma_segment_t *, int,
90 			    int);
91 static int		rt2661_alloc_tx_ring(struct rt2661_softc *,
92 			    struct rt2661_tx_ring *, int);
93 static void		rt2661_reset_tx_ring(struct rt2661_softc *,
94 			    struct rt2661_tx_ring *);
95 static void		rt2661_free_tx_ring(struct rt2661_softc *,
96 			    struct rt2661_tx_ring *);
97 static int		rt2661_alloc_rx_ring(struct rt2661_softc *,
98 			    struct rt2661_rx_ring *, int);
99 static void		rt2661_reset_rx_ring(struct rt2661_softc *,
100 			    struct rt2661_rx_ring *);
101 static void		rt2661_free_rx_ring(struct rt2661_softc *,
102 			    struct rt2661_rx_ring *);
103 static struct ieee80211_node *rt2661_node_alloc(struct ieee80211vap *,
104 			    const uint8_t [IEEE80211_ADDR_LEN]);
105 static void		rt2661_newassoc(struct ieee80211_node *, int);
106 static int		rt2661_newstate(struct ieee80211vap *,
107 			    enum ieee80211_state, int);
108 static uint16_t		rt2661_eeprom_read(struct rt2661_softc *, uint8_t);
109 static void		rt2661_rx_intr(struct rt2661_softc *);
110 static void		rt2661_tx_intr(struct rt2661_softc *);
111 static void		rt2661_tx_dma_intr(struct rt2661_softc *,
112 			    struct rt2661_tx_ring *);
113 static void		rt2661_mcu_beacon_expire(struct rt2661_softc *);
114 static void		rt2661_mcu_wakeup(struct rt2661_softc *);
115 static void		rt2661_mcu_cmd_intr(struct rt2661_softc *);
116 static void		rt2661_scan_start(struct ieee80211com *);
117 static void		rt2661_scan_end(struct ieee80211com *);
118 static void		rt2661_set_channel(struct ieee80211com *);
119 static void		rt2661_setup_tx_desc(struct rt2661_softc *,
120 			    struct rt2661_tx_desc *, uint32_t, uint16_t, int,
121 			    int, const bus_dma_segment_t *, int, int);
122 static int		rt2661_tx_data(struct rt2661_softc *, struct mbuf *,
123 			    struct ieee80211_node *, int);
124 static int		rt2661_tx_mgt(struct rt2661_softc *, struct mbuf *,
125 			    struct ieee80211_node *);
126 static void		rt2661_start_locked(struct ifnet *);
127 static void		rt2661_start(struct ifnet *);
128 static int		rt2661_raw_xmit(struct ieee80211_node *, struct mbuf *,
129 			    const struct ieee80211_bpf_params *);
130 static void		rt2661_watchdog(void *);
131 static int		rt2661_ioctl(struct ifnet *, u_long, caddr_t);
132 static void		rt2661_bbp_write(struct rt2661_softc *, uint8_t,
133 			    uint8_t);
134 static uint8_t		rt2661_bbp_read(struct rt2661_softc *, uint8_t);
135 static void		rt2661_rf_write(struct rt2661_softc *, uint8_t,
136 			    uint32_t);
137 static int		rt2661_tx_cmd(struct rt2661_softc *, uint8_t,
138 			    uint16_t);
139 static void		rt2661_select_antenna(struct rt2661_softc *);
140 static void		rt2661_enable_mrr(struct rt2661_softc *);
141 static void		rt2661_set_txpreamble(struct rt2661_softc *);
142 static void		rt2661_set_basicrates(struct rt2661_softc *,
143 			    const struct ieee80211_rateset *);
144 static void		rt2661_select_band(struct rt2661_softc *,
145 			    struct ieee80211_channel *);
146 static void		rt2661_set_chan(struct rt2661_softc *,
147 			    struct ieee80211_channel *);
148 static void		rt2661_set_bssid(struct rt2661_softc *,
149 			    const uint8_t *);
150 static void		rt2661_set_macaddr(struct rt2661_softc *,
151 			   const uint8_t *);
152 static void		rt2661_update_promisc(struct ifnet *);
153 static int		rt2661_wme_update(struct ieee80211com *) __unused;
154 static void		rt2661_update_slot(struct ifnet *);
155 static const char	*rt2661_get_rf(int);
156 static void		rt2661_read_eeprom(struct rt2661_softc *,
157 			    uint8_t macaddr[IEEE80211_ADDR_LEN]);
158 static int		rt2661_bbp_init(struct rt2661_softc *);
159 static void		rt2661_init_locked(struct rt2661_softc *);
160 static void		rt2661_init(void *);
161 static void             rt2661_stop_locked(struct rt2661_softc *);
162 static void		rt2661_stop(void *);
163 static int		rt2661_load_microcode(struct rt2661_softc *);
164 #ifdef notyet
165 static void		rt2661_rx_tune(struct rt2661_softc *);
166 static void		rt2661_radar_start(struct rt2661_softc *);
167 static int		rt2661_radar_stop(struct rt2661_softc *);
168 #endif
169 static int		rt2661_prepare_beacon(struct rt2661_softc *,
170 			    struct ieee80211vap *);
171 static void		rt2661_enable_tsf_sync(struct rt2661_softc *);
172 static int		rt2661_get_rssi(struct rt2661_softc *, uint8_t);
173 
174 static const struct {
175 	uint32_t	reg;
176 	uint32_t	val;
177 } rt2661_def_mac[] = {
178 	RT2661_DEF_MAC
179 };
180 
181 static const struct {
182 	uint8_t	reg;
183 	uint8_t	val;
184 } rt2661_def_bbp[] = {
185 	RT2661_DEF_BBP
186 };
187 
188 static const struct rfprog {
189 	uint8_t		chan;
190 	uint32_t	r1, r2, r3, r4;
191 }  rt2661_rf5225_1[] = {
192 	RT2661_RF5225_1
193 }, rt2661_rf5225_2[] = {
194 	RT2661_RF5225_2
195 };
196 
197 int
198 rt2661_attach(device_t dev, int id)
199 {
200 	struct rt2661_softc *sc = device_get_softc(dev);
201 	struct ieee80211com *ic;
202 	struct ifnet *ifp;
203 	uint32_t val;
204 	int error, ac, ntries;
205 	uint8_t bands;
206 	uint8_t macaddr[IEEE80211_ADDR_LEN];
207 
208 	sc->sc_id = id;
209 	sc->sc_dev = dev;
210 
211 	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
212 	if (ifp == NULL) {
213 		device_printf(sc->sc_dev, "can not if_alloc()\n");
214 		return ENOMEM;
215 	}
216 	ic = ifp->if_l2com;
217 
218 	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
219 	    MTX_DEF | MTX_RECURSE);
220 
221 	callout_init_mtx(&sc->watchdog_ch, &sc->sc_mtx, 0);
222 
223 	/* wait for NIC to initialize */
224 	for (ntries = 0; ntries < 1000; ntries++) {
225 		if ((val = RAL_READ(sc, RT2661_MAC_CSR0)) != 0)
226 			break;
227 		DELAY(1000);
228 	}
229 	if (ntries == 1000) {
230 		device_printf(sc->sc_dev,
231 		    "timeout waiting for NIC to initialize\n");
232 		error = EIO;
233 		goto fail1;
234 	}
235 
236 	/* retrieve RF rev. no and various other things from EEPROM */
237 	rt2661_read_eeprom(sc, macaddr);
238 
239 	device_printf(dev, "MAC/BBP RT%X, RF %s\n", val,
240 	    rt2661_get_rf(sc->rf_rev));
241 
242 	/*
243 	 * Allocate Tx and Rx rings.
244 	 */
245 	for (ac = 0; ac < 4; ac++) {
246 		error = rt2661_alloc_tx_ring(sc, &sc->txq[ac],
247 		    RT2661_TX_RING_COUNT);
248 		if (error != 0) {
249 			device_printf(sc->sc_dev,
250 			    "could not allocate Tx ring %d\n", ac);
251 			goto fail2;
252 		}
253 	}
254 
255 	error = rt2661_alloc_tx_ring(sc, &sc->mgtq, RT2661_MGT_RING_COUNT);
256 	if (error != 0) {
257 		device_printf(sc->sc_dev, "could not allocate Mgt ring\n");
258 		goto fail2;
259 	}
260 
261 	error = rt2661_alloc_rx_ring(sc, &sc->rxq, RT2661_RX_RING_COUNT);
262 	if (error != 0) {
263 		device_printf(sc->sc_dev, "could not allocate Rx ring\n");
264 		goto fail3;
265 	}
266 
267 	ifp->if_softc = sc;
268 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
269 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
270 	ifp->if_init = rt2661_init;
271 	ifp->if_ioctl = rt2661_ioctl;
272 	ifp->if_start = rt2661_start;
273 	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
274 	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
275 	IFQ_SET_READY(&ifp->if_snd);
276 
277 	ic->ic_ifp = ifp;
278 	ic->ic_opmode = IEEE80211_M_STA;
279 	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
280 
281 	/* set device capabilities */
282 	ic->ic_caps =
283 		  IEEE80211_C_STA		/* station mode */
284 		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
285 		| IEEE80211_C_HOSTAP		/* hostap mode */
286 		| IEEE80211_C_MONITOR		/* monitor mode */
287 		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
288 		| IEEE80211_C_WDS		/* 4-address traffic works */
289 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
290 		| IEEE80211_C_SHSLOT		/* short slot time supported */
291 		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
292 		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
293 #ifdef notyet
294 		| IEEE80211_C_TXFRAG		/* handle tx frags */
295 		| IEEE80211_C_WME		/* 802.11e */
296 #endif
297 		;
298 
299 	bands = 0;
300 	setbit(&bands, IEEE80211_MODE_11B);
301 	setbit(&bands, IEEE80211_MODE_11G);
302 	if (sc->rf_rev == RT2661_RF_5225 || sc->rf_rev == RT2661_RF_5325)
303 		setbit(&bands, IEEE80211_MODE_11A);
304 	ieee80211_init_channels(ic, NULL, &bands);
305 
306 	ieee80211_ifattach(ic, macaddr);
307 	ic->ic_newassoc = rt2661_newassoc;
308 	ic->ic_node_alloc = rt2661_node_alloc;
309 #if 0
310 	ic->ic_wme.wme_update = rt2661_wme_update;
311 #endif
312 	ic->ic_scan_start = rt2661_scan_start;
313 	ic->ic_scan_end = rt2661_scan_end;
314 	ic->ic_set_channel = rt2661_set_channel;
315 	ic->ic_updateslot = rt2661_update_slot;
316 	ic->ic_update_promisc = rt2661_update_promisc;
317 	ic->ic_raw_xmit = rt2661_raw_xmit;
318 
319 	ic->ic_vap_create = rt2661_vap_create;
320 	ic->ic_vap_delete = rt2661_vap_delete;
321 
322 	bpfattach(ifp, DLT_IEEE802_11_RADIO,
323 	    sizeof (struct ieee80211_frame) + sizeof (sc->sc_txtap));
324 
325 	sc->sc_rxtap_len = sizeof sc->sc_rxtap;
326 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
327 	sc->sc_rxtap.wr_ihdr.it_present = htole32(RT2661_RX_RADIOTAP_PRESENT);
328 
329 	sc->sc_txtap_len = sizeof sc->sc_txtap;
330 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
331 	sc->sc_txtap.wt_ihdr.it_present = htole32(RT2661_TX_RADIOTAP_PRESENT);
332 
333 #ifdef RAL_DEBUG
334 	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
335 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
336 	    "debug", CTLFLAG_RW, &sc->sc_debug, 0, "debug msgs");
337 #endif
338 	if (bootverbose)
339 		ieee80211_announce(ic);
340 
341 	return 0;
342 
343 fail3:	rt2661_free_tx_ring(sc, &sc->mgtq);
344 fail2:	while (--ac >= 0)
345 		rt2661_free_tx_ring(sc, &sc->txq[ac]);
346 fail1:	mtx_destroy(&sc->sc_mtx);
347 	if_free(ifp);
348 	return error;
349 }
350 
351 int
352 rt2661_detach(void *xsc)
353 {
354 	struct rt2661_softc *sc = xsc;
355 	struct ifnet *ifp = sc->sc_ifp;
356 	struct ieee80211com *ic = ifp->if_l2com;
357 
358 	RAL_LOCK(sc);
359 	rt2661_stop_locked(sc);
360 	RAL_UNLOCK(sc);
361 
362 	bpfdetach(ifp);
363 	ieee80211_ifdetach(ic);
364 
365 	rt2661_free_tx_ring(sc, &sc->txq[0]);
366 	rt2661_free_tx_ring(sc, &sc->txq[1]);
367 	rt2661_free_tx_ring(sc, &sc->txq[2]);
368 	rt2661_free_tx_ring(sc, &sc->txq[3]);
369 	rt2661_free_tx_ring(sc, &sc->mgtq);
370 	rt2661_free_rx_ring(sc, &sc->rxq);
371 
372 	if_free(ifp);
373 
374 	mtx_destroy(&sc->sc_mtx);
375 
376 	return 0;
377 }
378 
379 static struct ieee80211vap *
380 rt2661_vap_create(struct ieee80211com *ic,
381 	const char name[IFNAMSIZ], int unit, int opmode, int flags,
382 	const uint8_t bssid[IEEE80211_ADDR_LEN],
383 	const uint8_t mac[IEEE80211_ADDR_LEN])
384 {
385 	struct ifnet *ifp = ic->ic_ifp;
386 	struct rt2661_vap *rvp;
387 	struct ieee80211vap *vap;
388 
389 	switch (opmode) {
390 	case IEEE80211_M_STA:
391 	case IEEE80211_M_IBSS:
392 	case IEEE80211_M_AHDEMO:
393 	case IEEE80211_M_MONITOR:
394 	case IEEE80211_M_HOSTAP:
395 		if (!TAILQ_EMPTY(&ic->ic_vaps)) {
396 			if_printf(ifp, "only 1 vap supported\n");
397 			return NULL;
398 		}
399 		if (opmode == IEEE80211_M_STA)
400 			flags |= IEEE80211_CLONE_NOBEACONS;
401 		break;
402 	case IEEE80211_M_WDS:
403 		if (TAILQ_EMPTY(&ic->ic_vaps) ||
404 		    ic->ic_opmode != IEEE80211_M_HOSTAP) {
405 			if_printf(ifp, "wds only supported in ap mode\n");
406 			return NULL;
407 		}
408 		/*
409 		 * Silently remove any request for a unique
410 		 * bssid; WDS vap's always share the local
411 		 * mac address.
412 		 */
413 		flags &= ~IEEE80211_CLONE_BSSID;
414 		break;
415 	default:
416 		if_printf(ifp, "unknown opmode %d\n", opmode);
417 		return NULL;
418 	}
419 	rvp = (struct rt2661_vap *) malloc(sizeof(struct rt2661_vap),
420 	    M_80211_VAP, M_NOWAIT | M_ZERO);
421 	if (rvp == NULL)
422 		return NULL;
423 	vap = &rvp->ral_vap;
424 	ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid, mac);
425 
426 	/* override state transition machine */
427 	rvp->ral_newstate = vap->iv_newstate;
428 	vap->iv_newstate = rt2661_newstate;
429 #if 0
430 	vap->iv_update_beacon = rt2661_beacon_update;
431 #endif
432 
433 	ieee80211_amrr_init(&rvp->amrr, vap,
434 	    IEEE80211_AMRR_MIN_SUCCESS_THRESHOLD,
435 	    IEEE80211_AMRR_MAX_SUCCESS_THRESHOLD,
436 	    500 /* ms */);
437 
438 	/* complete setup */
439 	ieee80211_vap_attach(vap, ieee80211_media_change, ieee80211_media_status);
440 	if (TAILQ_FIRST(&ic->ic_vaps) == vap)
441 		ic->ic_opmode = opmode;
442 	return vap;
443 }
444 
445 static void
446 rt2661_vap_delete(struct ieee80211vap *vap)
447 {
448 	struct rt2661_vap *rvp = RT2661_VAP(vap);
449 
450 	ieee80211_amrr_cleanup(&rvp->amrr);
451 	ieee80211_vap_detach(vap);
452 	free(rvp, M_80211_VAP);
453 }
454 
455 void
456 rt2661_shutdown(void *xsc)
457 {
458 	struct rt2661_softc *sc = xsc;
459 
460 	rt2661_stop(sc);
461 }
462 
463 void
464 rt2661_suspend(void *xsc)
465 {
466 	struct rt2661_softc *sc = xsc;
467 
468 	rt2661_stop(sc);
469 }
470 
471 void
472 rt2661_resume(void *xsc)
473 {
474 	struct rt2661_softc *sc = xsc;
475 	struct ifnet *ifp = sc->sc_ifp;
476 
477 	if (ifp->if_flags & IFF_UP)
478 		rt2661_init(sc);
479 }
480 
481 static void
482 rt2661_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
483 {
484 	if (error != 0)
485 		return;
486 
487 	KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
488 
489 	*(bus_addr_t *)arg = segs[0].ds_addr;
490 }
491 
492 static int
493 rt2661_alloc_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring,
494     int count)
495 {
496 	int i, error;
497 
498 	ring->count = count;
499 	ring->queued = 0;
500 	ring->cur = ring->next = ring->stat = 0;
501 
502 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 4, 0,
503 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
504 	    count * RT2661_TX_DESC_SIZE, 1, count * RT2661_TX_DESC_SIZE,
505 	    0, NULL, NULL, &ring->desc_dmat);
506 	if (error != 0) {
507 		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
508 		goto fail;
509 	}
510 
511 	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
512 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
513 	if (error != 0) {
514 		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
515 		goto fail;
516 	}
517 
518 	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
519 	    count * RT2661_TX_DESC_SIZE, rt2661_dma_map_addr, &ring->physaddr,
520 	    0);
521 	if (error != 0) {
522 		device_printf(sc->sc_dev, "could not load desc DMA map\n");
523 		goto fail;
524 	}
525 
526 	ring->data = malloc(count * sizeof (struct rt2661_tx_data), M_DEVBUF,
527 	    M_NOWAIT | M_ZERO);
528 	if (ring->data == NULL) {
529 		device_printf(sc->sc_dev, "could not allocate soft data\n");
530 		error = ENOMEM;
531 		goto fail;
532 	}
533 
534 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
535 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
536 	    RT2661_MAX_SCATTER, MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
537 	if (error != 0) {
538 		device_printf(sc->sc_dev, "could not create data DMA tag\n");
539 		goto fail;
540 	}
541 
542 	for (i = 0; i < count; i++) {
543 		error = bus_dmamap_create(ring->data_dmat, 0,
544 		    &ring->data[i].map);
545 		if (error != 0) {
546 			device_printf(sc->sc_dev, "could not create DMA map\n");
547 			goto fail;
548 		}
549 	}
550 
551 	return 0;
552 
553 fail:	rt2661_free_tx_ring(sc, ring);
554 	return error;
555 }
556 
557 static void
558 rt2661_reset_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring)
559 {
560 	struct rt2661_tx_desc *desc;
561 	struct rt2661_tx_data *data;
562 	int i;
563 
564 	for (i = 0; i < ring->count; i++) {
565 		desc = &ring->desc[i];
566 		data = &ring->data[i];
567 
568 		if (data->m != NULL) {
569 			bus_dmamap_sync(ring->data_dmat, data->map,
570 			    BUS_DMASYNC_POSTWRITE);
571 			bus_dmamap_unload(ring->data_dmat, data->map);
572 			m_freem(data->m);
573 			data->m = NULL;
574 		}
575 
576 		if (data->ni != NULL) {
577 			ieee80211_free_node(data->ni);
578 			data->ni = NULL;
579 		}
580 
581 		desc->flags = 0;
582 	}
583 
584 	bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
585 
586 	ring->queued = 0;
587 	ring->cur = ring->next = ring->stat = 0;
588 }
589 
590 static void
591 rt2661_free_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring)
592 {
593 	struct rt2661_tx_data *data;
594 	int i;
595 
596 	if (ring->desc != NULL) {
597 		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
598 		    BUS_DMASYNC_POSTWRITE);
599 		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
600 		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
601 	}
602 
603 	if (ring->desc_dmat != NULL)
604 		bus_dma_tag_destroy(ring->desc_dmat);
605 
606 	if (ring->data != NULL) {
607 		for (i = 0; i < ring->count; i++) {
608 			data = &ring->data[i];
609 
610 			if (data->m != NULL) {
611 				bus_dmamap_sync(ring->data_dmat, data->map,
612 				    BUS_DMASYNC_POSTWRITE);
613 				bus_dmamap_unload(ring->data_dmat, data->map);
614 				m_freem(data->m);
615 			}
616 
617 			if (data->ni != NULL)
618 				ieee80211_free_node(data->ni);
619 
620 			if (data->map != NULL)
621 				bus_dmamap_destroy(ring->data_dmat, data->map);
622 		}
623 
624 		free(ring->data, M_DEVBUF);
625 	}
626 
627 	if (ring->data_dmat != NULL)
628 		bus_dma_tag_destroy(ring->data_dmat);
629 }
630 
631 static int
632 rt2661_alloc_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring,
633     int count)
634 {
635 	struct rt2661_rx_desc *desc;
636 	struct rt2661_rx_data *data;
637 	bus_addr_t physaddr;
638 	int i, error;
639 
640 	ring->count = count;
641 	ring->cur = ring->next = 0;
642 
643 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 4, 0,
644 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
645 	    count * RT2661_RX_DESC_SIZE, 1, count * RT2661_RX_DESC_SIZE,
646 	    0, NULL, NULL, &ring->desc_dmat);
647 	if (error != 0) {
648 		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
649 		goto fail;
650 	}
651 
652 	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
653 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
654 	if (error != 0) {
655 		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
656 		goto fail;
657 	}
658 
659 	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
660 	    count * RT2661_RX_DESC_SIZE, rt2661_dma_map_addr, &ring->physaddr,
661 	    0);
662 	if (error != 0) {
663 		device_printf(sc->sc_dev, "could not load desc DMA map\n");
664 		goto fail;
665 	}
666 
667 	ring->data = malloc(count * sizeof (struct rt2661_rx_data), M_DEVBUF,
668 	    M_NOWAIT | M_ZERO);
669 	if (ring->data == NULL) {
670 		device_printf(sc->sc_dev, "could not allocate soft data\n");
671 		error = ENOMEM;
672 		goto fail;
673 	}
674 
675 	/*
676 	 * Pre-allocate Rx buffers and populate Rx ring.
677 	 */
678 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
679 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
680 	    1, MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
681 	if (error != 0) {
682 		device_printf(sc->sc_dev, "could not create data DMA tag\n");
683 		goto fail;
684 	}
685 
686 	for (i = 0; i < count; i++) {
687 		desc = &sc->rxq.desc[i];
688 		data = &sc->rxq.data[i];
689 
690 		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
691 		if (error != 0) {
692 			device_printf(sc->sc_dev, "could not create DMA map\n");
693 			goto fail;
694 		}
695 
696 		data->m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
697 		if (data->m == NULL) {
698 			device_printf(sc->sc_dev,
699 			    "could not allocate rx mbuf\n");
700 			error = ENOMEM;
701 			goto fail;
702 		}
703 
704 		error = bus_dmamap_load(ring->data_dmat, data->map,
705 		    mtod(data->m, void *), MCLBYTES, rt2661_dma_map_addr,
706 		    &physaddr, 0);
707 		if (error != 0) {
708 			device_printf(sc->sc_dev,
709 			    "could not load rx buf DMA map");
710 			goto fail;
711 		}
712 
713 		desc->flags = htole32(RT2661_RX_BUSY);
714 		desc->physaddr = htole32(physaddr);
715 	}
716 
717 	bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
718 
719 	return 0;
720 
721 fail:	rt2661_free_rx_ring(sc, ring);
722 	return error;
723 }
724 
725 static void
726 rt2661_reset_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring)
727 {
728 	int i;
729 
730 	for (i = 0; i < ring->count; i++)
731 		ring->desc[i].flags = htole32(RT2661_RX_BUSY);
732 
733 	bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
734 
735 	ring->cur = ring->next = 0;
736 }
737 
738 static void
739 rt2661_free_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring)
740 {
741 	struct rt2661_rx_data *data;
742 	int i;
743 
744 	if (ring->desc != NULL) {
745 		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
746 		    BUS_DMASYNC_POSTWRITE);
747 		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
748 		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
749 	}
750 
751 	if (ring->desc_dmat != NULL)
752 		bus_dma_tag_destroy(ring->desc_dmat);
753 
754 	if (ring->data != NULL) {
755 		for (i = 0; i < ring->count; i++) {
756 			data = &ring->data[i];
757 
758 			if (data->m != NULL) {
759 				bus_dmamap_sync(ring->data_dmat, data->map,
760 				    BUS_DMASYNC_POSTREAD);
761 				bus_dmamap_unload(ring->data_dmat, data->map);
762 				m_freem(data->m);
763 			}
764 
765 			if (data->map != NULL)
766 				bus_dmamap_destroy(ring->data_dmat, data->map);
767 		}
768 
769 		free(ring->data, M_DEVBUF);
770 	}
771 
772 	if (ring->data_dmat != NULL)
773 		bus_dma_tag_destroy(ring->data_dmat);
774 }
775 
776 static struct ieee80211_node *
777 rt2661_node_alloc(struct ieee80211vap *vap,
778 	const uint8_t mac[IEEE80211_ADDR_LEN])
779 {
780 	struct rt2661_node *rn;
781 
782 	rn = malloc(sizeof (struct rt2661_node), M_80211_NODE,
783 	    M_NOWAIT | M_ZERO);
784 
785 	return (rn != NULL) ? &rn->ni : NULL;
786 }
787 
788 static void
789 rt2661_newassoc(struct ieee80211_node *ni, int isnew)
790 {
791 	struct ieee80211vap *vap = ni->ni_vap;
792 
793 	ieee80211_amrr_node_init(&RT2661_VAP(vap)->amrr,
794 	    &RT2661_NODE(ni)->amrr, ni);
795 }
796 
797 static int
798 rt2661_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
799 {
800 	struct rt2661_vap *rvp = RT2661_VAP(vap);
801 	struct ieee80211com *ic = vap->iv_ic;
802 	struct rt2661_softc *sc = ic->ic_ifp->if_softc;
803 	int error;
804 
805 	if (nstate == IEEE80211_S_INIT && vap->iv_state == IEEE80211_S_RUN) {
806 		uint32_t tmp;
807 
808 		/* abort TSF synchronization */
809 		tmp = RAL_READ(sc, RT2661_TXRX_CSR9);
810 		RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp & ~0x00ffffff);
811 	}
812 
813 	error = rvp->ral_newstate(vap, nstate, arg);
814 
815 	if (error == 0 && nstate == IEEE80211_S_RUN) {
816 		struct ieee80211_node *ni = vap->iv_bss;
817 
818 		if (vap->iv_opmode != IEEE80211_M_MONITOR) {
819 			rt2661_enable_mrr(sc);
820 			rt2661_set_txpreamble(sc);
821 			rt2661_set_basicrates(sc, &ni->ni_rates);
822 			rt2661_set_bssid(sc, ni->ni_bssid);
823 		}
824 
825 		if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
826 		    vap->iv_opmode == IEEE80211_M_IBSS) {
827 			error = rt2661_prepare_beacon(sc, vap);
828 			if (error != 0)
829 				return error;
830 		}
831 		if (vap->iv_opmode != IEEE80211_M_MONITOR)
832 			rt2661_enable_tsf_sync(sc);
833 	}
834 	return error;
835 }
836 
837 /*
838  * Read 16 bits at address 'addr' from the serial EEPROM (either 93C46 or
839  * 93C66).
840  */
841 static uint16_t
842 rt2661_eeprom_read(struct rt2661_softc *sc, uint8_t addr)
843 {
844 	uint32_t tmp;
845 	uint16_t val;
846 	int n;
847 
848 	/* clock C once before the first command */
849 	RT2661_EEPROM_CTL(sc, 0);
850 
851 	RT2661_EEPROM_CTL(sc, RT2661_S);
852 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
853 	RT2661_EEPROM_CTL(sc, RT2661_S);
854 
855 	/* write start bit (1) */
856 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
857 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
858 
859 	/* write READ opcode (10) */
860 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
861 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
862 	RT2661_EEPROM_CTL(sc, RT2661_S);
863 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
864 
865 	/* write address (A5-A0 or A7-A0) */
866 	n = (RAL_READ(sc, RT2661_E2PROM_CSR) & RT2661_93C46) ? 5 : 7;
867 	for (; n >= 0; n--) {
868 		RT2661_EEPROM_CTL(sc, RT2661_S |
869 		    (((addr >> n) & 1) << RT2661_SHIFT_D));
870 		RT2661_EEPROM_CTL(sc, RT2661_S |
871 		    (((addr >> n) & 1) << RT2661_SHIFT_D) | RT2661_C);
872 	}
873 
874 	RT2661_EEPROM_CTL(sc, RT2661_S);
875 
876 	/* read data Q15-Q0 */
877 	val = 0;
878 	for (n = 15; n >= 0; n--) {
879 		RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
880 		tmp = RAL_READ(sc, RT2661_E2PROM_CSR);
881 		val |= ((tmp & RT2661_Q) >> RT2661_SHIFT_Q) << n;
882 		RT2661_EEPROM_CTL(sc, RT2661_S);
883 	}
884 
885 	RT2661_EEPROM_CTL(sc, 0);
886 
887 	/* clear Chip Select and clock C */
888 	RT2661_EEPROM_CTL(sc, RT2661_S);
889 	RT2661_EEPROM_CTL(sc, 0);
890 	RT2661_EEPROM_CTL(sc, RT2661_C);
891 
892 	return val;
893 }
894 
895 static void
896 rt2661_tx_intr(struct rt2661_softc *sc)
897 {
898 	struct ifnet *ifp = sc->sc_ifp;
899 	struct rt2661_tx_ring *txq;
900 	struct rt2661_tx_data *data;
901 	struct rt2661_node *rn;
902 	uint32_t val;
903 	int qid, retrycnt;
904 
905 	for (;;) {
906 		struct ieee80211_node *ni;
907 		struct mbuf *m;
908 
909 		val = RAL_READ(sc, RT2661_STA_CSR4);
910 		if (!(val & RT2661_TX_STAT_VALID))
911 			break;
912 
913 		/* retrieve the queue in which this frame was sent */
914 		qid = RT2661_TX_QID(val);
915 		txq = (qid <= 3) ? &sc->txq[qid] : &sc->mgtq;
916 
917 		/* retrieve rate control algorithm context */
918 		data = &txq->data[txq->stat];
919 		m = data->m;
920 		data->m = NULL;
921 		ni = data->ni;
922 		data->ni = NULL;
923 
924 		/* if no frame has been sent, ignore */
925 		if (ni == NULL)
926 			continue;
927 
928 		rn = RT2661_NODE(ni);
929 
930 		switch (RT2661_TX_RESULT(val)) {
931 		case RT2661_TX_SUCCESS:
932 			retrycnt = RT2661_TX_RETRYCNT(val);
933 
934 			DPRINTFN(sc, 10, "data frame sent successfully after "
935 			    "%d retries\n", retrycnt);
936 			if (data->rix != IEEE80211_FIXED_RATE_NONE)
937 				ieee80211_amrr_tx_complete(&rn->amrr,
938 				    IEEE80211_AMRR_SUCCESS, retrycnt);
939 			ifp->if_opackets++;
940 			break;
941 
942 		case RT2661_TX_RETRY_FAIL:
943 			retrycnt = RT2661_TX_RETRYCNT(val);
944 
945 			DPRINTFN(sc, 9, "%s\n",
946 			    "sending data frame failed (too much retries)");
947 			if (data->rix != IEEE80211_FIXED_RATE_NONE)
948 				ieee80211_amrr_tx_complete(&rn->amrr,
949 				    IEEE80211_AMRR_FAILURE, retrycnt);
950 			ifp->if_oerrors++;
951 			break;
952 
953 		default:
954 			/* other failure */
955 			device_printf(sc->sc_dev,
956 			    "sending data frame failed 0x%08x\n", val);
957 			ifp->if_oerrors++;
958 		}
959 
960 		DPRINTFN(sc, 15, "tx done q=%d idx=%u\n", qid, txq->stat);
961 
962 		txq->queued--;
963 		if (++txq->stat >= txq->count)	/* faster than % count */
964 			txq->stat = 0;
965 
966 		if (m->m_flags & M_TXCB)
967 			ieee80211_process_callback(ni, m,
968 				RT2661_TX_RESULT(val) != RT2661_TX_SUCCESS);
969 		m_freem(m);
970 		ieee80211_free_node(ni);
971 	}
972 
973 	sc->sc_tx_timer = 0;
974 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
975 
976 	rt2661_start_locked(ifp);
977 }
978 
979 static void
980 rt2661_tx_dma_intr(struct rt2661_softc *sc, struct rt2661_tx_ring *txq)
981 {
982 	struct rt2661_tx_desc *desc;
983 	struct rt2661_tx_data *data;
984 
985 	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_POSTREAD);
986 
987 	for (;;) {
988 		desc = &txq->desc[txq->next];
989 		data = &txq->data[txq->next];
990 
991 		if ((le32toh(desc->flags) & RT2661_TX_BUSY) ||
992 		    !(le32toh(desc->flags) & RT2661_TX_VALID))
993 			break;
994 
995 		bus_dmamap_sync(txq->data_dmat, data->map,
996 		    BUS_DMASYNC_POSTWRITE);
997 		bus_dmamap_unload(txq->data_dmat, data->map);
998 
999 		/* descriptor is no longer valid */
1000 		desc->flags &= ~htole32(RT2661_TX_VALID);
1001 
1002 		DPRINTFN(sc, 15, "tx dma done q=%p idx=%u\n", txq, txq->next);
1003 
1004 		if (++txq->next >= txq->count)	/* faster than % count */
1005 			txq->next = 0;
1006 	}
1007 
1008 	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1009 }
1010 
1011 static void
1012 rt2661_rx_intr(struct rt2661_softc *sc)
1013 {
1014 	struct ifnet *ifp = sc->sc_ifp;
1015 	struct ieee80211com *ic = ifp->if_l2com;
1016 	struct rt2661_rx_desc *desc;
1017 	struct rt2661_rx_data *data;
1018 	bus_addr_t physaddr;
1019 	struct ieee80211_frame *wh;
1020 	struct ieee80211_node *ni;
1021 	struct mbuf *mnew, *m;
1022 	int error;
1023 
1024 	bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1025 	    BUS_DMASYNC_POSTREAD);
1026 
1027 	for (;;) {
1028 		int rssi;
1029 
1030 		desc = &sc->rxq.desc[sc->rxq.cur];
1031 		data = &sc->rxq.data[sc->rxq.cur];
1032 
1033 		if (le32toh(desc->flags) & RT2661_RX_BUSY)
1034 			break;
1035 
1036 		if ((le32toh(desc->flags) & RT2661_RX_PHY_ERROR) ||
1037 		    (le32toh(desc->flags) & RT2661_RX_CRC_ERROR)) {
1038 			/*
1039 			 * This should not happen since we did not request
1040 			 * to receive those frames when we filled TXRX_CSR0.
1041 			 */
1042 			DPRINTFN(sc, 5, "PHY or CRC error flags 0x%08x\n",
1043 			    le32toh(desc->flags));
1044 			ifp->if_ierrors++;
1045 			goto skip;
1046 		}
1047 
1048 		if ((le32toh(desc->flags) & RT2661_RX_CIPHER_MASK) != 0) {
1049 			ifp->if_ierrors++;
1050 			goto skip;
1051 		}
1052 
1053 		/*
1054 		 * Try to allocate a new mbuf for this ring element and load it
1055 		 * before processing the current mbuf. If the ring element
1056 		 * cannot be loaded, drop the received packet and reuse the old
1057 		 * mbuf. In the unlikely case that the old mbuf can't be
1058 		 * reloaded either, explicitly panic.
1059 		 */
1060 		mnew = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1061 		if (mnew == NULL) {
1062 			ifp->if_ierrors++;
1063 			goto skip;
1064 		}
1065 
1066 		bus_dmamap_sync(sc->rxq.data_dmat, data->map,
1067 		    BUS_DMASYNC_POSTREAD);
1068 		bus_dmamap_unload(sc->rxq.data_dmat, data->map);
1069 
1070 		error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1071 		    mtod(mnew, void *), MCLBYTES, rt2661_dma_map_addr,
1072 		    &physaddr, 0);
1073 		if (error != 0) {
1074 			m_freem(mnew);
1075 
1076 			/* try to reload the old mbuf */
1077 			error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1078 			    mtod(data->m, void *), MCLBYTES,
1079 			    rt2661_dma_map_addr, &physaddr, 0);
1080 			if (error != 0) {
1081 				/* very unlikely that it will fail... */
1082 				panic("%s: could not load old rx mbuf",
1083 				    device_get_name(sc->sc_dev));
1084 			}
1085 			ifp->if_ierrors++;
1086 			goto skip;
1087 		}
1088 
1089 		/*
1090 	 	 * New mbuf successfully loaded, update Rx ring and continue
1091 		 * processing.
1092 		 */
1093 		m = data->m;
1094 		data->m = mnew;
1095 		desc->physaddr = htole32(physaddr);
1096 
1097 		/* finalize mbuf */
1098 		m->m_pkthdr.rcvif = ifp;
1099 		m->m_pkthdr.len = m->m_len =
1100 		    (le32toh(desc->flags) >> 16) & 0xfff;
1101 
1102 		rssi = rt2661_get_rssi(sc, desc->rssi);
1103 
1104 		if (bpf_peers_present(ifp->if_bpf)) {
1105 			struct rt2661_rx_radiotap_header *tap = &sc->sc_rxtap;
1106 			uint32_t tsf_lo, tsf_hi;
1107 
1108 			/* get timestamp (low and high 32 bits) */
1109 			tsf_hi = RAL_READ(sc, RT2661_TXRX_CSR13);
1110 			tsf_lo = RAL_READ(sc, RT2661_TXRX_CSR12);
1111 
1112 			tap->wr_tsf =
1113 			    htole64(((uint64_t)tsf_hi << 32) | tsf_lo);
1114 			tap->wr_flags = 0;
1115 			tap->wr_rate = ieee80211_plcp2rate(desc->rate,
1116 			    (desc->flags & htole32(RT2661_RX_OFDM)) ?
1117 				IEEE80211_T_OFDM : IEEE80211_T_CCK);
1118 			tap->wr_antsignal = rssi < 0 ? 0 : rssi;
1119 
1120 			bpf_mtap2(ifp->if_bpf, tap, sc->sc_rxtap_len, m);
1121 		}
1122 		sc->sc_flags |= RAL_INPUT_RUNNING;
1123 		RAL_UNLOCK(sc);
1124 		wh = mtod(m, struct ieee80211_frame *);
1125 
1126 		/* send the frame to the 802.11 layer */
1127 		ni = ieee80211_find_rxnode(ic,
1128 		    (struct ieee80211_frame_min *)wh);
1129 		if (ni != NULL) {
1130 			/* Error happened during RSSI conversion. */
1131 			if (rssi < 0)
1132 				rssi = -30;	/* XXX ignored by net80211 */
1133 
1134 			(void) ieee80211_input(ni, m, rssi,
1135 			    RT2661_NOISE_FLOOR, 0);
1136 			ieee80211_free_node(ni);
1137 		} else
1138 			(void) ieee80211_input_all(ic, m, rssi,
1139 			    RT2661_NOISE_FLOOR, 0);
1140 
1141 		RAL_LOCK(sc);
1142 		sc->sc_flags &= ~RAL_INPUT_RUNNING;
1143 
1144 skip:		desc->flags |= htole32(RT2661_RX_BUSY);
1145 
1146 		DPRINTFN(sc, 15, "rx intr idx=%u\n", sc->rxq.cur);
1147 
1148 		sc->rxq.cur = (sc->rxq.cur + 1) % RT2661_RX_RING_COUNT;
1149 	}
1150 
1151 	bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1152 	    BUS_DMASYNC_PREWRITE);
1153 }
1154 
1155 /* ARGSUSED */
1156 static void
1157 rt2661_mcu_beacon_expire(struct rt2661_softc *sc)
1158 {
1159 	/* do nothing */
1160 }
1161 
1162 static void
1163 rt2661_mcu_wakeup(struct rt2661_softc *sc)
1164 {
1165 	RAL_WRITE(sc, RT2661_MAC_CSR11, 5 << 16);
1166 
1167 	RAL_WRITE(sc, RT2661_SOFT_RESET_CSR, 0x7);
1168 	RAL_WRITE(sc, RT2661_IO_CNTL_CSR, 0x18);
1169 	RAL_WRITE(sc, RT2661_PCI_USEC_CSR, 0x20);
1170 
1171 	/* send wakeup command to MCU */
1172 	rt2661_tx_cmd(sc, RT2661_MCU_CMD_WAKEUP, 0);
1173 }
1174 
1175 static void
1176 rt2661_mcu_cmd_intr(struct rt2661_softc *sc)
1177 {
1178 	RAL_READ(sc, RT2661_M2H_CMD_DONE_CSR);
1179 	RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
1180 }
1181 
1182 void
1183 rt2661_intr(void *arg)
1184 {
1185 	struct rt2661_softc *sc = arg;
1186 	struct ifnet *ifp = sc->sc_ifp;
1187 	uint32_t r1, r2;
1188 
1189 	RAL_LOCK(sc);
1190 
1191 	/* disable MAC and MCU interrupts */
1192 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffff7f);
1193 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
1194 
1195 	/* don't re-enable interrupts if we're shutting down */
1196 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
1197 		RAL_UNLOCK(sc);
1198 		return;
1199 	}
1200 
1201 	r1 = RAL_READ(sc, RT2661_INT_SOURCE_CSR);
1202 	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, r1);
1203 
1204 	r2 = RAL_READ(sc, RT2661_MCU_INT_SOURCE_CSR);
1205 	RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, r2);
1206 
1207 	if (r1 & RT2661_MGT_DONE)
1208 		rt2661_tx_dma_intr(sc, &sc->mgtq);
1209 
1210 	if (r1 & RT2661_RX_DONE)
1211 		rt2661_rx_intr(sc);
1212 
1213 	if (r1 & RT2661_TX0_DMA_DONE)
1214 		rt2661_tx_dma_intr(sc, &sc->txq[0]);
1215 
1216 	if (r1 & RT2661_TX1_DMA_DONE)
1217 		rt2661_tx_dma_intr(sc, &sc->txq[1]);
1218 
1219 	if (r1 & RT2661_TX2_DMA_DONE)
1220 		rt2661_tx_dma_intr(sc, &sc->txq[2]);
1221 
1222 	if (r1 & RT2661_TX3_DMA_DONE)
1223 		rt2661_tx_dma_intr(sc, &sc->txq[3]);
1224 
1225 	if (r1 & RT2661_TX_DONE)
1226 		rt2661_tx_intr(sc);
1227 
1228 	if (r2 & RT2661_MCU_CMD_DONE)
1229 		rt2661_mcu_cmd_intr(sc);
1230 
1231 	if (r2 & RT2661_MCU_BEACON_EXPIRE)
1232 		rt2661_mcu_beacon_expire(sc);
1233 
1234 	if (r2 & RT2661_MCU_WAKEUP)
1235 		rt2661_mcu_wakeup(sc);
1236 
1237 	/* re-enable MAC and MCU interrupts */
1238 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
1239 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
1240 
1241 	RAL_UNLOCK(sc);
1242 }
1243 
1244 static uint8_t
1245 rt2661_plcp_signal(int rate)
1246 {
1247 	switch (rate) {
1248 	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1249 	case 12:	return 0xb;
1250 	case 18:	return 0xf;
1251 	case 24:	return 0xa;
1252 	case 36:	return 0xe;
1253 	case 48:	return 0x9;
1254 	case 72:	return 0xd;
1255 	case 96:	return 0x8;
1256 	case 108:	return 0xc;
1257 
1258 	/* CCK rates (NB: not IEEE std, device-specific) */
1259 	case 2:		return 0x0;
1260 	case 4:		return 0x1;
1261 	case 11:	return 0x2;
1262 	case 22:	return 0x3;
1263 	}
1264 	return 0xff;		/* XXX unsupported/unknown rate */
1265 }
1266 
1267 static void
1268 rt2661_setup_tx_desc(struct rt2661_softc *sc, struct rt2661_tx_desc *desc,
1269     uint32_t flags, uint16_t xflags, int len, int rate,
1270     const bus_dma_segment_t *segs, int nsegs, int ac)
1271 {
1272 	struct ifnet *ifp = sc->sc_ifp;
1273 	struct ieee80211com *ic = ifp->if_l2com;
1274 	uint16_t plcp_length;
1275 	int i, remainder;
1276 
1277 	desc->flags = htole32(flags);
1278 	desc->flags |= htole32(len << 16);
1279 	desc->flags |= htole32(RT2661_TX_BUSY | RT2661_TX_VALID);
1280 
1281 	desc->xflags = htole16(xflags);
1282 	desc->xflags |= htole16(nsegs << 13);
1283 
1284 	desc->wme = htole16(
1285 	    RT2661_QID(ac) |
1286 	    RT2661_AIFSN(2) |
1287 	    RT2661_LOGCWMIN(4) |
1288 	    RT2661_LOGCWMAX(10));
1289 
1290 	/*
1291 	 * Remember in which queue this frame was sent. This field is driver
1292 	 * private data only. It will be made available by the NIC in STA_CSR4
1293 	 * on Tx interrupts.
1294 	 */
1295 	desc->qid = ac;
1296 
1297 	/* setup PLCP fields */
1298 	desc->plcp_signal  = rt2661_plcp_signal(rate);
1299 	desc->plcp_service = 4;
1300 
1301 	len += IEEE80211_CRC_LEN;
1302 	if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM) {
1303 		desc->flags |= htole32(RT2661_TX_OFDM);
1304 
1305 		plcp_length = len & 0xfff;
1306 		desc->plcp_length_hi = plcp_length >> 6;
1307 		desc->plcp_length_lo = plcp_length & 0x3f;
1308 	} else {
1309 		plcp_length = (16 * len + rate - 1) / rate;
1310 		if (rate == 22) {
1311 			remainder = (16 * len) % 22;
1312 			if (remainder != 0 && remainder < 7)
1313 				desc->plcp_service |= RT2661_PLCP_LENGEXT;
1314 		}
1315 		desc->plcp_length_hi = plcp_length >> 8;
1316 		desc->plcp_length_lo = plcp_length & 0xff;
1317 
1318 		if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1319 			desc->plcp_signal |= 0x08;
1320 	}
1321 
1322 	/* RT2x61 supports scatter with up to 5 segments */
1323 	for (i = 0; i < nsegs; i++) {
1324 		desc->addr[i] = htole32(segs[i].ds_addr);
1325 		desc->len [i] = htole16(segs[i].ds_len);
1326 	}
1327 }
1328 
1329 static int
1330 rt2661_tx_mgt(struct rt2661_softc *sc, struct mbuf *m0,
1331     struct ieee80211_node *ni)
1332 {
1333 	struct ieee80211vap *vap = ni->ni_vap;
1334 	struct ieee80211com *ic = ni->ni_ic;
1335 	struct ifnet *ifp = sc->sc_ifp;
1336 	struct rt2661_tx_desc *desc;
1337 	struct rt2661_tx_data *data;
1338 	struct ieee80211_frame *wh;
1339 	struct ieee80211_key *k;
1340 	bus_dma_segment_t segs[RT2661_MAX_SCATTER];
1341 	uint16_t dur;
1342 	uint32_t flags = 0;	/* XXX HWSEQ */
1343 	int nsegs, rate, error;
1344 
1345 	desc = &sc->mgtq.desc[sc->mgtq.cur];
1346 	data = &sc->mgtq.data[sc->mgtq.cur];
1347 
1348 	rate = vap->iv_txparms[ieee80211_chan2mode(ic->ic_curchan)].mgmtrate;
1349 
1350 	wh = mtod(m0, struct ieee80211_frame *);
1351 
1352 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1353 		k = ieee80211_crypto_encap(ni, m0);
1354 		if (k == NULL) {
1355 			m_freem(m0);
1356 			return ENOBUFS;
1357 		}
1358 	}
1359 
1360 	error = bus_dmamap_load_mbuf_sg(sc->mgtq.data_dmat, data->map, m0,
1361 	    segs, &nsegs, 0);
1362 	if (error != 0) {
1363 		device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1364 		    error);
1365 		m_freem(m0);
1366 		return error;
1367 	}
1368 
1369 	if (bpf_peers_present(ifp->if_bpf)) {
1370 		struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1371 
1372 		tap->wt_flags = 0;
1373 		tap->wt_rate = rate;
1374 
1375 		bpf_mtap2(ifp->if_bpf, tap, sc->sc_txtap_len, m0);
1376 	}
1377 
1378 	data->m = m0;
1379 	data->ni = ni;
1380 	/* management frames are not taken into account for amrr */
1381 	data->rix = IEEE80211_FIXED_RATE_NONE;
1382 
1383 	wh = mtod(m0, struct ieee80211_frame *);
1384 
1385 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1386 		flags |= RT2661_TX_NEED_ACK;
1387 
1388 		dur = ieee80211_ack_duration(ic->ic_rt,
1389 		    rate, ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1390 		*(uint16_t *)wh->i_dur = htole16(dur);
1391 
1392 		/* tell hardware to add timestamp in probe responses */
1393 		if ((wh->i_fc[0] &
1394 		    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1395 		    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1396 			flags |= RT2661_TX_TIMESTAMP;
1397 	}
1398 
1399 	rt2661_setup_tx_desc(sc, desc, flags, 0 /* XXX HWSEQ */,
1400 	    m0->m_pkthdr.len, rate, segs, nsegs, RT2661_QID_MGT);
1401 
1402 	bus_dmamap_sync(sc->mgtq.data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1403 	bus_dmamap_sync(sc->mgtq.desc_dmat, sc->mgtq.desc_map,
1404 	    BUS_DMASYNC_PREWRITE);
1405 
1406 	DPRINTFN(sc, 10, "sending mgt frame len=%u idx=%u rate=%u\n",
1407 	    m0->m_pkthdr.len, sc->mgtq.cur, rate);
1408 
1409 	/* kick mgt */
1410 	sc->mgtq.queued++;
1411 	sc->mgtq.cur = (sc->mgtq.cur + 1) % RT2661_MGT_RING_COUNT;
1412 	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, RT2661_KICK_MGT);
1413 
1414 	return 0;
1415 }
1416 
1417 static int
1418 rt2661_sendprot(struct rt2661_softc *sc, int ac,
1419     const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate)
1420 {
1421 	struct ieee80211com *ic = ni->ni_ic;
1422 	struct rt2661_tx_ring *txq = &sc->txq[ac];
1423 	const struct ieee80211_frame *wh;
1424 	struct rt2661_tx_desc *desc;
1425 	struct rt2661_tx_data *data;
1426 	struct mbuf *mprot;
1427 	int protrate, ackrate, pktlen, flags, isshort, error;
1428 	uint16_t dur;
1429 	bus_dma_segment_t segs[RT2661_MAX_SCATTER];
1430 	int nsegs;
1431 
1432 	KASSERT(prot == IEEE80211_PROT_RTSCTS || prot == IEEE80211_PROT_CTSONLY,
1433 	    ("protection %d", prot));
1434 
1435 	wh = mtod(m, const struct ieee80211_frame *);
1436 	pktlen = m->m_pkthdr.len + IEEE80211_CRC_LEN;
1437 
1438 	protrate = ieee80211_ctl_rate(ic->ic_rt, rate);
1439 	ackrate = ieee80211_ack_rate(ic->ic_rt, rate);
1440 
1441 	isshort = (ic->ic_flags & IEEE80211_F_SHPREAMBLE) != 0;
1442 	dur = ieee80211_compute_duration(ic->ic_rt, pktlen, rate, isshort)
1443 	    + ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1444 	flags = RT2661_TX_MORE_FRAG;
1445 	if (prot == IEEE80211_PROT_RTSCTS) {
1446 		/* NB: CTS is the same size as an ACK */
1447 		dur += ieee80211_ack_duration(ic->ic_rt, rate, isshort);
1448 		flags |= RT2661_TX_NEED_ACK;
1449 		mprot = ieee80211_alloc_rts(ic, wh->i_addr1, wh->i_addr2, dur);
1450 	} else {
1451 		mprot = ieee80211_alloc_cts(ic, ni->ni_vap->iv_myaddr, dur);
1452 	}
1453 	if (mprot == NULL) {
1454 		/* XXX stat + msg */
1455 		return ENOBUFS;
1456 	}
1457 
1458 	data = &txq->data[txq->cur];
1459 	desc = &txq->desc[txq->cur];
1460 
1461 	error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, mprot, segs,
1462 	    &nsegs, 0);
1463 	if (error != 0) {
1464 		device_printf(sc->sc_dev,
1465 		    "could not map mbuf (error %d)\n", error);
1466 		m_freem(mprot);
1467 		return error;
1468 	}
1469 
1470 	data->m = mprot;
1471 	data->ni = ieee80211_ref_node(ni);
1472 	/* ctl frames are not taken into account for amrr */
1473 	data->rix = IEEE80211_FIXED_RATE_NONE;
1474 
1475 	rt2661_setup_tx_desc(sc, desc, flags, 0, mprot->m_pkthdr.len,
1476 	    protrate, segs, 1, ac);
1477 
1478 	bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1479 	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1480 
1481 	txq->queued++;
1482 	txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1483 
1484 	return 0;
1485 }
1486 
1487 static int
1488 rt2661_tx_data(struct rt2661_softc *sc, struct mbuf *m0,
1489     struct ieee80211_node *ni, int ac)
1490 {
1491 	struct ieee80211vap *vap = ni->ni_vap;
1492 	struct ifnet *ifp = sc->sc_ifp;
1493 	struct ieee80211com *ic = ifp->if_l2com;
1494 	struct rt2661_tx_ring *txq = &sc->txq[ac];
1495 	struct rt2661_tx_desc *desc;
1496 	struct rt2661_tx_data *data;
1497 	struct ieee80211_frame *wh;
1498 	const struct ieee80211_txparam *tp;
1499 	struct ieee80211_key *k;
1500 	const struct chanAccParams *cap;
1501 	struct mbuf *mnew;
1502 	bus_dma_segment_t segs[RT2661_MAX_SCATTER];
1503 	uint16_t dur;
1504 	uint32_t flags;
1505 	int error, nsegs, rate, noack = 0;
1506 
1507 	wh = mtod(m0, struct ieee80211_frame *);
1508 
1509 	tp = &vap->iv_txparms[ieee80211_chan2mode(ni->ni_chan)];
1510 	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1511 		rate = tp->mcastrate;
1512 	} else if (m0->m_flags & M_EAPOL) {
1513 		rate = tp->mgmtrate;
1514 	} else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
1515 		rate = tp->ucastrate;
1516 	} else {
1517 		(void) ieee80211_amrr_choose(ni, &RT2661_NODE(ni)->amrr);
1518 		rate = ni->ni_txrate;
1519 	}
1520 	rate &= IEEE80211_RATE_VAL;
1521 
1522 	if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
1523 		cap = &ic->ic_wme.wme_chanParams;
1524 		noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
1525 	}
1526 
1527 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1528 		k = ieee80211_crypto_encap(ni, m0);
1529 		if (k == NULL) {
1530 			m_freem(m0);
1531 			return ENOBUFS;
1532 		}
1533 
1534 		/* packet header may have moved, reset our local pointer */
1535 		wh = mtod(m0, struct ieee80211_frame *);
1536 	}
1537 
1538 	flags = 0;
1539 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1540 		int prot = IEEE80211_PROT_NONE;
1541 		if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold)
1542 			prot = IEEE80211_PROT_RTSCTS;
1543 		else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1544 		    ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM)
1545 			prot = ic->ic_protmode;
1546 		if (prot != IEEE80211_PROT_NONE) {
1547 			error = rt2661_sendprot(sc, ac, m0, ni, prot, rate);
1548 			if (error) {
1549 				m_freem(m0);
1550 				return error;
1551 			}
1552 			flags |= RT2661_TX_LONG_RETRY | RT2661_TX_IFS;
1553 		}
1554 	}
1555 
1556 	data = &txq->data[txq->cur];
1557 	desc = &txq->desc[txq->cur];
1558 
1559 	error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m0, segs,
1560 	    &nsegs, 0);
1561 	if (error != 0 && error != EFBIG) {
1562 		device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1563 		    error);
1564 		m_freem(m0);
1565 		return error;
1566 	}
1567 	if (error != 0) {
1568 		mnew = m_defrag(m0, M_DONTWAIT);
1569 		if (mnew == NULL) {
1570 			device_printf(sc->sc_dev,
1571 			    "could not defragment mbuf\n");
1572 			m_freem(m0);
1573 			return ENOBUFS;
1574 		}
1575 		m0 = mnew;
1576 
1577 		error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m0,
1578 		    segs, &nsegs, 0);
1579 		if (error != 0) {
1580 			device_printf(sc->sc_dev,
1581 			    "could not map mbuf (error %d)\n", error);
1582 			m_freem(m0);
1583 			return error;
1584 		}
1585 
1586 		/* packet header have moved, reset our local pointer */
1587 		wh = mtod(m0, struct ieee80211_frame *);
1588 	}
1589 
1590 	if (bpf_peers_present(ifp->if_bpf)) {
1591 		struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1592 
1593 		tap->wt_flags = 0;
1594 		tap->wt_rate = rate;
1595 		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1596 		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1597 
1598 		bpf_mtap2(ifp->if_bpf, tap, sc->sc_txtap_len, m0);
1599 	}
1600 
1601 	data->m = m0;
1602 	data->ni = ni;
1603 
1604 	/* remember link conditions for rate adaptation algorithm */
1605 	if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE) {
1606 		data->rix = ni->ni_txrate;
1607 		/* XXX probably need last rssi value and not avg */
1608 		data->rssi = ic->ic_node_getrssi(ni);
1609 	} else
1610 		data->rix = IEEE80211_FIXED_RATE_NONE;
1611 
1612 	if (!noack && !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1613 		flags |= RT2661_TX_NEED_ACK;
1614 
1615 		dur = ieee80211_ack_duration(ic->ic_rt,
1616 		    rate, ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1617 		*(uint16_t *)wh->i_dur = htole16(dur);
1618 	}
1619 
1620 	rt2661_setup_tx_desc(sc, desc, flags, 0, m0->m_pkthdr.len, rate, segs,
1621 	    nsegs, ac);
1622 
1623 	bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1624 	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1625 
1626 	DPRINTFN(sc, 10, "sending data frame len=%u idx=%u rate=%u\n",
1627 	    m0->m_pkthdr.len, txq->cur, rate);
1628 
1629 	/* kick Tx */
1630 	txq->queued++;
1631 	txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1632 	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 1 << ac);
1633 
1634 	return 0;
1635 }
1636 
1637 static void
1638 rt2661_start_locked(struct ifnet *ifp)
1639 {
1640 	struct rt2661_softc *sc = ifp->if_softc;
1641 	struct mbuf *m;
1642 	struct ieee80211_node *ni;
1643 	int ac;
1644 
1645 	RAL_LOCK_ASSERT(sc);
1646 
1647 	/* prevent management frames from being sent if we're not ready */
1648 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING) || sc->sc_invalid)
1649 		return;
1650 
1651 	for (;;) {
1652 		IFQ_DRV_DEQUEUE(&ifp->if_snd, m);
1653 		if (m == NULL)
1654 			break;
1655 
1656 		ac = M_WME_GETAC(m);
1657 		if (sc->txq[ac].queued >= RT2661_TX_RING_COUNT - 1) {
1658 			/* there is no place left in this ring */
1659 			IFQ_DRV_PREPEND(&ifp->if_snd, m);
1660 			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1661 			break;
1662 		}
1663 		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1664 		if (rt2661_tx_data(sc, m, ni, ac) != 0) {
1665 			ieee80211_free_node(ni);
1666 			ifp->if_oerrors++;
1667 			break;
1668 		}
1669 
1670 		sc->sc_tx_timer = 5;
1671 	}
1672 }
1673 
1674 static void
1675 rt2661_start(struct ifnet *ifp)
1676 {
1677 	struct rt2661_softc *sc = ifp->if_softc;
1678 
1679 	RAL_LOCK(sc);
1680 	rt2661_start_locked(ifp);
1681 	RAL_UNLOCK(sc);
1682 }
1683 
1684 static int
1685 rt2661_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
1686 	const struct ieee80211_bpf_params *params)
1687 {
1688 	struct ieee80211com *ic = ni->ni_ic;
1689 	struct ifnet *ifp = ic->ic_ifp;
1690 	struct rt2661_softc *sc = ifp->if_softc;
1691 
1692 	RAL_LOCK(sc);
1693 
1694 	/* prevent management frames from being sent if we're not ready */
1695 	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
1696 		RAL_UNLOCK(sc);
1697 		m_freem(m);
1698 		ieee80211_free_node(ni);
1699 		return ENETDOWN;
1700 	}
1701 	if (sc->mgtq.queued >= RT2661_MGT_RING_COUNT) {
1702 		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1703 		RAL_UNLOCK(sc);
1704 		m_freem(m);
1705 		ieee80211_free_node(ni);
1706 		return ENOBUFS;		/* XXX */
1707 	}
1708 
1709 	ifp->if_opackets++;
1710 
1711 	/*
1712 	 * Legacy path; interpret frame contents to decide
1713 	 * precisely how to send the frame.
1714 	 * XXX raw path
1715 	 */
1716 	if (rt2661_tx_mgt(sc, m, ni) != 0)
1717 		goto bad;
1718 	sc->sc_tx_timer = 5;
1719 
1720 	RAL_UNLOCK(sc);
1721 
1722 	return 0;
1723 bad:
1724 	ifp->if_oerrors++;
1725 	ieee80211_free_node(ni);
1726 	RAL_UNLOCK(sc);
1727 	return EIO;		/* XXX */
1728 }
1729 
1730 static void
1731 rt2661_watchdog(void *arg)
1732 {
1733 	struct rt2661_softc *sc = (struct rt2661_softc *)arg;
1734 	struct ifnet *ifp = sc->sc_ifp;
1735 
1736 	RAL_LOCK_ASSERT(sc);
1737 
1738 	KASSERT(ifp->if_drv_flags & IFF_DRV_RUNNING, ("not running"));
1739 
1740 	if (sc->sc_invalid)		/* card ejected */
1741 		return;
1742 
1743 	if (sc->sc_tx_timer > 0 && --sc->sc_tx_timer == 0) {
1744 		if_printf(ifp, "device timeout\n");
1745 		rt2661_init_locked(sc);
1746 		ifp->if_oerrors++;
1747 		/* NB: callout is reset in rt2661_init() */
1748 		return;
1749 	}
1750 	callout_reset(&sc->watchdog_ch, hz, rt2661_watchdog, sc);
1751 }
1752 
1753 static int
1754 rt2661_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1755 {
1756 	struct rt2661_softc *sc = ifp->if_softc;
1757 	struct ieee80211com *ic = ifp->if_l2com;
1758 	struct ifreq *ifr = (struct ifreq *) data;
1759 	int error = 0, startall = 0;
1760 
1761 	switch (cmd) {
1762 	case SIOCSIFFLAGS:
1763 		RAL_LOCK(sc);
1764 		if (ifp->if_flags & IFF_UP) {
1765 			if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1766 				rt2661_init_locked(sc);
1767 				startall = 1;
1768 			} else
1769 				rt2661_update_promisc(ifp);
1770 		} else {
1771 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1772 				rt2661_stop_locked(sc);
1773 		}
1774 		RAL_UNLOCK(sc);
1775 		if (startall)
1776 			ieee80211_start_all(ic);
1777 		break;
1778 	case SIOCGIFMEDIA:
1779 		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
1780 		break;
1781 	case SIOCGIFADDR:
1782 		error = ether_ioctl(ifp, cmd, data);
1783 		break;
1784 	default:
1785 		error = EINVAL;
1786 		break;
1787 	}
1788 	return error;
1789 }
1790 
1791 static void
1792 rt2661_bbp_write(struct rt2661_softc *sc, uint8_t reg, uint8_t val)
1793 {
1794 	uint32_t tmp;
1795 	int ntries;
1796 
1797 	for (ntries = 0; ntries < 100; ntries++) {
1798 		if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
1799 			break;
1800 		DELAY(1);
1801 	}
1802 	if (ntries == 100) {
1803 		device_printf(sc->sc_dev, "could not write to BBP\n");
1804 		return;
1805 	}
1806 
1807 	tmp = RT2661_BBP_BUSY | (reg & 0x7f) << 8 | val;
1808 	RAL_WRITE(sc, RT2661_PHY_CSR3, tmp);
1809 
1810 	DPRINTFN(sc, 15, "BBP R%u <- 0x%02x\n", reg, val);
1811 }
1812 
1813 static uint8_t
1814 rt2661_bbp_read(struct rt2661_softc *sc, uint8_t reg)
1815 {
1816 	uint32_t val;
1817 	int ntries;
1818 
1819 	for (ntries = 0; ntries < 100; ntries++) {
1820 		if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
1821 			break;
1822 		DELAY(1);
1823 	}
1824 	if (ntries == 100) {
1825 		device_printf(sc->sc_dev, "could not read from BBP\n");
1826 		return 0;
1827 	}
1828 
1829 	val = RT2661_BBP_BUSY | RT2661_BBP_READ | reg << 8;
1830 	RAL_WRITE(sc, RT2661_PHY_CSR3, val);
1831 
1832 	for (ntries = 0; ntries < 100; ntries++) {
1833 		val = RAL_READ(sc, RT2661_PHY_CSR3);
1834 		if (!(val & RT2661_BBP_BUSY))
1835 			return val & 0xff;
1836 		DELAY(1);
1837 	}
1838 
1839 	device_printf(sc->sc_dev, "could not read from BBP\n");
1840 	return 0;
1841 }
1842 
1843 static void
1844 rt2661_rf_write(struct rt2661_softc *sc, uint8_t reg, uint32_t val)
1845 {
1846 	uint32_t tmp;
1847 	int ntries;
1848 
1849 	for (ntries = 0; ntries < 100; ntries++) {
1850 		if (!(RAL_READ(sc, RT2661_PHY_CSR4) & RT2661_RF_BUSY))
1851 			break;
1852 		DELAY(1);
1853 	}
1854 	if (ntries == 100) {
1855 		device_printf(sc->sc_dev, "could not write to RF\n");
1856 		return;
1857 	}
1858 
1859 	tmp = RT2661_RF_BUSY | RT2661_RF_21BIT | (val & 0x1fffff) << 2 |
1860 	    (reg & 3);
1861 	RAL_WRITE(sc, RT2661_PHY_CSR4, tmp);
1862 
1863 	/* remember last written value in sc */
1864 	sc->rf_regs[reg] = val;
1865 
1866 	DPRINTFN(sc, 15, "RF R[%u] <- 0x%05x\n", reg & 3, val & 0x1fffff);
1867 }
1868 
1869 static int
1870 rt2661_tx_cmd(struct rt2661_softc *sc, uint8_t cmd, uint16_t arg)
1871 {
1872 	if (RAL_READ(sc, RT2661_H2M_MAILBOX_CSR) & RT2661_H2M_BUSY)
1873 		return EIO;	/* there is already a command pending */
1874 
1875 	RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR,
1876 	    RT2661_H2M_BUSY | RT2661_TOKEN_NO_INTR << 16 | arg);
1877 
1878 	RAL_WRITE(sc, RT2661_HOST_CMD_CSR, RT2661_KICK_CMD | cmd);
1879 
1880 	return 0;
1881 }
1882 
1883 static void
1884 rt2661_select_antenna(struct rt2661_softc *sc)
1885 {
1886 	uint8_t bbp4, bbp77;
1887 	uint32_t tmp;
1888 
1889 	bbp4  = rt2661_bbp_read(sc,  4);
1890 	bbp77 = rt2661_bbp_read(sc, 77);
1891 
1892 	/* TBD */
1893 
1894 	/* make sure Rx is disabled before switching antenna */
1895 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
1896 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
1897 
1898 	rt2661_bbp_write(sc,  4, bbp4);
1899 	rt2661_bbp_write(sc, 77, bbp77);
1900 
1901 	/* restore Rx filter */
1902 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
1903 }
1904 
1905 /*
1906  * Enable multi-rate retries for frames sent at OFDM rates.
1907  * In 802.11b/g mode, allow fallback to CCK rates.
1908  */
1909 static void
1910 rt2661_enable_mrr(struct rt2661_softc *sc)
1911 {
1912 	struct ifnet *ifp = sc->sc_ifp;
1913 	struct ieee80211com *ic = ifp->if_l2com;
1914 	uint32_t tmp;
1915 
1916 	tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
1917 
1918 	tmp &= ~RT2661_MRR_CCK_FALLBACK;
1919 	if (!IEEE80211_IS_CHAN_5GHZ(ic->ic_bsschan))
1920 		tmp |= RT2661_MRR_CCK_FALLBACK;
1921 	tmp |= RT2661_MRR_ENABLED;
1922 
1923 	RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
1924 }
1925 
1926 static void
1927 rt2661_set_txpreamble(struct rt2661_softc *sc)
1928 {
1929 	struct ifnet *ifp = sc->sc_ifp;
1930 	struct ieee80211com *ic = ifp->if_l2com;
1931 	uint32_t tmp;
1932 
1933 	tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
1934 
1935 	tmp &= ~RT2661_SHORT_PREAMBLE;
1936 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1937 		tmp |= RT2661_SHORT_PREAMBLE;
1938 
1939 	RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
1940 }
1941 
1942 static void
1943 rt2661_set_basicrates(struct rt2661_softc *sc,
1944     const struct ieee80211_rateset *rs)
1945 {
1946 #define RV(r)	((r) & IEEE80211_RATE_VAL)
1947 	struct ifnet *ifp = sc->sc_ifp;
1948 	struct ieee80211com *ic = ifp->if_l2com;
1949 	uint32_t mask = 0;
1950 	uint8_t rate;
1951 	int i, j;
1952 
1953 	for (i = 0; i < rs->rs_nrates; i++) {
1954 		rate = rs->rs_rates[i];
1955 
1956 		if (!(rate & IEEE80211_RATE_BASIC))
1957 			continue;
1958 
1959 		/*
1960 		 * Find h/w rate index.  We know it exists because the rate
1961 		 * set has already been negotiated.
1962 		 */
1963 		for (j = 0; ic->ic_sup_rates[IEEE80211_MODE_11G].rs_rates[j] != RV(rate); j++);
1964 
1965 		mask |= 1 << j;
1966 	}
1967 
1968 	RAL_WRITE(sc, RT2661_TXRX_CSR5, mask);
1969 
1970 	DPRINTF(sc, "Setting basic rate mask to 0x%x\n", mask);
1971 #undef RV
1972 }
1973 
1974 /*
1975  * Reprogram MAC/BBP to switch to a new band.  Values taken from the reference
1976  * driver.
1977  */
1978 static void
1979 rt2661_select_band(struct rt2661_softc *sc, struct ieee80211_channel *c)
1980 {
1981 	uint8_t bbp17, bbp35, bbp96, bbp97, bbp98, bbp104;
1982 	uint32_t tmp;
1983 
1984 	/* update all BBP registers that depend on the band */
1985 	bbp17 = 0x20; bbp96 = 0x48; bbp104 = 0x2c;
1986 	bbp35 = 0x50; bbp97 = 0x48; bbp98  = 0x48;
1987 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
1988 		bbp17 += 0x08; bbp96 += 0x10; bbp104 += 0x0c;
1989 		bbp35 += 0x10; bbp97 += 0x10; bbp98  += 0x10;
1990 	}
1991 	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
1992 	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
1993 		bbp17 += 0x10; bbp96 += 0x10; bbp104 += 0x10;
1994 	}
1995 
1996 	rt2661_bbp_write(sc,  17, bbp17);
1997 	rt2661_bbp_write(sc,  96, bbp96);
1998 	rt2661_bbp_write(sc, 104, bbp104);
1999 
2000 	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2001 	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2002 		rt2661_bbp_write(sc, 75, 0x80);
2003 		rt2661_bbp_write(sc, 86, 0x80);
2004 		rt2661_bbp_write(sc, 88, 0x80);
2005 	}
2006 
2007 	rt2661_bbp_write(sc, 35, bbp35);
2008 	rt2661_bbp_write(sc, 97, bbp97);
2009 	rt2661_bbp_write(sc, 98, bbp98);
2010 
2011 	tmp = RAL_READ(sc, RT2661_PHY_CSR0);
2012 	tmp &= ~(RT2661_PA_PE_2GHZ | RT2661_PA_PE_5GHZ);
2013 	if (IEEE80211_IS_CHAN_2GHZ(c))
2014 		tmp |= RT2661_PA_PE_2GHZ;
2015 	else
2016 		tmp |= RT2661_PA_PE_5GHZ;
2017 	RAL_WRITE(sc, RT2661_PHY_CSR0, tmp);
2018 }
2019 
2020 static void
2021 rt2661_set_chan(struct rt2661_softc *sc, struct ieee80211_channel *c)
2022 {
2023 	struct ifnet *ifp = sc->sc_ifp;
2024 	struct ieee80211com *ic = ifp->if_l2com;
2025 	const struct rfprog *rfprog;
2026 	uint8_t bbp3, bbp94 = RT2661_BBPR94_DEFAULT;
2027 	int8_t power;
2028 	u_int i, chan;
2029 
2030 	chan = ieee80211_chan2ieee(ic, c);
2031 	KASSERT(chan != 0 && chan != IEEE80211_CHAN_ANY, ("chan 0x%x", chan));
2032 
2033 	/* select the appropriate RF settings based on what EEPROM says */
2034 	rfprog = (sc->rfprog == 0) ? rt2661_rf5225_1 : rt2661_rf5225_2;
2035 
2036 	/* find the settings for this channel (we know it exists) */
2037 	for (i = 0; rfprog[i].chan != chan; i++);
2038 
2039 	power = sc->txpow[i];
2040 	if (power < 0) {
2041 		bbp94 += power;
2042 		power = 0;
2043 	} else if (power > 31) {
2044 		bbp94 += power - 31;
2045 		power = 31;
2046 	}
2047 
2048 	/*
2049 	 * If we are switching from the 2GHz band to the 5GHz band or
2050 	 * vice-versa, BBP registers need to be reprogrammed.
2051 	 */
2052 	if (c->ic_flags != sc->sc_curchan->ic_flags) {
2053 		rt2661_select_band(sc, c);
2054 		rt2661_select_antenna(sc);
2055 	}
2056 	sc->sc_curchan = c;
2057 
2058 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2059 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2060 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2061 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2062 
2063 	DELAY(200);
2064 
2065 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2066 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2067 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7 | 1);
2068 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2069 
2070 	DELAY(200);
2071 
2072 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2073 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2074 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2075 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2076 
2077 	/* enable smart mode for MIMO-capable RFs */
2078 	bbp3 = rt2661_bbp_read(sc, 3);
2079 
2080 	bbp3 &= ~RT2661_SMART_MODE;
2081 	if (sc->rf_rev == RT2661_RF_5325 || sc->rf_rev == RT2661_RF_2529)
2082 		bbp3 |= RT2661_SMART_MODE;
2083 
2084 	rt2661_bbp_write(sc, 3, bbp3);
2085 
2086 	if (bbp94 != RT2661_BBPR94_DEFAULT)
2087 		rt2661_bbp_write(sc, 94, bbp94);
2088 
2089 	/* 5GHz radio needs a 1ms delay here */
2090 	if (IEEE80211_IS_CHAN_5GHZ(c))
2091 		DELAY(1000);
2092 }
2093 
2094 static void
2095 rt2661_set_bssid(struct rt2661_softc *sc, const uint8_t *bssid)
2096 {
2097 	uint32_t tmp;
2098 
2099 	tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24;
2100 	RAL_WRITE(sc, RT2661_MAC_CSR4, tmp);
2101 
2102 	tmp = bssid[4] | bssid[5] << 8 | RT2661_ONE_BSSID << 16;
2103 	RAL_WRITE(sc, RT2661_MAC_CSR5, tmp);
2104 }
2105 
2106 static void
2107 rt2661_set_macaddr(struct rt2661_softc *sc, const uint8_t *addr)
2108 {
2109 	uint32_t tmp;
2110 
2111 	tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24;
2112 	RAL_WRITE(sc, RT2661_MAC_CSR2, tmp);
2113 
2114 	tmp = addr[4] | addr[5] << 8;
2115 	RAL_WRITE(sc, RT2661_MAC_CSR3, tmp);
2116 }
2117 
2118 static void
2119 rt2661_update_promisc(struct ifnet *ifp)
2120 {
2121 	struct rt2661_softc *sc = ifp->if_softc;
2122 	uint32_t tmp;
2123 
2124 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2125 
2126 	tmp &= ~RT2661_DROP_NOT_TO_ME;
2127 	if (!(ifp->if_flags & IFF_PROMISC))
2128 		tmp |= RT2661_DROP_NOT_TO_ME;
2129 
2130 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2131 
2132 	DPRINTF(sc, "%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
2133 	    "entering" : "leaving");
2134 }
2135 
2136 /*
2137  * Update QoS (802.11e) settings for each h/w Tx ring.
2138  */
2139 static int
2140 rt2661_wme_update(struct ieee80211com *ic)
2141 {
2142 	struct rt2661_softc *sc = ic->ic_ifp->if_softc;
2143 	const struct wmeParams *wmep;
2144 
2145 	wmep = ic->ic_wme.wme_chanParams.cap_wmeParams;
2146 
2147 	/* XXX: not sure about shifts. */
2148 	/* XXX: the reference driver plays with AC_VI settings too. */
2149 
2150 	/* update TxOp */
2151 	RAL_WRITE(sc, RT2661_AC_TXOP_CSR0,
2152 	    wmep[WME_AC_BE].wmep_txopLimit << 16 |
2153 	    wmep[WME_AC_BK].wmep_txopLimit);
2154 	RAL_WRITE(sc, RT2661_AC_TXOP_CSR1,
2155 	    wmep[WME_AC_VI].wmep_txopLimit << 16 |
2156 	    wmep[WME_AC_VO].wmep_txopLimit);
2157 
2158 	/* update CWmin */
2159 	RAL_WRITE(sc, RT2661_CWMIN_CSR,
2160 	    wmep[WME_AC_BE].wmep_logcwmin << 12 |
2161 	    wmep[WME_AC_BK].wmep_logcwmin <<  8 |
2162 	    wmep[WME_AC_VI].wmep_logcwmin <<  4 |
2163 	    wmep[WME_AC_VO].wmep_logcwmin);
2164 
2165 	/* update CWmax */
2166 	RAL_WRITE(sc, RT2661_CWMAX_CSR,
2167 	    wmep[WME_AC_BE].wmep_logcwmax << 12 |
2168 	    wmep[WME_AC_BK].wmep_logcwmax <<  8 |
2169 	    wmep[WME_AC_VI].wmep_logcwmax <<  4 |
2170 	    wmep[WME_AC_VO].wmep_logcwmax);
2171 
2172 	/* update Aifsn */
2173 	RAL_WRITE(sc, RT2661_AIFSN_CSR,
2174 	    wmep[WME_AC_BE].wmep_aifsn << 12 |
2175 	    wmep[WME_AC_BK].wmep_aifsn <<  8 |
2176 	    wmep[WME_AC_VI].wmep_aifsn <<  4 |
2177 	    wmep[WME_AC_VO].wmep_aifsn);
2178 
2179 	return 0;
2180 }
2181 
2182 static void
2183 rt2661_update_slot(struct ifnet *ifp)
2184 {
2185 	struct rt2661_softc *sc = ifp->if_softc;
2186 	struct ieee80211com *ic = ifp->if_l2com;
2187 	uint8_t slottime;
2188 	uint32_t tmp;
2189 
2190 	slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
2191 
2192 	tmp = RAL_READ(sc, RT2661_MAC_CSR9);
2193 	tmp = (tmp & ~0xff) | slottime;
2194 	RAL_WRITE(sc, RT2661_MAC_CSR9, tmp);
2195 }
2196 
2197 static const char *
2198 rt2661_get_rf(int rev)
2199 {
2200 	switch (rev) {
2201 	case RT2661_RF_5225:	return "RT5225";
2202 	case RT2661_RF_5325:	return "RT5325 (MIMO XR)";
2203 	case RT2661_RF_2527:	return "RT2527";
2204 	case RT2661_RF_2529:	return "RT2529 (MIMO XR)";
2205 	default:		return "unknown";
2206 	}
2207 }
2208 
2209 static void
2210 rt2661_read_eeprom(struct rt2661_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
2211 {
2212 	uint16_t val;
2213 	int i;
2214 
2215 	/* read MAC address */
2216 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC01);
2217 	macaddr[0] = val & 0xff;
2218 	macaddr[1] = val >> 8;
2219 
2220 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC23);
2221 	macaddr[2] = val & 0xff;
2222 	macaddr[3] = val >> 8;
2223 
2224 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC45);
2225 	macaddr[4] = val & 0xff;
2226 	macaddr[5] = val >> 8;
2227 
2228 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_ANTENNA);
2229 	/* XXX: test if different from 0xffff? */
2230 	sc->rf_rev   = (val >> 11) & 0x1f;
2231 	sc->hw_radio = (val >> 10) & 0x1;
2232 	sc->rx_ant   = (val >> 4)  & 0x3;
2233 	sc->tx_ant   = (val >> 2)  & 0x3;
2234 	sc->nb_ant   = val & 0x3;
2235 
2236 	DPRINTF(sc, "RF revision=%d\n", sc->rf_rev);
2237 
2238 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_CONFIG2);
2239 	sc->ext_5ghz_lna = (val >> 6) & 0x1;
2240 	sc->ext_2ghz_lna = (val >> 4) & 0x1;
2241 
2242 	DPRINTF(sc, "External 2GHz LNA=%d\nExternal 5GHz LNA=%d\n",
2243 	    sc->ext_2ghz_lna, sc->ext_5ghz_lna);
2244 
2245 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_2GHZ_OFFSET);
2246 	if ((val & 0xff) != 0xff)
2247 		sc->rssi_2ghz_corr = (int8_t)(val & 0xff);	/* signed */
2248 
2249 	/* Only [-10, 10] is valid */
2250 	if (sc->rssi_2ghz_corr < -10 || sc->rssi_2ghz_corr > 10)
2251 		sc->rssi_2ghz_corr = 0;
2252 
2253 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_5GHZ_OFFSET);
2254 	if ((val & 0xff) != 0xff)
2255 		sc->rssi_5ghz_corr = (int8_t)(val & 0xff);	/* signed */
2256 
2257 	/* Only [-10, 10] is valid */
2258 	if (sc->rssi_5ghz_corr < -10 || sc->rssi_5ghz_corr > 10)
2259 		sc->rssi_5ghz_corr = 0;
2260 
2261 	/* adjust RSSI correction for external low-noise amplifier */
2262 	if (sc->ext_2ghz_lna)
2263 		sc->rssi_2ghz_corr -= 14;
2264 	if (sc->ext_5ghz_lna)
2265 		sc->rssi_5ghz_corr -= 14;
2266 
2267 	DPRINTF(sc, "RSSI 2GHz corr=%d\nRSSI 5GHz corr=%d\n",
2268 	    sc->rssi_2ghz_corr, sc->rssi_5ghz_corr);
2269 
2270 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_FREQ_OFFSET);
2271 	if ((val >> 8) != 0xff)
2272 		sc->rfprog = (val >> 8) & 0x3;
2273 	if ((val & 0xff) != 0xff)
2274 		sc->rffreq = val & 0xff;
2275 
2276 	DPRINTF(sc, "RF prog=%d\nRF freq=%d\n", sc->rfprog, sc->rffreq);
2277 
2278 	/* read Tx power for all a/b/g channels */
2279 	for (i = 0; i < 19; i++) {
2280 		val = rt2661_eeprom_read(sc, RT2661_EEPROM_TXPOWER + i);
2281 		sc->txpow[i * 2] = (int8_t)(val >> 8);		/* signed */
2282 		DPRINTF(sc, "Channel=%d Tx power=%d\n",
2283 		    rt2661_rf5225_1[i * 2].chan, sc->txpow[i * 2]);
2284 		sc->txpow[i * 2 + 1] = (int8_t)(val & 0xff);	/* signed */
2285 		DPRINTF(sc, "Channel=%d Tx power=%d\n",
2286 		    rt2661_rf5225_1[i * 2 + 1].chan, sc->txpow[i * 2 + 1]);
2287 	}
2288 
2289 	/* read vendor-specific BBP values */
2290 	for (i = 0; i < 16; i++) {
2291 		val = rt2661_eeprom_read(sc, RT2661_EEPROM_BBP_BASE + i);
2292 		if (val == 0 || val == 0xffff)
2293 			continue;	/* skip invalid entries */
2294 		sc->bbp_prom[i].reg = val >> 8;
2295 		sc->bbp_prom[i].val = val & 0xff;
2296 		DPRINTF(sc, "BBP R%d=%02x\n", sc->bbp_prom[i].reg,
2297 		    sc->bbp_prom[i].val);
2298 	}
2299 }
2300 
2301 static int
2302 rt2661_bbp_init(struct rt2661_softc *sc)
2303 {
2304 #define N(a)	(sizeof (a) / sizeof ((a)[0]))
2305 	int i, ntries;
2306 	uint8_t val;
2307 
2308 	/* wait for BBP to be ready */
2309 	for (ntries = 0; ntries < 100; ntries++) {
2310 		val = rt2661_bbp_read(sc, 0);
2311 		if (val != 0 && val != 0xff)
2312 			break;
2313 		DELAY(100);
2314 	}
2315 	if (ntries == 100) {
2316 		device_printf(sc->sc_dev, "timeout waiting for BBP\n");
2317 		return EIO;
2318 	}
2319 
2320 	/* initialize BBP registers to default values */
2321 	for (i = 0; i < N(rt2661_def_bbp); i++) {
2322 		rt2661_bbp_write(sc, rt2661_def_bbp[i].reg,
2323 		    rt2661_def_bbp[i].val);
2324 	}
2325 
2326 	/* write vendor-specific BBP values (from EEPROM) */
2327 	for (i = 0; i < 16; i++) {
2328 		if (sc->bbp_prom[i].reg == 0)
2329 			continue;
2330 		rt2661_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2331 	}
2332 
2333 	return 0;
2334 #undef N
2335 }
2336 
2337 static void
2338 rt2661_init_locked(struct rt2661_softc *sc)
2339 {
2340 #define N(a)	(sizeof (a) / sizeof ((a)[0]))
2341 	struct ifnet *ifp = sc->sc_ifp;
2342 	struct ieee80211com *ic = ifp->if_l2com;
2343 	uint32_t tmp, sta[3];
2344 	int i, error, ntries;
2345 
2346 	RAL_LOCK_ASSERT(sc);
2347 
2348 	if ((sc->sc_flags & RAL_FW_LOADED) == 0) {
2349 		error = rt2661_load_microcode(sc);
2350 		if (error != 0) {
2351 			if_printf(ifp,
2352 			    "%s: could not load 8051 microcode, error %d\n",
2353 			    __func__, error);
2354 			return;
2355 		}
2356 		sc->sc_flags |= RAL_FW_LOADED;
2357 	}
2358 
2359 	rt2661_stop_locked(sc);
2360 
2361 	/* initialize Tx rings */
2362 	RAL_WRITE(sc, RT2661_AC1_BASE_CSR, sc->txq[1].physaddr);
2363 	RAL_WRITE(sc, RT2661_AC0_BASE_CSR, sc->txq[0].physaddr);
2364 	RAL_WRITE(sc, RT2661_AC2_BASE_CSR, sc->txq[2].physaddr);
2365 	RAL_WRITE(sc, RT2661_AC3_BASE_CSR, sc->txq[3].physaddr);
2366 
2367 	/* initialize Mgt ring */
2368 	RAL_WRITE(sc, RT2661_MGT_BASE_CSR, sc->mgtq.physaddr);
2369 
2370 	/* initialize Rx ring */
2371 	RAL_WRITE(sc, RT2661_RX_BASE_CSR, sc->rxq.physaddr);
2372 
2373 	/* initialize Tx rings sizes */
2374 	RAL_WRITE(sc, RT2661_TX_RING_CSR0,
2375 	    RT2661_TX_RING_COUNT << 24 |
2376 	    RT2661_TX_RING_COUNT << 16 |
2377 	    RT2661_TX_RING_COUNT <<  8 |
2378 	    RT2661_TX_RING_COUNT);
2379 
2380 	RAL_WRITE(sc, RT2661_TX_RING_CSR1,
2381 	    RT2661_TX_DESC_WSIZE << 16 |
2382 	    RT2661_TX_RING_COUNT <<  8 |	/* XXX: HCCA ring unused */
2383 	    RT2661_MGT_RING_COUNT);
2384 
2385 	/* initialize Rx rings */
2386 	RAL_WRITE(sc, RT2661_RX_RING_CSR,
2387 	    RT2661_RX_DESC_BACK  << 16 |
2388 	    RT2661_RX_DESC_WSIZE <<  8 |
2389 	    RT2661_RX_RING_COUNT);
2390 
2391 	/* XXX: some magic here */
2392 	RAL_WRITE(sc, RT2661_TX_DMA_DST_CSR, 0xaa);
2393 
2394 	/* load base addresses of all 5 Tx rings (4 data + 1 mgt) */
2395 	RAL_WRITE(sc, RT2661_LOAD_TX_RING_CSR, 0x1f);
2396 
2397 	/* load base address of Rx ring */
2398 	RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 2);
2399 
2400 	/* initialize MAC registers to default values */
2401 	for (i = 0; i < N(rt2661_def_mac); i++)
2402 		RAL_WRITE(sc, rt2661_def_mac[i].reg, rt2661_def_mac[i].val);
2403 
2404 	rt2661_set_macaddr(sc, IF_LLADDR(ifp));
2405 
2406 	/* set host ready */
2407 	RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2408 	RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2409 
2410 	/* wait for BBP/RF to wakeup */
2411 	for (ntries = 0; ntries < 1000; ntries++) {
2412 		if (RAL_READ(sc, RT2661_MAC_CSR12) & 8)
2413 			break;
2414 		DELAY(1000);
2415 	}
2416 	if (ntries == 1000) {
2417 		printf("timeout waiting for BBP/RF to wakeup\n");
2418 		rt2661_stop_locked(sc);
2419 		return;
2420 	}
2421 
2422 	if (rt2661_bbp_init(sc) != 0) {
2423 		rt2661_stop_locked(sc);
2424 		return;
2425 	}
2426 
2427 	/* select default channel */
2428 	sc->sc_curchan = ic->ic_curchan;
2429 	rt2661_select_band(sc, sc->sc_curchan);
2430 	rt2661_select_antenna(sc);
2431 	rt2661_set_chan(sc, sc->sc_curchan);
2432 
2433 	/* update Rx filter */
2434 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0) & 0xffff;
2435 
2436 	tmp |= RT2661_DROP_PHY_ERROR | RT2661_DROP_CRC_ERROR;
2437 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2438 		tmp |= RT2661_DROP_CTL | RT2661_DROP_VER_ERROR |
2439 		       RT2661_DROP_ACKCTS;
2440 		if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2441 			tmp |= RT2661_DROP_TODS;
2442 		if (!(ifp->if_flags & IFF_PROMISC))
2443 			tmp |= RT2661_DROP_NOT_TO_ME;
2444 	}
2445 
2446 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2447 
2448 	/* clear STA registers */
2449 	RAL_READ_REGION_4(sc, RT2661_STA_CSR0, sta, N(sta));
2450 
2451 	/* initialize ASIC */
2452 	RAL_WRITE(sc, RT2661_MAC_CSR1, 4);
2453 
2454 	/* clear any pending interrupt */
2455 	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2456 
2457 	/* enable interrupts */
2458 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
2459 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
2460 
2461 	/* kick Rx */
2462 	RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 1);
2463 
2464 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2465 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2466 
2467 	callout_reset(&sc->watchdog_ch, hz, rt2661_watchdog, sc);
2468 #undef N
2469 }
2470 
2471 static void
2472 rt2661_init(void *priv)
2473 {
2474 	struct rt2661_softc *sc = priv;
2475 	struct ifnet *ifp = sc->sc_ifp;
2476 	struct ieee80211com *ic = ifp->if_l2com;
2477 
2478 	RAL_LOCK(sc);
2479 	rt2661_init_locked(sc);
2480 	RAL_UNLOCK(sc);
2481 
2482 	if (ifp->if_drv_flags & IFF_DRV_RUNNING)
2483 		ieee80211_start_all(ic);		/* start all vap's */
2484 }
2485 
2486 void
2487 rt2661_stop_locked(struct rt2661_softc *sc)
2488 {
2489 	struct ifnet *ifp = sc->sc_ifp;
2490 	uint32_t tmp;
2491 	volatile int *flags = &sc->sc_flags;
2492 
2493 	while (*flags & RAL_INPUT_RUNNING)
2494 		msleep(sc, &sc->sc_mtx, 0, "ralrunning", hz/10);
2495 
2496 	callout_stop(&sc->watchdog_ch);
2497 	sc->sc_tx_timer = 0;
2498 
2499 	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
2500 		ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2501 
2502 		/* abort Tx (for all 5 Tx rings) */
2503 		RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 0x1f << 16);
2504 
2505 		/* disable Rx (value remains after reset!) */
2506 		tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2507 		RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2508 
2509 		/* reset ASIC */
2510 		RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2511 		RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2512 
2513 		/* disable interrupts */
2514 		RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffffff);
2515 		RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
2516 
2517 		/* clear any pending interrupt */
2518 		RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2519 		RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, 0xffffffff);
2520 
2521 		/* reset Tx and Rx rings */
2522 		rt2661_reset_tx_ring(sc, &sc->txq[0]);
2523 		rt2661_reset_tx_ring(sc, &sc->txq[1]);
2524 		rt2661_reset_tx_ring(sc, &sc->txq[2]);
2525 		rt2661_reset_tx_ring(sc, &sc->txq[3]);
2526 		rt2661_reset_tx_ring(sc, &sc->mgtq);
2527 		rt2661_reset_rx_ring(sc, &sc->rxq);
2528 	}
2529 }
2530 
2531 void
2532 rt2661_stop(void *priv)
2533 {
2534 	struct rt2661_softc *sc = priv;
2535 
2536 	RAL_LOCK(sc);
2537 	rt2661_stop_locked(sc);
2538 	RAL_UNLOCK(sc);
2539 }
2540 
2541 static int
2542 rt2661_load_microcode(struct rt2661_softc *sc)
2543 {
2544 	struct ifnet *ifp = sc->sc_ifp;
2545 	const struct firmware *fp;
2546 	const char *imagename;
2547 	int ntries, error;
2548 
2549 	RAL_LOCK_ASSERT(sc);
2550 
2551 	switch (sc->sc_id) {
2552 	case 0x0301: imagename = "rt2561sfw"; break;
2553 	case 0x0302: imagename = "rt2561fw"; break;
2554 	case 0x0401: imagename = "rt2661fw"; break;
2555 	default:
2556 		if_printf(ifp, "%s: unexpected pci device id 0x%x, "
2557 		    "don't know how to retrieve firmware\n",
2558 		    __func__, sc->sc_id);
2559 		return EINVAL;
2560 	}
2561 	RAL_UNLOCK(sc);
2562 	fp = firmware_get(imagename);
2563 	RAL_LOCK(sc);
2564 	if (fp == NULL) {
2565 		if_printf(ifp, "%s: unable to retrieve firmware image %s\n",
2566 		    __func__, imagename);
2567 		return EINVAL;
2568 	}
2569 
2570 	/*
2571 	 * Load 8051 microcode into NIC.
2572 	 */
2573 	/* reset 8051 */
2574 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2575 
2576 	/* cancel any pending Host to MCU command */
2577 	RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR, 0);
2578 	RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
2579 	RAL_WRITE(sc, RT2661_HOST_CMD_CSR, 0);
2580 
2581 	/* write 8051's microcode */
2582 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET | RT2661_MCU_SEL);
2583 	RAL_WRITE_REGION_1(sc, RT2661_MCU_CODE_BASE, fp->data, fp->datasize);
2584 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2585 
2586 	/* kick 8051's ass */
2587 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, 0);
2588 
2589 	/* wait for 8051 to initialize */
2590 	for (ntries = 0; ntries < 500; ntries++) {
2591 		if (RAL_READ(sc, RT2661_MCU_CNTL_CSR) & RT2661_MCU_READY)
2592 			break;
2593 		DELAY(100);
2594 	}
2595 	if (ntries == 500) {
2596 		if_printf(ifp, "%s: timeout waiting for MCU to initialize\n",
2597 		    __func__);
2598 		error = EIO;
2599 	} else
2600 		error = 0;
2601 
2602 	firmware_put(fp, FIRMWARE_UNLOAD);
2603 	return error;
2604 }
2605 
2606 #ifdef notyet
2607 /*
2608  * Dynamically tune Rx sensitivity (BBP register 17) based on average RSSI and
2609  * false CCA count.  This function is called periodically (every seconds) when
2610  * in the RUN state.  Values taken from the reference driver.
2611  */
2612 static void
2613 rt2661_rx_tune(struct rt2661_softc *sc)
2614 {
2615 	uint8_t bbp17;
2616 	uint16_t cca;
2617 	int lo, hi, dbm;
2618 
2619 	/*
2620 	 * Tuning range depends on operating band and on the presence of an
2621 	 * external low-noise amplifier.
2622 	 */
2623 	lo = 0x20;
2624 	if (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan))
2625 		lo += 0x08;
2626 	if ((IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan) && sc->ext_2ghz_lna) ||
2627 	    (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan) && sc->ext_5ghz_lna))
2628 		lo += 0x10;
2629 	hi = lo + 0x20;
2630 
2631 	/* retrieve false CCA count since last call (clear on read) */
2632 	cca = RAL_READ(sc, RT2661_STA_CSR1) & 0xffff;
2633 
2634 	if (dbm >= -35) {
2635 		bbp17 = 0x60;
2636 	} else if (dbm >= -58) {
2637 		bbp17 = hi;
2638 	} else if (dbm >= -66) {
2639 		bbp17 = lo + 0x10;
2640 	} else if (dbm >= -74) {
2641 		bbp17 = lo + 0x08;
2642 	} else {
2643 		/* RSSI < -74dBm, tune using false CCA count */
2644 
2645 		bbp17 = sc->bbp17; /* current value */
2646 
2647 		hi -= 2 * (-74 - dbm);
2648 		if (hi < lo)
2649 			hi = lo;
2650 
2651 		if (bbp17 > hi) {
2652 			bbp17 = hi;
2653 
2654 		} else if (cca > 512) {
2655 			if (++bbp17 > hi)
2656 				bbp17 = hi;
2657 		} else if (cca < 100) {
2658 			if (--bbp17 < lo)
2659 				bbp17 = lo;
2660 		}
2661 	}
2662 
2663 	if (bbp17 != sc->bbp17) {
2664 		rt2661_bbp_write(sc, 17, bbp17);
2665 		sc->bbp17 = bbp17;
2666 	}
2667 }
2668 
2669 /*
2670  * Enter/Leave radar detection mode.
2671  * This is for 802.11h additional regulatory domains.
2672  */
2673 static void
2674 rt2661_radar_start(struct rt2661_softc *sc)
2675 {
2676 	uint32_t tmp;
2677 
2678 	/* disable Rx */
2679 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2680 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2681 
2682 	rt2661_bbp_write(sc, 82, 0x20);
2683 	rt2661_bbp_write(sc, 83, 0x00);
2684 	rt2661_bbp_write(sc, 84, 0x40);
2685 
2686 	/* save current BBP registers values */
2687 	sc->bbp18 = rt2661_bbp_read(sc, 18);
2688 	sc->bbp21 = rt2661_bbp_read(sc, 21);
2689 	sc->bbp22 = rt2661_bbp_read(sc, 22);
2690 	sc->bbp16 = rt2661_bbp_read(sc, 16);
2691 	sc->bbp17 = rt2661_bbp_read(sc, 17);
2692 	sc->bbp64 = rt2661_bbp_read(sc, 64);
2693 
2694 	rt2661_bbp_write(sc, 18, 0xff);
2695 	rt2661_bbp_write(sc, 21, 0x3f);
2696 	rt2661_bbp_write(sc, 22, 0x3f);
2697 	rt2661_bbp_write(sc, 16, 0xbd);
2698 	rt2661_bbp_write(sc, 17, sc->ext_5ghz_lna ? 0x44 : 0x34);
2699 	rt2661_bbp_write(sc, 64, 0x21);
2700 
2701 	/* restore Rx filter */
2702 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2703 }
2704 
2705 static int
2706 rt2661_radar_stop(struct rt2661_softc *sc)
2707 {
2708 	uint8_t bbp66;
2709 
2710 	/* read radar detection result */
2711 	bbp66 = rt2661_bbp_read(sc, 66);
2712 
2713 	/* restore BBP registers values */
2714 	rt2661_bbp_write(sc, 16, sc->bbp16);
2715 	rt2661_bbp_write(sc, 17, sc->bbp17);
2716 	rt2661_bbp_write(sc, 18, sc->bbp18);
2717 	rt2661_bbp_write(sc, 21, sc->bbp21);
2718 	rt2661_bbp_write(sc, 22, sc->bbp22);
2719 	rt2661_bbp_write(sc, 64, sc->bbp64);
2720 
2721 	return bbp66 == 1;
2722 }
2723 #endif
2724 
2725 static int
2726 rt2661_prepare_beacon(struct rt2661_softc *sc, struct ieee80211vap *vap)
2727 {
2728 	struct ieee80211com *ic = vap->iv_ic;
2729 	struct ieee80211_beacon_offsets bo;
2730 	struct rt2661_tx_desc desc;
2731 	struct mbuf *m0;
2732 	int rate;
2733 
2734 	m0 = ieee80211_beacon_alloc(vap->iv_bss, &bo);
2735 	if (m0 == NULL) {
2736 		device_printf(sc->sc_dev, "could not allocate beacon frame\n");
2737 		return ENOBUFS;
2738 	}
2739 
2740 	/* send beacons at the lowest available rate */
2741 	rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_bsschan) ? 12 : 2;
2742 
2743 	rt2661_setup_tx_desc(sc, &desc, RT2661_TX_TIMESTAMP, RT2661_TX_HWSEQ,
2744 	    m0->m_pkthdr.len, rate, NULL, 0, RT2661_QID_MGT);
2745 
2746 	/* copy the first 24 bytes of Tx descriptor into NIC memory */
2747 	RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0, (uint8_t *)&desc, 24);
2748 
2749 	/* copy beacon header and payload into NIC memory */
2750 	RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0 + 24,
2751 	    mtod(m0, uint8_t *), m0->m_pkthdr.len);
2752 
2753 	m_freem(m0);
2754 
2755 	return 0;
2756 }
2757 
2758 /*
2759  * Enable TSF synchronization and tell h/w to start sending beacons for IBSS
2760  * and HostAP operating modes.
2761  */
2762 static void
2763 rt2661_enable_tsf_sync(struct rt2661_softc *sc)
2764 {
2765 	struct ifnet *ifp = sc->sc_ifp;
2766 	struct ieee80211com *ic = ifp->if_l2com;
2767 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2768 	uint32_t tmp;
2769 
2770 	if (vap->iv_opmode != IEEE80211_M_STA) {
2771 		/*
2772 		 * Change default 16ms TBTT adjustment to 8ms.
2773 		 * Must be done before enabling beacon generation.
2774 		 */
2775 		RAL_WRITE(sc, RT2661_TXRX_CSR10, 1 << 12 | 8);
2776 	}
2777 
2778 	tmp = RAL_READ(sc, RT2661_TXRX_CSR9) & 0xff000000;
2779 
2780 	/* set beacon interval (in 1/16ms unit) */
2781 	tmp |= vap->iv_bss->ni_intval * 16;
2782 
2783 	tmp |= RT2661_TSF_TICKING | RT2661_ENABLE_TBTT;
2784 	if (vap->iv_opmode == IEEE80211_M_STA)
2785 		tmp |= RT2661_TSF_MODE(1);
2786 	else
2787 		tmp |= RT2661_TSF_MODE(2) | RT2661_GENERATE_BEACON;
2788 
2789 	RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp);
2790 }
2791 
2792 /*
2793  * Retrieve the "Received Signal Strength Indicator" from the raw values
2794  * contained in Rx descriptors.  The computation depends on which band the
2795  * frame was received.  Correction values taken from the reference driver.
2796  */
2797 static int
2798 rt2661_get_rssi(struct rt2661_softc *sc, uint8_t raw)
2799 {
2800 	int lna, agc, rssi;
2801 
2802 	lna = (raw >> 5) & 0x3;
2803 	agc = raw & 0x1f;
2804 
2805 	if (lna == 0) {
2806 		/*
2807 		 * No mapping available.
2808 		 *
2809 		 * NB: Since RSSI is relative to noise floor, -1 is
2810 		 *     adequate for caller to know error happened.
2811 		 */
2812 		return -1;
2813 	}
2814 
2815 	rssi = (2 * agc) - RT2661_NOISE_FLOOR;
2816 
2817 	if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan)) {
2818 		rssi += sc->rssi_2ghz_corr;
2819 
2820 		if (lna == 1)
2821 			rssi -= 64;
2822 		else if (lna == 2)
2823 			rssi -= 74;
2824 		else if (lna == 3)
2825 			rssi -= 90;
2826 	} else {
2827 		rssi += sc->rssi_5ghz_corr;
2828 
2829 		if (lna == 1)
2830 			rssi -= 64;
2831 		else if (lna == 2)
2832 			rssi -= 86;
2833 		else if (lna == 3)
2834 			rssi -= 100;
2835 	}
2836 	return rssi;
2837 }
2838 
2839 static void
2840 rt2661_scan_start(struct ieee80211com *ic)
2841 {
2842 	struct ifnet *ifp = ic->ic_ifp;
2843 	struct rt2661_softc *sc = ifp->if_softc;
2844 	uint32_t tmp;
2845 
2846 	/* abort TSF synchronization */
2847 	tmp = RAL_READ(sc, RT2661_TXRX_CSR9);
2848 	RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp & ~0xffffff);
2849 	rt2661_set_bssid(sc, ifp->if_broadcastaddr);
2850 }
2851 
2852 static void
2853 rt2661_scan_end(struct ieee80211com *ic)
2854 {
2855 	struct ifnet *ifp = ic->ic_ifp;
2856 	struct rt2661_softc *sc = ifp->if_softc;
2857 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2858 
2859 	rt2661_enable_tsf_sync(sc);
2860 	/* XXX keep local copy */
2861 	rt2661_set_bssid(sc, vap->iv_bss->ni_bssid);
2862 }
2863 
2864 static void
2865 rt2661_set_channel(struct ieee80211com *ic)
2866 {
2867 	struct ifnet *ifp = ic->ic_ifp;
2868 	struct rt2661_softc *sc = ifp->if_softc;
2869 
2870 	RAL_LOCK(sc);
2871 	rt2661_set_chan(sc, ic->ic_curchan);
2872 
2873 	sc->sc_txtap.wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
2874 	sc->sc_txtap.wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
2875 	sc->sc_rxtap.wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
2876 	sc->sc_rxtap.wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
2877 	RAL_UNLOCK(sc);
2878 
2879 }
2880