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