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