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