Home | History | Annotate | Line # | Download | only in ic
ath.c revision 1.19
      1 /*	$NetBSD: ath.c,v 1.19 2004/02/29 00:47:21 dyoung Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer,
     12  *    without modification.
     13  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
     14  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
     15  *    redistribution must be conditioned upon including a substantially
     16  *    similar Disclaimer requirement for further binary redistribution.
     17  * 3. Neither the names of the above-listed copyright holders nor the names
     18  *    of any contributors may be used to endorse or promote products derived
     19  *    from this software without specific prior written permission.
     20  *
     21  * Alternatively, this software may be distributed under the terms of the
     22  * GNU General Public License ("GPL") version 2 as published by the Free
     23  * Software Foundation.
     24  *
     25  * NO WARRANTY
     26  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     28  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
     29  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
     30  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
     31  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
     34  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
     36  * THE POSSIBILITY OF SUCH DAMAGES.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #ifdef __FreeBSD__
     41 __FBSDID("$FreeBSD: src/sys/dev/ath/if_ath.c,v 1.36 2003/11/29 01:23:59 sam Exp $");
     42 #endif
     43 #ifdef __NetBSD__
     44 __KERNEL_RCSID(0, "$NetBSD: ath.c,v 1.19 2004/02/29 00:47:21 dyoung Exp $");
     45 #endif
     46 
     47 /*
     48  * Driver for the Atheros Wireless LAN controller.
     49  *
     50  * This software is derived from work of Atsushi Onoe; his contribution
     51  * is greatly appreciated.
     52  */
     53 
     54 #include "opt_inet.h"
     55 
     56 #ifdef __NetBSD__
     57 #include "bpfilter.h"
     58 #endif /* __NetBSD__ */
     59 
     60 #include <sys/param.h>
     61 #include <sys/systm.h>
     62 #include <sys/types.h>
     63 #include <sys/sysctl.h>
     64 #include <sys/mbuf.h>
     65 #include <sys/malloc.h>
     66 #include <sys/lock.h>
     67 #ifdef __FreeBSD__
     68 #include <sys/mutex.h>
     69 #endif
     70 #include <sys/kernel.h>
     71 #include <sys/socket.h>
     72 #include <sys/sockio.h>
     73 #include <sys/errno.h>
     74 #include <sys/callout.h>
     75 #ifdef __FreeBSD__
     76 #include <sys/bus.h>
     77 #else
     78 #include <machine/bus.h>
     79 #endif
     80 #include <sys/endian.h>
     81 
     82 #include <machine/bus.h>
     83 
     84 #include <net/if.h>
     85 #include <net/if_dl.h>
     86 #include <net/if_media.h>
     87 #include <net/if_arp.h>
     88 #ifdef __FreeBSD__
     89 #include <net/ethernet.h>
     90 #else
     91 #include <net/if_ether.h>
     92 #endif
     93 #include <net/if_llc.h>
     94 
     95 #include <net80211/ieee80211_var.h>
     96 #include <net80211/ieee80211_compat.h>
     97 
     98 #if NBPFILTER > 0
     99 #include <net/bpf.h>
    100 #endif
    101 
    102 #ifdef INET
    103 #include <netinet/in.h>
    104 #endif
    105 
    106 #include <dev/ic/athcompat.h>
    107 
    108 #define	AR_DEBUG
    109 #ifdef __FreeBSD__
    110 #include <dev/ath/if_athvar.h>
    111 #include <contrib/dev/ath/ah_desc.h>
    112 #else
    113 #include <dev/ic/athvar.h>
    114 #include <../contrib/sys/dev/ic/athhal_desc.h>
    115 #endif
    116 
    117 /* unaligned little endian access */
    118 #define LE_READ_2(p)							\
    119 	((u_int16_t)							\
    120 	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
    121 #define LE_READ_4(p)							\
    122 	((u_int32_t)							\
    123 	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) |	\
    124 	  (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
    125 
    126 #ifdef __FreeBSD__
    127 static void	ath_init(void *);
    128 #else
    129 static int	ath_init(struct ifnet *);
    130 #endif
    131 static int	ath_init1(struct ath_softc *);
    132 static int	ath_intr1(struct ath_softc *);
    133 static void	ath_stop(struct ifnet *);
    134 static void	ath_start(struct ifnet *);
    135 static void	ath_reset(struct ath_softc *);
    136 static int	ath_media_change(struct ifnet *);
    137 static void	ath_watchdog(struct ifnet *);
    138 static int	ath_ioctl(struct ifnet *, u_long, caddr_t);
    139 static void	ath_fatal_proc(void *, int);
    140 static void	ath_rxorn_proc(void *, int);
    141 static void	ath_bmiss_proc(void *, int);
    142 static void	ath_initkeytable(struct ath_softc *);
    143 static void	ath_mode_init(struct ath_softc *);
    144 static int	ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
    145 static void	ath_beacon_proc(void *, int);
    146 static void	ath_beacon_free(struct ath_softc *);
    147 static void	ath_beacon_config(struct ath_softc *);
    148 static int	ath_desc_alloc(struct ath_softc *);
    149 static void	ath_desc_free(struct ath_softc *);
    150 static struct ieee80211_node *ath_node_alloc(struct ieee80211com *);
    151 static void	ath_node_free(struct ieee80211com *, struct ieee80211_node *);
    152 static void	ath_node_copy(struct ieee80211com *,
    153 			struct ieee80211_node *, const struct ieee80211_node *);
    154 static u_int8_t	ath_node_getrssi(struct ieee80211com *,
    155 			struct ieee80211_node *);
    156 static int	ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
    157 static void	ath_rx_proc(void *, int);
    158 static int	ath_tx_start(struct ath_softc *, struct ieee80211_node *,
    159 			     struct ath_buf *, struct mbuf *);
    160 static void	ath_tx_proc(void *, int);
    161 static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
    162 static void	ath_draintxq(struct ath_softc *);
    163 static void	ath_stoprecv(struct ath_softc *);
    164 static int	ath_startrecv(struct ath_softc *);
    165 static void	ath_next_scan(void *);
    166 static void	ath_calibrate(void *);
    167 static int	ath_newstate(struct ieee80211com *, enum ieee80211_state, int);
    168 static void	ath_newassoc(struct ieee80211com *,
    169 			struct ieee80211_node *, int);
    170 static int	ath_getchannels(struct ath_softc *, u_int cc, HAL_BOOL outdoor);
    171 
    172 static int	ath_rate_setup(struct ath_softc *sc, u_int mode);
    173 static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
    174 static void	ath_rate_ctl_reset(struct ath_softc *, enum ieee80211_state);
    175 static void	ath_rate_ctl(void *, struct ieee80211_node *);
    176 
    177 #ifdef __NetBSD__
    178 int	ath_enable(struct ath_softc *);
    179 void	ath_disable(struct ath_softc *);
    180 void	ath_power(int, void *);
    181 #endif
    182 
    183 #ifdef __FreeBSD__
    184 SYSCTL_DECL(_hw_ath);
    185 /* XXX validate sysctl values */
    186 SYSCTL_INT(_hw_ath, OID_AUTO, dwell, CTLFLAG_RW, &ath_dwelltime,
    187 	    0, "channel dwell time (ms) for AP/station scanning");
    188 SYSCTL_INT(_hw_ath, OID_AUTO, calibrate, CTLFLAG_RW, &ath_calinterval,
    189 	    0, "chip calibration interval (secs)");
    190 SYSCTL_INT(_hw_ath, OID_AUTO, outdoor, CTLFLAG_RD, &ath_outdoor,
    191 	    0, "enable/disable outdoor operation");
    192 SYSCTL_INT(_hw_ath, OID_AUTO, countrycode, CTLFLAG_RD, &ath_countrycode,
    193 	    0, "country code");
    194 SYSCTL_INT(_hw_ath, OID_AUTO, regdomain, CTLFLAG_RD, &ath_regdomain,
    195 	    0, "regulatory domain");
    196 #endif /* __FreeBSD__ */
    197 
    198 static	int ath_dwelltime = 200;		/* 5 channels/second */
    199 static	int ath_calinterval = 30;		/* calibrate every 30 secs */
    200 static	int ath_outdoor = AH_TRUE;		/* outdoor operation */
    201 static	int ath_countrycode = CTRY_DEFAULT;	/* country code */
    202 static	int ath_regdomain = 0;			/* regulatory domain */
    203 
    204 #ifdef AR_DEBUG
    205 int	ath_debug = 0;
    206 #ifdef __FreeBSD__
    207 SYSCTL_INT(_hw_ath, OID_AUTO, debug, CTLFLAG_RW, &ath_debug,
    208 	    0, "control debugging printfs");
    209 #endif /* __FreeBSD__ */
    210 #define	IFF_DUMPPKTS(_ifp) \
    211 	(ath_debug || \
    212 	    ((_ifp)->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
    213 static	void ath_printrxbuf(struct ath_buf *bf, int);
    214 static	void ath_printtxbuf(struct ath_buf *bf, int);
    215 #define	DPRINTF(X)	if (ath_debug) printf X
    216 #define	DPRINTF2(X)	if (ath_debug > 1) printf X
    217 #else
    218 #define	IFF_DUMPPKTS(_ifp) \
    219 	(((_ifp)->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
    220 #define	DPRINTF(X)
    221 #define	DPRINTF2(X)
    222 #endif
    223 
    224 #ifdef __NetBSD__
    225 int
    226 ath_activate(struct device *self, enum devact act)
    227 {
    228 	struct ath_softc *sc = (struct ath_softc *)self;
    229 	int rv = 0, s;
    230 
    231 	s = splnet();
    232 	switch (act) {
    233 	case DVACT_ACTIVATE:
    234 		rv = EOPNOTSUPP;
    235 		break;
    236 	case DVACT_DEACTIVATE:
    237 		if_deactivate(&sc->sc_ic.ic_if);
    238 		break;
    239 	}
    240 	splx(s);
    241 	return rv;
    242 }
    243 
    244 int
    245 ath_enable(struct ath_softc *sc)
    246 {
    247 	if (ATH_IS_ENABLED(sc) == 0) {
    248 		if (sc->sc_enable != NULL && (*sc->sc_enable)(sc) != 0) {
    249 			printf("%s: device enable failed\n",
    250 				sc->sc_dev.dv_xname);
    251 			return (EIO);
    252 		}
    253 		sc->sc_flags |= ATH_ENABLED;
    254 	}
    255 	return (0);
    256 }
    257 
    258 void
    259 ath_disable(struct ath_softc *sc)
    260 {
    261 	if (!ATH_IS_ENABLED(sc))
    262 		return;
    263 	if (sc->sc_disable != NULL)
    264 		(*sc->sc_disable)(sc);
    265 	sc->sc_flags &= ~ATH_ENABLED;
    266 }
    267 #endif	/* #ifdef __NetBSD__ */
    268 
    269 int
    270 ath_attach(u_int16_t devid, struct ath_softc *sc)
    271 {
    272 	struct ieee80211com *ic = &sc->sc_ic;
    273 	struct ifnet *ifp = &ic->ic_if;
    274 	struct ath_hal *ah;
    275 	HAL_STATUS status;
    276 	int error = 0;
    277 
    278 	DPRINTF(("ath_attach: devid 0x%x\n", devid));
    279 
    280 #ifdef __FreeBSD__
    281 	/* set these up early for if_printf use */
    282 	if_initname(ifp, device_get_name(sc->sc_dev),
    283 	    device_get_unit(sc->sc_dev));
    284 #else
    285 	memcpy(ifp->if_xname, sc->sc_dev.dv_xname, IFNAMSIZ);
    286 #endif
    287 
    288 	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, &status);
    289 	if (ah == NULL) {
    290 		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
    291 			status);
    292 		error = ENXIO;
    293 		goto bad;
    294 	}
    295 	if (ah->ah_abi != HAL_ABI_VERSION) {
    296 		if_printf(ifp, "HAL ABI mismatch detected (0x%x != 0x%x)\n",
    297 			ah->ah_abi, HAL_ABI_VERSION);
    298 		error = ENXIO;
    299 		goto bad;
    300 	}
    301 	if_printf(ifp, "mac %d.%d phy %d.%d",
    302 		ah->ah_macVersion, ah->ah_macRev,
    303 		ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
    304 	if (ah->ah_analog5GhzRev)
    305 		printf(" 5ghz radio %d.%d",
    306 			ah->ah_analog5GhzRev >> 4, ah->ah_analog5GhzRev & 0xf);
    307 	if (ah->ah_analog2GhzRev)
    308 		printf(" 2ghz radio %d.%d",
    309 			ah->ah_analog2GhzRev >> 4, ah->ah_analog2GhzRev & 0xf);
    310 	printf("\n");
    311 	sc->sc_ah = ah;
    312 	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
    313 
    314 	/*
    315 	 * Collect the channel list using the default country
    316 	 * code and including outdoor channels.  The 802.11 layer
    317 	 * is resposible for filtering this list based on settings
    318 	 * like the phy mode.
    319 	 */
    320 	error = ath_getchannels(sc, ath_countrycode, ath_outdoor);
    321 	if (error != 0)
    322 		goto bad;
    323 	/*
    324 	 * Copy these back; they are set as a side effect
    325 	 * of constructing the channel list.
    326 	 */
    327 	ath_regdomain = ath_hal_getregdomain(ah);
    328 	ath_countrycode = ath_hal_getcountrycode(ah);
    329 
    330 	/*
    331 	 * Setup rate tables for all potential media types.
    332 	 */
    333 	ath_rate_setup(sc, IEEE80211_MODE_11A);
    334 	ath_rate_setup(sc, IEEE80211_MODE_11B);
    335 	ath_rate_setup(sc, IEEE80211_MODE_11G);
    336 	ath_rate_setup(sc, IEEE80211_MODE_TURBO);
    337 
    338 	error = ath_desc_alloc(sc);
    339 	if (error != 0) {
    340 		if_printf(ifp, "failed to allocate descriptors: %d\n", error);
    341 		goto bad;
    342 	}
    343 	ATH_CALLOUT_INIT(&sc->sc_scan_ch);
    344 	ATH_CALLOUT_INIT(&sc->sc_cal_ch);
    345 
    346 #ifdef __FreeBSD__
    347 	ATH_TXBUF_LOCK_INIT(sc);
    348 	ATH_TXQ_LOCK_INIT(sc);
    349 #endif
    350 
    351 	ATH_TASK_INIT(&sc->sc_txtask, ath_tx_proc, sc);
    352 	ATH_TASK_INIT(&sc->sc_rxtask, ath_rx_proc, sc);
    353 	ATH_TASK_INIT(&sc->sc_swbatask, ath_beacon_proc, sc);
    354 	ATH_TASK_INIT(&sc->sc_rxorntask, ath_rxorn_proc, sc);
    355 	ATH_TASK_INIT(&sc->sc_fataltask, ath_fatal_proc, sc);
    356 	ATH_TASK_INIT(&sc->sc_bmisstask, ath_bmiss_proc, sc);
    357 
    358 	/*
    359 	 * For now just pre-allocate one data queue and one
    360 	 * beacon queue.  Note that the HAL handles resetting
    361 	 * them at the needed time.  Eventually we'll want to
    362 	 * allocate more tx queues for splitting management
    363 	 * frames and for QOS support.
    364 	 */
    365 	sc->sc_txhalq = ath_hal_setuptxqueue(ah,
    366 		HAL_TX_QUEUE_DATA,
    367 		AH_TRUE			/* enable interrupts */
    368 	);
    369 	if (sc->sc_txhalq == (u_int) -1) {
    370 		if_printf(ifp, "unable to setup a data xmit queue!\n");
    371 		goto bad;
    372 	}
    373 	sc->sc_bhalq = ath_hal_setuptxqueue(ah,
    374 		HAL_TX_QUEUE_BEACON,
    375 		AH_TRUE			/* enable interrupts */
    376 	);
    377 	if (sc->sc_bhalq == (u_int) -1) {
    378 		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
    379 		goto bad;
    380 	}
    381 
    382 	ifp->if_softc = sc;
    383 	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
    384 	ifp->if_start = ath_start;
    385 	ifp->if_watchdog = ath_watchdog;
    386 	ifp->if_ioctl = ath_ioctl;
    387 	ifp->if_init = ath_init;
    388 #ifdef __FreeBSD__
    389 	ifp->if_snd.ifq_maxlen = IFQ_MAXLEN;
    390 #else
    391 #if 0
    392 	ifp->if_stop = ath_stop;		/* XXX */
    393 #endif
    394 	IFQ_SET_READY(&ifp->if_snd);
    395 #endif
    396 
    397 	ic->ic_softc = sc;
    398 	ic->ic_newassoc = ath_newassoc;
    399 	/* XXX not right but it's not used anywhere important */
    400 	ic->ic_phytype = IEEE80211_T_OFDM;
    401 	ic->ic_opmode = IEEE80211_M_STA;
    402 	ic->ic_caps = IEEE80211_C_WEP		/* wep supported */
    403 		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
    404 		| IEEE80211_C_HOSTAP		/* hostap mode */
    405 		| IEEE80211_C_MONITOR		/* monitor mode */
    406 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
    407 		| IEEE80211_C_RCVMGT;		/* recv management frames */
    408 
    409 	/* get mac address from hardware */
    410 	ath_hal_getmac(ah, ic->ic_myaddr);
    411 
    412 #ifdef __NetBSD__
    413 	if_attach(ifp);
    414 #endif
    415 	/* call MI attach routine. */
    416 	ieee80211_ifattach(ifp);
    417 	/* override default methods */
    418 	ic->ic_node_alloc = ath_node_alloc;
    419 	ic->ic_node_free = ath_node_free;
    420 	ic->ic_node_copy = ath_node_copy;
    421 	ic->ic_node_getrssi = ath_node_getrssi;
    422 	sc->sc_newstate = ic->ic_newstate;
    423 	ic->ic_newstate = ath_newstate;
    424 	/* complete initialization */
    425 	ieee80211_media_init(ifp, ath_media_change, ieee80211_media_status);
    426 
    427 #if NBPFILTER > 0
    428 	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
    429 		sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th),
    430 		&sc->sc_drvbpf);
    431 #endif
    432 	/*
    433 	 * Initialize constant fields.
    434 	 *
    435 	 * NB: the channel is setup each time we transition to the
    436 	 *     RUN state to avoid filling it in for each frame.
    437 	 */
    438 	sc->sc_tx_th.wt_ihdr.it_len = sizeof(sc->sc_tx_th);
    439 	sc->sc_tx_th.wt_ihdr.it_present = ATH_TX_RADIOTAP_PRESENT;
    440 
    441 	sc->sc_rx_th.wr_ihdr.it_len = sizeof(sc->sc_rx_th);
    442 	sc->sc_rx_th.wr_ihdr.it_present = ATH_RX_RADIOTAP_PRESENT;
    443 
    444 	if_printf(ifp, "802.11 address: %s\n", ether_sprintf(ic->ic_myaddr));
    445 
    446 #ifdef __NetBSD__
    447 	sc->sc_flags |= ATH_ATTACHED;
    448 	/*
    449 	 * Make sure the interface is shutdown during reboot.
    450 	 */
    451 	sc->sc_sdhook = shutdownhook_establish(ath_shutdown, sc);
    452 	if (sc->sc_sdhook == NULL)
    453 		printf("%s: WARNING: unable to establish shutdown hook\n",
    454 			sc->sc_dev.dv_xname);
    455 	sc->sc_powerhook = powerhook_establish(ath_power, sc);
    456 	if (sc->sc_powerhook == NULL)
    457 		printf("%s: WARNING: unable to establish power hook\n",
    458 			sc->sc_dev.dv_xname);
    459 #endif
    460 	return 0;
    461 bad:
    462 	if (ah)
    463 		ath_hal_detach(ah);
    464 	sc->sc_invalid = 1;
    465 	return error;
    466 }
    467 
    468 int
    469 ath_detach(struct ath_softc *sc)
    470 {
    471 	struct ifnet *ifp = &sc->sc_ic.ic_if;
    472 	ath_softc_critsect_decl(s);
    473 
    474 	DPRINTF(("ath_detach: if_flags %x\n", ifp->if_flags));
    475 	if ((sc->sc_flags & ATH_ATTACHED) == 0)
    476 		return (0);
    477 
    478 	ath_softc_critsect_begin(sc, s);
    479 	ath_stop(ifp);
    480 #if NBPFILTER > 0
    481 	bpfdetach(ifp);
    482 #endif
    483 	ath_desc_free(sc);
    484 	ath_hal_detach(sc->sc_ah);
    485 	ieee80211_ifdetach(ifp);
    486 #ifdef __NetBSD__
    487 	if_detach(ifp);
    488 #endif /* __NetBSD__ */
    489 	ath_softc_critsect_end(sc, s);
    490 #ifdef __NetBSD__
    491 	powerhook_disestablish(sc->sc_powerhook);
    492 	shutdownhook_disestablish(sc->sc_sdhook);
    493 #endif /* __NetBSD__ */
    494 #ifdef __FreeBSD__
    495 
    496 	ATH_TXBUF_LOCK_DESTROY(sc);
    497 	ATH_TXQ_LOCK_DESTROY(sc);
    498 
    499 #endif /* __FreeBSD__ */
    500 	return 0;
    501 }
    502 
    503 #ifdef __NetBSD__
    504 void
    505 ath_power(int why, void *arg)
    506 {
    507 	struct ath_softc *sc = arg;
    508 	int s;
    509 
    510 	DPRINTF(("ath_power(%d)\n", why));
    511 
    512 	s = splnet();
    513 	switch (why) {
    514 	case PWR_SUSPEND:
    515 	case PWR_STANDBY:
    516 		ath_suspend(sc, why);
    517 		break;
    518 	case PWR_RESUME:
    519 		ath_resume(sc, why);
    520 		break;
    521 	case PWR_SOFTSUSPEND:
    522 	case PWR_SOFTSTANDBY:
    523 	case PWR_SOFTRESUME:
    524 		break;
    525 	}
    526 	splx(s);
    527 }
    528 #endif
    529 
    530 void
    531 ath_suspend(struct ath_softc *sc, int why)
    532 {
    533 	struct ifnet *ifp = &sc->sc_ic.ic_if;
    534 
    535 	DPRINTF(("ath_suspend: if_flags %x\n", ifp->if_flags));
    536 
    537 	ath_stop(ifp);
    538 	if (sc->sc_power != NULL)
    539 		(*sc->sc_power)(sc, why);
    540 }
    541 
    542 void
    543 ath_resume(struct ath_softc *sc, int why)
    544 {
    545 	struct ifnet *ifp = &sc->sc_ic.ic_if;
    546 
    547 	DPRINTF(("ath_resume: if_flags %x\n", ifp->if_flags));
    548 
    549 	if (ifp->if_flags & IFF_UP) {
    550 		ath_init(ifp);
    551 #if 0
    552 		(void)ath_intr(sc);
    553 #endif
    554 		if (sc->sc_power != NULL)
    555 			(*sc->sc_power)(sc, why);
    556 		if (ifp->if_flags & IFF_RUNNING)
    557 			ath_start(ifp);
    558 	}
    559 }
    560 
    561 #ifdef __NetBSD__
    562 void
    563 ath_shutdown(void *arg)
    564 {
    565 	struct ath_softc *sc = arg;
    566 
    567 	ath_stop(&sc->sc_ic.ic_if);
    568 }
    569 #else
    570 void
    571 ath_shutdown(struct ath_softc *sc)
    572 {
    573 #if 1
    574 	return;
    575 #else
    576 	struct ifnet *ifp = &sc->sc_ic.ic_if;
    577 
    578 	DPRINTF(("ath_shutdown: if_flags %x\n", ifp->if_flags));
    579 
    580 	ath_stop(ifp);
    581 #endif
    582 }
    583 #endif
    584 
    585 #ifdef __NetBSD__
    586 int
    587 ath_intr(void *arg)
    588 {
    589 	return ath_intr1((struct ath_softc *)arg);
    590 }
    591 #else
    592 void
    593 ath_intr(void *arg)
    594 {
    595 	(void)ath_intr1((struct ath_softc *)arg);
    596 }
    597 #endif
    598 
    599 static int
    600 ath_intr1(struct ath_softc *sc)
    601 {
    602 	struct ieee80211com *ic = &sc->sc_ic;
    603 	struct ifnet *ifp = &ic->ic_if;
    604 	struct ath_hal *ah = sc->sc_ah;
    605 	HAL_INT status;
    606 
    607 	if (sc->sc_invalid) {
    608 		/*
    609 		 * The hardware is not ready/present, don't touch anything.
    610 		 * Note this can happen early on if the IRQ is shared.
    611 		 */
    612 		DPRINTF(("ath_intr: invalid; ignored\n"));
    613 		return 0;
    614 	}
    615 	if ((ifp->if_flags & (IFF_RUNNING|IFF_UP)) != (IFF_RUNNING|IFF_UP)) {
    616 		DPRINTF(("ath_intr: if_flags 0x%x\n", ifp->if_flags));
    617 		ath_hal_getisr(ah, &status);	/* clear ISR */
    618 		ath_hal_intrset(ah, 0);		/* disable further intr's */
    619 		return 1; /* XXX */
    620 	}
    621 	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
    622 	DPRINTF2(("ath_intr: status 0x%x\n", status));
    623 #ifdef AR_DEBUG
    624 	if (ath_debug &&
    625 	    (status & (HAL_INT_FATAL|HAL_INT_RXORN|HAL_INT_BMISS))) {
    626 		if_printf(ifp, "ath_intr: status 0x%x\n", status);
    627 		ath_hal_dumpstate(ah);
    628 	}
    629 #endif /* AR_DEBUG */
    630 	status &= sc->sc_imask;			/* discard unasked for bits */
    631 	if (status & HAL_INT_FATAL) {
    632 		sc->sc_stats.ast_hardware++;
    633 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
    634 		ATH_TASK_RUN_OR_ENQUEUE(&sc->sc_fataltask);
    635 	} else if (status & HAL_INT_RXORN) {
    636 		sc->sc_stats.ast_rxorn++;
    637 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
    638 		ATH_TASK_RUN_OR_ENQUEUE(&sc->sc_rxorntask);
    639 	} else {
    640 		if (status & HAL_INT_RXEOL) {
    641 			/*
    642 			 * NB: the hardware should re-read the link when
    643 			 *     RXE bit is written, but it doesn't work at
    644 			 *     least on older hardware revs.
    645 			 */
    646 			sc->sc_stats.ast_rxeol++;
    647 			sc->sc_rxlink = NULL;
    648 		}
    649 		if (status & HAL_INT_TXURN) {
    650 			sc->sc_stats.ast_txurn++;
    651 			/* bump tx trigger level */
    652 			ath_hal_updatetxtriglevel(ah, AH_TRUE);
    653 		}
    654 		if (status & HAL_INT_RX)
    655 			ATH_TASK_RUN_OR_ENQUEUE(&sc->sc_rxtask);
    656 		if (status & HAL_INT_TX)
    657 			ATH_TASK_RUN_OR_ENQUEUE(&sc->sc_txtask);
    658 		if (status & HAL_INT_SWBA)
    659 			ATH_TASK_RUN_OR_ENQUEUE(&sc->sc_swbatask);
    660 		if (status & HAL_INT_BMISS) {
    661 			sc->sc_stats.ast_bmiss++;
    662 			ATH_TASK_RUN_OR_ENQUEUE(&sc->sc_bmisstask);
    663 		}
    664 	}
    665 	return 1;
    666 }
    667 
    668 static void
    669 ath_fatal_proc(void *arg, int pending)
    670 {
    671 	struct ath_softc *sc = arg;
    672 
    673 	device_printf(sc->sc_dev, "hardware error; resetting\n");
    674 	ath_reset(sc);
    675 }
    676 
    677 static void
    678 ath_rxorn_proc(void *arg, int pending)
    679 {
    680 	struct ath_softc *sc = arg;
    681 
    682 	device_printf(sc->sc_dev, "rx FIFO overrun; resetting\n");
    683 	ath_reset(sc);
    684 }
    685 
    686 static void
    687 ath_bmiss_proc(void *arg, int pending)
    688 {
    689 	struct ath_softc *sc = arg;
    690 	struct ieee80211com *ic = &sc->sc_ic;
    691 
    692 	DPRINTF(("ath_bmiss_proc: pending %u\n", pending));
    693 	if (ic->ic_opmode != IEEE80211_M_STA)
    694 		return;
    695 	if (ic->ic_state == IEEE80211_S_RUN) {
    696 		/*
    697 		 * Rather than go directly to scan state, try to
    698 		 * reassociate first.  If that fails then the state
    699 		 * machine will drop us into scanning after timing
    700 		 * out waiting for a probe response.
    701 		 */
    702 		ieee80211_new_state(ic, IEEE80211_S_ASSOC, -1);
    703 	}
    704 }
    705 
    706 static u_int
    707 ath_chan2flags(struct ieee80211com *ic, struct ieee80211_channel *chan)
    708 {
    709 	enum ieee80211_phymode mode = ieee80211_chan2mode(ic, chan);
    710 
    711 	switch (mode) {
    712 	case IEEE80211_MODE_AUTO:
    713 		return 0;
    714 	case IEEE80211_MODE_11A:
    715 		return CHANNEL_A;
    716 	case IEEE80211_MODE_11B:
    717 		return CHANNEL_B;
    718 	case IEEE80211_MODE_11G:
    719 		return CHANNEL_PUREG;
    720 	case IEEE80211_MODE_TURBO:
    721 		return CHANNEL_T;
    722 	default:
    723 		panic("%s: unsupported mode %d\n", __func__, mode);
    724 		return 0;
    725 	}
    726 }
    727 
    728 #ifdef __NetBSD__
    729 static int
    730 ath_init(struct ifnet *ifp)
    731 {
    732 	return ath_init1((struct ath_softc *)ifp->if_softc);
    733 }
    734 #else
    735 static void
    736 ath_init(void *arg)
    737 {
    738 	(void)ath_init1((struct ath_softc *)arg);
    739 }
    740 #endif
    741 
    742 static int
    743 ath_init1(struct ath_softc *sc)
    744 {
    745 	struct ieee80211com *ic = &sc->sc_ic;
    746 	struct ifnet *ifp = &ic->ic_if;
    747 	struct ieee80211_node *ni;
    748 	enum ieee80211_phymode mode;
    749 	struct ath_hal *ah = sc->sc_ah;
    750 	HAL_STATUS status;
    751 	HAL_CHANNEL hchan;
    752 	int error = 0;
    753 	ath_softc_critsect_decl(s);
    754 
    755 	DPRINTF(("ath_init: if_flags 0x%x\n", ifp->if_flags));
    756 
    757 #ifdef __NetBSD__
    758 	if ((error = ath_enable(sc)) != 0)
    759 		return error;
    760 #endif
    761 
    762 	ath_softc_critsect_begin(sc, s);
    763 	/*
    764 	 * Stop anything previously setup.  This is safe
    765 	 * whether this is the first time through or not.
    766 	 */
    767 	ath_stop(ifp);
    768 
    769 	/*
    770 	 * The basic interface to setting the hardware in a good
    771 	 * state is ``reset''.  On return the hardware is known to
    772 	 * be powered up and with interrupts disabled.  This must
    773 	 * be followed by initialization of the appropriate bits
    774 	 * and then setup of the interrupt mask.
    775 	 */
    776 	hchan.channel = ic->ic_ibss_chan->ic_freq;
    777 	hchan.channelFlags = ath_chan2flags(ic, ic->ic_ibss_chan);
    778 	if (!ath_hal_reset(ah, ic->ic_opmode, &hchan, AH_FALSE, &status)) {
    779 		if_printf(ifp, "unable to reset hardware; hal status %u\n",
    780 			status);
    781 		error = -1;
    782 		goto done;
    783 	}
    784 
    785 	/*
    786 	 * Setup the hardware after reset: the key cache
    787 	 * is filled as needed and the receive engine is
    788 	 * set going.  Frame transmit is handled entirely
    789 	 * in the frame output path; there's nothing to do
    790 	 * here except setup the interrupt mask.
    791 	 */
    792 	if (ic->ic_flags & IEEE80211_F_WEPON)
    793 		ath_initkeytable(sc);
    794 	if ((error = ath_startrecv(sc)) != 0) {
    795 		if_printf(ifp, "unable to start recv logic\n");
    796 		goto done;
    797 	}
    798 
    799 	/*
    800 	 * Enable interrupts.
    801 	 */
    802 	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
    803 		  | HAL_INT_RXEOL | HAL_INT_RXORN
    804 		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
    805 	ath_hal_intrset(ah, sc->sc_imask);
    806 
    807 	ifp->if_flags |= IFF_RUNNING;
    808 	ic->ic_state = IEEE80211_S_INIT;
    809 
    810 	/*
    811 	 * The hardware should be ready to go now so it's safe
    812 	 * to kick the 802.11 state machine as it's likely to
    813 	 * immediately call back to us to send mgmt frames.
    814 	 */
    815 	ni = ic->ic_bss;
    816 	ni->ni_chan = ic->ic_ibss_chan;
    817 	mode = ieee80211_chan2mode(ic, ni->ni_chan);
    818 	if (mode != sc->sc_curmode)
    819 		ath_setcurmode(sc, mode);
    820 	if (ic->ic_opmode != IEEE80211_M_MONITOR)
    821 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
    822 	else
    823 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
    824 done:
    825 	ath_softc_critsect_end(sc, s);
    826 	return error;
    827 }
    828 
    829 static void
    830 ath_stop(struct ifnet *ifp)
    831 {
    832 	struct ieee80211com *ic = (struct ieee80211com *) ifp;
    833 	struct ath_softc *sc = ifp->if_softc;
    834 	struct ath_hal *ah = sc->sc_ah;
    835 	ath_softc_critsect_decl(s);
    836 
    837 	DPRINTF(("ath_stop: invalid %u if_flags 0x%x\n",
    838 		sc->sc_invalid, ifp->if_flags));
    839 
    840 	ath_softc_critsect_begin(sc, s);
    841 	if (ifp->if_flags & IFF_RUNNING) {
    842 		/*
    843 		 * Shutdown the hardware and driver:
    844 		 *    disable interrupts
    845 		 *    turn off timers
    846 		 *    clear transmit machinery
    847 		 *    clear receive machinery
    848 		 *    drain and release tx queues
    849 		 *    reclaim beacon resources
    850 		 *    reset 802.11 state machine
    851 		 *    power down hardware
    852 		 *
    853 		 * Note that some of this work is not possible if the
    854 		 * hardware is gone (invalid).
    855 		 */
    856 		ifp->if_flags &= ~IFF_RUNNING;
    857 		ifp->if_timer = 0;
    858 		if (!sc->sc_invalid)
    859 			ath_hal_intrset(ah, 0);
    860 		ath_draintxq(sc);
    861 		if (!sc->sc_invalid)
    862 			ath_stoprecv(sc);
    863 		else
    864 			sc->sc_rxlink = NULL;
    865 #ifdef __FreeBSD__
    866 		IF_DRAIN(&ifp->if_snd);
    867 #else
    868 		IF_PURGE(&ifp->if_snd);
    869 #endif
    870 		ath_beacon_free(sc);
    871 		ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
    872 		if (!sc->sc_invalid) {
    873 			ath_hal_setpower(ah, HAL_PM_FULL_SLEEP, 0);
    874 		}
    875 #ifdef __NetBSD__
    876 		ath_disable(sc);
    877 #endif
    878 	}
    879 	ath_softc_critsect_end(sc, s);
    880 }
    881 
    882 /*
    883  * Reset the hardware w/o losing operational state.  This is
    884  * basically a more efficient way of doing ath_stop, ath_init,
    885  * followed by state transitions to the current 802.11
    886  * operational state.  Used to recover from errors rx overrun
    887  * and to reset the hardware when rf gain settings must be reset.
    888  */
    889 static void
    890 ath_reset(struct ath_softc *sc)
    891 {
    892 	struct ieee80211com *ic = &sc->sc_ic;
    893 	struct ifnet *ifp = &ic->ic_if;
    894 	struct ath_hal *ah = sc->sc_ah;
    895 	struct ieee80211_channel *c;
    896 	HAL_STATUS status;
    897 	HAL_CHANNEL hchan;
    898 
    899 	/*
    900 	 * Convert to a HAL channel description with the flags
    901 	 * constrained to reflect the current operating mode.
    902 	 */
    903 	c = ic->ic_ibss_chan;
    904 	hchan.channel = c->ic_freq;
    905 	hchan.channelFlags = ath_chan2flags(ic, c);
    906 
    907 	ath_hal_intrset(ah, 0);		/* disable interrupts */
    908 	ath_draintxq(sc);		/* stop xmit side */
    909 	ath_stoprecv(sc);		/* stop recv side */
    910 	/* NB: indicate channel change so we do a full reset */
    911 	if (!ath_hal_reset(ah, ic->ic_opmode, &hchan, AH_TRUE, &status))
    912 		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
    913 			__func__, status);
    914 	ath_hal_intrset(ah, sc->sc_imask);
    915 	if (ath_startrecv(sc) != 0)	/* restart recv */
    916 		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
    917 	ath_start(ifp);			/* restart xmit */
    918 	if (ic->ic_state == IEEE80211_S_RUN)
    919 		ath_beacon_config(sc);	/* restart beacons */
    920 }
    921 
    922 static void
    923 ath_start(struct ifnet *ifp)
    924 {
    925 	struct ath_softc *sc = ifp->if_softc;
    926 	struct ath_hal *ah = sc->sc_ah;
    927 	struct ieee80211com *ic = &sc->sc_ic;
    928 	struct ieee80211_node *ni;
    929 	struct ath_buf *bf;
    930 	struct mbuf *m;
    931 	struct ieee80211_frame *wh;
    932 	ath_txbuf_critsect_decl(s);
    933 
    934 	if ((ifp->if_flags & IFF_RUNNING) == 0 || sc->sc_invalid)
    935 		return;
    936 	for (;;) {
    937 		/*
    938 		 * Grab a TX buffer and associated resources.
    939 		 */
    940 		ath_txbuf_critsect_begin(sc, s);
    941 		bf = TAILQ_FIRST(&sc->sc_txbuf);
    942 		if (bf != NULL)
    943 			TAILQ_REMOVE(&sc->sc_txbuf, bf, bf_list);
    944 		ath_txbuf_critsect_end(sc, s);
    945 		if (bf == NULL) {
    946 			DPRINTF(("ath_start: out of xmit buffers\n"));
    947 			sc->sc_stats.ast_tx_qstop++;
    948 			ifp->if_flags |= IFF_OACTIVE;
    949 			break;
    950 		}
    951 		/*
    952 		 * Poll the management queue for frames; they
    953 		 * have priority over normal data frames.
    954 		 */
    955 		IF_DEQUEUE(&ic->ic_mgtq, m);
    956 		if (m == NULL) {
    957 			/*
    958 			 * No data frames go out unless we're associated.
    959 			 */
    960 			if (ic->ic_state != IEEE80211_S_RUN) {
    961 				DPRINTF(("ath_start: ignore data packet, "
    962 					"state %u\n", ic->ic_state));
    963 				sc->sc_stats.ast_tx_discard++;
    964 				ath_txbuf_critsect_begin(sc, s);
    965 				TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
    966 				ath_txbuf_critsect_end(sc, s);
    967 				break;
    968 			}
    969 			IF_DEQUEUE(&ifp->if_snd, m);
    970 			if (m == NULL) {
    971 				ath_txbuf_critsect_begin(sc, s);
    972 				TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
    973 				ath_txbuf_critsect_end(sc, s);
    974 				break;
    975 			}
    976 			ifp->if_opackets++;
    977 
    978 #ifdef __NetBSD__
    979 #if NBPFILTER > 0
    980 			if (ifp->if_bpf)
    981 				bpf_mtap(ifp->if_bpf, m);
    982 #endif
    983 #endif
    984 #ifdef __FreeBSD__
    985 			BPF_MTAP(ifp, m);
    986 #endif
    987 			/*
    988 			 * Encapsulate the packet in prep for transmission.
    989 			 */
    990 			m = ieee80211_encap(ifp, m, &ni);
    991 			if (m == NULL) {
    992 				DPRINTF(("ath_start: encapsulation failure\n"));
    993 				sc->sc_stats.ast_tx_encap++;
    994 				goto bad;
    995 			}
    996 			wh = mtod(m, struct ieee80211_frame *);
    997 			if (ic->ic_flags & IEEE80211_F_WEPON)
    998 				wh->i_fc[1] |= IEEE80211_FC1_WEP;
    999 		} else {
   1000 			/*
   1001 			 * Hack!  The referenced node pointer is in the
   1002 			 * rcvif field of the packet header.  This is
   1003 			 * placed there by ieee80211_mgmt_output because
   1004 			 * we need to hold the reference with the frame
   1005 			 * and there's no other way (other than packet
   1006 			 * tags which we consider too expensive to use)
   1007 			 * to pass it along.
   1008 			 */
   1009 			ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
   1010 			m->m_pkthdr.rcvif = NULL;
   1011 
   1012 			wh = mtod(m, struct ieee80211_frame *);
   1013 			if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
   1014 			    IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
   1015 				/* fill time stamp */
   1016 				u_int64_t tsf;
   1017 				u_int32_t *tstamp;
   1018 
   1019 				tsf = ath_hal_gettsf64(ah);
   1020 				/* XXX: adjust 100us delay to xmit */
   1021 				tsf += 100;
   1022 				tstamp = (u_int32_t *)&wh[1];
   1023 				tstamp[0] = htole32(tsf & 0xffffffff);
   1024 				tstamp[1] = htole32(tsf >> 32);
   1025 			}
   1026 			sc->sc_stats.ast_tx_mgmt++;
   1027 		}
   1028 #if NBPFILTER > 0
   1029 		if (ic->ic_rawbpf)
   1030 			bpf_mtap(ic->ic_rawbpf, m);
   1031 #endif
   1032 
   1033 #if NBPFILTER > 0
   1034 		if (sc->sc_drvbpf) {
   1035 #ifdef __FreeBSD__
   1036 			struct mbuf *mb;
   1037 
   1038 			MGETHDR(mb, M_DONTWAIT, m->m_type);
   1039 			if (mb != NULL) {
   1040 				sc->sc_tx_th.wt_rate =
   1041 					ni->ni_rates.rs_rates[ni->ni_txrate];
   1042 
   1043 				mb->m_next = m;
   1044 				mb->m_data = (caddr_t)&sc->sc_tx_th;
   1045 				mb->m_len = sizeof(sc->sc_tx_th);
   1046 				mb->m_pkthdr.len += mb->m_len;
   1047 				bpf_mtap(sc->sc_drvbpf, mb);
   1048 				m_free(mb);
   1049 			}
   1050 #else
   1051 			struct mbuf mb;
   1052 
   1053 			M_COPY_PKTHDR(&mb, m);
   1054 			sc->sc_tx_th.wt_rate =
   1055 				ni->ni_rates.rs_rates[ni->ni_txrate];
   1056 
   1057 			mb.m_next = m;
   1058 			mb.m_data = (caddr_t)&sc->sc_tx_th;
   1059 			mb.m_len = sizeof(sc->sc_tx_th);
   1060 			mb.m_pkthdr.len += mb.m_len;
   1061 			bpf_mtap(sc->sc_drvbpf, &mb);
   1062 #endif
   1063 		}
   1064 #endif
   1065 
   1066 		if (ath_tx_start(sc, ni, bf, m)) {
   1067 	bad:
   1068 			ath_txbuf_critsect_begin(sc, s);
   1069 			TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   1070 			ath_txbuf_critsect_end(sc, s);
   1071 			ifp->if_oerrors++;
   1072 			if (ni && ni != ic->ic_bss)
   1073 				ieee80211_free_node(ic, ni);
   1074 			continue;
   1075 		}
   1076 
   1077 		sc->sc_tx_timer = 5;
   1078 		ifp->if_timer = 1;
   1079 	}
   1080 }
   1081 
   1082 static int
   1083 ath_media_change(struct ifnet *ifp)
   1084 {
   1085 	int error;
   1086 
   1087 	error = ieee80211_media_change(ifp);
   1088 	if (error == ENETRESET) {
   1089 		if ((ifp->if_flags & (IFF_RUNNING|IFF_UP)) ==
   1090 		    (IFF_RUNNING|IFF_UP))
   1091 			ath_init(ifp);		/* XXX lose error */
   1092 		error = 0;
   1093 	}
   1094 	return error;
   1095 }
   1096 
   1097 static void
   1098 ath_watchdog(struct ifnet *ifp)
   1099 {
   1100 	struct ath_softc *sc = ifp->if_softc;
   1101 	struct ieee80211com *ic = &sc->sc_ic;
   1102 
   1103 	ifp->if_timer = 0;
   1104 	if ((ifp->if_flags & IFF_RUNNING) == 0 || sc->sc_invalid)
   1105 		return;
   1106 	if (sc->sc_tx_timer) {
   1107 		if (--sc->sc_tx_timer == 0) {
   1108 			if_printf(ifp, "device timeout\n");
   1109 #ifdef AR_DEBUG
   1110 			if (ath_debug)
   1111 				ath_hal_dumpstate(sc->sc_ah);
   1112 #endif /* AR_DEBUG */
   1113 			ath_init(ifp);		/* XXX ath_reset??? */
   1114 			ifp->if_oerrors++;
   1115 			sc->sc_stats.ast_watchdog++;
   1116 			return;
   1117 		}
   1118 		ifp->if_timer = 1;
   1119 	}
   1120 	if (ic->ic_fixed_rate == -1) {
   1121 		/*
   1122 		 * Run the rate control algorithm if we're not
   1123 		 * locked at a fixed rate.
   1124 		 */
   1125 		if (ic->ic_opmode == IEEE80211_M_STA)
   1126 			ath_rate_ctl(sc, ic->ic_bss);
   1127 		else
   1128 			ieee80211_iterate_nodes(ic, ath_rate_ctl, sc);
   1129 	}
   1130 	ieee80211_watchdog(ifp);
   1131 }
   1132 
   1133 static int
   1134 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
   1135 {
   1136 	struct ath_softc *sc = ifp->if_softc;
   1137 	struct ifreq *ifr = (struct ifreq *)data;
   1138 	int error = 0;
   1139 	ath_softc_critsect_decl(s);
   1140 
   1141 	ath_softc_critsect_begin(sc, s);
   1142 	switch (cmd) {
   1143 	case SIOCSIFFLAGS:
   1144 		if (ifp->if_flags & IFF_UP) {
   1145 			if (ifp->if_flags & IFF_RUNNING) {
   1146 				/*
   1147 				 * To avoid rescanning another access point,
   1148 				 * do not call ath_init() here.  Instead,
   1149 				 * only reflect promisc mode settings.
   1150 				 */
   1151 				ath_mode_init(sc);
   1152 			} else {
   1153 				/*
   1154 				 * Beware of being called during detach to
   1155 				 * reset promiscuous mode.  In that case we
   1156 				 * will still be marked UP but not RUNNING.
   1157 				 * However trying to re-init the interface
   1158 				 * is the wrong thing to do as we've already
   1159 				 * torn down much of our state.  There's
   1160 				 * probably a better way to deal with this.
   1161 				 */
   1162 				if (!sc->sc_invalid)
   1163 					ath_init(ifp);	/* XXX lose error */
   1164 			}
   1165 		} else
   1166 			ath_stop(ifp);
   1167 		break;
   1168 	case SIOCADDMULTI:
   1169 	case SIOCDELMULTI:
   1170 #ifdef __FreeBSD__
   1171 		/*
   1172 		 * The upper layer has already installed/removed
   1173 		 * the multicast address(es), just recalculate the
   1174 		 * multicast filter for the card.
   1175 		 */
   1176 		if (ifp->if_flags & IFF_RUNNING)
   1177 			ath_mode_init(sc);
   1178 #endif
   1179 #ifdef __NetBSD__
   1180 		error = (cmd == SIOCADDMULTI) ?
   1181 		    ether_addmulti(ifr, &sc->sc_ic.ic_ec) :
   1182 		    ether_delmulti(ifr, &sc->sc_ic.ic_ec);
   1183 		if (error == ENETRESET) {
   1184 			if (ifp->if_flags & IFF_RUNNING)
   1185 				ath_mode_init(sc);
   1186 			error = 0;
   1187 		}
   1188 #endif
   1189 		break;
   1190 	case SIOCGATHSTATS:
   1191 		error = copyout(&sc->sc_stats,
   1192 				ifr->ifr_data, sizeof (sc->sc_stats));
   1193 		break;
   1194 	case SIOCGATHDIAG: {
   1195 		struct ath_diag *ad = (struct ath_diag *)data;
   1196 		struct ath_hal *ah = sc->sc_ah;
   1197 		void *data;
   1198 		u_int size;
   1199 
   1200 		if (ath_hal_getdiagstate(ah, ad->ad_id, &data, &size)) {
   1201 			if (size < ad->ad_size)
   1202 				ad->ad_size = size;
   1203 			if (data)
   1204 				error = copyout(data, ad->ad_data, ad->ad_size);
   1205 		} else
   1206 			error = EINVAL;
   1207 		break;
   1208 	}
   1209 	default:
   1210 		error = ieee80211_ioctl(ifp, cmd, data);
   1211 		if (error == ENETRESET) {
   1212 			if ((ifp->if_flags & (IFF_RUNNING|IFF_UP)) ==
   1213 			    (IFF_RUNNING|IFF_UP))
   1214 				ath_init(ifp);		/* XXX lose error */
   1215 			error = 0;
   1216 		}
   1217 		break;
   1218 	}
   1219 	ath_softc_critsect_end(sc, s);
   1220 	return error;
   1221 }
   1222 
   1223 /*
   1224  * Fill the hardware key cache with key entries.
   1225  */
   1226 static void
   1227 ath_initkeytable(struct ath_softc *sc)
   1228 {
   1229 	struct ieee80211com *ic = &sc->sc_ic;
   1230 	struct ath_hal *ah = sc->sc_ah;
   1231 	int i;
   1232 
   1233 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
   1234 		struct ieee80211_wepkey *k = &ic->ic_nw_keys[i];
   1235 		if (k->wk_len == 0)
   1236 			ath_hal_keyreset(ah, i);
   1237 		else
   1238 			/* XXX return value */
   1239 			/* NB: this uses HAL_KEYVAL == ieee80211_wepkey */
   1240 			ath_hal_keyset(ah, i, (const HAL_KEYVAL *) k);
   1241 	}
   1242 }
   1243 
   1244 static void
   1245 ath_mcastfilter_accum(caddr_t dl, u_int32_t (*mfilt)[2])
   1246 {
   1247 	u_int32_t val;
   1248 	u_int8_t pos;
   1249 
   1250 	val = LE_READ_4(dl + 0);
   1251 	pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
   1252 	val = LE_READ_4(dl + 3);
   1253 	pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
   1254 	pos &= 0x3f;
   1255 	(*mfilt)[pos / 32] |= (1 << (pos % 32));
   1256 }
   1257 
   1258 #ifdef __FreeBSD__
   1259 static void
   1260 ath_mcastfilter_compute(struct ath_softc *sc, u_int32_t (*mfilt)[2])
   1261 {
   1262 	struct ieee80211com *ic = &sc->sc_ic;
   1263 	struct ifnet *ifp = &ic->ic_if;
   1264 	struct ifmultiaddr *ifma;
   1265 
   1266 	TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
   1267 		caddr_t dl;
   1268 
   1269 		/* calculate XOR of eight 6bit values */
   1270 		dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
   1271 		ath_mcastfilter_accum(dl, &mfilt);
   1272 	}
   1273 }
   1274 #else
   1275 static void
   1276 ath_mcastfilter_compute(struct ath_softc *sc, u_int32_t (*mfilt)[2])
   1277 {
   1278 	struct ifnet *ifp = &sc->sc_ic.ic_if;
   1279 	struct ether_multi *enm;
   1280 	struct ether_multistep estep;
   1281 
   1282 	ETHER_FIRST_MULTI(estep, &sc->sc_ic.ic_ec, enm);
   1283 	while (enm != NULL) {
   1284 		/* XXX Punt on ranges. */
   1285 		if (!IEEE80211_ADDR_EQ(enm->enm_addrlo, enm->enm_addrhi)) {
   1286 			(*mfilt)[0] = (*mfilt)[1] = ~((u_int32_t)0);
   1287 			ifp->if_flags |= IFF_ALLMULTI;
   1288 			return;
   1289 		}
   1290 		ath_mcastfilter_accum(enm->enm_addrlo, mfilt);
   1291 		ETHER_NEXT_MULTI(estep, enm);
   1292 	}
   1293 	ifp->if_flags &= ~IFF_ALLMULTI;
   1294 }
   1295 #endif
   1296 
   1297 /*
   1298  * Calculate the receive filter according to the
   1299  * operating mode and state:
   1300  *
   1301  * o always accept unicast, broadcast, and multicast traffic
   1302  * o maintain current state of phy error reception
   1303  * o probe request frames are accepted only when operating in
   1304  *   hostap, adhoc, or monitor modes
   1305  * o enable promiscuous mode according to the interface state
   1306  * o accept beacons:
   1307  *   - when operating in adhoc mode so the 802.11 layer creates
   1308  *     node table entries for peers,
   1309  *   - when operating in station mode for collecting rssi data when
   1310  *     the station is otherwise quiet, or
   1311  *   - when scanning
   1312  */
   1313 static u_int32_t
   1314 ath_calcrxfilter(struct ath_softc *sc)
   1315 {
   1316 	struct ieee80211com *ic = &sc->sc_ic;
   1317 	struct ath_hal *ah = sc->sc_ah;
   1318 	struct ifnet *ifp = &ic->ic_if;
   1319 	u_int32_t rfilt;
   1320 
   1321 	rfilt = (ath_hal_getrxfilter(ah) & HAL_RX_FILTER_PHYERR)
   1322 	      | HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
   1323 	if (ic->ic_opmode != IEEE80211_M_STA)
   1324 		rfilt |= HAL_RX_FILTER_PROBEREQ;
   1325 	if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
   1326 	    (ifp->if_flags & IFF_PROMISC))
   1327 		rfilt |= HAL_RX_FILTER_PROM;
   1328 	if (ic->ic_opmode == IEEE80211_M_STA ||
   1329 	    ic->ic_opmode == IEEE80211_M_IBSS ||
   1330 	    ic->ic_state == IEEE80211_S_SCAN)
   1331 		rfilt |= HAL_RX_FILTER_BEACON;
   1332 	return rfilt;
   1333 }
   1334 
   1335 static void
   1336 ath_mode_init(struct ath_softc *sc)
   1337 {
   1338 #ifdef __FreeBSD__
   1339 	struct ieee80211com *ic = &sc->sc_ic;
   1340 #endif
   1341 	struct ath_hal *ah = sc->sc_ah;
   1342 	u_int32_t rfilt, mfilt[2];
   1343 
   1344 	/* configure rx filter */
   1345 	rfilt = ath_calcrxfilter(sc);
   1346 	ath_hal_setrxfilter(ah, rfilt);
   1347 
   1348 	/* configure operational mode */
   1349 	ath_hal_setopmode(ah);
   1350 
   1351 	/* calculate and install multicast filter */
   1352 #ifdef __FreeBSD__
   1353 	if ((ic->ic_if.if_flags & IFF_ALLMULTI) == 0) {
   1354 		mfilt[0] = mfilt[1] = 0;
   1355 		ath_mcastfilter_compute(sc, &mfilt);
   1356 	} else {
   1357 		mfilt[0] = mfilt[1] = ~0;
   1358 	}
   1359 #endif
   1360 #ifdef __NetBSD__
   1361 	mfilt[0] = mfilt[1] = 0;
   1362 	ath_mcastfilter_compute(sc, &mfilt);
   1363 #endif
   1364 	ath_hal_setmcastfilter(ah, mfilt[0], mfilt[1]);
   1365 	DPRINTF(("ath_mode_init: RX filter 0x%x, MC filter %08x:%08x\n",
   1366 		rfilt, mfilt[0], mfilt[1]));
   1367 }
   1368 
   1369 #ifdef __FreeBSD__
   1370 static void
   1371 ath_mbuf_load_cb(void *arg, bus_dma_segment_t *seg, int nseg, bus_size_t mapsize, int error)
   1372 {
   1373 	struct ath_buf *bf = arg;
   1374 
   1375 	KASSERT(nseg <= ATH_MAX_SCATTER,
   1376 		("ath_mbuf_load_cb: too many DMA segments %u", nseg));
   1377 	bf->bf_mapsize = mapsize;
   1378 	bf->bf_nseg = nseg;
   1379 	bcopy(seg, bf->bf_segs, nseg * sizeof (seg[0]));
   1380 }
   1381 #endif /* __FreeBSD__ */
   1382 
   1383 static struct mbuf *
   1384 ath_getmbuf(int flags, int type, u_int pktlen)
   1385 {
   1386 	struct mbuf *m;
   1387 
   1388 	KASSERT(pktlen <= MCLBYTES, ("802.11 packet too large: %u", pktlen));
   1389 #ifdef __FreeBSD__
   1390 	if (pktlen <= MHLEN)
   1391 		MGETHDR(m, flags, type);
   1392 	else
   1393 		m = m_getcl(flags, type, M_PKTHDR);
   1394 #else
   1395 	MGETHDR(m, flags, type);
   1396 	if (m != NULL && pktlen > MHLEN)
   1397 		MCLGET(m, flags);
   1398 #endif
   1399 	return m;
   1400 }
   1401 
   1402 static int
   1403 ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
   1404 {
   1405 	struct ieee80211com *ic = &sc->sc_ic;
   1406 	struct ifnet *ifp = &ic->ic_if;
   1407 	struct ath_hal *ah = sc->sc_ah;
   1408 	struct ieee80211_frame *wh;
   1409 	struct ath_buf *bf;
   1410 	struct ath_desc *ds;
   1411 	struct mbuf *m;
   1412 	int error, pktlen;
   1413 	u_int8_t *frm, rate;
   1414 	u_int16_t capinfo;
   1415 	struct ieee80211_rateset *rs;
   1416 	const HAL_RATE_TABLE *rt;
   1417 
   1418 	bf = sc->sc_bcbuf;
   1419 	if (bf->bf_m != NULL) {
   1420 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   1421 		m_freem(bf->bf_m);
   1422 		bf->bf_m = NULL;
   1423 		bf->bf_node = NULL;
   1424 	}
   1425 	/*
   1426 	 * NB: the beacon data buffer must be 32-bit aligned;
   1427 	 * we assume the mbuf routines will return us something
   1428 	 * with this alignment (perhaps should assert).
   1429 	 */
   1430 	rs = &ni->ni_rates;
   1431 	pktlen = sizeof (struct ieee80211_frame)
   1432 	       + 8 + 2 + 2 + 2+ni->ni_esslen + 2+rs->rs_nrates + 3 + 6;
   1433 	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
   1434 		pktlen += 2;
   1435 	m = ath_getmbuf(M_DONTWAIT, MT_DATA, pktlen);
   1436 	if (m == NULL) {
   1437 		DPRINTF(("ath_beacon_alloc: cannot get mbuf/cluster; size %u\n",
   1438 			pktlen));
   1439 		sc->sc_stats.ast_be_nombuf++;
   1440 		return ENOMEM;
   1441 	}
   1442 
   1443 	wh = mtod(m, struct ieee80211_frame *);
   1444 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
   1445 	    IEEE80211_FC0_SUBTYPE_BEACON;
   1446 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
   1447 	*(u_int16_t *)wh->i_dur = 0;
   1448 	memcpy(wh->i_addr1, ifp->if_broadcastaddr, IEEE80211_ADDR_LEN);
   1449 	memcpy(wh->i_addr2, ic->ic_myaddr, IEEE80211_ADDR_LEN);
   1450 	memcpy(wh->i_addr3, ni->ni_bssid, IEEE80211_ADDR_LEN);
   1451 	*(u_int16_t *)wh->i_seq = 0;
   1452 
   1453 	/*
   1454 	 * beacon frame format
   1455 	 *	[8] time stamp
   1456 	 *	[2] beacon interval
   1457 	 *	[2] cabability information
   1458 	 *	[tlv] ssid
   1459 	 *	[tlv] supported rates
   1460 	 *	[tlv] parameter set (IBSS)
   1461 	 *	[tlv] extended supported rates
   1462 	 */
   1463 	frm = (u_int8_t *)&wh[1];
   1464 	memset(frm, 0, 8);	/* timestamp is set by hardware */
   1465 	frm += 8;
   1466 	*(u_int16_t *)frm = htole16(ni->ni_intval);
   1467 	frm += 2;
   1468 	if (ic->ic_opmode == IEEE80211_M_IBSS)
   1469 		capinfo = IEEE80211_CAPINFO_IBSS;
   1470 	else
   1471 		capinfo = IEEE80211_CAPINFO_ESS;
   1472 	if (ic->ic_flags & IEEE80211_F_WEPON)
   1473 		capinfo |= IEEE80211_CAPINFO_PRIVACY;
   1474 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
   1475 	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
   1476 		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
   1477 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
   1478 		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
   1479 	*(u_int16_t *)frm = htole16(capinfo);
   1480 	frm += 2;
   1481 	*frm++ = IEEE80211_ELEMID_SSID;
   1482 	*frm++ = ni->ni_esslen;
   1483 	memcpy(frm, ni->ni_essid, ni->ni_esslen);
   1484 	frm += ni->ni_esslen;
   1485 	frm = ieee80211_add_rates(frm, rs);
   1486 	*frm++ = IEEE80211_ELEMID_DSPARMS;
   1487 	*frm++ = 1;
   1488 	*frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
   1489 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
   1490 		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
   1491 		*frm++ = 2;
   1492 		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
   1493 	} else {
   1494 		/* TODO: TIM */
   1495 		*frm++ = IEEE80211_ELEMID_TIM;
   1496 		*frm++ = 4;	/* length */
   1497 		*frm++ = 0;	/* DTIM count */
   1498 		*frm++ = 1;	/* DTIM period */
   1499 		*frm++ = 0;	/* bitmap control */
   1500 		*frm++ = 0;	/* Partial Virtual Bitmap (variable length) */
   1501 	}
   1502 	frm = ieee80211_add_xrates(frm, rs);
   1503 	m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
   1504 	KASSERT(m->m_pkthdr.len <= pktlen,
   1505 		("beacon bigger than expected, len %u calculated %u",
   1506 		m->m_pkthdr.len, pktlen));
   1507 
   1508 	DPRINTF2(("ath_beacon_alloc: m %p len %u\n", m, m->m_len));
   1509 	error = ath_buf_dmamap_load_mbuf(sc->sc_dmat, bf, m, BUS_DMA_NOWAIT);
   1510 	if (error != 0) {
   1511 		m_freem(m);
   1512 		return error;
   1513 	}
   1514 	KASSERT(bf->bf_nseg == 1,
   1515 		("ath_beacon_alloc: multi-segment packet; nseg %u",
   1516 		bf->bf_nseg));
   1517 	bf->bf_m = m;
   1518 
   1519 	/* setup descriptors */
   1520 	ds = bf->bf_desc;
   1521 
   1522 	ds->ds_link = 0;
   1523 	ds->ds_data = bf->bf_segs[0].ds_addr;
   1524 
   1525 	DPRINTF2(("%s: segaddr %p seglen %u\n", __func__,
   1526 	    (caddr_t)bf->bf_segs[0].ds_addr, (u_int)bf->bf_segs[0].ds_len));
   1527 
   1528 	/*
   1529 	 * Calculate rate code.
   1530 	 * XXX everything at min xmit rate
   1531 	 */
   1532 	rt = sc->sc_currates;
   1533 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
   1534 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
   1535 		rate = rt->info[0].rateCode | rt->info[0].shortPreamble;
   1536 	else
   1537 		rate = rt->info[0].rateCode;
   1538 	if (!ath_hal_setuptxdesc(ah, ds
   1539 		, m->m_pkthdr.len + IEEE80211_CRC_LEN	/* packet length */
   1540 		, sizeof(struct ieee80211_frame)	/* header length */
   1541 		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
   1542 		, 0x20				/* txpower XXX */
   1543 		, rate, 1			/* series 0 rate/tries */
   1544 		, HAL_TXKEYIX_INVALID		/* no encryption */
   1545 		, 0				/* antenna mode */
   1546 		, HAL_TXDESC_NOACK		/* no ack for beacons */
   1547 		, 0				/* rts/cts rate */
   1548 		, 0				/* rts/cts duration */
   1549 	)) {
   1550 		printf("%s: ath_hal_setuptxdesc failed\n", __func__);
   1551 		return -1;
   1552 	}
   1553 	/* NB: beacon's BufLen must be a multiple of 4 bytes */
   1554 	/* XXX verify mbuf data area covers this roundup */
   1555 	if (!ath_hal_filltxdesc(ah, ds
   1556 		, roundup(bf->bf_segs[0].ds_len, 4)	/* buffer length */
   1557 		, AH_TRUE				/* first segment */
   1558 		, AH_TRUE				/* last segment */
   1559 	)) {
   1560 		printf("%s: ath_hal_filltxdesc failed\n", __func__);
   1561 		return -1;
   1562 	}
   1563 
   1564 	/* XXX it is not appropriate to bus_dmamap_sync? -dcy */
   1565 
   1566 	return 0;
   1567 }
   1568 
   1569 static void
   1570 ath_beacon_proc(void *arg, int pending)
   1571 {
   1572 	struct ath_softc *sc = arg;
   1573 	struct ieee80211com *ic = &sc->sc_ic;
   1574 	struct ath_buf *bf = sc->sc_bcbuf;
   1575 	struct ath_hal *ah = sc->sc_ah;
   1576 
   1577 	DPRINTF2(("%s: pending %u\n", __func__, pending));
   1578 	if (ic->ic_opmode == IEEE80211_M_STA ||
   1579 	    bf == NULL || bf->bf_m == NULL) {
   1580 		DPRINTF(("%s: ic_flags=%x bf=%p bf_m=%p\n",
   1581 			__func__, ic->ic_flags, bf, bf ? bf->bf_m : NULL));
   1582 		return;
   1583 	}
   1584 	/* TODO: update beacon to reflect PS poll state */
   1585 	if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
   1586 		DPRINTF(("%s: beacon queue %u did not stop?",
   1587 			__func__, sc->sc_bhalq));
   1588 		return;			/* busy, XXX is this right? */
   1589 	}
   1590 	ath_buf_dmamap_sync(sc->sc_dmat, bf, BUS_DMASYNC_PREWRITE);
   1591 
   1592 	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
   1593 	ath_hal_txstart(ah, sc->sc_bhalq);
   1594 	DPRINTF2(("%s: BCDP%u = %p (%p)\n", __func__,
   1595 		sc->sc_bhalq, (caddr_t)bf->bf_daddr, bf->bf_desc));
   1596 }
   1597 
   1598 static void
   1599 ath_beacon_free(struct ath_softc *sc)
   1600 {
   1601 	struct ath_buf *bf = sc->sc_bcbuf;
   1602 
   1603 	if (bf->bf_m != NULL) {
   1604 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   1605 		m_freem(bf->bf_m);
   1606 		bf->bf_m = NULL;
   1607 		bf->bf_node = NULL;
   1608 	}
   1609 }
   1610 
   1611 /*
   1612  * Configure the beacon and sleep timers.
   1613  *
   1614  * When operating as an AP this resets the TSF and sets
   1615  * up the hardware to notify us when we need to issue beacons.
   1616  *
   1617  * When operating in station mode this sets up the beacon
   1618  * timers according to the timestamp of the last received
   1619  * beacon and the current TSF, configures PCF and DTIM
   1620  * handling, programs the sleep registers so the hardware
   1621  * will wakeup in time to receive beacons, and configures
   1622  * the beacon miss handling so we'll receive a BMISS
   1623  * interrupt when we stop seeing beacons from the AP
   1624  * we've associated with.
   1625  */
   1626 static void
   1627 ath_beacon_config(struct ath_softc *sc)
   1628 {
   1629 	struct ath_hal *ah = sc->sc_ah;
   1630 	struct ieee80211com *ic = &sc->sc_ic;
   1631 	struct ieee80211_node *ni = ic->ic_bss;
   1632 	u_int32_t nexttbtt;
   1633 
   1634 	nexttbtt = (LE_READ_4(ni->ni_tstamp + 4) << 22) |
   1635 	    (LE_READ_4(ni->ni_tstamp) >> 10);
   1636 	DPRINTF(("%s: nexttbtt=%u\n", __func__, nexttbtt));
   1637 	nexttbtt += ni->ni_intval;
   1638 	if (ic->ic_opmode == IEEE80211_M_STA) {
   1639 		HAL_BEACON_STATE bs;
   1640 		u_int32_t bmisstime;
   1641 
   1642 		/* NB: no PCF support right now */
   1643 		memset(&bs, 0, sizeof(bs));
   1644 		bs.bs_intval = ni->ni_intval;
   1645 		bs.bs_nexttbtt = nexttbtt;
   1646 		bs.bs_dtimperiod = bs.bs_intval;
   1647 		bs.bs_nextdtim = nexttbtt;
   1648 		/*
   1649 		 * Calculate the number of consecutive beacons to miss
   1650 		 * before taking a BMISS interrupt.  The configuration
   1651 		 * is specified in ms, so we need to convert that to
   1652 		 * TU's and then calculate based on the beacon interval.
   1653 		 * Note that we clamp the result to at most 10 beacons.
   1654 		 */
   1655 		bmisstime = (ic->ic_bmisstimeout * 1000) / 1024;
   1656 		bs.bs_bmissthreshold = howmany(bmisstime,ni->ni_intval);
   1657 		if (bs.bs_bmissthreshold > 10)
   1658 			bs.bs_bmissthreshold = 10;
   1659 		else if (bs.bs_bmissthreshold <= 0)
   1660 			bs.bs_bmissthreshold = 1;
   1661 
   1662 		/*
   1663 		 * Calculate sleep duration.  The configuration is
   1664 		 * given in ms.  We insure a multiple of the beacon
   1665 		 * period is used.  Also, if the sleep duration is
   1666 		 * greater than the DTIM period then it makes senses
   1667 		 * to make it a multiple of that.
   1668 		 *
   1669 		 * XXX fixed at 100ms
   1670 		 */
   1671 		bs.bs_sleepduration =
   1672 			roundup((100 * 1000) / 1024, bs.bs_intval);
   1673 		if (bs.bs_sleepduration > bs.bs_dtimperiod)
   1674 			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
   1675 
   1676 		DPRINTF(("%s: intval %u nexttbtt %u dtim %u nextdtim %u bmiss %u sleep %u\n"
   1677 			, __func__
   1678 			, bs.bs_intval
   1679 			, bs.bs_nexttbtt
   1680 			, bs.bs_dtimperiod
   1681 			, bs.bs_nextdtim
   1682 			, bs.bs_bmissthreshold
   1683 			, bs.bs_sleepduration
   1684 		));
   1685 		ath_hal_intrset(ah, 0);
   1686 		/*
   1687 		 * Reset our tsf so the hardware will update the
   1688 		 * tsf register to reflect timestamps found in
   1689 		 * received beacons.
   1690 		 */
   1691 		ath_hal_resettsf(ah);
   1692 		ath_hal_beacontimers(ah, &bs, 0/*XXX*/, 0, 0);
   1693 		sc->sc_imask |= HAL_INT_BMISS;
   1694 		ath_hal_intrset(ah, sc->sc_imask);
   1695 	} else {
   1696 		DPRINTF(("%s: intval %u nexttbtt %u\n",
   1697 			__func__, ni->ni_intval, nexttbtt));
   1698 		ath_hal_intrset(ah, 0);
   1699 		ath_hal_beaconinit(ah, nexttbtt, ni->ni_intval);
   1700 		if (ic->ic_opmode != IEEE80211_M_MONITOR)
   1701 			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
   1702 		ath_hal_intrset(ah, sc->sc_imask);
   1703 	}
   1704 }
   1705 
   1706 #ifdef __FreeBSD__
   1707 static void
   1708 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
   1709 {
   1710 	bus_addr_t *paddr = (bus_addr_t*) arg;
   1711 	*paddr = segs->ds_addr;
   1712 }
   1713 #endif
   1714 
   1715 #ifdef __FreeBSD__
   1716 static int
   1717 ath_desc_alloc(struct ath_softc *sc)
   1718 {
   1719 	int i, bsize, error;
   1720 	struct ath_desc *ds;
   1721 	struct ath_buf *bf;
   1722 
   1723 	/* allocate descriptors */
   1724 	sc->sc_desc_len = sizeof(struct ath_desc) *
   1725 				(ATH_TXBUF * ATH_TXDESC + ATH_RXBUF + 1);
   1726 	error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT, &sc->sc_ddmamap);
   1727 	if (error != 0)
   1728 		return error;
   1729 
   1730 	error = bus_dmamem_alloc(sc->sc_dmat, (void**) &sc->sc_desc,
   1731 				 BUS_DMA_NOWAIT, &sc->sc_ddmamap);
   1732 
   1733 	if (error != 0)
   1734 		goto fail0;
   1735 
   1736 	error = bus_dmamap_load(sc->sc_dmat, sc->sc_ddmamap,
   1737 				sc->sc_desc, sc->sc_desc_len,
   1738 				ath_load_cb, &sc->sc_desc_paddr,
   1739 				BUS_DMA_NOWAIT);
   1740 	if (error != 0)
   1741 		goto fail1;
   1742 
   1743 	ds = sc->sc_desc;
   1744 	DPRINTF(("ath_desc_alloc: DMA map: %p (%d) -> %p (%lu)\n",
   1745 	    ds, sc->sc_desc_len,
   1746 	    (caddr_t) sc->sc_desc_paddr, /*XXX*/ (u_long) sc->sc_desc_len));
   1747 
   1748 	/* allocate buffers */
   1749 	bsize = sizeof(struct ath_buf) * (ATH_TXBUF + ATH_RXBUF + 1);
   1750 	bf = malloc(bsize, M_DEVBUF, M_NOWAIT | M_ZERO);
   1751 	if (bf == NULL) {
   1752 		printf("%s: unable to allocate Tx/Rx buffers\n",
   1753 		    sc->sc_dev.dv_xname);
   1754 		error = -1;
   1755 		goto fail2;
   1756 	}
   1757 	sc->sc_bufptr = bf;
   1758 
   1759 	TAILQ_INIT(&sc->sc_rxbuf);
   1760 	for (i = 0; i < ATH_RXBUF; i++, bf++, ds++) {
   1761 		bf->bf_desc = ds;
   1762 		bf->bf_daddr = sc->sc_desc_paddr +
   1763 		    ((caddr_t)ds - (caddr_t)sc->sc_desc);
   1764 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
   1765 					  &bf->bf_dmamap);
   1766 		if (error != 0)
   1767 			break;
   1768 		TAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
   1769 	}
   1770 
   1771 	TAILQ_INIT(&sc->sc_txbuf);
   1772 	for (i = 0; i < ATH_TXBUF; i++, bf++, ds += ATH_TXDESC) {
   1773 		bf->bf_desc = ds;
   1774 		bf->bf_daddr = sc->sc_desc_paddr +
   1775 		    ((caddr_t)ds - (caddr_t)sc->sc_desc);
   1776 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
   1777 					  &bf->bf_dmamap);
   1778 		if (error != 0)
   1779 			break;
   1780 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   1781 	}
   1782 	TAILQ_INIT(&sc->sc_txq);
   1783 
   1784 	/* beacon buffer */
   1785 	bf->bf_desc = ds;
   1786 	bf->bf_daddr = sc->sc_desc_paddr + ((caddr_t)ds - (caddr_t)sc->sc_desc);
   1787 	error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT, &bf->bf_dmamap);
   1788 	if (error != 0)
   1789 		return error;
   1790 	sc->sc_bcbuf = bf;
   1791 	return 0;
   1792 
   1793 fail2:
   1794 	bus_dmamap_unload(sc->sc_dmat, sc->sc_ddmamap);
   1795 fail1:
   1796 	bus_dmamem_free(sc->sc_dmat, sc->sc_desc, sc->sc_ddmamap);
   1797 fail0:
   1798 	bus_dmamap_destroy(sc->sc_dmat, sc->sc_ddmamap);
   1799 	sc->sc_ddmamap = NULL;
   1800 	return error;
   1801 }
   1802 #else
   1803 static int
   1804 ath_desc_alloc(struct ath_softc *sc)
   1805 {
   1806 	int i, bsize, error = -1;
   1807 	struct ath_desc *ds;
   1808 	struct ath_buf *bf;
   1809 
   1810 	/* allocate descriptors */
   1811 	sc->sc_desc_len = sizeof(struct ath_desc) *
   1812 				(ATH_TXBUF * ATH_TXDESC + ATH_RXBUF + 1);
   1813 	if ((error = bus_dmamem_alloc(sc->sc_dmat, sc->sc_desc_len, PAGE_SIZE,
   1814 	    0, &sc->sc_dseg, 1, &sc->sc_dnseg, 0)) != 0) {
   1815 		printf("%s: unable to allocate control data, error = %d\n",
   1816 		    sc->sc_dev.dv_xname, error);
   1817 		goto fail0;
   1818 	}
   1819 
   1820 	if ((error = bus_dmamem_map(sc->sc_dmat, &sc->sc_dseg, sc->sc_dnseg,
   1821 	    sc->sc_desc_len, (caddr_t *)&sc->sc_desc, BUS_DMA_COHERENT)) != 0) {
   1822 		printf("%s: unable to map control data, error = %d\n",
   1823 		    sc->sc_dev.dv_xname, error);
   1824 		goto fail1;
   1825 	}
   1826 
   1827 	if ((error = bus_dmamap_create(sc->sc_dmat, sc->sc_desc_len, 1,
   1828 	    sc->sc_desc_len, 0, 0, &sc->sc_ddmamap)) != 0) {
   1829 		printf("%s: unable to create control data DMA map, "
   1830 		    "error = %d\n", sc->sc_dev.dv_xname, error);
   1831 		goto fail2;
   1832 	}
   1833 
   1834 	if ((error = bus_dmamap_load(sc->sc_dmat, sc->sc_ddmamap, sc->sc_desc,
   1835 	    sc->sc_desc_len, NULL, 0)) != 0) {
   1836 		printf("%s: unable to load control data DMA map, error = %d\n",
   1837 		    sc->sc_dev.dv_xname, error);
   1838 		goto fail3;
   1839 	}
   1840 
   1841 	ds = sc->sc_desc;
   1842 	sc->sc_desc_paddr = sc->sc_ddmamap->dm_segs[0].ds_addr;
   1843 
   1844 	DPRINTF(("ath_desc_alloc: DMA map: %p (%lu) -> %p (%lu)\n",
   1845 	    ds, (u_long)sc->sc_desc_len,
   1846 	    (caddr_t) sc->sc_desc_paddr, /*XXX*/ (u_long) sc->sc_desc_len));
   1847 
   1848 	/* allocate buffers */
   1849 	bsize = sizeof(struct ath_buf) * (ATH_TXBUF + ATH_RXBUF + 1);
   1850 	bf = malloc(bsize, M_DEVBUF, M_NOWAIT | M_ZERO);
   1851 	if (bf == NULL) {
   1852 		printf("%s: unable to allocate Tx/Rx buffers\n",
   1853 		    sc->sc_dev.dv_xname);
   1854 		error = ENOMEM;
   1855 		goto fail3;
   1856 	}
   1857 	sc->sc_bufptr = bf;
   1858 
   1859 	TAILQ_INIT(&sc->sc_rxbuf);
   1860 	for (i = 0; i < ATH_RXBUF; i++, bf++, ds++) {
   1861 		bf->bf_desc = ds;
   1862 		bf->bf_daddr = sc->sc_desc_paddr +
   1863 		    ((caddr_t)ds - (caddr_t)sc->sc_desc);
   1864 		if ((error = bus_dmamap_create(sc->sc_dmat, MCLBYTES, 1,
   1865 		    MCLBYTES, 0, 0, &bf->bf_dmamap)) != 0) {
   1866 			printf("%s: unable to create Rx dmamap, error = %d\n",
   1867 			    sc->sc_dev.dv_xname, error);
   1868 			goto fail4;
   1869 		}
   1870 		TAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
   1871 	}
   1872 
   1873 	TAILQ_INIT(&sc->sc_txbuf);
   1874 	for (i = 0; i < ATH_TXBUF; i++, bf++, ds += ATH_TXDESC) {
   1875 		bf->bf_desc = ds;
   1876 		bf->bf_daddr = sc->sc_desc_paddr +
   1877 		    ((caddr_t)ds - (caddr_t)sc->sc_desc);
   1878 		if ((error = bus_dmamap_create(sc->sc_dmat, MCLBYTES,
   1879 		    ATH_TXDESC, MCLBYTES, 0, 0, &bf->bf_dmamap)) != 0) {
   1880 			printf("%s: unable to create Tx dmamap, error = %d\n",
   1881 			    sc->sc_dev.dv_xname, error);
   1882 			goto fail5;
   1883 		}
   1884 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   1885 	}
   1886 	TAILQ_INIT(&sc->sc_txq);
   1887 
   1888 	/* beacon buffer */
   1889 	bf->bf_desc = ds;
   1890 	bf->bf_daddr = sc->sc_desc_paddr + ((caddr_t)ds - (caddr_t)sc->sc_desc);
   1891 	if ((error = bus_dmamap_create(sc->sc_dmat, MCLBYTES, 1, MCLBYTES, 0, 0,
   1892 	    &bf->bf_dmamap)) != 0) {
   1893 		printf("%s: unable to create beacon dmamap, error = %d\n",
   1894 		    sc->sc_dev.dv_xname, error);
   1895 		goto fail5;
   1896 	}
   1897 	sc->sc_bcbuf = bf;
   1898 	return 0;
   1899 
   1900 fail5:
   1901 	for (i = ATH_RXBUF; i < ATH_RXBUF + ATH_TXBUF; i++) {
   1902 		if (sc->sc_bufptr[i].bf_dmamap == NULL)
   1903 			continue;
   1904 		bus_dmamap_destroy(sc->sc_dmat, sc->sc_bufptr[i].bf_dmamap);
   1905 	}
   1906 fail4:
   1907 	for (i = 0; i < ATH_RXBUF; i++) {
   1908 		if (sc->sc_bufptr[i].bf_dmamap == NULL)
   1909 			continue;
   1910 		bus_dmamap_destroy(sc->sc_dmat, sc->sc_bufptr[i].bf_dmamap);
   1911 	}
   1912 fail3:
   1913 	bus_dmamap_unload(sc->sc_dmat, sc->sc_ddmamap);
   1914 fail2:
   1915 	bus_dmamap_destroy(sc->sc_dmat, sc->sc_ddmamap);
   1916 	sc->sc_ddmamap = NULL;
   1917 fail1:
   1918 	bus_dmamem_unmap(sc->sc_dmat, (caddr_t)sc->sc_desc, sc->sc_desc_len);
   1919 fail0:
   1920 	bus_dmamem_free(sc->sc_dmat, &sc->sc_dseg, sc->sc_dnseg);
   1921 	return error;
   1922 }
   1923 #endif
   1924 
   1925 static void
   1926 ath_desc_free(struct ath_softc *sc)
   1927 {
   1928 	struct ath_buf *bf;
   1929 
   1930 #ifdef __FreeBSD__
   1931 	bus_dmamap_unload(sc->sc_dmat, sc->sc_ddmamap);
   1932 	bus_dmamem_free(sc->sc_dmat, sc->sc_desc, sc->sc_ddmamap);
   1933 	bus_dmamap_destroy(sc->sc_dmat, sc->sc_ddmamap);
   1934 #else
   1935 	bus_dmamap_unload(sc->sc_dmat, sc->sc_ddmamap);
   1936 	bus_dmamap_destroy(sc->sc_dmat, sc->sc_ddmamap);
   1937 	bus_dmamem_free(sc->sc_dmat, &sc->sc_dseg, sc->sc_dnseg);
   1938 #endif
   1939 
   1940 	TAILQ_FOREACH(bf, &sc->sc_txq, bf_list) {
   1941 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   1942 		bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
   1943 		m_freem(bf->bf_m);
   1944 	}
   1945 	TAILQ_FOREACH(bf, &sc->sc_txbuf, bf_list)
   1946 		bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
   1947 	TAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
   1948 		if (bf->bf_m) {
   1949 			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   1950 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
   1951 			m_freem(bf->bf_m);
   1952 			bf->bf_m = NULL;
   1953 		}
   1954 	}
   1955 	if (sc->sc_bcbuf != NULL) {
   1956 		bus_dmamap_unload(sc->sc_dmat, sc->sc_bcbuf->bf_dmamap);
   1957 		bus_dmamap_destroy(sc->sc_dmat, sc->sc_bcbuf->bf_dmamap);
   1958 		sc->sc_bcbuf = NULL;
   1959 	}
   1960 
   1961 	TAILQ_INIT(&sc->sc_rxbuf);
   1962 	TAILQ_INIT(&sc->sc_txbuf);
   1963 	TAILQ_INIT(&sc->sc_txq);
   1964 	free(sc->sc_bufptr, M_DEVBUF);
   1965 	sc->sc_bufptr = NULL;
   1966 }
   1967 
   1968 static struct ieee80211_node *
   1969 ath_node_alloc(struct ieee80211com *ic)
   1970 {
   1971 	struct ath_node *an =
   1972 		malloc(sizeof(struct ath_node), M_DEVBUF, M_NOWAIT | M_ZERO);
   1973 	if (an) {
   1974 		int i;
   1975 		for (i = 0; i < ATH_RHIST_SIZE; i++)
   1976 			an->an_rx_hist[i].arh_ticks = ATH_RHIST_NOTIME;
   1977 		an->an_rx_hist_next = ATH_RHIST_SIZE-1;
   1978 		return &an->an_node;
   1979 	} else
   1980 		return NULL;
   1981 }
   1982 
   1983 static void
   1984 ath_node_free(struct ieee80211com *ic, struct ieee80211_node *ni)
   1985 {
   1986 	struct ath_softc *sc = ic->ic_if.if_softc;
   1987 	struct ath_buf *bf;
   1988 
   1989 	TAILQ_FOREACH(bf, &sc->sc_txq, bf_list) {
   1990 		if (bf->bf_node == ni)
   1991 			bf->bf_node = NULL;
   1992 	}
   1993 	free(ni, M_DEVBUF);
   1994 }
   1995 
   1996 static void
   1997 ath_node_copy(struct ieee80211com *ic,
   1998 	struct ieee80211_node *dst, const struct ieee80211_node *src)
   1999 {
   2000 	*(struct ath_node *)dst = *(const struct ath_node *)src;
   2001 }
   2002 
   2003 static u_int8_t
   2004 ath_node_getrssi(struct ieee80211com *ic, struct ieee80211_node *ni)
   2005 {
   2006 	struct ath_node *an = ATH_NODE(ni);
   2007 	int i, now, nsamples, rssi;
   2008 
   2009 	/*
   2010 	 * Calculate the average over the last second of sampled data.
   2011 	 */
   2012 	now = ATH_TICKS();
   2013 	nsamples = 0;
   2014 	rssi = 0;
   2015 	i = an->an_rx_hist_next;
   2016 	do {
   2017 		struct ath_recv_hist *rh = &an->an_rx_hist[i];
   2018 		if (rh->arh_ticks == ATH_RHIST_NOTIME)
   2019 			goto done;
   2020 		if (now - rh->arh_ticks > hz)
   2021 			goto done;
   2022 		rssi += rh->arh_rssi;
   2023 		nsamples++;
   2024 		if (i == 0)
   2025 			i = ATH_RHIST_SIZE-1;
   2026 		else
   2027 			i--;
   2028 	} while (i != an->an_rx_hist_next);
   2029 done:
   2030 	/*
   2031 	 * Return either the average or the last known
   2032 	 * value if there is no recent data.
   2033 	 */
   2034 	return (nsamples ? rssi / nsamples : an->an_rx_hist[i].arh_rssi);
   2035 }
   2036 
   2037 static int
   2038 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
   2039 {
   2040 	struct ath_hal *ah = sc->sc_ah;
   2041 	int error;
   2042 	struct mbuf *m;
   2043 	struct ath_desc *ds;
   2044 
   2045 	m = bf->bf_m;
   2046 	if (m == NULL) {
   2047 		/*
   2048 		 * NB: by assigning a page to the rx dma buffer we
   2049 		 * implicitly satisfy the Atheros requirement that
   2050 		 * this buffer be cache-line-aligned and sized to be
   2051 		 * multiple of the cache line size.  Not doing this
   2052 		 * causes weird stuff to happen (for the 5210 at least).
   2053 		 */
   2054 		m = ath_getmbuf(M_DONTWAIT, MT_DATA, MCLBYTES);
   2055 		if (m == NULL) {
   2056 			DPRINTF(("ath_rxbuf_init: no mbuf/cluster\n"));
   2057 			sc->sc_stats.ast_rx_nombuf++;
   2058 			return ENOMEM;
   2059 		}
   2060 		bf->bf_m = m;
   2061 		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
   2062 
   2063 		error = ath_buf_dmamap_load_mbuf(sc->sc_dmat, bf, m,
   2064 		                                 BUS_DMA_NOWAIT);
   2065 		if (error != 0) {
   2066 			DPRINTF(("ath_rxbuf_init: ath_buf_dmamap_load_mbuf failed;"
   2067 				" error %d\n", error));
   2068 			sc->sc_stats.ast_rx_busdma++;
   2069 			return error;
   2070 		}
   2071 		KASSERT(bf->bf_nseg == 1,
   2072 			("ath_rxbuf_init: multi-segment packet; nseg %u",
   2073 			bf->bf_nseg));
   2074 	}
   2075 	ath_buf_dmamap_sync(sc->sc_dmat, bf, BUS_DMASYNC_PREREAD);
   2076 
   2077 	/*
   2078 	 * Setup descriptors.  For receive we always terminate
   2079 	 * the descriptor list with a self-linked entry so we'll
   2080 	 * not get overrun under high load (as can happen with a
   2081 	 * 5212 when ANI processing enables PHY errors).
   2082 	 *
   2083 	 * To insure the last descriptor is self-linked we create
   2084 	 * each descriptor as self-linked and add it to the end.  As
   2085 	 * each additional descriptor is added the previous self-linked
   2086 	 * entry is ``fixed'' naturally.  This should be safe even
   2087 	 * if DMA is happening.  When processing RX interrupts we
   2088 	 * never remove/process the last, self-linked, entry on the
   2089 	 * descriptor list.  This insures the hardware always has
   2090 	 * someplace to write a new frame.
   2091 	 */
   2092 	ds = bf->bf_desc;
   2093 	ds->ds_link = bf->bf_daddr;	/* link to self */
   2094 	ds->ds_data = bf->bf_segs[0].ds_addr;
   2095 	ath_hal_setuprxdesc(ah, ds
   2096 		, m->m_len		/* buffer size */
   2097 		, 0
   2098 	);
   2099 
   2100 	if (sc->sc_rxlink != NULL)
   2101 		*sc->sc_rxlink = bf->bf_daddr;
   2102 	sc->sc_rxlink = &ds->ds_link;
   2103 	return 0;
   2104 }
   2105 
   2106 static void
   2107 ath_rx_proc(void *arg, int npending)
   2108 {
   2109 #define	PA2DESC(_sc, _pa) \
   2110 	((struct ath_desc *)((caddr_t)(_sc)->sc_desc + \
   2111 		((_pa) - (_sc)->sc_desc_paddr)))
   2112 	struct ath_softc *sc = arg;
   2113 	struct ath_buf *bf;
   2114 	struct ieee80211com *ic = &sc->sc_ic;
   2115 	struct ifnet *ifp = &ic->ic_if;
   2116 	struct ath_hal *ah = sc->sc_ah;
   2117 	struct ath_desc *ds;
   2118 	struct mbuf *m;
   2119 	struct ieee80211_frame *wh, whbuf;
   2120 	struct ieee80211_node *ni;
   2121 	struct ath_node *an;
   2122 	struct ath_recv_hist *rh;
   2123 	int len;
   2124 	u_int phyerr;
   2125 	HAL_STATUS status;
   2126 
   2127 	DPRINTF2(("ath_rx_proc: pending %u\n", npending));
   2128 	do {
   2129 		bf = TAILQ_FIRST(&sc->sc_rxbuf);
   2130 		if (bf == NULL) {		/* NB: shouldn't happen */
   2131 			if_printf(ifp, "ath_rx_proc: no buffer!\n");
   2132 			break;
   2133 		}
   2134 		ds = bf->bf_desc;
   2135 		if (ds->ds_link == bf->bf_daddr) {
   2136 			/* NB: never process the self-linked entry at the end */
   2137 			break;
   2138 		}
   2139 		m = bf->bf_m;
   2140 		if (m == NULL) {		/* NB: shouldn't happen */
   2141 			if_printf(ifp, "ath_rx_proc: no mbuf!\n");
   2142 			continue;
   2143 		}
   2144 		/* XXX sync descriptor memory */
   2145 		/*
   2146 		 * Must provide the virtual address of the current
   2147 		 * descriptor, the physical address, and the virtual
   2148 		 * address of the next descriptor in the h/w chain.
   2149 		 * This allows the HAL to look ahead to see if the
   2150 		 * hardware is done with a descriptor by checking the
   2151 		 * done bit in the following descriptor and the address
   2152 		 * of the current descriptor the DMA engine is working
   2153 		 * on.  All this is necessary because of our use of
   2154 		 * a self-linked list to avoid rx overruns.
   2155 		 */
   2156 		status = ath_hal_rxprocdesc(ah, ds,
   2157 				bf->bf_daddr, PA2DESC(sc, ds->ds_link));
   2158 #ifdef AR_DEBUG
   2159 		if (ath_debug > 1)
   2160 			ath_printrxbuf(bf, status == HAL_OK);
   2161 #endif
   2162 		if (status == HAL_EINPROGRESS)
   2163 			break;
   2164 		TAILQ_REMOVE(&sc->sc_rxbuf, bf, bf_list);
   2165 		if (ds->ds_rxstat.rs_status != 0) {
   2166 			if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
   2167 				sc->sc_stats.ast_rx_crcerr++;
   2168 			if (ds->ds_rxstat.rs_status & HAL_RXERR_FIFO)
   2169 				sc->sc_stats.ast_rx_fifoerr++;
   2170 			if (ds->ds_rxstat.rs_status & HAL_RXERR_DECRYPT)
   2171 				sc->sc_stats.ast_rx_badcrypt++;
   2172 			if (ds->ds_rxstat.rs_status & HAL_RXERR_PHY) {
   2173 				sc->sc_stats.ast_rx_phyerr++;
   2174 				phyerr = ds->ds_rxstat.rs_phyerr & 0x1f;
   2175 				sc->sc_stats.ast_rx_phy[phyerr]++;
   2176 			} else {
   2177 				/*
   2178 				 * NB: don't count PHY errors as input errors;
   2179 				 * we enable them on the 5212 to collect info
   2180 				 * about environmental noise and, in that
   2181 				 * setting, they don't really reflect tx/rx
   2182 				 * errors.
   2183 				 */
   2184 				ifp->if_ierrors++;
   2185 			}
   2186 			goto rx_next;
   2187 		}
   2188 
   2189 		len = ds->ds_rxstat.rs_datalen;
   2190 		if (len < IEEE80211_MIN_LEN) {
   2191 			DPRINTF(("ath_rx_proc: short packet %d\n", len));
   2192 			sc->sc_stats.ast_rx_tooshort++;
   2193 			goto rx_next;
   2194 		}
   2195 
   2196 		ath_buf_dmamap_sync(sc->sc_dmat, bf, BUS_DMASYNC_POSTREAD);
   2197 
   2198 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   2199 		bf->bf_m = NULL;
   2200 		m->m_pkthdr.rcvif = ifp;
   2201 		m->m_pkthdr.len = m->m_len = len;
   2202 
   2203 #if NBPFILTER > 0
   2204 		if (sc->sc_drvbpf) {
   2205 #ifdef __FreeBSD__
   2206 			struct mbuf *mb;
   2207 
   2208 			/* XXX pre-allocate space when setting up recv's */
   2209 			MGETHDR(mb, M_DONTWAIT, m->m_type);
   2210 			if (mb != NULL) {
   2211 				sc->sc_rx_th.wr_rate =
   2212 					sc->sc_hwmap[ds->ds_rxstat.rs_rate];
   2213 				sc->sc_rx_th.wr_antsignal =
   2214 					ds->ds_rxstat.rs_rssi;
   2215 				sc->sc_rx_th.wr_antenna =
   2216 					ds->ds_rxstat.rs_antenna;
   2217 				/* XXX TSF */
   2218 
   2219 				(void) m_dup_pkthdr(mb, m, M_DONTWAIT);
   2220 				mb->m_next = m;
   2221 				mb->m_data = (caddr_t)&sc->sc_rx_th;
   2222 				mb->m_len = sizeof(sc->sc_rx_th);
   2223 				mb->m_pkthdr.len += mb->m_len;
   2224 				bpf_mtap(sc->sc_drvbpf, mb);
   2225 				m_free(mb);
   2226 			}
   2227 #else
   2228 			/* XXX pre-allocate space when setting up recv's */
   2229 			struct mbuf mb;
   2230 
   2231 			sc->sc_rx_th.wr_rate =
   2232 				sc->sc_hwmap[ds->ds_rxstat.rs_rate];
   2233 			sc->sc_rx_th.wr_antsignal =
   2234 				ds->ds_rxstat.rs_rssi;
   2235 			sc->sc_rx_th.wr_antenna =
   2236 				ds->ds_rxstat.rs_antenna;
   2237 			/* XXX TSF */
   2238 
   2239 			M_COPY_PKTHDR(&mb, m);
   2240 			mb.m_next = m;
   2241 			mb.m_data = (caddr_t)&sc->sc_rx_th;
   2242 			mb.m_len = sizeof(sc->sc_rx_th);
   2243 			mb.m_pkthdr.len += mb.m_len;
   2244 			bpf_mtap(sc->sc_drvbpf, &mb);
   2245 #endif
   2246 		}
   2247 #endif
   2248 
   2249 		m_adj(m, -IEEE80211_CRC_LEN);
   2250 		wh = mtod(m, struct ieee80211_frame *);
   2251 		if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
   2252 			/*
   2253 			 * WEP is decrypted by hardware. Clear WEP bit
   2254 			 * and trim WEP header for ieee80211_input().
   2255 			 */
   2256 			wh->i_fc[1] &= ~IEEE80211_FC1_WEP;
   2257 			memcpy(&whbuf, wh, sizeof(whbuf));
   2258 			m_adj(m, IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN);
   2259 			wh = mtod(m, struct ieee80211_frame *);
   2260 			memcpy(wh, &whbuf, sizeof(whbuf));
   2261 			/*
   2262 			 * Also trim WEP ICV from the tail.
   2263 			 */
   2264 			m_adj(m, -IEEE80211_WEP_CRCLEN);
   2265 			/*
   2266 			 * The header has probably moved.
   2267 			 */
   2268 			wh = mtod(m, struct ieee80211_frame *);
   2269 		}
   2270 
   2271 		/*
   2272 		 * Locate the node for sender, track state, and
   2273 		 * then pass this node (referenced) up to the 802.11
   2274 		 * layer for its use.  We are required to pass
   2275 		 * something so we fall back to ic_bss when this frame
   2276 		 * is from an unknown sender.
   2277 		 */
   2278 		ni = ieee80211_find_rxnode(ic, wh);
   2279 
   2280 		/*
   2281 		 * Record driver-specific state.
   2282 		 */
   2283 		an = ATH_NODE(ni);
   2284 		if (++(an->an_rx_hist_next) == ATH_RHIST_SIZE)
   2285 			an->an_rx_hist_next = 0;
   2286 		rh = &an->an_rx_hist[an->an_rx_hist_next];
   2287 		rh->arh_ticks = ATH_TICKS();
   2288 		rh->arh_rssi = ds->ds_rxstat.rs_rssi;
   2289 		rh->arh_antenna = ds->ds_rxstat.rs_antenna;
   2290 
   2291 		/*
   2292 		 * Send frame up for processing.
   2293 		 */
   2294 		ieee80211_input(ifp, m, ni,
   2295 			ds->ds_rxstat.rs_rssi, ds->ds_rxstat.rs_tstamp);
   2296 
   2297 		/*
   2298 		 * The frame may have caused the node to be marked for
   2299 		 * reclamation (e.g. in response to a DEAUTH message)
   2300 		 * so use free_node here instead of unref_node.
   2301 		 */
   2302 		if (ni == ic->ic_bss)
   2303 			ieee80211_unref_node(&ni);
   2304 		else
   2305 			ieee80211_free_node(ic, ni);
   2306   rx_next:
   2307 		TAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
   2308 	} while (ath_rxbuf_init(sc, bf) == 0);
   2309 
   2310 	ath_hal_rxmonitor(ah);			/* rx signal state monitoring */
   2311 	ath_hal_rxena(ah);			/* in case of RXEOL */
   2312 
   2313 #ifdef __NetBSD__
   2314 	if ((ifp->if_flags & IFF_OACTIVE) == 0 && !IFQ_IS_EMPTY(&ifp->if_snd))
   2315 		ath_start(ifp);
   2316 #endif /* __NetBSD__ */
   2317 #undef PA2DESC
   2318 }
   2319 
   2320 /*
   2321  * XXX Size of an ACK control frame in bytes.
   2322  */
   2323 #define	IEEE80211_ACK_SIZE	(2+2+IEEE80211_ADDR_LEN+4)
   2324 
   2325 static int
   2326 ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
   2327     struct mbuf *m0)
   2328 {
   2329 	struct ieee80211com *ic = &sc->sc_ic;
   2330 	struct ath_hal *ah = sc->sc_ah;
   2331 	struct ifnet *ifp = &sc->sc_ic.ic_if;
   2332 	int i, error, iswep, hdrlen, pktlen;
   2333 	u_int8_t rix, cix, txrate, ctsrate;
   2334 	struct ath_desc *ds;
   2335 	struct mbuf *m;
   2336 	struct ieee80211_frame *wh;
   2337 	u_int32_t iv;
   2338 	u_int8_t *ivp;
   2339 	u_int8_t hdrbuf[sizeof(struct ieee80211_frame) +
   2340 	    IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN];
   2341 	u_int subtype, flags, ctsduration, antenna;
   2342 	HAL_PKT_TYPE atype;
   2343 	const HAL_RATE_TABLE *rt;
   2344 	HAL_BOOL shortPreamble;
   2345 	struct ath_node *an;
   2346 	ath_txq_critsect_decl(s);
   2347 
   2348 	wh = mtod(m0, struct ieee80211_frame *);
   2349 	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
   2350 	hdrlen = sizeof(struct ieee80211_frame);
   2351 	pktlen = m0->m_pkthdr.len;
   2352 
   2353 	if (iswep) {
   2354 		memcpy(hdrbuf, mtod(m0, caddr_t), hdrlen);
   2355 		m_adj(m0, hdrlen);
   2356 		M_PREPEND(m0, sizeof(hdrbuf), M_DONTWAIT);
   2357 		if (m0 == NULL) {
   2358 			sc->sc_stats.ast_tx_nombuf++;
   2359 			return ENOMEM;
   2360 		}
   2361 		ivp = hdrbuf + hdrlen;
   2362 		wh = mtod(m0, struct ieee80211_frame *);
   2363 		/*
   2364 		 * XXX
   2365 		 * IV must not duplicate during the lifetime of the key.
   2366 		 * But no mechanism to renew keys is defined in IEEE 802.11
   2367 		 * WEP.  And IV may be duplicated between other stations
   2368 		 * because of the session key itself is shared.
   2369 		 * So we use pseudo random IV for now, though it is not the
   2370 		 * right way.
   2371 		 */
   2372                 iv = ic->ic_iv;
   2373 		/*
   2374 		 * Skip 'bad' IVs from Fluhrer/Mantin/Shamir:
   2375 		 * (B, 255, N) with 3 <= B < 8
   2376 		 */
   2377 		if (iv >= 0x03ff00 && (iv & 0xf8ff00) == 0x00ff00)
   2378 			iv += 0x000100;
   2379 		ic->ic_iv = iv + 1;
   2380 		for (i = 0; i < IEEE80211_WEP_IVLEN; i++) {
   2381 			ivp[i] = iv;
   2382 			iv >>= 8;
   2383 		}
   2384 		ivp[i] = sc->sc_ic.ic_wep_txkey << 6;	/* Key ID and pad */
   2385 		memcpy(mtod(m0, caddr_t), hdrbuf, sizeof(hdrbuf));
   2386 		/*
   2387 		 * The ICV length must be included into hdrlen and pktlen.
   2388 		 */
   2389 		hdrlen = sizeof(hdrbuf) + IEEE80211_WEP_CRCLEN;
   2390 		pktlen = m0->m_pkthdr.len + IEEE80211_WEP_CRCLEN;
   2391 	}
   2392 	pktlen += IEEE80211_CRC_LEN;
   2393 
   2394 	/*
   2395 	 * Load the DMA map so any coalescing is done.  This
   2396 	 * also calculates the number of descriptors we need.
   2397 	 */
   2398 	error = ath_buf_dmamap_load_mbuf(sc->sc_dmat, bf, m0, BUS_DMA_NOWAIT);
   2399 	/*
   2400 	 * Discard null packets and check for packets that
   2401 	 * require too many TX descriptors.  We try to convert
   2402 	 * the latter to a cluster.
   2403 	 */
   2404 	if (error == EFBIG) {		/* too many desc's, linearize */
   2405 		sc->sc_stats.ast_tx_linear++;
   2406 		MGETHDR(m, M_DONTWAIT, MT_DATA);
   2407 		if (m == NULL) {
   2408 			sc->sc_stats.ast_tx_nombuf++;
   2409 			m_freem(m0);
   2410 			return ENOMEM;
   2411 		}
   2412 #ifdef __FreeBSD__
   2413 		M_MOVE_PKTHDR(m, m0);
   2414 #else
   2415 		M_COPY_PKTHDR(m, m0);
   2416 #endif
   2417 		MCLGET(m, M_DONTWAIT);
   2418 		if ((m->m_flags & M_EXT) == 0) {
   2419 			sc->sc_stats.ast_tx_nomcl++;
   2420 			m_freem(m0);
   2421 			m_free(m);
   2422 			return ENOMEM;
   2423 		}
   2424 		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(m, caddr_t));
   2425 		m_freem(m0);
   2426 		m->m_len = m->m_pkthdr.len;
   2427 		m0 = m;
   2428 		error = ath_buf_dmamap_load_mbuf(sc->sc_dmat, bf, m0,
   2429 					         BUS_DMA_NOWAIT);
   2430 		if (error != 0) {
   2431 			sc->sc_stats.ast_tx_busdma++;
   2432 			m_freem(m0);
   2433 			return error;
   2434 		}
   2435 		KASSERT(bf->bf_nseg == 1,
   2436 			("ath_tx_start: packet not one segment; nseg %u",
   2437 			bf->bf_nseg));
   2438 	} else if (error != 0) {
   2439 		sc->sc_stats.ast_tx_busdma++;
   2440 		m_freem(m0);
   2441 		return error;
   2442 	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
   2443 		sc->sc_stats.ast_tx_nodata++;
   2444 		m_freem(m0);
   2445 		return EIO;
   2446 	}
   2447 	DPRINTF2(("ath_tx_start: m %p len %u\n", m0, pktlen));
   2448 	ath_buf_dmamap_sync(sc->sc_dmat, bf, BUS_DMASYNC_PREWRITE);
   2449 	bf->bf_m = m0;
   2450 	bf->bf_node = ni;			/* NB: held reference */
   2451 
   2452 	/* setup descriptors */
   2453 	ds = bf->bf_desc;
   2454 	rt = sc->sc_currates;
   2455 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
   2456 
   2457 	/*
   2458 	 * Calculate Atheros packet type from IEEE80211 packet header
   2459 	 * and setup for rate calculations.
   2460 	 */
   2461 	atype = HAL_PKT_TYPE_NORMAL;			/* default */
   2462 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
   2463 	case IEEE80211_FC0_TYPE_MGT:
   2464 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
   2465 		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
   2466 			atype = HAL_PKT_TYPE_BEACON;
   2467 		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
   2468 			atype = HAL_PKT_TYPE_PROBE_RESP;
   2469 		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
   2470 			atype = HAL_PKT_TYPE_ATIM;
   2471 		rix = 0;			/* XXX lowest rate */
   2472 		break;
   2473 	case IEEE80211_FC0_TYPE_CTL:
   2474 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
   2475 		if (subtype == IEEE80211_FC0_SUBTYPE_PS_POLL)
   2476 			atype = HAL_PKT_TYPE_PSPOLL;
   2477 		rix = 0;			/* XXX lowest rate */
   2478 		break;
   2479 	default:
   2480 		rix = sc->sc_rixmap[ni->ni_rates.rs_rates[ni->ni_txrate] &
   2481 				IEEE80211_RATE_VAL];
   2482 		if (rix == 0xff) {
   2483 			if_printf(ifp, "bogus xmit rate 0x%x\n",
   2484 				ni->ni_rates.rs_rates[ni->ni_txrate]);
   2485 			sc->sc_stats.ast_tx_badrate++;
   2486 			m_freem(m0);
   2487 			return EIO;
   2488 		}
   2489 		break;
   2490 	}
   2491 	/*
   2492 	 * NB: the 802.11 layer marks whether or not we should
   2493 	 * use short preamble based on the current mode and
   2494 	 * negotiated parameters.
   2495 	 */
   2496 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
   2497 	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
   2498 		txrate = rt->info[rix].rateCode | rt->info[rix].shortPreamble;
   2499 		shortPreamble = AH_TRUE;
   2500 		sc->sc_stats.ast_tx_shortpre++;
   2501 	} else {
   2502 		txrate = rt->info[rix].rateCode;
   2503 		shortPreamble = AH_FALSE;
   2504 	}
   2505 
   2506 	/*
   2507 	 * Calculate miscellaneous flags.
   2508 	 */
   2509 	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for wep errors */
   2510 	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
   2511 		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
   2512 		sc->sc_stats.ast_tx_noack++;
   2513 	} else if (pktlen > ic->ic_rtsthreshold) {
   2514 		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
   2515 		sc->sc_stats.ast_tx_rts++;
   2516 	}
   2517 
   2518 	/*
   2519 	 * Calculate duration.  This logically belongs in the 802.11
   2520 	 * layer but it lacks sufficient information to calculate it.
   2521 	 */
   2522 	if ((flags & HAL_TXDESC_NOACK) == 0 &&
   2523 	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
   2524 		u_int16_t dur;
   2525 		/*
   2526 		 * XXX not right with fragmentation.
   2527 		 */
   2528 		dur = ath_hal_computetxtime(ah, rt, IEEE80211_ACK_SIZE,
   2529 				rix, shortPreamble);
   2530 		*((u_int16_t*) wh->i_dur) = htole16(dur);
   2531 	}
   2532 
   2533 	/*
   2534 	 * Calculate RTS/CTS rate and duration if needed.
   2535 	 */
   2536 	ctsduration = 0;
   2537 	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
   2538 		/*
   2539 		 * CTS transmit rate is derived from the transmit rate
   2540 		 * by looking in the h/w rate table.  We must also factor
   2541 		 * in whether or not a short preamble is to be used.
   2542 		 */
   2543 		cix = rt->info[rix].controlRate;
   2544 		ctsrate = rt->info[cix].rateCode;
   2545 		if (shortPreamble)
   2546 			ctsrate |= rt->info[cix].shortPreamble;
   2547 		/*
   2548 		 * Compute the transmit duration based on the size
   2549 		 * of an ACK frame.  We call into the HAL to do the
   2550 		 * computation since it depends on the characteristics
   2551 		 * of the actual PHY being used.
   2552 		 */
   2553 		if (flags & HAL_TXDESC_RTSENA) {	/* SIFS + CTS */
   2554 			ctsduration += ath_hal_computetxtime(ah,
   2555 				rt, IEEE80211_ACK_SIZE, cix, shortPreamble);
   2556 		}
   2557 		/* SIFS + data */
   2558 		ctsduration += ath_hal_computetxtime(ah,
   2559 			rt, pktlen, rix, shortPreamble);
   2560 		if ((flags & HAL_TXDESC_NOACK) == 0) {	/* SIFS + ACK */
   2561 			ctsduration += ath_hal_computetxtime(ah,
   2562 				rt, IEEE80211_ACK_SIZE, cix, shortPreamble);
   2563 		}
   2564 	} else
   2565 		ctsrate = 0;
   2566 
   2567 	/*
   2568 	 * For now use the antenna on which the last good
   2569 	 * frame was received on.  We assume this field is
   2570 	 * initialized to 0 which gives us ``auto'' or the
   2571 	 * ``default'' antenna.
   2572 	 */
   2573 	an = (struct ath_node *) ni;
   2574 	if (an->an_tx_antenna)
   2575 		antenna = an->an_tx_antenna;
   2576 	else
   2577 		antenna = an->an_rx_hist[an->an_rx_hist_next].arh_antenna;
   2578 
   2579 	/*
   2580 	 * Formulate first tx descriptor with tx controls.
   2581 	 */
   2582 	/* XXX check return value? */
   2583 	ath_hal_setuptxdesc(ah, ds
   2584 		, pktlen		/* packet length */
   2585 		, hdrlen		/* header length */
   2586 		, atype			/* Atheros packet type */
   2587 		, 60			/* txpower XXX */
   2588 		, txrate, 1+10		/* series 0 rate/tries */
   2589 		, iswep ? sc->sc_ic.ic_wep_txkey : HAL_TXKEYIX_INVALID
   2590 		, antenna		/* antenna mode */
   2591 		, flags			/* flags */
   2592 		, ctsrate		/* rts/cts rate */
   2593 		, ctsduration		/* rts/cts duration */
   2594 	);
   2595 #ifdef notyet
   2596 	ath_hal_setupxtxdesc(ah, ds
   2597 		, AH_FALSE		/* short preamble */
   2598 		, 0, 0			/* series 1 rate/tries */
   2599 		, 0, 0			/* series 2 rate/tries */
   2600 		, 0, 0			/* series 3 rate/tries */
   2601 	);
   2602 #endif
   2603 	/*
   2604 	 * Fillin the remainder of the descriptor info.
   2605 	 */
   2606 	for (i = 0; i < bf->bf_nseg; i++, ds++) {
   2607 		ds->ds_data = bf->bf_segs[i].ds_addr;
   2608 		if (i == bf->bf_nseg - 1)
   2609 			ds->ds_link = 0;
   2610 		else
   2611 			ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
   2612 		ath_hal_filltxdesc(ah, ds
   2613 			, bf->bf_segs[i].ds_len	/* segment length */
   2614 			, i == 0		/* first segment */
   2615 			, i == bf->bf_nseg - 1	/* last segment */
   2616 		);
   2617 		DPRINTF2(("ath_tx_start: %d: %08x %08x %08x %08x %08x %08x\n",
   2618 		    i, ds->ds_link, ds->ds_data, ds->ds_ctl0, ds->ds_ctl1,
   2619 		    ds->ds_hw[0], ds->ds_hw[1]));
   2620 	}
   2621 
   2622 	/*
   2623 	 * Insert the frame on the outbound list and
   2624 	 * pass it on to the hardware.
   2625 	 */
   2626 	ath_txq_critsect_begin(sc, s);
   2627 	TAILQ_INSERT_TAIL(&sc->sc_txq, bf, bf_list);
   2628 	if (sc->sc_txlink == NULL) {
   2629 		ath_hal_puttxbuf(ah, sc->sc_txhalq, bf->bf_daddr);
   2630 		DPRINTF2(("ath_tx_start: TXDP0 = %p (%p)\n",
   2631 		    (caddr_t)bf->bf_daddr, bf->bf_desc));
   2632 	} else {
   2633 		*sc->sc_txlink = bf->bf_daddr;
   2634 		DPRINTF2(("ath_tx_start: link(%p)=%p (%p)\n",
   2635 		    sc->sc_txlink, (caddr_t)bf->bf_daddr, bf->bf_desc));
   2636 	}
   2637 	sc->sc_txlink = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
   2638 	ath_txq_critsect_end(sc, s);
   2639 
   2640 	ath_hal_txstart(ah, sc->sc_txhalq);
   2641 	return 0;
   2642 }
   2643 
   2644 static void
   2645 ath_tx_proc(void *arg, int npending)
   2646 {
   2647 	struct ath_softc *sc = arg;
   2648 	struct ath_hal *ah = sc->sc_ah;
   2649 	struct ath_buf *bf;
   2650 	struct ieee80211com *ic = &sc->sc_ic;
   2651 	struct ifnet *ifp = &ic->ic_if;
   2652 	struct ath_desc *ds;
   2653 	struct ieee80211_node *ni;
   2654 	struct ath_node *an;
   2655 	int sr, lr;
   2656 	HAL_STATUS status;
   2657 	ath_txq_critsect_decl(s);
   2658 	ath_txbuf_critsect_decl(s2);
   2659 
   2660 	DPRINTF2(("ath_tx_proc: pending %u tx queue %p, link %p\n",
   2661 		npending, (caddr_t) ath_hal_gettxbuf(sc->sc_ah, sc->sc_txhalq),
   2662 		sc->sc_txlink));
   2663 	for (;;) {
   2664 		ath_txq_critsect_begin(sc, s);
   2665 		bf = TAILQ_FIRST(&sc->sc_txq);
   2666 		if (bf == NULL) {
   2667 			sc->sc_txlink = NULL;
   2668 			ath_txq_critsect_end(sc, s);
   2669 			break;
   2670 		}
   2671 		/* only the last descriptor is needed */
   2672 		ds = &bf->bf_desc[bf->bf_nseg - 1];
   2673 		status = ath_hal_txprocdesc(ah, ds);
   2674 #ifdef AR_DEBUG
   2675 		if (ath_debug > 1)
   2676 			ath_printtxbuf(bf, status == HAL_OK);
   2677 #endif
   2678 		if (status == HAL_EINPROGRESS) {
   2679 			ath_txq_critsect_end(sc, s);
   2680 			break;
   2681 		}
   2682 		TAILQ_REMOVE(&sc->sc_txq, bf, bf_list);
   2683 		ath_txq_critsect_end(sc, s);
   2684 
   2685 		ni = bf->bf_node;
   2686 		if (ni != NULL) {
   2687 			an = (struct ath_node *) ni;
   2688 			if (ds->ds_txstat.ts_status == 0) {
   2689 				an->an_tx_ok++;
   2690 				an->an_tx_antenna = ds->ds_txstat.ts_antenna;
   2691 			} else {
   2692 				an->an_tx_err++;
   2693 				ifp->if_oerrors++;
   2694 				if (ds->ds_txstat.ts_status & HAL_TXERR_XRETRY)
   2695 					sc->sc_stats.ast_tx_xretries++;
   2696 				if (ds->ds_txstat.ts_status & HAL_TXERR_FIFO)
   2697 					sc->sc_stats.ast_tx_fifoerr++;
   2698 				if (ds->ds_txstat.ts_status & HAL_TXERR_FILT)
   2699 					sc->sc_stats.ast_tx_filtered++;
   2700 				an->an_tx_antenna = 0;	/* invalidate */
   2701 			}
   2702 			sr = ds->ds_txstat.ts_shortretry;
   2703 			lr = ds->ds_txstat.ts_longretry;
   2704 			sc->sc_stats.ast_tx_shortretry += sr;
   2705 			sc->sc_stats.ast_tx_longretry += lr;
   2706 			if (sr + lr)
   2707 				an->an_tx_retr++;
   2708 			/*
   2709 			 * Reclaim reference to node.
   2710 			 *
   2711 			 * NB: the node may be reclaimed here if, for example
   2712 			 *     this is a DEAUTH message that was sent and the
   2713 			 *     node was timed out due to inactivity.
   2714 			 */
   2715 			if (ni != ic->ic_bss)
   2716 				ieee80211_free_node(ic, ni);
   2717 		}
   2718 		ath_buf_dmamap_sync(sc->sc_dmat, bf, BUS_DMASYNC_POSTWRITE);
   2719 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   2720 		m_freem(bf->bf_m);
   2721 		bf->bf_m = NULL;
   2722 		bf->bf_node = NULL;
   2723 
   2724 		ath_txbuf_critsect_begin(sc, s2);
   2725 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   2726 		ath_txbuf_critsect_end(sc, s2);
   2727 	}
   2728 	ifp->if_flags &= ~IFF_OACTIVE;
   2729 	sc->sc_tx_timer = 0;
   2730 
   2731 	ath_start(ifp);
   2732 }
   2733 
   2734 /*
   2735  * Drain the transmit queue and reclaim resources.
   2736  */
   2737 static void
   2738 ath_draintxq(struct ath_softc *sc)
   2739 {
   2740 	struct ath_hal *ah = sc->sc_ah;
   2741 	struct ifnet *ifp = &sc->sc_ic.ic_if;
   2742 	struct ath_buf *bf;
   2743 	ath_txq_critsect_decl(s);
   2744 	ath_txbuf_critsect_decl(s2);
   2745 
   2746 	/* XXX return value */
   2747 	if (!sc->sc_invalid) {
   2748 		/* don't touch the hardware if marked invalid */
   2749 		(void) ath_hal_stoptxdma(ah, sc->sc_txhalq);
   2750 		DPRINTF(("ath_draintxq: tx queue %p, link %p\n",
   2751 		    (caddr_t) ath_hal_gettxbuf(ah, sc->sc_txhalq),
   2752 		    sc->sc_txlink));
   2753 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
   2754 		DPRINTF(("ath_draintxq: beacon queue %p\n",
   2755 		    (caddr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq)));
   2756 	}
   2757 	for (;;) {
   2758 		ath_txq_critsect_begin(sc, s);
   2759 		bf = TAILQ_FIRST(&sc->sc_txq);
   2760 		if (bf == NULL) {
   2761 			sc->sc_txlink = NULL;
   2762 			ath_txq_critsect_end(sc, s);
   2763 			break;
   2764 		}
   2765 		TAILQ_REMOVE(&sc->sc_txq, bf, bf_list);
   2766 		ath_txq_critsect_end(sc, s);
   2767 #ifdef AR_DEBUG
   2768 		if (ath_debug)
   2769 			ath_printtxbuf(bf,
   2770 				ath_hal_txprocdesc(ah, bf->bf_desc) == HAL_OK);
   2771 #endif /* AR_DEBUG */
   2772 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
   2773 		m_freem(bf->bf_m);
   2774 		bf->bf_m = NULL;
   2775 		bf->bf_node = NULL;
   2776 		ath_txbuf_critsect_begin(sc, s2);
   2777 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
   2778 		ath_txbuf_critsect_end(sc, s2);
   2779 	}
   2780 	ifp->if_flags &= ~IFF_OACTIVE;
   2781 	sc->sc_tx_timer = 0;
   2782 }
   2783 
   2784 /*
   2785  * Disable the receive h/w in preparation for a reset.
   2786  */
   2787 static void
   2788 ath_stoprecv(struct ath_softc *sc)
   2789 {
   2790 #define	PA2DESC(_sc, _pa) \
   2791 	((struct ath_desc *)((caddr_t)(_sc)->sc_desc + \
   2792 		((_pa) - (_sc)->sc_desc_paddr)))
   2793 	struct ath_hal *ah = sc->sc_ah;
   2794 
   2795 	ath_hal_stoppcurecv(ah);	/* disable PCU */
   2796 	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
   2797 	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
   2798 	DELAY(3000);			/* long enough for 1 frame */
   2799 #ifdef AR_DEBUG
   2800 	if (ath_debug) {
   2801 		struct ath_buf *bf;
   2802 
   2803 		DPRINTF(("ath_stoprecv: rx queue %p, link %p\n",
   2804 		    (caddr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink));
   2805 		TAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
   2806 			struct ath_desc *ds = bf->bf_desc;
   2807 			if (ath_hal_rxprocdesc(ah, ds, bf->bf_daddr,
   2808 			    PA2DESC(sc, ds->ds_link)) == HAL_OK)
   2809 				ath_printrxbuf(bf, 1);
   2810 		}
   2811 	}
   2812 #endif
   2813 	sc->sc_rxlink = NULL;		/* just in case */
   2814 #undef PA2DESC
   2815 }
   2816 
   2817 /*
   2818  * Enable the receive h/w following a reset.
   2819  */
   2820 static int
   2821 ath_startrecv(struct ath_softc *sc)
   2822 {
   2823 	struct ath_hal *ah = sc->sc_ah;
   2824 	struct ath_buf *bf;
   2825 
   2826 	sc->sc_rxlink = NULL;
   2827 	TAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
   2828 		int error = ath_rxbuf_init(sc, bf);
   2829 		if (error != 0) {
   2830 			DPRINTF(("ath_startrecv: ath_rxbuf_init failed %d\n",
   2831 				error));
   2832 			return error;
   2833 		}
   2834 	}
   2835 
   2836 	bf = TAILQ_FIRST(&sc->sc_rxbuf);
   2837 	ath_hal_putrxbuf(ah, bf->bf_daddr);
   2838 	ath_hal_rxena(ah);		/* enable recv descriptors */
   2839 	ath_mode_init(sc);		/* set filters, etc. */
   2840 	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
   2841 	return 0;
   2842 }
   2843 
   2844 /*
   2845  * Set/change channels.  If the channel is really being changed,
   2846  * it's done by resetting the chip.  To accomplish this we must
   2847  * first cleanup any pending DMA, then restart stuff after a la
   2848  * ath_init.
   2849  */
   2850 static int
   2851 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
   2852 {
   2853 	struct ath_hal *ah = sc->sc_ah;
   2854 	struct ieee80211com *ic = &sc->sc_ic;
   2855 
   2856 	DPRINTF(("ath_chan_set: %u (%u MHz) -> %u (%u MHz)\n",
   2857 	    ieee80211_chan2ieee(ic, ic->ic_ibss_chan),
   2858 		ic->ic_ibss_chan->ic_freq,
   2859 	    ieee80211_chan2ieee(ic, chan), chan->ic_freq));
   2860 	if (chan != ic->ic_ibss_chan) {
   2861 		HAL_STATUS status;
   2862 		HAL_CHANNEL hchan;
   2863 		enum ieee80211_phymode mode;
   2864 
   2865 		/*
   2866 		 * To switch channels clear any pending DMA operations;
   2867 		 * wait long enough for the RX fifo to drain, reset the
   2868 		 * hardware at the new frequency, and then re-enable
   2869 		 * the relevant bits of the h/w.
   2870 		 */
   2871 		ath_hal_intrset(ah, 0);		/* disable interrupts */
   2872 		ath_draintxq(sc);		/* clear pending tx frames */
   2873 		ath_stoprecv(sc);		/* turn off frame recv */
   2874 		/*
   2875 		 * Convert to a HAL channel description with
   2876 		 * the flags constrained to reflect the current
   2877 		 * operating mode.
   2878 		 */
   2879 		hchan.channel = chan->ic_freq;
   2880 		hchan.channelFlags = ath_chan2flags(ic, chan);
   2881 		if (!ath_hal_reset(ah, ic->ic_opmode, &hchan, AH_TRUE, &status)) {
   2882 			if_printf(&ic->ic_if, "ath_chan_set: unable to reset "
   2883 				"channel %u (%u Mhz)\n",
   2884 				ieee80211_chan2ieee(ic, chan), chan->ic_freq);
   2885 			return EIO;
   2886 		}
   2887 		/*
   2888 		 * Re-enable rx framework.
   2889 		 */
   2890 		if (ath_startrecv(sc) != 0) {
   2891 			if_printf(&ic->ic_if,
   2892 				"ath_chan_set: unable to restart recv logic\n");
   2893 			return EIO;
   2894 		}
   2895 
   2896 		/*
   2897 		 * Update BPF state.
   2898 		 */
   2899 		sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq =
   2900 			htole16(chan->ic_freq);
   2901 		sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags =
   2902 			htole16(chan->ic_flags);
   2903 
   2904 		/*
   2905 		 * Change channels and update the h/w rate map
   2906 		 * if we're switching; e.g. 11a to 11b/g.
   2907 		 */
   2908 		ic->ic_ibss_chan = chan;
   2909 		mode = ieee80211_chan2mode(ic, chan);
   2910 		if (mode != sc->sc_curmode)
   2911 			ath_setcurmode(sc, mode);
   2912 
   2913 		/*
   2914 		 * Re-enable interrupts.
   2915 		 */
   2916 		ath_hal_intrset(ah, sc->sc_imask);
   2917 	}
   2918 	return 0;
   2919 }
   2920 
   2921 static void
   2922 ath_next_scan(void *arg)
   2923 {
   2924 	struct ath_softc *sc = arg;
   2925 	struct ieee80211com *ic = &sc->sc_ic;
   2926 	struct ifnet *ifp = &ic->ic_if;
   2927 	int s;
   2928 
   2929 	/* don't call ath_start w/o network interrupts blocked */
   2930 	s = splnet();
   2931 
   2932 	if (ic->ic_state == IEEE80211_S_SCAN)
   2933 		ieee80211_next_scan(ifp);
   2934 	splx(s);
   2935 }
   2936 
   2937 /*
   2938  * Periodically recalibrate the PHY to account
   2939  * for temperature/environment changes.
   2940  */
   2941 static void
   2942 ath_calibrate(void *arg)
   2943 {
   2944 	struct ath_softc *sc = arg;
   2945 	struct ath_hal *ah = sc->sc_ah;
   2946 	struct ieee80211com *ic = &sc->sc_ic;
   2947 	struct ieee80211_channel *c;
   2948 	HAL_CHANNEL hchan;
   2949 
   2950 	sc->sc_stats.ast_per_cal++;
   2951 
   2952 	/*
   2953 	 * Convert to a HAL channel description with the flags
   2954 	 * constrained to reflect the current operating mode.
   2955 	 */
   2956 	c = ic->ic_ibss_chan;
   2957 	hchan.channel = c->ic_freq;
   2958 	hchan.channelFlags = ath_chan2flags(ic, c);
   2959 
   2960 	DPRINTF(("%s: channel %u/%x\n", __func__, c->ic_freq, c->ic_flags));
   2961 
   2962 	if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
   2963 		/*
   2964 		 * Rfgain is out of bounds, reset the chip
   2965 		 * to load new gain values.
   2966 		 */
   2967 		sc->sc_stats.ast_per_rfgain++;
   2968 		ath_reset(sc);
   2969 	}
   2970 	if (!ath_hal_calibrate(ah, &hchan)) {
   2971 		DPRINTF(("%s: calibration of channel %u failed\n",
   2972 			__func__, c->ic_freq));
   2973 		sc->sc_stats.ast_per_calfail++;
   2974 	}
   2975 	callout_reset(&sc->sc_cal_ch, hz * ath_calinterval, ath_calibrate, sc);
   2976 }
   2977 
   2978 static HAL_LED_STATE
   2979 ath_state_to_led(enum ieee80211_state state)
   2980 {
   2981 	switch (state) {
   2982 	case IEEE80211_S_INIT:
   2983 		return HAL_LED_INIT;
   2984 	case IEEE80211_S_SCAN:
   2985 		return HAL_LED_SCAN;
   2986 	case IEEE80211_S_AUTH:
   2987 		return HAL_LED_AUTH;
   2988 	case IEEE80211_S_ASSOC:
   2989 		return HAL_LED_ASSOC;
   2990 	case IEEE80211_S_RUN:
   2991 		return HAL_LED_RUN;
   2992 	default:
   2993 		panic("%s: unknown 802.11 state %d\n", __func__, state);
   2994 		return HAL_LED_INIT;
   2995 	}
   2996 }
   2997 
   2998 static int
   2999 ath_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
   3000 {
   3001 	struct ifnet *ifp = &ic->ic_if;
   3002 	struct ath_softc *sc = ifp->if_softc;
   3003 	struct ath_hal *ah = sc->sc_ah;
   3004 	struct ieee80211_node *ni;
   3005 	int i, error;
   3006 	const u_int8_t *bssid;
   3007 	u_int32_t rfilt;
   3008 
   3009 	DPRINTF(("%s: %s -> %s\n", __func__,
   3010 		ieee80211_state_name[ic->ic_state],
   3011 		ieee80211_state_name[nstate]));
   3012 
   3013 	ath_hal_setledstate(ah, ath_state_to_led(nstate));	/* set LED */
   3014 
   3015 	if (nstate == IEEE80211_S_INIT) {
   3016 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
   3017 		ath_hal_intrset(ah, sc->sc_imask);
   3018 		callout_stop(&sc->sc_scan_ch);
   3019 		callout_stop(&sc->sc_cal_ch);
   3020 		return (*sc->sc_newstate)(ic, nstate, arg);
   3021 	}
   3022 	ni = ic->ic_bss;
   3023 	error = ath_chan_set(sc, ni->ni_chan);
   3024 	if (error != 0)
   3025 		goto bad;
   3026 	rfilt = ath_calcrxfilter(sc);
   3027 	if (nstate == IEEE80211_S_SCAN) {
   3028 		callout_reset(&sc->sc_scan_ch, (hz * ath_dwelltime) / 1000,
   3029 			ath_next_scan, sc);
   3030 		bssid = ifp->if_broadcastaddr;
   3031 	} else {
   3032 		callout_stop(&sc->sc_scan_ch);
   3033 		bssid = ni->ni_bssid;
   3034 	}
   3035 	ath_hal_setrxfilter(ah, rfilt);
   3036 	DPRINTF(("%s: RX filter 0x%x bssid %s\n",
   3037 		 __func__, rfilt, ether_sprintf(bssid)));
   3038 
   3039 	if (nstate == IEEE80211_S_RUN && ic->ic_opmode == IEEE80211_M_STA)
   3040 		ath_hal_setassocid(ah, bssid, ni->ni_associd);
   3041 	else
   3042 		ath_hal_setassocid(ah, bssid, 0);
   3043 	if (ic->ic_flags & IEEE80211_F_WEPON) {
   3044 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
   3045 			if (ath_hal_keyisvalid(ah, i))
   3046 				ath_hal_keysetmac(ah, i, bssid);
   3047 	}
   3048 
   3049 	if (nstate == IEEE80211_S_RUN) {
   3050 		DPRINTF(("%s(RUN): ic_flags=0x%08x iv=%d bssid=%s "
   3051 			"capinfo=0x%04x chan=%d\n"
   3052 			 , __func__
   3053 			 , ic->ic_flags
   3054 			 , ni->ni_intval
   3055 			 , ether_sprintf(ni->ni_bssid)
   3056 			 , ni->ni_capinfo
   3057 			 , ieee80211_chan2ieee(ic, ni->ni_chan)));
   3058 
   3059 		/*
   3060 		 * Allocate and setup the beacon frame for AP or adhoc mode.
   3061 		 */
   3062 		if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
   3063 		    ic->ic_opmode == IEEE80211_M_IBSS) {
   3064 			error = ath_beacon_alloc(sc, ni);
   3065 			if (error != 0)
   3066 				goto bad;
   3067 		}
   3068 
   3069 		/*
   3070 		 * Configure the beacon and sleep timers.
   3071 		 */
   3072 		ath_beacon_config(sc);
   3073 
   3074 		/* start periodic recalibration timer */
   3075 		callout_reset(&sc->sc_cal_ch, hz * ath_calinterval,
   3076 			ath_calibrate, sc);
   3077 	} else {
   3078 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
   3079 		ath_hal_intrset(ah, sc->sc_imask);
   3080 		callout_stop(&sc->sc_cal_ch);		/* no calibration */
   3081 	}
   3082 	/*
   3083 	 * Reset the rate control state.
   3084 	 */
   3085 	ath_rate_ctl_reset(sc, nstate);
   3086 	/*
   3087 	 * Invoke the parent method to complete the work.
   3088 	 */
   3089 	return (*sc->sc_newstate)(ic, nstate, arg);
   3090 bad:
   3091 	callout_stop(&sc->sc_scan_ch);
   3092 	callout_stop(&sc->sc_cal_ch);
   3093 	/* NB: do not invoke the parent */
   3094 	return error;
   3095 }
   3096 
   3097 /*
   3098  * Setup driver-specific state for a newly associated node.
   3099  * Note that we're called also on a re-associate, the isnew
   3100  * param tells us if this is the first time or not.
   3101  */
   3102 static void
   3103 ath_newassoc(struct ieee80211com *ic, struct ieee80211_node *ni, int isnew)
   3104 {
   3105 	if (isnew) {
   3106 		struct ath_node *an = (struct ath_node *) ni;
   3107 
   3108 		an->an_tx_ok = an->an_tx_err =
   3109 			an->an_tx_retr = an->an_tx_upper = 0;
   3110 		/* start with highest negotiated rate */
   3111 		/*
   3112 		 * XXX should do otherwise but only when
   3113 		 * the rate control algorithm is better.
   3114 		 */
   3115 		KASSERT(ni->ni_rates.rs_nrates > 0,
   3116 			("new association w/ no rates!"));
   3117 		ni->ni_txrate = ni->ni_rates.rs_nrates - 1;
   3118 	}
   3119 }
   3120 
   3121 static int
   3122 ath_getchannels(struct ath_softc *sc, u_int cc, HAL_BOOL outdoor)
   3123 {
   3124 	struct ieee80211com *ic = &sc->sc_ic;
   3125 	struct ifnet *ifp = &ic->ic_if;
   3126 	struct ath_hal *ah = sc->sc_ah;
   3127 	HAL_CHANNEL *chans;
   3128 	int i, ix, nchan;
   3129 
   3130 	chans = malloc(IEEE80211_CHAN_MAX * sizeof(HAL_CHANNEL),
   3131 			M_TEMP, M_NOWAIT);
   3132 	if (chans == NULL) {
   3133 		if_printf(ifp, "unable to allocate channel table\n");
   3134 		return ENOMEM;
   3135 	}
   3136 	if (!ath_hal_init_channels(ah, chans, IEEE80211_CHAN_MAX, &nchan,
   3137 	    cc, HAL_MODE_ALL, outdoor, 0 /* no extended channels */)) {
   3138 		if_printf(ifp, "unable to collect channel list from hal\n");
   3139 		free(chans, M_TEMP);
   3140 		return EINVAL;
   3141 	}
   3142 
   3143 	/*
   3144 	 * Convert HAL channels to ieee80211 ones and insert
   3145 	 * them in the table according to their channel number.
   3146 	 */
   3147 	for (i = 0; i < nchan; i++) {
   3148 		HAL_CHANNEL *c = &chans[i];
   3149 		ix = ath_hal_mhz2ieee(c->channel, c->channelFlags);
   3150 		if (ix > IEEE80211_CHAN_MAX) {
   3151 			if_printf(ifp, "bad hal channel %u (%u/%x) ignored\n",
   3152 				ix, c->channel, c->channelFlags);
   3153 			continue;
   3154 		}
   3155 		/* NB: flags are known to be compatible */
   3156 		if (ic->ic_channels[ix].ic_freq == 0) {
   3157 			ic->ic_channels[ix].ic_freq = c->channel;
   3158 			ic->ic_channels[ix].ic_flags = c->channelFlags;
   3159 		} else {
   3160 			/* channels overlap; e.g. 11g and 11b */
   3161 			ic->ic_channels[ix].ic_flags |= c->channelFlags;
   3162 		}
   3163 	}
   3164 	free(chans, M_TEMP);
   3165 	return 0;
   3166 }
   3167 
   3168 static int
   3169 ath_rate_setup(struct ath_softc *sc, u_int mode)
   3170 {
   3171 	struct ath_hal *ah = sc->sc_ah;
   3172 	struct ieee80211com *ic = &sc->sc_ic;
   3173 	const HAL_RATE_TABLE *rt;
   3174 	struct ieee80211_rateset *rs;
   3175 	int i, maxrates;
   3176 
   3177 	switch (mode) {
   3178 	case IEEE80211_MODE_11A:
   3179 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11A);
   3180 		break;
   3181 	case IEEE80211_MODE_11B:
   3182 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11B);
   3183 		break;
   3184 	case IEEE80211_MODE_11G:
   3185 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11G);
   3186 		break;
   3187 	case IEEE80211_MODE_TURBO:
   3188 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_TURBO);
   3189 		break;
   3190 	default:
   3191 		DPRINTF(("%s: invalid mode %u\n", __func__, mode));
   3192 		return 0;
   3193 	}
   3194 	rt = sc->sc_rates[mode];
   3195 	if (rt == NULL)
   3196 		return 0;
   3197 	if (rt->rateCount > IEEE80211_RATE_MAXSIZE) {
   3198 		DPRINTF(("%s: rate table too small (%u > %u)\n",
   3199 			__func__, rt->rateCount, IEEE80211_RATE_MAXSIZE));
   3200 		maxrates = IEEE80211_RATE_MAXSIZE;
   3201 	} else
   3202 		maxrates = rt->rateCount;
   3203 	rs = &ic->ic_sup_rates[mode];
   3204 	for (i = 0; i < maxrates; i++)
   3205 		rs->rs_rates[i] = rt->info[i].dot11Rate;
   3206 	rs->rs_nrates = maxrates;
   3207 	return 1;
   3208 }
   3209 
   3210 static void
   3211 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
   3212 {
   3213 	const HAL_RATE_TABLE *rt;
   3214 	int i;
   3215 
   3216 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
   3217 	rt = sc->sc_rates[mode];
   3218 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
   3219 	for (i = 0; i < rt->rateCount; i++)
   3220 		sc->sc_rixmap[rt->info[i].dot11Rate & IEEE80211_RATE_VAL] = i;
   3221 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
   3222 	for (i = 0; i < 32; i++)
   3223 		sc->sc_hwmap[i] = rt->info[rt->rateCodeToIndex[i]].dot11Rate;
   3224 	sc->sc_currates = rt;
   3225 	sc->sc_curmode = mode;
   3226 }
   3227 
   3228 /*
   3229  * Reset the rate control state for each 802.11 state transition.
   3230  */
   3231 static void
   3232 ath_rate_ctl_reset(struct ath_softc *sc, enum ieee80211_state state)
   3233 {
   3234 	struct ieee80211com *ic = &sc->sc_ic;
   3235 	struct ieee80211_node *ni;
   3236 	struct ath_node *an;
   3237 
   3238 	if (ic->ic_opmode != IEEE80211_M_STA) {
   3239 		/*
   3240 		 * When operating as a station the node table holds
   3241 		 * the AP's that were discovered during scanning.
   3242 		 * For any other operating mode we want to reset the
   3243 		 * tx rate state of each node.
   3244 		 */
   3245 		TAILQ_FOREACH(ni, &ic->ic_node, ni_list) {
   3246 			ni->ni_txrate = 0;		/* use lowest rate */
   3247 			an = (struct ath_node *) ni;
   3248 			an->an_tx_ok = an->an_tx_err = an->an_tx_retr =
   3249 			    an->an_tx_upper = 0;
   3250 		}
   3251 	}
   3252 	/*
   3253 	 * Reset local xmit state; this is really only meaningful
   3254 	 * when operating in station or adhoc mode.
   3255 	 */
   3256 	ni = ic->ic_bss;
   3257 	an = (struct ath_node *) ni;
   3258 	an->an_tx_ok = an->an_tx_err = an->an_tx_retr = an->an_tx_upper = 0;
   3259 	if (state == IEEE80211_S_RUN) {
   3260 		/* start with highest negotiated rate */
   3261 		KASSERT(ni->ni_rates.rs_nrates > 0,
   3262 			("transition to RUN state w/ no rates!"));
   3263 		ni->ni_txrate = ni->ni_rates.rs_nrates - 1;
   3264 	} else {
   3265 		/* use lowest rate */
   3266 		ni->ni_txrate = 0;
   3267 	}
   3268 }
   3269 
   3270 /*
   3271  * Examine and potentially adjust the transmit rate.
   3272  */
   3273 static void
   3274 ath_rate_ctl(void *arg, struct ieee80211_node *ni)
   3275 {
   3276 	struct ath_softc *sc = arg;
   3277 	struct ath_node *an = (struct ath_node *) ni;
   3278 	struct ieee80211_rateset *rs = &ni->ni_rates;
   3279 	int mod = 0, orate, enough;
   3280 
   3281 	/*
   3282 	 * Rate control
   3283 	 * XXX: very primitive version.
   3284 	 */
   3285 	sc->sc_stats.ast_rate_calls++;
   3286 
   3287 	enough = (an->an_tx_ok + an->an_tx_err >= 10);
   3288 
   3289 	/* no packet reached -> down */
   3290 	if (an->an_tx_err > 0 && an->an_tx_ok == 0)
   3291 		mod = -1;
   3292 
   3293 	/* all packets needs retry in average -> down */
   3294 	if (enough && an->an_tx_ok < an->an_tx_retr)
   3295 		mod = -1;
   3296 
   3297 	/* no error and less than 10% of packets needs retry -> up */
   3298 	if (enough && an->an_tx_err == 0 && an->an_tx_ok > an->an_tx_retr * 10)
   3299 		mod = 1;
   3300 
   3301 	orate = ni->ni_txrate;
   3302 	switch (mod) {
   3303 	case 0:
   3304 		if (enough && an->an_tx_upper > 0)
   3305 			an->an_tx_upper--;
   3306 		break;
   3307 	case -1:
   3308 		if (ni->ni_txrate > 0) {
   3309 			ni->ni_txrate--;
   3310 			sc->sc_stats.ast_rate_drop++;
   3311 		}
   3312 		an->an_tx_upper = 0;
   3313 		break;
   3314 	case 1:
   3315 		if (++an->an_tx_upper < 2)
   3316 			break;
   3317 		an->an_tx_upper = 0;
   3318 		if (ni->ni_txrate + 1 < rs->rs_nrates) {
   3319 			ni->ni_txrate++;
   3320 			sc->sc_stats.ast_rate_raise++;
   3321 		}
   3322 		break;
   3323 	}
   3324 
   3325 	if (ni->ni_txrate != orate) {
   3326 		DPRINTF(("%s: %dM -> %dM (%d ok, %d err, %d retr)\n",
   3327 		    __func__,
   3328 		    (rs->rs_rates[orate] & IEEE80211_RATE_VAL) / 2,
   3329 		    (rs->rs_rates[ni->ni_txrate] & IEEE80211_RATE_VAL) / 2,
   3330 		    an->an_tx_ok, an->an_tx_err, an->an_tx_retr));
   3331 	}
   3332 	if (ni->ni_txrate != orate || enough)
   3333 		an->an_tx_ok = an->an_tx_err = an->an_tx_retr = 0;
   3334 }
   3335 
   3336 #ifdef AR_DEBUG
   3337 #ifdef __FreeBSD__
   3338 static int
   3339 sysctl_hw_ath_dump(SYSCTL_HANDLER_ARGS)
   3340 {
   3341 	char dmode[64];
   3342 	int error;
   3343 
   3344 	strncpy(dmode, "", sizeof(dmode) - 1);
   3345 	dmode[sizeof(dmode) - 1] = '\0';
   3346 	error = sysctl_handle_string(oidp, &dmode[0], sizeof(dmode), req);
   3347 
   3348 	if (error == 0 && req->newptr != NULL) {
   3349 		struct ifnet *ifp;
   3350 		struct ath_softc *sc;
   3351 
   3352 		ifp = ifunit("ath0");		/* XXX */
   3353 		if (!ifp)
   3354 			return EINVAL;
   3355 		sc = ifp->if_softc;
   3356 		if (strcmp(dmode, "hal") == 0)
   3357 			ath_hal_dumpstate(sc->sc_ah);
   3358 		else
   3359 			return EINVAL;
   3360 	}
   3361 	return error;
   3362 }
   3363 SYSCTL_PROC(_hw_ath, OID_AUTO, dump, CTLTYPE_STRING | CTLFLAG_RW,
   3364 	0, 0, sysctl_hw_ath_dump, "A", "Dump driver state");
   3365 #endif /* __FreeBSD__ */
   3366 
   3367 static void
   3368 ath_printrxbuf(struct ath_buf *bf, int done)
   3369 {
   3370 	struct ath_desc *ds;
   3371 	int i;
   3372 
   3373 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
   3374 		printf("R%d (%p %p) %08x %08x %08x %08x %08x %08x %c\n",
   3375 		    i, ds, (struct ath_desc *)bf->bf_daddr + i,
   3376 		    ds->ds_link, ds->ds_data,
   3377 		    ds->ds_ctl0, ds->ds_ctl1,
   3378 		    ds->ds_hw[0], ds->ds_hw[1],
   3379 		    !done ? ' ' : (ds->ds_rxstat.rs_status == 0) ? '*' : '!');
   3380 	}
   3381 }
   3382 
   3383 static void
   3384 ath_printtxbuf(struct ath_buf *bf, int done)
   3385 {
   3386 	struct ath_desc *ds;
   3387 	int i;
   3388 
   3389 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
   3390 		printf("T%d (%p %p) %08x %08x %08x %08x %08x %08x %08x %08x %c\n",
   3391 		    i, ds, (struct ath_desc *)bf->bf_daddr + i,
   3392 		    ds->ds_link, ds->ds_data,
   3393 		    ds->ds_ctl0, ds->ds_ctl1,
   3394 		    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3],
   3395 		    !done ? ' ' : (ds->ds_txstat.ts_status == 0) ? '*' : '!');
   3396 	}
   3397 }
   3398 #endif /* AR_DEBUG */
   3399