xref: /netbsd-src/sys/dev/ic/rt2661.c (revision 7fa608457b817eca6e0977b37f758ae064f3c99c)
1 /*	$NetBSD: rt2661.c,v 1.20 2007/10/21 17:03:37 degroote Exp $	*/
2 /*	$OpenBSD: rt2661.c,v 1.17 2006/05/01 08:41:11 damien Exp $	*/
3 /*	$FreeBSD: rt2560.c,v 1.5 2006/06/02 19:59:31 csjp Exp $	*/
4 
5 /*-
6  * Copyright (c) 2006
7  *	Damien Bergamini <damien.bergamini@free.fr>
8  *
9  * Permission to use, copy, modify, and distribute this software for any
10  * purpose with or without fee is hereby granted, provided that the above
11  * copyright notice and this permission notice appear in all copies.
12  *
13  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20  */
21 
22 /*-
23  * Ralink Technology RT2561, RT2561S and RT2661 chipset driver
24  * http://www.ralinktech.com/
25  */
26 
27 #include <sys/cdefs.h>
28 __KERNEL_RCSID(0, "$NetBSD: rt2661.c,v 1.20 2007/10/21 17:03:37 degroote Exp $");
29 
30 #include "bpfilter.h"
31 
32 #include <sys/param.h>
33 #include <sys/sockio.h>
34 #include <sys/sysctl.h>
35 #include <sys/mbuf.h>
36 #include <sys/kernel.h>
37 #include <sys/socket.h>
38 #include <sys/systm.h>
39 #include <sys/malloc.h>
40 #include <sys/callout.h>
41 #include <sys/conf.h>
42 #include <sys/device.h>
43 
44 #include <sys/bus.h>
45 #include <machine/endian.h>
46 #include <sys/intr.h>
47 
48 #if NBPFILTER > 0
49 #include <net/bpf.h>
50 #endif
51 #include <net/if.h>
52 #include <net/if_arp.h>
53 #include <net/if_dl.h>
54 #include <net/if_media.h>
55 #include <net/if_types.h>
56 #include <net/if_ether.h>
57 
58 #include <netinet/in.h>
59 #include <netinet/in_systm.h>
60 #include <netinet/in_var.h>
61 #include <netinet/ip.h>
62 
63 #include <net80211/ieee80211_var.h>
64 #include <net80211/ieee80211_rssadapt.h>
65 #include <net80211/ieee80211_radiotap.h>
66 
67 #include <dev/ic/rt2661reg.h>
68 #include <dev/ic/rt2661var.h>
69 
70 #include <dev/pci/pcireg.h>
71 #include <dev/pci/pcivar.h>
72 #include <dev/pci/pcidevs.h>
73 
74 #include <dev/firmload.h>
75 
76 #ifdef RAL_DEBUG
77 #define DPRINTF(x)	do { if (rt2661_debug > 0) printf x; } while (0)
78 #define DPRINTFN(n, x)	do { if (rt2661_debug >= (n)) printf x; } while (0)
79 int rt2661_debug = 0;
80 #else
81 #define DPRINTF(x)
82 #define DPRINTFN(n, x)
83 #endif
84 
85 static int	rt2661_alloc_tx_ring(struct rt2661_softc *,
86 		    struct rt2661_tx_ring *, int);
87 static void	rt2661_reset_tx_ring(struct rt2661_softc *,
88 		    struct rt2661_tx_ring *);
89 static void	rt2661_free_tx_ring(struct rt2661_softc *,
90 		    struct rt2661_tx_ring *);
91 static int	rt2661_alloc_rx_ring(struct rt2661_softc *,
92 		    struct rt2661_rx_ring *, int);
93 static void	rt2661_reset_rx_ring(struct rt2661_softc *,
94 		    struct rt2661_rx_ring *);
95 static void	rt2661_free_rx_ring(struct rt2661_softc *,
96 		    struct rt2661_rx_ring *);
97 static struct ieee80211_node *
98 		rt2661_node_alloc(struct ieee80211_node_table *);
99 static int	rt2661_media_change(struct ifnet *);
100 static void	rt2661_next_scan(void *);
101 static void	rt2661_iter_func(void *, struct ieee80211_node *);
102 static void	rt2661_rssadapt_updatestats(void *);
103 static int	rt2661_newstate(struct ieee80211com *, enum ieee80211_state,
104 		    int);
105 static uint16_t	rt2661_eeprom_read(struct rt2661_softc *, uint8_t);
106 static void	rt2661_tx_intr(struct rt2661_softc *);
107 static void	rt2661_tx_dma_intr(struct rt2661_softc *,
108 		    struct rt2661_tx_ring *);
109 static void	rt2661_rx_intr(struct rt2661_softc *);
110 static void	rt2661_mcu_beacon_expire(struct rt2661_softc *);
111 static void	rt2661_mcu_wakeup(struct rt2661_softc *);
112 static void	rt2661_mcu_cmd_intr(struct rt2661_softc *);
113 int		rt2661_intr(void *);
114 #if NBPFILTER > 0
115 static uint8_t	rt2661_rxrate(struct rt2661_rx_desc *);
116 #endif
117 static int	rt2661_ack_rate(struct ieee80211com *, int);
118 static uint16_t	rt2661_txtime(int, int, uint32_t);
119 static uint8_t	rt2661_plcp_signal(int);
120 static void	rt2661_setup_tx_desc(struct rt2661_softc *,
121 		    struct rt2661_tx_desc *, uint32_t, uint16_t, int, int,
122 		    const bus_dma_segment_t *, int, int);
123 static int	rt2661_tx_mgt(struct rt2661_softc *, struct mbuf *,
124 		    struct ieee80211_node *);
125 static struct mbuf *
126 		rt2661_get_rts(struct rt2661_softc *,
127 		    struct ieee80211_frame *, uint16_t);
128 static int	rt2661_tx_data(struct rt2661_softc *, struct mbuf *,
129 		    struct ieee80211_node *, int);
130 static void	rt2661_start(struct ifnet *);
131 static void	rt2661_watchdog(struct ifnet *);
132 static int	rt2661_reset(struct ifnet *);
133 static int	rt2661_ioctl(struct ifnet *, u_long, void *);
134 static void	rt2661_bbp_write(struct rt2661_softc *, uint8_t, uint8_t);
135 static uint8_t	rt2661_bbp_read(struct rt2661_softc *, uint8_t);
136 static void	rt2661_rf_write(struct rt2661_softc *, uint8_t, uint32_t);
137 static int	rt2661_tx_cmd(struct rt2661_softc *, uint8_t, uint16_t);
138 static void	rt2661_select_antenna(struct rt2661_softc *);
139 static void	rt2661_enable_mrr(struct rt2661_softc *);
140 static void	rt2661_set_txpreamble(struct rt2661_softc *);
141 static void	rt2661_set_basicrates(struct rt2661_softc *,
142 			const struct ieee80211_rateset *);
143 static void	rt2661_select_band(struct rt2661_softc *,
144 		    struct ieee80211_channel *);
145 static void	rt2661_set_chan(struct rt2661_softc *,
146 		    struct ieee80211_channel *);
147 static void	rt2661_set_bssid(struct rt2661_softc *, const uint8_t *);
148 static void	rt2661_set_macaddr(struct rt2661_softc *, const uint8_t *);
149 static void	rt2661_update_promisc(struct rt2661_softc *);
150 #if 0
151 static int	rt2661_wme_update(struct ieee80211com *);
152 #endif
153 
154 static void	rt2661_update_slot(struct ifnet *);
155 static const char *
156 		rt2661_get_rf(int);
157 static void	rt2661_read_eeprom(struct rt2661_softc *);
158 static int	rt2661_bbp_init(struct rt2661_softc *);
159 static int     	rt2661_init(struct ifnet *);
160 static void	rt2661_stop(struct ifnet *, int);
161 static int	rt2661_load_microcode(struct rt2661_softc *, const uint8_t *,
162 		    int);
163 #ifdef notyet
164 static void	rt2661_rx_tune(struct rt2661_softc *);
165 static void	rt2661_radar_start(struct rt2661_softc *);
166 static int	rt2661_radar_stop(struct rt2661_softc *);
167 #endif
168 static int	rt2661_prepare_beacon(struct rt2661_softc *);
169 static void	rt2661_enable_tsf_sync(struct rt2661_softc *);
170 static int	rt2661_get_rssi(struct rt2661_softc *, uint8_t);
171 
172 /*
173  * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
174  */
175 static const struct ieee80211_rateset rt2661_rateset_11a =
176 	{ 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
177 
178 static const struct ieee80211_rateset rt2661_rateset_11b =
179 	{ 4, { 2, 4, 11, 22 } };
180 
181 static const struct ieee80211_rateset rt2661_rateset_11g =
182 	{ 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
183 
184 /*
185  * Default values for MAC registers; values taken from the reference driver.
186  */
187 static const struct {
188 	uint32_t	reg;
189 	uint32_t	val;
190 } rt2661_def_mac[] = {
191 	{ RT2661_TXRX_CSR0,        0x0000b032 },
192 	{ RT2661_TXRX_CSR1,        0x9eb39eb3 },
193 	{ RT2661_TXRX_CSR2,        0x8a8b8c8d },
194 	{ RT2661_TXRX_CSR3,        0x00858687 },
195 	{ RT2661_TXRX_CSR7,        0x2e31353b },
196 	{ RT2661_TXRX_CSR8,        0x2a2a2a2c },
197 	{ RT2661_TXRX_CSR15,       0x0000000f },
198 	{ RT2661_MAC_CSR6,         0x00000fff },
199 	{ RT2661_MAC_CSR8,         0x016c030a },
200 	{ RT2661_MAC_CSR10,        0x00000718 },
201 	{ RT2661_MAC_CSR12,        0x00000004 },
202 	{ RT2661_MAC_CSR13,        0x0000e000 },
203 	{ RT2661_SEC_CSR0,         0x00000000 },
204 	{ RT2661_SEC_CSR1,         0x00000000 },
205 	{ RT2661_SEC_CSR5,         0x00000000 },
206 	{ RT2661_PHY_CSR1,         0x000023b0 },
207 	{ RT2661_PHY_CSR5,         0x060a100c },
208 	{ RT2661_PHY_CSR6,         0x00080606 },
209 	{ RT2661_PHY_CSR7,         0x00000a08 },
210 	{ RT2661_PCI_CFG_CSR,      0x3cca4808 },
211 	{ RT2661_AIFSN_CSR,        0x00002273 },
212 	{ RT2661_CWMIN_CSR,        0x00002344 },
213 	{ RT2661_CWMAX_CSR,        0x000034aa },
214 	{ RT2661_TEST_MODE_CSR,    0x00000200 },
215 	{ RT2661_M2H_CMD_DONE_CSR, 0xffffffff }
216 };
217 
218 /*
219  * Default values for BBP registers; values taken from the reference driver.
220  */
221 static const struct {
222 	uint8_t	reg;
223 	uint8_t	val;
224 } rt2661_def_bbp[] = {
225 	{   3, 0x00 },
226 	{  15, 0x30 },
227 	{  17, 0x20 },
228 	{  21, 0xc8 },
229 	{  22, 0x38 },
230 	{  23, 0x06 },
231 	{  24, 0xfe },
232 	{  25, 0x0a },
233 	{  26, 0x0d },
234 	{  34, 0x12 },
235 	{  37, 0x07 },
236 	{  39, 0xf8 },
237 	{  41, 0x60 },
238 	{  53, 0x10 },
239 	{  54, 0x18 },
240 	{  60, 0x10 },
241 	{  61, 0x04 },
242 	{  62, 0x04 },
243 	{  75, 0xfe },
244 	{  86, 0xfe },
245 	{  88, 0xfe },
246 	{  90, 0x0f },
247 	{  99, 0x00 },
248 	{ 102, 0x16 },
249 	{ 107, 0x04 }
250 };
251 
252 /*
253  * Default settings for RF registers; values taken from the reference driver.
254  */
255 static const struct rfprog {
256 	uint8_t		chan;
257 	uint32_t	r1;
258 	uint32_t	r2;
259 	uint32_t	r3;
260 	uint32_t	r4;
261 } rt2661_rf5225_1[] = {
262 	{   1, 0x00b33, 0x011e1, 0x1a014, 0x30282 },
263 	{   2, 0x00b33, 0x011e1, 0x1a014, 0x30287 },
264 	{   3, 0x00b33, 0x011e2, 0x1a014, 0x30282 },
265 	{   4, 0x00b33, 0x011e2, 0x1a014, 0x30287 },
266 	{   5, 0x00b33, 0x011e3, 0x1a014, 0x30282 },
267 	{   6, 0x00b33, 0x011e3, 0x1a014, 0x30287 },
268 	{   7, 0x00b33, 0x011e4, 0x1a014, 0x30282 },
269 	{   8, 0x00b33, 0x011e4, 0x1a014, 0x30287 },
270 	{   9, 0x00b33, 0x011e5, 0x1a014, 0x30282 },
271 	{  10, 0x00b33, 0x011e5, 0x1a014, 0x30287 },
272 	{  11, 0x00b33, 0x011e6, 0x1a014, 0x30282 },
273 	{  12, 0x00b33, 0x011e6, 0x1a014, 0x30287 },
274 	{  13, 0x00b33, 0x011e7, 0x1a014, 0x30282 },
275 	{  14, 0x00b33, 0x011e8, 0x1a014, 0x30284 },
276 
277 	{  36, 0x00b33, 0x01266, 0x26014, 0x30288 },
278 	{  40, 0x00b33, 0x01268, 0x26014, 0x30280 },
279 	{  44, 0x00b33, 0x01269, 0x26014, 0x30282 },
280 	{  48, 0x00b33, 0x0126a, 0x26014, 0x30284 },
281 	{  52, 0x00b33, 0x0126b, 0x26014, 0x30286 },
282 	{  56, 0x00b33, 0x0126c, 0x26014, 0x30288 },
283 	{  60, 0x00b33, 0x0126e, 0x26014, 0x30280 },
284 	{  64, 0x00b33, 0x0126f, 0x26014, 0x30282 },
285 
286 	{ 100, 0x00b33, 0x0128a, 0x2e014, 0x30280 },
287 	{ 104, 0x00b33, 0x0128b, 0x2e014, 0x30282 },
288 	{ 108, 0x00b33, 0x0128c, 0x2e014, 0x30284 },
289 	{ 112, 0x00b33, 0x0128d, 0x2e014, 0x30286 },
290 	{ 116, 0x00b33, 0x0128e, 0x2e014, 0x30288 },
291 	{ 120, 0x00b33, 0x012a0, 0x2e014, 0x30280 },
292 	{ 124, 0x00b33, 0x012a1, 0x2e014, 0x30282 },
293 	{ 128, 0x00b33, 0x012a2, 0x2e014, 0x30284 },
294 	{ 132, 0x00b33, 0x012a3, 0x2e014, 0x30286 },
295 	{ 136, 0x00b33, 0x012a4, 0x2e014, 0x30288 },
296 	{ 140, 0x00b33, 0x012a6, 0x2e014, 0x30280 },
297 
298 	{ 149, 0x00b33, 0x012a8, 0x2e014, 0x30287 },
299 	{ 153, 0x00b33, 0x012a9, 0x2e014, 0x30289 },
300 	{ 157, 0x00b33, 0x012ab, 0x2e014, 0x30281 },
301 	{ 161, 0x00b33, 0x012ac, 0x2e014, 0x30283 },
302 	{ 165, 0x00b33, 0x012ad, 0x2e014, 0x30285 }
303 
304 }, rt2661_rf5225_2[] = {
305 	{   1, 0x00b33, 0x011e1, 0x1a014, 0x30282 },
306 	{   2, 0x00b33, 0x011e1, 0x1a014, 0x30287 },
307 	{   3, 0x00b33, 0x011e2, 0x1a014, 0x30282 },
308 	{   4, 0x00b33, 0x011e2, 0x1a014, 0x30287 },
309 	{   5, 0x00b33, 0x011e3, 0x1a014, 0x30282 },
310 	{   6, 0x00b33, 0x011e3, 0x1a014, 0x30287 },
311 	{   7, 0x00b33, 0x011e4, 0x1a014, 0x30282 },
312 	{   8, 0x00b33, 0x011e4, 0x1a014, 0x30287 },
313 	{   9, 0x00b33, 0x011e5, 0x1a014, 0x30282 },
314 	{  10, 0x00b33, 0x011e5, 0x1a014, 0x30287 },
315 	{  11, 0x00b33, 0x011e6, 0x1a014, 0x30282 },
316 	{  12, 0x00b33, 0x011e6, 0x1a014, 0x30287 },
317 	{  13, 0x00b33, 0x011e7, 0x1a014, 0x30282 },
318 	{  14, 0x00b33, 0x011e8, 0x1a014, 0x30284 },
319 
320 	{  36, 0x00b35, 0x11206, 0x26014, 0x30280 },
321 	{  40, 0x00b34, 0x111a0, 0x26014, 0x30280 },
322 	{  44, 0x00b34, 0x111a1, 0x26014, 0x30286 },
323 	{  48, 0x00b34, 0x111a3, 0x26014, 0x30282 },
324 	{  52, 0x00b34, 0x111a4, 0x26014, 0x30288 },
325 	{  56, 0x00b34, 0x111a6, 0x26014, 0x30284 },
326 	{  60, 0x00b34, 0x111a8, 0x26014, 0x30280 },
327 	{  64, 0x00b34, 0x111a9, 0x26014, 0x30286 },
328 
329 	{ 100, 0x00b35, 0x11226, 0x2e014, 0x30280 },
330 	{ 104, 0x00b35, 0x11228, 0x2e014, 0x30280 },
331 	{ 108, 0x00b35, 0x1122a, 0x2e014, 0x30280 },
332 	{ 112, 0x00b35, 0x1122c, 0x2e014, 0x30280 },
333 	{ 116, 0x00b35, 0x1122e, 0x2e014, 0x30280 },
334 	{ 120, 0x00b34, 0x111c0, 0x2e014, 0x30280 },
335 	{ 124, 0x00b34, 0x111c1, 0x2e014, 0x30286 },
336 	{ 128, 0x00b34, 0x111c3, 0x2e014, 0x30282 },
337 	{ 132, 0x00b34, 0x111c4, 0x2e014, 0x30288 },
338 	{ 136, 0x00b34, 0x111c6, 0x2e014, 0x30284 },
339 	{ 140, 0x00b34, 0x111c8, 0x2e014, 0x30280 },
340 
341 	{ 149, 0x00b34, 0x111cb, 0x2e014, 0x30286 },
342 	{ 153, 0x00b34, 0x111cd, 0x2e014, 0x30282 },
343 	{ 157, 0x00b35, 0x11242, 0x2e014, 0x30285 },
344 	{ 161, 0x00b35, 0x11244, 0x2e014, 0x30285 },
345 	{ 165, 0x00b35, 0x11246, 0x2e014, 0x30285 }
346 };
347 
348 int
349 rt2661_attach(void *xsc, int id)
350 {
351 	struct rt2661_softc *sc = xsc;
352 	struct ieee80211com *ic = &sc->sc_ic;
353 	struct ifnet *ifp = &sc->sc_if;
354 	uint32_t val;
355 	int error, i, ntries;
356 
357 	sc->sc_id = id;
358 
359 	callout_init(&sc->scan_ch, 0);
360 	callout_init(&sc->rssadapt_ch, 0);
361 
362 	/* wait for NIC to initialize */
363 	for (ntries = 0; ntries < 1000; ntries++) {
364 		if ((val = RAL_READ(sc, RT2661_MAC_CSR0)) != 0)
365 			break;
366 		DELAY(1000);
367 	}
368 	if (ntries == 1000) {
369 		aprint_error("%s: timeout waiting for NIC to initialize\n",
370 		    sc->sc_dev.dv_xname);
371 		return EIO;
372 	}
373 
374 	/* retrieve RF rev. no and various other things from EEPROM */
375 	rt2661_read_eeprom(sc);
376 	aprint_normal("%s: 802.11 address %s\n", sc->sc_dev.dv_xname,
377 	    ether_sprintf(ic->ic_myaddr));
378 
379 	aprint_normal("%s: MAC/BBP RT%X, RF %s\n", sc->sc_dev.dv_xname, val,
380 	    rt2661_get_rf(sc->rf_rev));
381 
382 	/*
383 	 * Allocate Tx and Rx rings.
384 	 */
385 	error = rt2661_alloc_tx_ring(sc, &sc->txq[0], RT2661_TX_RING_COUNT);
386 	if (error != 0) {
387 		aprint_error("%s: could not allocate Tx ring 0\n",
388 		    sc->sc_dev.dv_xname);
389 		goto fail1;
390 	}
391 
392 	error = rt2661_alloc_tx_ring(sc, &sc->txq[1], RT2661_TX_RING_COUNT);
393 	if (error != 0) {
394 		aprint_error("%s: could not allocate Tx ring 1\n",
395 		    sc->sc_dev.dv_xname);
396 		goto fail2;
397 	}
398 
399 	error = rt2661_alloc_tx_ring(sc, &sc->txq[2], RT2661_TX_RING_COUNT);
400 	if (error != 0) {
401 		aprint_error("%s: could not allocate Tx ring 2\n",
402 		    sc->sc_dev.dv_xname);
403 		goto fail3;
404 	}
405 
406 	error = rt2661_alloc_tx_ring(sc, &sc->txq[3], RT2661_TX_RING_COUNT);
407 	if (error != 0) {
408 		aprint_error("%s: could not allocate Tx ring 3\n",
409 		    sc->sc_dev.dv_xname);
410 		goto fail4;
411 	}
412 
413 	error = rt2661_alloc_tx_ring(sc, &sc->mgtq, RT2661_MGT_RING_COUNT);
414 	if (error != 0) {
415 		aprint_error("%s: could not allocate Mgt ring\n",
416 		    sc->sc_dev.dv_xname);
417 		goto fail5;
418 	}
419 
420 	error = rt2661_alloc_rx_ring(sc, &sc->rxq, RT2661_RX_RING_COUNT);
421 	if (error != 0) {
422 		aprint_error("%s: could not allocate Rx ring\n",
423 		    sc->sc_dev.dv_xname);
424 		goto fail6;
425 	}
426 
427 	ifp->if_softc = sc;
428 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
429 	ifp->if_init = rt2661_init;
430 	ifp->if_ioctl = rt2661_ioctl;
431 	ifp->if_start = rt2661_start;
432 	ifp->if_watchdog = rt2661_watchdog;
433 	IFQ_SET_READY(&ifp->if_snd);
434 	memcpy(ifp->if_xname, sc->sc_dev.dv_xname, IFNAMSIZ);
435 
436 	ic->ic_ifp = ifp;
437 	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
438 	ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */
439 	ic->ic_state = IEEE80211_S_INIT;
440 
441 	/* set device capabilities */
442 	ic->ic_caps =
443 	    IEEE80211_C_IBSS |		/* IBSS mode supported */
444 	    IEEE80211_C_MONITOR |	/* monitor mode supported */
445 	    IEEE80211_C_HOSTAP |	/* HostAp mode supported */
446 	    IEEE80211_C_TXPMGT |	/* tx power management */
447 	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
448 	    IEEE80211_C_SHSLOT |	/* short slot time supported */
449 	    IEEE80211_C_WPA;		/* 802.11i */
450 
451 	if (sc->rf_rev == RT2661_RF_5225 || sc->rf_rev == RT2661_RF_5325) {
452 		/* set supported .11a rates */
453 		ic->ic_sup_rates[IEEE80211_MODE_11A] = rt2661_rateset_11a;
454 
455 		/* set supported .11a channels */
456 		for (i = 36; i <= 64; i += 4) {
457 			ic->ic_channels[i].ic_freq =
458 			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
459 			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
460 		}
461 		for (i = 100; i <= 140; i += 4) {
462 			ic->ic_channels[i].ic_freq =
463 			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
464 			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
465 		}
466 		for (i = 149; i <= 165; i += 4) {
467 			ic->ic_channels[i].ic_freq =
468 			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
469 			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
470 		}
471 	}
472 
473 	/* set supported .11b and .11g rates */
474 	ic->ic_sup_rates[IEEE80211_MODE_11B] = rt2661_rateset_11b;
475 	ic->ic_sup_rates[IEEE80211_MODE_11G] = rt2661_rateset_11g;
476 
477 	/* set supported .11b and .11g channels (1 through 14) */
478 	for (i = 1; i <= 14; i++) {
479 		ic->ic_channels[i].ic_freq =
480 		    ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
481 		ic->ic_channels[i].ic_flags =
482 		    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
483 		    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
484 	}
485 
486 	if_attach(ifp);
487 	ieee80211_ifattach(ic);
488 	ic->ic_node_alloc = rt2661_node_alloc;
489 	ic->ic_updateslot = rt2661_update_slot;
490 	ic->ic_reset = rt2661_reset;
491 
492 	/* override state transition machine */
493 	sc->sc_newstate = ic->ic_newstate;
494 	ic->ic_newstate = rt2661_newstate;
495 	ieee80211_media_init(ic, rt2661_media_change, ieee80211_media_status);
496 
497 #if NBPFILTER > 0
498 	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
499 	    sizeof (struct ieee80211_frame) + 64, &sc->sc_drvbpf);
500 
501 	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
502 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
503 	sc->sc_rxtap.wr_ihdr.it_present = htole32(RT2661_RX_RADIOTAP_PRESENT);
504 
505 	sc->sc_txtap_len = sizeof sc->sc_txtapu;
506 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
507 	sc->sc_txtap.wt_ihdr.it_present = htole32(RT2661_TX_RADIOTAP_PRESENT);
508 #endif
509 
510 	ieee80211_announce(ic);
511 
512 	return 0;
513 
514 fail6:	rt2661_free_tx_ring(sc, &sc->mgtq);
515 fail5:	rt2661_free_tx_ring(sc, &sc->txq[3]);
516 fail4:	rt2661_free_tx_ring(sc, &sc->txq[2]);
517 fail3:	rt2661_free_tx_ring(sc, &sc->txq[1]);
518 fail2:	rt2661_free_tx_ring(sc, &sc->txq[0]);
519 fail1:	return ENXIO;
520 }
521 
522 int
523 rt2661_detach(void *xsc)
524 {
525 	struct rt2661_softc *sc = xsc;
526 	struct ifnet *ifp = &sc->sc_if;
527 
528 	callout_stop(&sc->scan_ch);
529 	callout_stop(&sc->rssadapt_ch);
530 
531 	ieee80211_ifdetach(&sc->sc_ic);
532 	if_detach(ifp);
533 
534 	rt2661_free_tx_ring(sc, &sc->txq[0]);
535 	rt2661_free_tx_ring(sc, &sc->txq[1]);
536 	rt2661_free_tx_ring(sc, &sc->txq[2]);
537 	rt2661_free_tx_ring(sc, &sc->txq[3]);
538 	rt2661_free_tx_ring(sc, &sc->mgtq);
539 	rt2661_free_rx_ring(sc, &sc->rxq);
540 
541 	return 0;
542 }
543 
544 static int
545 rt2661_alloc_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring,
546     int count)
547 {
548 	int i, nsegs, error;
549 
550 	ring->count = count;
551 	ring->queued = 0;
552 	ring->cur = ring->next = ring->stat = 0;
553 
554 	error = bus_dmamap_create(sc->sc_dmat, count * RT2661_TX_DESC_SIZE, 1,
555 	    count * RT2661_TX_DESC_SIZE, 0, BUS_DMA_NOWAIT, &ring->map);
556 	if (error != 0) {
557 		aprint_error("%s: could not create desc DMA map\n",
558 		    sc->sc_dev.dv_xname);
559 		goto fail;
560 	}
561 
562 	error = bus_dmamem_alloc(sc->sc_dmat, count * RT2661_TX_DESC_SIZE,
563 	    PAGE_SIZE, 0, &ring->seg, 1, &nsegs, BUS_DMA_NOWAIT);
564 	if (error != 0) {
565 		aprint_error("%s: could not allocate DMA memory\n",
566 		    sc->sc_dev.dv_xname);
567 		goto fail;
568 	}
569 
570 	error = bus_dmamem_map(sc->sc_dmat, &ring->seg, nsegs,
571 	    count * RT2661_TX_DESC_SIZE, (void **)&ring->desc,
572 	    BUS_DMA_NOWAIT);
573 	if (error != 0) {
574 		aprint_error("%s: could not map desc DMA memory\n",
575 		    sc->sc_dev.dv_xname);
576 		goto fail;
577 	}
578 
579 	error = bus_dmamap_load(sc->sc_dmat, ring->map, ring->desc,
580 	    count * RT2661_TX_DESC_SIZE, NULL, BUS_DMA_NOWAIT);
581 	if (error != 0) {
582 		aprint_error("%s: could not load desc DMA map\n",
583 		    sc->sc_dev.dv_xname);
584 		goto fail;
585 	}
586 
587 	memset(ring->desc, 0, count * RT2661_TX_DESC_SIZE);
588 	ring->physaddr = ring->map->dm_segs->ds_addr;
589 
590 	ring->data = malloc(count * sizeof (struct rt2661_tx_data), M_DEVBUF,
591 	    M_NOWAIT);
592 	if (ring->data == NULL) {
593 		aprint_error("%s: could not allocate soft data\n",
594 		    sc->sc_dev.dv_xname);
595 		error = ENOMEM;
596 		goto fail;
597 	}
598 
599 	memset(ring->data, 0, count * sizeof (struct rt2661_tx_data));
600 	for (i = 0; i < count; i++) {
601 		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES,
602 		    RT2661_MAX_SCATTER, MCLBYTES, 0, BUS_DMA_NOWAIT,
603 		    &ring->data[i].map);
604 		if (error != 0) {
605 			aprint_error("%s: could not create DMA map\n",
606 			    sc->sc_dev.dv_xname);
607 			goto fail;
608 		}
609 	}
610 
611 	return 0;
612 
613 fail:	rt2661_free_tx_ring(sc, ring);
614 	return error;
615 }
616 
617 static void
618 rt2661_reset_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring)
619 {
620 	struct rt2661_tx_desc *desc;
621 	struct rt2661_tx_data *data;
622 	int i;
623 
624 	for (i = 0; i < ring->count; i++) {
625 		desc = &ring->desc[i];
626 		data = &ring->data[i];
627 
628 		if (data->m != NULL) {
629 			bus_dmamap_sync(sc->sc_dmat, data->map, 0,
630 			    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
631 			bus_dmamap_unload(sc->sc_dmat, data->map);
632 			m_freem(data->m);
633 			data->m = NULL;
634 		}
635 
636 		if (data->ni != NULL) {
637 			ieee80211_free_node(data->ni);
638 			data->ni = NULL;
639 		}
640 
641 		desc->flags = 0;
642 	}
643 
644 	bus_dmamap_sync(sc->sc_dmat, ring->map, 0, ring->map->dm_mapsize,
645 	    BUS_DMASYNC_PREWRITE);
646 
647 	ring->queued = 0;
648 	ring->cur = ring->next = ring->stat = 0;
649 }
650 
651 
652 static void
653 rt2661_free_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring)
654 {
655 	struct rt2661_tx_data *data;
656 	int i;
657 
658 	if (ring->desc != NULL) {
659 		bus_dmamap_sync(sc->sc_dmat, ring->map, 0,
660 		    ring->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
661 		bus_dmamap_unload(sc->sc_dmat, ring->map);
662 		bus_dmamem_unmap(sc->sc_dmat, (void *)ring->desc,
663 		    ring->count * RT2661_TX_DESC_SIZE);
664 		bus_dmamem_free(sc->sc_dmat, &ring->seg, 1);
665 	}
666 
667 	if (ring->data != NULL) {
668 		for (i = 0; i < ring->count; i++) {
669 			data = &ring->data[i];
670 
671 			if (data->m != NULL) {
672 				bus_dmamap_sync(sc->sc_dmat, data->map, 0,
673 				    data->map->dm_mapsize,
674 				    BUS_DMASYNC_POSTWRITE);
675 				bus_dmamap_unload(sc->sc_dmat, data->map);
676 				m_freem(data->m);
677 			}
678 
679 			if (data->ni != NULL)
680 				ieee80211_free_node(data->ni);
681 
682 			if (data->map != NULL)
683 				bus_dmamap_destroy(sc->sc_dmat, data->map);
684 		}
685 		free(ring->data, M_DEVBUF);
686 	}
687 }
688 
689 static int
690 rt2661_alloc_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring,
691     int count)
692 {
693 	struct rt2661_rx_desc *desc;
694 	struct rt2661_rx_data *data;
695 	int i, nsegs, error;
696 
697 	ring->count = count;
698 	ring->cur = ring->next = 0;
699 
700 	error = bus_dmamap_create(sc->sc_dmat, count * RT2661_RX_DESC_SIZE, 1,
701 	    count * RT2661_RX_DESC_SIZE, 0, BUS_DMA_NOWAIT, &ring->map);
702 	if (error != 0) {
703 		aprint_error("%s: could not create desc DMA map\n",
704 		    sc->sc_dev.dv_xname);
705 		goto fail;
706 	}
707 
708 	error = bus_dmamem_alloc(sc->sc_dmat, count * RT2661_RX_DESC_SIZE,
709 	    PAGE_SIZE, 0, &ring->seg, 1, &nsegs, BUS_DMA_NOWAIT);
710 	if (error != 0) {
711 		aprint_error("%s: could not allocate DMA memory\n",
712 		    sc->sc_dev.dv_xname);
713 		goto fail;
714 	}
715 
716 	error = bus_dmamem_map(sc->sc_dmat, &ring->seg, nsegs,
717 	    count * RT2661_RX_DESC_SIZE, (void **)&ring->desc,
718 	    BUS_DMA_NOWAIT);
719 	if (error != 0) {
720 		aprint_error("%s: could not map desc DMA memory\n",
721 		    sc->sc_dev.dv_xname);
722 		goto fail;
723 	}
724 
725 	error = bus_dmamap_load(sc->sc_dmat, ring->map, ring->desc,
726 	    count * RT2661_RX_DESC_SIZE, NULL, BUS_DMA_NOWAIT);
727 	if (error != 0) {
728 		aprint_error("%s: could not load desc DMA map\n",
729 		    sc->sc_dev.dv_xname);
730 		goto fail;
731 	}
732 
733 	memset(ring->desc, 0, count * RT2661_RX_DESC_SIZE);
734 	ring->physaddr = ring->map->dm_segs->ds_addr;
735 
736 	ring->data = malloc(count * sizeof (struct rt2661_rx_data), M_DEVBUF,
737 	    M_NOWAIT);
738 	if (ring->data == NULL) {
739 		aprint_error("%s: could not allocate soft data\n",
740 		    sc->sc_dev.dv_xname);
741 		error = ENOMEM;
742 		goto fail;
743 	}
744 
745 	/*
746 	 * Pre-allocate Rx buffers and populate Rx ring.
747 	 */
748 	memset(ring->data, 0, count * sizeof (struct rt2661_rx_data));
749 	for (i = 0; i < count; i++) {
750 		desc = &sc->rxq.desc[i];
751 		data = &sc->rxq.data[i];
752 
753 		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES, 1, MCLBYTES,
754 		    0, BUS_DMA_NOWAIT, &data->map);
755 		if (error != 0) {
756 			printf("%s: could not create DMA map\n",
757 			    sc->sc_dev.dv_xname);
758 			goto fail;
759 		}
760 
761 		MGETHDR(data->m, M_DONTWAIT, MT_DATA);
762 		if (data->m == NULL) {
763 			printf("%s: could not allocate rx mbuf\n",
764 			    sc->sc_dev.dv_xname);
765 			error = ENOMEM;
766 			goto fail;
767 		}
768 
769 		MCLGET(data->m, M_DONTWAIT);
770 		if (!(data->m->m_flags & M_EXT)) {
771 			printf("%s: could not allocate rx mbuf cluster\n",
772 			    sc->sc_dev.dv_xname);
773 			error = ENOMEM;
774 			goto fail;
775 		}
776 
777 		error = bus_dmamap_load(sc->sc_dmat, data->map,
778 		    mtod(data->m, void *), MCLBYTES, NULL, BUS_DMA_NOWAIT);
779 		if (error != 0) {
780 			printf("%s: could not load rx buf DMA map",
781 			    sc->sc_dev.dv_xname);
782 			goto fail;
783 		}
784 
785 		desc->flags = htole32(RT2661_RX_BUSY);
786 		desc->physaddr = htole32(data->map->dm_segs->ds_addr);
787 	}
788 
789 	bus_dmamap_sync(sc->sc_dmat, ring->map, 0, ring->map->dm_mapsize,
790 	    BUS_DMASYNC_PREWRITE);
791 
792 	return 0;
793 
794 fail:	rt2661_free_rx_ring(sc, ring);
795 	return error;
796 }
797 
798 static void
799 rt2661_reset_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring)
800 {
801 	int i;
802 
803 	for (i = 0; i < ring->count; i++)
804 		ring->desc[i].flags = htole32(RT2661_RX_BUSY);
805 
806 	bus_dmamap_sync(sc->sc_dmat, ring->map, 0, ring->map->dm_mapsize,
807 	    BUS_DMASYNC_PREWRITE);
808 
809 	ring->cur = ring->next = 0;
810 }
811 
812 static void
813 rt2661_free_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring)
814 {
815 	struct rt2661_rx_data *data;
816 	int i;
817 
818 	if (ring->desc != NULL) {
819 		bus_dmamap_sync(sc->sc_dmat, ring->map, 0,
820 		    ring->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
821 		bus_dmamap_unload(sc->sc_dmat, ring->map);
822 		bus_dmamem_unmap(sc->sc_dmat, (void *)ring->desc,
823 		    ring->count * RT2661_RX_DESC_SIZE);
824 		bus_dmamem_free(sc->sc_dmat, &ring->seg, 1);
825 	}
826 
827 	if (ring->data != NULL) {
828 		for (i = 0; i < ring->count; i++) {
829 			data = &ring->data[i];
830 
831 			if (data->m != NULL) {
832 				bus_dmamap_sync(sc->sc_dmat, data->map, 0,
833 				    data->map->dm_mapsize,
834 				    BUS_DMASYNC_POSTREAD);
835 				bus_dmamap_unload(sc->sc_dmat, data->map);
836 				m_freem(data->m);
837 			}
838 
839 			if (data->map != NULL)
840 				bus_dmamap_destroy(sc->sc_dmat, data->map);
841 		}
842 		free(ring->data, M_DEVBUF);
843 	}
844 }
845 
846 static struct ieee80211_node *
847 rt2661_node_alloc(struct ieee80211_node_table *nt)
848 {
849 	struct rt2661_node *rn;
850 
851 	rn = malloc(sizeof (struct rt2661_node), M_80211_NODE,
852 	    M_NOWAIT | M_ZERO);
853 
854 	return (rn != NULL) ? &rn->ni : NULL;
855 }
856 
857 static int
858 rt2661_media_change(struct ifnet *ifp)
859 {
860 	int error;
861 
862 	error = ieee80211_media_change(ifp);
863 	if (error != ENETRESET)
864 		return error;
865 
866 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
867 		rt2661_init(ifp);
868 
869 	return 0;
870 }
871 
872 /*
873  * This function is called periodically (every 200ms) during scanning to
874  * switch from one channel to another.
875  */
876 static void
877 rt2661_next_scan(void *arg)
878 {
879 	struct rt2661_softc *sc = arg;
880 	struct ieee80211com *ic = &sc->sc_ic;
881 
882 	if (ic->ic_state == IEEE80211_S_SCAN)
883 		ieee80211_next_scan(ic);
884 }
885 
886 /*
887  * This function is called for each neighbor node.
888  */
889 static void
890 rt2661_iter_func(void *arg, struct ieee80211_node *ni)
891 {
892 	struct rt2661_node *rn = (struct rt2661_node *)ni;
893 
894 	ieee80211_rssadapt_updatestats(&rn->rssadapt);
895 }
896 
897 /*
898  * This function is called periodically (every 100ms) in RUN state to update
899  * the rate adaptation statistics.
900  */
901 static void
902 rt2661_rssadapt_updatestats(void *arg)
903 {
904 	struct rt2661_softc *sc = arg;
905 	struct ieee80211com *ic = &sc->sc_ic;
906 
907 	ieee80211_iterate_nodes(&ic->ic_sta, rt2661_iter_func, arg);
908 
909 	callout_reset(&sc->rssadapt_ch, hz / 10, rt2661_rssadapt_updatestats,
910 	    sc);
911 }
912 
913 static int
914 rt2661_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
915 {
916 	struct rt2661_softc *sc = ic->ic_ifp->if_softc;
917 	enum ieee80211_state ostate;
918 	struct ieee80211_node *ni;
919 	uint32_t tmp;
920 	int error = 0;
921 
922 	ostate = ic->ic_state;
923 	callout_stop(&sc->scan_ch);
924 
925 	switch (nstate) {
926 	case IEEE80211_S_INIT:
927 		callout_stop(&sc->rssadapt_ch);
928 
929 		if (ostate == IEEE80211_S_RUN) {
930 			/* abort TSF synchronization */
931 			tmp = RAL_READ(sc, RT2661_TXRX_CSR9);
932 			RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp & ~0x00ffffff);
933 		}
934 		break;
935 
936 	case IEEE80211_S_SCAN:
937 		rt2661_set_chan(sc, ic->ic_curchan);
938 		callout_reset(&sc->scan_ch, hz / 5, rt2661_next_scan, sc);
939 		break;
940 
941 	case IEEE80211_S_AUTH:
942 	case IEEE80211_S_ASSOC:
943 		rt2661_set_chan(sc, ic->ic_curchan);
944 		break;
945 
946 	case IEEE80211_S_RUN:
947 		rt2661_set_chan(sc, ic->ic_curchan);
948 
949 		ni = ic->ic_bss;
950 
951 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
952 			rt2661_enable_mrr(sc);
953 			rt2661_set_txpreamble(sc);
954 			rt2661_set_basicrates(sc, &ni->ni_rates);
955 			rt2661_set_bssid(sc, ni->ni_bssid);
956 		}
957 
958 		if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
959 		    ic->ic_opmode == IEEE80211_M_IBSS) {
960 			if ((error = rt2661_prepare_beacon(sc)) != 0)
961 				break;
962 		}
963 
964 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
965 			callout_reset(&sc->rssadapt_ch, hz / 10,
966 			    rt2661_rssadapt_updatestats, sc);
967 			rt2661_enable_tsf_sync(sc);
968 		}
969 		break;
970 	}
971 
972 	return (error != 0) ? error : sc->sc_newstate(ic, nstate, arg);
973 }
974 
975 /*
976  * Read 16 bits at address 'addr' from the serial EEPROM (either 93C46 or
977  * 93C66).
978  */
979 static uint16_t
980 rt2661_eeprom_read(struct rt2661_softc *sc, uint8_t addr)
981 {
982 	uint32_t tmp;
983 	uint16_t val;
984 	int n;
985 
986 	/* clock C once before the first command */
987 	RT2661_EEPROM_CTL(sc, 0);
988 
989 	RT2661_EEPROM_CTL(sc, RT2661_S);
990 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
991 	RT2661_EEPROM_CTL(sc, RT2661_S);
992 
993 	/* write start bit (1) */
994 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
995 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
996 
997 	/* write READ opcode (10) */
998 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
999 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
1000 	RT2661_EEPROM_CTL(sc, RT2661_S);
1001 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
1002 
1003 	/* write address (A5-A0 or A7-A0) */
1004 	n = (RAL_READ(sc, RT2661_E2PROM_CSR) & RT2661_93C46) ? 5 : 7;
1005 	for (; n >= 0; n--) {
1006 		RT2661_EEPROM_CTL(sc, RT2661_S |
1007 		    (((addr >> n) & 1) << RT2661_SHIFT_D));
1008 		RT2661_EEPROM_CTL(sc, RT2661_S |
1009 		    (((addr >> n) & 1) << RT2661_SHIFT_D) | RT2661_C);
1010 	}
1011 
1012 	RT2661_EEPROM_CTL(sc, RT2661_S);
1013 
1014 	/* read data Q15-Q0 */
1015 	val = 0;
1016 	for (n = 15; n >= 0; n--) {
1017 		RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
1018 		tmp = RAL_READ(sc, RT2661_E2PROM_CSR);
1019 		val |= ((tmp & RT2661_Q) >> RT2661_SHIFT_Q) << n;
1020 		RT2661_EEPROM_CTL(sc, RT2661_S);
1021 	}
1022 
1023 	RT2661_EEPROM_CTL(sc, 0);
1024 
1025 	/* clear Chip Select and clock C */
1026 	RT2661_EEPROM_CTL(sc, RT2661_S);
1027 	RT2661_EEPROM_CTL(sc, 0);
1028 	RT2661_EEPROM_CTL(sc, RT2661_C);
1029 
1030 	return val;
1031 }
1032 
1033 static void
1034 rt2661_tx_intr(struct rt2661_softc *sc)
1035 {
1036 	struct ieee80211com *ic = &sc->sc_ic;
1037 	struct ifnet *ifp = &sc->sc_if;
1038 	struct rt2661_tx_ring *txq;
1039 	struct rt2661_tx_data *data;
1040 	struct rt2661_node *rn;
1041 	uint32_t val;
1042 	int qid, retrycnt;
1043 
1044 	for (;;) {
1045 		val = RAL_READ(sc, RT2661_STA_CSR4);
1046 		if (!(val & RT2661_TX_STAT_VALID))
1047 			break;
1048 
1049 		/* retrieve the queue in which this frame was sent */
1050 		qid = RT2661_TX_QID(val);
1051 		txq = (qid <= 3) ? &sc->txq[qid] : &sc->mgtq;
1052 
1053 		/* retrieve rate control algorithm context */
1054 		data = &txq->data[txq->stat];
1055 		rn = (struct rt2661_node *)data->ni;
1056 
1057 		/* if no frame has been sent, ignore */
1058 		if (rn == NULL)
1059 			continue;
1060 
1061 		switch (RT2661_TX_RESULT(val)) {
1062 		case RT2661_TX_SUCCESS:
1063 			retrycnt = RT2661_TX_RETRYCNT(val);
1064 
1065 			DPRINTFN(10, ("data frame sent successfully after "
1066 			    "%d retries\n", retrycnt));
1067 			if (retrycnt == 0 && data->id.id_node != NULL) {
1068 				ieee80211_rssadapt_raise_rate(ic,
1069 				    &rn->rssadapt, &data->id);
1070 			}
1071 			ifp->if_opackets++;
1072 			break;
1073 
1074 		case RT2661_TX_RETRY_FAIL:
1075 			DPRINTFN(9, ("sending data frame failed (too much "
1076 			    "retries)\n"));
1077 			if (data->id.id_node != NULL) {
1078 				ieee80211_rssadapt_lower_rate(ic, data->ni,
1079 				    &rn->rssadapt, &data->id);
1080 			}
1081 			ifp->if_oerrors++;
1082 			break;
1083 
1084 		default:
1085 			/* other failure */
1086 			printf("%s: sending data frame failed 0x%08x\n",
1087 			    sc->sc_dev.dv_xname, val);
1088 			ifp->if_oerrors++;
1089 		}
1090 
1091 		ieee80211_free_node(data->ni);
1092 		data->ni = NULL;
1093 
1094 		DPRINTFN(15, ("tx done q=%d idx=%u\n", qid, txq->stat));
1095 
1096 		txq->queued--;
1097 		if (++txq->stat >= txq->count)	/* faster than % count */
1098 			txq->stat = 0;
1099 	}
1100 
1101 	sc->sc_tx_timer = 0;
1102 	ifp->if_flags &= ~IFF_OACTIVE;
1103 	rt2661_start(ifp);
1104 }
1105 
1106 static void
1107 rt2661_tx_dma_intr(struct rt2661_softc *sc, struct rt2661_tx_ring *txq)
1108 {
1109 	struct rt2661_tx_desc *desc;
1110 	struct rt2661_tx_data *data;
1111 
1112 	for (;;) {
1113 		desc = &txq->desc[txq->next];
1114 		data = &txq->data[txq->next];
1115 
1116 		bus_dmamap_sync(sc->sc_dmat, txq->map,
1117 		    txq->next * RT2661_TX_DESC_SIZE, RT2661_TX_DESC_SIZE,
1118 		    BUS_DMASYNC_POSTREAD);
1119 
1120 		if ((le32toh(desc->flags) & RT2661_TX_BUSY) ||
1121 		    !(le32toh(desc->flags) & RT2661_TX_VALID))
1122 			break;
1123 
1124 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1125 		    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
1126 		bus_dmamap_unload(sc->sc_dmat, data->map);
1127 		m_freem(data->m);
1128 		data->m = NULL;
1129 		/* node reference is released in rt2661_tx_intr() */
1130 
1131 		/* descriptor is no longer valid */
1132 		desc->flags &= ~htole32(RT2661_TX_VALID);
1133 
1134 		bus_dmamap_sync(sc->sc_dmat, txq->map,
1135 		    txq->next * RT2661_TX_DESC_SIZE, RT2661_TX_DESC_SIZE,
1136 		    BUS_DMASYNC_PREWRITE);
1137 
1138 		DPRINTFN(15, ("tx dma done q=%p idx=%u\n", txq, txq->next));
1139 
1140 		if (++txq->next >= txq->count)	/* faster than % count */
1141 			txq->next = 0;
1142 	}
1143 }
1144 
1145 static void
1146 rt2661_rx_intr(struct rt2661_softc *sc)
1147 {
1148 	struct ieee80211com *ic = &sc->sc_ic;
1149 	struct ifnet *ifp = &sc->sc_if;
1150 	struct rt2661_rx_desc *desc;
1151 	struct rt2661_rx_data *data;
1152 	struct rt2661_node *rn;
1153 	struct ieee80211_frame *wh;
1154 	struct ieee80211_node *ni;
1155 	struct mbuf *mnew, *m;
1156 	int error;
1157 
1158 	for (;;) {
1159 		desc = &sc->rxq.desc[sc->rxq.cur];
1160 		data = &sc->rxq.data[sc->rxq.cur];
1161 
1162 		bus_dmamap_sync(sc->sc_dmat, sc->rxq.map,
1163 		    sc->rxq.cur * RT2661_RX_DESC_SIZE, RT2661_RX_DESC_SIZE,
1164 		    BUS_DMASYNC_POSTREAD);
1165 
1166 		if (le32toh(desc->flags) & RT2661_RX_BUSY)
1167 			break;
1168 
1169 		if ((le32toh(desc->flags) & RT2661_RX_PHY_ERROR) ||
1170 		    (le32toh(desc->flags) & RT2661_RX_CRC_ERROR)) {
1171 			/*
1172 			 * This should not happen since we did not request
1173 			 * to receive those frames when we filled TXRX_CSR0.
1174 			 */
1175 			DPRINTFN(5, ("PHY or CRC error flags 0x%08x\n",
1176 			    le32toh(desc->flags)));
1177 			ifp->if_ierrors++;
1178 			goto skip;
1179 		}
1180 
1181 		if ((le32toh(desc->flags) & RT2661_RX_CIPHER_MASK) != 0) {
1182 			ifp->if_ierrors++;
1183 			goto skip;
1184 		}
1185 
1186 		/*
1187 		 * Try to allocate a new mbuf for this ring element and load it
1188 		 * before processing the current mbuf. If the ring element
1189 		 * cannot be loaded, drop the received packet and reuse the old
1190 		 * mbuf. In the unlikely case that the old mbuf can't be
1191 		 * reloaded either, explicitly panic.
1192 		 */
1193 		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
1194 		if (mnew == NULL) {
1195 			ifp->if_ierrors++;
1196 			goto skip;
1197 		}
1198 
1199 		MCLGET(mnew, M_DONTWAIT);
1200 		if (!(mnew->m_flags & M_EXT)) {
1201 			m_freem(mnew);
1202 			ifp->if_ierrors++;
1203 			goto skip;
1204 		}
1205 
1206 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1207 		    data->map->dm_mapsize, BUS_DMASYNC_POSTREAD);
1208 		bus_dmamap_unload(sc->sc_dmat, data->map);
1209 
1210 		error = bus_dmamap_load(sc->sc_dmat, data->map,
1211 		    mtod(mnew, void *), MCLBYTES, NULL, BUS_DMA_NOWAIT);
1212 		if (error != 0) {
1213 			m_freem(mnew);
1214 
1215 			/* try to reload the old mbuf */
1216 			error = bus_dmamap_load(sc->sc_dmat, data->map,
1217 			    mtod(data->m, void *), MCLBYTES, NULL,
1218 			    BUS_DMA_NOWAIT);
1219 			if (error != 0) {
1220 				/* very unlikely that it will fail... */
1221 				panic("%s: could not load old rx mbuf",
1222 				    sc->sc_dev.dv_xname);
1223 			}
1224 			ifp->if_ierrors++;
1225 			goto skip;
1226 		}
1227 
1228 		/*
1229 	 	 * New mbuf successfully loaded, update Rx ring and continue
1230 		 * processing.
1231 		 */
1232 		m = data->m;
1233 		data->m = mnew;
1234 		desc->physaddr = htole32(data->map->dm_segs->ds_addr);
1235 
1236 		/* finalize mbuf */
1237 		m->m_pkthdr.rcvif = ifp;
1238 		m->m_pkthdr.len = m->m_len =
1239 		    (le32toh(desc->flags) >> 16) & 0xfff;
1240 
1241 #if NBPFILTER > 0
1242 		if (sc->sc_drvbpf != NULL) {
1243 			struct rt2661_rx_radiotap_header *tap = &sc->sc_rxtap;
1244 			uint32_t tsf_lo, tsf_hi;
1245 
1246 			/* get timestamp (low and high 32 bits) */
1247 			tsf_hi = RAL_READ(sc, RT2661_TXRX_CSR13);
1248 			tsf_lo = RAL_READ(sc, RT2661_TXRX_CSR12);
1249 
1250 			tap->wr_tsf =
1251 			    htole64(((uint64_t)tsf_hi << 32) | tsf_lo);
1252 			tap->wr_flags = 0;
1253 			tap->wr_rate = rt2661_rxrate(desc);
1254 			tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
1255 			tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
1256 			tap->wr_antsignal = desc->rssi;
1257 
1258 			bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m);
1259 		}
1260 #endif
1261 
1262 		wh = mtod(m, struct ieee80211_frame *);
1263 		ni = ieee80211_find_rxnode(ic,
1264 		    (struct ieee80211_frame_min *)wh);
1265 
1266 		/* send the frame to the 802.11 layer */
1267 		ieee80211_input(ic, m, ni, desc->rssi, 0);
1268 
1269 
1270 		/* give rssi to the rate adatation algorithm */
1271 		rn = (struct rt2661_node *)ni;
1272 		ieee80211_rssadapt_input(ic, ni, &rn->rssadapt,
1273 		    rt2661_get_rssi(sc, desc->rssi));
1274 
1275 		/* node is no longer needed */
1276 		ieee80211_free_node(ni);
1277 
1278 skip:		desc->flags |= htole32(RT2661_RX_BUSY);
1279 
1280 		bus_dmamap_sync(sc->sc_dmat, sc->rxq.map,
1281 		    sc->rxq.cur * RT2661_RX_DESC_SIZE, RT2661_RX_DESC_SIZE,
1282 		    BUS_DMASYNC_PREWRITE);
1283 
1284 		DPRINTFN(15, ("rx intr idx=%u\n", sc->rxq.cur));
1285 
1286 		sc->rxq.cur = (sc->rxq.cur + 1) % RT2661_RX_RING_COUNT;
1287 	}
1288 
1289 	/*
1290 	 * In HostAP mode, ieee80211_input() will enqueue packets in if_snd
1291 	 * without calling if_start().
1292 	 */
1293 	if (!IFQ_IS_EMPTY(&ifp->if_snd) && !(ifp->if_flags & IFF_OACTIVE))
1294 		rt2661_start(ifp);
1295 }
1296 
1297 /* ARGSUSED */
1298 static void
1299 rt2661_mcu_beacon_expire(struct rt2661_softc *sc)
1300 {
1301 	/* do nothing */
1302 }
1303 
1304 static void
1305 rt2661_mcu_wakeup(struct rt2661_softc *sc)
1306 {
1307 	RAL_WRITE(sc, RT2661_MAC_CSR11, 5 << 16);
1308 
1309 	RAL_WRITE(sc, RT2661_SOFT_RESET_CSR, 0x7);
1310 	RAL_WRITE(sc, RT2661_IO_CNTL_CSR, 0x18);
1311 	RAL_WRITE(sc, RT2661_PCI_USEC_CSR, 0x20);
1312 
1313 	/* send wakeup command to MCU */
1314 	rt2661_tx_cmd(sc, RT2661_MCU_CMD_WAKEUP, 0);
1315 }
1316 
1317 static void
1318 rt2661_mcu_cmd_intr(struct rt2661_softc *sc)
1319 {
1320 	RAL_READ(sc, RT2661_M2H_CMD_DONE_CSR);
1321 	RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
1322 }
1323 
1324 int
1325 rt2661_intr(void *arg)
1326 {
1327 	struct rt2661_softc *sc = arg;
1328 	struct ifnet *ifp = &sc->sc_if;
1329 	uint32_t r1, r2;
1330 
1331 	/* disable MAC and MCU interrupts */
1332 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffff7f);
1333 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
1334 
1335 	/* don't re-enable interrupts if we're shutting down */
1336 	if (!(ifp->if_flags & IFF_RUNNING))
1337 		return 0;
1338 
1339 	r1 = RAL_READ(sc, RT2661_INT_SOURCE_CSR);
1340 	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, r1);
1341 
1342 	r2 = RAL_READ(sc, RT2661_MCU_INT_SOURCE_CSR);
1343 	RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, r2);
1344 
1345 	if (r1 & RT2661_MGT_DONE)
1346 		rt2661_tx_dma_intr(sc, &sc->mgtq);
1347 
1348 	if (r1 & RT2661_RX_DONE)
1349 		rt2661_rx_intr(sc);
1350 
1351 	if (r1 & RT2661_TX0_DMA_DONE)
1352 		rt2661_tx_dma_intr(sc, &sc->txq[0]);
1353 
1354 	if (r1 & RT2661_TX1_DMA_DONE)
1355 		rt2661_tx_dma_intr(sc, &sc->txq[1]);
1356 
1357 	if (r1 & RT2661_TX2_DMA_DONE)
1358 		rt2661_tx_dma_intr(sc, &sc->txq[2]);
1359 
1360 	if (r1 & RT2661_TX3_DMA_DONE)
1361 		rt2661_tx_dma_intr(sc, &sc->txq[3]);
1362 
1363 	if (r1 & RT2661_TX_DONE)
1364 		rt2661_tx_intr(sc);
1365 
1366 	if (r2 & RT2661_MCU_CMD_DONE)
1367 		rt2661_mcu_cmd_intr(sc);
1368 
1369 	if (r2 & RT2661_MCU_BEACON_EXPIRE)
1370 		rt2661_mcu_beacon_expire(sc);
1371 
1372 	if (r2 & RT2661_MCU_WAKEUP)
1373 		rt2661_mcu_wakeup(sc);
1374 
1375 	/* re-enable MAC and MCU interrupts */
1376 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
1377 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
1378 
1379 	return 1;
1380 }
1381 
1382 /* quickly determine if a given rate is CCK or OFDM */
1383 #define RAL_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
1384 
1385 #define RAL_ACK_SIZE	14	/* 10 + 4(FCS) */
1386 #define RAL_CTS_SIZE	14	/* 10 + 4(FCS) */
1387 
1388 #define RAL_SIFS	10	/* us */
1389 
1390 /*
1391  * This function is only used by the Rx radiotap code. It returns the rate at
1392  * which a given frame was received.
1393  */
1394 #if NBPFILTER > 0
1395 static uint8_t
1396 rt2661_rxrate(struct rt2661_rx_desc *desc)
1397 {
1398 	if (le32toh(desc->flags) & RT2661_RX_OFDM) {
1399 		/* reverse function of rt2661_plcp_signal */
1400 		switch (desc->rate & 0xf) {
1401 		case 0xb:	return 12;
1402 		case 0xf:	return 18;
1403 		case 0xa:	return 24;
1404 		case 0xe:	return 36;
1405 		case 0x9:	return 48;
1406 		case 0xd:	return 72;
1407 		case 0x8:	return 96;
1408 		case 0xc:	return 108;
1409 		}
1410 	} else {
1411 		if (desc->rate == 10)
1412 			return 2;
1413 		if (desc->rate == 20)
1414 			return 4;
1415 		if (desc->rate == 55)
1416 			return 11;
1417 		if (desc->rate == 110)
1418 			return 22;
1419 	}
1420 	return 2;	/* should not get there */
1421 }
1422 #endif
1423 
1424 /*
1425  * Return the expected ack rate for a frame transmitted at rate `rate'.
1426  * XXX: this should depend on the destination node basic rate set.
1427  */
1428 static int
1429 rt2661_ack_rate(struct ieee80211com *ic, int rate)
1430 {
1431 	switch (rate) {
1432 	/* CCK rates */
1433 	case 2:
1434 		return 2;
1435 	case 4:
1436 	case 11:
1437 	case 22:
1438 		return (ic->ic_curmode == IEEE80211_MODE_11B) ? 4 : rate;
1439 
1440 	/* OFDM rates */
1441 	case 12:
1442 	case 18:
1443 		return 12;
1444 	case 24:
1445 	case 36:
1446 		return 24;
1447 	case 48:
1448 	case 72:
1449 	case 96:
1450 	case 108:
1451 		return 48;
1452 	}
1453 
1454 	/* default to 1Mbps */
1455 	return 2;
1456 }
1457 
1458 /*
1459  * Compute the duration (in us) needed to transmit `len' bytes at rate `rate'.
1460  * The function automatically determines the operating mode depending on the
1461  * given rate. `flags' indicates whether short preamble is in use or not.
1462  */
1463 static uint16_t
1464 rt2661_txtime(int len, int rate, uint32_t flags)
1465 {
1466 	uint16_t txtime;
1467 
1468 	if (RAL_RATE_IS_OFDM(rate)) {
1469 		/* IEEE Std 802.11a-1999, pp. 37 */
1470 		txtime = (8 + 4 * len + 3 + rate - 1) / rate;
1471 		txtime = 16 + 4 + 4 * txtime + 6;
1472 	} else {
1473 		/* IEEE Std 802.11b-1999, pp. 28 */
1474 		txtime = (16 * len + rate - 1) / rate;
1475 		if (rate != 2 && (flags & IEEE80211_F_SHPREAMBLE))
1476 			txtime +=  72 + 24;
1477 		else
1478 			txtime += 144 + 48;
1479 	}
1480 	return txtime;
1481 }
1482 
1483 static uint8_t
1484 rt2661_plcp_signal(int rate)
1485 {
1486 	switch (rate) {
1487 	/* CCK rates (returned values are device-dependent) */
1488 	case 2:		return 0x0;
1489 	case 4:		return 0x1;
1490 	case 11:	return 0x2;
1491 	case 22:	return 0x3;
1492 
1493 	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1494 	case 12:	return 0xb;
1495 	case 18:	return 0xf;
1496 	case 24:	return 0xa;
1497 	case 36:	return 0xe;
1498 	case 48:	return 0x9;
1499 	case 72:	return 0xd;
1500 	case 96:	return 0x8;
1501 	case 108:	return 0xc;
1502 
1503 	/* unsupported rates (should not get there) */
1504 	default:	return 0xff;
1505 	}
1506 }
1507 
1508 static void
1509 rt2661_setup_tx_desc(struct rt2661_softc *sc, struct rt2661_tx_desc *desc,
1510     uint32_t flags, uint16_t xflags, int len, int rate,
1511     const bus_dma_segment_t *segs, int nsegs, int ac)
1512 {
1513 	struct ieee80211com *ic = &sc->sc_ic;
1514 	uint16_t plcp_length;
1515 	int i, remainder;
1516 
1517 	desc->flags = htole32(flags);
1518 	desc->flags |= htole32(len << 16);
1519 	desc->flags |= htole32(RT2661_TX_BUSY | RT2661_TX_VALID);
1520 
1521 	desc->xflags = htole16(xflags);
1522 	desc->xflags |= htole16(nsegs << 13);
1523 
1524 	desc->wme = htole16(
1525 	    RT2661_QID(ac) |
1526 	    RT2661_AIFSN(2) |
1527 	    RT2661_LOGCWMIN(4) |
1528 	    RT2661_LOGCWMAX(10));
1529 
1530 	/*
1531 	 * Remember in which queue this frame was sent. This field is driver
1532 	 * private data only. It will be made available by the NIC in STA_CSR4
1533 	 * on Tx interrupts.
1534 	 */
1535 	desc->qid = ac;
1536 
1537 	/* setup PLCP fields */
1538 	desc->plcp_signal  = rt2661_plcp_signal(rate);
1539 	desc->plcp_service = 4;
1540 
1541 	len += IEEE80211_CRC_LEN;
1542 	if (RAL_RATE_IS_OFDM(rate)) {
1543 		desc->flags |= htole32(RT2661_TX_OFDM);
1544 
1545 		plcp_length = len & 0xfff;
1546 		desc->plcp_length_hi = plcp_length >> 6;
1547 		desc->plcp_length_lo = plcp_length & 0x3f;
1548 	} else {
1549 		plcp_length = (16 * len + rate - 1) / rate;
1550 		if (rate == 22) {
1551 			remainder = (16 * len) % 22;
1552 			if (remainder != 0 && remainder < 7)
1553 				desc->plcp_service |= RT2661_PLCP_LENGEXT;
1554 		}
1555 		desc->plcp_length_hi = plcp_length >> 8;
1556 		desc->plcp_length_lo = plcp_length & 0xff;
1557 
1558 		if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1559 			desc->plcp_signal |= 0x08;
1560 	}
1561 
1562 	/* RT2x61 supports scatter with up to 5 segments */
1563 	for (i = 0; i < nsegs; i++) {
1564 		desc->addr[i] = htole32(segs[i].ds_addr);
1565 		desc->len [i] = htole16(segs[i].ds_len);
1566 	}
1567 }
1568 
1569 static int
1570 rt2661_tx_mgt(struct rt2661_softc *sc, struct mbuf *m0,
1571     struct ieee80211_node *ni)
1572 {
1573 	struct ieee80211com *ic = &sc->sc_ic;
1574 	struct rt2661_tx_desc *desc;
1575 	struct rt2661_tx_data *data;
1576 	struct ieee80211_frame *wh;
1577 	struct ieee80211_key *k;
1578 	uint16_t dur;
1579 	uint32_t flags = 0;
1580 	int rate, error;
1581 
1582 	desc = &sc->mgtq.desc[sc->mgtq.cur];
1583 	data = &sc->mgtq.data[sc->mgtq.cur];
1584 
1585 	/* send mgt frames at the lowest available rate */
1586 	rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1587 
1588 	wh = mtod(m0, struct ieee80211_frame *);
1589 
1590 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1591 		k = ieee80211_crypto_encap(ic, ni, m0);
1592 		if (k == NULL) {
1593 			m_freem(m0);
1594 			return ENOBUFS;
1595 		}
1596 	}
1597 
1598 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1599 	    BUS_DMA_NOWAIT);
1600 	if (error != 0) {
1601 		printf("%s: could not map mbuf (error %d)\n",
1602 		    sc->sc_dev.dv_xname, error);
1603 		m_freem(m0);
1604 		return error;
1605 	}
1606 
1607 #if NBPFILTER > 0
1608 	if (sc->sc_drvbpf != NULL) {
1609 		struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1610 
1611 		tap->wt_flags = 0;
1612 		tap->wt_rate = rate;
1613 		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1614 		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1615 
1616 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
1617 	}
1618 #endif
1619 
1620 	data->m = m0;
1621 	data->ni = ni;
1622 
1623 	wh = mtod(m0, struct ieee80211_frame *);
1624 
1625 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1626 		flags |= RT2661_TX_NEED_ACK;
1627 
1628 		dur = rt2661_txtime(RAL_ACK_SIZE, rate, ic->ic_flags) +
1629 		    RAL_SIFS;
1630 		*(uint16_t *)wh->i_dur = htole16(dur);
1631 
1632 		/* tell hardware to add timestamp in probe responses */
1633 		if ((wh->i_fc[0] &
1634 		    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1635 		    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1636 			flags |= RT2661_TX_TIMESTAMP;
1637 	}
1638 
1639 	rt2661_setup_tx_desc(sc, desc, flags, 0 /* XXX HWSEQ */,
1640 	    m0->m_pkthdr.len, rate, data->map->dm_segs, data->map->dm_nsegs,
1641 	    RT2661_QID_MGT);
1642 
1643 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
1644 	    BUS_DMASYNC_PREWRITE);
1645 	bus_dmamap_sync(sc->sc_dmat, sc->mgtq.map,
1646 	    sc->mgtq.cur * RT2661_TX_DESC_SIZE, RT2661_TX_DESC_SIZE,
1647 	    BUS_DMASYNC_PREWRITE);
1648 
1649 	DPRINTFN(10, ("sending mgt frame len=%u idx=%u rate=%u\n",
1650 	    m0->m_pkthdr.len, sc->mgtq.cur, rate));
1651 
1652 	/* kick mgt */
1653 	sc->mgtq.queued++;
1654 	sc->mgtq.cur = (sc->mgtq.cur + 1) % RT2661_MGT_RING_COUNT;
1655 	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, RT2661_KICK_MGT);
1656 
1657 	return 0;
1658 }
1659 
1660 /*
1661  * Build a RTS control frame.
1662  */
1663 static struct mbuf *
1664 rt2661_get_rts(struct rt2661_softc *sc, struct ieee80211_frame *wh,
1665     uint16_t dur)
1666 {
1667 	struct ieee80211_frame_rts *rts;
1668 	struct mbuf *m;
1669 
1670 	MGETHDR(m, M_DONTWAIT, MT_DATA);
1671 	if (m == NULL) {
1672 		sc->sc_ic.ic_stats.is_tx_nobuf++;
1673 		printf("%s: could not allocate RTS frame\n",
1674 		    sc->sc_dev.dv_xname);
1675 		return NULL;
1676 	}
1677 
1678 	rts = mtod(m, struct ieee80211_frame_rts *);
1679 
1680 	rts->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_CTL |
1681 	    IEEE80211_FC0_SUBTYPE_RTS;
1682 	rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1683 	*(uint16_t *)rts->i_dur = htole16(dur);
1684 	IEEE80211_ADDR_COPY(rts->i_ra, wh->i_addr1);
1685 	IEEE80211_ADDR_COPY(rts->i_ta, wh->i_addr2);
1686 
1687 	m->m_pkthdr.len = m->m_len = sizeof (struct ieee80211_frame_rts);
1688 
1689 	return m;
1690 }
1691 
1692 static int
1693 rt2661_tx_data(struct rt2661_softc *sc, struct mbuf *m0,
1694     struct ieee80211_node *ni, int ac)
1695 {
1696 	struct ieee80211com *ic = &sc->sc_ic;
1697 	struct rt2661_tx_ring *txq = &sc->txq[ac];
1698 	struct rt2661_tx_desc *desc;
1699 	struct rt2661_tx_data *data;
1700 	struct rt2661_node *rn;
1701 	struct ieee80211_rateset *rs;
1702 	struct ieee80211_frame *wh;
1703 	struct ieee80211_key *k;
1704 	struct mbuf *mnew;
1705 	uint16_t dur;
1706 	uint32_t flags = 0;
1707 	int rate, error;
1708 
1709 	wh = mtod(m0, struct ieee80211_frame *);
1710 
1711 	if (ic->ic_fixed_rate != IEEE80211_FIXED_RATE_NONE) {
1712 		rs = &ic->ic_sup_rates[ic->ic_curmode];
1713 		rate = rs->rs_rates[ic->ic_fixed_rate];
1714 	} else {
1715 		rs = &ni->ni_rates;
1716 		rn = (struct rt2661_node *)ni;
1717 		ni->ni_txrate = ieee80211_rssadapt_choose(&rn->rssadapt, rs,
1718 		    wh, m0->m_pkthdr.len, -1, NULL, 0);
1719 		rate = rs->rs_rates[ni->ni_txrate];
1720 	}
1721 	rate &= IEEE80211_RATE_VAL;
1722 
1723 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1724 		k = ieee80211_crypto_encap(ic, ni, m0);
1725 		if (k == NULL) {
1726 			m_freem(m0);
1727 			return ENOBUFS;
1728 		}
1729 
1730 		/* packet header may have moved, reset our local pointer */
1731 		wh = mtod(m0, struct ieee80211_frame *);
1732 	}
1733 
1734 	/*
1735 	 * IEEE Std 802.11-1999, pp 82: "A STA shall use an RTS/CTS exchange
1736 	 * for directed frames only when the length of the MPDU is greater
1737 	 * than the length threshold indicated by [...]" ic_rtsthreshold.
1738 	 */
1739 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1740 	    m0->m_pkthdr.len > ic->ic_rtsthreshold) {
1741 		struct mbuf *m;
1742 		int rtsrate, ackrate;
1743 
1744 		rtsrate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1745 		ackrate = rt2661_ack_rate(ic, rate);
1746 
1747 		dur = rt2661_txtime(m0->m_pkthdr.len + 4, rate, ic->ic_flags) +
1748 		      rt2661_txtime(RAL_CTS_SIZE, rtsrate, ic->ic_flags) +
1749 		      rt2661_txtime(RAL_ACK_SIZE, ackrate, ic->ic_flags) +
1750 		      3 * RAL_SIFS;
1751 
1752 		m = rt2661_get_rts(sc, wh, dur);
1753 
1754 		desc = &txq->desc[txq->cur];
1755 		data = &txq->data[txq->cur];
1756 
1757 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m,
1758 		    BUS_DMA_NOWAIT);
1759 		if (error != 0) {
1760 			printf("%s: could not map mbuf (error %d)\n",
1761 			    sc->sc_dev.dv_xname, error);
1762 			m_freem(m);
1763 			m_freem(m0);
1764 			return error;
1765 		}
1766 
1767 		/* avoid multiple free() of the same node for each fragment */
1768 		ieee80211_ref_node(ni);
1769 
1770 		data->m = m;
1771 		data->ni = ni;
1772 
1773 		/* RTS frames are not taken into account for rssadapt */
1774 		data->id.id_node = NULL;
1775 
1776 		rt2661_setup_tx_desc(sc, desc, RT2661_TX_NEED_ACK |
1777 		    RT2661_TX_MORE_FRAG, 0, m->m_pkthdr.len, rtsrate,
1778 		    data->map->dm_segs, data->map->dm_nsegs, ac);
1779 
1780 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1781 		    data->map->dm_mapsize, BUS_DMASYNC_PREWRITE);
1782 		bus_dmamap_sync(sc->sc_dmat, txq->map,
1783 		    txq->cur * RT2661_TX_DESC_SIZE, RT2661_TX_DESC_SIZE,
1784 		    BUS_DMASYNC_PREWRITE);
1785 
1786 		txq->queued++;
1787 		txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1788 
1789 		/*
1790 		 * IEEE Std 802.11-1999: when an RTS/CTS exchange is used, the
1791 		 * asynchronous data frame shall be transmitted after the CTS
1792 		 * frame and a SIFS period.
1793 		 */
1794 		flags |= RT2661_TX_LONG_RETRY | RT2661_TX_IFS;
1795 	}
1796 
1797 	data = &txq->data[txq->cur];
1798 	desc = &txq->desc[txq->cur];
1799 
1800 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1801 	    BUS_DMA_NOWAIT);
1802 	if (error != 0 && error != EFBIG) {
1803 		printf("%s: could not map mbuf (error %d)\n",
1804 		    sc->sc_dev.dv_xname, error);
1805 		m_freem(m0);
1806 		return error;
1807 	}
1808 	if (error != 0) {
1809 		/* too many fragments, linearize */
1810 
1811 		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
1812 		if (mnew == NULL) {
1813 			m_freem(m0);
1814 			return ENOMEM;
1815 		}
1816 
1817 		M_COPY_PKTHDR(mnew, m0);
1818 		if (m0->m_pkthdr.len > MHLEN) {
1819 			MCLGET(mnew, M_DONTWAIT);
1820 			if (!(mnew->m_flags & M_EXT)) {
1821 				m_freem(m0);
1822 				m_freem(mnew);
1823 				return ENOMEM;
1824 			}
1825 		}
1826 
1827 		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(mnew, void *));
1828 		m_freem(m0);
1829 		mnew->m_len = mnew->m_pkthdr.len;
1830 		m0 = mnew;
1831 
1832 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1833 		    BUS_DMA_NOWAIT);
1834 		if (error != 0) {
1835 			printf("%s: could not map mbuf (error %d)\n",
1836 			    sc->sc_dev.dv_xname, error);
1837 			m_freem(m0);
1838 			return error;
1839 		}
1840 
1841 		/* packet header have moved, reset our local pointer */
1842 		wh = mtod(m0, struct ieee80211_frame *);
1843 	}
1844 
1845 #if NBPFILTER > 0
1846 	if (sc->sc_drvbpf != NULL) {
1847 		struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1848 
1849 		tap->wt_flags = 0;
1850 		tap->wt_rate = rate;
1851 		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1852 		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1853 
1854 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
1855 	}
1856 #endif
1857 
1858 	data->m = m0;
1859 	data->ni = ni;
1860 
1861 	/* remember link conditions for rate adaptation algorithm */
1862 	if (ic->ic_fixed_rate == IEEE80211_FIXED_RATE_NONE) {
1863 		data->id.id_len = m0->m_pkthdr.len;
1864 		data->id.id_rateidx = ni->ni_txrate;
1865 		data->id.id_node = ni;
1866 		data->id.id_rssi = ni->ni_rssi;
1867 	} else
1868 		data->id.id_node = NULL;
1869 
1870 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1871 		flags |= RT2661_TX_NEED_ACK;
1872 
1873 		dur = rt2661_txtime(RAL_ACK_SIZE, rt2661_ack_rate(ic, rate),
1874 		    ic->ic_flags) + RAL_SIFS;
1875 		*(uint16_t *)wh->i_dur = htole16(dur);
1876 	}
1877 
1878 	rt2661_setup_tx_desc(sc, desc, flags, 0, m0->m_pkthdr.len, rate,
1879 	    data->map->dm_segs, data->map->dm_nsegs, ac);
1880 
1881 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
1882 	    BUS_DMASYNC_PREWRITE);
1883 	bus_dmamap_sync(sc->sc_dmat, txq->map, txq->cur * RT2661_TX_DESC_SIZE,
1884 	    RT2661_TX_DESC_SIZE, BUS_DMASYNC_PREWRITE);
1885 
1886 	DPRINTFN(10, ("sending data frame len=%u idx=%u rate=%u\n",
1887 	    m0->m_pkthdr.len, txq->cur, rate));
1888 
1889 	/* kick Tx */
1890 	txq->queued++;
1891 	txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1892 	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 1);
1893 
1894 	return 0;
1895 }
1896 
1897 static void
1898 rt2661_start(struct ifnet *ifp)
1899 {
1900 	struct rt2661_softc *sc = ifp->if_softc;
1901 	struct ieee80211com *ic = &sc->sc_ic;
1902 	struct mbuf *m0;
1903 	struct ether_header *eh;
1904 	struct ieee80211_node *ni = NULL;
1905 	int ac;
1906 
1907 	/*
1908 	 * net80211 may still try to send management frames even if the
1909 	 * IFF_RUNNING flag is not set...
1910 	 */
1911 	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
1912 		return;
1913 
1914 	for (;;) {
1915 		IF_POLL(&ic->ic_mgtq, m0);
1916 		if (m0 != NULL) {
1917 			if (sc->mgtq.queued >= RT2661_MGT_RING_COUNT) {
1918 				ifp->if_flags |= IFF_OACTIVE;
1919 				break;
1920 			}
1921 			IF_DEQUEUE(&ic->ic_mgtq, m0);
1922 			if (m0 == NULL)
1923 				break;
1924 
1925 			ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
1926 			m0->m_pkthdr.rcvif = NULL;
1927 #if NBPFILTER > 0
1928 			if (ic->ic_rawbpf != NULL)
1929 				bpf_mtap(ic->ic_rawbpf, m0);
1930 #endif
1931 			if (rt2661_tx_mgt(sc, m0, ni) != 0)
1932 				break;
1933 
1934 		} else {
1935 			if (ic->ic_state != IEEE80211_S_RUN)
1936 				break;
1937 			IFQ_DEQUEUE(&ifp->if_snd, m0);
1938 			if (m0 == NULL)
1939 				break;
1940 
1941 			if (m0->m_len < sizeof (struct ether_header) &&
1942 			    !(m0 = m_pullup(m0, sizeof (struct ether_header))))
1943 				continue;
1944 
1945 			eh = mtod(m0, struct ether_header *);
1946 			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1947 			if (ni == NULL) {
1948 				m_freem(m0);
1949 				ifp->if_oerrors++;
1950 				continue;
1951 			}
1952 
1953 
1954 			/* classify mbuf so we can find which tx ring to use */
1955 			if (ieee80211_classify(ic, m0, ni) != 0) {
1956 				m_freem(m0);
1957 				ieee80211_free_node(ni);
1958 				ifp->if_oerrors++;
1959 				continue;
1960 			}
1961 
1962 			/* no QoS encapsulation for EAPOL frames */
1963 			ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
1964 			    M_WME_GETAC(m0) : WME_AC_BE;
1965 
1966 			if (sc->txq[0].queued >= RT2661_TX_RING_COUNT - 1) {
1967 				/* there is no place left in this ring */
1968 				ifp->if_flags |= IFF_OACTIVE;
1969 				break;
1970 			}
1971 #if NBPFILTER > 0
1972 			if (ifp->if_bpf != NULL)
1973 				bpf_mtap(ifp->if_bpf, m0);
1974 #endif
1975 			m0 = ieee80211_encap(ic, m0, ni);
1976 			if (m0 == NULL) {
1977 				ieee80211_free_node(ni);
1978 				ifp->if_oerrors++;
1979 				continue;
1980 			}
1981 #if NBPFILTER > 0
1982 			if (ic->ic_rawbpf != NULL)
1983 				bpf_mtap(ic->ic_rawbpf, m0);
1984 #endif
1985 			if (rt2661_tx_data(sc, m0, ni, 0) != 0) {
1986 				if (ni != NULL)
1987 					ieee80211_free_node(ni);
1988 				ifp->if_oerrors++;
1989 				break;
1990 			}
1991 		}
1992 
1993 		sc->sc_tx_timer = 5;
1994 		ifp->if_timer = 1;
1995 	}
1996 }
1997 
1998 static void
1999 rt2661_watchdog(struct ifnet *ifp)
2000 {
2001 	struct rt2661_softc *sc = ifp->if_softc;
2002 
2003 	ifp->if_timer = 0;
2004 
2005 	if (sc->sc_tx_timer > 0) {
2006 		if (--sc->sc_tx_timer == 0) {
2007 			printf("%s: device timeout\n", sc->sc_dev.dv_xname);
2008 			rt2661_init(ifp);
2009 			ifp->if_oerrors++;
2010 			return;
2011 		}
2012 		ifp->if_timer = 1;
2013 	}
2014 
2015 	ieee80211_watchdog(&sc->sc_ic);
2016 }
2017 
2018 /*
2019  * This function allows for fast channel switching in monitor mode (used by
2020  * kismet). In IBSS mode, we must explicitly reset the interface to
2021  * generate a new beacon frame.
2022  */
2023 static int
2024 rt2661_reset(struct ifnet *ifp)
2025 {
2026 	struct rt2661_softc *sc = ifp->if_softc;
2027 	struct ieee80211com *ic = &sc->sc_ic;
2028 
2029 	if (ic->ic_opmode != IEEE80211_M_MONITOR)
2030 		return ENETRESET;
2031 
2032 	rt2661_set_chan(sc, ic->ic_curchan);
2033 
2034 	return 0;
2035 }
2036 
2037 static int
2038 rt2661_ioctl(struct ifnet *ifp, u_long cmd, void *data)
2039 {
2040 	struct rt2661_softc *sc = ifp->if_softc;
2041 	struct ieee80211com *ic = &sc->sc_ic;
2042 	int s, error = 0;
2043 
2044 	s = splnet();
2045 
2046 	switch (cmd) {
2047 	case SIOCSIFFLAGS:
2048 		if (ifp->if_flags & IFF_UP) {
2049 			if (ifp->if_flags & IFF_RUNNING)
2050 				rt2661_update_promisc(sc);
2051 			else
2052 				rt2661_init(ifp);
2053 		} else {
2054 			if (ifp->if_flags & IFF_RUNNING)
2055 				rt2661_stop(ifp, 1);
2056 		}
2057 		break;
2058 
2059 	case SIOCADDMULTI:
2060 	case SIOCDELMULTI:
2061 		/* XXX no h/w multicast filter? --dyoung */
2062 		if ((error = ether_ioctl(ifp, cmd, data)) == ENETRESET)
2063 			error = 0;
2064 		break;
2065 
2066 	case SIOCS80211CHANNEL:
2067 		/*
2068 		 * This allows for fast channel switching in monitor mode
2069 		 * (used by kismet). In IBSS mode, we must explicitly reset
2070 		 * the interface to generate a new beacon frame.
2071 		 */
2072 		error = ieee80211_ioctl(ic, cmd, data);
2073 		if (error == ENETRESET &&
2074 		    ic->ic_opmode == IEEE80211_M_MONITOR) {
2075 			rt2661_set_chan(sc, ic->ic_ibss_chan);
2076 			error = 0;
2077 		}
2078 		break;
2079 
2080 	default:
2081 		error = ieee80211_ioctl(ic, cmd, data);
2082 
2083 	}
2084 
2085 	if (error == ENETRESET) {
2086 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
2087 		    (IFF_UP | IFF_RUNNING))
2088 			rt2661_init(ifp);
2089 		error = 0;
2090 	}
2091 
2092 	splx(s);
2093 
2094 	return error;
2095 }
2096 
2097 static void
2098 rt2661_bbp_write(struct rt2661_softc *sc, uint8_t reg, uint8_t val)
2099 {
2100 	uint32_t tmp;
2101 	int ntries;
2102 
2103 	for (ntries = 0; ntries < 100; ntries++) {
2104 		if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
2105 			break;
2106 		DELAY(1);
2107 	}
2108 	if (ntries == 100) {
2109 		printf("%s: could not write to BBP\n", sc->sc_dev.dv_xname);
2110 		return;
2111 	}
2112 
2113 	tmp = RT2661_BBP_BUSY | (reg & 0x7f) << 8 | val;
2114 	RAL_WRITE(sc, RT2661_PHY_CSR3, tmp);
2115 
2116 	DPRINTFN(15, ("BBP R%u <- 0x%02x\n", reg, val));
2117 }
2118 
2119 static uint8_t
2120 rt2661_bbp_read(struct rt2661_softc *sc, uint8_t reg)
2121 {
2122 	uint32_t val;
2123 	int ntries;
2124 
2125 	for (ntries = 0; ntries < 100; ntries++) {
2126 		if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
2127 			break;
2128 		DELAY(1);
2129 	}
2130 	if (ntries == 100) {
2131 		printf("%s: could not read from BBP\n", sc->sc_dev.dv_xname);
2132 		return 0;
2133 	}
2134 
2135 	val = RT2661_BBP_BUSY | RT2661_BBP_READ | reg << 8;
2136 	RAL_WRITE(sc, RT2661_PHY_CSR3, val);
2137 
2138 	for (ntries = 0; ntries < 100; ntries++) {
2139 		val = RAL_READ(sc, RT2661_PHY_CSR3);
2140 		if (!(val & RT2661_BBP_BUSY))
2141 			return val & 0xff;
2142 		DELAY(1);
2143 	}
2144 
2145 	printf("%s: could not read from BBP\n", sc->sc_dev.dv_xname);
2146 	return 0;
2147 }
2148 
2149 static void
2150 rt2661_rf_write(struct rt2661_softc *sc, uint8_t reg, uint32_t val)
2151 {
2152 	uint32_t tmp;
2153 	int ntries;
2154 
2155 	for (ntries = 0; ntries < 100; ntries++) {
2156 		if (!(RAL_READ(sc, RT2661_PHY_CSR4) & RT2661_RF_BUSY))
2157 			break;
2158 		DELAY(1);
2159 	}
2160 	if (ntries == 100) {
2161 		printf("%s: could not write to RF\n", sc->sc_dev.dv_xname);
2162 		return;
2163 	}
2164 
2165 	tmp = RT2661_RF_BUSY | RT2661_RF_21BIT | (val & 0x1fffff) << 2 |
2166 	    (reg & 3);
2167 	RAL_WRITE(sc, RT2661_PHY_CSR4, tmp);
2168 
2169 	/* remember last written value in sc */
2170 	sc->rf_regs[reg] = val;
2171 
2172 	DPRINTFN(15, ("RF R[%u] <- 0x%05x\n", reg & 3, val & 0x1fffff));
2173 }
2174 
2175 static int
2176 rt2661_tx_cmd(struct rt2661_softc *sc, uint8_t cmd, uint16_t arg)
2177 {
2178 	if (RAL_READ(sc, RT2661_H2M_MAILBOX_CSR) & RT2661_H2M_BUSY)
2179 		return EIO;	/* there is already a command pending */
2180 
2181 	RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR,
2182 	    RT2661_H2M_BUSY | RT2661_TOKEN_NO_INTR << 16 | arg);
2183 
2184 	RAL_WRITE(sc, RT2661_HOST_CMD_CSR, RT2661_KICK_CMD | cmd);
2185 
2186 	return 0;
2187 }
2188 
2189 static void
2190 rt2661_select_antenna(struct rt2661_softc *sc)
2191 {
2192 	uint8_t bbp4, bbp77;
2193 	uint32_t tmp;
2194 
2195 	bbp4  = rt2661_bbp_read(sc,  4);
2196 	bbp77 = rt2661_bbp_read(sc, 77);
2197 
2198 	/* TBD */
2199 
2200 	/* make sure Rx is disabled before switching antenna */
2201 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2202 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2203 
2204 	rt2661_bbp_write(sc,  4, bbp4);
2205 	rt2661_bbp_write(sc, 77, bbp77);
2206 
2207 	/* restore Rx filter */
2208 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2209 }
2210 
2211 /*
2212  * Enable multi-rate retries for frames sent at OFDM rates.
2213  * In 802.11b/g mode, allow fallback to CCK rates.
2214  */
2215 static void
2216 rt2661_enable_mrr(struct rt2661_softc *sc)
2217 {
2218 	struct ieee80211com *ic = &sc->sc_ic;
2219 	uint32_t tmp;
2220 
2221 	tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
2222 
2223 	tmp &= ~RT2661_MRR_CCK_FALLBACK;
2224 	if (!IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan))
2225 		tmp |= RT2661_MRR_CCK_FALLBACK;
2226 	tmp |= RT2661_MRR_ENABLED;
2227 
2228 	RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
2229 }
2230 
2231 static void
2232 rt2661_set_txpreamble(struct rt2661_softc *sc)
2233 {
2234 	uint32_t tmp;
2235 
2236 	tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
2237 
2238 	tmp &= ~RT2661_SHORT_PREAMBLE;
2239 	if (sc->sc_ic.ic_flags & IEEE80211_F_SHPREAMBLE)
2240 		tmp |= RT2661_SHORT_PREAMBLE;
2241 
2242 	RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
2243 }
2244 
2245 static void
2246 rt2661_set_basicrates(struct rt2661_softc *sc,
2247     const struct ieee80211_rateset *rs)
2248 {
2249 #define RV(r)	((r) & IEEE80211_RATE_VAL)
2250 	uint32_t mask = 0;
2251 	uint8_t rate;
2252 	int i, j;
2253 
2254 	for (i = 0; i < rs->rs_nrates; i++) {
2255 		rate = rs->rs_rates[i];
2256 
2257 		if (!(rate & IEEE80211_RATE_BASIC))
2258 			continue;
2259 
2260 		/*
2261 		 * Find h/w rate index.  We know it exists because the rate
2262 		 * set has already been negotiated.
2263 		 */
2264 		for (j = 0; rt2661_rateset_11g.rs_rates[j] != RV(rate); j++);
2265 
2266 		mask |= 1 << j;
2267 	}
2268 
2269 	RAL_WRITE(sc, RT2661_TXRX_CSR5, mask);
2270 
2271 	DPRINTF(("Setting basic rate mask to 0x%x\n", mask));
2272 #undef RV
2273 }
2274 
2275 /*
2276  * Reprogram MAC/BBP to switch to a new band.  Values taken from the reference
2277  * driver.
2278  */
2279 static void
2280 rt2661_select_band(struct rt2661_softc *sc, struct ieee80211_channel *c)
2281 {
2282 	uint8_t bbp17, bbp35, bbp96, bbp97, bbp98, bbp104;
2283 	uint32_t tmp;
2284 
2285 	/* update all BBP registers that depend on the band */
2286 	bbp17 = 0x20; bbp96 = 0x48; bbp104 = 0x2c;
2287 	bbp35 = 0x50; bbp97 = 0x48; bbp98  = 0x48;
2288 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
2289 		bbp17 += 0x08; bbp96 += 0x10; bbp104 += 0x0c;
2290 		bbp35 += 0x10; bbp97 += 0x10; bbp98  += 0x10;
2291 	}
2292 	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2293 	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2294 		bbp17 += 0x10; bbp96 += 0x10; bbp104 += 0x10;
2295 	}
2296 
2297 	rt2661_bbp_write(sc,  17, bbp17);
2298 	rt2661_bbp_write(sc,  96, bbp96);
2299 	rt2661_bbp_write(sc, 104, bbp104);
2300 
2301 	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2302 	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2303 		rt2661_bbp_write(sc, 75, 0x80);
2304 		rt2661_bbp_write(sc, 86, 0x80);
2305 		rt2661_bbp_write(sc, 88, 0x80);
2306 	}
2307 
2308 	rt2661_bbp_write(sc, 35, bbp35);
2309 	rt2661_bbp_write(sc, 97, bbp97);
2310 	rt2661_bbp_write(sc, 98, bbp98);
2311 
2312 	tmp = RAL_READ(sc, RT2661_PHY_CSR0);
2313 	tmp &= ~(RT2661_PA_PE_2GHZ | RT2661_PA_PE_5GHZ);
2314 	if (IEEE80211_IS_CHAN_2GHZ(c))
2315 		tmp |= RT2661_PA_PE_2GHZ;
2316 	else
2317 		tmp |= RT2661_PA_PE_5GHZ;
2318 	RAL_WRITE(sc, RT2661_PHY_CSR0, tmp);
2319 }
2320 
2321 static void
2322 rt2661_set_chan(struct rt2661_softc *sc, struct ieee80211_channel *c)
2323 {
2324 	struct ieee80211com *ic = &sc->sc_ic;
2325 	const struct rfprog *rfprog;
2326 	uint8_t bbp3, bbp94 = RT2661_BBPR94_DEFAULT;
2327 	int8_t power;
2328 	u_int i, chan;
2329 
2330 	chan = ieee80211_chan2ieee(ic, c);
2331 	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
2332 		return;
2333 
2334 	/* select the appropriate RF settings based on what EEPROM says */
2335 	rfprog = (sc->rfprog == 0) ? rt2661_rf5225_1 : rt2661_rf5225_2;
2336 
2337 	/* find the settings for this channel (we know it exists) */
2338 	for (i = 0; rfprog[i].chan != chan; i++);
2339 
2340 	power = sc->txpow[i];
2341 	if (power < 0) {
2342 		bbp94 += power;
2343 		power = 0;
2344 	} else if (power > 31) {
2345 		bbp94 += power - 31;
2346 		power = 31;
2347 	}
2348 
2349 	/*
2350 	 * If we've yet to select a channel, or we are switching from the
2351 	 * 2GHz band to the 5GHz band or vice-versa, BBP registers need to
2352 	 * be reprogrammed.
2353 	 */
2354 	if (sc->sc_curchan == NULL || c->ic_flags != sc->sc_curchan->ic_flags) {
2355 		rt2661_select_band(sc, c);
2356 		rt2661_select_antenna(sc);
2357 	}
2358 	sc->sc_curchan = c;
2359 
2360 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2361 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2362 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2363 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2364 
2365 	DELAY(200);
2366 
2367 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2368 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2369 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7 | 1);
2370 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2371 
2372 	DELAY(200);
2373 
2374 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2375 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2376 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2377 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2378 
2379 	/* enable smart mode for MIMO-capable RFs */
2380 	bbp3 = rt2661_bbp_read(sc, 3);
2381 
2382 	bbp3 &= ~RT2661_SMART_MODE;
2383 	if (sc->rf_rev == RT2661_RF_5325 || sc->rf_rev == RT2661_RF_2529)
2384 		bbp3 |= RT2661_SMART_MODE;
2385 
2386 	rt2661_bbp_write(sc, 3, bbp3);
2387 
2388 	if (bbp94 != RT2661_BBPR94_DEFAULT)
2389 		rt2661_bbp_write(sc, 94, bbp94);
2390 
2391 	/* 5GHz radio needs a 1ms delay here */
2392 	if (IEEE80211_IS_CHAN_5GHZ(c))
2393 		DELAY(1000);
2394 }
2395 
2396 static void
2397 rt2661_set_bssid(struct rt2661_softc *sc, const uint8_t *bssid)
2398 {
2399 	uint32_t tmp;
2400 
2401 	tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24;
2402 	RAL_WRITE(sc, RT2661_MAC_CSR4, tmp);
2403 
2404 	tmp = bssid[4] | bssid[5] << 8 | RT2661_ONE_BSSID << 16;
2405 	RAL_WRITE(sc, RT2661_MAC_CSR5, tmp);
2406 }
2407 
2408 static void
2409 rt2661_set_macaddr(struct rt2661_softc *sc, const uint8_t *addr)
2410 {
2411 	uint32_t tmp;
2412 
2413 	tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24;
2414 	RAL_WRITE(sc, RT2661_MAC_CSR2, tmp);
2415 
2416 	tmp = addr[4] | addr[5] << 8;
2417 	RAL_WRITE(sc, RT2661_MAC_CSR3, tmp);
2418 }
2419 
2420 static void
2421 rt2661_update_promisc(struct rt2661_softc *sc)
2422 {
2423 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
2424 	uint32_t tmp;
2425 
2426 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2427 
2428 	tmp &= ~RT2661_DROP_NOT_TO_ME;
2429 	if (!(ifp->if_flags & IFF_PROMISC))
2430 		tmp |= RT2661_DROP_NOT_TO_ME;
2431 
2432 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2433 
2434 	DPRINTF(("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
2435 	    "entering" : "leaving"));
2436 }
2437 
2438 #if 0
2439 /*
2440  * Update QoS (802.11e) settings for each h/w Tx ring.
2441  */
2442 static int
2443 rt2661_wme_update(struct ieee80211com *ic)
2444 {
2445 	struct rt2661_softc *sc = ic->ic_ifp->if_softc;
2446 	const struct wmeParams *wmep;
2447 
2448 	wmep = ic->ic_wme.wme_chanParams.cap_wmeParams;
2449 
2450 	/* XXX: not sure about shifts. */
2451 	/* XXX: the reference driver plays with AC_VI settings too. */
2452 
2453 	/* update TxOp */
2454 	RAL_WRITE(sc, RT2661_AC_TXOP_CSR0,
2455 	    wmep[WME_AC_BE].wmep_txopLimit << 16 |
2456 	    wmep[WME_AC_BK].wmep_txopLimit);
2457 	RAL_WRITE(sc, RT2661_AC_TXOP_CSR1,
2458 	    wmep[WME_AC_VI].wmep_txopLimit << 16 |
2459 	    wmep[WME_AC_VO].wmep_txopLimit);
2460 
2461 	/* update CWmin */
2462 	RAL_WRITE(sc, RT2661_CWMIN_CSR,
2463 	    wmep[WME_AC_BE].wmep_logcwmin << 12 |
2464 	    wmep[WME_AC_BK].wmep_logcwmin <<  8 |
2465 	    wmep[WME_AC_VI].wmep_logcwmin <<  4 |
2466 	    wmep[WME_AC_VO].wmep_logcwmin);
2467 
2468 	/* update CWmax */
2469 	RAL_WRITE(sc, RT2661_CWMAX_CSR,
2470 	    wmep[WME_AC_BE].wmep_logcwmax << 12 |
2471 	    wmep[WME_AC_BK].wmep_logcwmax <<  8 |
2472 	    wmep[WME_AC_VI].wmep_logcwmax <<  4 |
2473 	    wmep[WME_AC_VO].wmep_logcwmax);
2474 
2475 	/* update Aifsn */
2476 	RAL_WRITE(sc, RT2661_AIFSN_CSR,
2477 	    wmep[WME_AC_BE].wmep_aifsn << 12 |
2478 	    wmep[WME_AC_BK].wmep_aifsn <<  8 |
2479 	    wmep[WME_AC_VI].wmep_aifsn <<  4 |
2480 	    wmep[WME_AC_VO].wmep_aifsn);
2481 
2482 	return 0;
2483 }
2484 #endif
2485 
2486 static void
2487 rt2661_update_slot(struct ifnet *ifp)
2488 {
2489 	struct rt2661_softc *sc = ifp->if_softc;
2490 	struct ieee80211com *ic = &sc->sc_ic;
2491 	uint8_t slottime;
2492 	uint32_t tmp;
2493 
2494 	slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
2495 
2496 	tmp = RAL_READ(sc, RT2661_MAC_CSR9);
2497 	tmp = (tmp & ~0xff) | slottime;
2498 	RAL_WRITE(sc, RT2661_MAC_CSR9, tmp);
2499 }
2500 
2501 static const char *
2502 rt2661_get_rf(int rev)
2503 {
2504 	switch (rev) {
2505 	case RT2661_RF_5225:	return "RT5225";
2506 	case RT2661_RF_5325:	return "RT5325 (MIMO XR)";
2507 	case RT2661_RF_2527:	return "RT2527";
2508 	case RT2661_RF_2529:	return "RT2529 (MIMO XR)";
2509 	default:		return "unknown";
2510 	}
2511 }
2512 
2513 static void
2514 rt2661_read_eeprom(struct rt2661_softc *sc)
2515 {
2516 	struct ieee80211com *ic = &sc->sc_ic;
2517 	uint16_t val;
2518 	int i;
2519 
2520 	/* read MAC address */
2521 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC01);
2522 	ic->ic_myaddr[0] = val & 0xff;
2523 	ic->ic_myaddr[1] = val >> 8;
2524 
2525 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC23);
2526 	ic->ic_myaddr[2] = val & 0xff;
2527 	ic->ic_myaddr[3] = val >> 8;
2528 
2529 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC45);
2530 	ic->ic_myaddr[4] = val & 0xff;
2531 	ic->ic_myaddr[5] = val >> 8;
2532 
2533 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_ANTENNA);
2534 	/* XXX: test if different from 0xffff? */
2535 	sc->rf_rev   = (val >> 11) & 0x1f;
2536 	sc->hw_radio = (val >> 10) & 0x1;
2537 	sc->rx_ant   = (val >> 4)  & 0x3;
2538 	sc->tx_ant   = (val >> 2)  & 0x3;
2539 	sc->nb_ant   = val & 0x3;
2540 
2541 	DPRINTF(("RF revision=%d\n", sc->rf_rev));
2542 
2543 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_CONFIG2);
2544 	sc->ext_5ghz_lna = (val >> 6) & 0x1;
2545 	sc->ext_2ghz_lna = (val >> 4) & 0x1;
2546 
2547 	DPRINTF(("External 2GHz LNA=%d\nExternal 5GHz LNA=%d\n",
2548 	    sc->ext_2ghz_lna, sc->ext_5ghz_lna));
2549 
2550 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_2GHZ_OFFSET);
2551 	if ((val & 0xff) != 0xff)
2552 		sc->rssi_2ghz_corr = (int8_t)(val & 0xff);	/* signed */
2553 
2554 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_5GHZ_OFFSET);
2555 	if ((val & 0xff) != 0xff)
2556 		sc->rssi_5ghz_corr = (int8_t)(val & 0xff);	/* signed */
2557 
2558 	/* adjust RSSI correction for external low-noise amplifier */
2559 	if (sc->ext_2ghz_lna)
2560 		sc->rssi_2ghz_corr -= 14;
2561 	if (sc->ext_5ghz_lna)
2562 		sc->rssi_5ghz_corr -= 14;
2563 
2564 	DPRINTF(("RSSI 2GHz corr=%d\nRSSI 5GHz corr=%d\n",
2565 	    sc->rssi_2ghz_corr, sc->rssi_5ghz_corr));
2566 
2567 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_FREQ_OFFSET);
2568 	if ((val >> 8) != 0xff)
2569 		sc->rfprog = (val >> 8) & 0x3;
2570 	if ((val & 0xff) != 0xff)
2571 		sc->rffreq = val & 0xff;
2572 
2573 	DPRINTF(("RF prog=%d\nRF freq=%d\n", sc->rfprog, sc->rffreq));
2574 
2575 	/* read Tx power for all a/b/g channels */
2576 	for (i = 0; i < 19; i++) {
2577 		val = rt2661_eeprom_read(sc, RT2661_EEPROM_TXPOWER + i);
2578 		sc->txpow[i * 2] = (int8_t)(val >> 8);		/* signed */
2579 		DPRINTF(("Channel=%d Tx power=%d\n",
2580 		    rt2661_rf5225_1[i * 2].chan, sc->txpow[i * 2]));
2581 		sc->txpow[i * 2 + 1] = (int8_t)(val & 0xff);	/* signed */
2582 		DPRINTF(("Channel=%d Tx power=%d\n",
2583 		    rt2661_rf5225_1[i * 2 + 1].chan, sc->txpow[i * 2 + 1]));
2584 	}
2585 
2586 	/* read vendor-specific BBP values */
2587 	for (i = 0; i < 16; i++) {
2588 		val = rt2661_eeprom_read(sc, RT2661_EEPROM_BBP_BASE + i);
2589 		if (val == 0 || val == 0xffff)
2590 			continue;	/* skip invalid entries */
2591 		sc->bbp_prom[i].reg = val >> 8;
2592 		sc->bbp_prom[i].val = val & 0xff;
2593 		DPRINTF(("BBP R%d=%02x\n", sc->bbp_prom[i].reg,
2594 		    sc->bbp_prom[i].val));
2595 	}
2596 }
2597 
2598 static int
2599 rt2661_bbp_init(struct rt2661_softc *sc)
2600 {
2601 #define N(a)	(sizeof (a) / sizeof ((a)[0]))
2602 	int i, ntries;
2603 	uint8_t val;
2604 
2605 	/* wait for BBP to be ready */
2606 	for (ntries = 0; ntries < 100; ntries++) {
2607 		val = rt2661_bbp_read(sc, 0);
2608 		if (val != 0 && val != 0xff)
2609 			break;
2610 		DELAY(100);
2611 	}
2612 	if (ntries == 100) {
2613 		printf("%s: timeout waiting for BBP\n", sc->sc_dev.dv_xname);
2614 		return EIO;
2615 	}
2616 
2617 	/* initialize BBP registers to default values */
2618 	for (i = 0; i < N(rt2661_def_bbp); i++) {
2619 		rt2661_bbp_write(sc, rt2661_def_bbp[i].reg,
2620 		    rt2661_def_bbp[i].val);
2621 	}
2622 
2623 	/* write vendor-specific BBP values (from EEPROM) */
2624 	for (i = 0; i < 16; i++) {
2625 		if (sc->bbp_prom[i].reg == 0)
2626 			continue;
2627 		rt2661_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2628 	}
2629 
2630 	return 0;
2631 #undef N
2632 }
2633 
2634 static int
2635 rt2661_init(struct ifnet *ifp)
2636 {
2637 #define N(a)	(sizeof (a) / sizeof ((a)[0]))
2638 	struct rt2661_softc *sc = ifp->if_softc;
2639 	struct ieee80211com *ic = &sc->sc_ic;
2640 	const char *name = NULL;	/* make lint happy */
2641 	uint8_t *ucode;
2642 	size_t size;
2643 	uint32_t tmp, star[3];
2644 	int i, ntries;
2645 	firmware_handle_t fh;
2646 
2647 	/* for CardBus, power on the socket */
2648 	if (!(sc->sc_flags & RT2661_ENABLED)) {
2649 		if (sc->sc_enable != NULL && (*sc->sc_enable)(sc) != 0) {
2650 			printf("%s: could not enable device\n",
2651 			    sc->sc_dev.dv_xname);
2652 			return EIO;
2653 		}
2654 		sc->sc_flags |= RT2661_ENABLED;
2655 	}
2656 
2657 	rt2661_stop(ifp, 0);
2658 
2659 	if (!(sc->sc_flags & RT2661_FWLOADED)) {
2660 		switch (sc->sc_id) {
2661 		case PCI_PRODUCT_RALINK_RT2561:
2662 			name = "ral-rt2561";
2663 			break;
2664 		case PCI_PRODUCT_RALINK_RT2561S:
2665 			name = "ral-rt2561s";
2666 			break;
2667 		case PCI_PRODUCT_RALINK_RT2661:
2668 			name = "ral-rt2661";
2669 			break;
2670 		}
2671 
2672 		if (firmware_open("ral", name, &fh) != 0) {
2673 			printf("%s: could not open microcode %s\n",
2674 			    sc->sc_dev.dv_xname, name);
2675 			rt2661_stop(ifp, 1);
2676 			return EIO;
2677 		}
2678 
2679 		size = firmware_get_size(fh);
2680 		if (!(ucode = firmware_malloc(size))) {
2681 			printf("%s: could not alloc microcode memory\n",
2682 			    sc->sc_dev.dv_xname);
2683 			firmware_close(fh);
2684 			rt2661_stop(ifp, 1);
2685 			return ENOMEM;
2686 		}
2687 
2688 		if (firmware_read(fh, 0, ucode, size) != 0) {
2689 			printf("%s: could not read microcode %s\n",
2690 			    sc->sc_dev.dv_xname, name);
2691 			firmware_free(ucode, 0);
2692 			firmware_close(fh);
2693 			rt2661_stop(ifp, 1);
2694 			return EIO;
2695 		}
2696 
2697 		if (rt2661_load_microcode(sc, ucode, size) != 0) {
2698 			printf("%s: could not load 8051 microcode\n",
2699 			    sc->sc_dev.dv_xname);
2700 			firmware_free(ucode, 0);
2701 			firmware_close(fh);
2702 			rt2661_stop(ifp, 1);
2703 			return EIO;
2704 		}
2705 
2706 		firmware_free(ucode, 0);
2707 		firmware_close(fh);
2708 		sc->sc_flags |= RT2661_FWLOADED;
2709 	}
2710 
2711 	/* initialize Tx rings */
2712 	RAL_WRITE(sc, RT2661_AC1_BASE_CSR, sc->txq[1].physaddr);
2713 	RAL_WRITE(sc, RT2661_AC0_BASE_CSR, sc->txq[0].physaddr);
2714 	RAL_WRITE(sc, RT2661_AC2_BASE_CSR, sc->txq[2].physaddr);
2715 	RAL_WRITE(sc, RT2661_AC3_BASE_CSR, sc->txq[3].physaddr);
2716 
2717 	/* initialize Mgt ring */
2718 	RAL_WRITE(sc, RT2661_MGT_BASE_CSR, sc->mgtq.physaddr);
2719 
2720 	/* initialize Rx ring */
2721 	RAL_WRITE(sc, RT2661_RX_BASE_CSR, sc->rxq.physaddr);
2722 
2723 	/* initialize Tx rings sizes */
2724 	RAL_WRITE(sc, RT2661_TX_RING_CSR0,
2725 	    RT2661_TX_RING_COUNT << 24 |
2726 	    RT2661_TX_RING_COUNT << 16 |
2727 	    RT2661_TX_RING_COUNT <<  8 |
2728 	    RT2661_TX_RING_COUNT);
2729 
2730 	RAL_WRITE(sc, RT2661_TX_RING_CSR1,
2731 	    RT2661_TX_DESC_WSIZE << 16 |
2732 	    RT2661_TX_RING_COUNT <<  8 |	/* XXX: HCCA ring unused */
2733 	    RT2661_MGT_RING_COUNT);
2734 
2735 	/* initialize Rx rings */
2736 	RAL_WRITE(sc, RT2661_RX_RING_CSR,
2737 	    RT2661_RX_DESC_BACK  << 16 |
2738 	    RT2661_RX_DESC_WSIZE <<  8 |
2739 	    RT2661_RX_RING_COUNT);
2740 
2741 	/* XXX: some magic here */
2742 	RAL_WRITE(sc, RT2661_TX_DMA_DST_CSR, 0xaa);
2743 
2744 	/* load base addresses of all 5 Tx rings (4 data + 1 mgt) */
2745 	RAL_WRITE(sc, RT2661_LOAD_TX_RING_CSR, 0x1f);
2746 
2747 	/* load base address of Rx ring */
2748 	RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 2);
2749 
2750 	/* initialize MAC registers to default values */
2751 	for (i = 0; i < N(rt2661_def_mac); i++)
2752 		RAL_WRITE(sc, rt2661_def_mac[i].reg, rt2661_def_mac[i].val);
2753 
2754 	IEEE80211_ADDR_COPY(ic->ic_myaddr, CLLADDR(ifp->if_sadl));
2755 	rt2661_set_macaddr(sc, ic->ic_myaddr);
2756 
2757 	/* set host ready */
2758 	RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2759 	RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2760 
2761 	/* wait for BBP/RF to wakeup */
2762 	for (ntries = 0; ntries < 1000; ntries++) {
2763 		if (RAL_READ(sc, RT2661_MAC_CSR12) & 8)
2764 			break;
2765 		DELAY(1000);
2766 	}
2767 	if (ntries == 1000) {
2768 		printf("timeout waiting for BBP/RF to wakeup\n");
2769 		rt2661_stop(ifp, 1);
2770 		return EIO;
2771 	}
2772 
2773 	if (rt2661_bbp_init(sc) != 0) {
2774 		rt2661_stop(ifp, 1);
2775 		return EIO;
2776 	}
2777 
2778 	/* select default channel */
2779 	sc->sc_curchan = ic->ic_curchan;
2780 	rt2661_select_band(sc, sc->sc_curchan);
2781 	rt2661_select_antenna(sc);
2782 	rt2661_set_chan(sc, sc->sc_curchan);
2783 
2784 	/* update Rx filter */
2785 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0) & 0xffff;
2786 
2787 	tmp |= RT2661_DROP_PHY_ERROR | RT2661_DROP_CRC_ERROR;
2788 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2789 		tmp |= RT2661_DROP_CTL | RT2661_DROP_VER_ERROR |
2790 		       RT2661_DROP_ACKCTS;
2791 		if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2792 			tmp |= RT2661_DROP_TODS;
2793 		if (!(ifp->if_flags & IFF_PROMISC))
2794 			tmp |= RT2661_DROP_NOT_TO_ME;
2795 	}
2796 
2797 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2798 
2799 	/* clear STA registers */
2800 	RAL_READ_REGION_4(sc, RT2661_STA_CSR0, star, N(star));
2801 
2802 	/* initialize ASIC */
2803 	RAL_WRITE(sc, RT2661_MAC_CSR1, 4);
2804 
2805 	/* clear any pending interrupt */
2806 	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2807 
2808 	/* enable interrupts */
2809 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
2810 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
2811 
2812 	/* kick Rx */
2813 	RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 1);
2814 
2815 	ifp->if_flags &= ~IFF_OACTIVE;
2816 	ifp->if_flags |= IFF_RUNNING;
2817 
2818 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2819 		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
2820 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2821 	} else
2822 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2823 
2824 	return 0;
2825 #undef N
2826 }
2827 
2828 static void
2829 rt2661_stop(struct ifnet *ifp, int disable)
2830 {
2831 	struct rt2661_softc *sc = ifp->if_softc;
2832 	struct ieee80211com *ic = &sc->sc_ic;
2833 	uint32_t tmp;
2834 
2835 	sc->sc_tx_timer = 0;
2836 	ifp->if_timer = 0;
2837 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2838 
2839 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);	/* free all nodes */
2840 
2841 	/* abort Tx (for all 5 Tx rings) */
2842 	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 0x1f << 16);
2843 
2844 	/* disable Rx (value remains after reset!) */
2845 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2846 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2847 
2848 	/* reset ASIC */
2849 	RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2850 	RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2851 
2852 	/* disable interrupts */
2853 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffff7f);
2854 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
2855 
2856 	/* clear any pending interrupt */
2857 	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2858 	RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, 0xffffffff);
2859 
2860 	/* reset Tx and Rx rings */
2861 	rt2661_reset_tx_ring(sc, &sc->txq[0]);
2862 	rt2661_reset_tx_ring(sc, &sc->txq[1]);
2863 	rt2661_reset_tx_ring(sc, &sc->txq[2]);
2864 	rt2661_reset_tx_ring(sc, &sc->txq[3]);
2865 	rt2661_reset_tx_ring(sc, &sc->mgtq);
2866 	rt2661_reset_rx_ring(sc, &sc->rxq);
2867 
2868 	/* for CardBus, power down the socket */
2869 	if (disable && sc->sc_disable != NULL) {
2870 		if (sc->sc_flags & RT2661_ENABLED) {
2871 			(*sc->sc_disable)(sc);
2872 			sc->sc_flags &= ~(RT2661_ENABLED | RT2661_FWLOADED);
2873 		}
2874 	}
2875 }
2876 
2877 static int
2878 rt2661_load_microcode(struct rt2661_softc *sc, const uint8_t *ucode, int size)
2879 {
2880 	int ntries;
2881 
2882 	/* reset 8051 */
2883 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2884 
2885 	/* cancel any pending Host to MCU command */
2886 	RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR, 0);
2887 	RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
2888 	RAL_WRITE(sc, RT2661_HOST_CMD_CSR, 0);
2889 
2890 	/* write 8051's microcode */
2891 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET | RT2661_MCU_SEL);
2892 	RAL_WRITE_REGION_1(sc, RT2661_MCU_CODE_BASE, ucode, size);
2893 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2894 
2895 	/* kick 8051's ass */
2896 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, 0);
2897 
2898 	/* wait for 8051 to initialize */
2899 	for (ntries = 0; ntries < 500; ntries++) {
2900 		if (RAL_READ(sc, RT2661_MCU_CNTL_CSR) & RT2661_MCU_READY)
2901 			break;
2902 		DELAY(100);
2903 	}
2904 	if (ntries == 500) {
2905 		printf("timeout waiting for MCU to initialize\n");
2906 		return EIO;
2907 	}
2908 	return 0;
2909 }
2910 
2911 #ifdef notyet
2912 /*
2913  * Dynamically tune Rx sensitivity (BBP register 17) based on average RSSI and
2914  * false CCA count.  This function is called periodically (every seconds) when
2915  * in the RUN state.  Values taken from the reference driver.
2916  */
2917 static void
2918 rt2661_rx_tune(struct rt2661_softc *sc)
2919 {
2920 	uint8_t bbp17;
2921 	uint16_t cca;
2922 	int lo, hi, dbm;
2923 
2924 	/*
2925 	 * Tuning range depends on operating band and on the presence of an
2926 	 * external low-noise amplifier.
2927 	 */
2928 	lo = 0x20;
2929 	if (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan))
2930 		lo += 0x08;
2931 	if ((IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan) && sc->ext_2ghz_lna) ||
2932 	    (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan) && sc->ext_5ghz_lna))
2933 		lo += 0x10;
2934 	hi = lo + 0x20;
2935 
2936 	/* retrieve false CCA count since last call (clear on read) */
2937 	cca = RAL_READ(sc, RT2661_STA_CSR1) & 0xffff;
2938 
2939 	if (dbm >= -35) {
2940 		bbp17 = 0x60;
2941 	} else if (dbm >= -58) {
2942 		bbp17 = hi;
2943 	} else if (dbm >= -66) {
2944 		bbp17 = lo + 0x10;
2945 	} else if (dbm >= -74) {
2946 		bbp17 = lo + 0x08;
2947 	} else {
2948 		/* RSSI < -74dBm, tune using false CCA count */
2949 
2950 		bbp17 = sc->bbp17; /* current value */
2951 
2952 		hi -= 2 * (-74 - dbm);
2953 		if (hi < lo)
2954 			hi = lo;
2955 
2956 		if (bbp17 > hi) {
2957 			bbp17 = hi;
2958 
2959 		} else if (cca > 512) {
2960 			if (++bbp17 > hi)
2961 				bbp17 = hi;
2962 		} else if (cca < 100) {
2963 			if (--bbp17 < lo)
2964 				bbp17 = lo;
2965 		}
2966 	}
2967 
2968 	if (bbp17 != sc->bbp17) {
2969 		rt2661_bbp_write(sc, 17, bbp17);
2970 		sc->bbp17 = bbp17;
2971 	}
2972 }
2973 
2974 /*
2975  * Enter/Leave radar detection mode.
2976  * This is for 802.11h additional regulatory domains.
2977  */
2978 static void
2979 rt2661_radar_start(struct rt2661_softc *sc)
2980 {
2981 	uint32_t tmp;
2982 
2983 	/* disable Rx */
2984 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2985 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2986 
2987 	rt2661_bbp_write(sc, 82, 0x20);
2988 	rt2661_bbp_write(sc, 83, 0x00);
2989 	rt2661_bbp_write(sc, 84, 0x40);
2990 
2991 	/* save current BBP registers values */
2992 	sc->bbp18 = rt2661_bbp_read(sc, 18);
2993 	sc->bbp21 = rt2661_bbp_read(sc, 21);
2994 	sc->bbp22 = rt2661_bbp_read(sc, 22);
2995 	sc->bbp16 = rt2661_bbp_read(sc, 16);
2996 	sc->bbp17 = rt2661_bbp_read(sc, 17);
2997 	sc->bbp64 = rt2661_bbp_read(sc, 64);
2998 
2999 	rt2661_bbp_write(sc, 18, 0xff);
3000 	rt2661_bbp_write(sc, 21, 0x3f);
3001 	rt2661_bbp_write(sc, 22, 0x3f);
3002 	rt2661_bbp_write(sc, 16, 0xbd);
3003 	rt2661_bbp_write(sc, 17, sc->ext_5ghz_lna ? 0x44 : 0x34);
3004 	rt2661_bbp_write(sc, 64, 0x21);
3005 
3006 	/* restore Rx filter */
3007 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
3008 }
3009 
3010 static int
3011 rt2661_radar_stop(struct rt2661_softc *sc)
3012 {
3013 	uint8_t bbp66;
3014 
3015 	/* read radar detection result */
3016 	bbp66 = rt2661_bbp_read(sc, 66);
3017 
3018 	/* restore BBP registers values */
3019 	rt2661_bbp_write(sc, 16, sc->bbp16);
3020 	rt2661_bbp_write(sc, 17, sc->bbp17);
3021 	rt2661_bbp_write(sc, 18, sc->bbp18);
3022 	rt2661_bbp_write(sc, 21, sc->bbp21);
3023 	rt2661_bbp_write(sc, 22, sc->bbp22);
3024 	rt2661_bbp_write(sc, 64, sc->bbp64);
3025 
3026 	return bbp66 == 1;
3027 }
3028 #endif
3029 
3030 static int
3031 rt2661_prepare_beacon(struct rt2661_softc *sc)
3032 {
3033 	struct ieee80211com *ic = &sc->sc_ic;
3034 	struct rt2661_tx_desc desc;
3035 	struct mbuf *m0;
3036 	struct ieee80211_beacon_offsets bo;
3037 	int rate;
3038 
3039 	m0 = ieee80211_beacon_alloc(ic, ic->ic_bss, &bo);
3040 
3041 	if (m0 == NULL) {
3042 		printf("%s: could not allocate beacon frame\n",
3043 		    sc->sc_dev.dv_xname);
3044 		return ENOBUFS;
3045 	}
3046 
3047 	/* send beacons at the lowest available rate */
3048 	rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan) ? 12 : 2;
3049 
3050 	rt2661_setup_tx_desc(sc, &desc, RT2661_TX_TIMESTAMP, RT2661_TX_HWSEQ,
3051 	    m0->m_pkthdr.len, rate, NULL, 0, RT2661_QID_MGT);
3052 
3053 	/* copy the first 24 bytes of Tx descriptor into NIC memory */
3054 	RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0, (uint8_t *)&desc, 24);
3055 
3056 	/* copy beacon header and payload into NIC memory */
3057 	RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0 + 24,
3058 	    mtod(m0, uint8_t *), m0->m_pkthdr.len);
3059 
3060 	m_freem(m0);
3061 
3062 	return 0;
3063 }
3064 
3065 /*
3066  * Enable TSF synchronization and tell h/w to start sending beacons for IBSS
3067  * and HostAP operating modes.
3068  */
3069 static void
3070 rt2661_enable_tsf_sync(struct rt2661_softc *sc)
3071 {
3072 	struct ieee80211com *ic = &sc->sc_ic;
3073 	uint32_t tmp;
3074 
3075 	if (ic->ic_opmode != IEEE80211_M_STA) {
3076 		/*
3077 		 * Change default 16ms TBTT adjustment to 8ms.
3078 		 * Must be done before enabling beacon generation.
3079 		 */
3080 		RAL_WRITE(sc, RT2661_TXRX_CSR10, 1 << 12 | 8);
3081 	}
3082 
3083 	tmp = RAL_READ(sc, RT2661_TXRX_CSR9) & 0xff000000;
3084 
3085 	/* set beacon interval (in 1/16ms unit) */
3086 	tmp |= ic->ic_bss->ni_intval * 16;
3087 
3088 	tmp |= RT2661_TSF_TICKING | RT2661_ENABLE_TBTT;
3089 	if (ic->ic_opmode == IEEE80211_M_STA)
3090 		tmp |= RT2661_TSF_MODE(1);
3091 	else
3092 		tmp |= RT2661_TSF_MODE(2) | RT2661_GENERATE_BEACON;
3093 
3094 	RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp);
3095 }
3096 
3097 /*
3098  * Retrieve the "Received Signal Strength Indicator" from the raw values
3099  * contained in Rx descriptors.  The computation depends on which band the
3100  * frame was received.  Correction values taken from the reference driver.
3101  */
3102 static int
3103 rt2661_get_rssi(struct rt2661_softc *sc, uint8_t raw)
3104 {
3105 	int lna, agc, rssi;
3106 
3107 	lna = (raw >> 5) & 0x3;
3108 	agc = raw & 0x1f;
3109 
3110 	rssi = 2 * agc;
3111 
3112 	if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan)) {
3113 		rssi += sc->rssi_2ghz_corr;
3114 
3115 		if (lna == 1)
3116 			rssi -= 64;
3117 		else if (lna == 2)
3118 			rssi -= 74;
3119 		else if (lna == 3)
3120 			rssi -= 90;
3121 	} else {
3122 		rssi += sc->rssi_5ghz_corr;
3123 
3124 		if (lna == 1)
3125 			rssi -= 64;
3126 		else if (lna == 2)
3127 			rssi -= 86;
3128 		else if (lna == 3)
3129 			rssi -= 100;
3130 	}
3131 	return rssi;
3132 }
3133