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