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