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