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