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