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