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