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