Home | History | Annotate | Line # | Download | only in ic
rt2661.c revision 1.6
      1 /*	$NetBSD: rt2661.c,v 1.6 2006/06/08 20:56:41 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 (at) 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.6 2006/06/08 20:56:41 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_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 static void	rt2661_rx_tune(struct rt2661_softc *);
    162 #ifdef notyet
    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  * various settings like rate control statistics or Rx sensitivity.
    898  */
    899 static void
    900 rt2661_updatestats(void *arg)
    901 {
    902 	struct rt2661_softc *sc = arg;
    903 	struct ieee80211com *ic = &sc->sc_ic;
    904 
    905 	if (ic->ic_opmode == IEEE80211_M_STA)
    906 		rt2661_iter_func(sc, ic->ic_bss);
    907 	else
    908 		ieee80211_iterate_nodes(&ic->ic_sta, rt2661_iter_func, arg);
    909 
    910 	/* update rx sensitivity every 1 sec */
    911 	if (++sc->ncalls == 10) {
    912 		rt2661_rx_tune(sc);
    913 		sc->ncalls = 0;
    914 	}
    915 
    916 	callout_reset(&sc->rssadapt_ch, hz / 10, rt2661_updatestats, sc);
    917 }
    918 
    919 static int
    920 rt2661_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
    921 {
    922 	struct rt2661_softc *sc = ic->ic_ifp->if_softc;
    923 	enum ieee80211_state ostate;
    924 	struct ieee80211_node *ni;
    925 	uint32_t tmp;
    926 	int error = 0;
    927 
    928 	ostate = ic->ic_state;
    929 	callout_stop(&sc->scan_ch);
    930 
    931 	switch (nstate) {
    932 	case IEEE80211_S_INIT:
    933 		callout_stop(&sc->rssadapt_ch);
    934 
    935 		if (ostate == IEEE80211_S_RUN) {
    936 			/* abort TSF synchronization */
    937 			tmp = RAL_READ(sc, RT2661_TXRX_CSR9);
    938 			RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp & ~0x00ffffff);
    939 		}
    940 		break;
    941 
    942 	case IEEE80211_S_SCAN:
    943 		rt2661_set_chan(sc, ic->ic_curchan);
    944 		callout_reset(&sc->scan_ch, hz / 5, rt2661_next_scan, sc);
    945 		break;
    946 
    947 	case IEEE80211_S_AUTH:
    948 	case IEEE80211_S_ASSOC:
    949 		rt2661_set_chan(sc, ic->ic_curchan);
    950 		break;
    951 
    952 	case IEEE80211_S_RUN:
    953 		rt2661_set_chan(sc, ic->ic_curchan);
    954 
    955 		ni = ic->ic_bss;
    956 
    957 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
    958 			rt2661_enable_mrr(sc);
    959 			rt2661_set_txpreamble(sc);
    960 			rt2661_set_basicrates(sc, &ni->ni_rates);
    961 			rt2661_set_bssid(sc, ni->ni_bssid);
    962 		}
    963 
    964 		if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
    965 		    ic->ic_opmode == IEEE80211_M_IBSS) {
    966 			if ((error = rt2661_prepare_beacon(sc)) != 0)
    967 				break;
    968 		}
    969 
    970 		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
    971 			sc->ncalls = 0;
    972 			sc->avg_rssi = -95;	/* reset EMA */
    973 			callout_reset(&sc->rssadapt_ch, hz / 10,
    974 			    rt2661_updatestats, sc);
    975 			rt2661_enable_tsf_sync(sc);
    976 		}
    977 		break;
    978 	}
    979 
    980 	return (error != 0) ? error : sc->sc_newstate(ic, nstate, arg);
    981 }
    982 
    983 /*
    984  * Read 16 bits at address 'addr' from the serial EEPROM (either 93C46 or
    985  * 93C66).
    986  */
    987 static uint16_t
    988 rt2661_eeprom_read(struct rt2661_softc *sc, uint8_t addr)
    989 {
    990 	uint32_t tmp;
    991 	uint16_t val;
    992 	int n;
    993 
    994 	/* clock C once before the first command */
    995 	RT2661_EEPROM_CTL(sc, 0);
    996 
    997 	RT2661_EEPROM_CTL(sc, RT2661_S);
    998 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
    999 	RT2661_EEPROM_CTL(sc, RT2661_S);
   1000 
   1001 	/* write start bit (1) */
   1002 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
   1003 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
   1004 
   1005 	/* write READ opcode (10) */
   1006 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
   1007 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
   1008 	RT2661_EEPROM_CTL(sc, RT2661_S);
   1009 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
   1010 
   1011 	/* write address (A5-A0 or A7-A0) */
   1012 	n = (RAL_READ(sc, RT2661_E2PROM_CSR) & RT2661_93C46) ? 5 : 7;
   1013 	for (; n >= 0; n--) {
   1014 		RT2661_EEPROM_CTL(sc, RT2661_S |
   1015 		    (((addr >> n) & 1) << RT2661_SHIFT_D));
   1016 		RT2661_EEPROM_CTL(sc, RT2661_S |
   1017 		    (((addr >> n) & 1) << RT2661_SHIFT_D) | RT2661_C);
   1018 	}
   1019 
   1020 	RT2661_EEPROM_CTL(sc, RT2661_S);
   1021 
   1022 	/* read data Q15-Q0 */
   1023 	val = 0;
   1024 	for (n = 15; n >= 0; n--) {
   1025 		RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
   1026 		tmp = RAL_READ(sc, RT2661_E2PROM_CSR);
   1027 		val |= ((tmp & RT2661_Q) >> RT2661_SHIFT_Q) << n;
   1028 		RT2661_EEPROM_CTL(sc, RT2661_S);
   1029 	}
   1030 
   1031 	RT2661_EEPROM_CTL(sc, 0);
   1032 
   1033 	/* clear Chip Select and clock C */
   1034 	RT2661_EEPROM_CTL(sc, RT2661_S);
   1035 	RT2661_EEPROM_CTL(sc, 0);
   1036 	RT2661_EEPROM_CTL(sc, RT2661_C);
   1037 
   1038 	return val;
   1039 }
   1040 
   1041 static void
   1042 rt2661_tx_intr(struct rt2661_softc *sc)
   1043 {
   1044 	struct ieee80211com *ic = &sc->sc_ic;
   1045 	struct ifnet *ifp = &sc->sc_if;
   1046 	struct rt2661_tx_ring *txq;
   1047 	struct rt2661_tx_data *data;
   1048 	struct rt2661_node *rn;
   1049 	uint32_t val;
   1050 	int qid, retrycnt;
   1051 
   1052 	for (;;) {
   1053 		val = RAL_READ(sc, RT2661_STA_CSR4);
   1054 		if (!(val & RT2661_TX_STAT_VALID))
   1055 			break;
   1056 
   1057 		/* retrieve the queue in which this frame was sent */
   1058 		qid = RT2661_TX_QID(val);
   1059 		txq = (qid <= 3) ? &sc->txq[qid] : &sc->mgtq;
   1060 
   1061 		/* retrieve rate control algorithm context */
   1062 		data = &txq->data[txq->stat];
   1063 		rn = (struct rt2661_node *)data->ni;
   1064 
   1065 		/* if no frame has been sent, ignore */
   1066 		if (rn == NULL)
   1067 			continue;
   1068 
   1069 		switch (RT2661_TX_RESULT(val)) {
   1070 		case RT2661_TX_SUCCESS:
   1071 			retrycnt = RT2661_TX_RETRYCNT(val);
   1072 
   1073 			DPRINTFN(10, ("data frame sent successfully after "
   1074 			    "%d retries\n", retrycnt));
   1075 			if (retrycnt == 0 && data->id.id_node != NULL) {
   1076 				ieee80211_rssadapt_raise_rate(ic,
   1077 				    &rn->rssadapt, &data->id);
   1078 			}
   1079 			ifp->if_opackets++;
   1080 			break;
   1081 
   1082 		case RT2661_TX_RETRY_FAIL:
   1083 			DPRINTFN(9, ("sending data frame failed (too much "
   1084 			    "retries)\n"));
   1085 			if (data->id.id_node != NULL) {
   1086 				ieee80211_rssadapt_lower_rate(ic, data->ni,
   1087 				    &rn->rssadapt, &data->id);
   1088 			}
   1089 			ifp->if_oerrors++;
   1090 			break;
   1091 
   1092 		default:
   1093 			/* other failure */
   1094 			printf("%s: sending data frame failed 0x%08x\n",
   1095 			    sc->sc_dev.dv_xname, val);
   1096 			ifp->if_oerrors++;
   1097 		}
   1098 
   1099 		ieee80211_free_node(data->ni);
   1100 		data->ni = NULL;
   1101 
   1102 		DPRINTFN(15, ("tx done q=%d idx=%u\n", qid, txq->stat));
   1103 
   1104 		txq->queued--;
   1105 		if (++txq->stat >= txq->count)	/* faster than % count */
   1106 			txq->stat = 0;
   1107 	}
   1108 
   1109 	sc->sc_tx_timer = 0;
   1110 	ifp->if_flags &= ~IFF_OACTIVE;
   1111 	rt2661_start(ifp);
   1112 }
   1113 
   1114 static void
   1115 rt2661_tx_dma_intr(struct rt2661_softc *sc, struct rt2661_tx_ring *txq)
   1116 {
   1117 	struct rt2661_tx_desc *desc;
   1118 	struct rt2661_tx_data *data;
   1119 
   1120 	for (;;) {
   1121 		desc = &txq->desc[txq->next];
   1122 		data = &txq->data[txq->next];
   1123 
   1124 		bus_dmamap_sync(sc->sc_dmat, txq->map,
   1125 		    txq->next * RT2661_TX_DESC_SIZE, RT2661_TX_DESC_SIZE,
   1126 		    BUS_DMASYNC_POSTREAD);
   1127 
   1128 		if ((le32toh(desc->flags) & RT2661_TX_BUSY) ||
   1129 		    !(le32toh(desc->flags) & RT2661_TX_VALID))
   1130 			break;
   1131 
   1132 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
   1133 		    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
   1134 		bus_dmamap_unload(sc->sc_dmat, data->map);
   1135 		m_freem(data->m);
   1136 		data->m = NULL;
   1137 		/* node reference is released in rt2661_tx_intr() */
   1138 
   1139 		/* descriptor is no longer valid */
   1140 		desc->flags &= ~htole32(RT2661_TX_VALID);
   1141 
   1142 		bus_dmamap_sync(sc->sc_dmat, txq->map,
   1143 		    txq->next * RT2661_TX_DESC_SIZE, RT2661_TX_DESC_SIZE,
   1144 		    BUS_DMASYNC_PREWRITE);
   1145 
   1146 		DPRINTFN(15, ("tx dma done q=%p idx=%u\n", txq, txq->next));
   1147 
   1148 		if (++txq->next >= txq->count)	/* faster than % count */
   1149 			txq->next = 0;
   1150 	}
   1151 }
   1152 
   1153 static void
   1154 rt2661_rx_intr(struct rt2661_softc *sc)
   1155 {
   1156 	struct ieee80211com *ic = &sc->sc_ic;
   1157 	struct ifnet *ifp = &sc->sc_if;
   1158 	struct rt2661_rx_desc *desc;
   1159 	struct rt2661_rx_data *data;
   1160 	struct rt2661_node *rn;
   1161 	struct ieee80211_frame *wh;
   1162 	struct ieee80211_node *ni;
   1163 	struct mbuf *mnew, *m;
   1164 	int error, rssi;
   1165 
   1166 	for (;;) {
   1167 		desc = &sc->rxq.desc[sc->rxq.cur];
   1168 		data = &sc->rxq.data[sc->rxq.cur];
   1169 
   1170 		bus_dmamap_sync(sc->sc_dmat, sc->rxq.map,
   1171 		    sc->rxq.cur * RT2661_RX_DESC_SIZE, RT2661_RX_DESC_SIZE,
   1172 		    BUS_DMASYNC_POSTREAD);
   1173 
   1174 		if (le32toh(desc->flags) & RT2661_RX_BUSY)
   1175 			break;
   1176 
   1177 		if ((le32toh(desc->flags) & RT2661_RX_PHY_ERROR) ||
   1178 		    (le32toh(desc->flags) & RT2661_RX_CRC_ERROR)) {
   1179 			/*
   1180 			 * This should not happen since we did not request
   1181 			 * to receive those frames when we filled TXRX_CSR0.
   1182 			 */
   1183 			DPRINTFN(5, ("PHY or CRC error flags 0x%08x\n",
   1184 			    le32toh(desc->flags)));
   1185 			ifp->if_ierrors++;
   1186 			goto skip;
   1187 		}
   1188 
   1189 		if ((le32toh(desc->flags) & RT2661_RX_CIPHER_MASK) != 0) {
   1190 			ifp->if_ierrors++;
   1191 			goto skip;
   1192 		}
   1193 
   1194 		/*
   1195 		 * Try to allocate a new mbuf for this ring element and load it
   1196 		 * before processing the current mbuf. If the ring element
   1197 		 * cannot be loaded, drop the received packet and reuse the old
   1198 		 * mbuf. In the unlikely case that the old mbuf can't be
   1199 		 * reloaded either, explicitly panic.
   1200 		 */
   1201 		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
   1202 		if (mnew == NULL) {
   1203 			ifp->if_ierrors++;
   1204 			goto skip;
   1205 		}
   1206 
   1207 		MCLGET(mnew, M_DONTWAIT);
   1208 		if (!(mnew->m_flags & M_EXT)) {
   1209 			m_freem(mnew);
   1210 			ifp->if_ierrors++;
   1211 			goto skip;
   1212 		}
   1213 
   1214 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
   1215 		    data->map->dm_mapsize, BUS_DMASYNC_POSTREAD);
   1216 		bus_dmamap_unload(sc->sc_dmat, data->map);
   1217 
   1218 		error = bus_dmamap_load(sc->sc_dmat, data->map,
   1219 		    mtod(mnew, void *), MCLBYTES, NULL, BUS_DMA_NOWAIT);
   1220 		if (error != 0) {
   1221 			m_freem(mnew);
   1222 
   1223 			/* try to reload the old mbuf */
   1224 			error = bus_dmamap_load(sc->sc_dmat, data->map,
   1225 			    mtod(data->m, void *), MCLBYTES, NULL,
   1226 			    BUS_DMA_NOWAIT);
   1227 			if (error != 0) {
   1228 				/* very unlikely that it will fail... */
   1229 				panic("%s: could not load old rx mbuf",
   1230 				    sc->sc_dev.dv_xname);
   1231 			}
   1232 			ifp->if_ierrors++;
   1233 			goto skip;
   1234 		}
   1235 
   1236 		/*
   1237 	 	 * New mbuf successfully loaded, update Rx ring and continue
   1238 		 * processing.
   1239 		 */
   1240 		m = data->m;
   1241 		data->m = mnew;
   1242 		desc->physaddr = htole32(data->map->dm_segs->ds_addr);
   1243 
   1244 		/* finalize mbuf */
   1245 		m->m_pkthdr.rcvif = ifp;
   1246 		m->m_pkthdr.len = m->m_len =
   1247 		    (le32toh(desc->flags) >> 16) & 0xfff;
   1248 
   1249 #if NBPFILTER > 0
   1250 		if (sc->sc_drvbpf != NULL) {
   1251 			struct rt2661_rx_radiotap_header *tap = &sc->sc_rxtap;
   1252 			uint32_t tsf_lo, tsf_hi;
   1253 
   1254 			/* get timestamp (low and high 32 bits) */
   1255 			tsf_hi = RAL_READ(sc, RT2661_TXRX_CSR13);
   1256 			tsf_lo = RAL_READ(sc, RT2661_TXRX_CSR12);
   1257 
   1258 			tap->wr_tsf =
   1259 			    htole64(((uint64_t)tsf_hi << 32) | tsf_lo);
   1260 			tap->wr_flags = 0;
   1261 			tap->wr_rate = rt2661_rxrate(desc);
   1262 			tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
   1263 			tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
   1264 			tap->wr_antsignal = desc->rssi;
   1265 
   1266 			bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m);
   1267 		}
   1268 #endif
   1269 
   1270 		wh = mtod(m, struct ieee80211_frame *);
   1271 		ni = ieee80211_find_rxnode(ic,
   1272 		    (struct ieee80211_frame_min *)wh);
   1273 
   1274 		/* send the frame to the 802.11 layer */
   1275 		ieee80211_input(ic, m, ni, desc->rssi, 0);
   1276 
   1277 
   1278 		/* give rssi to the rate adatation algorithm */
   1279 		rn = (struct rt2661_node *)ni;
   1280 		rssi = rt2661_get_rssi(sc, desc->rssi);
   1281 		ieee80211_rssadapt_input(ic, ni, &rn->rssadapt, rssi);
   1282 
   1283 		/*-
   1284 		 * Keep track of the average RSSI using an Exponential Moving
   1285 		 * Average (EMA) of 8 Wilder's days:
   1286 		 *     avg = (1 / N) x rssi + ((N - 1) / N) x avg
   1287 		 */
   1288 		sc->avg_rssi = (rssi + 7 * sc->avg_rssi) / 8;
   1289 
   1290 		/* node is no longer needed */
   1291 		ieee80211_free_node(ni);
   1292 
   1293 skip:		desc->flags |= htole32(RT2661_RX_BUSY);
   1294 
   1295 		bus_dmamap_sync(sc->sc_dmat, sc->rxq.map,
   1296 		    sc->rxq.cur * RT2661_RX_DESC_SIZE, RT2661_RX_DESC_SIZE,
   1297 		    BUS_DMASYNC_PREWRITE);
   1298 
   1299 		DPRINTFN(15, ("rx intr idx=%u\n", sc->rxq.cur));
   1300 
   1301 		sc->rxq.cur = (sc->rxq.cur + 1) % RT2661_RX_RING_COUNT;
   1302 	}
   1303 
   1304 	/*
   1305 	 * In HostAP mode, ieee80211_input() will enqueue packets in if_snd
   1306 	 * without calling if_start().
   1307 	 */
   1308 	if (!IFQ_IS_EMPTY(&ifp->if_snd) && !(ifp->if_flags & IFF_OACTIVE))
   1309 		rt2661_start(ifp);
   1310 }
   1311 
   1312 /* ARGSUSED */
   1313 static void
   1314 rt2661_mcu_beacon_expire(struct rt2661_softc *sc)
   1315 {
   1316 	/* do nothing */
   1317 }
   1318 
   1319 static void
   1320 rt2661_mcu_wakeup(struct rt2661_softc *sc)
   1321 {
   1322 	RAL_WRITE(sc, RT2661_MAC_CSR11, 5 << 16);
   1323 
   1324 	RAL_WRITE(sc, RT2661_SOFT_RESET_CSR, 0x7);
   1325 	RAL_WRITE(sc, RT2661_IO_CNTL_CSR, 0x18);
   1326 	RAL_WRITE(sc, RT2661_PCI_USEC_CSR, 0x20);
   1327 
   1328 	/* send wakeup command to MCU */
   1329 	rt2661_tx_cmd(sc, RT2661_MCU_CMD_WAKEUP, 0);
   1330 }
   1331 
   1332 static void
   1333 rt2661_mcu_cmd_intr(struct rt2661_softc *sc)
   1334 {
   1335 	RAL_READ(sc, RT2661_M2H_CMD_DONE_CSR);
   1336 	RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
   1337 }
   1338 
   1339 int
   1340 rt2661_intr(void *arg)
   1341 {
   1342 	struct rt2661_softc *sc = arg;
   1343 	struct ifnet *ifp = &sc->sc_if;
   1344 	uint32_t r1, r2;
   1345 
   1346 	/* disable MAC and MCU interrupts */
   1347 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffff7f);
   1348 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
   1349 
   1350 	/* don't re-enable interrupts if we're shutting down */
   1351 	if (!(ifp->if_flags & IFF_RUNNING))
   1352 		return 0;
   1353 
   1354 	r1 = RAL_READ(sc, RT2661_INT_SOURCE_CSR);
   1355 	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, r1);
   1356 
   1357 	r2 = RAL_READ(sc, RT2661_MCU_INT_SOURCE_CSR);
   1358 	RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, r2);
   1359 
   1360 	if (r1 & RT2661_MGT_DONE)
   1361 		rt2661_tx_dma_intr(sc, &sc->mgtq);
   1362 
   1363 	if (r1 & RT2661_RX_DONE)
   1364 		rt2661_rx_intr(sc);
   1365 
   1366 	if (r1 & RT2661_TX0_DMA_DONE)
   1367 		rt2661_tx_dma_intr(sc, &sc->txq[0]);
   1368 
   1369 	if (r1 & RT2661_TX1_DMA_DONE)
   1370 		rt2661_tx_dma_intr(sc, &sc->txq[1]);
   1371 
   1372 	if (r1 & RT2661_TX2_DMA_DONE)
   1373 		rt2661_tx_dma_intr(sc, &sc->txq[2]);
   1374 
   1375 	if (r1 & RT2661_TX3_DMA_DONE)
   1376 		rt2661_tx_dma_intr(sc, &sc->txq[3]);
   1377 
   1378 	if (r1 & RT2661_TX_DONE)
   1379 		rt2661_tx_intr(sc);
   1380 
   1381 	if (r2 & RT2661_MCU_CMD_DONE)
   1382 		rt2661_mcu_cmd_intr(sc);
   1383 
   1384 	if (r2 & RT2661_MCU_BEACON_EXPIRE)
   1385 		rt2661_mcu_beacon_expire(sc);
   1386 
   1387 	if (r2 & RT2661_MCU_WAKEUP)
   1388 		rt2661_mcu_wakeup(sc);
   1389 
   1390 	/* re-enable MAC and MCU interrupts */
   1391 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
   1392 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
   1393 
   1394 	return 1;
   1395 }
   1396 
   1397 /* quickly determine if a given rate is CCK or OFDM */
   1398 #define RAL_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
   1399 
   1400 #define RAL_ACK_SIZE	14	/* 10 + 4(FCS) */
   1401 #define RAL_CTS_SIZE	14	/* 10 + 4(FCS) */
   1402 
   1403 #define RAL_SIFS	10	/* us */
   1404 
   1405 /*
   1406  * This function is only used by the Rx radiotap code. It returns the rate at
   1407  * which a given frame was received.
   1408  */
   1409 #if NBPFILTER > 0
   1410 static uint8_t
   1411 rt2661_rxrate(struct rt2661_rx_desc *desc)
   1412 {
   1413 	if (le32toh(desc->flags) & RT2661_RX_OFDM) {
   1414 		/* reverse function of rt2661_plcp_signal */
   1415 		switch (desc->rate & 0xf) {
   1416 		case 0xb:	return 12;
   1417 		case 0xf:	return 18;
   1418 		case 0xa:	return 24;
   1419 		case 0xe:	return 36;
   1420 		case 0x9:	return 48;
   1421 		case 0xd:	return 72;
   1422 		case 0x8:	return 96;
   1423 		case 0xc:	return 108;
   1424 		}
   1425 	} else {
   1426 		if (desc->rate == 10)
   1427 			return 2;
   1428 		if (desc->rate == 20)
   1429 			return 4;
   1430 		if (desc->rate == 55)
   1431 			return 11;
   1432 		if (desc->rate == 110)
   1433 			return 22;
   1434 	}
   1435 	return 2;	/* should not get there */
   1436 }
   1437 #endif
   1438 
   1439 /*
   1440  * Return the expected ack rate for a frame transmitted at rate `rate'.
   1441  * XXX: this should depend on the destination node basic rate set.
   1442  */
   1443 static int
   1444 rt2661_ack_rate(struct ieee80211com *ic, int rate)
   1445 {
   1446 	switch (rate) {
   1447 	/* CCK rates */
   1448 	case 2:
   1449 		return 2;
   1450 	case 4:
   1451 	case 11:
   1452 	case 22:
   1453 		return (ic->ic_curmode == IEEE80211_MODE_11B) ? 4 : rate;
   1454 
   1455 	/* OFDM rates */
   1456 	case 12:
   1457 	case 18:
   1458 		return 12;
   1459 	case 24:
   1460 	case 36:
   1461 		return 24;
   1462 	case 48:
   1463 	case 72:
   1464 	case 96:
   1465 	case 108:
   1466 		return 48;
   1467 	}
   1468 
   1469 	/* default to 1Mbps */
   1470 	return 2;
   1471 }
   1472 
   1473 /*
   1474  * Compute the duration (in us) needed to transmit `len' bytes at rate `rate'.
   1475  * The function automatically determines the operating mode depending on the
   1476  * given rate. `flags' indicates whether short preamble is in use or not.
   1477  */
   1478 static uint16_t
   1479 rt2661_txtime(int len, int rate, uint32_t flags)
   1480 {
   1481 	uint16_t txtime;
   1482 
   1483 	if (RAL_RATE_IS_OFDM(rate)) {
   1484 		/* IEEE Std 802.11a-1999, pp. 37 */
   1485 		txtime = (8 + 4 * len + 3 + rate - 1) / rate;
   1486 		txtime = 16 + 4 + 4 * txtime + 6;
   1487 	} else {
   1488 		/* IEEE Std 802.11b-1999, pp. 28 */
   1489 		txtime = (16 * len + rate - 1) / rate;
   1490 		if (rate != 2 && (flags & IEEE80211_F_SHPREAMBLE))
   1491 			txtime +=  72 + 24;
   1492 		else
   1493 			txtime += 144 + 48;
   1494 	}
   1495 	return txtime;
   1496 }
   1497 
   1498 static uint8_t
   1499 rt2661_plcp_signal(int rate)
   1500 {
   1501 	switch (rate) {
   1502 	/* CCK rates (returned values are device-dependent) */
   1503 	case 2:		return 0x0;
   1504 	case 4:		return 0x1;
   1505 	case 11:	return 0x2;
   1506 	case 22:	return 0x3;
   1507 
   1508 	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
   1509 	case 12:	return 0xb;
   1510 	case 18:	return 0xf;
   1511 	case 24:	return 0xa;
   1512 	case 36:	return 0xe;
   1513 	case 48:	return 0x9;
   1514 	case 72:	return 0xd;
   1515 	case 96:	return 0x8;
   1516 	case 108:	return 0xc;
   1517 
   1518 	/* unsupported rates (should not get there) */
   1519 	default:	return 0xff;
   1520 	}
   1521 }
   1522 
   1523 static void
   1524 rt2661_setup_tx_desc(struct rt2661_softc *sc, struct rt2661_tx_desc *desc,
   1525     uint32_t flags, uint16_t xflags, int len, int rate,
   1526     const bus_dma_segment_t *segs, int nsegs, int ac)
   1527 {
   1528 	struct ieee80211com *ic = &sc->sc_ic;
   1529 	uint16_t plcp_length;
   1530 	int i, remainder;
   1531 
   1532 	desc->flags = htole32(flags);
   1533 	desc->flags |= htole32(len << 16);
   1534 	desc->flags |= htole32(RT2661_TX_BUSY | RT2661_TX_VALID);
   1535 
   1536 	desc->xflags = htole16(xflags);
   1537 	desc->xflags |= htole16(nsegs << 13);
   1538 
   1539 	desc->wme = htole16(
   1540 	    RT2661_QID(ac) |
   1541 	    RT2661_AIFSN(2) |
   1542 	    RT2661_LOGCWMIN(4) |
   1543 	    RT2661_LOGCWMAX(10));
   1544 
   1545 	/*
   1546 	 * Remember in which queue this frame was sent. This field is driver
   1547 	 * private data only. It will be made available by the NIC in STA_CSR4
   1548 	 * on Tx interrupts.
   1549 	 */
   1550 	desc->qid = ac;
   1551 
   1552 	/* setup PLCP fields */
   1553 	desc->plcp_signal  = rt2661_plcp_signal(rate);
   1554 	desc->plcp_service = 4;
   1555 
   1556 	len += IEEE80211_CRC_LEN;
   1557 	if (RAL_RATE_IS_OFDM(rate)) {
   1558 		desc->flags |= htole32(RT2661_TX_OFDM);
   1559 
   1560 		plcp_length = len & 0xfff;
   1561 		desc->plcp_length_hi = plcp_length >> 6;
   1562 		desc->plcp_length_lo = plcp_length & 0x3f;
   1563 	} else {
   1564 		plcp_length = (16 * len + rate - 1) / rate;
   1565 		if (rate == 22) {
   1566 			remainder = (16 * len) % 22;
   1567 			if (remainder != 0 && remainder < 7)
   1568 				desc->plcp_service |= RT2661_PLCP_LENGEXT;
   1569 		}
   1570 		desc->plcp_length_hi = plcp_length >> 8;
   1571 		desc->plcp_length_lo = plcp_length & 0xff;
   1572 
   1573 		if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
   1574 			desc->plcp_signal |= 0x08;
   1575 	}
   1576 
   1577 	/* RT2x61 supports scatter with up to 5 segments */
   1578 	for (i = 0; i < nsegs; i++) {
   1579 		desc->addr[i] = htole32(segs[i].ds_addr);
   1580 		desc->len [i] = htole16(segs[i].ds_len);
   1581 	}
   1582 }
   1583 
   1584 static int
   1585 rt2661_tx_mgt(struct rt2661_softc *sc, struct mbuf *m0,
   1586     struct ieee80211_node *ni)
   1587 {
   1588 	struct ieee80211com *ic = &sc->sc_ic;
   1589 	struct rt2661_tx_desc *desc;
   1590 	struct rt2661_tx_data *data;
   1591 	struct ieee80211_frame *wh;
   1592 	uint16_t dur;
   1593 	uint32_t flags = 0;
   1594 	int rate, error;
   1595 
   1596 	desc = &sc->mgtq.desc[sc->mgtq.cur];
   1597 	data = &sc->mgtq.data[sc->mgtq.cur];
   1598 
   1599 	/* send mgt frames at the lowest available rate */
   1600 	rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
   1601 
   1602 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
   1603 	    BUS_DMA_NOWAIT);
   1604 	if (error != 0) {
   1605 		printf("%s: could not map mbuf (error %d)\n",
   1606 		    sc->sc_dev.dv_xname, error);
   1607 		m_freem(m0);
   1608 		return error;
   1609 	}
   1610 
   1611 #if NBPFILTER > 0
   1612 	if (sc->sc_drvbpf != NULL) {
   1613 		struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
   1614 
   1615 		tap->wt_flags = 0;
   1616 		tap->wt_rate = rate;
   1617 		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
   1618 		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
   1619 
   1620 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
   1621 	}
   1622 #endif
   1623 
   1624 	data->m = m0;
   1625 	data->ni = ni;
   1626 
   1627 	wh = mtod(m0, struct ieee80211_frame *);
   1628 
   1629 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
   1630 		flags |= RT2661_TX_NEED_ACK;
   1631 
   1632 		dur = rt2661_txtime(RAL_ACK_SIZE, rate, ic->ic_flags) +
   1633 		    RAL_SIFS;
   1634 		*(uint16_t *)wh->i_dur = htole16(dur);
   1635 
   1636 		/* tell hardware to add timestamp in probe responses */
   1637 		if ((wh->i_fc[0] &
   1638 		    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
   1639 		    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
   1640 			flags |= RT2661_TX_TIMESTAMP;
   1641 	}
   1642 
   1643 	rt2661_setup_tx_desc(sc, desc, flags, 0 /* XXX HWSEQ */,
   1644 	    m0->m_pkthdr.len, rate, data->map->dm_segs, data->map->dm_nsegs,
   1645 	    RT2661_QID_MGT);
   1646 
   1647 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
   1648 	    BUS_DMASYNC_PREWRITE);
   1649 	bus_dmamap_sync(sc->sc_dmat, sc->mgtq.map,
   1650 	    sc->mgtq.cur * RT2661_TX_DESC_SIZE, RT2661_TX_DESC_SIZE,
   1651 	    BUS_DMASYNC_PREWRITE);
   1652 
   1653 	DPRINTFN(10, ("sending mgt frame len=%u idx=%u rate=%u\n",
   1654 	    m0->m_pkthdr.len, sc->mgtq.cur, rate));
   1655 
   1656 	/* kick mgt */
   1657 	sc->mgtq.queued++;
   1658 	sc->mgtq.cur = (sc->mgtq.cur + 1) % RT2661_MGT_RING_COUNT;
   1659 	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, RT2661_KICK_MGT);
   1660 
   1661 	return 0;
   1662 }
   1663 
   1664 /*
   1665  * Build a RTS control frame.
   1666  */
   1667 static struct mbuf *
   1668 rt2661_get_rts(struct rt2661_softc *sc, struct ieee80211_frame *wh,
   1669     uint16_t dur)
   1670 {
   1671 	struct ieee80211_frame_rts *rts;
   1672 	struct mbuf *m;
   1673 
   1674 	MGETHDR(m, M_DONTWAIT, MT_DATA);
   1675 	if (m == NULL) {
   1676 		sc->sc_ic.ic_stats.is_tx_nobuf++;
   1677 		printf("%s: could not allocate RTS frame\n",
   1678 		    sc->sc_dev.dv_xname);
   1679 		return NULL;
   1680 	}
   1681 
   1682 	rts = mtod(m, struct ieee80211_frame_rts *);
   1683 
   1684 	rts->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_CTL |
   1685 	    IEEE80211_FC0_SUBTYPE_RTS;
   1686 	rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
   1687 	*(uint16_t *)rts->i_dur = htole16(dur);
   1688 	IEEE80211_ADDR_COPY(rts->i_ra, wh->i_addr1);
   1689 	IEEE80211_ADDR_COPY(rts->i_ta, wh->i_addr2);
   1690 
   1691 	m->m_pkthdr.len = m->m_len = sizeof (struct ieee80211_frame_rts);
   1692 
   1693 	return m;
   1694 }
   1695 
   1696 static int
   1697 rt2661_tx_data(struct rt2661_softc *sc, struct mbuf *m0,
   1698     struct ieee80211_node *ni, int ac)
   1699 {
   1700 	struct ieee80211com *ic = &sc->sc_ic;
   1701 	struct rt2661_tx_ring *txq = &sc->txq[ac];
   1702 	struct rt2661_tx_desc *desc;
   1703 	struct rt2661_tx_data *data;
   1704 	struct rt2661_node *rn;
   1705 	struct ieee80211_rateset *rs;
   1706 	struct ieee80211_frame *wh;
   1707 	struct ieee80211_key *k;
   1708 	struct mbuf *mnew;
   1709 	uint16_t dur;
   1710 	uint32_t flags = 0;
   1711 	int rate, error;
   1712 
   1713 	wh = mtod(m0, struct ieee80211_frame *);
   1714 
   1715 	if (ic->ic_fixed_rate != IEEE80211_FIXED_RATE_NONE) {
   1716 		rs = &ic->ic_sup_rates[ic->ic_curmode];
   1717 		rate = rs->rs_rates[ic->ic_fixed_rate];
   1718 	} else {
   1719 		rs = &ni->ni_rates;
   1720 		rn = (struct rt2661_node *)ni;
   1721 		ni->ni_txrate = ieee80211_rssadapt_choose(&rn->rssadapt, rs,
   1722 		    wh, m0->m_pkthdr.len, -1, NULL, 0);
   1723 		rate = rs->rs_rates[ni->ni_txrate];
   1724 	}
   1725 	rate &= IEEE80211_RATE_VAL;
   1726 
   1727 	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
   1728 		k = ieee80211_crypto_encap(ic, ni, m0);
   1729 		if (k == NULL) {
   1730 			m_freem(m0);
   1731 			return ENOBUFS;
   1732 		}
   1733 
   1734 		/* packet header may have moved, reset our local pointer */
   1735 		wh = mtod(m0, struct ieee80211_frame *);
   1736 	}
   1737 
   1738 	/*
   1739 	 * IEEE Std 802.11-1999, pp 82: "A STA shall use an RTS/CTS exchange
   1740 	 * for directed frames only when the length of the MPDU is greater
   1741 	 * than the length threshold indicated by [...]" ic_rtsthreshold.
   1742 	 */
   1743 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
   1744 	    m0->m_pkthdr.len + IEEE80211_CRC_LEN > ic->ic_rtsthreshold) {
   1745 		struct mbuf *m;
   1746 		int rtsrate, ackrate;
   1747 
   1748 		rtsrate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
   1749 		ackrate = rt2661_ack_rate(ic, rate);
   1750 
   1751 		dur = rt2661_txtime(m0->m_pkthdr.len + 4, rate, ic->ic_flags) +
   1752 		      rt2661_txtime(RAL_CTS_SIZE, rtsrate, ic->ic_flags) +
   1753 		      rt2661_txtime(RAL_ACK_SIZE, ackrate, ic->ic_flags) +
   1754 		      3 * RAL_SIFS;
   1755 
   1756 		m = rt2661_get_rts(sc, wh, dur);
   1757 
   1758 		desc = &txq->desc[txq->cur];
   1759 		data = &txq->data[txq->cur];
   1760 
   1761 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m,
   1762 		    BUS_DMA_NOWAIT);
   1763 		if (error != 0) {
   1764 			printf("%s: could not map mbuf (error %d)\n",
   1765 			    sc->sc_dev.dv_xname, error);
   1766 			m_freem(m);
   1767 			m_freem(m0);
   1768 			return error;
   1769 		}
   1770 
   1771 		/* avoid multiple free() of the same node for each fragment */
   1772 		ieee80211_ref_node(ni);
   1773 
   1774 		data->m = m;
   1775 		data->ni = ni;
   1776 
   1777 		/* RTS frames are not taken into account for rssadapt */
   1778 		data->id.id_node = NULL;
   1779 
   1780 		rt2661_setup_tx_desc(sc, desc, RT2661_TX_NEED_ACK |
   1781 		    RT2661_TX_MORE_FRAG, 0, m->m_pkthdr.len, rtsrate,
   1782 		    data->map->dm_segs, data->map->dm_nsegs, ac);
   1783 
   1784 		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
   1785 		    data->map->dm_mapsize, BUS_DMASYNC_PREWRITE);
   1786 		bus_dmamap_sync(sc->sc_dmat, txq->map,
   1787 		    txq->cur * RT2661_TX_DESC_SIZE, RT2661_TX_DESC_SIZE,
   1788 		    BUS_DMASYNC_PREWRITE);
   1789 
   1790 		txq->queued++;
   1791 		txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
   1792 
   1793 		/*
   1794 		 * IEEE Std 802.11-1999: when an RTS/CTS exchange is used, the
   1795 		 * asynchronous data frame shall be transmitted after the CTS
   1796 		 * frame and a SIFS period.
   1797 		 */
   1798 		flags |= RT2661_TX_LONG_RETRY | RT2661_TX_IFS;
   1799 	}
   1800 
   1801 	data = &txq->data[txq->cur];
   1802 	desc = &txq->desc[txq->cur];
   1803 
   1804 	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
   1805 	    BUS_DMA_NOWAIT);
   1806 	if (error != 0 && error != EFBIG) {
   1807 		printf("%s: could not map mbuf (error %d)\n",
   1808 		    sc->sc_dev.dv_xname, error);
   1809 		m_freem(m0);
   1810 		return error;
   1811 	}
   1812 	if (error != 0) {
   1813 		/* too many fragments, linearize */
   1814 
   1815 		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
   1816 		if (mnew == NULL) {
   1817 			m_freem(m0);
   1818 			return ENOMEM;
   1819 		}
   1820 
   1821 		M_COPY_PKTHDR(mnew, m0);
   1822 		if (m0->m_pkthdr.len > MHLEN) {
   1823 			MCLGET(mnew, M_DONTWAIT);
   1824 			if (!(mnew->m_flags & M_EXT)) {
   1825 				m_freem(m0);
   1826 				m_freem(mnew);
   1827 				return ENOMEM;
   1828 			}
   1829 		}
   1830 
   1831 		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(mnew, caddr_t));
   1832 		m_freem(m0);
   1833 		mnew->m_len = mnew->m_pkthdr.len;
   1834 		m0 = mnew;
   1835 
   1836 		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
   1837 		    BUS_DMA_NOWAIT);
   1838 		if (error != 0) {
   1839 			printf("%s: could not map mbuf (error %d)\n",
   1840 			    sc->sc_dev.dv_xname, error);
   1841 			m_freem(m0);
   1842 			return error;
   1843 		}
   1844 
   1845 		/* packet header have moved, reset our local pointer */
   1846 		wh = mtod(m0, struct ieee80211_frame *);
   1847 	}
   1848 
   1849 #if NBPFILTER > 0
   1850 	if (sc->sc_drvbpf != NULL) {
   1851 		struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
   1852 
   1853 		tap->wt_flags = 0;
   1854 		tap->wt_rate = rate;
   1855 		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
   1856 		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
   1857 
   1858 		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
   1859 	}
   1860 #endif
   1861 
   1862 	data->m = m0;
   1863 	data->ni = ni;
   1864 
   1865 	/* remember link conditions for rate control algorithm */
   1866 	if (ic->ic_fixed_rate == IEEE80211_FIXED_RATE_NONE) {
   1867 		data->id.id_len = m0->m_pkthdr.len;
   1868 		data->id.id_rateidx = ni->ni_txrate;
   1869 		data->id.id_node = ni;
   1870 		data->id.id_rssi = ni->ni_rssi;
   1871 	} else
   1872 		data->id.id_node = NULL;
   1873 
   1874 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
   1875 		flags |= RT2661_TX_NEED_ACK;
   1876 
   1877 		dur = rt2661_txtime(RAL_ACK_SIZE, rt2661_ack_rate(ic, rate),
   1878 		    ic->ic_flags) + RAL_SIFS;
   1879 		*(uint16_t *)wh->i_dur = htole16(dur);
   1880 	}
   1881 
   1882 	rt2661_setup_tx_desc(sc, desc, flags, 0, m0->m_pkthdr.len, rate,
   1883 	    data->map->dm_segs, data->map->dm_nsegs, ac);
   1884 
   1885 	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
   1886 	    BUS_DMASYNC_PREWRITE);
   1887 	bus_dmamap_sync(sc->sc_dmat, txq->map, txq->cur * RT2661_TX_DESC_SIZE,
   1888 	    RT2661_TX_DESC_SIZE, BUS_DMASYNC_PREWRITE);
   1889 
   1890 	DPRINTFN(10, ("sending data frame len=%u idx=%u rate=%u\n",
   1891 	    m0->m_pkthdr.len, txq->cur, rate));
   1892 
   1893 	/* kick Tx */
   1894 	txq->queued++;
   1895 	txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
   1896 	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 1);
   1897 
   1898 	return 0;
   1899 }
   1900 
   1901 static void
   1902 rt2661_start(struct ifnet *ifp)
   1903 {
   1904 	struct rt2661_softc *sc = ifp->if_softc;
   1905 	struct ieee80211com *ic = &sc->sc_ic;
   1906 	struct mbuf *m0;
   1907 	struct ether_header *eh;
   1908 	struct ieee80211_node *ni = NULL;
   1909 	int ac;
   1910 
   1911 	/*
   1912 	 * net80211 may still try to send management frames even if the
   1913 	 * IFF_RUNNING flag is not set...
   1914 	 */
   1915 	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
   1916 		return;
   1917 
   1918 	for (;;) {
   1919 		IF_POLL(&ic->ic_mgtq, m0);
   1920 		if (m0 != NULL) {
   1921 			if (sc->mgtq.queued >= RT2661_MGT_RING_COUNT) {
   1922 				ifp->if_flags |= IFF_OACTIVE;
   1923 				break;
   1924 			}
   1925 			IF_DEQUEUE(&ic->ic_mgtq, m0);
   1926 
   1927 			ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
   1928 			m0->m_pkthdr.rcvif = NULL;
   1929 #if NBPFILTER > 0
   1930 			if (ic->ic_rawbpf != NULL)
   1931 				bpf_mtap(ic->ic_rawbpf, m0);
   1932 #endif
   1933 			if (rt2661_tx_mgt(sc, m0, ni) != 0)
   1934 				break;
   1935 
   1936 		} else {
   1937 			if (ic->ic_state != IEEE80211_S_RUN)
   1938 				break;
   1939 			IFQ_DEQUEUE(&ifp->if_snd, m0);
   1940 			if (m0 == NULL)
   1941 				break;
   1942 
   1943 			if (m0->m_len < sizeof (struct ether_header) &&
   1944 			    !(m0 = m_pullup(m0, sizeof (struct ether_header))))
   1945 				continue;
   1946 
   1947 			eh = mtod(m0, struct ether_header *);
   1948 			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
   1949 			if (ni == NULL) {
   1950 				m_freem(m0);
   1951 				ifp->if_oerrors++;
   1952 				continue;
   1953 			}
   1954 
   1955 
   1956 			/* classify mbuf so we can find which tx ring to use */
   1957 			if (ieee80211_classify(ic, m0, ni) != 0) {
   1958 				m_freem(m0);
   1959 				ieee80211_free_node(ni);
   1960 				ifp->if_oerrors++;
   1961 				continue;
   1962 			}
   1963 
   1964 			/* no QoS encapsulation for EAPOL frames */
   1965 			ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
   1966 			    M_WME_GETAC(m0) : WME_AC_BE;
   1967 
   1968 			if (sc->txq[0].queued >= RT2661_TX_RING_COUNT - 1) {
   1969 				/* there is no place left in this ring */
   1970 				IF_PREPEND(&ifp->if_snd, m0);
   1971 				ifp->if_flags |= IFF_OACTIVE;
   1972 				break;
   1973 			}
   1974 #if NBPFILTER > 0
   1975 			if (ifp->if_bpf != NULL)
   1976 				bpf_mtap(ifp->if_bpf, m0);
   1977 #endif
   1978 			m0 = ieee80211_encap(ic, m0, ni);
   1979 			if (m0 == NULL) {
   1980 				ieee80211_free_node(ni);
   1981 				ifp->if_oerrors++;
   1982 				continue;
   1983 			}
   1984 #if NBPFILTER > 0
   1985 			if (ic->ic_rawbpf != NULL)
   1986 				bpf_mtap(ic->ic_rawbpf, m0);
   1987 #endif
   1988 			if (rt2661_tx_data(sc, m0, ni, 0) != 0) {
   1989 				if (ni != NULL)
   1990 					ieee80211_free_node(ni);
   1991 				ifp->if_oerrors++;
   1992 				break;
   1993 			}
   1994 		}
   1995 
   1996 		sc->sc_tx_timer = 5;
   1997 		ifp->if_timer = 1;
   1998 	}
   1999 }
   2000 
   2001 static void
   2002 rt2661_watchdog(struct ifnet *ifp)
   2003 {
   2004 	struct rt2661_softc *sc = ifp->if_softc;
   2005 
   2006 	ifp->if_timer = 0;
   2007 
   2008 	if (sc->sc_tx_timer > 0) {
   2009 		if (--sc->sc_tx_timer == 0) {
   2010 			printf("%s: device timeout\n", sc->sc_dev.dv_xname);
   2011 			rt2661_init(ifp);
   2012 			ifp->if_oerrors++;
   2013 			return;
   2014 		}
   2015 		ifp->if_timer = 1;
   2016 	}
   2017 
   2018 	ieee80211_watchdog(&sc->sc_ic);
   2019 }
   2020 
   2021 /*
   2022  * This function allows for fast channel switching in monitor mode (used by
   2023  * kismet). In IBSS mode, we must explicitly reset the interface to
   2024  * generate a new beacon frame.
   2025  */
   2026 static int
   2027 rt2661_reset(struct ifnet *ifp)
   2028 {
   2029 	struct rt2661_softc *sc = ifp->if_softc;
   2030 	struct ieee80211com *ic = &sc->sc_ic;
   2031 
   2032 	if (ic->ic_opmode != IEEE80211_M_MONITOR)
   2033 		return ENETRESET;
   2034 
   2035 	rt2661_set_chan(sc, ic->ic_curchan);
   2036 
   2037 	return 0;
   2038 }
   2039 
   2040 static int
   2041 rt2661_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
   2042 {
   2043 	struct rt2661_softc *sc = ifp->if_softc;
   2044 	struct ieee80211com *ic = &sc->sc_ic;
   2045 	struct ifreq *ifr;
   2046 	int s, error = 0;
   2047 
   2048 	s = splnet();
   2049 
   2050 	switch (cmd) {
   2051 	case SIOCSIFFLAGS:
   2052 		if (ifp->if_flags & IFF_UP) {
   2053 			if (ifp->if_flags & IFF_RUNNING)
   2054 				rt2661_update_promisc(sc);
   2055 			else
   2056 				rt2661_init(ifp);
   2057 		} else {
   2058 			if (ifp->if_flags & IFF_RUNNING)
   2059 				rt2661_stop(ifp, 1);
   2060 		}
   2061 		break;
   2062 
   2063 	case SIOCADDMULTI:
   2064 	case SIOCDELMULTI:
   2065 		ifr = (struct ifreq *)data;
   2066 		error = (cmd == SIOCADDMULTI) ?
   2067 		    ether_addmulti(ifr, &sc->sc_ec) :
   2068 		    ether_delmulti(ifr, &sc->sc_ec);
   2069 
   2070 
   2071 		if (error == ENETRESET)
   2072 			error = 0;
   2073 		break;
   2074 
   2075 	case SIOCS80211CHANNEL:
   2076 		/*
   2077 		 * This allows for fast channel switching in monitor mode
   2078 		 * (used by kismet). In IBSS mode, we must explicitly reset
   2079 		 * the interface to generate a new beacon frame.
   2080 		 */
   2081 		error = ieee80211_ioctl(ic, cmd, data);
   2082 		if (error == ENETRESET &&
   2083 		    ic->ic_opmode == IEEE80211_M_MONITOR) {
   2084 			rt2661_set_chan(sc, ic->ic_ibss_chan);
   2085 			error = 0;
   2086 		}
   2087 		break;
   2088 
   2089 	default:
   2090 		error = ieee80211_ioctl(ic, cmd, data);
   2091 
   2092 	}
   2093 
   2094 	if (error == ENETRESET) {
   2095 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
   2096 		    (IFF_UP | IFF_RUNNING))
   2097 			rt2661_init(ifp);
   2098 		error = 0;
   2099 	}
   2100 
   2101 	splx(s);
   2102 
   2103 	return error;
   2104 }
   2105 
   2106 static void
   2107 rt2661_bbp_write(struct rt2661_softc *sc, uint8_t reg, uint8_t val)
   2108 {
   2109 	uint32_t tmp;
   2110 	int ntries;
   2111 
   2112 	for (ntries = 0; ntries < 100; ntries++) {
   2113 		if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
   2114 			break;
   2115 		DELAY(1);
   2116 	}
   2117 	if (ntries == 100) {
   2118 		printf("%s: could not write to BBP\n", sc->sc_dev.dv_xname);
   2119 		return;
   2120 	}
   2121 
   2122 	tmp = RT2661_BBP_BUSY | (reg & 0x7f) << 8 | val;
   2123 	RAL_WRITE(sc, RT2661_PHY_CSR3, tmp);
   2124 
   2125 	DPRINTFN(15, ("BBP R%u <- 0x%02x\n", reg, val));
   2126 }
   2127 
   2128 static uint8_t
   2129 rt2661_bbp_read(struct rt2661_softc *sc, uint8_t reg)
   2130 {
   2131 	uint32_t val;
   2132 	int ntries;
   2133 
   2134 	for (ntries = 0; ntries < 100; ntries++) {
   2135 		if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
   2136 			break;
   2137 		DELAY(1);
   2138 	}
   2139 	if (ntries == 100) {
   2140 		printf("%s: could not read from BBP\n", sc->sc_dev.dv_xname);
   2141 		return 0;
   2142 	}
   2143 
   2144 	val = RT2661_BBP_BUSY | RT2661_BBP_READ | reg << 8;
   2145 	RAL_WRITE(sc, RT2661_PHY_CSR3, val);
   2146 
   2147 	for (ntries = 0; ntries < 100; ntries++) {
   2148 		val = RAL_READ(sc, RT2661_PHY_CSR3);
   2149 		if (!(val & RT2661_BBP_BUSY))
   2150 			return val & 0xff;
   2151 		DELAY(1);
   2152 	}
   2153 
   2154 	printf("%s: could not read from BBP\n", sc->sc_dev.dv_xname);
   2155 	return 0;
   2156 }
   2157 
   2158 static void
   2159 rt2661_rf_write(struct rt2661_softc *sc, uint8_t reg, uint32_t val)
   2160 {
   2161 	uint32_t tmp;
   2162 	int ntries;
   2163 
   2164 	for (ntries = 0; ntries < 100; ntries++) {
   2165 		if (!(RAL_READ(sc, RT2661_PHY_CSR4) & RT2661_RF_BUSY))
   2166 			break;
   2167 		DELAY(1);
   2168 	}
   2169 	if (ntries == 100) {
   2170 		printf("%s: could not write to RF\n", sc->sc_dev.dv_xname);
   2171 		return;
   2172 	}
   2173 
   2174 	tmp = RT2661_RF_BUSY | RT2661_RF_21BIT | (val & 0x1fffff) << 2 |
   2175 	    (reg & 3);
   2176 	RAL_WRITE(sc, RT2661_PHY_CSR4, tmp);
   2177 
   2178 	/* remember last written value in sc */
   2179 	sc->rf_regs[reg] = val;
   2180 
   2181 	DPRINTFN(15, ("RF R[%u] <- 0x%05x\n", reg & 3, val & 0x1fffff));
   2182 }
   2183 
   2184 static int
   2185 rt2661_tx_cmd(struct rt2661_softc *sc, uint8_t cmd, uint16_t arg)
   2186 {
   2187 	if (RAL_READ(sc, RT2661_H2M_MAILBOX_CSR) & RT2661_H2M_BUSY)
   2188 		return EIO;	/* there is already a command pending */
   2189 
   2190 	RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR,
   2191 	    RT2661_H2M_BUSY | RT2661_TOKEN_NO_INTR << 16 | arg);
   2192 
   2193 	RAL_WRITE(sc, RT2661_HOST_CMD_CSR, RT2661_KICK_CMD | cmd);
   2194 
   2195 	return 0;
   2196 }
   2197 
   2198 static void
   2199 rt2661_select_antenna(struct rt2661_softc *sc)
   2200 {
   2201 	uint8_t bbp4, bbp77;
   2202 	uint32_t tmp;
   2203 
   2204 	bbp4  = rt2661_bbp_read(sc,  4);
   2205 	bbp77 = rt2661_bbp_read(sc, 77);
   2206 
   2207 	/* TBD */
   2208 
   2209 	/* make sure Rx is disabled before switching antenna */
   2210 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
   2211 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
   2212 
   2213 	rt2661_bbp_write(sc,  4, bbp4);
   2214 	rt2661_bbp_write(sc, 77, bbp77);
   2215 
   2216 	/* restore Rx filter */
   2217 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
   2218 }
   2219 
   2220 /*
   2221  * Enable multi-rate retries for frames sent at OFDM rates.
   2222  * In 802.11b/g mode, allow fallback to CCK rates.
   2223  */
   2224 static void
   2225 rt2661_enable_mrr(struct rt2661_softc *sc)
   2226 {
   2227 	struct ieee80211com *ic = &sc->sc_ic;
   2228 	uint32_t tmp;
   2229 
   2230 	tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
   2231 
   2232 	tmp &= ~RT2661_MRR_CCK_FALLBACK;
   2233 	if (!IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan))
   2234 		tmp |= RT2661_MRR_CCK_FALLBACK;
   2235 	tmp |= RT2661_MRR_ENABLED;
   2236 
   2237 	RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
   2238 }
   2239 
   2240 static void
   2241 rt2661_set_txpreamble(struct rt2661_softc *sc)
   2242 {
   2243 	uint32_t tmp;
   2244 
   2245 	tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
   2246 
   2247 	tmp &= ~RT2661_SHORT_PREAMBLE;
   2248 	if (sc->sc_ic.ic_flags & IEEE80211_F_SHPREAMBLE)
   2249 		tmp |= RT2661_SHORT_PREAMBLE;
   2250 
   2251 	RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
   2252 }
   2253 
   2254 static void
   2255 rt2661_set_basicrates(struct rt2661_softc *sc,
   2256     const struct ieee80211_rateset *rs)
   2257 {
   2258 #define RV(r)	((r) & IEEE80211_RATE_VAL)
   2259 	uint32_t mask = 0;
   2260 	uint8_t rate;
   2261 	int i, j;
   2262 
   2263 	for (i = 0; i < rs->rs_nrates; i++) {
   2264 		rate = rs->rs_rates[i];
   2265 
   2266 		if (!(rate & IEEE80211_RATE_BASIC))
   2267 			continue;
   2268 
   2269 		/*
   2270 		 * Find h/w rate index.  We know it exists because the rate
   2271 		 * set has already been negotiated.
   2272 		 */
   2273 		for (j = 0; rt2661_rateset_11g.rs_rates[j] != RV(rate); j++);
   2274 
   2275 		mask |= 1 << j;
   2276 	}
   2277 
   2278 	RAL_WRITE(sc, RT2661_TXRX_CSR5, mask);
   2279 
   2280 	DPRINTF(("Setting basic rate mask to 0x%x\n", mask));
   2281 #undef RV
   2282 }
   2283 
   2284 /*
   2285  * Reprogram MAC/BBP to switch to a new band.  Values taken from the reference
   2286  * driver.
   2287  */
   2288 static void
   2289 rt2661_select_band(struct rt2661_softc *sc, struct ieee80211_channel *c)
   2290 {
   2291 	uint8_t bbp17, bbp35, bbp96, bbp97, bbp98, bbp104;
   2292 	uint32_t tmp;
   2293 
   2294 	/* update all BBP registers that depend on the band */
   2295 	bbp17 = 0x20; bbp96 = 0x48; bbp104 = 0x2c;
   2296 	bbp35 = 0x50; bbp97 = 0x48; bbp98  = 0x48;
   2297 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
   2298 		bbp17 += 0x08; bbp96 += 0x10; bbp104 += 0x0c;
   2299 		bbp35 += 0x10; bbp97 += 0x10; bbp98  += 0x10;
   2300 	}
   2301 	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
   2302 	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
   2303 		bbp17 += 0x10; bbp96 += 0x10; bbp104 += 0x10;
   2304 	}
   2305 
   2306 	sc->bbp17 = bbp17;
   2307 	rt2661_bbp_write(sc,  17, bbp17);
   2308 	rt2661_bbp_write(sc,  96, bbp96);
   2309 	rt2661_bbp_write(sc, 104, bbp104);
   2310 
   2311 	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
   2312 	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
   2313 		rt2661_bbp_write(sc, 75, 0x80);
   2314 		rt2661_bbp_write(sc, 86, 0x80);
   2315 		rt2661_bbp_write(sc, 88, 0x80);
   2316 	}
   2317 
   2318 	rt2661_bbp_write(sc, 35, bbp35);
   2319 	rt2661_bbp_write(sc, 97, bbp97);
   2320 	rt2661_bbp_write(sc, 98, bbp98);
   2321 
   2322 	tmp = RAL_READ(sc, RT2661_PHY_CSR0);
   2323 	tmp &= ~(RT2661_PA_PE_2GHZ | RT2661_PA_PE_5GHZ);
   2324 	if (IEEE80211_IS_CHAN_2GHZ(c))
   2325 		tmp |= RT2661_PA_PE_2GHZ;
   2326 	else
   2327 		tmp |= RT2661_PA_PE_5GHZ;
   2328 	RAL_WRITE(sc, RT2661_PHY_CSR0, tmp);
   2329 }
   2330 
   2331 static void
   2332 rt2661_set_chan(struct rt2661_softc *sc, struct ieee80211_channel *c)
   2333 {
   2334 	struct ieee80211com *ic = &sc->sc_ic;
   2335 	const struct rfprog *rfprog;
   2336 	uint8_t bbp3, bbp94 = RT2661_BBPR94_DEFAULT;
   2337 	int8_t power;
   2338 	u_int i, chan;
   2339 
   2340 	chan = ieee80211_chan2ieee(ic, c);
   2341 	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
   2342 		return;
   2343 
   2344 	/* select the appropriate RF settings based on what EEPROM says */
   2345 	rfprog = (sc->rfprog == 0) ? rt2661_rf5225_1 : rt2661_rf5225_2;
   2346 
   2347 	/* find the settings for this channel (we know it exists) */
   2348 	for (i = 0; rfprog[i].chan != chan; i++);
   2349 
   2350 	power = sc->txpow[i];
   2351 	if (power < 0) {
   2352 		bbp94 += power;
   2353 		power = 0;
   2354 	} else if (power > 31) {
   2355 		bbp94 += power - 31;
   2356 		power = 31;
   2357 	}
   2358 
   2359 	/*
   2360 	 * If we are switching from the 2GHz band to the 5GHz band or
   2361 	 * vice-versa, BBP registers need to be reprogrammed.
   2362 	 */
   2363 	if (c->ic_flags != sc->sc_curchan->ic_flags) {
   2364 		rt2661_select_band(sc, c);
   2365 		rt2661_select_antenna(sc);
   2366 	}
   2367 	sc->sc_curchan = c;
   2368 
   2369 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
   2370 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
   2371 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
   2372 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
   2373 
   2374 	DELAY(200);
   2375 
   2376 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
   2377 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
   2378 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7 | 1);
   2379 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
   2380 
   2381 	DELAY(200);
   2382 
   2383 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
   2384 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
   2385 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
   2386 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
   2387 
   2388 	/* enable smart mode for MIMO-capable RFs */
   2389 	bbp3 = rt2661_bbp_read(sc, 3);
   2390 
   2391 	bbp3 &= ~RT2661_SMART_MODE;
   2392 	if (sc->rf_rev == RT2661_RF_5325 || sc->rf_rev == RT2661_RF_2529)
   2393 		bbp3 |= RT2661_SMART_MODE;
   2394 
   2395 	rt2661_bbp_write(sc, 3, bbp3);
   2396 
   2397 	if (bbp94 != RT2661_BBPR94_DEFAULT)
   2398 		rt2661_bbp_write(sc, 94, bbp94);
   2399 
   2400 	/* 5GHz radio needs a 1ms delay here */
   2401 	if (IEEE80211_IS_CHAN_5GHZ(c))
   2402 		DELAY(1000);
   2403 }
   2404 
   2405 static void
   2406 rt2661_set_bssid(struct rt2661_softc *sc, const uint8_t *bssid)
   2407 {
   2408 	uint32_t tmp;
   2409 
   2410 	tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24;
   2411 	RAL_WRITE(sc, RT2661_MAC_CSR4, tmp);
   2412 
   2413 	tmp = bssid[4] | bssid[5] << 8 | RT2661_ONE_BSSID << 16;
   2414 	RAL_WRITE(sc, RT2661_MAC_CSR5, tmp);
   2415 }
   2416 
   2417 static void
   2418 rt2661_set_macaddr(struct rt2661_softc *sc, const uint8_t *addr)
   2419 {
   2420 	uint32_t tmp;
   2421 
   2422 	tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24;
   2423 	RAL_WRITE(sc, RT2661_MAC_CSR2, tmp);
   2424 
   2425 	tmp = addr[4] | addr[5] << 8;
   2426 	RAL_WRITE(sc, RT2661_MAC_CSR3, tmp);
   2427 }
   2428 
   2429 static void
   2430 rt2661_update_promisc(struct rt2661_softc *sc)
   2431 {
   2432 	struct ifnet *ifp = sc->sc_ic.ic_ifp;
   2433 	uint32_t tmp;
   2434 
   2435 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
   2436 
   2437 	tmp &= ~RT2661_DROP_NOT_TO_ME;
   2438 	if (!(ifp->if_flags & IFF_PROMISC))
   2439 		tmp |= RT2661_DROP_NOT_TO_ME;
   2440 
   2441 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
   2442 
   2443 	DPRINTF(("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
   2444 	    "entering" : "leaving"));
   2445 }
   2446 
   2447 /*
   2448  * Update QoS (802.11e) settings for each h/w Tx ring.
   2449  */
   2450 static int
   2451 rt2661_wme_update(struct ieee80211com *ic)
   2452 {
   2453 	struct rt2661_softc *sc = ic->ic_ifp->if_softc;
   2454 	const struct wmeParams *wmep;
   2455 
   2456 	wmep = ic->ic_wme.wme_chanParams.cap_wmeParams;
   2457 
   2458 	/* XXX: not sure about shifts. */
   2459 	/* XXX: the reference driver plays with AC_VI settings too. */
   2460 
   2461 	/* update TxOp */
   2462 	RAL_WRITE(sc, RT2661_AC_TXOP_CSR0,
   2463 	    wmep[WME_AC_BE].wmep_txopLimit << 16 |
   2464 	    wmep[WME_AC_BK].wmep_txopLimit);
   2465 	RAL_WRITE(sc, RT2661_AC_TXOP_CSR1,
   2466 	    wmep[WME_AC_VI].wmep_txopLimit << 16 |
   2467 	    wmep[WME_AC_VO].wmep_txopLimit);
   2468 
   2469 	/* update CWmin */
   2470 	RAL_WRITE(sc, RT2661_CWMIN_CSR,
   2471 	    wmep[WME_AC_BE].wmep_logcwmin << 12 |
   2472 	    wmep[WME_AC_BK].wmep_logcwmin <<  8 |
   2473 	    wmep[WME_AC_VI].wmep_logcwmin <<  4 |
   2474 	    wmep[WME_AC_VO].wmep_logcwmin);
   2475 
   2476 	/* update CWmax */
   2477 	RAL_WRITE(sc, RT2661_CWMAX_CSR,
   2478 	    wmep[WME_AC_BE].wmep_logcwmax << 12 |
   2479 	    wmep[WME_AC_BK].wmep_logcwmax <<  8 |
   2480 	    wmep[WME_AC_VI].wmep_logcwmax <<  4 |
   2481 	    wmep[WME_AC_VO].wmep_logcwmax);
   2482 
   2483 	/* update Aifsn */
   2484 	RAL_WRITE(sc, RT2661_AIFSN_CSR,
   2485 	    wmep[WME_AC_BE].wmep_aifsn << 12 |
   2486 	    wmep[WME_AC_BK].wmep_aifsn <<  8 |
   2487 	    wmep[WME_AC_VI].wmep_aifsn <<  4 |
   2488 	    wmep[WME_AC_VO].wmep_aifsn);
   2489 
   2490 	return 0;
   2491 }
   2492 
   2493 static void
   2494 rt2661_update_slot(struct ifnet *ifp)
   2495 {
   2496 	struct rt2661_softc *sc = ifp->if_softc;
   2497 	struct ieee80211com *ic = &sc->sc_ic;
   2498 	uint8_t slottime;
   2499 	uint32_t tmp;
   2500 
   2501 	slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
   2502 
   2503 	tmp = RAL_READ(sc, RT2661_MAC_CSR9);
   2504 	tmp = (tmp & ~0xff) | slottime;
   2505 	RAL_WRITE(sc, RT2661_MAC_CSR9, tmp);
   2506 }
   2507 
   2508 static const char *
   2509 rt2661_get_rf(int rev)
   2510 {
   2511 	switch (rev) {
   2512 	case RT2661_RF_5225:	return "RT5225";
   2513 	case RT2661_RF_5325:	return "RT5325 (MIMO XR)";
   2514 	case RT2661_RF_2527:	return "RT2527";
   2515 	case RT2661_RF_2529:	return "RT2529 (MIMO XR)";
   2516 	default:		return "unknown";
   2517 	}
   2518 }
   2519 
   2520 static void
   2521 rt2661_read_eeprom(struct rt2661_softc *sc)
   2522 {
   2523 	struct ieee80211com *ic = &sc->sc_ic;
   2524 	uint16_t val;
   2525 	int i;
   2526 
   2527 	/* read MAC address */
   2528 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC01);
   2529 	ic->ic_myaddr[0] = val & 0xff;
   2530 	ic->ic_myaddr[1] = val >> 8;
   2531 
   2532 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC23);
   2533 	ic->ic_myaddr[2] = val & 0xff;
   2534 	ic->ic_myaddr[3] = val >> 8;
   2535 
   2536 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC45);
   2537 	ic->ic_myaddr[4] = val & 0xff;
   2538 	ic->ic_myaddr[5] = val >> 8;
   2539 
   2540 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_ANTENNA);
   2541 	/* XXX: test if different from 0xffff? */
   2542 	sc->rf_rev   = (val >> 11) & 0x1f;
   2543 	sc->hw_radio = (val >> 10) & 0x1;
   2544 	sc->rx_ant   = (val >> 4)  & 0x3;
   2545 	sc->tx_ant   = (val >> 2)  & 0x3;
   2546 	sc->nb_ant   = val & 0x3;
   2547 
   2548 	DPRINTF(("RF revision=%d\n", sc->rf_rev));
   2549 
   2550 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_CONFIG2);
   2551 	sc->ext_5ghz_lna = (val >> 6) & 0x1;
   2552 	sc->ext_2ghz_lna = (val >> 4) & 0x1;
   2553 
   2554 	DPRINTF(("External 2GHz LNA=%d\nExternal 5GHz LNA=%d\n",
   2555 	    sc->ext_2ghz_lna, sc->ext_5ghz_lna));
   2556 
   2557 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_2GHZ_OFFSET);
   2558 	if ((val & 0xff) != 0xff)
   2559 		sc->rssi_2ghz_corr = (int8_t)(val & 0xff);	/* signed */
   2560 
   2561 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_5GHZ_OFFSET);
   2562 	if ((val & 0xff) != 0xff)
   2563 		sc->rssi_5ghz_corr = (int8_t)(val & 0xff);	/* signed */
   2564 
   2565 	/* adjust RSSI correction for external low-noise amplifier */
   2566 	if (sc->ext_2ghz_lna)
   2567 		sc->rssi_2ghz_corr -= 14;
   2568 	if (sc->ext_5ghz_lna)
   2569 		sc->rssi_5ghz_corr -= 14;
   2570 
   2571 	DPRINTF(("RSSI 2GHz corr=%d\nRSSI 5GHz corr=%d\n",
   2572 	    sc->rssi_2ghz_corr, sc->rssi_5ghz_corr));
   2573 
   2574 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_FREQ_OFFSET);
   2575 	if ((val >> 8) != 0xff)
   2576 		sc->rfprog = (val >> 8) & 0x3;
   2577 	if ((val & 0xff) != 0xff)
   2578 		sc->rffreq = val & 0xff;
   2579 
   2580 	DPRINTF(("RF prog=%d\nRF freq=%d\n", sc->rfprog, sc->rffreq));
   2581 
   2582 	/* read Tx power for all a/b/g channels */
   2583 	for (i = 0; i < 19; i++) {
   2584 		val = rt2661_eeprom_read(sc, RT2661_EEPROM_TXPOWER + i);
   2585 		sc->txpow[i * 2] = (int8_t)(val >> 8);		/* signed */
   2586 		DPRINTF(("Channel=%d Tx power=%d\n",
   2587 		    rt2661_rf5225_1[i * 2].chan, sc->txpow[i * 2]));
   2588 		sc->txpow[i * 2 + 1] = (int8_t)(val & 0xff);	/* signed */
   2589 		DPRINTF(("Channel=%d Tx power=%d\n",
   2590 		    rt2661_rf5225_1[i * 2 + 1].chan, sc->txpow[i * 2 + 1]));
   2591 	}
   2592 
   2593 	/* read vendor-specific BBP values */
   2594 	for (i = 0; i < 16; i++) {
   2595 		val = rt2661_eeprom_read(sc, RT2661_EEPROM_BBP_BASE + i);
   2596 		if (val == 0 || val == 0xffff)
   2597 			continue;	/* skip invalid entries */
   2598 		sc->bbp_prom[i].reg = val >> 8;
   2599 		sc->bbp_prom[i].val = val & 0xff;
   2600 		DPRINTF(("BBP R%d=%02x\n", sc->bbp_prom[i].reg,
   2601 		    sc->bbp_prom[i].val));
   2602 	}
   2603 }
   2604 
   2605 static int
   2606 rt2661_bbp_init(struct rt2661_softc *sc)
   2607 {
   2608 #define N(a)	(sizeof (a) / sizeof ((a)[0]))
   2609 	int i, ntries;
   2610 	uint8_t val;
   2611 
   2612 	/* wait for BBP to be ready */
   2613 	for (ntries = 0; ntries < 100; ntries++) {
   2614 		val = rt2661_bbp_read(sc, 0);
   2615 		if (val != 0 && val != 0xff)
   2616 			break;
   2617 		DELAY(100);
   2618 	}
   2619 	if (ntries == 100) {
   2620 		printf("%s: timeout waiting for BBP\n", sc->sc_dev.dv_xname);
   2621 		return EIO;
   2622 	}
   2623 
   2624 	/* initialize BBP registers to default values */
   2625 	for (i = 0; i < N(rt2661_def_bbp); i++) {
   2626 		rt2661_bbp_write(sc, rt2661_def_bbp[i].reg,
   2627 		    rt2661_def_bbp[i].val);
   2628 	}
   2629 
   2630 	/* write vendor-specific BBP values (from EEPROM) */
   2631 	for (i = 0; i < 16; i++) {
   2632 		if (sc->bbp_prom[i].reg == 0)
   2633 			continue;
   2634 		rt2661_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
   2635 	}
   2636 
   2637 	return 0;
   2638 #undef N
   2639 }
   2640 
   2641 static int
   2642 rt2661_init(struct ifnet *ifp)
   2643 {
   2644 #define N(a)	(sizeof (a) / sizeof ((a)[0]))
   2645 	struct rt2661_softc *sc = ifp->if_softc;
   2646 	struct ieee80211com *ic = &sc->sc_ic;
   2647 	const char *name = NULL;	/* make lint happy */
   2648 	uint8_t *ucode;
   2649 	size_t size;
   2650 	uint32_t tmp, star[3];
   2651 	int i, ntries;
   2652 	firmware_handle_t fh;
   2653 
   2654 	/* for CardBus, power on the socket */
   2655 	if (!(sc->sc_flags & RT2661_ENABLED)) {
   2656 		if (sc->sc_enable != NULL && (*sc->sc_enable)(sc) != 0) {
   2657 			printf("%s: could not enable device\n",
   2658 			    sc->sc_dev.dv_xname);
   2659 			return EIO;
   2660 		}
   2661 		sc->sc_flags |= RT2661_ENABLED;
   2662 	}
   2663 
   2664 	rt2661_stop(ifp, 0);
   2665 
   2666 	if (!(sc->sc_flags & RT2661_FWLOADED)) {
   2667 		switch (sc->sc_id) {
   2668 		case PCI_PRODUCT_RALINK_RT2561:
   2669 			name = "ral-rt2561";
   2670 			break;
   2671 		case PCI_PRODUCT_RALINK_RT2561S:
   2672 			name = "ral-rt2561s";
   2673 			break;
   2674 		case PCI_PRODUCT_RALINK_RT2661:
   2675 			name = "ral-rt2661";
   2676 			break;
   2677 		}
   2678 
   2679 		if (firmware_open("ral", name, &fh) != 0) {
   2680 			printf("%s: could not open microcode %s\n",
   2681 			    sc->sc_dev.dv_xname, name);
   2682 			rt2661_stop(ifp, 1);
   2683 			return EIO;
   2684 		}
   2685 
   2686 		size = firmware_get_size(fh);
   2687 		if (!(ucode = firmware_malloc(size))) {
   2688 			printf("%s: could not alloc microcode memory\n",
   2689 			    sc->sc_dev.dv_xname);
   2690 			rt2661_stop(ifp, 1);
   2691 			return ENOMEM;
   2692 		}
   2693 
   2694 		if (firmware_read(fh, 0, ucode, size) != 0) {
   2695 			printf("%s: could not read microcode %s\n",
   2696 			    sc->sc_dev.dv_xname, name);
   2697 			firmware_free(ucode, 0);
   2698 			rt2661_stop(ifp, 1);
   2699 			return EIO;
   2700 		}
   2701 
   2702 		if (rt2661_load_microcode(sc, ucode, size) != 0) {
   2703 			printf("%s: could not load 8051 microcode\n",
   2704 			    sc->sc_dev.dv_xname);
   2705 			firmware_free(ucode, 0);
   2706 			rt2661_stop(ifp, 1);
   2707 			return EIO;
   2708 		}
   2709 
   2710 		firmware_free(ucode, 0);
   2711 		firmware_close(fh);
   2712 		sc->sc_flags |= RT2661_FWLOADED;
   2713 	}
   2714 
   2715 	/* initialize Tx rings */
   2716 	RAL_WRITE(sc, RT2661_AC1_BASE_CSR, sc->txq[1].physaddr);
   2717 	RAL_WRITE(sc, RT2661_AC0_BASE_CSR, sc->txq[0].physaddr);
   2718 	RAL_WRITE(sc, RT2661_AC2_BASE_CSR, sc->txq[2].physaddr);
   2719 	RAL_WRITE(sc, RT2661_AC3_BASE_CSR, sc->txq[3].physaddr);
   2720 
   2721 	/* initialize Mgt ring */
   2722 	RAL_WRITE(sc, RT2661_MGT_BASE_CSR, sc->mgtq.physaddr);
   2723 
   2724 	/* initialize Rx ring */
   2725 	RAL_WRITE(sc, RT2661_RX_BASE_CSR, sc->rxq.physaddr);
   2726 
   2727 	/* initialize Tx rings sizes */
   2728 	RAL_WRITE(sc, RT2661_TX_RING_CSR0,
   2729 	    RT2661_TX_RING_COUNT << 24 |
   2730 	    RT2661_TX_RING_COUNT << 16 |
   2731 	    RT2661_TX_RING_COUNT <<  8 |
   2732 	    RT2661_TX_RING_COUNT);
   2733 
   2734 	RAL_WRITE(sc, RT2661_TX_RING_CSR1,
   2735 	    RT2661_TX_DESC_WSIZE << 16 |
   2736 	    RT2661_TX_RING_COUNT <<  8 |	/* XXX: HCCA ring unused */
   2737 	    RT2661_MGT_RING_COUNT);
   2738 
   2739 	/* initialize Rx rings */
   2740 	RAL_WRITE(sc, RT2661_RX_RING_CSR,
   2741 	    RT2661_RX_DESC_BACK  << 16 |
   2742 	    RT2661_RX_DESC_WSIZE <<  8 |
   2743 	    RT2661_RX_RING_COUNT);
   2744 
   2745 	/* XXX: some magic here */
   2746 	RAL_WRITE(sc, RT2661_TX_DMA_DST_CSR, 0xaa);
   2747 
   2748 	/* load base addresses of all 5 Tx rings (4 data + 1 mgt) */
   2749 	RAL_WRITE(sc, RT2661_LOAD_TX_RING_CSR, 0x1f);
   2750 
   2751 	/* load base address of Rx ring */
   2752 	RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 2);
   2753 
   2754 	/* initialize MAC registers to default values */
   2755 	for (i = 0; i < N(rt2661_def_mac); i++)
   2756 		RAL_WRITE(sc, rt2661_def_mac[i].reg, rt2661_def_mac[i].val);
   2757 
   2758 	IEEE80211_ADDR_COPY(ic->ic_myaddr, LLADDR(ifp->if_sadl));
   2759 	rt2661_set_macaddr(sc, ic->ic_myaddr);
   2760 
   2761 	/* set host ready */
   2762 	RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
   2763 	RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
   2764 
   2765 	/* wait for BBP/RF to wakeup */
   2766 	for (ntries = 0; ntries < 1000; ntries++) {
   2767 		if (RAL_READ(sc, RT2661_MAC_CSR12) & 8)
   2768 			break;
   2769 		DELAY(1000);
   2770 	}
   2771 	if (ntries == 1000) {
   2772 		printf("timeout waiting for BBP/RF to wakeup\n");
   2773 		rt2661_stop(ifp, 1);
   2774 		return EIO;
   2775 	}
   2776 
   2777 	if (rt2661_bbp_init(sc) != 0) {
   2778 		rt2661_stop(ifp, 1);
   2779 		return EIO;
   2780 	}
   2781 
   2782 	/* select default channel */
   2783 	sc->sc_curchan = ic->ic_curchan;
   2784 	rt2661_select_band(sc, sc->sc_curchan);
   2785 	rt2661_select_antenna(sc);
   2786 	rt2661_set_chan(sc, sc->sc_curchan);
   2787 
   2788 	/* update Rx filter */
   2789 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0) & 0xffff;
   2790 
   2791 	tmp |= RT2661_DROP_PHY_ERROR | RT2661_DROP_CRC_ERROR;
   2792 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
   2793 		tmp |= RT2661_DROP_CTL | RT2661_DROP_VER_ERROR |
   2794 		       RT2661_DROP_ACKCTS;
   2795 		if (ic->ic_opmode != IEEE80211_M_HOSTAP)
   2796 			tmp |= RT2661_DROP_TODS;
   2797 		if (!(ifp->if_flags & IFF_PROMISC))
   2798 			tmp |= RT2661_DROP_NOT_TO_ME;
   2799 	}
   2800 
   2801 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
   2802 
   2803 	/* clear STA registers */
   2804 	RAL_READ_REGION_4(sc, RT2661_STA_CSR0, star, N(star));
   2805 
   2806 	/* initialize ASIC */
   2807 	RAL_WRITE(sc, RT2661_MAC_CSR1, 4);
   2808 
   2809 	/* clear any pending interrupt */
   2810 	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
   2811 
   2812 	/* enable interrupts */
   2813 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
   2814 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
   2815 
   2816 	/* kick Rx */
   2817 	RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 1);
   2818 
   2819 	ifp->if_flags &= ~IFF_OACTIVE;
   2820 	ifp->if_flags |= IFF_RUNNING;
   2821 
   2822 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
   2823 		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
   2824 			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
   2825 	} else
   2826 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
   2827 
   2828 	return 0;
   2829 #undef N
   2830 }
   2831 
   2832 static void
   2833 rt2661_stop(struct ifnet *ifp, int disable)
   2834 {
   2835 	struct rt2661_softc *sc = ifp->if_softc;
   2836 	struct ieee80211com *ic = &sc->sc_ic;
   2837 	uint32_t tmp;
   2838 
   2839 	sc->sc_tx_timer = 0;
   2840 	ifp->if_timer = 0;
   2841 	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
   2842 
   2843 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);	/* free all nodes */
   2844 
   2845 	/* abort Tx (for all 5 Tx rings) */
   2846 	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 0x1f << 16);
   2847 
   2848 	/* disable Rx (value remains after reset!) */
   2849 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
   2850 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
   2851 
   2852 	/* reset ASIC */
   2853 	RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
   2854 	RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
   2855 
   2856 	/* disable interrupts */
   2857 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffff7f);
   2858 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
   2859 
   2860 	/* clear any pending interrupt */
   2861 	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
   2862 	RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, 0xffffffff);
   2863 
   2864 	/* reset Tx and Rx rings */
   2865 	rt2661_reset_tx_ring(sc, &sc->txq[0]);
   2866 	rt2661_reset_tx_ring(sc, &sc->txq[1]);
   2867 	rt2661_reset_tx_ring(sc, &sc->txq[2]);
   2868 	rt2661_reset_tx_ring(sc, &sc->txq[3]);
   2869 	rt2661_reset_tx_ring(sc, &sc->mgtq);
   2870 	rt2661_reset_rx_ring(sc, &sc->rxq);
   2871 
   2872 	/* for CardBus, power down the socket */
   2873 	if (disable && sc->sc_disable != NULL) {
   2874 		if (sc->sc_flags & RT2661_ENABLED) {
   2875 			(*sc->sc_disable)(sc);
   2876 			sc->sc_flags &= ~(RT2661_ENABLED | RT2661_FWLOADED);
   2877 		}
   2878 	}
   2879 }
   2880 
   2881 static int
   2882 rt2661_load_microcode(struct rt2661_softc *sc, const uint8_t *ucode, int size)
   2883 {
   2884 	int ntries;
   2885 
   2886 	/* reset 8051 */
   2887 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
   2888 
   2889 	/* cancel any pending Host to MCU command */
   2890 	RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR, 0);
   2891 	RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
   2892 	RAL_WRITE(sc, RT2661_HOST_CMD_CSR, 0);
   2893 
   2894 	/* write 8051's microcode */
   2895 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET | RT2661_MCU_SEL);
   2896 	RAL_WRITE_REGION_1(sc, RT2661_MCU_CODE_BASE, ucode, size);
   2897 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
   2898 
   2899 	/* kick 8051's ass */
   2900 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, 0);
   2901 
   2902 	/* wait for 8051 to initialize */
   2903 	for (ntries = 0; ntries < 500; ntries++) {
   2904 		if (RAL_READ(sc, RT2661_MCU_CNTL_CSR) & RT2661_MCU_READY)
   2905 			break;
   2906 		DELAY(100);
   2907 	}
   2908 	if (ntries == 500) {
   2909 		printf("timeout waiting for MCU to initialize\n");
   2910 		return EIO;
   2911 	}
   2912 	return 0;
   2913 }
   2914 
   2915 /*
   2916  * Dynamically tune Rx sensitivity (BBP register 17) based on average RSSI and
   2917  * false CCA count.  This function is called periodically (every seconds) when
   2918  * in the RUN state.  Values taken from the reference driver.
   2919  */
   2920 static void
   2921 rt2661_rx_tune(struct rt2661_softc *sc)
   2922 {
   2923 	uint8_t bbp17;
   2924 	uint16_t cca;
   2925 	int lo, hi, dbm;
   2926 
   2927 	/*
   2928 	 * Tuning range depends on operating band and on the presence of an
   2929 	 * external low-noise amplifier.
   2930 	 */
   2931 	lo = 0x20;
   2932 	if (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan))
   2933 		lo += 0x08;
   2934 	if ((IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan) && sc->ext_2ghz_lna) ||
   2935 	    (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan) && sc->ext_5ghz_lna))
   2936 		lo += 0x10;
   2937 	hi = lo + 0x20;
   2938 
   2939 	dbm = sc->avg_rssi;
   2940 	/* retrieve false CCA count since last call (clear on read) */
   2941 	cca = RAL_READ(sc, RT2661_STA_CSR1) & 0xffff;
   2942 
   2943 	DPRINTFN(2, ("RSSI=%ddBm false CCA=%d\n", dbm, cca));
   2944 	if (dbm < -74) {
   2945 		/* very bad RSSI, tune using false CCA count */
   2946 		bbp17 = sc->bbp17; /* current value */
   2947 
   2948 		hi -= 2 * (-74 - dbm);
   2949 		if (hi < lo)
   2950 			hi = lo;
   2951 
   2952 		if (bbp17 > hi)
   2953 			bbp17 = hi;
   2954 		else if (cca > 512)
   2955 			bbp17 = min(bbp17 + 1, hi);
   2956 		else if (cca < 100)
   2957 			bbp17 = max(bbp17 - 1, lo);
   2958 	} else if (dbm < -66) {
   2959 		bbp17 = lo + 0x08;
   2960 	} else if (dbm < -58) {
   2961 		bbp17 = lo + 0x10;
   2962 	} else if (dbm < -35) {
   2963 		bbp17 = hi;
   2964 	} else {	/* very good RSSI >= -35dBm */
   2965 		bbp17 = 0x60;	/* very low sensitivity */
   2966 	}
   2967 
   2968 	if (bbp17 != sc->bbp17) {
   2969 		DPRINTF(("BBP17 %x->%x\n", sc->bbp17, bbp17));
   2970 		rt2661_bbp_write(sc, 17, bbp17);
   2971 		sc->bbp17 = bbp17;
   2972 	}
   2973 }
   2974 
   2975 #ifdef notyet
   2976 /*
   2977  * Enter/Leave radar detection mode.
   2978  * This is for 802.11h additional regulatory domains.
   2979  */
   2980 static void
   2981 rt2661_radar_start(struct rt2661_softc *sc)
   2982 {
   2983 	uint32_t tmp;
   2984 
   2985 	/* disable Rx */
   2986 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
   2987 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
   2988 
   2989 	rt2661_bbp_write(sc, 82, 0x20);
   2990 	rt2661_bbp_write(sc, 83, 0x00);
   2991 	rt2661_bbp_write(sc, 84, 0x40);
   2992 
   2993 	/* save current BBP registers values */
   2994 	sc->bbp18 = rt2661_bbp_read(sc, 18);
   2995 	sc->bbp21 = rt2661_bbp_read(sc, 21);
   2996 	sc->bbp22 = rt2661_bbp_read(sc, 22);
   2997 	sc->bbp16 = rt2661_bbp_read(sc, 16);
   2998 	sc->bbp17 = rt2661_bbp_read(sc, 17);
   2999 	sc->bbp64 = rt2661_bbp_read(sc, 64);
   3000 
   3001 	rt2661_bbp_write(sc, 18, 0xff);
   3002 	rt2661_bbp_write(sc, 21, 0x3f);
   3003 	rt2661_bbp_write(sc, 22, 0x3f);
   3004 	rt2661_bbp_write(sc, 16, 0xbd);
   3005 	rt2661_bbp_write(sc, 17, sc->ext_5ghz_lna ? 0x44 : 0x34);
   3006 	rt2661_bbp_write(sc, 64, 0x21);
   3007 
   3008 	/* restore Rx filter */
   3009 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
   3010 }
   3011 
   3012 static int
   3013 rt2661_radar_stop(struct rt2661_softc *sc)
   3014 {
   3015 	uint8_t bbp66;
   3016 
   3017 	/* read radar detection result */
   3018 	bbp66 = rt2661_bbp_read(sc, 66);
   3019 
   3020 	/* restore BBP registers values */
   3021 	rt2661_bbp_write(sc, 16, sc->bbp16);
   3022 	rt2661_bbp_write(sc, 17, sc->bbp17);
   3023 	rt2661_bbp_write(sc, 18, sc->bbp18);
   3024 	rt2661_bbp_write(sc, 21, sc->bbp21);
   3025 	rt2661_bbp_write(sc, 22, sc->bbp22);
   3026 	rt2661_bbp_write(sc, 64, sc->bbp64);
   3027 
   3028 	return bbp66 == 1;
   3029 }
   3030 #endif
   3031 
   3032 static int
   3033 rt2661_prepare_beacon(struct rt2661_softc *sc)
   3034 {
   3035 	struct ieee80211com *ic = &sc->sc_ic;
   3036 	struct rt2661_tx_desc desc;
   3037 	struct mbuf *m0;
   3038 	struct ieee80211_beacon_offsets bo;
   3039 	int rate;
   3040 
   3041 	m0 = ieee80211_beacon_alloc(ic, ic->ic_bss, &bo);
   3042 
   3043 	if (m0 == NULL) {
   3044 		printf("%s: could not allocate beacon frame\n",
   3045 		    sc->sc_dev.dv_xname);
   3046 		return ENOBUFS;
   3047 	}
   3048 
   3049 	/* send beacons at the lowest available rate */
   3050 	rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan) ? 12 : 2;
   3051 
   3052 	rt2661_setup_tx_desc(sc, &desc, RT2661_TX_TIMESTAMP, RT2661_TX_HWSEQ,
   3053 	    m0->m_pkthdr.len, rate, NULL, 0, RT2661_QID_MGT);
   3054 
   3055 	/* copy the first 24 bytes of Tx descriptor into NIC memory */
   3056 	RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0, (uint8_t *)&desc, 24);
   3057 
   3058 	/* copy beacon header and payload into NIC memory */
   3059 	RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0 + 24,
   3060 	    mtod(m0, uint8_t *), m0->m_pkthdr.len);
   3061 
   3062 	m_freem(m0);
   3063 
   3064 	return 0;
   3065 }
   3066 
   3067 /*
   3068  * Enable TSF synchronization and tell h/w to start sending beacons for IBSS
   3069  * and HostAP operating modes.
   3070  */
   3071 static void
   3072 rt2661_enable_tsf_sync(struct rt2661_softc *sc)
   3073 {
   3074 	struct ieee80211com *ic = &sc->sc_ic;
   3075 	uint32_t tmp;
   3076 
   3077 	if (ic->ic_opmode != IEEE80211_M_STA) {
   3078 		/*
   3079 		 * Change default 16ms TBTT adjustment to 8ms.
   3080 		 * Must be done before enabling beacon generation.
   3081 		 */
   3082 		RAL_WRITE(sc, RT2661_TXRX_CSR10, 1 << 12 | 8);
   3083 	}
   3084 
   3085 	tmp = RAL_READ(sc, RT2661_TXRX_CSR9) & 0xff000000;
   3086 
   3087 	/* set beacon interval (in 1/16ms unit) */
   3088 	tmp |= ic->ic_bss->ni_intval * 16;
   3089 
   3090 	tmp |= RT2661_TSF_TICKING | RT2661_ENABLE_TBTT;
   3091 	if (ic->ic_opmode == IEEE80211_M_STA)
   3092 		tmp |= RT2661_TSF_MODE(1);
   3093 	else
   3094 		tmp |= RT2661_TSF_MODE(2) | RT2661_GENERATE_BEACON;
   3095 
   3096 	RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp);
   3097 }
   3098 
   3099 /*
   3100  * Retrieve the "Received Signal Strength Indicator" from the raw values
   3101  * contained in Rx descriptors.  The computation depends on which band the
   3102  * frame was received.  Correction values taken from the reference driver.
   3103  */
   3104 static int
   3105 rt2661_get_rssi(struct rt2661_softc *sc, uint8_t raw)
   3106 {
   3107 	int lna, agc, rssi;
   3108 
   3109 	lna = (raw >> 5) & 0x3;
   3110 	agc = raw & 0x1f;
   3111 
   3112 	rssi = 2 * agc;
   3113 
   3114 	if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan)) {
   3115 		rssi += sc->rssi_2ghz_corr;
   3116 
   3117 		if (lna == 1)
   3118 			rssi -= 64;
   3119 		else if (lna == 2)
   3120 			rssi -= 74;
   3121 		else if (lna == 3)
   3122 			rssi -= 90;
   3123 	} else {
   3124 		rssi += sc->rssi_5ghz_corr;
   3125 
   3126 		if (lna == 1)
   3127 			rssi -= 64;
   3128 		else if (lna == 2)
   3129 			rssi -= 86;
   3130 		else if (lna == 3)
   3131 			rssi -= 100;
   3132 	}
   3133 	return rssi;
   3134 }
   3135