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