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