xref: /freebsd/sys/dev/ral/rt2661.c (revision 87569f75a91f298c52a71823c04d41cf53c88889)
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/ral/if_ralrate.h>
63 #include <dev/ral/rt2661reg.h>
64 #include <dev/ral/rt2661var.h>
65 #include <dev/ral/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 /*
162  * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
163  */
164 static const struct ieee80211_rateset rt2661_rateset_11a =
165 	{ 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
166 
167 static const struct ieee80211_rateset rt2661_rateset_11b =
168 	{ 4, { 2, 4, 11, 22 } };
169 
170 static const struct ieee80211_rateset rt2661_rateset_11g =
171 	{ 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
172 
173 static const struct {
174 	uint32_t	reg;
175 	uint32_t	val;
176 } rt2661_def_mac[] = {
177 	RT2661_DEF_MAC
178 };
179 
180 static const struct {
181 	uint8_t	reg;
182 	uint8_t	val;
183 } rt2661_def_bbp[] = {
184 	RT2661_DEF_BBP
185 };
186 
187 static const struct rfprog {
188 	uint8_t		chan;
189 	uint32_t	r1, r2, r3, r4;
190 }  rt2661_rf5225_1[] = {
191 	RT2661_RF5225_1
192 }, rt2661_rf5225_2[] = {
193 	RT2661_RF5225_2
194 };
195 
196 int
197 rt2661_attach(device_t dev, int id)
198 {
199 	struct rt2661_softc *sc = device_get_softc(dev);
200 	struct ieee80211com *ic = &sc->sc_ic;
201 	struct ifnet *ifp;
202 	uint32_t val;
203 	const uint8_t *ucode = NULL;
204 	int error, i, ac, ntries, size = 0;
205 
206 	sc->sc_dev = dev;
207 
208 	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
209 	    MTX_DEF | MTX_RECURSE);
210 
211 	callout_init(&sc->scan_ch, debug_mpsafenet ? CALLOUT_MPSAFE : 0);
212 	callout_init(&sc->rssadapt_ch, CALLOUT_MPSAFE);
213 
214 	/* wait for NIC to initialize */
215 	for (ntries = 0; ntries < 1000; ntries++) {
216 		if ((val = RAL_READ(sc, RT2661_MAC_CSR0)) != 0)
217 			break;
218 		DELAY(1000);
219 	}
220 	if (ntries == 1000) {
221 		device_printf(sc->sc_dev,
222 		    "timeout waiting for NIC to initialize\n");
223 		error = EIO;
224 		goto fail1;
225 	}
226 
227 	/* retrieve RF rev. no and various other things from EEPROM */
228 	rt2661_read_eeprom(sc);
229 
230 	device_printf(dev, "MAC/BBP RT%X, RF %s\n", val,
231 	    rt2661_get_rf(sc->rf_rev));
232 
233 	/*
234 	 * Load 8051 microcode into NIC.
235 	 */
236 	switch (id) {
237 	case 0x0301:
238 		ucode = rt2561s_ucode;
239 		size = sizeof rt2561s_ucode;
240 		break;
241 	case 0x0302:
242 		ucode = rt2561_ucode;
243 		size = sizeof rt2561_ucode;
244 		break;
245 	case 0x0401:
246 		ucode = rt2661_ucode;
247 		size = sizeof rt2661_ucode;
248 		break;
249 	}
250 
251 	error = rt2661_load_microcode(sc, ucode, size);
252 	if (error != 0) {
253 		device_printf(sc->sc_dev, "could not load 8051 microcode\n");
254 		goto fail1;
255 	}
256 
257 	/*
258 	 * Allocate Tx and Rx rings.
259 	 */
260 	for (ac = 0; ac < 4; ac++) {
261 		error = rt2661_alloc_tx_ring(sc, &sc->txq[ac],
262 		    RT2661_TX_RING_COUNT);
263 		if (error != 0) {
264 			device_printf(sc->sc_dev,
265 			    "could not allocate Tx ring %d\n", ac);
266 			goto fail2;
267 		}
268 	}
269 
270 	error = rt2661_alloc_tx_ring(sc, &sc->mgtq, RT2661_MGT_RING_COUNT);
271 	if (error != 0) {
272 		device_printf(sc->sc_dev, "could not allocate Mgt ring\n");
273 		goto fail2;
274 	}
275 
276 	error = rt2661_alloc_rx_ring(sc, &sc->rxq, RT2661_RX_RING_COUNT);
277 	if (error != 0) {
278 		device_printf(sc->sc_dev, "could not allocate Rx ring\n");
279 		goto fail3;
280 	}
281 
282 	ifp = sc->sc_ifp = if_alloc(IFT_ETHER);
283 	if (ifp == NULL) {
284 		device_printf(sc->sc_dev, "can not if_alloc()\n");
285 		error = ENOMEM;
286 		goto fail4;
287 	}
288 
289 	ifp->if_softc = sc;
290 	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
291 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
292 	ifp->if_init = rt2661_init;
293 	ifp->if_ioctl = rt2661_ioctl;
294 	ifp->if_start = rt2661_start;
295 	ifp->if_watchdog = rt2661_watchdog;
296 	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
297 	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
298 	IFQ_SET_READY(&ifp->if_snd);
299 
300 	ic->ic_ifp = ifp;
301 	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
302 	ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */
303 	ic->ic_state = IEEE80211_S_INIT;
304 
305 	/* set device capabilities */
306 	ic->ic_caps =
307 	    IEEE80211_C_IBSS |		/* IBSS mode supported */
308 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
309 	    IEEE80211_C_HOSTAP |	/* HostAp mode supported */
310 	    IEEE80211_C_TXPMGT |	/* tx power management */
311 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
312 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
313 #ifdef notyet
314 	    IEEE80211_C_WME |		/* 802.11e */
315 #endif
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  * This function is only used by the Rx radiotap code. It returns the rate at
1273  * which a given frame was received.
1274  */
1275 static uint8_t
1276 rt2661_rxrate(struct rt2661_rx_desc *desc)
1277 {
1278 	if (le32toh(desc->flags) & RT2661_RX_OFDM) {
1279 		/* reverse function of rt2661_plcp_signal */
1280 		switch (desc->rate & 0xf) {
1281 		case 0xb:	return 12;
1282 		case 0xf:	return 18;
1283 		case 0xa:	return 24;
1284 		case 0xe:	return 36;
1285 		case 0x9:	return 48;
1286 		case 0xd:	return 72;
1287 		case 0x8:	return 96;
1288 		case 0xc:	return 108;
1289 		}
1290 	} else {
1291 		if (desc->rate == 10)
1292 			return 2;
1293 		if (desc->rate == 20)
1294 			return 4;
1295 		if (desc->rate == 55)
1296 			return 11;
1297 		if (desc->rate == 110)
1298 			return 22;
1299 	}
1300 	return 2;	/* should not get there */
1301 }
1302 
1303 /*
1304  * Return the expected ack rate for a frame transmitted at rate `rate'.
1305  * XXX: this should depend on the destination node basic rate set.
1306  */
1307 static int
1308 rt2661_ack_rate(struct ieee80211com *ic, int rate)
1309 {
1310 	switch (rate) {
1311 	/* CCK rates */
1312 	case 2:
1313 		return 2;
1314 	case 4:
1315 	case 11:
1316 	case 22:
1317 		return (ic->ic_curmode == IEEE80211_MODE_11B) ? 4 : rate;
1318 
1319 	/* OFDM rates */
1320 	case 12:
1321 	case 18:
1322 		return 12;
1323 	case 24:
1324 	case 36:
1325 		return 24;
1326 	case 48:
1327 	case 72:
1328 	case 96:
1329 	case 108:
1330 		return 48;
1331 	}
1332 
1333 	/* default to 1Mbps */
1334 	return 2;
1335 }
1336 
1337 /*
1338  * Compute the duration (in us) needed to transmit `len' bytes at rate `rate'.
1339  * The function automatically determines the operating mode depending on the
1340  * given rate. `flags' indicates whether short preamble is in use or not.
1341  */
1342 static uint16_t
1343 rt2661_txtime(int len, int rate, uint32_t flags)
1344 {
1345 	uint16_t txtime;
1346 
1347 	if (RAL_RATE_IS_OFDM(rate)) {
1348 		/* IEEE Std 802.11a-1999, pp. 37 */
1349 		txtime = (8 + 4 * len + 3 + rate - 1) / rate;
1350 		txtime = 16 + 4 + 4 * txtime + 6;
1351 	} else {
1352 		/* IEEE Std 802.11b-1999, pp. 28 */
1353 		txtime = (16 * len + rate - 1) / rate;
1354 		if (rate != 2 && (flags & IEEE80211_F_SHPREAMBLE))
1355 			txtime +=  72 + 24;
1356 		else
1357 			txtime += 144 + 48;
1358 	}
1359 
1360 	return txtime;
1361 }
1362 
1363 static uint8_t
1364 rt2661_plcp_signal(int rate)
1365 {
1366 	switch (rate) {
1367 	/* CCK rates (returned values are device-dependent) */
1368 	case 2:		return 0x0;
1369 	case 4:		return 0x1;
1370 	case 11:	return 0x2;
1371 	case 22:	return 0x3;
1372 
1373 	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1374 	case 12:	return 0xb;
1375 	case 18:	return 0xf;
1376 	case 24:	return 0xa;
1377 	case 36:	return 0xe;
1378 	case 48:	return 0x9;
1379 	case 72:	return 0xd;
1380 	case 96:	return 0x8;
1381 	case 108:	return 0xc;
1382 
1383 	/* unsupported rates (should not get there) */
1384 	default:	return 0xff;
1385 	}
1386 }
1387 
1388 static void
1389 rt2661_setup_tx_desc(struct rt2661_softc *sc, struct rt2661_tx_desc *desc,
1390     uint32_t flags, uint16_t xflags, int len, int rate,
1391     const bus_dma_segment_t *segs, int nsegs, int ac)
1392 {
1393 	struct ieee80211com *ic = &sc->sc_ic;
1394 	uint16_t plcp_length;
1395 	int i, remainder;
1396 
1397 	desc->flags = htole32(flags);
1398 	desc->flags |= htole32(len << 16);
1399 	desc->flags |= htole32(RT2661_TX_BUSY | RT2661_TX_VALID);
1400 
1401 	desc->xflags = htole16(xflags);
1402 	desc->xflags |= htole16(nsegs << 13);
1403 
1404 	desc->wme = htole16(
1405 	    RT2661_QID(ac) |
1406 	    RT2661_AIFSN(2) |
1407 	    RT2661_LOGCWMIN(4) |
1408 	    RT2661_LOGCWMAX(10));
1409 
1410 	/*
1411 	 * Remember in which queue this frame was sent. This field is driver
1412 	 * private data only. It will be made available by the NIC in STA_CSR4
1413 	 * on Tx interrupts.
1414 	 */
1415 	desc->qid = ac;
1416 
1417 	/* setup PLCP fields */
1418 	desc->plcp_signal  = rt2661_plcp_signal(rate);
1419 	desc->plcp_service = 4;
1420 
1421 	len += IEEE80211_CRC_LEN;
1422 	if (RAL_RATE_IS_OFDM(rate)) {
1423 		desc->flags |= htole32(RT2661_TX_OFDM);
1424 
1425 		plcp_length = len & 0xfff;
1426 		desc->plcp_length_hi = plcp_length >> 6;
1427 		desc->plcp_length_lo = plcp_length & 0x3f;
1428 	} else {
1429 		plcp_length = (16 * len + rate - 1) / rate;
1430 		if (rate == 22) {
1431 			remainder = (16 * len) % 22;
1432 			if (remainder != 0 && remainder < 7)
1433 				desc->plcp_service |= RT2661_PLCP_LENGEXT;
1434 		}
1435 		desc->plcp_length_hi = plcp_length >> 8;
1436 		desc->plcp_length_lo = plcp_length & 0xff;
1437 
1438 		if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1439 			desc->plcp_signal |= 0x08;
1440 	}
1441 
1442 	/* RT2x61 supports scatter with up to 5 segments */
1443 	for (i = 0; i < nsegs; i++) {
1444 		desc->addr[i] = htole32(segs[i].ds_addr);
1445 		desc->len [i] = htole16(segs[i].ds_len);
1446 	}
1447 }
1448 
1449 static int
1450 rt2661_tx_mgt(struct rt2661_softc *sc, struct mbuf *m0,
1451     struct ieee80211_node *ni)
1452 {
1453 	struct ieee80211com *ic = &sc->sc_ic;
1454 	struct rt2661_tx_desc *desc;
1455 	struct rt2661_tx_data *data;
1456 	struct ieee80211_frame *wh;
1457 	bus_dma_segment_t segs[RT2661_MAX_SCATTER];
1458 	uint16_t dur;
1459 	uint32_t flags = 0;	/* XXX HWSEQ */
1460 	int nsegs, rate, error;
1461 
1462 	desc = &sc->mgtq.desc[sc->mgtq.cur];
1463 	data = &sc->mgtq.data[sc->mgtq.cur];
1464 
1465 	/* send mgt frames at the lowest available rate */
1466 	rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1467 
1468 	error = bus_dmamap_load_mbuf_sg(sc->mgtq.data_dmat, data->map, m0,
1469 	    segs, &nsegs, 0);
1470 	if (error != 0) {
1471 		device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1472 		    error);
1473 		m_freem(m0);
1474 		return error;
1475 	}
1476 
1477 	if (sc->sc_drvbpf != NULL) {
1478 		struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1479 
1480 		tap->wt_flags = 0;
1481 		tap->wt_rate = rate;
1482 		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1483 		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1484 
1485 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
1486 	}
1487 
1488 	data->m = m0;
1489 	data->ni = ni;
1490 
1491 	wh = mtod(m0, struct ieee80211_frame *);
1492 
1493 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1494 		flags |= RT2661_TX_NEED_ACK;
1495 
1496 		dur = rt2661_txtime(RAL_ACK_SIZE, rate, ic->ic_flags) +
1497 		    RAL_SIFS;
1498 		*(uint16_t *)wh->i_dur = htole16(dur);
1499 
1500 		/* tell hardware to add timestamp in probe responses */
1501 		if ((wh->i_fc[0] &
1502 		    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1503 		    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1504 			flags |= RT2661_TX_TIMESTAMP;
1505 	}
1506 
1507 	rt2661_setup_tx_desc(sc, desc, flags, 0 /* XXX HWSEQ */,
1508 	    m0->m_pkthdr.len, rate, segs, nsegs, RT2661_QID_MGT);
1509 
1510 	bus_dmamap_sync(sc->mgtq.data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1511 	bus_dmamap_sync(sc->mgtq.desc_dmat, sc->mgtq.desc_map,
1512 	    BUS_DMASYNC_PREWRITE);
1513 
1514 	DPRINTFN(10, ("sending mgt frame len=%u idx=%u rate=%u\n",
1515 	    m0->m_pkthdr.len, sc->mgtq.cur, rate));
1516 
1517 	/* kick mgt */
1518 	sc->mgtq.queued++;
1519 	sc->mgtq.cur = (sc->mgtq.cur + 1) % RT2661_MGT_RING_COUNT;
1520 	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, RT2661_KICK_MGT);
1521 
1522 	return 0;
1523 }
1524 
1525 /*
1526  * Build a RTS control frame.
1527  */
1528 static struct mbuf *
1529 rt2661_get_rts(struct rt2661_softc *sc, struct ieee80211_frame *wh,
1530     uint16_t dur)
1531 {
1532 	struct ieee80211_frame_rts *rts;
1533 	struct mbuf *m;
1534 
1535 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1536 	if (m == NULL) {
1537 		sc->sc_ic.ic_stats.is_tx_nobuf++;
1538 		device_printf(sc->sc_dev, "could not allocate RTS frame\n");
1539 		return NULL;
1540 	}
1541 
1542 	rts = mtod(m, struct ieee80211_frame_rts *);
1543 
1544 	rts->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_CTL |
1545 	    IEEE80211_FC0_SUBTYPE_RTS;
1546 	rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1547 	*(uint16_t *)rts->i_dur = htole16(dur);
1548 	IEEE80211_ADDR_COPY(rts->i_ra, wh->i_addr1);
1549 	IEEE80211_ADDR_COPY(rts->i_ta, wh->i_addr2);
1550 
1551 	m->m_pkthdr.len = m->m_len = sizeof (struct ieee80211_frame_rts);
1552 
1553 	return m;
1554 }
1555 
1556 static int
1557 rt2661_tx_data(struct rt2661_softc *sc, struct mbuf *m0,
1558     struct ieee80211_node *ni, int ac)
1559 {
1560 	struct ieee80211com *ic = &sc->sc_ic;
1561 	struct rt2661_tx_ring *txq = &sc->txq[ac];
1562 	struct rt2661_tx_desc *desc;
1563 	struct rt2661_tx_data *data;
1564 	struct rt2661_node *rn;
1565 	struct ieee80211_rateset *rs;
1566 	struct ieee80211_frame *wh;
1567 	struct ieee80211_key *k;
1568 	const struct chanAccParams *cap;
1569 	struct mbuf *mnew;
1570 	bus_dma_segment_t segs[RT2661_MAX_SCATTER];
1571 	uint16_t dur;
1572 	uint32_t flags = 0;
1573 	int error, nsegs, rate, noack = 0;
1574 
1575 	wh = mtod(m0, struct ieee80211_frame *);
1576 
1577 	if (ic->ic_fixed_rate != IEEE80211_FIXED_RATE_NONE) {
1578 		rs = &ic->ic_sup_rates[ic->ic_curmode];
1579 		rate = rs->rs_rates[ic->ic_fixed_rate];
1580 	} else {
1581 		rs = &ni->ni_rates;
1582 		rn = (struct rt2661_node *)ni;
1583 		ni->ni_txrate = ral_rssadapt_choose(&rn->rssadapt, rs,
1584 		    wh, m0->m_pkthdr.len, NULL, 0);
1585 		rate = rs->rs_rates[ni->ni_txrate];
1586 	}
1587 	rate &= IEEE80211_RATE_VAL;
1588 
1589 	if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
1590 		cap = &ic->ic_wme.wme_chanParams;
1591 		noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
1592 	}
1593 
1594 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1595 		k = ieee80211_crypto_encap(ic, ni, m0);
1596 		if (k == NULL) {
1597 			m_freem(m0);
1598 			return ENOBUFS;
1599 		}
1600 
1601 		/* packet header may have moved, reset our local pointer */
1602 		wh = mtod(m0, struct ieee80211_frame *);
1603 	}
1604 
1605 	/*
1606 	 * IEEE Std 802.11-1999, pp 82: "A STA shall use an RTS/CTS exchange
1607 	 * for directed frames only when the length of the MPDU is greater
1608 	 * than the length threshold indicated by [...]" ic_rtsthreshold.
1609 	 */
1610 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1611 	    m0->m_pkthdr.len > ic->ic_rtsthreshold) {
1612 		struct mbuf *m;
1613 		uint16_t dur;
1614 		int rtsrate, ackrate;
1615 
1616 		rtsrate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1617 		ackrate = rt2661_ack_rate(ic, rate);
1618 
1619 		dur = rt2661_txtime(m0->m_pkthdr.len + 4, rate, ic->ic_flags) +
1620 		      rt2661_txtime(RAL_CTS_SIZE, rtsrate, ic->ic_flags) +
1621 		      /* XXX: noack (QoS)? */
1622 		      rt2661_txtime(RAL_ACK_SIZE, ackrate, ic->ic_flags) +
1623 		      3 * RAL_SIFS;
1624 
1625 		m = rt2661_get_rts(sc, wh, dur);
1626 
1627 		desc = &txq->desc[txq->cur];
1628 		data = &txq->data[txq->cur];
1629 
1630 		error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m,
1631 		    segs, &nsegs, 0);
1632 		if (error != 0) {
1633 			device_printf(sc->sc_dev,
1634 			    "could not map mbuf (error %d)\n", error);
1635 			m_freem(m);
1636 			m_freem(m0);
1637 			return error;
1638 		}
1639 
1640 		/* avoid multiple free() of the same node for each fragment */
1641 		ieee80211_ref_node(ni);
1642 
1643 		data->m = m;
1644 		data->ni = ni;
1645 
1646 		/* RTS frames are not taken into account for rssadapt */
1647 		data->id.id_node = NULL;
1648 
1649 		rt2661_setup_tx_desc(sc, desc, RT2661_TX_NEED_ACK |
1650 		    RT2661_TX_MORE_FRAG, 0, m->m_pkthdr.len, rtsrate, segs,
1651 		    nsegs, ac);
1652 
1653 		bus_dmamap_sync(txq->data_dmat, data->map,
1654 		    BUS_DMASYNC_PREWRITE);
1655 
1656 		txq->queued++;
1657 		txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1658 
1659 		/*
1660 		 * IEEE Std 802.11-1999: when an RTS/CTS exchange is used, the
1661 		 * asynchronous data frame shall be transmitted after the CTS
1662 		 * frame and a SIFS period.
1663 		 */
1664 		flags |= RT2661_TX_LONG_RETRY | RT2661_TX_IFS;
1665 	}
1666 
1667 	data = &txq->data[txq->cur];
1668 	desc = &txq->desc[txq->cur];
1669 
1670 	error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m0, segs,
1671 	    &nsegs, 0);
1672 	if (error != 0 && error != EFBIG) {
1673 		device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1674 		    error);
1675 		m_freem(m0);
1676 		return error;
1677 	}
1678 	if (error != 0) {
1679 		mnew = m_defrag(m0, M_DONTWAIT);
1680 		if (mnew == NULL) {
1681 			device_printf(sc->sc_dev,
1682 			    "could not defragment mbuf\n");
1683 			m_freem(m0);
1684 			return ENOBUFS;
1685 		}
1686 		m0 = mnew;
1687 
1688 		error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m0,
1689 		    segs, &nsegs, 0);
1690 		if (error != 0) {
1691 			device_printf(sc->sc_dev,
1692 			    "could not map mbuf (error %d)\n", error);
1693 			m_freem(m0);
1694 			return error;
1695 		}
1696 
1697 		/* packet header have moved, reset our local pointer */
1698 		wh = mtod(m0, struct ieee80211_frame *);
1699 	}
1700 
1701 	if (sc->sc_drvbpf != NULL) {
1702 		struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1703 
1704 		tap->wt_flags = 0;
1705 		tap->wt_rate = rate;
1706 		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1707 		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1708 
1709 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
1710 	}
1711 
1712 	data->m = m0;
1713 	data->ni = ni;
1714 
1715 	/* remember link conditions for rate adaptation algorithm */
1716 	if (ic->ic_fixed_rate == IEEE80211_FIXED_RATE_NONE) {
1717 		data->id.id_len = m0->m_pkthdr.len;
1718 		data->id.id_rateidx = ni->ni_txrate;
1719 		data->id.id_node = ni;
1720 		data->id.id_rssi = ni->ni_rssi;
1721 	} else
1722 		data->id.id_node = NULL;
1723 
1724 	if (!noack && !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1725 		flags |= RT2661_TX_NEED_ACK;
1726 
1727 		dur = rt2661_txtime(RAL_ACK_SIZE, rt2661_ack_rate(ic, rate),
1728 		    ic->ic_flags) + RAL_SIFS;
1729 		*(uint16_t *)wh->i_dur = htole16(dur);
1730 	}
1731 
1732 	rt2661_setup_tx_desc(sc, desc, flags, 0, m0->m_pkthdr.len, rate, segs,
1733 	    nsegs, ac);
1734 
1735 	bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1736 	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1737 
1738 	DPRINTFN(10, ("sending data frame len=%u idx=%u rate=%u\n",
1739 	    m0->m_pkthdr.len, txq->cur, rate));
1740 
1741 	/* kick Tx */
1742 	txq->queued++;
1743 	txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1744 	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 1 << ac);
1745 
1746 	return 0;
1747 }
1748 
1749 static void
1750 rt2661_start(struct ifnet *ifp)
1751 {
1752 	struct rt2661_softc *sc = ifp->if_softc;
1753 	struct ieee80211com *ic = &sc->sc_ic;
1754 	struct mbuf *m0;
1755 	struct ether_header *eh;
1756 	struct ieee80211_node *ni;
1757 	int ac;
1758 
1759 	RAL_LOCK(sc);
1760 
1761 	for (;;) {
1762 		IF_POLL(&ic->ic_mgtq, m0);
1763 		if (m0 != NULL) {
1764 			if (sc->mgtq.queued >= RT2661_MGT_RING_COUNT) {
1765 				ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1766 				break;
1767 			}
1768 			IF_DEQUEUE(&ic->ic_mgtq, m0);
1769 
1770 			ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
1771 			m0->m_pkthdr.rcvif = NULL;
1772 
1773 			if (ic->ic_rawbpf != NULL)
1774 				bpf_mtap(ic->ic_rawbpf, m0);
1775 
1776 			if (rt2661_tx_mgt(sc, m0, ni) != 0)
1777 				break;
1778 
1779 		} else {
1780 			if (ic->ic_state != IEEE80211_S_RUN)
1781 				break;
1782 
1783 			IFQ_DRV_DEQUEUE(&ifp->if_snd, m0);
1784 			if (m0 == NULL)
1785 				break;
1786 
1787 			if (m0->m_len < sizeof (struct ether_header) &&
1788 			    !(m0 = m_pullup(m0, sizeof (struct ether_header))))
1789 				continue;
1790 
1791 			eh = mtod(m0, struct ether_header *);
1792 			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1793 			if (ni == NULL) {
1794 				m_freem(m0);
1795 				ifp->if_oerrors++;
1796 				continue;
1797 			}
1798 
1799 			/* classify mbuf so we can find which tx ring to use */
1800 			if (ieee80211_classify(ic, m0, ni) != 0) {
1801 				m_freem(m0);
1802 				ieee80211_free_node(ni);
1803 				ifp->if_oerrors++;
1804 				continue;
1805 			}
1806 
1807 			/* no QoS encapsulation for EAPOL frames */
1808 			ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
1809 			    M_WME_GETAC(m0) : WME_AC_BE;
1810 
1811 			if (sc->txq[ac].queued >= RT2661_TX_RING_COUNT - 1) {
1812 				/* there is no place left in this ring */
1813 				IFQ_DRV_PREPEND(&ifp->if_snd, m0);
1814 				ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1815 				break;
1816 			}
1817 
1818 			BPF_MTAP(ifp, m0);
1819 
1820 			m0 = ieee80211_encap(ic, m0, ni);
1821 			if (m0 == NULL) {
1822 				ieee80211_free_node(ni);
1823 				ifp->if_oerrors++;
1824 				continue;
1825 			}
1826 
1827 			if (ic->ic_rawbpf != NULL)
1828 				bpf_mtap(ic->ic_rawbpf, m0);
1829 
1830 			if (rt2661_tx_data(sc, m0, ni, ac) != 0) {
1831 				ieee80211_free_node(ni);
1832 				ifp->if_oerrors++;
1833 				break;
1834 			}
1835 		}
1836 
1837 		sc->sc_tx_timer = 5;
1838 		ifp->if_timer = 1;
1839 	}
1840 
1841 	RAL_UNLOCK(sc);
1842 }
1843 
1844 static void
1845 rt2661_watchdog(struct ifnet *ifp)
1846 {
1847 	struct rt2661_softc *sc = ifp->if_softc;
1848 	struct ieee80211com *ic = &sc->sc_ic;
1849 
1850 	RAL_LOCK(sc);
1851 
1852 	ifp->if_timer = 0;
1853 
1854 	if (sc->sc_tx_timer > 0) {
1855 		if (--sc->sc_tx_timer == 0) {
1856 			device_printf(sc->sc_dev, "device timeout\n");
1857 			rt2661_init(sc);
1858 			ifp->if_oerrors++;
1859 			RAL_UNLOCK(sc);
1860 			return;
1861 		}
1862 		ifp->if_timer = 1;
1863 	}
1864 
1865 	ieee80211_watchdog(ic);
1866 
1867 	RAL_UNLOCK(sc);
1868 }
1869 
1870 /*
1871  * This function allows for fast channel switching in monitor mode (used by
1872  * net-mgmt/kismet). In IBSS mode, we must explicitly reset the interface to
1873  * generate a new beacon frame.
1874  */
1875 static int
1876 rt2661_reset(struct ifnet *ifp)
1877 {
1878 	struct rt2661_softc *sc = ifp->if_softc;
1879 	struct ieee80211com *ic = &sc->sc_ic;
1880 
1881 	if (ic->ic_opmode != IEEE80211_M_MONITOR)
1882 		return ENETRESET;
1883 
1884 	rt2661_set_chan(sc, ic->ic_curchan);
1885 
1886 	return 0;
1887 }
1888 
1889 static int
1890 rt2661_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1891 {
1892 	struct rt2661_softc *sc = ifp->if_softc;
1893 	struct ieee80211com *ic = &sc->sc_ic;
1894 	int error = 0;
1895 
1896 	RAL_LOCK(sc);
1897 
1898 	switch (cmd) {
1899 	case SIOCSIFFLAGS:
1900 		if (ifp->if_flags & IFF_UP) {
1901 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1902 				rt2661_update_promisc(sc);
1903 			else
1904 				rt2661_init(sc);
1905 		} else {
1906 			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1907 				rt2661_stop(sc);
1908 		}
1909 		break;
1910 
1911 	default:
1912 		error = ieee80211_ioctl(ic, cmd, data);
1913 	}
1914 
1915 	if (error == ENETRESET) {
1916 		if ((ifp->if_flags & IFF_UP) &&
1917 		    (ifp->if_drv_flags & IFF_DRV_RUNNING) &&
1918 		    (ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
1919 			rt2661_init(sc);
1920 		error = 0;
1921 	}
1922 
1923 	RAL_UNLOCK(sc);
1924 
1925 	return error;
1926 }
1927 
1928 static void
1929 rt2661_bbp_write(struct rt2661_softc *sc, uint8_t reg, uint8_t val)
1930 {
1931 	uint32_t tmp;
1932 	int ntries;
1933 
1934 	for (ntries = 0; ntries < 100; ntries++) {
1935 		if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
1936 			break;
1937 		DELAY(1);
1938 	}
1939 	if (ntries == 100) {
1940 		device_printf(sc->sc_dev, "could not write to BBP\n");
1941 		return;
1942 	}
1943 
1944 	tmp = RT2661_BBP_BUSY | (reg & 0x7f) << 8 | val;
1945 	RAL_WRITE(sc, RT2661_PHY_CSR3, tmp);
1946 
1947 	DPRINTFN(15, ("BBP R%u <- 0x%02x\n", reg, val));
1948 }
1949 
1950 static uint8_t
1951 rt2661_bbp_read(struct rt2661_softc *sc, uint8_t reg)
1952 {
1953 	uint32_t val;
1954 	int ntries;
1955 
1956 	for (ntries = 0; ntries < 100; ntries++) {
1957 		if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
1958 			break;
1959 		DELAY(1);
1960 	}
1961 	if (ntries == 100) {
1962 		device_printf(sc->sc_dev, "could not read from BBP\n");
1963 		return 0;
1964 	}
1965 
1966 	val = RT2661_BBP_BUSY | RT2661_BBP_READ | reg << 8;
1967 	RAL_WRITE(sc, RT2661_PHY_CSR3, val);
1968 
1969 	for (ntries = 0; ntries < 100; ntries++) {
1970 		val = RAL_READ(sc, RT2661_PHY_CSR3);
1971 		if (!(val & RT2661_BBP_BUSY))
1972 			return val & 0xff;
1973 		DELAY(1);
1974 	}
1975 
1976 	device_printf(sc->sc_dev, "could not read from BBP\n");
1977 	return 0;
1978 }
1979 
1980 static void
1981 rt2661_rf_write(struct rt2661_softc *sc, uint8_t reg, uint32_t val)
1982 {
1983 	uint32_t tmp;
1984 	int ntries;
1985 
1986 	for (ntries = 0; ntries < 100; ntries++) {
1987 		if (!(RAL_READ(sc, RT2661_PHY_CSR4) & RT2661_RF_BUSY))
1988 			break;
1989 		DELAY(1);
1990 	}
1991 	if (ntries == 100) {
1992 		device_printf(sc->sc_dev, "could not write to RF\n");
1993 		return;
1994 	}
1995 
1996 	tmp = RT2661_RF_BUSY | RT2661_RF_21BIT | (val & 0x1fffff) << 2 |
1997 	    (reg & 3);
1998 	RAL_WRITE(sc, RT2661_PHY_CSR4, tmp);
1999 
2000 	/* remember last written value in sc */
2001 	sc->rf_regs[reg] = val;
2002 
2003 	DPRINTFN(15, ("RF R[%u] <- 0x%05x\n", reg & 3, val & 0x1fffff));
2004 }
2005 
2006 static int
2007 rt2661_tx_cmd(struct rt2661_softc *sc, uint8_t cmd, uint16_t arg)
2008 {
2009 	if (RAL_READ(sc, RT2661_H2M_MAILBOX_CSR) & RT2661_H2M_BUSY)
2010 		return EIO;	/* there is already a command pending */
2011 
2012 	RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR,
2013 	    RT2661_H2M_BUSY | RT2661_TOKEN_NO_INTR << 16 | arg);
2014 
2015 	RAL_WRITE(sc, RT2661_HOST_CMD_CSR, RT2661_KICK_CMD | cmd);
2016 
2017 	return 0;
2018 }
2019 
2020 static void
2021 rt2661_select_antenna(struct rt2661_softc *sc)
2022 {
2023 	uint8_t bbp4, bbp77;
2024 	uint32_t tmp;
2025 
2026 	bbp4  = rt2661_bbp_read(sc,  4);
2027 	bbp77 = rt2661_bbp_read(sc, 77);
2028 
2029 	/* TBD */
2030 
2031 	/* make sure Rx is disabled before switching antenna */
2032 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2033 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2034 
2035 	rt2661_bbp_write(sc,  4, bbp4);
2036 	rt2661_bbp_write(sc, 77, bbp77);
2037 
2038 	/* restore Rx filter */
2039 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2040 }
2041 
2042 /*
2043  * Enable multi-rate retries for frames sent at OFDM rates.
2044  * In 802.11b/g mode, allow fallback to CCK rates.
2045  */
2046 static void
2047 rt2661_enable_mrr(struct rt2661_softc *sc)
2048 {
2049 	struct ieee80211com *ic = &sc->sc_ic;
2050 	uint32_t tmp;
2051 
2052 	tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
2053 
2054 	tmp &= ~RT2661_MRR_CCK_FALLBACK;
2055 	if (!IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan))
2056 		tmp |= RT2661_MRR_CCK_FALLBACK;
2057 	tmp |= RT2661_MRR_ENABLED;
2058 
2059 	RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
2060 }
2061 
2062 static void
2063 rt2661_set_txpreamble(struct rt2661_softc *sc)
2064 {
2065 	uint32_t tmp;
2066 
2067 	tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
2068 
2069 	tmp &= ~RT2661_SHORT_PREAMBLE;
2070 	if (sc->sc_ic.ic_flags & IEEE80211_F_SHPREAMBLE)
2071 		tmp |= RT2661_SHORT_PREAMBLE;
2072 
2073 	RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
2074 }
2075 
2076 static void
2077 rt2661_set_basicrates(struct rt2661_softc *sc,
2078     const struct ieee80211_rateset *rs)
2079 {
2080 #define RV(r)	((r) & IEEE80211_RATE_VAL)
2081 	uint32_t mask = 0;
2082 	uint8_t rate;
2083 	int i, j;
2084 
2085 	for (i = 0; i < rs->rs_nrates; i++) {
2086 		rate = rs->rs_rates[i];
2087 
2088 		if (!(rate & IEEE80211_RATE_BASIC))
2089 			continue;
2090 
2091 		/*
2092 		 * Find h/w rate index.  We know it exists because the rate
2093 		 * set has already been negotiated.
2094 		 */
2095 		for (j = 0; rt2661_rateset_11g.rs_rates[j] != RV(rate); j++);
2096 
2097 		mask |= 1 << j;
2098 	}
2099 
2100 	RAL_WRITE(sc, RT2661_TXRX_CSR5, mask);
2101 
2102 	DPRINTF(("Setting basic rate mask to 0x%x\n", mask));
2103 #undef RV
2104 }
2105 
2106 /*
2107  * Reprogram MAC/BBP to switch to a new band.  Values taken from the reference
2108  * driver.
2109  */
2110 static void
2111 rt2661_select_band(struct rt2661_softc *sc, struct ieee80211_channel *c)
2112 {
2113 	uint8_t bbp17, bbp35, bbp96, bbp97, bbp98, bbp104;
2114 	uint32_t tmp;
2115 
2116 	/* update all BBP registers that depend on the band */
2117 	bbp17 = 0x20; bbp96 = 0x48; bbp104 = 0x2c;
2118 	bbp35 = 0x50; bbp97 = 0x48; bbp98  = 0x48;
2119 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
2120 		bbp17 += 0x08; bbp96 += 0x10; bbp104 += 0x0c;
2121 		bbp35 += 0x10; bbp97 += 0x10; bbp98  += 0x10;
2122 	}
2123 	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2124 	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2125 		bbp17 += 0x10; bbp96 += 0x10; bbp104 += 0x10;
2126 	}
2127 
2128 	rt2661_bbp_write(sc,  17, bbp17);
2129 	rt2661_bbp_write(sc,  96, bbp96);
2130 	rt2661_bbp_write(sc, 104, bbp104);
2131 
2132 	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2133 	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2134 		rt2661_bbp_write(sc, 75, 0x80);
2135 		rt2661_bbp_write(sc, 86, 0x80);
2136 		rt2661_bbp_write(sc, 88, 0x80);
2137 	}
2138 
2139 	rt2661_bbp_write(sc, 35, bbp35);
2140 	rt2661_bbp_write(sc, 97, bbp97);
2141 	rt2661_bbp_write(sc, 98, bbp98);
2142 
2143 	tmp = RAL_READ(sc, RT2661_PHY_CSR0);
2144 	tmp &= ~(RT2661_PA_PE_2GHZ | RT2661_PA_PE_5GHZ);
2145 	if (IEEE80211_IS_CHAN_2GHZ(c))
2146 		tmp |= RT2661_PA_PE_2GHZ;
2147 	else
2148 		tmp |= RT2661_PA_PE_5GHZ;
2149 	RAL_WRITE(sc, RT2661_PHY_CSR0, tmp);
2150 }
2151 
2152 static void
2153 rt2661_set_chan(struct rt2661_softc *sc, struct ieee80211_channel *c)
2154 {
2155 	struct ieee80211com *ic = &sc->sc_ic;
2156 	const struct rfprog *rfprog;
2157 	uint8_t bbp3, bbp94 = RT2661_BBPR94_DEFAULT;
2158 	int8_t power;
2159 	u_int i, chan;
2160 
2161 	chan = ieee80211_chan2ieee(ic, c);
2162 	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
2163 		return;
2164 
2165 	/* select the appropriate RF settings based on what EEPROM says */
2166 	rfprog = (sc->rfprog == 0) ? rt2661_rf5225_1 : rt2661_rf5225_2;
2167 
2168 	/* find the settings for this channel (we know it exists) */
2169 	for (i = 0; rfprog[i].chan != chan; i++);
2170 
2171 	power = sc->txpow[i];
2172 	if (power < 0) {
2173 		bbp94 += power;
2174 		power = 0;
2175 	} else if (power > 31) {
2176 		bbp94 += power - 31;
2177 		power = 31;
2178 	}
2179 
2180 	/*
2181 	 * If we are switching from the 2GHz band to the 5GHz band or
2182 	 * vice-versa, BBP registers need to be reprogrammed.
2183 	 */
2184 	if (c->ic_flags != sc->sc_curchan->ic_flags) {
2185 		rt2661_select_band(sc, c);
2186 		rt2661_select_antenna(sc);
2187 	}
2188 	sc->sc_curchan = c;
2189 
2190 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2191 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2192 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2193 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2194 
2195 	DELAY(200);
2196 
2197 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2198 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2199 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7 | 1);
2200 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2201 
2202 	DELAY(200);
2203 
2204 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2205 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2206 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2207 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2208 
2209 	/* enable smart mode for MIMO-capable RFs */
2210 	bbp3 = rt2661_bbp_read(sc, 3);
2211 
2212 	bbp3 &= ~RT2661_SMART_MODE;
2213 	if (sc->rf_rev == RT2661_RF_5325 || sc->rf_rev == RT2661_RF_2529)
2214 		bbp3 |= RT2661_SMART_MODE;
2215 
2216 	rt2661_bbp_write(sc, 3, bbp3);
2217 
2218 	if (bbp94 != RT2661_BBPR94_DEFAULT)
2219 		rt2661_bbp_write(sc, 94, bbp94);
2220 
2221 	/* 5GHz radio needs a 1ms delay here */
2222 	if (IEEE80211_IS_CHAN_5GHZ(c))
2223 		DELAY(1000);
2224 }
2225 
2226 static void
2227 rt2661_set_bssid(struct rt2661_softc *sc, const uint8_t *bssid)
2228 {
2229 	uint32_t tmp;
2230 
2231 	tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24;
2232 	RAL_WRITE(sc, RT2661_MAC_CSR4, tmp);
2233 
2234 	tmp = bssid[4] | bssid[5] << 8 | RT2661_ONE_BSSID << 16;
2235 	RAL_WRITE(sc, RT2661_MAC_CSR5, tmp);
2236 }
2237 
2238 static void
2239 rt2661_set_macaddr(struct rt2661_softc *sc, const uint8_t *addr)
2240 {
2241 	uint32_t tmp;
2242 
2243 	tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24;
2244 	RAL_WRITE(sc, RT2661_MAC_CSR2, tmp);
2245 
2246 	tmp = addr[4] | addr[5] << 8;
2247 	RAL_WRITE(sc, RT2661_MAC_CSR3, tmp);
2248 }
2249 
2250 static void
2251 rt2661_update_promisc(struct rt2661_softc *sc)
2252 {
2253 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
2254 	uint32_t tmp;
2255 
2256 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2257 
2258 	tmp &= ~RT2661_DROP_NOT_TO_ME;
2259 	if (!(ifp->if_flags & IFF_PROMISC))
2260 		tmp |= RT2661_DROP_NOT_TO_ME;
2261 
2262 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2263 
2264 	DPRINTF(("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
2265 	    "entering" : "leaving"));
2266 }
2267 
2268 /*
2269  * Update QoS (802.11e) settings for each h/w Tx ring.
2270  */
2271 static int
2272 rt2661_wme_update(struct ieee80211com *ic)
2273 {
2274 	struct rt2661_softc *sc = ic->ic_ifp->if_softc;
2275 	const struct wmeParams *wmep;
2276 
2277 	wmep = ic->ic_wme.wme_chanParams.cap_wmeParams;
2278 
2279 	/* XXX: not sure about shifts. */
2280 	/* XXX: the reference driver plays with AC_VI settings too. */
2281 
2282 	/* update TxOp */
2283 	RAL_WRITE(sc, RT2661_AC_TXOP_CSR0,
2284 	    wmep[WME_AC_BE].wmep_txopLimit << 16 |
2285 	    wmep[WME_AC_BK].wmep_txopLimit);
2286 	RAL_WRITE(sc, RT2661_AC_TXOP_CSR1,
2287 	    wmep[WME_AC_VI].wmep_txopLimit << 16 |
2288 	    wmep[WME_AC_VO].wmep_txopLimit);
2289 
2290 	/* update CWmin */
2291 	RAL_WRITE(sc, RT2661_CWMIN_CSR,
2292 	    wmep[WME_AC_BE].wmep_logcwmin << 12 |
2293 	    wmep[WME_AC_BK].wmep_logcwmin <<  8 |
2294 	    wmep[WME_AC_VI].wmep_logcwmin <<  4 |
2295 	    wmep[WME_AC_VO].wmep_logcwmin);
2296 
2297 	/* update CWmax */
2298 	RAL_WRITE(sc, RT2661_CWMAX_CSR,
2299 	    wmep[WME_AC_BE].wmep_logcwmax << 12 |
2300 	    wmep[WME_AC_BK].wmep_logcwmax <<  8 |
2301 	    wmep[WME_AC_VI].wmep_logcwmax <<  4 |
2302 	    wmep[WME_AC_VO].wmep_logcwmax);
2303 
2304 	/* update Aifsn */
2305 	RAL_WRITE(sc, RT2661_AIFSN_CSR,
2306 	    wmep[WME_AC_BE].wmep_aifsn << 12 |
2307 	    wmep[WME_AC_BK].wmep_aifsn <<  8 |
2308 	    wmep[WME_AC_VI].wmep_aifsn <<  4 |
2309 	    wmep[WME_AC_VO].wmep_aifsn);
2310 
2311 	return 0;
2312 }
2313 
2314 static void
2315 rt2661_update_slot(struct ifnet *ifp)
2316 {
2317 	struct rt2661_softc *sc = ifp->if_softc;
2318 	struct ieee80211com *ic = &sc->sc_ic;
2319 	uint8_t slottime;
2320 	uint32_t tmp;
2321 
2322 	slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
2323 
2324 	tmp = RAL_READ(sc, RT2661_MAC_CSR9);
2325 	tmp = (tmp & ~0xff) | slottime;
2326 	RAL_WRITE(sc, RT2661_MAC_CSR9, tmp);
2327 }
2328 
2329 static const char *
2330 rt2661_get_rf(int rev)
2331 {
2332 	switch (rev) {
2333 	case RT2661_RF_5225:	return "RT5225";
2334 	case RT2661_RF_5325:	return "RT5325 (MIMO XR)";
2335 	case RT2661_RF_2527:	return "RT2527";
2336 	case RT2661_RF_2529:	return "RT2529 (MIMO XR)";
2337 	default:		return "unknown";
2338 	}
2339 }
2340 
2341 static void
2342 rt2661_read_eeprom(struct rt2661_softc *sc)
2343 {
2344 	struct ieee80211com *ic = &sc->sc_ic;
2345 	uint16_t val;
2346 	int i;
2347 
2348 	/* read MAC address */
2349 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC01);
2350 	ic->ic_myaddr[0] = val & 0xff;
2351 	ic->ic_myaddr[1] = val >> 8;
2352 
2353 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC23);
2354 	ic->ic_myaddr[2] = val & 0xff;
2355 	ic->ic_myaddr[3] = val >> 8;
2356 
2357 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC45);
2358 	ic->ic_myaddr[4] = val & 0xff;
2359 	ic->ic_myaddr[5] = val >> 8;
2360 
2361 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_ANTENNA);
2362 	/* XXX: test if different from 0xffff? */
2363 	sc->rf_rev   = (val >> 11) & 0x1f;
2364 	sc->hw_radio = (val >> 10) & 0x1;
2365 	sc->rx_ant   = (val >> 4)  & 0x3;
2366 	sc->tx_ant   = (val >> 2)  & 0x3;
2367 	sc->nb_ant   = val & 0x3;
2368 
2369 	DPRINTF(("RF revision=%d\n", sc->rf_rev));
2370 
2371 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_CONFIG2);
2372 	sc->ext_5ghz_lna = (val >> 6) & 0x1;
2373 	sc->ext_2ghz_lna = (val >> 4) & 0x1;
2374 
2375 	DPRINTF(("External 2GHz LNA=%d\nExternal 5GHz LNA=%d\n",
2376 	    sc->ext_2ghz_lna, sc->ext_5ghz_lna));
2377 
2378 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_2GHZ_OFFSET);
2379 	if ((val & 0xff) != 0xff)
2380 		sc->rssi_2ghz_corr = (int8_t)(val & 0xff);	/* signed */
2381 
2382 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_5GHZ_OFFSET);
2383 	if ((val & 0xff) != 0xff)
2384 		sc->rssi_5ghz_corr = (int8_t)(val & 0xff);	/* signed */
2385 
2386 	/* adjust RSSI correction for external low-noise amplifier */
2387 	if (sc->ext_2ghz_lna)
2388 		sc->rssi_2ghz_corr -= 14;
2389 	if (sc->ext_5ghz_lna)
2390 		sc->rssi_5ghz_corr -= 14;
2391 
2392 	DPRINTF(("RSSI 2GHz corr=%d\nRSSI 5GHz corr=%d\n",
2393 	    sc->rssi_2ghz_corr, sc->rssi_5ghz_corr));
2394 
2395 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_FREQ_OFFSET);
2396 	if ((val >> 8) != 0xff)
2397 		sc->rfprog = (val >> 8) & 0x3;
2398 	if ((val & 0xff) != 0xff)
2399 		sc->rffreq = val & 0xff;
2400 
2401 	DPRINTF(("RF prog=%d\nRF freq=%d\n", sc->rfprog, sc->rffreq));
2402 
2403 	/* read Tx power for all a/b/g channels */
2404 	for (i = 0; i < 19; i++) {
2405 		val = rt2661_eeprom_read(sc, RT2661_EEPROM_TXPOWER + i);
2406 		sc->txpow[i * 2] = (int8_t)(val >> 8);		/* signed */
2407 		DPRINTF(("Channel=%d Tx power=%d\n",
2408 		    rt2661_rf5225_1[i * 2].chan, sc->txpow[i * 2]));
2409 		sc->txpow[i * 2 + 1] = (int8_t)(val & 0xff);	/* signed */
2410 		DPRINTF(("Channel=%d Tx power=%d\n",
2411 		    rt2661_rf5225_1[i * 2 + 1].chan, sc->txpow[i * 2 + 1]));
2412 	}
2413 
2414 	/* read vendor-specific BBP values */
2415 	for (i = 0; i < 16; i++) {
2416 		val = rt2661_eeprom_read(sc, RT2661_EEPROM_BBP_BASE + i);
2417 		if (val == 0 || val == 0xffff)
2418 			continue;	/* skip invalid entries */
2419 		sc->bbp_prom[i].reg = val >> 8;
2420 		sc->bbp_prom[i].val = val & 0xff;
2421 		DPRINTF(("BBP R%d=%02x\n", sc->bbp_prom[i].reg,
2422 		    sc->bbp_prom[i].val));
2423 	}
2424 }
2425 
2426 static int
2427 rt2661_bbp_init(struct rt2661_softc *sc)
2428 {
2429 #define N(a)	(sizeof (a) / sizeof ((a)[0]))
2430 	int i, ntries;
2431 	uint8_t val;
2432 
2433 	/* wait for BBP to be ready */
2434 	for (ntries = 0; ntries < 100; ntries++) {
2435 		val = rt2661_bbp_read(sc, 0);
2436 		if (val != 0 && val != 0xff)
2437 			break;
2438 		DELAY(100);
2439 	}
2440 	if (ntries == 100) {
2441 		device_printf(sc->sc_dev, "timeout waiting for BBP\n");
2442 		return EIO;
2443 	}
2444 
2445 	/* initialize BBP registers to default values */
2446 	for (i = 0; i < N(rt2661_def_bbp); i++) {
2447 		rt2661_bbp_write(sc, rt2661_def_bbp[i].reg,
2448 		    rt2661_def_bbp[i].val);
2449 	}
2450 
2451 	/* write vendor-specific BBP values (from EEPROM) */
2452 	for (i = 0; i < 16; i++) {
2453 		if (sc->bbp_prom[i].reg == 0)
2454 			continue;
2455 		rt2661_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2456 	}
2457 
2458 	return 0;
2459 #undef N
2460 }
2461 
2462 static void
2463 rt2661_init(void *priv)
2464 {
2465 #define N(a)	(sizeof (a) / sizeof ((a)[0]))
2466 	struct rt2661_softc *sc = priv;
2467 	struct ieee80211com *ic = &sc->sc_ic;
2468 	struct ifnet *ifp = ic->ic_ifp;
2469 	uint32_t tmp, sta[3];
2470 	int i, ntries;
2471 
2472 	rt2661_stop(sc);
2473 
2474 	/* initialize Tx rings */
2475 	RAL_WRITE(sc, RT2661_AC1_BASE_CSR, sc->txq[1].physaddr);
2476 	RAL_WRITE(sc, RT2661_AC0_BASE_CSR, sc->txq[0].physaddr);
2477 	RAL_WRITE(sc, RT2661_AC2_BASE_CSR, sc->txq[2].physaddr);
2478 	RAL_WRITE(sc, RT2661_AC3_BASE_CSR, sc->txq[3].physaddr);
2479 
2480 	/* initialize Mgt ring */
2481 	RAL_WRITE(sc, RT2661_MGT_BASE_CSR, sc->mgtq.physaddr);
2482 
2483 	/* initialize Rx ring */
2484 	RAL_WRITE(sc, RT2661_RX_BASE_CSR, sc->rxq.physaddr);
2485 
2486 	/* initialize Tx rings sizes */
2487 	RAL_WRITE(sc, RT2661_TX_RING_CSR0,
2488 	    RT2661_TX_RING_COUNT << 24 |
2489 	    RT2661_TX_RING_COUNT << 16 |
2490 	    RT2661_TX_RING_COUNT <<  8 |
2491 	    RT2661_TX_RING_COUNT);
2492 
2493 	RAL_WRITE(sc, RT2661_TX_RING_CSR1,
2494 	    RT2661_TX_DESC_WSIZE << 16 |
2495 	    RT2661_TX_RING_COUNT <<  8 |	/* XXX: HCCA ring unused */
2496 	    RT2661_MGT_RING_COUNT);
2497 
2498 	/* initialize Rx rings */
2499 	RAL_WRITE(sc, RT2661_RX_RING_CSR,
2500 	    RT2661_RX_DESC_BACK  << 16 |
2501 	    RT2661_RX_DESC_WSIZE <<  8 |
2502 	    RT2661_RX_RING_COUNT);
2503 
2504 	/* XXX: some magic here */
2505 	RAL_WRITE(sc, RT2661_TX_DMA_DST_CSR, 0xaa);
2506 
2507 	/* load base addresses of all 5 Tx rings (4 data + 1 mgt) */
2508 	RAL_WRITE(sc, RT2661_LOAD_TX_RING_CSR, 0x1f);
2509 
2510 	/* load base address of Rx ring */
2511 	RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 2);
2512 
2513 	/* initialize MAC registers to default values */
2514 	for (i = 0; i < N(rt2661_def_mac); i++)
2515 		RAL_WRITE(sc, rt2661_def_mac[i].reg, rt2661_def_mac[i].val);
2516 
2517 	IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2518 	rt2661_set_macaddr(sc, ic->ic_myaddr);
2519 
2520 	/* set host ready */
2521 	RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2522 	RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2523 
2524 	/* wait for BBP/RF to wakeup */
2525 	for (ntries = 0; ntries < 1000; ntries++) {
2526 		if (RAL_READ(sc, RT2661_MAC_CSR12) & 8)
2527 			break;
2528 		DELAY(1000);
2529 	}
2530 	if (ntries == 1000) {
2531 		printf("timeout waiting for BBP/RF to wakeup\n");
2532 		rt2661_stop(sc);
2533 		return;
2534 	}
2535 
2536 	if (rt2661_bbp_init(sc) != 0) {
2537 		rt2661_stop(sc);
2538 		return;
2539 	}
2540 
2541 	/* select default channel */
2542 	sc->sc_curchan = ic->ic_curchan;
2543 	rt2661_select_band(sc, sc->sc_curchan);
2544 	rt2661_select_antenna(sc);
2545 	rt2661_set_chan(sc, sc->sc_curchan);
2546 
2547 	/* update Rx filter */
2548 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0) & 0xffff;
2549 
2550 	tmp |= RT2661_DROP_PHY_ERROR | RT2661_DROP_CRC_ERROR;
2551 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2552 		tmp |= RT2661_DROP_CTL | RT2661_DROP_VER_ERROR |
2553 		       RT2661_DROP_ACKCTS;
2554 		if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2555 			tmp |= RT2661_DROP_TODS;
2556 		if (!(ifp->if_flags & IFF_PROMISC))
2557 			tmp |= RT2661_DROP_NOT_TO_ME;
2558 	}
2559 
2560 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2561 
2562 	/* clear STA registers */
2563 	RAL_READ_REGION_4(sc, RT2661_STA_CSR0, sta, N(sta));
2564 
2565 	/* initialize ASIC */
2566 	RAL_WRITE(sc, RT2661_MAC_CSR1, 4);
2567 
2568 	/* clear any pending interrupt */
2569 	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2570 
2571 	/* enable interrupts */
2572 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
2573 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
2574 
2575 	/* kick Rx */
2576 	RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 1);
2577 
2578 	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2579 	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2580 
2581 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2582 		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
2583 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2584 	} else
2585 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2586 }
2587 
2588 void
2589 rt2661_stop(void *priv)
2590 {
2591 	struct rt2661_softc *sc = priv;
2592 	struct ieee80211com *ic = &sc->sc_ic;
2593 	struct ifnet *ifp = ic->ic_ifp;
2594 	uint32_t tmp;
2595 
2596 	sc->sc_tx_timer = 0;
2597 	ifp->if_timer = 0;
2598 	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2599 
2600 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2601 
2602 	/* abort Tx (for all 5 Tx rings) */
2603 	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 0x1f << 16);
2604 
2605 	/* disable Rx (value remains after reset!) */
2606 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2607 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2608 
2609 	/* reset ASIC */
2610 	RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2611 	RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2612 
2613 	/* disable interrupts */
2614 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffff7f);
2615 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
2616 
2617 	/* reset Tx and Rx rings */
2618 	rt2661_reset_tx_ring(sc, &sc->txq[0]);
2619 	rt2661_reset_tx_ring(sc, &sc->txq[1]);
2620 	rt2661_reset_tx_ring(sc, &sc->txq[2]);
2621 	rt2661_reset_tx_ring(sc, &sc->txq[3]);
2622 	rt2661_reset_tx_ring(sc, &sc->mgtq);
2623 	rt2661_reset_rx_ring(sc, &sc->rxq);
2624 }
2625 
2626 static int
2627 rt2661_load_microcode(struct rt2661_softc *sc, const uint8_t *ucode, int size)
2628 {
2629 	int ntries;
2630 
2631 	/* reset 8051 */
2632 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2633 
2634 	/* cancel any pending Host to MCU command */
2635 	RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR, 0);
2636 	RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
2637 	RAL_WRITE(sc, RT2661_HOST_CMD_CSR, 0);
2638 
2639 	/* write 8051's microcode */
2640 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET | RT2661_MCU_SEL);
2641 	RAL_WRITE_REGION_1(sc, RT2661_MCU_CODE_BASE, ucode, size);
2642 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2643 
2644 	/* kick 8051's ass */
2645 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, 0);
2646 
2647 	/* wait for 8051 to initialize */
2648 	for (ntries = 0; ntries < 500; ntries++) {
2649 		if (RAL_READ(sc, RT2661_MCU_CNTL_CSR) & RT2661_MCU_READY)
2650 			break;
2651 		DELAY(100);
2652 	}
2653 	if (ntries == 500) {
2654 		printf("timeout waiting for MCU to initialize\n");
2655 		return EIO;
2656 	}
2657 	return 0;
2658 }
2659 
2660 #ifdef notyet
2661 /*
2662  * Dynamically tune Rx sensitivity (BBP register 17) based on average RSSI and
2663  * false CCA count.  This function is called periodically (every seconds) when
2664  * in the RUN state.  Values taken from the reference driver.
2665  */
2666 static void
2667 rt2661_rx_tune(struct rt2661_softc *sc)
2668 {
2669 	uint8_t bbp17;
2670 	uint16_t cca;
2671 	int lo, hi, dbm;
2672 
2673 	/*
2674 	 * Tuning range depends on operating band and on the presence of an
2675 	 * external low-noise amplifier.
2676 	 */
2677 	lo = 0x20;
2678 	if (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan))
2679 		lo += 0x08;
2680 	if ((IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan) && sc->ext_2ghz_lna) ||
2681 	    (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan) && sc->ext_5ghz_lna))
2682 		lo += 0x10;
2683 	hi = lo + 0x20;
2684 
2685 	/* retrieve false CCA count since last call (clear on read) */
2686 	cca = RAL_READ(sc, RT2661_STA_CSR1) & 0xffff;
2687 
2688 	if (dbm >= -35) {
2689 		bbp17 = 0x60;
2690 	} else if (dbm >= -58) {
2691 		bbp17 = hi;
2692 	} else if (dbm >= -66) {
2693 		bbp17 = lo + 0x10;
2694 	} else if (dbm >= -74) {
2695 		bbp17 = lo + 0x08;
2696 	} else {
2697 		/* RSSI < -74dBm, tune using false CCA count */
2698 
2699 		bbp17 = sc->bbp17; /* current value */
2700 
2701 		hi -= 2 * (-74 - dbm);
2702 		if (hi < lo)
2703 			hi = lo;
2704 
2705 		if (bbp17 > hi) {
2706 			bbp17 = hi;
2707 
2708 		} else if (cca > 512) {
2709 			if (++bbp17 > hi)
2710 				bbp17 = hi;
2711 		} else if (cca < 100) {
2712 			if (--bbp17 < lo)
2713 				bbp17 = lo;
2714 		}
2715 	}
2716 
2717 	if (bbp17 != sc->bbp17) {
2718 		rt2661_bbp_write(sc, 17, bbp17);
2719 		sc->bbp17 = bbp17;
2720 	}
2721 }
2722 
2723 /*
2724  * Enter/Leave radar detection mode.
2725  * This is for 802.11h additional regulatory domains.
2726  */
2727 static void
2728 rt2661_radar_start(struct rt2661_softc *sc)
2729 {
2730 	uint32_t tmp;
2731 
2732 	/* disable Rx */
2733 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2734 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2735 
2736 	rt2661_bbp_write(sc, 82, 0x20);
2737 	rt2661_bbp_write(sc, 83, 0x00);
2738 	rt2661_bbp_write(sc, 84, 0x40);
2739 
2740 	/* save current BBP registers values */
2741 	sc->bbp18 = rt2661_bbp_read(sc, 18);
2742 	sc->bbp21 = rt2661_bbp_read(sc, 21);
2743 	sc->bbp22 = rt2661_bbp_read(sc, 22);
2744 	sc->bbp16 = rt2661_bbp_read(sc, 16);
2745 	sc->bbp17 = rt2661_bbp_read(sc, 17);
2746 	sc->bbp64 = rt2661_bbp_read(sc, 64);
2747 
2748 	rt2661_bbp_write(sc, 18, 0xff);
2749 	rt2661_bbp_write(sc, 21, 0x3f);
2750 	rt2661_bbp_write(sc, 22, 0x3f);
2751 	rt2661_bbp_write(sc, 16, 0xbd);
2752 	rt2661_bbp_write(sc, 17, sc->ext_5ghz_lna ? 0x44 : 0x34);
2753 	rt2661_bbp_write(sc, 64, 0x21);
2754 
2755 	/* restore Rx filter */
2756 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2757 }
2758 
2759 static int
2760 rt2661_radar_stop(struct rt2661_softc *sc)
2761 {
2762 	uint8_t bbp66;
2763 
2764 	/* read radar detection result */
2765 	bbp66 = rt2661_bbp_read(sc, 66);
2766 
2767 	/* restore BBP registers values */
2768 	rt2661_bbp_write(sc, 16, sc->bbp16);
2769 	rt2661_bbp_write(sc, 17, sc->bbp17);
2770 	rt2661_bbp_write(sc, 18, sc->bbp18);
2771 	rt2661_bbp_write(sc, 21, sc->bbp21);
2772 	rt2661_bbp_write(sc, 22, sc->bbp22);
2773 	rt2661_bbp_write(sc, 64, sc->bbp64);
2774 
2775 	return bbp66 == 1;
2776 }
2777 #endif
2778 
2779 static int
2780 rt2661_prepare_beacon(struct rt2661_softc *sc)
2781 {
2782 	struct ieee80211com *ic = &sc->sc_ic;
2783 	struct ieee80211_beacon_offsets bo;
2784 	struct rt2661_tx_desc desc;
2785 	struct mbuf *m0;
2786 	int rate;
2787 
2788 	m0 = ieee80211_beacon_alloc(ic, ic->ic_bss, &bo);
2789 	if (m0 == NULL) {
2790 		device_printf(sc->sc_dev, "could not allocate beacon frame\n");
2791 		return ENOBUFS;
2792 	}
2793 
2794 	/* send beacons at the lowest available rate */
2795 	rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan) ? 12 : 2;
2796 
2797 	rt2661_setup_tx_desc(sc, &desc, RT2661_TX_TIMESTAMP, RT2661_TX_HWSEQ,
2798 	    m0->m_pkthdr.len, rate, NULL, 0, RT2661_QID_MGT);
2799 
2800 	/* copy the first 24 bytes of Tx descriptor into NIC memory */
2801 	RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0, (uint8_t *)&desc, 24);
2802 
2803 	/* copy beacon header and payload into NIC memory */
2804 	RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0 + 24,
2805 	    mtod(m0, uint8_t *), m0->m_pkthdr.len);
2806 
2807 	m_freem(m0);
2808 
2809 	return 0;
2810 }
2811 
2812 /*
2813  * Enable TSF synchronization and tell h/w to start sending beacons for IBSS
2814  * and HostAP operating modes.
2815  */
2816 static void
2817 rt2661_enable_tsf_sync(struct rt2661_softc *sc)
2818 {
2819 	struct ieee80211com *ic = &sc->sc_ic;
2820 	uint32_t tmp;
2821 
2822 	if (ic->ic_opmode != IEEE80211_M_STA) {
2823 		/*
2824 		 * Change default 16ms TBTT adjustment to 8ms.
2825 		 * Must be done before enabling beacon generation.
2826 		 */
2827 		RAL_WRITE(sc, RT2661_TXRX_CSR10, 1 << 12 | 8);
2828 	}
2829 
2830 	tmp = RAL_READ(sc, RT2661_TXRX_CSR9) & 0xff000000;
2831 
2832 	/* set beacon interval (in 1/16ms unit) */
2833 	tmp |= ic->ic_bss->ni_intval * 16;
2834 
2835 	tmp |= RT2661_TSF_TICKING | RT2661_ENABLE_TBTT;
2836 	if (ic->ic_opmode == IEEE80211_M_STA)
2837 		tmp |= RT2661_TSF_MODE(1);
2838 	else
2839 		tmp |= RT2661_TSF_MODE(2) | RT2661_GENERATE_BEACON;
2840 
2841 	RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp);
2842 }
2843 
2844 /*
2845  * Retrieve the "Received Signal Strength Indicator" from the raw values
2846  * contained in Rx descriptors.  The computation depends on which band the
2847  * frame was received.  Correction values taken from the reference driver.
2848  */
2849 static int
2850 rt2661_get_rssi(struct rt2661_softc *sc, uint8_t raw)
2851 {
2852 	int lna, agc, rssi;
2853 
2854 	lna = (raw >> 5) & 0x3;
2855 	agc = raw & 0x1f;
2856 
2857 	rssi = 2 * agc;
2858 
2859 	if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan)) {
2860 		rssi += sc->rssi_2ghz_corr;
2861 
2862 		if (lna == 1)
2863 			rssi -= 64;
2864 		else if (lna == 2)
2865 			rssi -= 74;
2866 		else if (lna == 3)
2867 			rssi -= 90;
2868 	} else {
2869 		rssi += sc->rssi_5ghz_corr;
2870 
2871 		if (lna == 1)
2872 			rssi -= 64;
2873 		else if (lna == 2)
2874 			rssi -= 86;
2875 		else if (lna == 3)
2876 			rssi -= 100;
2877 	}
2878 	return rssi;
2879 }
2880