if_ath.c revision 186904
161033Sdfr/*-
261033Sdfr * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
361033Sdfr * All rights reserved.
461033Sdfr *
561033Sdfr * Redistribution and use in source and binary forms, with or without
661033Sdfr * modification, are permitted provided that the following conditions
761033Sdfr * are met:
861033Sdfr * 1. Redistributions of source code must retain the above copyright
961033Sdfr *    notice, this list of conditions and the following disclaimer,
1061033Sdfr *    without modification.
1161033Sdfr * 2. Redistributions in binary form must reproduce at minimum a disclaimer
1261033Sdfr *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
1361033Sdfr *    redistribution must be conditioned upon including a substantially
1461033Sdfr *    similar Disclaimer requirement for further binary redistribution.
1561033Sdfr *
1661033Sdfr * NO WARRANTY
1761033Sdfr * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
1861033Sdfr * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
1961033Sdfr * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
2061033Sdfr * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
2161033Sdfr * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
2261033Sdfr * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
2361033Sdfr * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
2461033Sdfr * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
2561033Sdfr * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
2661033Sdfr * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
2761033Sdfr * THE POSSIBILITY OF SUCH DAMAGES.
2861033Sdfr */
2961033Sdfr
3065822Sjhb#include <sys/cdefs.h>
3161033Sdfr__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath.c 186904 2009-01-08 17:12:47Z sam $");
3261033Sdfr
3361033Sdfr/*
3461033Sdfr * Driver for the Atheros Wireless LAN controller.
3561033Sdfr *
3661033Sdfr * This software is derived from work of Atsushi Onoe; his contribution
3761033Sdfr * is greatly appreciated.
3861033Sdfr */
3961033Sdfr
4061033Sdfr#include "opt_inet.h"
4161033Sdfr#include "opt_ath.h"
4261033Sdfr
4361033Sdfr#include <sys/param.h>
4461033Sdfr#include <sys/systm.h>
4561033Sdfr#include <sys/sysctl.h>
4661033Sdfr#include <sys/mbuf.h>
4761033Sdfr#include <sys/malloc.h>
4861033Sdfr#include <sys/lock.h>
4961033Sdfr#include <sys/mutex.h>
5061033Sdfr#include <sys/kernel.h>
5161033Sdfr#include <sys/socket.h>
5261033Sdfr#include <sys/sockio.h>
5361033Sdfr#include <sys/errno.h>
5461033Sdfr#include <sys/callout.h>
5561033Sdfr#include <sys/bus.h>
5661033Sdfr#include <sys/endian.h>
5761033Sdfr#include <sys/kthread.h>
5861033Sdfr#include <sys/taskqueue.h>
5961033Sdfr
6061033Sdfr#include <machine/bus.h>
6161033Sdfr
6261033Sdfr#include <net/if.h>
6361033Sdfr#include <net/if_dl.h>
6461033Sdfr#include <net/if_media.h>
6561033Sdfr#include <net/if_types.h>
6661033Sdfr#include <net/if_arp.h>
6761033Sdfr#include <net/ethernet.h>
6861033Sdfr#include <net/if_llc.h>
6961033Sdfr
7061033Sdfr#include <net80211/ieee80211_var.h>
7161033Sdfr#ifdef ATH_SUPPORT_TDMA
7261033Sdfr#include <net80211/ieee80211_tdma.h>
7361033Sdfr#endif
7461033Sdfr
7561033Sdfr#include <net/bpf.h>
7661033Sdfr
7761033Sdfr#ifdef INET
7861033Sdfr#include <netinet/in.h>
7961033Sdfr#include <netinet/if_ether.h>
8061033Sdfr#endif
8161033Sdfr
8261033Sdfr#include <dev/ath/if_athvar.h>
8361033Sdfr#include <dev/ath/ath_hal/ah_devid.h>		/* XXX for softled */
8461033Sdfr
8561033Sdfr#ifdef ATH_TX99_DIAG
8661033Sdfr#include <dev/ath/ath_tx99/ath_tx99.h>
8761033Sdfr#endif
8861033Sdfr
8961033Sdfr/*
9061033Sdfr * We require a HAL w/ the changes for split tx/rx MIC.
9161033Sdfr */
9261033SdfrCTASSERT(HAL_ABI_VERSION > 0x06052200);
9361033Sdfr
9461033Sdfr/*
9561033Sdfr * ATH_BCBUF determines the number of vap's that can transmit
9661033Sdfr * beacons and also (currently) the number of vap's that can
9761033Sdfr * have unique mac addresses/bssid.  When staggering beacons
9861033Sdfr * 4 is probably a good max as otherwise the beacons become
9961033Sdfr * very closely spaced and there is limited time for cab q traffic
10061033Sdfr * to go out.  You can burst beacons instead but that is not good
10161033Sdfr * for stations in power save and at some point you really want
10261033Sdfr * another radio (and channel).
10361033Sdfr *
10461033Sdfr * The limit on the number of mac addresses is tied to our use of
10561033Sdfr * the U/L bit and tracking addresses in a byte; it would be
10661033Sdfr * worthwhile to allow more for applications like proxy sta.
10761033Sdfr */
10861033SdfrCTASSERT(ATH_BCBUF <= 8);
10961033Sdfr
11061033Sdfr/* unaligned little endian access */
11161033Sdfr#define LE_READ_2(p)							\
11261033Sdfr	((u_int16_t)							\
11361033Sdfr	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
11461033Sdfr#define LE_READ_4(p)							\
11561033Sdfr	((u_int32_t)							\
11661033Sdfr	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) |	\
11761033Sdfr	  (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
11861033Sdfr
11961033Sdfr#define	CTRY_XR9	5001		/* Ubiquiti XR9 */
12061033Sdfr#define	CTRY_GZ901	5002		/* ZComax GZ-901 */
12161033Sdfr
12261033Sdfrstatic struct ieee80211vap *ath_vap_create(struct ieee80211com *,
12361033Sdfr		    const char name[IFNAMSIZ], int unit, int opmode,
12461033Sdfr		    int flags, const uint8_t bssid[IEEE80211_ADDR_LEN],
12561033Sdfr		    const uint8_t mac[IEEE80211_ADDR_LEN]);
12661033Sdfrstatic void	ath_vap_delete(struct ieee80211vap *);
12761033Sdfrstatic void	ath_init(void *);
12861033Sdfrstatic void	ath_stop_locked(struct ifnet *);
12961033Sdfrstatic void	ath_stop(struct ifnet *);
13061033Sdfrstatic void	ath_start(struct ifnet *);
13161033Sdfrstatic int	ath_reset(struct ifnet *);
13261033Sdfrstatic int	ath_reset_vap(struct ieee80211vap *, u_long);
13361033Sdfrstatic int	ath_media_change(struct ifnet *);
13461033Sdfrstatic void	ath_watchdog(struct ifnet *);
13561033Sdfrstatic int	ath_ioctl(struct ifnet *, u_long, caddr_t);
13661033Sdfrstatic void	ath_fatal_proc(void *, int);
13761033Sdfrstatic void	ath_bmiss_vap(struct ieee80211vap *);
13861033Sdfrstatic void	ath_bmiss_proc(void *, int);
13961033Sdfrstatic int	ath_keyset(struct ath_softc *, const struct ieee80211_key *,
14064199Shsu			struct ieee80211_node *);
14161033Sdfrstatic int	ath_key_alloc(struct ieee80211vap *,
14261033Sdfr			struct ieee80211_key *,
14361033Sdfr			ieee80211_keyix *, ieee80211_keyix *);
14461033Sdfrstatic int	ath_key_delete(struct ieee80211vap *,
14561033Sdfr			const struct ieee80211_key *);
14661033Sdfrstatic int	ath_key_set(struct ieee80211vap *, const struct ieee80211_key *,
14761033Sdfr			const u_int8_t mac[IEEE80211_ADDR_LEN]);
14861033Sdfrstatic void	ath_key_update_begin(struct ieee80211vap *);
14961033Sdfrstatic void	ath_key_update_end(struct ieee80211vap *);
15061033Sdfrstatic void	ath_update_mcast(struct ifnet *);
15161033Sdfrstatic void	ath_update_promisc(struct ifnet *);
15261033Sdfrstatic void	ath_mode_init(struct ath_softc *);
15361033Sdfrstatic void	ath_setslottime(struct ath_softc *);
15461033Sdfrstatic void	ath_updateslot(struct ifnet *);
15561033Sdfrstatic int	ath_beaconq_setup(struct ath_hal *);
15661033Sdfrstatic int	ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
15761033Sdfrstatic void	ath_beacon_update(struct ieee80211vap *, int item);
15861033Sdfrstatic void	ath_beacon_setup(struct ath_softc *, struct ath_buf *);
15961033Sdfrstatic void	ath_beacon_proc(void *, int);
16061033Sdfrstatic struct ath_buf *ath_beacon_generate(struct ath_softc *,
16161033Sdfr			struct ieee80211vap *);
16261033Sdfrstatic void	ath_bstuck_proc(void *, int);
16361033Sdfrstatic void	ath_beacon_return(struct ath_softc *, struct ath_buf *);
16461033Sdfrstatic void	ath_beacon_free(struct ath_softc *);
16561033Sdfrstatic void	ath_beacon_config(struct ath_softc *, struct ieee80211vap *);
16661033Sdfrstatic void	ath_descdma_cleanup(struct ath_softc *sc,
16761033Sdfr			struct ath_descdma *, ath_bufhead *);
16861033Sdfrstatic int	ath_desc_alloc(struct ath_softc *);
16961033Sdfrstatic void	ath_desc_free(struct ath_softc *);
17061033Sdfrstatic struct ieee80211_node *ath_node_alloc(struct ieee80211vap *,
17161033Sdfr			const uint8_t [IEEE80211_ADDR_LEN]);
17261033Sdfrstatic void	ath_node_free(struct ieee80211_node *);
17361033Sdfrstatic void	ath_node_getsignal(const struct ieee80211_node *,
17461033Sdfr			int8_t *, int8_t *);
17561033Sdfrstatic int	ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
17661033Sdfrstatic void	ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
17761033Sdfr			int subtype, int rssi, int noise, u_int32_t rstamp);
17861033Sdfrstatic void	ath_setdefantenna(struct ath_softc *, u_int);
17961033Sdfrstatic void	ath_rx_proc(void *, int);
18061033Sdfrstatic void	ath_txq_init(struct ath_softc *sc, struct ath_txq *, int);
18161033Sdfrstatic struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
18261033Sdfrstatic int	ath_tx_setup(struct ath_softc *, int, int);
18361033Sdfrstatic int	ath_wme_update(struct ieee80211com *);
18461033Sdfrstatic void	ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
18561033Sdfrstatic void	ath_tx_cleanup(struct ath_softc *);
18661033Sdfrstatic void	ath_freetx(struct mbuf *);
18761033Sdfrstatic int	ath_tx_start(struct ath_softc *, struct ieee80211_node *,
18861033Sdfr			     struct ath_buf *, struct mbuf *);
18961033Sdfrstatic void	ath_tx_proc_q0(void *, int);
19061033Sdfrstatic void	ath_tx_proc_q0123(void *, int);
19161033Sdfrstatic void	ath_tx_proc(void *, int);
19261033Sdfrstatic void	ath_tx_draintxq(struct ath_softc *, struct ath_txq *);
19361033Sdfrstatic int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
19461033Sdfrstatic void	ath_draintxq(struct ath_softc *);
19561033Sdfrstatic void	ath_stoprecv(struct ath_softc *);
19661033Sdfrstatic int	ath_startrecv(struct ath_softc *);
19761033Sdfrstatic void	ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
19861033Sdfrstatic void	ath_scan_start(struct ieee80211com *);
19961033Sdfrstatic void	ath_scan_end(struct ieee80211com *);
20061033Sdfrstatic void	ath_set_channel(struct ieee80211com *);
20161033Sdfrstatic void	ath_calibrate(void *);
20261033Sdfrstatic int	ath_newstate(struct ieee80211vap *, enum ieee80211_state, int);
20361033Sdfrstatic void	ath_setup_stationkey(struct ieee80211_node *);
20461033Sdfrstatic void	ath_newassoc(struct ieee80211_node *, int);
205static int	ath_setregdomain(struct ieee80211com *,
206		    struct ieee80211_regdomain *, int,
207		    struct ieee80211_channel []);
208static void	ath_getradiocaps(struct ieee80211com *, int *,
209		    struct ieee80211_channel []);
210static int	ath_getchannels(struct ath_softc *);
211static void	ath_led_event(struct ath_softc *, int);
212
213static int	ath_rate_setup(struct ath_softc *, u_int mode);
214static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
215
216static void	ath_sysctlattach(struct ath_softc *);
217static int	ath_raw_xmit(struct ieee80211_node *,
218			struct mbuf *, const struct ieee80211_bpf_params *);
219static void	ath_bpfattach(struct ath_softc *);
220static void	ath_announce(struct ath_softc *);
221
222#ifdef ATH_SUPPORT_TDMA
223static void	ath_tdma_settimers(struct ath_softc *sc, u_int32_t nexttbtt,
224		    u_int32_t bintval);
225static void	ath_tdma_bintvalsetup(struct ath_softc *sc,
226		    const struct ieee80211_tdma_state *tdma);
227static void	ath_tdma_config(struct ath_softc *sc, struct ieee80211vap *vap);
228static void	ath_tdma_update(struct ieee80211_node *ni,
229		    const struct ieee80211_tdma_param *tdma);
230static void	ath_tdma_beacon_send(struct ath_softc *sc,
231		    struct ieee80211vap *vap);
232
233static __inline void
234ath_hal_setcca(struct ath_hal *ah, int ena)
235{
236	/*
237	 * NB: fill me in; this is not provided by default because disabling
238	 *     CCA in most locales violates regulatory.
239	 */
240}
241
242static __inline int
243ath_hal_getcca(struct ath_hal *ah)
244{
245	u_int32_t diag;
246	if (ath_hal_getcapability(ah, HAL_CAP_DIAG, 0, &diag) != HAL_OK)
247		return 1;
248	return ((diag & 0x500000) == 0);
249}
250
251#define	TDMA_EP_MULTIPLIER	(1<<10) /* pow2 to optimize out * and / */
252#define	TDMA_LPF_LEN		6
253#define	TDMA_DUMMY_MARKER	0x127
254#define	TDMA_EP_MUL(x, mul)	((x) * (mul))
255#define	TDMA_IN(x)		(TDMA_EP_MUL((x), TDMA_EP_MULTIPLIER))
256#define	TDMA_LPF(x, y, len) \
257    ((x != TDMA_DUMMY_MARKER) ? (((x) * ((len)-1) + (y)) / (len)) : (y))
258#define	TDMA_SAMPLE(x, y) do {					\
259	x = TDMA_LPF((x), TDMA_IN(y), TDMA_LPF_LEN);		\
260} while (0)
261#define	TDMA_EP_RND(x,mul) \
262	((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
263#define	TDMA_AVG(x)		TDMA_EP_RND(x, TDMA_EP_MULTIPLIER)
264#endif /* ATH_SUPPORT_TDMA */
265
266SYSCTL_DECL(_hw_ath);
267
268/* XXX validate sysctl values */
269static	int ath_longcalinterval = 30;		/* long cals every 30 secs */
270SYSCTL_INT(_hw_ath, OID_AUTO, longcal, CTLFLAG_RW, &ath_longcalinterval,
271	    0, "long chip calibration interval (secs)");
272static	int ath_shortcalinterval = 100;		/* short cals every 100 ms */
273SYSCTL_INT(_hw_ath, OID_AUTO, shortcal, CTLFLAG_RW, &ath_shortcalinterval,
274	    0, "short chip calibration interval (msecs)");
275static	int ath_resetcalinterval = 20*60;	/* reset cal state 20 mins */
276SYSCTL_INT(_hw_ath, OID_AUTO, resetcal, CTLFLAG_RW, &ath_resetcalinterval,
277	    0, "reset chip calibration results (secs)");
278
279static	int ath_rxbuf = ATH_RXBUF;		/* # rx buffers to allocate */
280SYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RW, &ath_rxbuf,
281	    0, "rx buffers allocated");
282TUNABLE_INT("hw.ath.rxbuf", &ath_rxbuf);
283static	int ath_txbuf = ATH_TXBUF;		/* # tx buffers to allocate */
284SYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RW, &ath_txbuf,
285	    0, "tx buffers allocated");
286TUNABLE_INT("hw.ath.txbuf", &ath_txbuf);
287
288#ifdef ATH_DEBUG
289enum {
290	ATH_DEBUG_XMIT		= 0x00000001,	/* basic xmit operation */
291	ATH_DEBUG_XMIT_DESC	= 0x00000002,	/* xmit descriptors */
292	ATH_DEBUG_RECV		= 0x00000004,	/* basic recv operation */
293	ATH_DEBUG_RECV_DESC	= 0x00000008,	/* recv descriptors */
294	ATH_DEBUG_RATE		= 0x00000010,	/* rate control */
295	ATH_DEBUG_RESET		= 0x00000020,	/* reset processing */
296	ATH_DEBUG_MODE		= 0x00000040,	/* mode init/setup */
297	ATH_DEBUG_BEACON 	= 0x00000080,	/* beacon handling */
298	ATH_DEBUG_WATCHDOG 	= 0x00000100,	/* watchdog timeout */
299	ATH_DEBUG_INTR		= 0x00001000,	/* ISR */
300	ATH_DEBUG_TX_PROC	= 0x00002000,	/* tx ISR proc */
301	ATH_DEBUG_RX_PROC	= 0x00004000,	/* rx ISR proc */
302	ATH_DEBUG_BEACON_PROC	= 0x00008000,	/* beacon ISR proc */
303	ATH_DEBUG_CALIBRATE	= 0x00010000,	/* periodic calibration */
304	ATH_DEBUG_KEYCACHE	= 0x00020000,	/* key cache management */
305	ATH_DEBUG_STATE		= 0x00040000,	/* 802.11 state transitions */
306	ATH_DEBUG_NODE		= 0x00080000,	/* node management */
307	ATH_DEBUG_LED		= 0x00100000,	/* led management */
308	ATH_DEBUG_FF		= 0x00200000,	/* fast frames */
309	ATH_DEBUG_DFS		= 0x00400000,	/* DFS processing */
310	ATH_DEBUG_TDMA		= 0x00800000,	/* TDMA processing */
311	ATH_DEBUG_TDMA_TIMER	= 0x01000000,	/* TDMA timer processing */
312	ATH_DEBUG_REGDOMAIN	= 0x02000000,	/* regulatory processing */
313	ATH_DEBUG_FATAL		= 0x80000000,	/* fatal errors */
314	ATH_DEBUG_ANY		= 0xffffffff
315};
316static	int ath_debug = 0;
317SYSCTL_INT(_hw_ath, OID_AUTO, debug, CTLFLAG_RW, &ath_debug,
318	    0, "control debugging printfs");
319TUNABLE_INT("hw.ath.debug", &ath_debug);
320
321#define	IFF_DUMPPKTS(sc, m) \
322	((sc->sc_debug & (m)) || \
323	    (sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
324#define	DPRINTF(sc, m, fmt, ...) do {				\
325	if (sc->sc_debug & (m))					\
326		printf(fmt, __VA_ARGS__);			\
327} while (0)
328#define	KEYPRINTF(sc, ix, hk, mac) do {				\
329	if (sc->sc_debug & ATH_DEBUG_KEYCACHE)			\
330		ath_keyprint(sc, __func__, ix, hk, mac);	\
331} while (0)
332static	void ath_printrxbuf(struct ath_softc *, const struct ath_buf *bf,
333	u_int ix, int);
334static	void ath_printtxbuf(struct ath_softc *, const struct ath_buf *bf,
335	u_int qnum, u_int ix, int done);
336#else
337#define	IFF_DUMPPKTS(sc, m) \
338	((sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
339#define	DPRINTF(sc, m, fmt, ...) do {				\
340	(void) sc;						\
341} while (0)
342#define	KEYPRINTF(sc, k, ix, mac) do {				\
343	(void) sc;						\
344} while (0)
345#endif
346
347MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
348
349int
350ath_attach(u_int16_t devid, struct ath_softc *sc)
351{
352	struct ifnet *ifp;
353	struct ieee80211com *ic;
354	struct ath_hal *ah = NULL;
355	HAL_STATUS status;
356	int error = 0, i;
357	u_int wmodes;
358
359	DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
360
361	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
362	if (ifp == NULL) {
363		device_printf(sc->sc_dev, "can not if_alloc()\n");
364		error = ENOSPC;
365		goto bad;
366	}
367	ic = ifp->if_l2com;
368
369	/* set these up early for if_printf use */
370	if_initname(ifp, device_get_name(sc->sc_dev),
371		device_get_unit(sc->sc_dev));
372
373	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, &status);
374	if (ah == NULL) {
375		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
376			status);
377		error = ENXIO;
378		goto bad;
379	}
380	if (ah->ah_abi != HAL_ABI_VERSION) {
381		if_printf(ifp, "HAL ABI mismatch detected "
382			"(HAL:0x%x != driver:0x%x)\n",
383			ah->ah_abi, HAL_ABI_VERSION);
384		error = ENXIO;
385		goto bad;
386	}
387	sc->sc_ah = ah;
388	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
389#ifdef	ATH_DEBUG
390	sc->sc_debug = ath_debug;
391#endif
392
393	/*
394	 * Check if the MAC has multi-rate retry support.
395	 * We do this by trying to setup a fake extended
396	 * descriptor.  MAC's that don't have support will
397	 * return false w/o doing anything.  MAC's that do
398	 * support it will return true w/o doing anything.
399	 */
400	sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
401
402	/*
403	 * Check if the device has hardware counters for PHY
404	 * errors.  If so we need to enable the MIB interrupt
405	 * so we can act on stat triggers.
406	 */
407	if (ath_hal_hwphycounters(ah))
408		sc->sc_needmib = 1;
409
410	/*
411	 * Get the hardware key cache size.
412	 */
413	sc->sc_keymax = ath_hal_keycachesize(ah);
414	if (sc->sc_keymax > ATH_KEYMAX) {
415		if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
416			ATH_KEYMAX, sc->sc_keymax);
417		sc->sc_keymax = ATH_KEYMAX;
418	}
419	/*
420	 * Reset the key cache since some parts do not
421	 * reset the contents on initial power up.
422	 */
423	for (i = 0; i < sc->sc_keymax; i++)
424		ath_hal_keyreset(ah, i);
425
426	/*
427	 * Collect the default channel list.
428	 */
429	error = ath_getchannels(sc);
430	if (error != 0)
431		goto bad;
432
433	/*
434	 * Setup rate tables for all potential media types.
435	 */
436	ath_rate_setup(sc, IEEE80211_MODE_11A);
437	ath_rate_setup(sc, IEEE80211_MODE_11B);
438	ath_rate_setup(sc, IEEE80211_MODE_11G);
439	ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
440	ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
441	ath_rate_setup(sc, IEEE80211_MODE_STURBO_A);
442	ath_rate_setup(sc, IEEE80211_MODE_11NA);
443	ath_rate_setup(sc, IEEE80211_MODE_11NG);
444	ath_rate_setup(sc, IEEE80211_MODE_HALF);
445	ath_rate_setup(sc, IEEE80211_MODE_QUARTER);
446
447	/* NB: setup here so ath_rate_update is happy */
448	ath_setcurmode(sc, IEEE80211_MODE_11A);
449
450	/*
451	 * Allocate tx+rx descriptors and populate the lists.
452	 */
453	error = ath_desc_alloc(sc);
454	if (error != 0) {
455		if_printf(ifp, "failed to allocate descriptors: %d\n", error);
456		goto bad;
457	}
458	callout_init(&sc->sc_cal_ch, CALLOUT_MPSAFE);
459
460	ATH_TXBUF_LOCK_INIT(sc);
461
462	sc->sc_tq = taskqueue_create("ath_taskq", M_NOWAIT,
463		taskqueue_thread_enqueue, &sc->sc_tq);
464	taskqueue_start_threads(&sc->sc_tq, 1, PI_NET,
465		"%s taskq", ifp->if_xname);
466
467	TASK_INIT(&sc->sc_rxtask, 0, ath_rx_proc, sc);
468	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
469	TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_proc, sc);
470
471	/*
472	 * Allocate hardware transmit queues: one queue for
473	 * beacon frames and one data queue for each QoS
474	 * priority.  Note that the hal handles reseting
475	 * these queues at the needed time.
476	 *
477	 * XXX PS-Poll
478	 */
479	sc->sc_bhalq = ath_beaconq_setup(ah);
480	if (sc->sc_bhalq == (u_int) -1) {
481		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
482		error = EIO;
483		goto bad2;
484	}
485	sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
486	if (sc->sc_cabq == NULL) {
487		if_printf(ifp, "unable to setup CAB xmit queue!\n");
488		error = EIO;
489		goto bad2;
490	}
491	/* NB: insure BK queue is the lowest priority h/w queue */
492	if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
493		if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
494			ieee80211_wme_acnames[WME_AC_BK]);
495		error = EIO;
496		goto bad2;
497	}
498	if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
499	    !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
500	    !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
501		/*
502		 * Not enough hardware tx queues to properly do WME;
503		 * just punt and assign them all to the same h/w queue.
504		 * We could do a better job of this if, for example,
505		 * we allocate queues when we switch from station to
506		 * AP mode.
507		 */
508		if (sc->sc_ac2q[WME_AC_VI] != NULL)
509			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
510		if (sc->sc_ac2q[WME_AC_BE] != NULL)
511			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
512		sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
513		sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
514		sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
515	}
516
517	/*
518	 * Special case certain configurations.  Note the
519	 * CAB queue is handled by these specially so don't
520	 * include them when checking the txq setup mask.
521	 */
522	switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
523	case 0x01:
524		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
525		break;
526	case 0x0f:
527		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
528		break;
529	default:
530		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
531		break;
532	}
533
534	/*
535	 * Setup rate control.  Some rate control modules
536	 * call back to change the anntena state so expose
537	 * the necessary entry points.
538	 * XXX maybe belongs in struct ath_ratectrl?
539	 */
540	sc->sc_setdefantenna = ath_setdefantenna;
541	sc->sc_rc = ath_rate_attach(sc);
542	if (sc->sc_rc == NULL) {
543		error = EIO;
544		goto bad2;
545	}
546
547	sc->sc_blinking = 0;
548	sc->sc_ledstate = 1;
549	sc->sc_ledon = 0;			/* low true */
550	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
551	callout_init(&sc->sc_ledtimer, CALLOUT_MPSAFE);
552	/*
553	 * Auto-enable soft led processing for IBM cards and for
554	 * 5211 minipci cards.  Users can also manually enable/disable
555	 * support with a sysctl.
556	 */
557	sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
558	if (sc->sc_softled) {
559		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin);
560		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
561	}
562
563	ifp->if_softc = sc;
564	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
565	ifp->if_start = ath_start;
566	ifp->if_watchdog = ath_watchdog;
567	ifp->if_ioctl = ath_ioctl;
568	ifp->if_init = ath_init;
569	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
570	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
571	IFQ_SET_READY(&ifp->if_snd);
572
573	ic->ic_ifp = ifp;
574	/* XXX not right but it's not used anywhere important */
575	ic->ic_phytype = IEEE80211_T_OFDM;
576	ic->ic_opmode = IEEE80211_M_STA;
577	ic->ic_caps =
578		  IEEE80211_C_STA		/* station mode */
579		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
580		| IEEE80211_C_HOSTAP		/* hostap mode */
581		| IEEE80211_C_MONITOR		/* monitor mode */
582		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
583		| IEEE80211_C_WDS		/* 4-address traffic works */
584		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
585		| IEEE80211_C_SHSLOT		/* short slot time supported */
586		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
587		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
588		| IEEE80211_C_TXFRAG		/* handle tx frags */
589		;
590	/*
591	 * Query the hal to figure out h/w crypto support.
592	 */
593	if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
594		ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP;
595	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
596		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_OCB;
597	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
598		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_CCM;
599	if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
600		ic->ic_cryptocaps |= IEEE80211_CRYPTO_CKIP;
601	if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
602		ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIP;
603		/*
604		 * Check if h/w does the MIC and/or whether the
605		 * separate key cache entries are required to
606		 * handle both tx+rx MIC keys.
607		 */
608		if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
609			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
610		/*
611		 * If the h/w supports storing tx+rx MIC keys
612		 * in one cache slot automatically enable use.
613		 */
614		if (ath_hal_hastkipsplit(ah) ||
615		    !ath_hal_settkipsplit(ah, AH_FALSE))
616			sc->sc_splitmic = 1;
617		/*
618		 * If the h/w can do TKIP MIC together with WME then
619		 * we use it; otherwise we force the MIC to be done
620		 * in software by the net80211 layer.
621		 */
622		if (ath_hal_haswmetkipmic(ah))
623			sc->sc_wmetkipmic = 1;
624	}
625	sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
626	sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
627	/*
628	 * Mark key cache slots associated with global keys
629	 * as in use.  If we knew TKIP was not to be used we
630	 * could leave the +32, +64, and +32+64 slots free.
631	 */
632	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
633		setbit(sc->sc_keymap, i);
634		setbit(sc->sc_keymap, i+64);
635		if (sc->sc_splitmic) {
636			setbit(sc->sc_keymap, i+32);
637			setbit(sc->sc_keymap, i+32+64);
638		}
639	}
640	/*
641	 * TPC support can be done either with a global cap or
642	 * per-packet support.  The latter is not available on
643	 * all parts.  We're a bit pedantic here as all parts
644	 * support a global cap.
645	 */
646	if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
647		ic->ic_caps |= IEEE80211_C_TXPMGT;
648
649	/*
650	 * Mark WME capability only if we have sufficient
651	 * hardware queues to do proper priority scheduling.
652	 */
653	if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
654		ic->ic_caps |= IEEE80211_C_WME;
655	/*
656	 * Check for misc other capabilities.
657	 */
658	if (ath_hal_hasbursting(ah))
659		ic->ic_caps |= IEEE80211_C_BURST;
660	sc->sc_hasbmask = ath_hal_hasbssidmask(ah);
661	sc->sc_hastsfadd = ath_hal_hastsfadjust(ah);
662	if (ath_hal_hasfastframes(ah))
663		ic->ic_caps |= IEEE80211_C_FF;
664	wmodes = ath_hal_getwirelessmodes(ah, ic->ic_regdomain.country);
665	if (wmodes & (HAL_MODE_108G|HAL_MODE_TURBO))
666		ic->ic_caps |= IEEE80211_C_TURBOP;
667#ifdef ATH_SUPPORT_TDMA
668	if (ath_hal_macversion(ah) > 0x78) {
669		ic->ic_caps |= IEEE80211_C_TDMA; /* capable of TDMA */
670		ic->ic_tdma_update = ath_tdma_update;
671	}
672#endif
673	/*
674	 * Indicate we need the 802.11 header padded to a
675	 * 32-bit boundary for 4-address and QoS frames.
676	 */
677	ic->ic_flags |= IEEE80211_F_DATAPAD;
678
679	/*
680	 * Query the hal about antenna support.
681	 */
682	sc->sc_defant = ath_hal_getdefantenna(ah);
683
684	/*
685	 * Not all chips have the VEOL support we want to
686	 * use with IBSS beacons; check here for it.
687	 */
688	sc->sc_hasveol = ath_hal_hasveol(ah);
689
690	/* get mac address from hardware */
691	ath_hal_getmac(ah, ic->ic_myaddr);
692	if (sc->sc_hasbmask)
693		ath_hal_getbssidmask(ah, sc->sc_hwbssidmask);
694
695	/* NB: used to size node table key mapping array */
696	ic->ic_max_keyix = sc->sc_keymax;
697	/* call MI attach routine. */
698	ieee80211_ifattach(ic);
699	ic->ic_setregdomain = ath_setregdomain;
700	ic->ic_getradiocaps = ath_getradiocaps;
701	sc->sc_opmode = HAL_M_STA;
702
703	/* override default methods */
704	ic->ic_newassoc = ath_newassoc;
705	ic->ic_updateslot = ath_updateslot;
706	ic->ic_wme.wme_update = ath_wme_update;
707	ic->ic_vap_create = ath_vap_create;
708	ic->ic_vap_delete = ath_vap_delete;
709	ic->ic_raw_xmit = ath_raw_xmit;
710	ic->ic_update_mcast = ath_update_mcast;
711	ic->ic_update_promisc = ath_update_promisc;
712	ic->ic_node_alloc = ath_node_alloc;
713	sc->sc_node_free = ic->ic_node_free;
714	ic->ic_node_free = ath_node_free;
715	ic->ic_node_getsignal = ath_node_getsignal;
716	ic->ic_scan_start = ath_scan_start;
717	ic->ic_scan_end = ath_scan_end;
718	ic->ic_set_channel = ath_set_channel;
719
720	ath_bpfattach(sc);
721	/*
722	 * Setup dynamic sysctl's now that country code and
723	 * regdomain are available from the hal.
724	 */
725	ath_sysctlattach(sc);
726
727	if (bootverbose)
728		ieee80211_announce(ic);
729	ath_announce(sc);
730	return 0;
731bad2:
732	ath_tx_cleanup(sc);
733	ath_desc_free(sc);
734bad:
735	if (ah)
736		ath_hal_detach(ah);
737	if (ifp != NULL)
738		if_free(ifp);
739	sc->sc_invalid = 1;
740	return error;
741}
742
743int
744ath_detach(struct ath_softc *sc)
745{
746	struct ifnet *ifp = sc->sc_ifp;
747
748	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
749		__func__, ifp->if_flags);
750
751	/*
752	 * NB: the order of these is important:
753	 * o stop the chip so no more interrupts will fire
754	 * o call the 802.11 layer before detaching the hal to
755	 *   insure callbacks into the driver to delete global
756	 *   key cache entries can be handled
757	 * o free the taskqueue which drains any pending tasks
758	 * o reclaim the bpf tap now that we know nothing will use
759	 *   it (e.g. rx processing from the task q thread)
760	 * o reclaim the tx queue data structures after calling
761	 *   the 802.11 layer as we'll get called back to reclaim
762	 *   node state and potentially want to use them
763	 * o to cleanup the tx queues the hal is called, so detach
764	 *   it last
765	 * Other than that, it's straightforward...
766	 */
767	ath_stop(ifp);
768	ieee80211_ifdetach(ifp->if_l2com);
769	taskqueue_free(sc->sc_tq);
770	bpfdetach(ifp);
771#ifdef ATH_TX99_DIAG
772	if (sc->sc_tx99 != NULL)
773		sc->sc_tx99->detach(sc->sc_tx99);
774#endif
775	ath_rate_detach(sc->sc_rc);
776	ath_desc_free(sc);
777	ath_tx_cleanup(sc);
778	ath_hal_detach(sc->sc_ah);	/* NB: sets chip in full sleep */
779	if_free(ifp);
780
781	return 0;
782}
783
784/*
785 * MAC address handling for multiple BSS on the same radio.
786 * The first vap uses the MAC address from the EEPROM.  For
787 * subsequent vap's we set the U/L bit (bit 1) in the MAC
788 * address and use the next six bits as an index.
789 */
790static void
791assign_address(struct ath_softc *sc, uint8_t mac[IEEE80211_ADDR_LEN], int clone)
792{
793	int i;
794
795	if (clone && sc->sc_hasbmask) {
796		/* NB: we only do this if h/w supports multiple bssid */
797		for (i = 0; i < 8; i++)
798			if ((sc->sc_bssidmask & (1<<i)) == 0)
799				break;
800		if (i != 0)
801			mac[0] |= (i << 2)|0x2;
802	} else
803		i = 0;
804	sc->sc_bssidmask |= 1<<i;
805	sc->sc_hwbssidmask[0] &= ~mac[0];
806	if (i == 0)
807		sc->sc_nbssid0++;
808}
809
810static void
811reclaim_address(struct ath_softc *sc, const uint8_t mac[IEEE80211_ADDR_LEN])
812{
813	int i = mac[0] >> 2;
814	uint8_t mask;
815
816	if (i != 0 || --sc->sc_nbssid0 == 0) {
817		sc->sc_bssidmask &= ~(1<<i);
818		/* recalculate bssid mask from remaining addresses */
819		mask = 0xff;
820		for (i = 1; i < 8; i++)
821			if (sc->sc_bssidmask & (1<<i))
822				mask &= ~((i<<2)|0x2);
823		sc->sc_hwbssidmask[0] |= mask;
824	}
825}
826
827/*
828 * Assign a beacon xmit slot.  We try to space out
829 * assignments so when beacons are staggered the
830 * traffic coming out of the cab q has maximal time
831 * to go out before the next beacon is scheduled.
832 */
833static int
834assign_bslot(struct ath_softc *sc)
835{
836	u_int slot, free;
837
838	free = 0;
839	for (slot = 0; slot < ATH_BCBUF; slot++)
840		if (sc->sc_bslot[slot] == NULL) {
841			if (sc->sc_bslot[(slot+1)%ATH_BCBUF] == NULL &&
842			    sc->sc_bslot[(slot-1)%ATH_BCBUF] == NULL)
843				return slot;
844			free = slot;
845			/* NB: keep looking for a double slot */
846		}
847	return free;
848}
849
850static struct ieee80211vap *
851ath_vap_create(struct ieee80211com *ic,
852	const char name[IFNAMSIZ], int unit, int opmode, int flags,
853	const uint8_t bssid[IEEE80211_ADDR_LEN],
854	const uint8_t mac0[IEEE80211_ADDR_LEN])
855{
856	struct ath_softc *sc = ic->ic_ifp->if_softc;
857	struct ath_vap *avp;
858	struct ieee80211vap *vap;
859	uint8_t mac[IEEE80211_ADDR_LEN];
860	int ic_opmode, needbeacon, error;
861
862	avp = (struct ath_vap *) malloc(sizeof(struct ath_vap),
863	    M_80211_VAP, M_WAITOK | M_ZERO);
864	needbeacon = 0;
865	IEEE80211_ADDR_COPY(mac, mac0);
866
867	ATH_LOCK(sc);
868	switch (opmode) {
869	case IEEE80211_M_STA:
870		if (sc->sc_nstavaps != 0) {	/* XXX only 1 sta for now */
871			device_printf(sc->sc_dev, "only 1 sta vap supported\n");
872			goto bad;
873		}
874		if (sc->sc_nvaps) {
875			/*
876			 * When there are multiple vaps we must fall
877			 * back to s/w beacon miss handling.
878			 */
879			flags |= IEEE80211_CLONE_NOBEACONS;
880		}
881		if (flags & IEEE80211_CLONE_NOBEACONS)
882			ic_opmode = IEEE80211_M_HOSTAP;
883		else
884			ic_opmode = opmode;
885		break;
886	case IEEE80211_M_IBSS:
887		if (sc->sc_nvaps != 0) {	/* XXX only 1 for now */
888			device_printf(sc->sc_dev,
889			    "only 1 ibss vap supported\n");
890			goto bad;
891		}
892		ic_opmode = opmode;
893		needbeacon = 1;
894		break;
895	case IEEE80211_M_AHDEMO:
896#ifdef ATH_SUPPORT_TDMA
897		if (flags & IEEE80211_CLONE_TDMA) {
898			needbeacon = 1;
899			flags |= IEEE80211_CLONE_NOBEACONS;
900		}
901		/* fall thru... */
902#endif
903	case IEEE80211_M_MONITOR:
904		if (sc->sc_nvaps != 0 && ic->ic_opmode != opmode) {
905			/* XXX not right for monitor mode */
906			ic_opmode = ic->ic_opmode;
907		} else
908			ic_opmode = opmode;
909		break;
910	case IEEE80211_M_HOSTAP:
911		needbeacon = 1;
912		/* fall thru... */
913	case IEEE80211_M_WDS:
914		if (sc->sc_nvaps && ic->ic_opmode == IEEE80211_M_STA) {
915			device_printf(sc->sc_dev,
916			    "wds not supported in sta mode\n");
917			goto bad;
918		}
919		if (opmode == IEEE80211_M_WDS) {
920			/*
921			 * Silently remove any request for a unique
922			 * bssid; WDS vap's always share the local
923			 * mac address.
924			 */
925			flags &= ~IEEE80211_CLONE_BSSID;
926		}
927		ic_opmode = IEEE80211_M_HOSTAP;
928		break;
929	default:
930		device_printf(sc->sc_dev, "unknown opmode %d\n", opmode);
931		goto bad;
932	}
933	/*
934	 * Check that a beacon buffer is available; the code below assumes it.
935	 */
936	if (needbeacon & STAILQ_EMPTY(&sc->sc_bbuf)) {
937		device_printf(sc->sc_dev, "no beacon buffer available\n");
938		goto bad;
939	}
940
941	/* STA, AHDEMO? */
942	if (opmode == IEEE80211_M_HOSTAP) {
943		assign_address(sc, mac, flags & IEEE80211_CLONE_BSSID);
944		ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
945	}
946
947	vap = &avp->av_vap;
948	/* XXX can't hold mutex across if_alloc */
949	ATH_UNLOCK(sc);
950	error = ieee80211_vap_setup(ic, vap, name, unit, opmode, flags,
951	    bssid, mac);
952	ATH_LOCK(sc);
953	if (error != 0) {
954		device_printf(sc->sc_dev, "%s: error %d creating vap\n",
955		    __func__, error);
956		goto bad2;
957	}
958
959	/* h/w crypto support */
960	vap->iv_key_alloc = ath_key_alloc;
961	vap->iv_key_delete = ath_key_delete;
962	vap->iv_key_set = ath_key_set;
963	vap->iv_key_update_begin = ath_key_update_begin;
964	vap->iv_key_update_end = ath_key_update_end;
965
966	/* override various methods */
967	avp->av_recv_mgmt = vap->iv_recv_mgmt;
968	vap->iv_recv_mgmt = ath_recv_mgmt;
969	vap->iv_reset = ath_reset_vap;
970	vap->iv_update_beacon = ath_beacon_update;
971	avp->av_newstate = vap->iv_newstate;
972	vap->iv_newstate = ath_newstate;
973	avp->av_bmiss = vap->iv_bmiss;
974	vap->iv_bmiss = ath_bmiss_vap;
975
976	avp->av_bslot = -1;
977	if (needbeacon) {
978		/*
979		 * Allocate beacon state and setup the q for buffered
980		 * multicast frames.  We know a beacon buffer is
981		 * available because we checked above.
982		 */
983		avp->av_bcbuf = STAILQ_FIRST(&sc->sc_bbuf);
984		STAILQ_REMOVE_HEAD(&sc->sc_bbuf, bf_list);
985		if (opmode != IEEE80211_M_IBSS || !sc->sc_hasveol) {
986			/*
987			 * Assign the vap to a beacon xmit slot.  As above
988			 * this cannot fail to find a free one.
989			 */
990			avp->av_bslot = assign_bslot(sc);
991			KASSERT(sc->sc_bslot[avp->av_bslot] == NULL,
992			    ("beacon slot %u not empty", avp->av_bslot));
993			sc->sc_bslot[avp->av_bslot] = vap;
994			sc->sc_nbcnvaps++;
995		}
996		if (sc->sc_hastsfadd && sc->sc_nbcnvaps > 0) {
997			/*
998			 * Multple vaps are to transmit beacons and we
999			 * have h/w support for TSF adjusting; enable
1000			 * use of staggered beacons.
1001			 */
1002			sc->sc_stagbeacons = 1;
1003		}
1004		ath_txq_init(sc, &avp->av_mcastq, ATH_TXQ_SWQ);
1005	}
1006
1007	ic->ic_opmode = ic_opmode;
1008	if (opmode != IEEE80211_M_WDS) {
1009		sc->sc_nvaps++;
1010		if (opmode == IEEE80211_M_STA)
1011			sc->sc_nstavaps++;
1012	}
1013	switch (ic_opmode) {
1014	case IEEE80211_M_IBSS:
1015		sc->sc_opmode = HAL_M_IBSS;
1016		break;
1017	case IEEE80211_M_STA:
1018		sc->sc_opmode = HAL_M_STA;
1019		break;
1020	case IEEE80211_M_AHDEMO:
1021#ifdef ATH_SUPPORT_TDMA
1022		if (vap->iv_caps & IEEE80211_C_TDMA) {
1023			sc->sc_tdma = 1;
1024			/* NB: disable tsf adjust */
1025			sc->sc_stagbeacons = 0;
1026		}
1027		/*
1028		 * NB: adhoc demo mode is a pseudo mode; to the hal it's
1029		 * just ap mode.
1030		 */
1031		/* fall thru... */
1032#endif
1033	case IEEE80211_M_HOSTAP:
1034		sc->sc_opmode = HAL_M_HOSTAP;
1035		break;
1036	case IEEE80211_M_MONITOR:
1037		sc->sc_opmode = HAL_M_MONITOR;
1038		break;
1039	default:
1040		/* XXX should not happen */
1041		break;
1042	}
1043	if (sc->sc_hastsfadd) {
1044		/*
1045		 * Configure whether or not TSF adjust should be done.
1046		 */
1047		ath_hal_settsfadjust(sc->sc_ah, sc->sc_stagbeacons);
1048	}
1049	if (flags & IEEE80211_CLONE_NOBEACONS) {
1050		/*
1051		 * Enable s/w beacon miss handling.
1052		 */
1053		sc->sc_swbmiss = 1;
1054	}
1055	ATH_UNLOCK(sc);
1056
1057	/* complete setup */
1058	ieee80211_vap_attach(vap, ath_media_change, ieee80211_media_status);
1059	return vap;
1060bad2:
1061	reclaim_address(sc, mac);
1062	ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
1063bad:
1064	free(avp, M_80211_VAP);
1065	ATH_UNLOCK(sc);
1066	return NULL;
1067}
1068
1069static void
1070ath_vap_delete(struct ieee80211vap *vap)
1071{
1072	struct ieee80211com *ic = vap->iv_ic;
1073	struct ifnet *ifp = ic->ic_ifp;
1074	struct ath_softc *sc = ifp->if_softc;
1075	struct ath_hal *ah = sc->sc_ah;
1076	struct ath_vap *avp = ATH_VAP(vap);
1077
1078	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1079		/*
1080		 * Quiesce the hardware while we remove the vap.  In
1081		 * particular we need to reclaim all references to
1082		 * the vap state by any frames pending on the tx queues.
1083		 */
1084		ath_hal_intrset(ah, 0);		/* disable interrupts */
1085		ath_draintxq(sc);		/* stop xmit side */
1086		ath_stoprecv(sc);		/* stop recv side */
1087	}
1088
1089	ieee80211_vap_detach(vap);
1090	ATH_LOCK(sc);
1091	/*
1092	 * Reclaim beacon state.  Note this must be done before
1093	 * the vap instance is reclaimed as we may have a reference
1094	 * to it in the buffer for the beacon frame.
1095	 */
1096	if (avp->av_bcbuf != NULL) {
1097		if (avp->av_bslot != -1) {
1098			sc->sc_bslot[avp->av_bslot] = NULL;
1099			sc->sc_nbcnvaps--;
1100		}
1101		ath_beacon_return(sc, avp->av_bcbuf);
1102		avp->av_bcbuf = NULL;
1103		if (sc->sc_nbcnvaps == 0) {
1104			sc->sc_stagbeacons = 0;
1105			if (sc->sc_hastsfadd)
1106				ath_hal_settsfadjust(sc->sc_ah, 0);
1107		}
1108		/*
1109		 * Reclaim any pending mcast frames for the vap.
1110		 */
1111		ath_tx_draintxq(sc, &avp->av_mcastq);
1112		ATH_TXQ_LOCK_DESTROY(&avp->av_mcastq);
1113	}
1114	/*
1115	 * Update bookkeeping.
1116	 */
1117	if (vap->iv_opmode == IEEE80211_M_STA) {
1118		sc->sc_nstavaps--;
1119		if (sc->sc_nstavaps == 0 && sc->sc_swbmiss)
1120			sc->sc_swbmiss = 0;
1121	} else if (vap->iv_opmode == IEEE80211_M_HOSTAP) {
1122		reclaim_address(sc, vap->iv_myaddr);
1123		ath_hal_setbssidmask(ah, sc->sc_hwbssidmask);
1124	}
1125	if (vap->iv_opmode != IEEE80211_M_WDS)
1126		sc->sc_nvaps--;
1127#ifdef ATH_SUPPORT_TDMA
1128	/* TDMA operation ceases when the last vap is destroyed */
1129	if (sc->sc_tdma && sc->sc_nvaps == 0) {
1130		sc->sc_tdma = 0;
1131		sc->sc_swbmiss = 0;
1132	}
1133#endif
1134	ATH_UNLOCK(sc);
1135	free(avp, M_80211_VAP);
1136
1137	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1138		/*
1139		 * Restart rx+tx machines if still running (RUNNING will
1140		 * be reset if we just destroyed the last vap).
1141		 */
1142		if (ath_startrecv(sc) != 0)
1143			if_printf(ifp, "%s: unable to restart recv logic\n",
1144			    __func__);
1145		if (sc->sc_beacons)
1146			ath_beacon_config(sc, NULL);
1147		ath_hal_intrset(ah, sc->sc_imask);
1148	}
1149}
1150
1151void
1152ath_suspend(struct ath_softc *sc)
1153{
1154	struct ifnet *ifp = sc->sc_ifp;
1155	struct ieee80211com *ic = ifp->if_l2com;
1156
1157	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1158		__func__, ifp->if_flags);
1159
1160	sc->sc_resume_up = (ifp->if_flags & IFF_UP) != 0;
1161	if (ic->ic_opmode == IEEE80211_M_STA)
1162		ath_stop(ifp);
1163	else
1164		ieee80211_suspend_all(ic);
1165	/*
1166	 * NB: don't worry about putting the chip in low power
1167	 * mode; pci will power off our socket on suspend and
1168	 * cardbus detaches the device.
1169	 */
1170}
1171
1172/*
1173 * Reset the key cache since some parts do not reset the
1174 * contents on resume.  First we clear all entries, then
1175 * re-load keys that the 802.11 layer assumes are setup
1176 * in h/w.
1177 */
1178static void
1179ath_reset_keycache(struct ath_softc *sc)
1180{
1181	struct ifnet *ifp = sc->sc_ifp;
1182	struct ieee80211com *ic = ifp->if_l2com;
1183	struct ath_hal *ah = sc->sc_ah;
1184	int i;
1185
1186	for (i = 0; i < sc->sc_keymax; i++)
1187		ath_hal_keyreset(ah, i);
1188	ieee80211_crypto_reload_keys(ic);
1189}
1190
1191void
1192ath_resume(struct ath_softc *sc)
1193{
1194	struct ifnet *ifp = sc->sc_ifp;
1195	struct ieee80211com *ic = ifp->if_l2com;
1196	struct ath_hal *ah = sc->sc_ah;
1197	HAL_STATUS status;
1198
1199	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1200		__func__, ifp->if_flags);
1201
1202	/*
1203	 * Must reset the chip before we reload the
1204	 * keycache as we were powered down on suspend.
1205	 */
1206	ath_hal_reset(ah, sc->sc_opmode, &sc->sc_curchan, AH_FALSE, &status);
1207	ath_reset_keycache(sc);
1208	if (sc->sc_resume_up) {
1209		if (ic->ic_opmode == IEEE80211_M_STA) {
1210			ath_init(sc);
1211			ieee80211_beacon_miss(ic);
1212		} else
1213			ieee80211_resume_all(ic);
1214	}
1215	if (sc->sc_softled) {
1216		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin);
1217		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
1218	}
1219}
1220
1221void
1222ath_shutdown(struct ath_softc *sc)
1223{
1224	struct ifnet *ifp = sc->sc_ifp;
1225
1226	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1227		__func__, ifp->if_flags);
1228
1229	ath_stop(ifp);
1230	/* NB: no point powering down chip as we're about to reboot */
1231}
1232
1233/*
1234 * Interrupt handler.  Most of the actual processing is deferred.
1235 */
1236void
1237ath_intr(void *arg)
1238{
1239	struct ath_softc *sc = arg;
1240	struct ifnet *ifp = sc->sc_ifp;
1241	struct ath_hal *ah = sc->sc_ah;
1242	HAL_INT status;
1243
1244	if (sc->sc_invalid) {
1245		/*
1246		 * The hardware is not ready/present, don't touch anything.
1247		 * Note this can happen early on if the IRQ is shared.
1248		 */
1249		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
1250		return;
1251	}
1252	if (!ath_hal_intrpend(ah))		/* shared irq, not for us */
1253		return;
1254	if ((ifp->if_flags & IFF_UP) == 0 ||
1255	    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1256		HAL_INT status;
1257
1258		DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1259			__func__, ifp->if_flags);
1260		ath_hal_getisr(ah, &status);	/* clear ISR */
1261		ath_hal_intrset(ah, 0);		/* disable further intr's */
1262		return;
1263	}
1264	/*
1265	 * Figure out the reason(s) for the interrupt.  Note
1266	 * that the hal returns a pseudo-ISR that may include
1267	 * bits we haven't explicitly enabled so we mask the
1268	 * value to insure we only process bits we requested.
1269	 */
1270	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
1271	DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
1272	status &= sc->sc_imask;			/* discard unasked for bits */
1273	if (status & HAL_INT_FATAL) {
1274		sc->sc_stats.ast_hardware++;
1275		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
1276		ath_fatal_proc(sc, 0);
1277	} else {
1278		if (status & HAL_INT_SWBA) {
1279			/*
1280			 * Software beacon alert--time to send a beacon.
1281			 * Handle beacon transmission directly; deferring
1282			 * this is too slow to meet timing constraints
1283			 * under load.
1284			 */
1285#ifdef ATH_SUPPORT_TDMA
1286			if (sc->sc_tdma) {
1287				if (sc->sc_tdmaswba == 0) {
1288					struct ieee80211com *ic = ifp->if_l2com;
1289					struct ieee80211vap *vap =
1290					    TAILQ_FIRST(&ic->ic_vaps);
1291					ath_tdma_beacon_send(sc, vap);
1292					sc->sc_tdmaswba =
1293					    vap->iv_tdma->tdma_bintval;
1294				} else
1295					sc->sc_tdmaswba--;
1296			} else
1297#endif
1298				ath_beacon_proc(sc, 0);
1299		}
1300		if (status & HAL_INT_RXEOL) {
1301			/*
1302			 * NB: the hardware should re-read the link when
1303			 *     RXE bit is written, but it doesn't work at
1304			 *     least on older hardware revs.
1305			 */
1306			sc->sc_stats.ast_rxeol++;
1307			sc->sc_rxlink = NULL;
1308		}
1309		if (status & HAL_INT_TXURN) {
1310			sc->sc_stats.ast_txurn++;
1311			/* bump tx trigger level */
1312			ath_hal_updatetxtriglevel(ah, AH_TRUE);
1313		}
1314		if (status & HAL_INT_RX)
1315			taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1316		if (status & HAL_INT_TX)
1317			taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
1318		if (status & HAL_INT_BMISS) {
1319			sc->sc_stats.ast_bmiss++;
1320			taskqueue_enqueue(sc->sc_tq, &sc->sc_bmisstask);
1321		}
1322		if (status & HAL_INT_MIB) {
1323			sc->sc_stats.ast_mib++;
1324			/*
1325			 * Disable interrupts until we service the MIB
1326			 * interrupt; otherwise it will continue to fire.
1327			 */
1328			ath_hal_intrset(ah, 0);
1329			/*
1330			 * Let the hal handle the event.  We assume it will
1331			 * clear whatever condition caused the interrupt.
1332			 */
1333			ath_hal_mibevent(ah, &sc->sc_halstats);
1334			ath_hal_intrset(ah, sc->sc_imask);
1335		}
1336		if (status & HAL_INT_RXORN) {
1337			/* NB: hal marks HAL_INT_FATAL when RXORN is fatal */
1338			sc->sc_stats.ast_rxorn++;
1339		}
1340	}
1341}
1342
1343static void
1344ath_fatal_proc(void *arg, int pending)
1345{
1346	struct ath_softc *sc = arg;
1347	struct ifnet *ifp = sc->sc_ifp;
1348	u_int32_t *state;
1349	u_int32_t len;
1350	void *sp;
1351
1352	if_printf(ifp, "hardware error; resetting\n");
1353	/*
1354	 * Fatal errors are unrecoverable.  Typically these
1355	 * are caused by DMA errors.  Collect h/w state from
1356	 * the hal so we can diagnose what's going on.
1357	 */
1358	if (ath_hal_getfatalstate(sc->sc_ah, &sp, &len)) {
1359		KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
1360		state = sp;
1361		if_printf(ifp, "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n",
1362		    state[0], state[1] , state[2], state[3],
1363		    state[4], state[5]);
1364	}
1365	ath_reset(ifp);
1366}
1367
1368static void
1369ath_bmiss_vap(struct ieee80211vap *vap)
1370{
1371	struct ifnet *ifp = vap->iv_ic->ic_ifp;
1372	struct ath_softc *sc = ifp->if_softc;
1373	u_int64_t lastrx = sc->sc_lastrx;
1374	u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
1375	u_int bmisstimeout =
1376		vap->iv_bmissthreshold * vap->iv_bss->ni_intval * 1024;
1377
1378	DPRINTF(sc, ATH_DEBUG_BEACON,
1379	    "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
1380	    __func__, (unsigned long long) tsf,
1381	    (unsigned long long)(tsf - lastrx),
1382	    (unsigned long long) lastrx, bmisstimeout);
1383	/*
1384	 * Workaround phantom bmiss interrupts by sanity-checking
1385	 * the time of our last rx'd frame.  If it is within the
1386	 * beacon miss interval then ignore the interrupt.  If it's
1387	 * truly a bmiss we'll get another interrupt soon and that'll
1388	 * be dispatched up for processing.
1389	 */
1390	if (tsf - lastrx > bmisstimeout)
1391		ATH_VAP(vap)->av_bmiss(vap);
1392	else
1393		sc->sc_stats.ast_bmiss_phantom++;
1394}
1395
1396static int
1397ath_hal_gethangstate(struct ath_hal *ah, uint32_t mask, uint32_t *hangs)
1398{
1399	uint32_t rsize;
1400	void *sp;
1401
1402	if (!ath_hal_getdiagstate(ah, 32, &mask, sizeof(&mask), &sp, &rsize))
1403		return 0;
1404	KASSERT(rsize == sizeof(uint32_t), ("resultsize %u", rsize));
1405	*hangs = *(uint32_t *)sp;
1406	return 1;
1407}
1408
1409static void
1410ath_bmiss_proc(void *arg, int pending)
1411{
1412	struct ath_softc *sc = arg;
1413	struct ifnet *ifp = sc->sc_ifp;
1414	uint32_t hangs;
1415
1416	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
1417
1418	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0) {
1419		if_printf(ifp, "bb hang detected (0x%x), reseting\n", hangs);
1420		ath_reset(ifp);
1421	} else
1422		ieee80211_beacon_miss(ifp->if_l2com);
1423}
1424
1425/*
1426 * Convert net80211 channel to a HAL channel with the flags
1427 * constrained to reflect the current operating mode and
1428 * the frequency possibly mapped for GSM channels.
1429 */
1430static void
1431ath_mapchan(const struct ieee80211com *ic,
1432	HAL_CHANNEL *hc, const struct ieee80211_channel *chan)
1433{
1434#define	N(a)	(sizeof(a) / sizeof(a[0]))
1435	static const u_int modeflags[IEEE80211_MODE_MAX] = {
1436		0,			/* IEEE80211_MODE_AUTO */
1437		CHANNEL_A,		/* IEEE80211_MODE_11A */
1438		CHANNEL_B,		/* IEEE80211_MODE_11B */
1439		CHANNEL_PUREG,		/* IEEE80211_MODE_11G */
1440		0,			/* IEEE80211_MODE_FH */
1441		CHANNEL_108A,		/* IEEE80211_MODE_TURBO_A */
1442		CHANNEL_108G,		/* IEEE80211_MODE_TURBO_G */
1443		CHANNEL_ST,		/* IEEE80211_MODE_STURBO_A */
1444		CHANNEL_A,		/* IEEE80211_MODE_11NA */
1445		CHANNEL_PUREG,		/* IEEE80211_MODE_11NG */
1446	};
1447	enum ieee80211_phymode mode = ieee80211_chan2mode(chan);
1448
1449	KASSERT(mode < N(modeflags), ("unexpected phy mode %u", mode));
1450	KASSERT(modeflags[mode] != 0, ("mode %u undefined", mode));
1451	hc->channelFlags = modeflags[mode];
1452	if (IEEE80211_IS_CHAN_HALF(chan))
1453		hc->channelFlags |= CHANNEL_HALF;
1454	if (IEEE80211_IS_CHAN_QUARTER(chan))
1455		hc->channelFlags |= CHANNEL_QUARTER;
1456	if (IEEE80211_IS_CHAN_HT20(chan))
1457		hc->channelFlags |= CHANNEL_HT20;
1458	if (IEEE80211_IS_CHAN_HT40D(chan))
1459		hc->channelFlags |= CHANNEL_HT40MINUS;
1460	if (IEEE80211_IS_CHAN_HT40U(chan))
1461		hc->channelFlags |= CHANNEL_HT40PLUS;
1462
1463	if (IEEE80211_IS_CHAN_GSM(chan)) {
1464		if (ic->ic_regdomain.country == CTRY_XR9)
1465			hc->channel = 1520 + chan->ic_freq;
1466		else if (ic->ic_regdomain.country == CTRY_GZ901)
1467			hc->channel = 1544 + chan->ic_freq;
1468		else
1469			hc->channel = 3344 - chan->ic_freq;
1470	} else
1471		hc->channel = chan->ic_freq;
1472#undef N
1473}
1474
1475/*
1476 * Handle TKIP MIC setup to deal hardware that doesn't do MIC
1477 * calcs together with WME.  If necessary disable the crypto
1478 * hardware and mark the 802.11 state so keys will be setup
1479 * with the MIC work done in software.
1480 */
1481static void
1482ath_settkipmic(struct ath_softc *sc)
1483{
1484	struct ifnet *ifp = sc->sc_ifp;
1485	struct ieee80211com *ic = ifp->if_l2com;
1486
1487	if ((ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIP) && !sc->sc_wmetkipmic) {
1488		if (ic->ic_flags & IEEE80211_F_WME) {
1489			ath_hal_settkipmic(sc->sc_ah, AH_FALSE);
1490			ic->ic_cryptocaps &= ~IEEE80211_CRYPTO_TKIPMIC;
1491		} else {
1492			ath_hal_settkipmic(sc->sc_ah, AH_TRUE);
1493			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
1494		}
1495	}
1496}
1497
1498static void
1499ath_init(void *arg)
1500{
1501	struct ath_softc *sc = (struct ath_softc *) arg;
1502	struct ifnet *ifp = sc->sc_ifp;
1503	struct ieee80211com *ic = ifp->if_l2com;
1504	struct ath_hal *ah = sc->sc_ah;
1505	HAL_STATUS status;
1506
1507	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1508		__func__, ifp->if_flags);
1509
1510	ATH_LOCK(sc);
1511	/*
1512	 * Stop anything previously setup.  This is safe
1513	 * whether this is the first time through or not.
1514	 */
1515	ath_stop_locked(ifp);
1516
1517	/*
1518	 * The basic interface to setting the hardware in a good
1519	 * state is ``reset''.  On return the hardware is known to
1520	 * be powered up and with interrupts disabled.  This must
1521	 * be followed by initialization of the appropriate bits
1522	 * and then setup of the interrupt mask.
1523	 */
1524	ath_mapchan(ic, &sc->sc_curchan, ic->ic_curchan);
1525	ath_settkipmic(sc);
1526	if (!ath_hal_reset(ah, sc->sc_opmode, &sc->sc_curchan, AH_FALSE, &status)) {
1527		if_printf(ifp, "unable to reset hardware; hal status %u\n",
1528			status);
1529		ATH_UNLOCK(sc);
1530		return;
1531	}
1532	ath_chan_change(sc, ic->ic_curchan);
1533
1534	/*
1535	 * Likewise this is set during reset so update
1536	 * state cached in the driver.
1537	 */
1538	sc->sc_diversity = ath_hal_getdiversity(ah);
1539	sc->sc_lastlongcal = 0;
1540	sc->sc_resetcal = 1;
1541	sc->sc_lastcalreset = 0;
1542
1543	/*
1544	 * Setup the hardware after reset: the key cache
1545	 * is filled as needed and the receive engine is
1546	 * set going.  Frame transmit is handled entirely
1547	 * in the frame output path; there's nothing to do
1548	 * here except setup the interrupt mask.
1549	 */
1550	if (ath_startrecv(sc) != 0) {
1551		if_printf(ifp, "unable to start recv logic\n");
1552		ATH_UNLOCK(sc);
1553		return;
1554	}
1555
1556	/*
1557	 * Enable interrupts.
1558	 */
1559	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
1560		  | HAL_INT_RXEOL | HAL_INT_RXORN
1561		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
1562	/*
1563	 * Enable MIB interrupts when there are hardware phy counters.
1564	 * Note we only do this (at the moment) for station mode.
1565	 */
1566	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
1567		sc->sc_imask |= HAL_INT_MIB;
1568
1569	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1570	ath_hal_intrset(ah, sc->sc_imask);
1571
1572	ATH_UNLOCK(sc);
1573
1574#ifdef ATH_TX99_DIAG
1575	if (sc->sc_tx99 != NULL)
1576		sc->sc_tx99->start(sc->sc_tx99);
1577	else
1578#endif
1579	ieee80211_start_all(ic);		/* start all vap's */
1580}
1581
1582static void
1583ath_stop_locked(struct ifnet *ifp)
1584{
1585	struct ath_softc *sc = ifp->if_softc;
1586	struct ath_hal *ah = sc->sc_ah;
1587
1588	DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1589		__func__, sc->sc_invalid, ifp->if_flags);
1590
1591	ATH_LOCK_ASSERT(sc);
1592	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1593		/*
1594		 * Shutdown the hardware and driver:
1595		 *    reset 802.11 state machine
1596		 *    turn off timers
1597		 *    disable interrupts
1598		 *    turn off the radio
1599		 *    clear transmit machinery
1600		 *    clear receive machinery
1601		 *    drain and release tx queues
1602		 *    reclaim beacon resources
1603		 *    power down hardware
1604		 *
1605		 * Note that some of this work is not possible if the
1606		 * hardware is gone (invalid).
1607		 */
1608#ifdef ATH_TX99_DIAG
1609		if (sc->sc_tx99 != NULL)
1610			sc->sc_tx99->stop(sc->sc_tx99);
1611#endif
1612		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1613		ifp->if_timer = 0;
1614		if (!sc->sc_invalid) {
1615			if (sc->sc_softled) {
1616				callout_stop(&sc->sc_ledtimer);
1617				ath_hal_gpioset(ah, sc->sc_ledpin,
1618					!sc->sc_ledon);
1619				sc->sc_blinking = 0;
1620			}
1621			ath_hal_intrset(ah, 0);
1622		}
1623		ath_draintxq(sc);
1624		if (!sc->sc_invalid) {
1625			ath_stoprecv(sc);
1626			ath_hal_phydisable(ah);
1627		} else
1628			sc->sc_rxlink = NULL;
1629		ath_beacon_free(sc);	/* XXX not needed */
1630	}
1631}
1632
1633static void
1634ath_stop(struct ifnet *ifp)
1635{
1636	struct ath_softc *sc = ifp->if_softc;
1637
1638	ATH_LOCK(sc);
1639	ath_stop_locked(ifp);
1640	ATH_UNLOCK(sc);
1641}
1642
1643/*
1644 * Reset the hardware w/o losing operational state.  This is
1645 * basically a more efficient way of doing ath_stop, ath_init,
1646 * followed by state transitions to the current 802.11
1647 * operational state.  Used to recover from various errors and
1648 * to reset or reload hardware state.
1649 */
1650static int
1651ath_reset(struct ifnet *ifp)
1652{
1653	struct ath_softc *sc = ifp->if_softc;
1654	struct ieee80211com *ic = ifp->if_l2com;
1655	struct ath_hal *ah = sc->sc_ah;
1656	HAL_STATUS status;
1657
1658	/*
1659	 * Convert to a HAL channel description with the flags
1660	 * constrained to reflect the current operating mode.
1661	 */
1662	ath_mapchan(ic, &sc->sc_curchan, ic->ic_curchan);
1663
1664	ath_hal_intrset(ah, 0);		/* disable interrupts */
1665	ath_draintxq(sc);		/* stop xmit side */
1666	ath_stoprecv(sc);		/* stop recv side */
1667	ath_settkipmic(sc);		/* configure TKIP MIC handling */
1668	/* NB: indicate channel change so we do a full reset */
1669	if (!ath_hal_reset(ah, sc->sc_opmode, &sc->sc_curchan, AH_TRUE, &status))
1670		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
1671			__func__, status);
1672	sc->sc_diversity = ath_hal_getdiversity(ah);
1673	if (ath_startrecv(sc) != 0)	/* restart recv */
1674		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
1675	/*
1676	 * We may be doing a reset in response to an ioctl
1677	 * that changes the channel so update any state that
1678	 * might change as a result.
1679	 */
1680	ath_chan_change(sc, ic->ic_curchan);
1681	if (sc->sc_beacons) {
1682#ifdef ATH_SUPPORT_TDMA
1683		if (sc->sc_tdma)
1684			ath_tdma_config(sc, NULL);
1685		else
1686#endif
1687			ath_beacon_config(sc, NULL);	/* restart beacons */
1688	}
1689	ath_hal_intrset(ah, sc->sc_imask);
1690
1691	ath_start(ifp);			/* restart xmit */
1692	return 0;
1693}
1694
1695static int
1696ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
1697{
1698	struct ieee80211com *ic = vap->iv_ic;
1699	struct ifnet *ifp = ic->ic_ifp;
1700	struct ath_softc *sc = ifp->if_softc;
1701	struct ath_hal *ah = sc->sc_ah;
1702
1703	switch (cmd) {
1704	case IEEE80211_IOC_TXPOWER:
1705		/*
1706		 * If per-packet TPC is enabled, then we have nothing
1707		 * to do; otherwise we need to force the global limit.
1708		 * All this can happen directly; no need to reset.
1709		 */
1710		if (!ath_hal_gettpc(ah))
1711			ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
1712		return 0;
1713	}
1714	return ath_reset(ifp);
1715}
1716
1717static int
1718ath_ff_always(struct ath_txq *txq, struct ath_buf *bf)
1719{
1720	return 0;
1721}
1722
1723#if 0
1724static int
1725ath_ff_ageflushtestdone(struct ath_txq *txq, struct ath_buf *bf)
1726{
1727	return (txq->axq_curage - bf->bf_age) < ATH_FF_STAGEMAX;
1728}
1729#endif
1730
1731/*
1732 * Flush FF staging queue.
1733 */
1734static void
1735ath_ff_stageq_flush(struct ath_softc *sc, struct ath_txq *txq,
1736	int (*ath_ff_flushdonetest)(struct ath_txq *txq, struct ath_buf *bf))
1737{
1738	struct ath_buf *bf;
1739	struct ieee80211_node *ni;
1740	int pktlen, pri;
1741
1742	for (;;) {
1743		ATH_TXQ_LOCK(txq);
1744		/*
1745		 * Go from the back (oldest) to front so we can
1746		 * stop early based on the age of the entry.
1747		 */
1748		bf = TAILQ_LAST(&txq->axq_stageq, axq_headtype);
1749		if (bf == NULL || ath_ff_flushdonetest(txq, bf)) {
1750			ATH_TXQ_UNLOCK(txq);
1751			break;
1752		}
1753
1754		ni = bf->bf_node;
1755		pri = M_WME_GETAC(bf->bf_m);
1756		KASSERT(ATH_NODE(ni)->an_ff_buf[pri],
1757			("no bf on staging queue %p", bf));
1758		ATH_NODE(ni)->an_ff_buf[pri] = NULL;
1759		TAILQ_REMOVE(&txq->axq_stageq, bf, bf_stagelist);
1760
1761		ATH_TXQ_UNLOCK(txq);
1762
1763		DPRINTF(sc, ATH_DEBUG_FF, "%s: flush frame, age %u\n",
1764			__func__, bf->bf_age);
1765
1766		sc->sc_stats.ast_ff_flush++;
1767
1768		/* encap and xmit */
1769		bf->bf_m = ieee80211_encap(ni, bf->bf_m);
1770		if (bf->bf_m == NULL) {
1771			DPRINTF(sc, ATH_DEBUG_XMIT | ATH_DEBUG_FF,
1772				"%s: discard, encapsulation failure\n",
1773				__func__);
1774			sc->sc_stats.ast_tx_encap++;
1775			goto bad;
1776		}
1777		pktlen = bf->bf_m->m_pkthdr.len; /* NB: don't reference below */
1778		if (ath_tx_start(sc, ni, bf, bf->bf_m) == 0) {
1779#if 0 /*XXX*/
1780			ifp->if_opackets++;
1781#endif
1782			continue;
1783		}
1784	bad:
1785		if (ni != NULL)
1786			ieee80211_free_node(ni);
1787		bf->bf_node = NULL;
1788		if (bf->bf_m != NULL) {
1789			m_freem(bf->bf_m);
1790			bf->bf_m = NULL;
1791		}
1792
1793		ATH_TXBUF_LOCK(sc);
1794		STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1795		ATH_TXBUF_UNLOCK(sc);
1796	}
1797}
1798
1799static __inline u_int32_t
1800ath_ff_approx_txtime(struct ath_softc *sc, struct ath_node *an, struct mbuf *m)
1801{
1802	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
1803	u_int32_t framelen;
1804	struct ath_buf *bf;
1805
1806	/*
1807	 * Approximate the frame length to be transmitted. A swag to add
1808	 * the following maximal values to the skb payload:
1809	 *   - 32: 802.11 encap + CRC
1810	 *   - 24: encryption overhead (if wep bit)
1811	 *   - 4 + 6: fast-frame header and padding
1812	 *   - 16: 2 LLC FF tunnel headers
1813	 *   - 14: 1 802.3 FF tunnel header (skb already accounts for 2nd)
1814	 */
1815	framelen = m->m_pkthdr.len + 32 + 4 + 6 + 16 + 14;
1816	if (ic->ic_flags & IEEE80211_F_PRIVACY)
1817		framelen += 24;
1818	bf = an->an_ff_buf[M_WME_GETAC(m)];
1819	if (bf != NULL)
1820		framelen += bf->bf_m->m_pkthdr.len;
1821	return ath_hal_computetxtime(sc->sc_ah, sc->sc_currates, framelen,
1822			sc->sc_lastdatarix, AH_FALSE);
1823}
1824
1825/*
1826 * Determine if a data frame may be aggregated via ff tunnelling.
1827 * Note the caller is responsible for checking if the destination
1828 * supports fast frames.
1829 *
1830 *  NB: allowing EAPOL frames to be aggregated with other unicast traffic.
1831 *      Do 802.1x EAPOL frames proceed in the clear? Then they couldn't
1832 *      be aggregated with other types of frames when encryption is on?
1833 *
1834 *  NB: assumes lock on an_ff_buf effectively held by txq lock mechanism.
1835 */
1836static __inline int
1837ath_ff_can_aggregate(struct ath_softc *sc,
1838	struct ath_node *an, struct mbuf *m, int *flushq)
1839{
1840	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
1841	struct ath_txq *txq;
1842	u_int32_t txoplimit;
1843	u_int pri;
1844
1845	*flushq = 0;
1846
1847	/*
1848	 * If there is no frame to combine with and the txq has
1849	 * fewer frames than the minimum required; then do not
1850	 * attempt to aggregate this frame.
1851	 */
1852	pri = M_WME_GETAC(m);
1853	txq = sc->sc_ac2q[pri];
1854	if (an->an_ff_buf[pri] == NULL && txq->axq_depth < sc->sc_fftxqmin)
1855		return 0;
1856	/*
1857	 * When not in station mode never aggregate a multicast
1858	 * frame; this insures, for example, that a combined frame
1859	 * does not require multiple encryption keys when using
1860	 * 802.1x/WPA.
1861	 */
1862	if (ic->ic_opmode != IEEE80211_M_STA &&
1863	    ETHER_IS_MULTICAST(mtod(m, struct ether_header *)->ether_dhost))
1864		return 0;
1865	/*
1866	 * Consult the max bursting interval to insure a combined
1867	 * frame fits within the TxOp window.
1868	 */
1869	txoplimit = IEEE80211_TXOP_TO_US(
1870		ic->ic_wme.wme_chanParams.cap_wmeParams[pri].wmep_txopLimit);
1871	if (txoplimit != 0 && ath_ff_approx_txtime(sc, an, m) > txoplimit) {
1872		DPRINTF(sc, ATH_DEBUG_XMIT | ATH_DEBUG_FF,
1873			"%s: FF TxOp violation\n", __func__);
1874		if (an->an_ff_buf[pri] != NULL)
1875			*flushq = 1;
1876		return 0;
1877	}
1878	return 1;		/* try to aggregate */
1879}
1880
1881/*
1882 * Check if the supplied frame can be partnered with an existing
1883 * or pending frame.  Return a reference to any frame that should be
1884 * sent on return; otherwise return NULL.
1885 */
1886static struct mbuf *
1887ath_ff_check(struct ath_softc *sc, struct ath_txq *txq,
1888	struct ath_buf *bf, struct mbuf *m, struct ieee80211_node *ni)
1889{
1890	struct ath_node *an = ATH_NODE(ni);
1891	struct ath_buf *bfstaged;
1892	int ff_flush, pri;
1893
1894	/*
1895	 * Check if the supplied frame can be aggregated.
1896	 *
1897	 * NB: we use the txq lock to protect references to
1898	 *     an->an_ff_txbuf in ath_ff_can_aggregate().
1899	 */
1900	ATH_TXQ_LOCK(txq);
1901	pri = M_WME_GETAC(m);
1902	if (ath_ff_can_aggregate(sc, an, m, &ff_flush)) {
1903		struct ath_buf *bfstaged = an->an_ff_buf[pri];
1904		if (bfstaged != NULL) {
1905			/*
1906			 * A frame is available for partnering; remove
1907			 * it, chain it to this one, and encapsulate.
1908			 */
1909			an->an_ff_buf[pri] = NULL;
1910			TAILQ_REMOVE(&txq->axq_stageq, bfstaged, bf_stagelist);
1911			ATH_TXQ_UNLOCK(txq);
1912
1913			/*
1914			 * Chain mbufs and add FF magic.
1915			 */
1916			DPRINTF(sc, ATH_DEBUG_FF,
1917				"[%s] aggregate fast-frame, age %u\n",
1918				ether_sprintf(ni->ni_macaddr), txq->axq_curage);
1919			m->m_nextpkt = NULL;
1920			bfstaged->bf_m->m_nextpkt = m;
1921			m = bfstaged->bf_m;
1922			bfstaged->bf_m = NULL;
1923			m->m_flags |= M_FF;
1924			/*
1925			 * Release the node reference held while
1926			 * the packet sat on an_ff_buf[]
1927			 */
1928			bfstaged->bf_node = NULL;
1929			ieee80211_free_node(ni);
1930
1931			/*
1932			 * Return bfstaged to the free list.
1933			 */
1934			ATH_TXBUF_LOCK(sc);
1935			STAILQ_INSERT_HEAD(&sc->sc_txbuf, bfstaged, bf_list);
1936			ATH_TXBUF_UNLOCK(sc);
1937
1938			return m;		/* ready to go */
1939		} else {
1940			/*
1941			 * No frame available, queue this frame to wait
1942			 * for a partner.  Note that we hold the buffer
1943			 * and a reference to the node; we need the
1944			 * buffer in particular so we're certain we
1945			 * can flush the frame at a later time.
1946			 */
1947			DPRINTF(sc, ATH_DEBUG_FF,
1948				"[%s] stage fast-frame, age %u\n",
1949				ether_sprintf(ni->ni_macaddr), txq->axq_curage);
1950
1951			bf->bf_m = m;
1952			bf->bf_node = ni;	/* NB: held reference */
1953			bf->bf_age = txq->axq_curage;
1954			an->an_ff_buf[pri] = bf;
1955			TAILQ_INSERT_HEAD(&txq->axq_stageq, bf, bf_stagelist);
1956			ATH_TXQ_UNLOCK(txq);
1957
1958			return NULL;		/* consumed */
1959		}
1960	}
1961	/*
1962	 * Frame could not be aggregated, it needs to be returned
1963	 * to the caller for immediate transmission.  In addition
1964	 * we check if we should first flush a frame from the
1965	 * staging queue before sending this one.
1966	 *
1967	 * NB: ath_ff_can_aggregate only marks ff_flush if a frame
1968	 *     is present to flush.
1969	 */
1970	if (ff_flush) {
1971		int pktlen;
1972
1973		bfstaged = an->an_ff_buf[pri];
1974		an->an_ff_buf[pri] = NULL;
1975		TAILQ_REMOVE(&txq->axq_stageq, bfstaged, bf_stagelist);
1976		ATH_TXQ_UNLOCK(txq);
1977
1978		DPRINTF(sc, ATH_DEBUG_FF, "[%s] flush staged frame\n",
1979			ether_sprintf(an->an_node.ni_macaddr));
1980
1981		/* encap and xmit */
1982		bfstaged->bf_m = ieee80211_encap(ni, bfstaged->bf_m);
1983		if (bfstaged->bf_m == NULL) {
1984			DPRINTF(sc, ATH_DEBUG_XMIT | ATH_DEBUG_FF,
1985				"%s: discard, encap failure\n", __func__);
1986			sc->sc_stats.ast_tx_encap++;
1987			goto ff_flushbad;
1988		}
1989		pktlen = bfstaged->bf_m->m_pkthdr.len;
1990		if (ath_tx_start(sc, ni, bfstaged, bfstaged->bf_m)) {
1991			DPRINTF(sc, ATH_DEBUG_XMIT,
1992				"%s: discard, xmit failure\n", __func__);
1993	ff_flushbad:
1994			/*
1995			 * Unable to transmit frame that was on the staging
1996			 * queue.  Reclaim the node reference and other
1997			 * resources.
1998			 */
1999			if (ni != NULL)
2000				ieee80211_free_node(ni);
2001			bfstaged->bf_node = NULL;
2002			if (bfstaged->bf_m != NULL) {
2003				m_freem(bfstaged->bf_m);
2004				bfstaged->bf_m = NULL;
2005			}
2006
2007			ATH_TXBUF_LOCK(sc);
2008			STAILQ_INSERT_HEAD(&sc->sc_txbuf, bfstaged, bf_list);
2009			ATH_TXBUF_UNLOCK(sc);
2010		} else {
2011#if 0
2012			ifp->if_opackets++;
2013#endif
2014		}
2015	} else {
2016		if (an->an_ff_buf[pri] != NULL) {
2017			/*
2018			 * XXX: out-of-order condition only occurs for AP
2019			 * mode and multicast.  There may be no valid way
2020			 * to get this condition.
2021			 */
2022			DPRINTF(sc, ATH_DEBUG_FF, "[%s] out-of-order frame\n",
2023				ether_sprintf(an->an_node.ni_macaddr));
2024			/* XXX stat */
2025		}
2026		ATH_TXQ_UNLOCK(txq);
2027	}
2028	return m;
2029}
2030
2031static struct ath_buf *
2032_ath_getbuf_locked(struct ath_softc *sc)
2033{
2034	struct ath_buf *bf;
2035
2036	ATH_TXBUF_LOCK_ASSERT(sc);
2037
2038	bf = STAILQ_FIRST(&sc->sc_txbuf);
2039	if (bf != NULL && (bf->bf_flags & ATH_BUF_BUSY) == 0)
2040		STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
2041	else
2042		bf = NULL;
2043	if (bf == NULL) {
2044		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: %s\n", __func__,
2045		    STAILQ_FIRST(&sc->sc_txbuf) == NULL ?
2046			"out of xmit buffers" : "xmit buffer busy");
2047		sc->sc_stats.ast_tx_nobuf++;
2048	}
2049	return bf;
2050}
2051
2052static struct ath_buf *
2053ath_getbuf(struct ath_softc *sc)
2054{
2055	struct ath_buf *bf;
2056
2057	ATH_TXBUF_LOCK(sc);
2058	bf = _ath_getbuf_locked(sc);
2059	if (bf == NULL) {
2060		struct ifnet *ifp = sc->sc_ifp;
2061
2062		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
2063		sc->sc_stats.ast_tx_qstop++;
2064		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2065	}
2066	ATH_TXBUF_UNLOCK(sc);
2067	return bf;
2068}
2069
2070/*
2071 * Cleanup driver resources when we run out of buffers
2072 * while processing fragments; return the tx buffers
2073 * allocated and drop node references.
2074 */
2075static void
2076ath_txfrag_cleanup(struct ath_softc *sc,
2077	ath_bufhead *frags, struct ieee80211_node *ni)
2078{
2079	struct ath_buf *bf, *next;
2080
2081	ATH_TXBUF_LOCK_ASSERT(sc);
2082
2083	STAILQ_FOREACH_SAFE(bf, frags, bf_list, next) {
2084		/* NB: bf assumed clean */
2085		STAILQ_REMOVE_HEAD(frags, bf_list);
2086		STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
2087		ieee80211_node_decref(ni);
2088	}
2089}
2090
2091/*
2092 * Setup xmit of a fragmented frame.  Allocate a buffer
2093 * for each frag and bump the node reference count to
2094 * reflect the held reference to be setup by ath_tx_start.
2095 */
2096static int
2097ath_txfrag_setup(struct ath_softc *sc, ath_bufhead *frags,
2098	struct mbuf *m0, struct ieee80211_node *ni)
2099{
2100	struct mbuf *m;
2101	struct ath_buf *bf;
2102
2103	ATH_TXBUF_LOCK(sc);
2104	for (m = m0->m_nextpkt; m != NULL; m = m->m_nextpkt) {
2105		bf = _ath_getbuf_locked(sc);
2106		if (bf == NULL) {	/* out of buffers, cleanup */
2107			ath_txfrag_cleanup(sc, frags, ni);
2108			break;
2109		}
2110		ieee80211_node_incref(ni);
2111		STAILQ_INSERT_TAIL(frags, bf, bf_list);
2112	}
2113	ATH_TXBUF_UNLOCK(sc);
2114
2115	return !STAILQ_EMPTY(frags);
2116}
2117
2118static void
2119ath_start(struct ifnet *ifp)
2120{
2121	struct ath_softc *sc = ifp->if_softc;
2122	struct ieee80211com *ic = ifp->if_l2com;
2123	struct ieee80211_node *ni;
2124	struct ath_buf *bf;
2125	struct mbuf *m, *next;
2126	struct ath_txq *txq;
2127	ath_bufhead frags;
2128	int pri;
2129
2130	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
2131		return;
2132	for (;;) {
2133		/*
2134		 * Grab a TX buffer and associated resources.
2135		 */
2136		bf = ath_getbuf(sc);
2137		if (bf == NULL)
2138			break;
2139
2140		IFQ_DEQUEUE(&ifp->if_snd, m);
2141		if (m == NULL) {
2142			ATH_TXBUF_LOCK(sc);
2143			STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
2144			ATH_TXBUF_UNLOCK(sc);
2145			break;
2146		}
2147		STAILQ_INIT(&frags);
2148		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
2149		pri = M_WME_GETAC(m);
2150		txq = sc->sc_ac2q[pri];
2151		if (IEEE80211_ATH_CAP(ni->ni_vap, ni, IEEE80211_NODE_FF)) {
2152			/*
2153			 * Check queue length; if too deep drop this
2154			 * frame (tail drop considered good).
2155			 */
2156			if (txq->axq_depth >= sc->sc_fftxqmax) {
2157				DPRINTF(sc, ATH_DEBUG_FF,
2158				    "[%s] tail drop on q %u depth %u\n",
2159				    ether_sprintf(ni->ni_macaddr),
2160				    txq->axq_qnum, txq->axq_depth);
2161				sc->sc_stats.ast_tx_qfull++;
2162				m_freem(m);
2163				goto reclaim;
2164			}
2165			m = ath_ff_check(sc, txq, bf, m, ni);
2166			if (m == NULL) {
2167				/* NB: ni ref & bf held on stageq */
2168				continue;
2169			}
2170		}
2171		ifp->if_opackets++;
2172		/*
2173		 * Encapsulate the packet in prep for transmission.
2174		 */
2175		m = ieee80211_encap(ni, m);
2176		if (m == NULL) {
2177			DPRINTF(sc, ATH_DEBUG_XMIT,
2178			    "%s: encapsulation failure\n", __func__);
2179			sc->sc_stats.ast_tx_encap++;
2180			goto bad;
2181		}
2182		/*
2183		 * Check for fragmentation.  If this frame
2184		 * has been broken up verify we have enough
2185		 * buffers to send all the fragments so all
2186		 * go out or none...
2187		 */
2188		if ((m->m_flags & M_FRAG) &&
2189		    !ath_txfrag_setup(sc, &frags, m, ni)) {
2190			DPRINTF(sc, ATH_DEBUG_XMIT,
2191			    "%s: out of txfrag buffers\n", __func__);
2192			ic->ic_stats.is_tx_nobuf++;	/* XXX */
2193			ath_freetx(m);
2194			goto bad;
2195		}
2196	nextfrag:
2197		/*
2198		 * Pass the frame to the h/w for transmission.
2199		 * Fragmented frames have each frag chained together
2200		 * with m_nextpkt.  We know there are sufficient ath_buf's
2201		 * to send all the frags because of work done by
2202		 * ath_txfrag_setup.  We leave m_nextpkt set while
2203		 * calling ath_tx_start so it can use it to extend the
2204		 * the tx duration to cover the subsequent frag and
2205		 * so it can reclaim all the mbufs in case of an error;
2206		 * ath_tx_start clears m_nextpkt once it commits to
2207		 * handing the frame to the hardware.
2208		 */
2209		next = m->m_nextpkt;
2210		if (ath_tx_start(sc, ni, bf, m)) {
2211	bad:
2212			ifp->if_oerrors++;
2213	reclaim:
2214			bf->bf_m = NULL;
2215			bf->bf_node = NULL;
2216			ATH_TXBUF_LOCK(sc);
2217			STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
2218			ath_txfrag_cleanup(sc, &frags, ni);
2219			ATH_TXBUF_UNLOCK(sc);
2220			if (ni != NULL)
2221				ieee80211_free_node(ni);
2222			continue;
2223		}
2224		if (next != NULL) {
2225			/*
2226			 * Beware of state changing between frags.
2227			 * XXX check sta power-save state?
2228			 */
2229			if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
2230				DPRINTF(sc, ATH_DEBUG_XMIT,
2231				    "%s: flush fragmented packet, state %s\n",
2232				    __func__,
2233				    ieee80211_state_name[ni->ni_vap->iv_state]);
2234				ath_freetx(next);
2235				goto reclaim;
2236			}
2237			m = next;
2238			bf = STAILQ_FIRST(&frags);
2239			KASSERT(bf != NULL, ("no buf for txfrag"));
2240			STAILQ_REMOVE_HEAD(&frags, bf_list);
2241			goto nextfrag;
2242		}
2243
2244		ifp->if_timer = 5;
2245#if 0
2246		/*
2247		 * Flush stale frames from the fast-frame staging queue.
2248		 */
2249		if (ic->ic_opmode != IEEE80211_M_STA)
2250			ath_ff_stageq_flush(sc, txq, ath_ff_ageflushtestdone);
2251#endif
2252	}
2253}
2254
2255static int
2256ath_media_change(struct ifnet *ifp)
2257{
2258	int error = ieee80211_media_change(ifp);
2259	/* NB: only the fixed rate can change and that doesn't need a reset */
2260	return (error == ENETRESET ? 0 : error);
2261}
2262
2263#ifdef ATH_DEBUG
2264static void
2265ath_keyprint(struct ath_softc *sc, const char *tag, u_int ix,
2266	const HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
2267{
2268	static const char *ciphers[] = {
2269		"WEP",
2270		"AES-OCB",
2271		"AES-CCM",
2272		"CKIP",
2273		"TKIP",
2274		"CLR",
2275	};
2276	int i, n;
2277
2278	printf("%s: [%02u] %-7s ", tag, ix, ciphers[hk->kv_type]);
2279	for (i = 0, n = hk->kv_len; i < n; i++)
2280		printf("%02x", hk->kv_val[i]);
2281	printf(" mac %s", ether_sprintf(mac));
2282	if (hk->kv_type == HAL_CIPHER_TKIP) {
2283		printf(" %s ", sc->sc_splitmic ? "mic" : "rxmic");
2284		for (i = 0; i < sizeof(hk->kv_mic); i++)
2285			printf("%02x", hk->kv_mic[i]);
2286		if (!sc->sc_splitmic) {
2287			printf(" txmic ");
2288			for (i = 0; i < sizeof(hk->kv_txmic); i++)
2289				printf("%02x", hk->kv_txmic[i]);
2290		}
2291	}
2292	printf("\n");
2293}
2294#endif
2295
2296/*
2297 * Set a TKIP key into the hardware.  This handles the
2298 * potential distribution of key state to multiple key
2299 * cache slots for TKIP.
2300 */
2301static int
2302ath_keyset_tkip(struct ath_softc *sc, const struct ieee80211_key *k,
2303	HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
2304{
2305#define	IEEE80211_KEY_XR	(IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV)
2306	static const u_int8_t zerobssid[IEEE80211_ADDR_LEN];
2307	struct ath_hal *ah = sc->sc_ah;
2308
2309	KASSERT(k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP,
2310		("got a non-TKIP key, cipher %u", k->wk_cipher->ic_cipher));
2311	if ((k->wk_flags & IEEE80211_KEY_XR) == IEEE80211_KEY_XR) {
2312		if (sc->sc_splitmic) {
2313			/*
2314			 * TX key goes at first index, RX key at the rx index.
2315			 * The hal handles the MIC keys at index+64.
2316			 */
2317			memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_mic));
2318			KEYPRINTF(sc, k->wk_keyix, hk, zerobssid);
2319			if (!ath_hal_keyset(ah, k->wk_keyix, hk, zerobssid))
2320				return 0;
2321
2322			memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
2323			KEYPRINTF(sc, k->wk_keyix+32, hk, mac);
2324			/* XXX delete tx key on failure? */
2325			return ath_hal_keyset(ah, k->wk_keyix+32, hk, mac);
2326		} else {
2327			/*
2328			 * Room for both TX+RX MIC keys in one key cache
2329			 * slot, just set key at the first index; the hal
2330			 * will handle the rest.
2331			 */
2332			memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
2333			memcpy(hk->kv_txmic, k->wk_txmic, sizeof(hk->kv_txmic));
2334			KEYPRINTF(sc, k->wk_keyix, hk, mac);
2335			return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
2336		}
2337	} else if (k->wk_flags & IEEE80211_KEY_XMIT) {
2338		if (sc->sc_splitmic) {
2339			/*
2340			 * NB: must pass MIC key in expected location when
2341			 * the keycache only holds one MIC key per entry.
2342			 */
2343			memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_txmic));
2344		} else
2345			memcpy(hk->kv_txmic, k->wk_txmic, sizeof(hk->kv_txmic));
2346		KEYPRINTF(sc, k->wk_keyix, hk, mac);
2347		return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
2348	} else if (k->wk_flags & IEEE80211_KEY_RECV) {
2349		memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
2350		KEYPRINTF(sc, k->wk_keyix, hk, mac);
2351		return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
2352	}
2353	return 0;
2354#undef IEEE80211_KEY_XR
2355}
2356
2357/*
2358 * Set a net80211 key into the hardware.  This handles the
2359 * potential distribution of key state to multiple key
2360 * cache slots for TKIP with hardware MIC support.
2361 */
2362static int
2363ath_keyset(struct ath_softc *sc, const struct ieee80211_key *k,
2364	struct ieee80211_node *bss)
2365{
2366#define	N(a)	(sizeof(a)/sizeof(a[0]))
2367	static const u_int8_t ciphermap[] = {
2368		HAL_CIPHER_WEP,		/* IEEE80211_CIPHER_WEP */
2369		HAL_CIPHER_TKIP,	/* IEEE80211_CIPHER_TKIP */
2370		HAL_CIPHER_AES_OCB,	/* IEEE80211_CIPHER_AES_OCB */
2371		HAL_CIPHER_AES_CCM,	/* IEEE80211_CIPHER_AES_CCM */
2372		(u_int8_t) -1,		/* 4 is not allocated */
2373		HAL_CIPHER_CKIP,	/* IEEE80211_CIPHER_CKIP */
2374		HAL_CIPHER_CLR,		/* IEEE80211_CIPHER_NONE */
2375	};
2376	struct ath_hal *ah = sc->sc_ah;
2377	const struct ieee80211_cipher *cip = k->wk_cipher;
2378	u_int8_t gmac[IEEE80211_ADDR_LEN];
2379	const u_int8_t *mac;
2380	HAL_KEYVAL hk;
2381
2382	memset(&hk, 0, sizeof(hk));
2383	/*
2384	 * Software crypto uses a "clear key" so non-crypto
2385	 * state kept in the key cache are maintained and
2386	 * so that rx frames have an entry to match.
2387	 */
2388	if ((k->wk_flags & IEEE80211_KEY_SWCRYPT) == 0) {
2389		KASSERT(cip->ic_cipher < N(ciphermap),
2390			("invalid cipher type %u", cip->ic_cipher));
2391		hk.kv_type = ciphermap[cip->ic_cipher];
2392		hk.kv_len = k->wk_keylen;
2393		memcpy(hk.kv_val, k->wk_key, k->wk_keylen);
2394	} else
2395		hk.kv_type = HAL_CIPHER_CLR;
2396
2397	if ((k->wk_flags & IEEE80211_KEY_GROUP) && sc->sc_mcastkey) {
2398		/*
2399		 * Group keys on hardware that supports multicast frame
2400		 * key search use a mac that is the sender's address with
2401		 * the high bit set instead of the app-specified address.
2402		 */
2403		IEEE80211_ADDR_COPY(gmac, bss->ni_macaddr);
2404		gmac[0] |= 0x80;
2405		mac = gmac;
2406	} else
2407		mac = k->wk_macaddr;
2408
2409	if (hk.kv_type == HAL_CIPHER_TKIP &&
2410	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2411		return ath_keyset_tkip(sc, k, &hk, mac);
2412	} else {
2413		KEYPRINTF(sc, k->wk_keyix, &hk, mac);
2414		return ath_hal_keyset(ah, k->wk_keyix, &hk, mac);
2415	}
2416#undef N
2417}
2418
2419/*
2420 * Allocate tx/rx key slots for TKIP.  We allocate two slots for
2421 * each key, one for decrypt/encrypt and the other for the MIC.
2422 */
2423static u_int16_t
2424key_alloc_2pair(struct ath_softc *sc,
2425	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2426{
2427#define	N(a)	(sizeof(a)/sizeof(a[0]))
2428	u_int i, keyix;
2429
2430	KASSERT(sc->sc_splitmic, ("key cache !split"));
2431	/* XXX could optimize */
2432	for (i = 0; i < N(sc->sc_keymap)/4; i++) {
2433		u_int8_t b = sc->sc_keymap[i];
2434		if (b != 0xff) {
2435			/*
2436			 * One or more slots in this byte are free.
2437			 */
2438			keyix = i*NBBY;
2439			while (b & 1) {
2440		again:
2441				keyix++;
2442				b >>= 1;
2443			}
2444			/* XXX IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV */
2445			if (isset(sc->sc_keymap, keyix+32) ||
2446			    isset(sc->sc_keymap, keyix+64) ||
2447			    isset(sc->sc_keymap, keyix+32+64)) {
2448				/* full pair unavailable */
2449				/* XXX statistic */
2450				if (keyix == (i+1)*NBBY) {
2451					/* no slots were appropriate, advance */
2452					continue;
2453				}
2454				goto again;
2455			}
2456			setbit(sc->sc_keymap, keyix);
2457			setbit(sc->sc_keymap, keyix+64);
2458			setbit(sc->sc_keymap, keyix+32);
2459			setbit(sc->sc_keymap, keyix+32+64);
2460			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2461				"%s: key pair %u,%u %u,%u\n",
2462				__func__, keyix, keyix+64,
2463				keyix+32, keyix+32+64);
2464			*txkeyix = keyix;
2465			*rxkeyix = keyix+32;
2466			return 1;
2467		}
2468	}
2469	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
2470	return 0;
2471#undef N
2472}
2473
2474/*
2475 * Allocate tx/rx key slots for TKIP.  We allocate two slots for
2476 * each key, one for decrypt/encrypt and the other for the MIC.
2477 */
2478static u_int16_t
2479key_alloc_pair(struct ath_softc *sc,
2480	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2481{
2482#define	N(a)	(sizeof(a)/sizeof(a[0]))
2483	u_int i, keyix;
2484
2485	KASSERT(!sc->sc_splitmic, ("key cache split"));
2486	/* XXX could optimize */
2487	for (i = 0; i < N(sc->sc_keymap)/4; i++) {
2488		u_int8_t b = sc->sc_keymap[i];
2489		if (b != 0xff) {
2490			/*
2491			 * One or more slots in this byte are free.
2492			 */
2493			keyix = i*NBBY;
2494			while (b & 1) {
2495		again:
2496				keyix++;
2497				b >>= 1;
2498			}
2499			if (isset(sc->sc_keymap, keyix+64)) {
2500				/* full pair unavailable */
2501				/* XXX statistic */
2502				if (keyix == (i+1)*NBBY) {
2503					/* no slots were appropriate, advance */
2504					continue;
2505				}
2506				goto again;
2507			}
2508			setbit(sc->sc_keymap, keyix);
2509			setbit(sc->sc_keymap, keyix+64);
2510			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2511				"%s: key pair %u,%u\n",
2512				__func__, keyix, keyix+64);
2513			*txkeyix = *rxkeyix = keyix;
2514			return 1;
2515		}
2516	}
2517	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
2518	return 0;
2519#undef N
2520}
2521
2522/*
2523 * Allocate a single key cache slot.
2524 */
2525static int
2526key_alloc_single(struct ath_softc *sc,
2527	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2528{
2529#define	N(a)	(sizeof(a)/sizeof(a[0]))
2530	u_int i, keyix;
2531
2532	/* XXX try i,i+32,i+64,i+32+64 to minimize key pair conflicts */
2533	for (i = 0; i < N(sc->sc_keymap); i++) {
2534		u_int8_t b = sc->sc_keymap[i];
2535		if (b != 0xff) {
2536			/*
2537			 * One or more slots are free.
2538			 */
2539			keyix = i*NBBY;
2540			while (b & 1)
2541				keyix++, b >>= 1;
2542			setbit(sc->sc_keymap, keyix);
2543			DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: key %u\n",
2544				__func__, keyix);
2545			*txkeyix = *rxkeyix = keyix;
2546			return 1;
2547		}
2548	}
2549	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of space\n", __func__);
2550	return 0;
2551#undef N
2552}
2553
2554/*
2555 * Allocate one or more key cache slots for a uniacst key.  The
2556 * key itself is needed only to identify the cipher.  For hardware
2557 * TKIP with split cipher+MIC keys we allocate two key cache slot
2558 * pairs so that we can setup separate TX and RX MIC keys.  Note
2559 * that the MIC key for a TKIP key at slot i is assumed by the
2560 * hardware to be at slot i+64.  This limits TKIP keys to the first
2561 * 64 entries.
2562 */
2563static int
2564ath_key_alloc(struct ieee80211vap *vap, struct ieee80211_key *k,
2565	ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
2566{
2567	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2568
2569	/*
2570	 * Group key allocation must be handled specially for
2571	 * parts that do not support multicast key cache search
2572	 * functionality.  For those parts the key id must match
2573	 * the h/w key index so lookups find the right key.  On
2574	 * parts w/ the key search facility we install the sender's
2575	 * mac address (with the high bit set) and let the hardware
2576	 * find the key w/o using the key id.  This is preferred as
2577	 * it permits us to support multiple users for adhoc and/or
2578	 * multi-station operation.
2579	 */
2580	if (k->wk_keyix != IEEE80211_KEYIX_NONE ||	/* global key */
2581	    ((k->wk_flags & IEEE80211_KEY_GROUP) && !sc->sc_mcastkey)) {
2582		if (!(&vap->iv_nw_keys[0] <= k &&
2583		      k < &vap->iv_nw_keys[IEEE80211_WEP_NKID])) {
2584			/* should not happen */
2585			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2586				"%s: bogus group key\n", __func__);
2587			return 0;
2588		}
2589		/*
2590		 * XXX we pre-allocate the global keys so
2591		 * have no way to check if they've already been allocated.
2592		 */
2593		*keyix = *rxkeyix = k - vap->iv_nw_keys;
2594		return 1;
2595	}
2596
2597	/*
2598	 * We allocate two pair for TKIP when using the h/w to do
2599	 * the MIC.  For everything else, including software crypto,
2600	 * we allocate a single entry.  Note that s/w crypto requires
2601	 * a pass-through slot on the 5211 and 5212.  The 5210 does
2602	 * not support pass-through cache entries and we map all
2603	 * those requests to slot 0.
2604	 */
2605	if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
2606		return key_alloc_single(sc, keyix, rxkeyix);
2607	} else if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP &&
2608	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2609		if (sc->sc_splitmic)
2610			return key_alloc_2pair(sc, keyix, rxkeyix);
2611		else
2612			return key_alloc_pair(sc, keyix, rxkeyix);
2613	} else {
2614		return key_alloc_single(sc, keyix, rxkeyix);
2615	}
2616}
2617
2618/*
2619 * Delete an entry in the key cache allocated by ath_key_alloc.
2620 */
2621static int
2622ath_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
2623{
2624	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2625	struct ath_hal *ah = sc->sc_ah;
2626	const struct ieee80211_cipher *cip = k->wk_cipher;
2627	u_int keyix = k->wk_keyix;
2628
2629	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: delete key %u\n", __func__, keyix);
2630
2631	ath_hal_keyreset(ah, keyix);
2632	/*
2633	 * Handle split tx/rx keying required for TKIP with h/w MIC.
2634	 */
2635	if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
2636	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic)
2637		ath_hal_keyreset(ah, keyix+32);		/* RX key */
2638	if (keyix >= IEEE80211_WEP_NKID) {
2639		/*
2640		 * Don't touch keymap entries for global keys so
2641		 * they are never considered for dynamic allocation.
2642		 */
2643		clrbit(sc->sc_keymap, keyix);
2644		if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
2645		    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2646			clrbit(sc->sc_keymap, keyix+64);	/* TX key MIC */
2647			if (sc->sc_splitmic) {
2648				/* +32 for RX key, +32+64 for RX key MIC */
2649				clrbit(sc->sc_keymap, keyix+32);
2650				clrbit(sc->sc_keymap, keyix+32+64);
2651			}
2652		}
2653	}
2654	return 1;
2655}
2656
2657/*
2658 * Set the key cache contents for the specified key.  Key cache
2659 * slot(s) must already have been allocated by ath_key_alloc.
2660 */
2661static int
2662ath_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k,
2663	const u_int8_t mac[IEEE80211_ADDR_LEN])
2664{
2665	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2666
2667	return ath_keyset(sc, k, vap->iv_bss);
2668}
2669
2670/*
2671 * Block/unblock tx+rx processing while a key change is done.
2672 * We assume the caller serializes key management operations
2673 * so we only need to worry about synchronization with other
2674 * uses that originate in the driver.
2675 */
2676static void
2677ath_key_update_begin(struct ieee80211vap *vap)
2678{
2679	struct ifnet *ifp = vap->iv_ic->ic_ifp;
2680	struct ath_softc *sc = ifp->if_softc;
2681
2682	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2683	taskqueue_block(sc->sc_tq);
2684	IF_LOCK(&ifp->if_snd);		/* NB: doesn't block mgmt frames */
2685}
2686
2687static void
2688ath_key_update_end(struct ieee80211vap *vap)
2689{
2690	struct ifnet *ifp = vap->iv_ic->ic_ifp;
2691	struct ath_softc *sc = ifp->if_softc;
2692
2693	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2694	IF_UNLOCK(&ifp->if_snd);
2695	taskqueue_unblock(sc->sc_tq);
2696}
2697
2698/*
2699 * Calculate the receive filter according to the
2700 * operating mode and state:
2701 *
2702 * o always accept unicast, broadcast, and multicast traffic
2703 * o accept PHY error frames when hardware doesn't have MIB support
2704 *   to count and we need them for ANI (sta mode only until recently)
2705 *   and we are not scanning (ANI is disabled)
2706 *   NB: older hal's add rx filter bits out of sight and we need to
2707 *	 blindly preserve them
2708 * o probe request frames are accepted only when operating in
2709 *   hostap, adhoc, or monitor modes
2710 * o enable promiscuous mode
2711 *   - when in monitor mode
2712 *   - if interface marked PROMISC (assumes bridge setting is filtered)
2713 * o accept beacons:
2714 *   - when operating in station mode for collecting rssi data when
2715 *     the station is otherwise quiet, or
2716 *   - when operating in adhoc mode so the 802.11 layer creates
2717 *     node table entries for peers,
2718 *   - when scanning
2719 *   - when doing s/w beacon miss (e.g. for ap+sta)
2720 *   - when operating in ap mode in 11g to detect overlapping bss that
2721 *     require protection
2722 * o accept control frames:
2723 *   - when in monitor mode
2724 * XXX BAR frames for 11n
2725 * XXX HT protection for 11n
2726 */
2727static u_int32_t
2728ath_calcrxfilter(struct ath_softc *sc)
2729{
2730	struct ifnet *ifp = sc->sc_ifp;
2731	struct ieee80211com *ic = ifp->if_l2com;
2732	u_int32_t rfilt;
2733
2734	rfilt = HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
2735#if HAL_ABI_VERSION < 0x08011600
2736	rfilt |= (ath_hal_getrxfilter(sc->sc_ah) &
2737		(HAL_RX_FILTER_PHYRADAR | HAL_RX_FILTER_PHYERR));
2738#elif HAL_ABI_VERSION < 0x08060100
2739	if (ic->ic_opmode == IEEE80211_M_STA &&
2740	    !sc->sc_needmib && !sc->sc_scanning)
2741		rfilt |= HAL_RX_FILTER_PHYERR;
2742#else
2743	if (!sc->sc_needmib && !sc->sc_scanning)
2744		rfilt |= HAL_RX_FILTER_PHYERR;
2745#endif
2746	if (ic->ic_opmode != IEEE80211_M_STA)
2747		rfilt |= HAL_RX_FILTER_PROBEREQ;
2748	if (ic->ic_opmode == IEEE80211_M_MONITOR || (ifp->if_flags & IFF_PROMISC))
2749		rfilt |= HAL_RX_FILTER_PROM;
2750	if (ic->ic_opmode == IEEE80211_M_STA ||
2751	    ic->ic_opmode == IEEE80211_M_IBSS ||
2752	    sc->sc_swbmiss || sc->sc_scanning)
2753		rfilt |= HAL_RX_FILTER_BEACON;
2754	/*
2755	 * NB: We don't recalculate the rx filter when
2756	 * ic_protmode changes; otherwise we could do
2757	 * this only when ic_protmode != NONE.
2758	 */
2759	if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
2760	    IEEE80211_IS_CHAN_ANYG(ic->ic_curchan))
2761		rfilt |= HAL_RX_FILTER_BEACON;
2762	if (ic->ic_opmode == IEEE80211_M_MONITOR)
2763		rfilt |= HAL_RX_FILTER_CONTROL;
2764	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, %s if_flags 0x%x\n",
2765	    __func__, rfilt, ieee80211_opmode_name[ic->ic_opmode], ifp->if_flags);
2766	return rfilt;
2767}
2768
2769static void
2770ath_update_promisc(struct ifnet *ifp)
2771{
2772	struct ath_softc *sc = ifp->if_softc;
2773	u_int32_t rfilt;
2774
2775	/* configure rx filter */
2776	rfilt = ath_calcrxfilter(sc);
2777	ath_hal_setrxfilter(sc->sc_ah, rfilt);
2778
2779	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
2780}
2781
2782static void
2783ath_update_mcast(struct ifnet *ifp)
2784{
2785	struct ath_softc *sc = ifp->if_softc;
2786	u_int32_t mfilt[2];
2787
2788	/* calculate and install multicast filter */
2789	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
2790		struct ifmultiaddr *ifma;
2791		/*
2792		 * Merge multicast addresses to form the hardware filter.
2793		 */
2794		mfilt[0] = mfilt[1] = 0;
2795		IF_ADDR_LOCK(ifp);	/* XXX need some fiddling to remove? */
2796		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2797			caddr_t dl;
2798			u_int32_t val;
2799			u_int8_t pos;
2800
2801			/* calculate XOR of eight 6bit values */
2802			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
2803			val = LE_READ_4(dl + 0);
2804			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2805			val = LE_READ_4(dl + 3);
2806			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2807			pos &= 0x3f;
2808			mfilt[pos / 32] |= (1 << (pos % 32));
2809		}
2810		IF_ADDR_UNLOCK(ifp);
2811	} else
2812		mfilt[0] = mfilt[1] = ~0;
2813	ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
2814	DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
2815		__func__, mfilt[0], mfilt[1]);
2816}
2817
2818static void
2819ath_mode_init(struct ath_softc *sc)
2820{
2821	struct ifnet *ifp = sc->sc_ifp;
2822	struct ieee80211com *ic = ifp->if_l2com;
2823	struct ath_hal *ah = sc->sc_ah;
2824	u_int32_t rfilt;
2825
2826	/* configure rx filter */
2827	rfilt = ath_calcrxfilter(sc);
2828	ath_hal_setrxfilter(ah, rfilt);
2829
2830	/* configure operational mode */
2831	ath_hal_setopmode(ah);
2832
2833	/*
2834	 * Handle any link-level address change.  Note that we only
2835	 * need to force ic_myaddr; any other addresses are handled
2836	 * as a byproduct of the ifnet code marking the interface
2837	 * down then up.
2838	 *
2839	 * XXX should get from lladdr instead of arpcom but that's more work
2840	 */
2841	IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2842	ath_hal_setmac(ah, ic->ic_myaddr);
2843
2844	/* calculate and install multicast filter */
2845	ath_update_mcast(ifp);
2846}
2847
2848/*
2849 * Set the slot time based on the current setting.
2850 */
2851static void
2852ath_setslottime(struct ath_softc *sc)
2853{
2854	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2855	struct ath_hal *ah = sc->sc_ah;
2856	u_int usec;
2857
2858	if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
2859		usec = 13;
2860	else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
2861		usec = 21;
2862	else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
2863		/* honor short/long slot time only in 11g */
2864		/* XXX shouldn't honor on pure g or turbo g channel */
2865		if (ic->ic_flags & IEEE80211_F_SHSLOT)
2866			usec = HAL_SLOT_TIME_9;
2867		else
2868			usec = HAL_SLOT_TIME_20;
2869	} else
2870		usec = HAL_SLOT_TIME_9;
2871
2872	DPRINTF(sc, ATH_DEBUG_RESET,
2873	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
2874	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
2875	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
2876
2877	ath_hal_setslottime(ah, usec);
2878	sc->sc_updateslot = OK;
2879}
2880
2881/*
2882 * Callback from the 802.11 layer to update the
2883 * slot time based on the current setting.
2884 */
2885static void
2886ath_updateslot(struct ifnet *ifp)
2887{
2888	struct ath_softc *sc = ifp->if_softc;
2889	struct ieee80211com *ic = ifp->if_l2com;
2890
2891	/*
2892	 * When not coordinating the BSS, change the hardware
2893	 * immediately.  For other operation we defer the change
2894	 * until beacon updates have propagated to the stations.
2895	 */
2896	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
2897		sc->sc_updateslot = UPDATE;
2898	else
2899		ath_setslottime(sc);
2900}
2901
2902/*
2903 * Setup a h/w transmit queue for beacons.
2904 */
2905static int
2906ath_beaconq_setup(struct ath_hal *ah)
2907{
2908	HAL_TXQ_INFO qi;
2909
2910	memset(&qi, 0, sizeof(qi));
2911	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
2912	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
2913	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
2914	/* NB: for dynamic turbo, don't enable any other interrupts */
2915	qi.tqi_qflags = HAL_TXQ_TXDESCINT_ENABLE;
2916	return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
2917}
2918
2919/*
2920 * Setup the transmit queue parameters for the beacon queue.
2921 */
2922static int
2923ath_beaconq_config(struct ath_softc *sc)
2924{
2925#define	ATH_EXPONENT_TO_VALUE(v)	((1<<(v))-1)
2926	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2927	struct ath_hal *ah = sc->sc_ah;
2928	HAL_TXQ_INFO qi;
2929
2930	ath_hal_gettxqueueprops(ah, sc->sc_bhalq, &qi);
2931	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2932		/*
2933		 * Always burst out beacon and CAB traffic.
2934		 */
2935		qi.tqi_aifs = ATH_BEACON_AIFS_DEFAULT;
2936		qi.tqi_cwmin = ATH_BEACON_CWMIN_DEFAULT;
2937		qi.tqi_cwmax = ATH_BEACON_CWMAX_DEFAULT;
2938	} else {
2939		struct wmeParams *wmep =
2940			&ic->ic_wme.wme_chanParams.cap_wmeParams[WME_AC_BE];
2941		/*
2942		 * Adhoc mode; important thing is to use 2x cwmin.
2943		 */
2944		qi.tqi_aifs = wmep->wmep_aifsn;
2945		qi.tqi_cwmin = 2*ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
2946		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
2947	}
2948
2949	if (!ath_hal_settxqueueprops(ah, sc->sc_bhalq, &qi)) {
2950		device_printf(sc->sc_dev, "unable to update parameters for "
2951			"beacon hardware queue!\n");
2952		return 0;
2953	} else {
2954		ath_hal_resettxqueue(ah, sc->sc_bhalq); /* push to h/w */
2955		return 1;
2956	}
2957#undef ATH_EXPONENT_TO_VALUE
2958}
2959
2960/*
2961 * Allocate and setup an initial beacon frame.
2962 */
2963static int
2964ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
2965{
2966	struct ieee80211vap *vap = ni->ni_vap;
2967	struct ath_vap *avp = ATH_VAP(vap);
2968	struct ath_buf *bf;
2969	struct mbuf *m;
2970	int error;
2971
2972	bf = avp->av_bcbuf;
2973	if (bf->bf_m != NULL) {
2974		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2975		m_freem(bf->bf_m);
2976		bf->bf_m = NULL;
2977	}
2978	if (bf->bf_node != NULL) {
2979		ieee80211_free_node(bf->bf_node);
2980		bf->bf_node = NULL;
2981	}
2982
2983	/*
2984	 * NB: the beacon data buffer must be 32-bit aligned;
2985	 * we assume the mbuf routines will return us something
2986	 * with this alignment (perhaps should assert).
2987	 */
2988	m = ieee80211_beacon_alloc(ni, &avp->av_boff);
2989	if (m == NULL) {
2990		device_printf(sc->sc_dev, "%s: cannot get mbuf\n", __func__);
2991		sc->sc_stats.ast_be_nombuf++;
2992		return ENOMEM;
2993	}
2994	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2995				     bf->bf_segs, &bf->bf_nseg,
2996				     BUS_DMA_NOWAIT);
2997	if (error != 0) {
2998		device_printf(sc->sc_dev,
2999		    "%s: cannot map mbuf, bus_dmamap_load_mbuf_sg returns %d\n",
3000		    __func__, error);
3001		m_freem(m);
3002		return error;
3003	}
3004
3005	/*
3006	 * Calculate a TSF adjustment factor required for staggered
3007	 * beacons.  Note that we assume the format of the beacon
3008	 * frame leaves the tstamp field immediately following the
3009	 * header.
3010	 */
3011	if (sc->sc_stagbeacons && avp->av_bslot > 0) {
3012		uint64_t tsfadjust;
3013		struct ieee80211_frame *wh;
3014
3015		/*
3016		 * The beacon interval is in TU's; the TSF is in usecs.
3017		 * We figure out how many TU's to add to align the timestamp
3018		 * then convert to TSF units and handle byte swapping before
3019		 * inserting it in the frame.  The hardware will then add this
3020		 * each time a beacon frame is sent.  Note that we align vap's
3021		 * 1..N and leave vap 0 untouched.  This means vap 0 has a
3022		 * timestamp in one beacon interval while the others get a
3023		 * timstamp aligned to the next interval.
3024		 */
3025		tsfadjust = ni->ni_intval *
3026		    (ATH_BCBUF - avp->av_bslot) / ATH_BCBUF;
3027		tsfadjust = htole64(tsfadjust << 10);	/* TU -> TSF */
3028
3029		DPRINTF(sc, ATH_DEBUG_BEACON,
3030		    "%s: %s beacons bslot %d intval %u tsfadjust %llu\n",
3031		    __func__, sc->sc_stagbeacons ? "stagger" : "burst",
3032		    avp->av_bslot, ni->ni_intval,
3033		    (long long unsigned) le64toh(tsfadjust));
3034
3035		wh = mtod(m, struct ieee80211_frame *);
3036		memcpy(&wh[1], &tsfadjust, sizeof(tsfadjust));
3037	}
3038	bf->bf_m = m;
3039	bf->bf_node = ieee80211_ref_node(ni);
3040
3041	return 0;
3042}
3043
3044/*
3045 * Setup the beacon frame for transmit.
3046 */
3047static void
3048ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
3049{
3050#define	USE_SHPREAMBLE(_ic) \
3051	(((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
3052		== IEEE80211_F_SHPREAMBLE)
3053	struct ieee80211_node *ni = bf->bf_node;
3054	struct ieee80211com *ic = ni->ni_ic;
3055	struct mbuf *m = bf->bf_m;
3056	struct ath_hal *ah = sc->sc_ah;
3057	struct ath_desc *ds;
3058	int flags, antenna;
3059	const HAL_RATE_TABLE *rt;
3060	u_int8_t rix, rate;
3061
3062	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: m %p len %u\n",
3063		__func__, m, m->m_len);
3064
3065	/* setup descriptors */
3066	ds = bf->bf_desc;
3067
3068	flags = HAL_TXDESC_NOACK;
3069	if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
3070		ds->ds_link = bf->bf_daddr;	/* self-linked */
3071		flags |= HAL_TXDESC_VEOL;
3072		/*
3073		 * Let hardware handle antenna switching.
3074		 */
3075		antenna = sc->sc_txantenna;
3076	} else {
3077		ds->ds_link = 0;
3078		/*
3079		 * Switch antenna every 4 beacons.
3080		 * XXX assumes two antenna
3081		 */
3082		if (sc->sc_txantenna != 0)
3083			antenna = sc->sc_txantenna;
3084		else if (sc->sc_stagbeacons && sc->sc_nbcnvaps != 0)
3085			antenna = ((sc->sc_stats.ast_be_xmit / sc->sc_nbcnvaps) & 4 ? 2 : 1);
3086		else
3087			antenna = (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
3088	}
3089
3090	KASSERT(bf->bf_nseg == 1,
3091		("multi-segment beacon frame; nseg %u", bf->bf_nseg));
3092	ds->ds_data = bf->bf_segs[0].ds_addr;
3093	/*
3094	 * Calculate rate code.
3095	 * XXX everything at min xmit rate
3096	 */
3097	rix = 0;
3098	rt = sc->sc_currates;
3099	rate = rt->info[rix].rateCode;
3100	if (USE_SHPREAMBLE(ic))
3101		rate |= rt->info[rix].shortPreamble;
3102	ath_hal_setuptxdesc(ah, ds
3103		, m->m_len + IEEE80211_CRC_LEN	/* frame length */
3104		, sizeof(struct ieee80211_frame)/* header length */
3105		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
3106		, ni->ni_txpower		/* txpower XXX */
3107		, rate, 1			/* series 0 rate/tries */
3108		, HAL_TXKEYIX_INVALID		/* no encryption */
3109		, antenna			/* antenna mode */
3110		, flags				/* no ack, veol for beacons */
3111		, 0				/* rts/cts rate */
3112		, 0				/* rts/cts duration */
3113	);
3114	/* NB: beacon's BufLen must be a multiple of 4 bytes */
3115	ath_hal_filltxdesc(ah, ds
3116		, roundup(m->m_len, 4)		/* buffer length */
3117		, AH_TRUE			/* first segment */
3118		, AH_TRUE			/* last segment */
3119		, ds				/* first descriptor */
3120	);
3121#if 0
3122	ath_desc_swap(ds);
3123#endif
3124#undef USE_SHPREAMBLE
3125}
3126
3127static void
3128ath_beacon_update(struct ieee80211vap *vap, int item)
3129{
3130	struct ieee80211_beacon_offsets *bo = &ATH_VAP(vap)->av_boff;
3131
3132	setbit(bo->bo_flags, item);
3133}
3134
3135/*
3136 * Append the contents of src to dst; both queues
3137 * are assumed to be locked.
3138 */
3139static void
3140ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
3141{
3142	STAILQ_CONCAT(&dst->axq_q, &src->axq_q);
3143	dst->axq_link = src->axq_link;
3144	src->axq_link = NULL;
3145	dst->axq_depth += src->axq_depth;
3146	src->axq_depth = 0;
3147}
3148
3149/*
3150 * Transmit a beacon frame at SWBA.  Dynamic updates to the
3151 * frame contents are done as needed and the slot time is
3152 * also adjusted based on current state.
3153 */
3154static void
3155ath_beacon_proc(void *arg, int pending)
3156{
3157	struct ath_softc *sc = arg;
3158	struct ath_hal *ah = sc->sc_ah;
3159	struct ieee80211vap *vap;
3160	struct ath_buf *bf;
3161	int slot, otherant;
3162	uint32_t bfaddr;
3163
3164	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
3165		__func__, pending);
3166	/*
3167	 * Check if the previous beacon has gone out.  If
3168	 * not don't try to post another, skip this period
3169	 * and wait for the next.  Missed beacons indicate
3170	 * a problem and should not occur.  If we miss too
3171	 * many consecutive beacons reset the device.
3172	 */
3173	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
3174		sc->sc_bmisscount++;
3175		DPRINTF(sc, ATH_DEBUG_BEACON,
3176			"%s: missed %u consecutive beacons\n",
3177			__func__, sc->sc_bmisscount);
3178		if (sc->sc_bmisscount > 3)		/* NB: 3 is a guess */
3179			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
3180		return;
3181	}
3182	if (sc->sc_bmisscount != 0) {
3183		DPRINTF(sc, ATH_DEBUG_BEACON,
3184			"%s: resume beacon xmit after %u misses\n",
3185			__func__, sc->sc_bmisscount);
3186		sc->sc_bmisscount = 0;
3187	}
3188
3189	if (sc->sc_stagbeacons) {			/* staggered beacons */
3190		struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3191		uint32_t tsftu;
3192
3193		tsftu = ath_hal_gettsf32(ah) >> 10;
3194		/* XXX lintval */
3195		slot = ((tsftu % ic->ic_lintval) * ATH_BCBUF) / ic->ic_lintval;
3196		vap = sc->sc_bslot[(slot+1) % ATH_BCBUF];
3197		bfaddr = 0;
3198		if (vap != NULL && vap->iv_state == IEEE80211_S_RUN) {
3199			bf = ath_beacon_generate(sc, vap);
3200			if (bf != NULL)
3201				bfaddr = bf->bf_daddr;
3202		}
3203	} else {					/* burst'd beacons */
3204		uint32_t *bflink = &bfaddr;
3205
3206		for (slot = 0; slot < ATH_BCBUF; slot++) {
3207			vap = sc->sc_bslot[slot];
3208			if (vap != NULL && vap->iv_state == IEEE80211_S_RUN) {
3209				bf = ath_beacon_generate(sc, vap);
3210				if (bf != NULL) {
3211					*bflink = bf->bf_daddr;
3212					bflink = &bf->bf_desc->ds_link;
3213				}
3214			}
3215		}
3216		*bflink = 0;				/* terminate list */
3217	}
3218
3219	/*
3220	 * Handle slot time change when a non-ERP station joins/leaves
3221	 * an 11g network.  The 802.11 layer notifies us via callback,
3222	 * we mark updateslot, then wait one beacon before effecting
3223	 * the change.  This gives associated stations at least one
3224	 * beacon interval to note the state change.
3225	 */
3226	/* XXX locking */
3227	if (sc->sc_updateslot == UPDATE) {
3228		sc->sc_updateslot = COMMIT;	/* commit next beacon */
3229		sc->sc_slotupdate = slot;
3230	} else if (sc->sc_updateslot == COMMIT && sc->sc_slotupdate == slot)
3231		ath_setslottime(sc);		/* commit change to h/w */
3232
3233	/*
3234	 * Check recent per-antenna transmit statistics and flip
3235	 * the default antenna if noticeably more frames went out
3236	 * on the non-default antenna.
3237	 * XXX assumes 2 anntenae
3238	 */
3239	if (!sc->sc_diversity && (!sc->sc_stagbeacons || slot == 0)) {
3240		otherant = sc->sc_defant & 1 ? 2 : 1;
3241		if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
3242			ath_setdefantenna(sc, otherant);
3243		sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
3244	}
3245
3246	if (bfaddr != 0) {
3247		/*
3248		 * Stop any current dma and put the new frame on the queue.
3249		 * This should never fail since we check above that no frames
3250		 * are still pending on the queue.
3251		 */
3252		if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
3253			DPRINTF(sc, ATH_DEBUG_ANY,
3254				"%s: beacon queue %u did not stop?\n",
3255				__func__, sc->sc_bhalq);
3256		}
3257		/* NB: cabq traffic should already be queued and primed */
3258		ath_hal_puttxbuf(ah, sc->sc_bhalq, bfaddr);
3259		ath_hal_txstart(ah, sc->sc_bhalq);
3260
3261		sc->sc_stats.ast_be_xmit++;
3262	}
3263}
3264
3265static struct ath_buf *
3266ath_beacon_generate(struct ath_softc *sc, struct ieee80211vap *vap)
3267{
3268	struct ath_vap *avp = ATH_VAP(vap);
3269	struct ath_txq *cabq = sc->sc_cabq;
3270	struct ath_buf *bf;
3271	struct mbuf *m;
3272	int nmcastq, error;
3273
3274	KASSERT(vap->iv_state == IEEE80211_S_RUN,
3275	    ("not running, state %d", vap->iv_state));
3276	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
3277
3278	/*
3279	 * Update dynamic beacon contents.  If this returns
3280	 * non-zero then we need to remap the memory because
3281	 * the beacon frame changed size (probably because
3282	 * of the TIM bitmap).
3283	 */
3284	bf = avp->av_bcbuf;
3285	m = bf->bf_m;
3286	nmcastq = avp->av_mcastq.axq_depth;
3287	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, nmcastq)) {
3288		/* XXX too conservative? */
3289		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3290		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
3291					     bf->bf_segs, &bf->bf_nseg,
3292					     BUS_DMA_NOWAIT);
3293		if (error != 0) {
3294			if_printf(vap->iv_ifp,
3295			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
3296			    __func__, error);
3297			return NULL;
3298		}
3299	}
3300	if ((avp->av_boff.bo_tim[4] & 1) && cabq->axq_depth) {
3301		DPRINTF(sc, ATH_DEBUG_BEACON,
3302		    "%s: cabq did not drain, mcastq %u cabq %u\n",
3303		    __func__, nmcastq, cabq->axq_depth);
3304		sc->sc_stats.ast_cabq_busy++;
3305		if (sc->sc_nvaps > 1 && sc->sc_stagbeacons) {
3306			/*
3307			 * CABQ traffic from a previous vap is still pending.
3308			 * We must drain the q before this beacon frame goes
3309			 * out as otherwise this vap's stations will get cab
3310			 * frames from a different vap.
3311			 * XXX could be slow causing us to miss DBA
3312			 */
3313			ath_tx_draintxq(sc, cabq);
3314		}
3315	}
3316	ath_beacon_setup(sc, bf);
3317	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3318
3319	/*
3320	 * Enable the CAB queue before the beacon queue to
3321	 * insure cab frames are triggered by this beacon.
3322	 */
3323	if (avp->av_boff.bo_tim[4] & 1) {
3324		struct ath_hal *ah = sc->sc_ah;
3325
3326		/* NB: only at DTIM */
3327		ATH_TXQ_LOCK(cabq);
3328		ATH_TXQ_LOCK(&avp->av_mcastq);
3329		if (nmcastq) {
3330			struct ath_buf *bfm;
3331
3332			/*
3333			 * Move frames from the s/w mcast q to the h/w cab q.
3334			 * XXX MORE_DATA bit
3335			 */
3336			bfm = STAILQ_FIRST(&avp->av_mcastq.axq_q);
3337			if (cabq->axq_link != NULL) {
3338				*cabq->axq_link = bfm->bf_daddr;
3339			} else
3340				ath_hal_puttxbuf(ah, cabq->axq_qnum,
3341					bfm->bf_daddr);
3342			ath_txqmove(cabq, &avp->av_mcastq);
3343
3344			sc->sc_stats.ast_cabq_xmit += nmcastq;
3345		}
3346		/* NB: gated by beacon so safe to start here */
3347		ath_hal_txstart(ah, cabq->axq_qnum);
3348		ATH_TXQ_UNLOCK(cabq);
3349		ATH_TXQ_UNLOCK(&avp->av_mcastq);
3350	}
3351	return bf;
3352}
3353
3354static void
3355ath_beacon_start_adhoc(struct ath_softc *sc, struct ieee80211vap *vap)
3356{
3357	struct ath_vap *avp = ATH_VAP(vap);
3358	struct ath_hal *ah = sc->sc_ah;
3359	struct ath_buf *bf;
3360	struct mbuf *m;
3361	int error;
3362
3363	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
3364
3365	/*
3366	 * Update dynamic beacon contents.  If this returns
3367	 * non-zero then we need to remap the memory because
3368	 * the beacon frame changed size (probably because
3369	 * of the TIM bitmap).
3370	 */
3371	bf = avp->av_bcbuf;
3372	m = bf->bf_m;
3373	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, 0)) {
3374		/* XXX too conservative? */
3375		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3376		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
3377					     bf->bf_segs, &bf->bf_nseg,
3378					     BUS_DMA_NOWAIT);
3379		if (error != 0) {
3380			if_printf(vap->iv_ifp,
3381			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
3382			    __func__, error);
3383			return;
3384		}
3385	}
3386	ath_beacon_setup(sc, bf);
3387	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3388
3389	/* NB: caller is known to have already stopped tx dma */
3390	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
3391	ath_hal_txstart(ah, sc->sc_bhalq);
3392}
3393
3394/*
3395 * Reset the hardware after detecting beacons have stopped.
3396 */
3397static void
3398ath_bstuck_proc(void *arg, int pending)
3399{
3400	struct ath_softc *sc = arg;
3401	struct ifnet *ifp = sc->sc_ifp;
3402
3403	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
3404		sc->sc_bmisscount);
3405	ath_reset(ifp);
3406}
3407
3408/*
3409 * Reclaim beacon resources and return buffer to the pool.
3410 */
3411static void
3412ath_beacon_return(struct ath_softc *sc, struct ath_buf *bf)
3413{
3414
3415	if (bf->bf_m != NULL) {
3416		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3417		m_freem(bf->bf_m);
3418		bf->bf_m = NULL;
3419	}
3420	if (bf->bf_node != NULL) {
3421		ieee80211_free_node(bf->bf_node);
3422		bf->bf_node = NULL;
3423	}
3424	STAILQ_INSERT_TAIL(&sc->sc_bbuf, bf, bf_list);
3425}
3426
3427/*
3428 * Reclaim beacon resources.
3429 */
3430static void
3431ath_beacon_free(struct ath_softc *sc)
3432{
3433	struct ath_buf *bf;
3434
3435	STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
3436		if (bf->bf_m != NULL) {
3437			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3438			m_freem(bf->bf_m);
3439			bf->bf_m = NULL;
3440		}
3441		if (bf->bf_node != NULL) {
3442			ieee80211_free_node(bf->bf_node);
3443			bf->bf_node = NULL;
3444		}
3445	}
3446}
3447
3448/*
3449 * Configure the beacon and sleep timers.
3450 *
3451 * When operating as an AP this resets the TSF and sets
3452 * up the hardware to notify us when we need to issue beacons.
3453 *
3454 * When operating in station mode this sets up the beacon
3455 * timers according to the timestamp of the last received
3456 * beacon and the current TSF, configures PCF and DTIM
3457 * handling, programs the sleep registers so the hardware
3458 * will wakeup in time to receive beacons, and configures
3459 * the beacon miss handling so we'll receive a BMISS
3460 * interrupt when we stop seeing beacons from the AP
3461 * we've associated with.
3462 */
3463static void
3464ath_beacon_config(struct ath_softc *sc, struct ieee80211vap *vap)
3465{
3466#define	TSF_TO_TU(_h,_l) \
3467	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
3468#define	FUDGE	2
3469	struct ath_hal *ah = sc->sc_ah;
3470	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3471	struct ieee80211_node *ni;
3472	u_int32_t nexttbtt, intval, tsftu;
3473	u_int64_t tsf;
3474
3475	if (vap == NULL)
3476		vap = TAILQ_FIRST(&ic->ic_vaps);	/* XXX */
3477	ni = vap->iv_bss;
3478
3479	/* extract tstamp from last beacon and convert to TU */
3480	nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
3481			     LE_READ_4(ni->ni_tstamp.data));
3482	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
3483		/*
3484		 * For multi-bss ap support beacons are either staggered
3485		 * evenly over N slots or burst together.  For the former
3486		 * arrange for the SWBA to be delivered for each slot.
3487		 * Slots that are not occupied will generate nothing.
3488		 */
3489		/* NB: the beacon interval is kept internally in TU's */
3490		intval = ni->ni_intval & HAL_BEACON_PERIOD;
3491		if (sc->sc_stagbeacons)
3492			intval /= ATH_BCBUF;
3493	} else {
3494		/* NB: the beacon interval is kept internally in TU's */
3495		intval = ni->ni_intval & HAL_BEACON_PERIOD;
3496	}
3497	if (nexttbtt == 0)		/* e.g. for ap mode */
3498		nexttbtt = intval;
3499	else if (intval)		/* NB: can be 0 for monitor mode */
3500		nexttbtt = roundup(nexttbtt, intval);
3501	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
3502		__func__, nexttbtt, intval, ni->ni_intval);
3503	if (ic->ic_opmode == IEEE80211_M_STA && !sc->sc_swbmiss) {
3504		HAL_BEACON_STATE bs;
3505		int dtimperiod, dtimcount;
3506		int cfpperiod, cfpcount;
3507
3508		/*
3509		 * Setup dtim and cfp parameters according to
3510		 * last beacon we received (which may be none).
3511		 */
3512		dtimperiod = ni->ni_dtim_period;
3513		if (dtimperiod <= 0)		/* NB: 0 if not known */
3514			dtimperiod = 1;
3515		dtimcount = ni->ni_dtim_count;
3516		if (dtimcount >= dtimperiod)	/* NB: sanity check */
3517			dtimcount = 0;		/* XXX? */
3518		cfpperiod = 1;			/* NB: no PCF support yet */
3519		cfpcount = 0;
3520		/*
3521		 * Pull nexttbtt forward to reflect the current
3522		 * TSF and calculate dtim+cfp state for the result.
3523		 */
3524		tsf = ath_hal_gettsf64(ah);
3525		tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3526		do {
3527			nexttbtt += intval;
3528			if (--dtimcount < 0) {
3529				dtimcount = dtimperiod - 1;
3530				if (--cfpcount < 0)
3531					cfpcount = cfpperiod - 1;
3532			}
3533		} while (nexttbtt < tsftu);
3534		memset(&bs, 0, sizeof(bs));
3535		bs.bs_intval = intval;
3536		bs.bs_nexttbtt = nexttbtt;
3537		bs.bs_dtimperiod = dtimperiod*intval;
3538		bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
3539		bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
3540		bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
3541		bs.bs_cfpmaxduration = 0;
3542#if 0
3543		/*
3544		 * The 802.11 layer records the offset to the DTIM
3545		 * bitmap while receiving beacons; use it here to
3546		 * enable h/w detection of our AID being marked in
3547		 * the bitmap vector (to indicate frames for us are
3548		 * pending at the AP).
3549		 * XXX do DTIM handling in s/w to WAR old h/w bugs
3550		 * XXX enable based on h/w rev for newer chips
3551		 */
3552		bs.bs_timoffset = ni->ni_timoff;
3553#endif
3554		/*
3555		 * Calculate the number of consecutive beacons to miss
3556		 * before taking a BMISS interrupt.
3557		 * Note that we clamp the result to at most 10 beacons.
3558		 */
3559		bs.bs_bmissthreshold = vap->iv_bmissthreshold;
3560		if (bs.bs_bmissthreshold > 10)
3561			bs.bs_bmissthreshold = 10;
3562		else if (bs.bs_bmissthreshold <= 0)
3563			bs.bs_bmissthreshold = 1;
3564
3565		/*
3566		 * Calculate sleep duration.  The configuration is
3567		 * given in ms.  We insure a multiple of the beacon
3568		 * period is used.  Also, if the sleep duration is
3569		 * greater than the DTIM period then it makes senses
3570		 * to make it a multiple of that.
3571		 *
3572		 * XXX fixed at 100ms
3573		 */
3574		bs.bs_sleepduration =
3575			roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
3576		if (bs.bs_sleepduration > bs.bs_dtimperiod)
3577			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
3578
3579		DPRINTF(sc, ATH_DEBUG_BEACON,
3580			"%s: tsf %ju tsf:tu %u intval %u nexttbtt %u dtim %u nextdtim %u bmiss %u sleep %u cfp:period %u maxdur %u next %u timoffset %u\n"
3581			, __func__
3582			, tsf, tsftu
3583			, bs.bs_intval
3584			, bs.bs_nexttbtt
3585			, bs.bs_dtimperiod
3586			, bs.bs_nextdtim
3587			, bs.bs_bmissthreshold
3588			, bs.bs_sleepduration
3589			, bs.bs_cfpperiod
3590			, bs.bs_cfpmaxduration
3591			, bs.bs_cfpnext
3592			, bs.bs_timoffset
3593		);
3594		ath_hal_intrset(ah, 0);
3595		ath_hal_beacontimers(ah, &bs);
3596		sc->sc_imask |= HAL_INT_BMISS;
3597		ath_hal_intrset(ah, sc->sc_imask);
3598	} else {
3599		ath_hal_intrset(ah, 0);
3600		if (nexttbtt == intval)
3601			intval |= HAL_BEACON_RESET_TSF;
3602		if (ic->ic_opmode == IEEE80211_M_IBSS) {
3603			/*
3604			 * In IBSS mode enable the beacon timers but only
3605			 * enable SWBA interrupts if we need to manually
3606			 * prepare beacon frames.  Otherwise we use a
3607			 * self-linked tx descriptor and let the hardware
3608			 * deal with things.
3609			 */
3610			intval |= HAL_BEACON_ENA;
3611			if (!sc->sc_hasveol)
3612				sc->sc_imask |= HAL_INT_SWBA;
3613			if ((intval & HAL_BEACON_RESET_TSF) == 0) {
3614				/*
3615				 * Pull nexttbtt forward to reflect
3616				 * the current TSF.
3617				 */
3618				tsf = ath_hal_gettsf64(ah);
3619				tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3620				do {
3621					nexttbtt += intval;
3622				} while (nexttbtt < tsftu);
3623			}
3624			ath_beaconq_config(sc);
3625		} else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
3626			/*
3627			 * In AP mode we enable the beacon timers and
3628			 * SWBA interrupts to prepare beacon frames.
3629			 */
3630			intval |= HAL_BEACON_ENA;
3631			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
3632			ath_beaconq_config(sc);
3633		}
3634		ath_hal_beaconinit(ah, nexttbtt, intval);
3635		sc->sc_bmisscount = 0;
3636		ath_hal_intrset(ah, sc->sc_imask);
3637		/*
3638		 * When using a self-linked beacon descriptor in
3639		 * ibss mode load it once here.
3640		 */
3641		if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
3642			ath_beacon_start_adhoc(sc, vap);
3643	}
3644	sc->sc_syncbeacon = 0;
3645#undef FUDGE
3646#undef TSF_TO_TU
3647}
3648
3649static void
3650ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3651{
3652	bus_addr_t *paddr = (bus_addr_t*) arg;
3653	KASSERT(error == 0, ("error %u on bus_dma callback", error));
3654	*paddr = segs->ds_addr;
3655}
3656
3657static int
3658ath_descdma_setup(struct ath_softc *sc,
3659	struct ath_descdma *dd, ath_bufhead *head,
3660	const char *name, int nbuf, int ndesc)
3661{
3662#define	DS2PHYS(_dd, _ds) \
3663	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3664	struct ifnet *ifp = sc->sc_ifp;
3665	struct ath_desc *ds;
3666	struct ath_buf *bf;
3667	int i, bsize, error;
3668
3669	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
3670	    __func__, name, nbuf, ndesc);
3671
3672	dd->dd_name = name;
3673	dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
3674
3675	/*
3676	 * Setup DMA descriptor area.
3677	 */
3678	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
3679		       PAGE_SIZE, 0,		/* alignment, bounds */
3680		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
3681		       BUS_SPACE_MAXADDR,	/* highaddr */
3682		       NULL, NULL,		/* filter, filterarg */
3683		       dd->dd_desc_len,		/* maxsize */
3684		       1,			/* nsegments */
3685		       dd->dd_desc_len,		/* maxsegsize */
3686		       BUS_DMA_ALLOCNOW,	/* flags */
3687		       NULL,			/* lockfunc */
3688		       NULL,			/* lockarg */
3689		       &dd->dd_dmat);
3690	if (error != 0) {
3691		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
3692		return error;
3693	}
3694
3695	/* allocate descriptors */
3696	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
3697	if (error != 0) {
3698		if_printf(ifp, "unable to create dmamap for %s descriptors, "
3699			"error %u\n", dd->dd_name, error);
3700		goto fail0;
3701	}
3702
3703	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
3704				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
3705				 &dd->dd_dmamap);
3706	if (error != 0) {
3707		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
3708			"error %u\n", nbuf * ndesc, dd->dd_name, error);
3709		goto fail1;
3710	}
3711
3712	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
3713				dd->dd_desc, dd->dd_desc_len,
3714				ath_load_cb, &dd->dd_desc_paddr,
3715				BUS_DMA_NOWAIT);
3716	if (error != 0) {
3717		if_printf(ifp, "unable to map %s descriptors, error %u\n",
3718			dd->dd_name, error);
3719		goto fail2;
3720	}
3721
3722	ds = dd->dd_desc;
3723	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
3724	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
3725	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
3726
3727	/* allocate rx buffers */
3728	bsize = sizeof(struct ath_buf) * nbuf;
3729	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
3730	if (bf == NULL) {
3731		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
3732			dd->dd_name, bsize);
3733		goto fail3;
3734	}
3735	dd->dd_bufptr = bf;
3736
3737	STAILQ_INIT(head);
3738	for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
3739		bf->bf_desc = ds;
3740		bf->bf_daddr = DS2PHYS(dd, ds);
3741		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3742				&bf->bf_dmamap);
3743		if (error != 0) {
3744			if_printf(ifp, "unable to create dmamap for %s "
3745				"buffer %u, error %u\n", dd->dd_name, i, error);
3746			ath_descdma_cleanup(sc, dd, head);
3747			return error;
3748		}
3749		STAILQ_INSERT_TAIL(head, bf, bf_list);
3750	}
3751	return 0;
3752fail3:
3753	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3754fail2:
3755	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3756fail1:
3757	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3758fail0:
3759	bus_dma_tag_destroy(dd->dd_dmat);
3760	memset(dd, 0, sizeof(*dd));
3761	return error;
3762#undef DS2PHYS
3763}
3764
3765static void
3766ath_descdma_cleanup(struct ath_softc *sc,
3767	struct ath_descdma *dd, ath_bufhead *head)
3768{
3769	struct ath_buf *bf;
3770	struct ieee80211_node *ni;
3771
3772	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3773	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3774	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3775	bus_dma_tag_destroy(dd->dd_dmat);
3776
3777	STAILQ_FOREACH(bf, head, bf_list) {
3778		if (bf->bf_m) {
3779			m_freem(bf->bf_m);
3780			bf->bf_m = NULL;
3781		}
3782		if (bf->bf_dmamap != NULL) {
3783			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
3784			bf->bf_dmamap = NULL;
3785		}
3786		ni = bf->bf_node;
3787		bf->bf_node = NULL;
3788		if (ni != NULL) {
3789			/*
3790			 * Reclaim node reference.
3791			 */
3792			ieee80211_free_node(ni);
3793		}
3794	}
3795
3796	STAILQ_INIT(head);
3797	free(dd->dd_bufptr, M_ATHDEV);
3798	memset(dd, 0, sizeof(*dd));
3799}
3800
3801static int
3802ath_desc_alloc(struct ath_softc *sc)
3803{
3804	int error;
3805
3806	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
3807			"rx", ath_rxbuf, 1);
3808	if (error != 0)
3809		return error;
3810
3811	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
3812			"tx", ath_txbuf, ATH_TXDESC);
3813	if (error != 0) {
3814		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3815		return error;
3816	}
3817
3818	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
3819			"beacon", ATH_BCBUF, 1);
3820	if (error != 0) {
3821		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3822		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3823		return error;
3824	}
3825	return 0;
3826}
3827
3828static void
3829ath_desc_free(struct ath_softc *sc)
3830{
3831
3832	if (sc->sc_bdma.dd_desc_len != 0)
3833		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
3834	if (sc->sc_txdma.dd_desc_len != 0)
3835		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3836	if (sc->sc_rxdma.dd_desc_len != 0)
3837		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3838}
3839
3840static struct ieee80211_node *
3841ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
3842{
3843	struct ieee80211com *ic = vap->iv_ic;
3844	struct ath_softc *sc = ic->ic_ifp->if_softc;
3845	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
3846	struct ath_node *an;
3847
3848	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
3849	if (an == NULL) {
3850		/* XXX stat+msg */
3851		return NULL;
3852	}
3853	ath_rate_node_init(sc, an);
3854
3855	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
3856	return &an->an_node;
3857}
3858
3859static void
3860ath_node_free(struct ieee80211_node *ni)
3861{
3862	struct ieee80211com *ic = ni->ni_ic;
3863        struct ath_softc *sc = ic->ic_ifp->if_softc;
3864
3865	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
3866
3867	ath_rate_node_cleanup(sc, ATH_NODE(ni));
3868	sc->sc_node_free(ni);
3869}
3870
3871static void
3872ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
3873{
3874	struct ieee80211com *ic = ni->ni_ic;
3875	struct ath_softc *sc = ic->ic_ifp->if_softc;
3876	struct ath_hal *ah = sc->sc_ah;
3877	HAL_CHANNEL hchan;
3878
3879	*rssi = ic->ic_node_getrssi(ni);
3880	if (ni->ni_chan != IEEE80211_CHAN_ANYC) {
3881		ath_mapchan(ic, &hchan, ni->ni_chan);
3882		*noise = ath_hal_getchannoise(ah, &hchan);
3883	} else
3884		*noise = -95;		/* nominally correct */
3885}
3886
3887static int
3888ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
3889{
3890	struct ath_hal *ah = sc->sc_ah;
3891	int error;
3892	struct mbuf *m;
3893	struct ath_desc *ds;
3894
3895	m = bf->bf_m;
3896	if (m == NULL) {
3897		/*
3898		 * NB: by assigning a page to the rx dma buffer we
3899		 * implicitly satisfy the Atheros requirement that
3900		 * this buffer be cache-line-aligned and sized to be
3901		 * multiple of the cache line size.  Not doing this
3902		 * causes weird stuff to happen (for the 5210 at least).
3903		 */
3904		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
3905		if (m == NULL) {
3906			DPRINTF(sc, ATH_DEBUG_ANY,
3907				"%s: no mbuf/cluster\n", __func__);
3908			sc->sc_stats.ast_rx_nombuf++;
3909			return ENOMEM;
3910		}
3911		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
3912
3913		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
3914					     bf->bf_dmamap, m,
3915					     bf->bf_segs, &bf->bf_nseg,
3916					     BUS_DMA_NOWAIT);
3917		if (error != 0) {
3918			DPRINTF(sc, ATH_DEBUG_ANY,
3919			    "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
3920			    __func__, error);
3921			sc->sc_stats.ast_rx_busdma++;
3922			m_freem(m);
3923			return error;
3924		}
3925		KASSERT(bf->bf_nseg == 1,
3926			("multi-segment packet; nseg %u", bf->bf_nseg));
3927		bf->bf_m = m;
3928	}
3929	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
3930
3931	/*
3932	 * Setup descriptors.  For receive we always terminate
3933	 * the descriptor list with a self-linked entry so we'll
3934	 * not get overrun under high load (as can happen with a
3935	 * 5212 when ANI processing enables PHY error frames).
3936	 *
3937	 * To insure the last descriptor is self-linked we create
3938	 * each descriptor as self-linked and add it to the end.  As
3939	 * each additional descriptor is added the previous self-linked
3940	 * entry is ``fixed'' naturally.  This should be safe even
3941	 * if DMA is happening.  When processing RX interrupts we
3942	 * never remove/process the last, self-linked, entry on the
3943	 * descriptor list.  This insures the hardware always has
3944	 * someplace to write a new frame.
3945	 */
3946	ds = bf->bf_desc;
3947	ds->ds_link = bf->bf_daddr;	/* link to self */
3948	ds->ds_data = bf->bf_segs[0].ds_addr;
3949	ath_hal_setuprxdesc(ah, ds
3950		, m->m_len		/* buffer size */
3951		, 0
3952	);
3953
3954	if (sc->sc_rxlink != NULL)
3955		*sc->sc_rxlink = bf->bf_daddr;
3956	sc->sc_rxlink = &ds->ds_link;
3957	return 0;
3958}
3959
3960/*
3961 * Extend 15-bit time stamp from rx descriptor to
3962 * a full 64-bit TSF using the specified TSF.
3963 */
3964static __inline u_int64_t
3965ath_extend_tsf(u_int32_t rstamp, u_int64_t tsf)
3966{
3967	if ((tsf & 0x7fff) < rstamp)
3968		tsf -= 0x8000;
3969	return ((tsf &~ 0x7fff) | rstamp);
3970}
3971
3972/*
3973 * Intercept management frames to collect beacon rssi data
3974 * and to do ibss merges.
3975 */
3976static void
3977ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
3978	int subtype, int rssi, int noise, u_int32_t rstamp)
3979{
3980	struct ieee80211vap *vap = ni->ni_vap;
3981	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
3982
3983	/*
3984	 * Call up first so subsequent work can use information
3985	 * potentially stored in the node (e.g. for ibss merge).
3986	 */
3987	ATH_VAP(vap)->av_recv_mgmt(ni, m, subtype, rssi, noise, rstamp);
3988	switch (subtype) {
3989	case IEEE80211_FC0_SUBTYPE_BEACON:
3990		/* update rssi statistics for use by the hal */
3991		ATH_RSSI_LPF(sc->sc_halstats.ns_avgbrssi, rssi);
3992		if (sc->sc_syncbeacon &&
3993		    ni == vap->iv_bss && vap->iv_state == IEEE80211_S_RUN) {
3994			/*
3995			 * Resync beacon timers using the tsf of the beacon
3996			 * frame we just received.
3997			 */
3998			ath_beacon_config(sc, vap);
3999		}
4000		/* fall thru... */
4001	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
4002		if (vap->iv_opmode == IEEE80211_M_IBSS &&
4003		    vap->iv_state == IEEE80211_S_RUN) {
4004			u_int64_t tsf = ath_extend_tsf(rstamp,
4005				ath_hal_gettsf64(sc->sc_ah));
4006			/*
4007			 * Handle ibss merge as needed; check the tsf on the
4008			 * frame before attempting the merge.  The 802.11 spec
4009			 * says the station should change it's bssid to match
4010			 * the oldest station with the same ssid, where oldest
4011			 * is determined by the tsf.  Note that hardware
4012			 * reconfiguration happens through callback to
4013			 * ath_newstate as the state machine will go from
4014			 * RUN -> RUN when this happens.
4015			 */
4016			if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
4017				DPRINTF(sc, ATH_DEBUG_STATE,
4018				    "ibss merge, rstamp %u tsf %ju "
4019				    "tstamp %ju\n", rstamp, (uintmax_t)tsf,
4020				    (uintmax_t)ni->ni_tstamp.tsf);
4021				(void) ieee80211_ibss_merge(ni);
4022			}
4023		}
4024		break;
4025	}
4026}
4027
4028/*
4029 * Set the default antenna.
4030 */
4031static void
4032ath_setdefantenna(struct ath_softc *sc, u_int antenna)
4033{
4034	struct ath_hal *ah = sc->sc_ah;
4035
4036	/* XXX block beacon interrupts */
4037	ath_hal_setdefantenna(ah, antenna);
4038	if (sc->sc_defant != antenna)
4039		sc->sc_stats.ast_ant_defswitch++;
4040	sc->sc_defant = antenna;
4041	sc->sc_rxotherant = 0;
4042}
4043
4044static int
4045ath_rx_tap(struct ifnet *ifp, struct mbuf *m,
4046	const struct ath_rx_status *rs, u_int64_t tsf, int16_t nf)
4047{
4048#define	CHAN_HT20	htole32(IEEE80211_CHAN_HT20)
4049#define	CHAN_HT40U	htole32(IEEE80211_CHAN_HT40U)
4050#define	CHAN_HT40D	htole32(IEEE80211_CHAN_HT40D)
4051#define	CHAN_HT		(CHAN_HT20|CHAN_HT40U|CHAN_HT40D)
4052	struct ath_softc *sc = ifp->if_softc;
4053	const HAL_RATE_TABLE *rt;
4054	uint8_t rix;
4055
4056	/*
4057	 * Discard anything shorter than an ack or cts.
4058	 */
4059	if (m->m_pkthdr.len < IEEE80211_ACK_LEN) {
4060		DPRINTF(sc, ATH_DEBUG_RECV, "%s: runt packet %d\n",
4061			__func__, m->m_pkthdr.len);
4062		sc->sc_stats.ast_rx_tooshort++;
4063		return 0;
4064	}
4065	rt = sc->sc_currates;
4066	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
4067	rix = rt->rateCodeToIndex[rs->rs_rate];
4068	sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
4069	sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
4070#ifdef AH_SUPPORT_AR5416
4071	sc->sc_rx_th.wr_chan_flags &= ~CHAN_HT;
4072	if (sc->sc_rx_th.wr_rate & IEEE80211_RATE_MCS) {	/* HT rate */
4073		if ((rs->rs_flags & HAL_RX_2040) == 0)
4074			sc->sc_rx_th.wr_chan_flags |= CHAN_HT20;
4075		else if (sc->sc_curchan.channelFlags & CHANNEL_HT40PLUS)
4076			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40U;
4077		else
4078			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40D;
4079		if ((rs->rs_flags & HAL_RX_GI) == 0)
4080			sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_SHORTGI;
4081	}
4082#endif
4083	sc->sc_rx_th.wr_tsf = htole64(ath_extend_tsf(rs->rs_tstamp, tsf));
4084	if (rs->rs_status & HAL_RXERR_CRC)
4085		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
4086	/* XXX propagate other error flags from descriptor */
4087	sc->sc_rx_th.wr_antsignal = rs->rs_rssi + nf;
4088	sc->sc_rx_th.wr_antnoise = nf;
4089	sc->sc_rx_th.wr_antenna = rs->rs_antenna;
4090
4091	bpf_mtap2(ifp->if_bpf, &sc->sc_rx_th, sc->sc_rx_th_len, m);
4092
4093	return 1;
4094#undef CHAN_HT
4095#undef CHAN_HT20
4096#undef CHAN_HT40U
4097#undef CHAN_HT40D
4098}
4099
4100static void
4101ath_handle_micerror(struct ieee80211com *ic,
4102	struct ieee80211_frame *wh, int keyix)
4103{
4104	struct ieee80211_node *ni;
4105
4106	/* XXX recheck MIC to deal w/ chips that lie */
4107	/* XXX discard MIC errors on !data frames */
4108	ni = ieee80211_find_rxnode(ic, (const struct ieee80211_frame_min *) wh);
4109	if (ni != NULL) {
4110		ieee80211_notify_michael_failure(ni->ni_vap, wh, keyix);
4111		ieee80211_free_node(ni);
4112	}
4113}
4114
4115static void
4116ath_rx_proc(void *arg, int npending)
4117{
4118#define	PA2DESC(_sc, _pa) \
4119	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
4120		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
4121	struct ath_softc *sc = arg;
4122	struct ath_buf *bf;
4123	struct ifnet *ifp = sc->sc_ifp;
4124	struct ieee80211com *ic = ifp->if_l2com;
4125	struct ath_hal *ah = sc->sc_ah;
4126	struct ath_desc *ds;
4127	struct ath_rx_status *rs;
4128	struct mbuf *m;
4129	struct ieee80211_node *ni;
4130	int len, type, ngood;
4131	u_int phyerr;
4132	HAL_STATUS status;
4133	int16_t nf;
4134	u_int64_t tsf;
4135
4136	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
4137	ngood = 0;
4138	nf = ath_hal_getchannoise(ah, &sc->sc_curchan);
4139	sc->sc_stats.ast_rx_noise = nf;
4140	tsf = ath_hal_gettsf64(ah);
4141	do {
4142		bf = STAILQ_FIRST(&sc->sc_rxbuf);
4143		if (bf == NULL) {		/* NB: shouldn't happen */
4144			if_printf(ifp, "%s: no buffer!\n", __func__);
4145			break;
4146		}
4147		m = bf->bf_m;
4148		if (m == NULL) {		/* NB: shouldn't happen */
4149			/*
4150			 * If mbuf allocation failed previously there
4151			 * will be no mbuf; try again to re-populate it.
4152			 */
4153			/* XXX make debug msg */
4154			if_printf(ifp, "%s: no mbuf!\n", __func__);
4155			STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
4156			goto rx_next;
4157		}
4158		ds = bf->bf_desc;
4159		if (ds->ds_link == bf->bf_daddr) {
4160			/* NB: never process the self-linked entry at the end */
4161			break;
4162		}
4163		/* XXX sync descriptor memory */
4164		/*
4165		 * Must provide the virtual address of the current
4166		 * descriptor, the physical address, and the virtual
4167		 * address of the next descriptor in the h/w chain.
4168		 * This allows the HAL to look ahead to see if the
4169		 * hardware is done with a descriptor by checking the
4170		 * done bit in the following descriptor and the address
4171		 * of the current descriptor the DMA engine is working
4172		 * on.  All this is necessary because of our use of
4173		 * a self-linked list to avoid rx overruns.
4174		 */
4175		rs = &bf->bf_status.ds_rxstat;
4176		status = ath_hal_rxprocdesc(ah, ds,
4177				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
4178#ifdef ATH_DEBUG
4179		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
4180			ath_printrxbuf(sc, bf, 0, status == HAL_OK);
4181#endif
4182		if (status == HAL_EINPROGRESS)
4183			break;
4184		STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
4185		if (rs->rs_status != 0) {
4186			if (rs->rs_status & HAL_RXERR_CRC)
4187				sc->sc_stats.ast_rx_crcerr++;
4188			if (rs->rs_status & HAL_RXERR_FIFO)
4189				sc->sc_stats.ast_rx_fifoerr++;
4190			if (rs->rs_status & HAL_RXERR_PHY) {
4191				sc->sc_stats.ast_rx_phyerr++;
4192				phyerr = rs->rs_phyerr & 0x1f;
4193				sc->sc_stats.ast_rx_phy[phyerr]++;
4194				goto rx_error;	/* NB: don't count in ierrors */
4195			}
4196			if (rs->rs_status & HAL_RXERR_DECRYPT) {
4197				/*
4198				 * Decrypt error.  If the error occurred
4199				 * because there was no hardware key, then
4200				 * let the frame through so the upper layers
4201				 * can process it.  This is necessary for 5210
4202				 * parts which have no way to setup a ``clear''
4203				 * key cache entry.
4204				 *
4205				 * XXX do key cache faulting
4206				 */
4207				if (rs->rs_keyix == HAL_RXKEYIX_INVALID)
4208					goto rx_accept;
4209				sc->sc_stats.ast_rx_badcrypt++;
4210			}
4211			if (rs->rs_status & HAL_RXERR_MIC) {
4212				sc->sc_stats.ast_rx_badmic++;
4213				/*
4214				 * Do minimal work required to hand off
4215				 * the 802.11 header for notifcation.
4216				 */
4217				/* XXX frag's and qos frames */
4218				len = rs->rs_datalen;
4219				if (len >= sizeof (struct ieee80211_frame)) {
4220					bus_dmamap_sync(sc->sc_dmat,
4221					    bf->bf_dmamap,
4222					    BUS_DMASYNC_POSTREAD);
4223					ath_handle_micerror(ic,
4224					    mtod(m, struct ieee80211_frame *),
4225					    sc->sc_splitmic ?
4226						rs->rs_keyix-32 : rs->rs_keyix);
4227				}
4228			}
4229			ifp->if_ierrors++;
4230rx_error:
4231			/*
4232			 * Cleanup any pending partial frame.
4233			 */
4234			if (sc->sc_rxpending != NULL) {
4235				m_freem(sc->sc_rxpending);
4236				sc->sc_rxpending = NULL;
4237			}
4238			/*
4239			 * When a tap is present pass error frames
4240			 * that have been requested.  By default we
4241			 * pass decrypt+mic errors but others may be
4242			 * interesting (e.g. crc).
4243			 */
4244			if (bpf_peers_present(ifp->if_bpf) &&
4245			    (rs->rs_status & sc->sc_monpass)) {
4246				bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4247				    BUS_DMASYNC_POSTREAD);
4248				/* NB: bpf needs the mbuf length setup */
4249				len = rs->rs_datalen;
4250				m->m_pkthdr.len = m->m_len = len;
4251				(void) ath_rx_tap(ifp, m, rs, tsf, nf);
4252			}
4253			/* XXX pass MIC errors up for s/w reclaculation */
4254			goto rx_next;
4255		}
4256rx_accept:
4257		/*
4258		 * Sync and unmap the frame.  At this point we're
4259		 * committed to passing the mbuf somewhere so clear
4260		 * bf_m; this means a new mbuf must be allocated
4261		 * when the rx descriptor is setup again to receive
4262		 * another frame.
4263		 */
4264		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4265		    BUS_DMASYNC_POSTREAD);
4266		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4267		bf->bf_m = NULL;
4268
4269		len = rs->rs_datalen;
4270		m->m_len = len;
4271
4272		if (rs->rs_more) {
4273			/*
4274			 * Frame spans multiple descriptors; save
4275			 * it for the next completed descriptor, it
4276			 * will be used to construct a jumbogram.
4277			 */
4278			if (sc->sc_rxpending != NULL) {
4279				/* NB: max frame size is currently 2 clusters */
4280				sc->sc_stats.ast_rx_toobig++;
4281				m_freem(sc->sc_rxpending);
4282			}
4283			m->m_pkthdr.rcvif = ifp;
4284			m->m_pkthdr.len = len;
4285			sc->sc_rxpending = m;
4286			goto rx_next;
4287		} else if (sc->sc_rxpending != NULL) {
4288			/*
4289			 * This is the second part of a jumbogram,
4290			 * chain it to the first mbuf, adjust the
4291			 * frame length, and clear the rxpending state.
4292			 */
4293			sc->sc_rxpending->m_next = m;
4294			sc->sc_rxpending->m_pkthdr.len += len;
4295			m = sc->sc_rxpending;
4296			sc->sc_rxpending = NULL;
4297		} else {
4298			/*
4299			 * Normal single-descriptor receive; setup
4300			 * the rcvif and packet length.
4301			 */
4302			m->m_pkthdr.rcvif = ifp;
4303			m->m_pkthdr.len = len;
4304		}
4305
4306		ifp->if_ipackets++;
4307		sc->sc_stats.ast_ant_rx[rs->rs_antenna]++;
4308
4309		if (bpf_peers_present(ifp->if_bpf) &&
4310		    !ath_rx_tap(ifp, m, rs, tsf, nf)) {
4311			m_freem(m);		/* XXX reclaim */
4312			goto rx_next;
4313		}
4314
4315		/*
4316		 * From this point on we assume the frame is at least
4317		 * as large as ieee80211_frame_min; verify that.
4318		 */
4319		if (len < IEEE80211_MIN_LEN) {
4320			DPRINTF(sc, ATH_DEBUG_RECV, "%s: short packet %d\n",
4321				__func__, len);
4322			sc->sc_stats.ast_rx_tooshort++;
4323			m_freem(m);
4324			goto rx_next;
4325		}
4326
4327		if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
4328			const HAL_RATE_TABLE *rt = sc->sc_currates;
4329			uint8_t rix = rt->rateCodeToIndex[rs->rs_rate];
4330
4331			ieee80211_dump_pkt(ic, mtod(m, caddr_t), len,
4332			    sc->sc_hwmap[rix].ieeerate, rs->rs_rssi);
4333		}
4334
4335		m_adj(m, -IEEE80211_CRC_LEN);
4336
4337		/*
4338		 * Locate the node for sender, track state, and then
4339		 * pass the (referenced) node up to the 802.11 layer
4340		 * for its use.
4341		 */
4342		ni = ieee80211_find_rxnode_withkey(ic,
4343			mtod(m, const struct ieee80211_frame_min *),
4344			rs->rs_keyix == HAL_RXKEYIX_INVALID ?
4345				IEEE80211_KEYIX_NONE : rs->rs_keyix);
4346		if (ni != NULL) {
4347			/*
4348			 * Sending station is known, dispatch directly.
4349			 */
4350#ifdef ATH_SUPPORT_TDMA
4351			sc->sc_tdmars = rs;
4352#endif
4353			type = ieee80211_input(ni, m,
4354			    rs->rs_rssi, nf, rs->rs_tstamp);
4355			ieee80211_free_node(ni);
4356			/*
4357			 * Arrange to update the last rx timestamp only for
4358			 * frames from our ap when operating in station mode.
4359			 * This assumes the rx key is always setup when
4360			 * associated.
4361			 */
4362			if (ic->ic_opmode == IEEE80211_M_STA &&
4363			    rs->rs_keyix != HAL_RXKEYIX_INVALID)
4364				ngood++;
4365		} else {
4366			type = ieee80211_input_all(ic, m,
4367			    rs->rs_rssi, nf, rs->rs_tstamp);
4368		}
4369		/*
4370		 * Track rx rssi and do any rx antenna management.
4371		 */
4372		ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, rs->rs_rssi);
4373		if (sc->sc_diversity) {
4374			/*
4375			 * When using fast diversity, change the default rx
4376			 * antenna if diversity chooses the other antenna 3
4377			 * times in a row.
4378			 */
4379			if (sc->sc_defant != rs->rs_antenna) {
4380				if (++sc->sc_rxotherant >= 3)
4381					ath_setdefantenna(sc, rs->rs_antenna);
4382			} else
4383				sc->sc_rxotherant = 0;
4384		}
4385		if (sc->sc_softled) {
4386			/*
4387			 * Blink for any data frame.  Otherwise do a
4388			 * heartbeat-style blink when idle.  The latter
4389			 * is mainly for station mode where we depend on
4390			 * periodic beacon frames to trigger the poll event.
4391			 */
4392			if (type == IEEE80211_FC0_TYPE_DATA) {
4393				const HAL_RATE_TABLE *rt = sc->sc_currates;
4394				ath_led_event(sc,
4395				    rt->rateCodeToIndex[rs->rs_rate]);
4396			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
4397				ath_led_event(sc, 0);
4398		}
4399rx_next:
4400		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
4401	} while (ath_rxbuf_init(sc, bf) == 0);
4402
4403	/* rx signal state monitoring */
4404	ath_hal_rxmonitor(ah, &sc->sc_halstats, &sc->sc_curchan);
4405	if (ngood)
4406		sc->sc_lastrx = tsf;
4407
4408	if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0 &&
4409	    !IFQ_IS_EMPTY(&ifp->if_snd))
4410		ath_start(ifp);
4411
4412#undef PA2DESC
4413}
4414
4415static void
4416ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
4417{
4418	txq->axq_qnum = qnum;
4419	txq->axq_depth = 0;
4420	txq->axq_intrcnt = 0;
4421	txq->axq_link = NULL;
4422	STAILQ_INIT(&txq->axq_q);
4423	ATH_TXQ_LOCK_INIT(sc, txq);
4424	TAILQ_INIT(&txq->axq_stageq);
4425	txq->axq_curage = 0;
4426}
4427
4428/*
4429 * Setup a h/w transmit queue.
4430 */
4431static struct ath_txq *
4432ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
4433{
4434#define	N(a)	(sizeof(a)/sizeof(a[0]))
4435	struct ath_hal *ah = sc->sc_ah;
4436	HAL_TXQ_INFO qi;
4437	int qnum;
4438
4439	memset(&qi, 0, sizeof(qi));
4440	qi.tqi_subtype = subtype;
4441	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
4442	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
4443	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
4444	/*
4445	 * Enable interrupts only for EOL and DESC conditions.
4446	 * We mark tx descriptors to receive a DESC interrupt
4447	 * when a tx queue gets deep; otherwise waiting for the
4448	 * EOL to reap descriptors.  Note that this is done to
4449	 * reduce interrupt load and this only defers reaping
4450	 * descriptors, never transmitting frames.  Aside from
4451	 * reducing interrupts this also permits more concurrency.
4452	 * The only potential downside is if the tx queue backs
4453	 * up in which case the top half of the kernel may backup
4454	 * due to a lack of tx descriptors.
4455	 */
4456	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
4457	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
4458	if (qnum == -1) {
4459		/*
4460		 * NB: don't print a message, this happens
4461		 * normally on parts with too few tx queues
4462		 */
4463		return NULL;
4464	}
4465	if (qnum >= N(sc->sc_txq)) {
4466		device_printf(sc->sc_dev,
4467			"hal qnum %u out of range, max %zu!\n",
4468			qnum, N(sc->sc_txq));
4469		ath_hal_releasetxqueue(ah, qnum);
4470		return NULL;
4471	}
4472	if (!ATH_TXQ_SETUP(sc, qnum)) {
4473		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
4474		sc->sc_txqsetup |= 1<<qnum;
4475	}
4476	return &sc->sc_txq[qnum];
4477#undef N
4478}
4479
4480/*
4481 * Setup a hardware data transmit queue for the specified
4482 * access control.  The hal may not support all requested
4483 * queues in which case it will return a reference to a
4484 * previously setup queue.  We record the mapping from ac's
4485 * to h/w queues for use by ath_tx_start and also track
4486 * the set of h/w queues being used to optimize work in the
4487 * transmit interrupt handler and related routines.
4488 */
4489static int
4490ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
4491{
4492#define	N(a)	(sizeof(a)/sizeof(a[0]))
4493	struct ath_txq *txq;
4494
4495	if (ac >= N(sc->sc_ac2q)) {
4496		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
4497			ac, N(sc->sc_ac2q));
4498		return 0;
4499	}
4500	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
4501	if (txq != NULL) {
4502		sc->sc_ac2q[ac] = txq;
4503		return 1;
4504	} else
4505		return 0;
4506#undef N
4507}
4508
4509/*
4510 * Update WME parameters for a transmit queue.
4511 */
4512static int
4513ath_txq_update(struct ath_softc *sc, int ac)
4514{
4515#define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
4516#define	ATH_TXOP_TO_US(v)		(v<<5)
4517	struct ifnet *ifp = sc->sc_ifp;
4518	struct ieee80211com *ic = ifp->if_l2com;
4519	struct ath_txq *txq = sc->sc_ac2q[ac];
4520	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
4521	struct ath_hal *ah = sc->sc_ah;
4522	HAL_TXQ_INFO qi;
4523
4524	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
4525#ifdef ATH_SUPPORT_TDMA
4526	if (sc->sc_tdma) {
4527		/*
4528		 * AIFS is zero so there's no pre-transmit wait.  The
4529		 * burst time defines the slot duration and is configured
4530		 * via sysctl.  The QCU is setup to not do post-xmit
4531		 * back off, lockout all lower-priority QCU's, and fire
4532		 * off the DMA beacon alert timer which is setup based
4533		 * on the slot configuration.
4534		 */
4535		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4536			      | HAL_TXQ_TXERRINT_ENABLE
4537			      | HAL_TXQ_TXURNINT_ENABLE
4538			      | HAL_TXQ_TXEOLINT_ENABLE
4539			      | HAL_TXQ_DBA_GATED
4540			      | HAL_TXQ_BACKOFF_DISABLE
4541			      | HAL_TXQ_ARB_LOCKOUT_GLOBAL
4542			      ;
4543		qi.tqi_aifs = 0;
4544		/* XXX +dbaprep? */
4545		qi.tqi_readyTime = sc->sc_tdmaslotlen;
4546		qi.tqi_burstTime = qi.tqi_readyTime;
4547	} else {
4548#endif
4549		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4550			      | HAL_TXQ_TXERRINT_ENABLE
4551			      | HAL_TXQ_TXDESCINT_ENABLE
4552			      | HAL_TXQ_TXURNINT_ENABLE
4553			      ;
4554		qi.tqi_aifs = wmep->wmep_aifsn;
4555		qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
4556		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
4557		qi.tqi_readyTime = 0;
4558		qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
4559#ifdef ATH_SUPPORT_TDMA
4560	}
4561#endif
4562
4563	DPRINTF(sc, ATH_DEBUG_RESET,
4564	    "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
4565	    __func__, txq->axq_qnum, qi.tqi_qflags,
4566	    qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
4567
4568	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
4569		if_printf(ifp, "unable to update hardware queue "
4570			"parameters for %s traffic!\n",
4571			ieee80211_wme_acnames[ac]);
4572		return 0;
4573	} else {
4574		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
4575		return 1;
4576	}
4577#undef ATH_TXOP_TO_US
4578#undef ATH_EXPONENT_TO_VALUE
4579}
4580
4581/*
4582 * Callback from the 802.11 layer to update WME parameters.
4583 */
4584static int
4585ath_wme_update(struct ieee80211com *ic)
4586{
4587	struct ath_softc *sc = ic->ic_ifp->if_softc;
4588
4589	return !ath_txq_update(sc, WME_AC_BE) ||
4590	    !ath_txq_update(sc, WME_AC_BK) ||
4591	    !ath_txq_update(sc, WME_AC_VI) ||
4592	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
4593}
4594
4595/*
4596 * Reclaim resources for a setup queue.
4597 */
4598static void
4599ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
4600{
4601
4602	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
4603	ATH_TXQ_LOCK_DESTROY(txq);
4604	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
4605}
4606
4607/*
4608 * Reclaim all tx queue resources.
4609 */
4610static void
4611ath_tx_cleanup(struct ath_softc *sc)
4612{
4613	int i;
4614
4615	ATH_TXBUF_LOCK_DESTROY(sc);
4616	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4617		if (ATH_TXQ_SETUP(sc, i))
4618			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
4619}
4620
4621/*
4622 * Return h/w rate index for an IEEE rate (w/o basic rate bit).
4623 */
4624static int
4625ath_tx_findrix(const HAL_RATE_TABLE *rt, int rate)
4626{
4627	int i;
4628
4629	for (i = 0; i < rt->rateCount; i++)
4630		if ((rt->info[i].dot11Rate & IEEE80211_RATE_VAL) == rate)
4631			return i;
4632	return 0;		/* NB: lowest rate */
4633}
4634
4635/*
4636 * Reclaim mbuf resources.  For fragmented frames we
4637 * need to claim each frag chained with m_nextpkt.
4638 */
4639static void
4640ath_freetx(struct mbuf *m)
4641{
4642	struct mbuf *next;
4643
4644	do {
4645		next = m->m_nextpkt;
4646		m->m_nextpkt = NULL;
4647		m_freem(m);
4648	} while ((m = next) != NULL);
4649}
4650
4651static int
4652ath_tx_dmasetup(struct ath_softc *sc, struct ath_buf *bf, struct mbuf *m0)
4653{
4654	struct mbuf *m;
4655	int error;
4656
4657	/*
4658	 * Load the DMA map so any coalescing is done.  This
4659	 * also calculates the number of descriptors we need.
4660	 */
4661	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
4662				     bf->bf_segs, &bf->bf_nseg,
4663				     BUS_DMA_NOWAIT);
4664	if (error == EFBIG) {
4665		/* XXX packet requires too many descriptors */
4666		bf->bf_nseg = ATH_TXDESC+1;
4667	} else if (error != 0) {
4668		sc->sc_stats.ast_tx_busdma++;
4669		ath_freetx(m0);
4670		return error;
4671	}
4672	/*
4673	 * Discard null packets and check for packets that
4674	 * require too many TX descriptors.  We try to convert
4675	 * the latter to a cluster.
4676	 */
4677	if (bf->bf_nseg > ATH_TXDESC) {		/* too many desc's, linearize */
4678		sc->sc_stats.ast_tx_linear++;
4679		m = m_collapse(m0, M_DONTWAIT, ATH_TXDESC);
4680		if (m == NULL) {
4681			ath_freetx(m0);
4682			sc->sc_stats.ast_tx_nombuf++;
4683			return ENOMEM;
4684		}
4685		m0 = m;
4686		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
4687					     bf->bf_segs, &bf->bf_nseg,
4688					     BUS_DMA_NOWAIT);
4689		if (error != 0) {
4690			sc->sc_stats.ast_tx_busdma++;
4691			ath_freetx(m0);
4692			return error;
4693		}
4694		KASSERT(bf->bf_nseg <= ATH_TXDESC,
4695		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
4696	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
4697		sc->sc_stats.ast_tx_nodata++;
4698		ath_freetx(m0);
4699		return EIO;
4700	}
4701	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n",
4702		__func__, m0, m0->m_pkthdr.len);
4703	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
4704	bf->bf_m = m0;
4705
4706	return 0;
4707}
4708
4709static void
4710ath_tx_handoff(struct ath_softc *sc, struct ath_txq *txq, struct ath_buf *bf)
4711{
4712	struct ath_hal *ah = sc->sc_ah;
4713	struct ath_desc *ds, *ds0;
4714	int i;
4715
4716	/*
4717	 * Fillin the remainder of the descriptor info.
4718	 */
4719	ds0 = ds = bf->bf_desc;
4720	for (i = 0; i < bf->bf_nseg; i++, ds++) {
4721		ds->ds_data = bf->bf_segs[i].ds_addr;
4722		if (i == bf->bf_nseg - 1)
4723			ds->ds_link = 0;
4724		else
4725			ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
4726		ath_hal_filltxdesc(ah, ds
4727			, bf->bf_segs[i].ds_len	/* segment length */
4728			, i == 0		/* first segment */
4729			, i == bf->bf_nseg - 1	/* last segment */
4730			, ds0			/* first descriptor */
4731		);
4732		DPRINTF(sc, ATH_DEBUG_XMIT,
4733			"%s: %d: %08x %08x %08x %08x %08x %08x\n",
4734			__func__, i, ds->ds_link, ds->ds_data,
4735			ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
4736	}
4737	/*
4738	 * Insert the frame on the outbound list and pass it on
4739	 * to the hardware.  Multicast frames buffered for power
4740	 * save stations and transmit from the CAB queue are stored
4741	 * on a s/w only queue and loaded on to the CAB queue in
4742	 * the SWBA handler since frames only go out on DTIM and
4743	 * to avoid possible races.
4744	 */
4745	ATH_TXQ_LOCK(txq);
4746	KASSERT((bf->bf_flags & ATH_BUF_BUSY) == 0,
4747	     ("busy status 0x%x", bf->bf_flags));
4748	if (txq->axq_qnum != ATH_TXQ_SWQ) {
4749#ifdef ATH_SUPPORT_TDMA
4750		int qbusy;
4751
4752		ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4753		qbusy = ath_hal_txqenabled(ah, txq->axq_qnum);
4754		if (txq->axq_link == NULL) {
4755			/*
4756			 * Be careful writing the address to TXDP.  If
4757			 * the tx q is enabled then this write will be
4758			 * ignored.  Normally this is not an issue but
4759			 * when tdma is in use and the q is beacon gated
4760			 * this race can occur.  If the q is busy then
4761			 * defer the work to later--either when another
4762			 * packet comes along or when we prepare a beacon
4763			 * frame at SWBA.
4764			 */
4765			if (!qbusy) {
4766				ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
4767				txq->axq_flags &= ~ATH_TXQ_PUTPENDING;
4768				DPRINTF(sc, ATH_DEBUG_XMIT,
4769				    "%s: TXDP[%u] = %p (%p) depth %d\n",
4770				    __func__, txq->axq_qnum,
4771				    (caddr_t)bf->bf_daddr, bf->bf_desc,
4772				    txq->axq_depth);
4773			} else {
4774				txq->axq_flags |= ATH_TXQ_PUTPENDING;
4775				DPRINTF(sc, ATH_DEBUG_TDMA | ATH_DEBUG_XMIT,
4776				    "%s: Q%u busy, defer enable\n", __func__,
4777				    txq->axq_qnum);
4778			}
4779		} else {
4780			*txq->axq_link = bf->bf_daddr;
4781			DPRINTF(sc, ATH_DEBUG_XMIT,
4782			    "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
4783			    txq->axq_qnum, txq->axq_link,
4784			    (caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
4785			if ((txq->axq_flags & ATH_TXQ_PUTPENDING) && !qbusy) {
4786				/*
4787				 * The q was busy when we previously tried
4788				 * to write the address of the first buffer
4789				 * in the chain.  Since it's not busy now
4790				 * handle this chore.  We are certain the
4791				 * buffer at the front is the right one since
4792				 * axq_link is NULL only when the buffer list
4793				 * is/was empty.
4794				 */
4795				ath_hal_puttxbuf(ah, txq->axq_qnum,
4796					STAILQ_FIRST(&txq->axq_q)->bf_daddr);
4797				txq->axq_flags &= ~ATH_TXQ_PUTPENDING;
4798				DPRINTF(sc, ATH_DEBUG_TDMA | ATH_DEBUG_XMIT,
4799				    "%s: Q%u restarted\n", __func__,
4800				    txq->axq_qnum);
4801			}
4802		}
4803#else
4804		ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4805		if (txq->axq_link == NULL) {
4806			ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
4807			DPRINTF(sc, ATH_DEBUG_XMIT,
4808			    "%s: TXDP[%u] = %p (%p) depth %d\n",
4809			    __func__, txq->axq_qnum,
4810			    (caddr_t)bf->bf_daddr, bf->bf_desc,
4811			    txq->axq_depth);
4812		} else {
4813			*txq->axq_link = bf->bf_daddr;
4814			DPRINTF(sc, ATH_DEBUG_XMIT,
4815			    "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
4816			    txq->axq_qnum, txq->axq_link,
4817			    (caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
4818		}
4819#endif /* ATH_SUPPORT_TDMA */
4820		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
4821		ath_hal_txstart(ah, txq->axq_qnum);
4822	} else {
4823		if (txq->axq_link != NULL) {
4824			struct ath_buf *last = ATH_TXQ_LAST(txq);
4825			struct ieee80211_frame *wh;
4826
4827			/* mark previous frame */
4828			wh = mtod(last->bf_m, struct ieee80211_frame *);
4829			wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
4830			bus_dmamap_sync(sc->sc_dmat, last->bf_dmamap,
4831			    BUS_DMASYNC_PREWRITE);
4832
4833			/* link descriptor */
4834			*txq->axq_link = bf->bf_daddr;
4835		}
4836		ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4837		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
4838	}
4839	ATH_TXQ_UNLOCK(txq);
4840}
4841
4842static int
4843ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
4844    struct mbuf *m0)
4845{
4846	struct ieee80211vap *vap = ni->ni_vap;
4847	struct ath_vap *avp = ATH_VAP(vap);
4848	struct ath_hal *ah = sc->sc_ah;
4849	struct ifnet *ifp = sc->sc_ifp;
4850	struct ieee80211com *ic = ifp->if_l2com;
4851	const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
4852	int error, iswep, ismcast, isfrag, ismrr;
4853	int keyix, hdrlen, pktlen, try0;
4854	u_int8_t rix, txrate, ctsrate;
4855	u_int8_t cix = 0xff;		/* NB: silence compiler */
4856	struct ath_desc *ds;
4857	struct ath_txq *txq;
4858	struct ieee80211_frame *wh;
4859	u_int subtype, flags, ctsduration;
4860	HAL_PKT_TYPE atype;
4861	const HAL_RATE_TABLE *rt;
4862	HAL_BOOL shortPreamble;
4863	struct ath_node *an;
4864	u_int pri;
4865
4866	wh = mtod(m0, struct ieee80211_frame *);
4867	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
4868	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
4869	isfrag = m0->m_flags & M_FRAG;
4870	hdrlen = ieee80211_anyhdrsize(wh);
4871	/*
4872	 * Packet length must not include any
4873	 * pad bytes; deduct them here.
4874	 */
4875	pktlen = m0->m_pkthdr.len - (hdrlen & 3);
4876
4877	if (iswep) {
4878		const struct ieee80211_cipher *cip;
4879		struct ieee80211_key *k;
4880
4881		/*
4882		 * Construct the 802.11 header+trailer for an encrypted
4883		 * frame. The only reason this can fail is because of an
4884		 * unknown or unsupported cipher/key type.
4885		 */
4886		k = ieee80211_crypto_encap(ni, m0);
4887		if (k == NULL) {
4888			/*
4889			 * This can happen when the key is yanked after the
4890			 * frame was queued.  Just discard the frame; the
4891			 * 802.11 layer counts failures and provides
4892			 * debugging/diagnostics.
4893			 */
4894			ath_freetx(m0);
4895			return EIO;
4896		}
4897		/*
4898		 * Adjust the packet + header lengths for the crypto
4899		 * additions and calculate the h/w key index.  When
4900		 * a s/w mic is done the frame will have had any mic
4901		 * added to it prior to entry so m0->m_pkthdr.len will
4902		 * account for it. Otherwise we need to add it to the
4903		 * packet length.
4904		 */
4905		cip = k->wk_cipher;
4906		hdrlen += cip->ic_header;
4907		pktlen += cip->ic_header + cip->ic_trailer;
4908		/* NB: frags always have any TKIP MIC done in s/w */
4909		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && !isfrag)
4910			pktlen += cip->ic_miclen;
4911		keyix = k->wk_keyix;
4912
4913		/* packet header may have moved, reset our local pointer */
4914		wh = mtod(m0, struct ieee80211_frame *);
4915	} else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
4916		/*
4917		 * Use station key cache slot, if assigned.
4918		 */
4919		keyix = ni->ni_ucastkey.wk_keyix;
4920		if (keyix == IEEE80211_KEYIX_NONE)
4921			keyix = HAL_TXKEYIX_INVALID;
4922	} else
4923		keyix = HAL_TXKEYIX_INVALID;
4924
4925	pktlen += IEEE80211_CRC_LEN;
4926
4927	/*
4928	 * Load the DMA map so any coalescing is done.  This
4929	 * also calculates the number of descriptors we need.
4930	 */
4931	error = ath_tx_dmasetup(sc, bf, m0);
4932	if (error != 0)
4933		return error;
4934	bf->bf_node = ni;			/* NB: held reference */
4935	m0 = bf->bf_m;				/* NB: may have changed */
4936	wh = mtod(m0, struct ieee80211_frame *);
4937
4938	/* setup descriptors */
4939	ds = bf->bf_desc;
4940	rt = sc->sc_currates;
4941	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
4942
4943	/*
4944	 * NB: the 802.11 layer marks whether or not we should
4945	 * use short preamble based on the current mode and
4946	 * negotiated parameters.
4947	 */
4948	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
4949	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
4950		shortPreamble = AH_TRUE;
4951		sc->sc_stats.ast_tx_shortpre++;
4952	} else {
4953		shortPreamble = AH_FALSE;
4954	}
4955
4956	an = ATH_NODE(ni);
4957	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
4958	ismrr = 0;				/* default no multi-rate retry*/
4959	pri = M_WME_GETAC(m0);			/* honor classification */
4960	/* XXX use txparams instead of fixed values */
4961	/*
4962	 * Calculate Atheros packet type from IEEE80211 packet header,
4963	 * setup for rate calculations, and select h/w transmit queue.
4964	 */
4965	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
4966	case IEEE80211_FC0_TYPE_MGT:
4967		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
4968		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
4969			atype = HAL_PKT_TYPE_BEACON;
4970		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
4971			atype = HAL_PKT_TYPE_PROBE_RESP;
4972		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
4973			atype = HAL_PKT_TYPE_ATIM;
4974		else
4975			atype = HAL_PKT_TYPE_NORMAL;	/* XXX */
4976		rix = an->an_mgmtrix;
4977		txrate = rt->info[rix].rateCode;
4978		if (shortPreamble)
4979			txrate |= rt->info[rix].shortPreamble;
4980		try0 = ATH_TXMGTTRY;
4981		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
4982		break;
4983	case IEEE80211_FC0_TYPE_CTL:
4984		atype = HAL_PKT_TYPE_PSPOLL;	/* stop setting of duration */
4985		rix = an->an_mgmtrix;
4986		txrate = rt->info[rix].rateCode;
4987		if (shortPreamble)
4988			txrate |= rt->info[rix].shortPreamble;
4989		try0 = ATH_TXMGTTRY;
4990		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
4991		break;
4992	case IEEE80211_FC0_TYPE_DATA:
4993		atype = HAL_PKT_TYPE_NORMAL;		/* default */
4994		/*
4995		 * Data frames: multicast frames go out at a fixed rate,
4996		 * EAPOL frames use the mgmt frame rate; otherwise consult
4997		 * the rate control module for the rate to use.
4998		 */
4999		if (ismcast) {
5000			rix = an->an_mcastrix;
5001			txrate = rt->info[rix].rateCode;
5002			if (shortPreamble)
5003				txrate |= rt->info[rix].shortPreamble;
5004			try0 = 1;
5005		} else if (m0->m_flags & M_EAPOL) {
5006			/* XXX? maybe always use long preamble? */
5007			rix = an->an_mgmtrix;
5008			txrate = rt->info[rix].rateCode;
5009			if (shortPreamble)
5010				txrate |= rt->info[rix].shortPreamble;
5011			try0 = ATH_TXMAXTRY;	/* XXX?too many? */
5012		} else {
5013			ath_rate_findrate(sc, an, shortPreamble, pktlen,
5014				&rix, &try0, &txrate);
5015			sc->sc_txrix = rix;		/* for LED blinking */
5016			sc->sc_lastdatarix = rix;	/* for fast frames */
5017			if (try0 != ATH_TXMAXTRY)
5018				ismrr = 1;
5019		}
5020		if (cap->cap_wmeParams[pri].wmep_noackPolicy)
5021			flags |= HAL_TXDESC_NOACK;
5022		break;
5023	default:
5024		if_printf(ifp, "bogus frame type 0x%x (%s)\n",
5025			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
5026		/* XXX statistic */
5027		ath_freetx(m0);
5028		return EIO;
5029	}
5030	txq = sc->sc_ac2q[pri];
5031
5032	/*
5033	 * When servicing one or more stations in power-save mode
5034	 * (or) if there is some mcast data waiting on the mcast
5035	 * queue (to prevent out of order delivery) multicast
5036	 * frames must be buffered until after the beacon.
5037	 */
5038	if (ismcast && (vap->iv_ps_sta || avp->av_mcastq.axq_depth))
5039		txq = &avp->av_mcastq;
5040
5041	/*
5042	 * Calculate miscellaneous flags.
5043	 */
5044	if (ismcast) {
5045		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
5046	} else if (pktlen > vap->iv_rtsthreshold &&
5047	    (ni->ni_ath_flags & IEEE80211_NODE_FF) == 0) {
5048		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
5049		cix = rt->info[rix].controlRate;
5050		sc->sc_stats.ast_tx_rts++;
5051	}
5052	if (flags & HAL_TXDESC_NOACK)		/* NB: avoid double counting */
5053		sc->sc_stats.ast_tx_noack++;
5054#ifdef ATH_SUPPORT_TDMA
5055	if (sc->sc_tdma && (flags & HAL_TXDESC_NOACK) == 0) {
5056		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: ACK required w/ TDMA\n",
5057		    __func__);
5058		/* XXX statistic */
5059		ath_freetx(m0);
5060		return EIO;
5061	}
5062#endif
5063
5064	/*
5065	 * If 802.11g protection is enabled, determine whether
5066	 * to use RTS/CTS or just CTS.  Note that this is only
5067	 * done for OFDM unicast frames.
5068	 */
5069	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
5070	    rt->info[rix].phy == IEEE80211_T_OFDM &&
5071	    (flags & HAL_TXDESC_NOACK) == 0) {
5072		/* XXX fragments must use CCK rates w/ protection */
5073		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
5074			flags |= HAL_TXDESC_RTSENA;
5075		else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
5076			flags |= HAL_TXDESC_CTSENA;
5077		if (isfrag) {
5078			/*
5079			 * For frags it would be desirable to use the
5080			 * highest CCK rate for RTS/CTS.  But stations
5081			 * farther away may detect it at a lower CCK rate
5082			 * so use the configured protection rate instead
5083			 * (for now).
5084			 */
5085			cix = rt->info[sc->sc_protrix].controlRate;
5086		} else
5087			cix = rt->info[sc->sc_protrix].controlRate;
5088		sc->sc_stats.ast_tx_protect++;
5089	}
5090
5091	/*
5092	 * Calculate duration.  This logically belongs in the 802.11
5093	 * layer but it lacks sufficient information to calculate it.
5094	 */
5095	if ((flags & HAL_TXDESC_NOACK) == 0 &&
5096	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
5097		u_int16_t dur;
5098		if (shortPreamble)
5099			dur = rt->info[rix].spAckDuration;
5100		else
5101			dur = rt->info[rix].lpAckDuration;
5102		if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG) {
5103			dur += dur;		/* additional SIFS+ACK */
5104			KASSERT(m0->m_nextpkt != NULL, ("no fragment"));
5105			/*
5106			 * Include the size of next fragment so NAV is
5107			 * updated properly.  The last fragment uses only
5108			 * the ACK duration
5109			 */
5110			dur += ath_hal_computetxtime(ah, rt,
5111					m0->m_nextpkt->m_pkthdr.len,
5112					rix, shortPreamble);
5113		}
5114		if (isfrag) {
5115			/*
5116			 * Force hardware to use computed duration for next
5117			 * fragment by disabling multi-rate retry which updates
5118			 * duration based on the multi-rate duration table.
5119			 */
5120			ismrr = 0;
5121			try0 = ATH_TXMGTTRY;	/* XXX? */
5122		}
5123		*(u_int16_t *)wh->i_dur = htole16(dur);
5124	}
5125
5126	/*
5127	 * Calculate RTS/CTS rate and duration if needed.
5128	 */
5129	ctsduration = 0;
5130	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
5131		/*
5132		 * CTS transmit rate is derived from the transmit rate
5133		 * by looking in the h/w rate table.  We must also factor
5134		 * in whether or not a short preamble is to be used.
5135		 */
5136		/* NB: cix is set above where RTS/CTS is enabled */
5137		KASSERT(cix != 0xff, ("cix not setup"));
5138		ctsrate = rt->info[cix].rateCode;
5139		/*
5140		 * Compute the transmit duration based on the frame
5141		 * size and the size of an ACK frame.  We call into the
5142		 * HAL to do the computation since it depends on the
5143		 * characteristics of the actual PHY being used.
5144		 *
5145		 * NB: CTS is assumed the same size as an ACK so we can
5146		 *     use the precalculated ACK durations.
5147		 */
5148		if (shortPreamble) {
5149			ctsrate |= rt->info[cix].shortPreamble;
5150			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
5151				ctsduration += rt->info[cix].spAckDuration;
5152			ctsduration += ath_hal_computetxtime(ah,
5153				rt, pktlen, rix, AH_TRUE);
5154			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
5155				ctsduration += rt->info[rix].spAckDuration;
5156		} else {
5157			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
5158				ctsduration += rt->info[cix].lpAckDuration;
5159			ctsduration += ath_hal_computetxtime(ah,
5160				rt, pktlen, rix, AH_FALSE);
5161			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
5162				ctsduration += rt->info[rix].lpAckDuration;
5163		}
5164		/*
5165		 * Must disable multi-rate retry when using RTS/CTS.
5166		 */
5167		ismrr = 0;
5168		try0 = ATH_TXMGTTRY;		/* XXX */
5169	} else
5170		ctsrate = 0;
5171
5172	/*
5173	 * At this point we are committed to sending the frame
5174	 * and we don't need to look at m_nextpkt; clear it in
5175	 * case this frame is part of frag chain.
5176	 */
5177	m0->m_nextpkt = NULL;
5178
5179	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
5180		ieee80211_dump_pkt(ic, mtod(m0, caddr_t), m0->m_len,
5181			sc->sc_hwmap[rix].ieeerate, -1);
5182
5183	if (bpf_peers_present(ifp->if_bpf)) {
5184		u_int64_t tsf = ath_hal_gettsf64(ah);
5185
5186		sc->sc_tx_th.wt_tsf = htole64(tsf);
5187		sc->sc_tx_th.wt_flags = sc->sc_hwmap[rix].txflags;
5188		if (iswep)
5189			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
5190		if (isfrag)
5191			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
5192		sc->sc_tx_th.wt_rate = sc->sc_hwmap[rix].ieeerate;
5193		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
5194		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
5195
5196		bpf_mtap2(ifp->if_bpf, &sc->sc_tx_th, sc->sc_tx_th_len, m0);
5197	}
5198
5199	/*
5200	 * Determine if a tx interrupt should be generated for
5201	 * this descriptor.  We take a tx interrupt to reap
5202	 * descriptors when the h/w hits an EOL condition or
5203	 * when the descriptor is specifically marked to generate
5204	 * an interrupt.  We periodically mark descriptors in this
5205	 * way to insure timely replenishing of the supply needed
5206	 * for sending frames.  Defering interrupts reduces system
5207	 * load and potentially allows more concurrent work to be
5208	 * done but if done to aggressively can cause senders to
5209	 * backup.
5210	 *
5211	 * NB: use >= to deal with sc_txintrperiod changing
5212	 *     dynamically through sysctl.
5213	 */
5214	if (flags & HAL_TXDESC_INTREQ) {
5215		txq->axq_intrcnt = 0;
5216	} else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
5217		flags |= HAL_TXDESC_INTREQ;
5218		txq->axq_intrcnt = 0;
5219	}
5220
5221	/*
5222	 * Formulate first tx descriptor with tx controls.
5223	 */
5224	/* XXX check return value? */
5225	ath_hal_setuptxdesc(ah, ds
5226		, pktlen		/* packet length */
5227		, hdrlen		/* header length */
5228		, atype			/* Atheros packet type */
5229		, ni->ni_txpower	/* txpower */
5230		, txrate, try0		/* series 0 rate/tries */
5231		, keyix			/* key cache index */
5232		, sc->sc_txantenna	/* antenna mode */
5233		, flags			/* flags */
5234		, ctsrate		/* rts/cts rate */
5235		, ctsduration		/* rts/cts duration */
5236	);
5237	bf->bf_txflags = flags;
5238	/*
5239	 * Setup the multi-rate retry state only when we're
5240	 * going to use it.  This assumes ath_hal_setuptxdesc
5241	 * initializes the descriptors (so we don't have to)
5242	 * when the hardware supports multi-rate retry and
5243	 * we don't use it.
5244	 */
5245	if (ismrr)
5246		ath_rate_setupxtxdesc(sc, an, ds, shortPreamble, rix);
5247
5248	ath_tx_handoff(sc, txq, bf);
5249	return 0;
5250}
5251
5252/*
5253 * Process completed xmit descriptors from the specified queue.
5254 */
5255static int
5256ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
5257{
5258	struct ath_hal *ah = sc->sc_ah;
5259	struct ifnet *ifp = sc->sc_ifp;
5260	struct ieee80211com *ic = ifp->if_l2com;
5261	struct ath_buf *bf, *last;
5262	struct ath_desc *ds, *ds0;
5263	struct ath_tx_status *ts;
5264	struct ieee80211_node *ni;
5265	struct ath_node *an;
5266	int sr, lr, pri, nacked;
5267	HAL_STATUS status;
5268
5269	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
5270		__func__, txq->axq_qnum,
5271		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
5272		txq->axq_link);
5273	nacked = 0;
5274	for (;;) {
5275		ATH_TXQ_LOCK(txq);
5276		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
5277		bf = STAILQ_FIRST(&txq->axq_q);
5278		if (bf == NULL) {
5279			ATH_TXQ_UNLOCK(txq);
5280			break;
5281		}
5282		ds0 = &bf->bf_desc[0];
5283		ds = &bf->bf_desc[bf->bf_nseg - 1];
5284		ts = &bf->bf_status.ds_txstat;
5285		status = ath_hal_txprocdesc(ah, ds, ts);
5286#ifdef ATH_DEBUG
5287		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
5288			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
5289			    status == HAL_OK);
5290#endif
5291		if (status == HAL_EINPROGRESS) {
5292			ATH_TXQ_UNLOCK(txq);
5293			break;
5294		}
5295		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
5296#ifdef ATH_SUPPORT_TDMA
5297		if (txq->axq_depth > 0) {
5298			/*
5299			 * More frames follow.  Mark the buffer busy
5300			 * so it's not re-used while the hardware may
5301			 * still re-read the link field in the descriptor.
5302			 */
5303			bf->bf_flags |= ATH_BUF_BUSY;
5304		} else
5305#else
5306		if (txq->axq_depth == 0)
5307#endif
5308			txq->axq_link = NULL;
5309		ATH_TXQ_UNLOCK(txq);
5310
5311		ni = bf->bf_node;
5312		if (ni != NULL) {
5313			an = ATH_NODE(ni);
5314			if (ts->ts_status == 0) {
5315				u_int8_t txant = ts->ts_antenna;
5316				sc->sc_stats.ast_ant_tx[txant]++;
5317				sc->sc_ant_tx[txant]++;
5318				if (ts->ts_rate & HAL_TXSTAT_ALTRATE)
5319					sc->sc_stats.ast_tx_altrate++;
5320				pri = M_WME_GETAC(bf->bf_m);
5321				if (pri >= WME_AC_VO)
5322					ic->ic_wme.wme_hipri_traffic++;
5323				if ((bf->bf_txflags & HAL_TXDESC_NOACK) == 0)
5324					ni->ni_inact = ni->ni_inact_reload;
5325			} else {
5326				if (ts->ts_status & HAL_TXERR_XRETRY)
5327					sc->sc_stats.ast_tx_xretries++;
5328				if (ts->ts_status & HAL_TXERR_FIFO)
5329					sc->sc_stats.ast_tx_fifoerr++;
5330				if (ts->ts_status & HAL_TXERR_FILT)
5331					sc->sc_stats.ast_tx_filtered++;
5332				if (bf->bf_m->m_flags & M_FF)
5333					sc->sc_stats.ast_ff_txerr++;
5334			}
5335			sr = ts->ts_shortretry;
5336			lr = ts->ts_longretry;
5337			sc->sc_stats.ast_tx_shortretry += sr;
5338			sc->sc_stats.ast_tx_longretry += lr;
5339			/*
5340			 * Hand the descriptor to the rate control algorithm.
5341			 */
5342			if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
5343			    (bf->bf_txflags & HAL_TXDESC_NOACK) == 0) {
5344				/*
5345				 * If frame was ack'd update statistics,
5346				 * including the last rx time used to
5347				 * workaround phantom bmiss interrupts.
5348				 */
5349				if (ts->ts_status == 0) {
5350					nacked++;
5351					sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
5352					ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
5353						ts->ts_rssi);
5354				}
5355				ath_rate_tx_complete(sc, an, bf);
5356			}
5357			/*
5358			 * Do any tx complete callback.  Note this must
5359			 * be done before releasing the node reference.
5360			 */
5361			if (bf->bf_m->m_flags & M_TXCB)
5362				ieee80211_process_callback(ni, bf->bf_m,
5363				    (bf->bf_txflags & HAL_TXDESC_NOACK) == 0 ?
5364				        ts->ts_status : HAL_TXERR_XRETRY);
5365			/*
5366			 * Reclaim reference to node.
5367			 *
5368			 * NB: the node may be reclaimed here if, for example
5369			 *     this is a DEAUTH message that was sent and the
5370			 *     node was timed out due to inactivity.
5371			 */
5372			ieee80211_free_node(ni);
5373		}
5374		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
5375		    BUS_DMASYNC_POSTWRITE);
5376		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
5377
5378		m_freem(bf->bf_m);
5379		bf->bf_m = NULL;
5380		bf->bf_node = NULL;
5381
5382		ATH_TXBUF_LOCK(sc);
5383		last = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
5384		if (last != NULL)
5385			last->bf_flags &= ~ATH_BUF_BUSY;
5386		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5387		ATH_TXBUF_UNLOCK(sc);
5388	}
5389	/*
5390	 * Flush fast-frame staging queue when traffic slows.
5391	 */
5392	if (txq->axq_depth <= 1)
5393		ath_ff_stageq_flush(sc, txq, ath_ff_always);
5394	return nacked;
5395}
5396
5397static __inline int
5398txqactive(struct ath_hal *ah, int qnum)
5399{
5400	u_int32_t txqs = 1<<qnum;
5401	ath_hal_gettxintrtxqs(ah, &txqs);
5402	return (txqs & (1<<qnum));
5403}
5404
5405/*
5406 * Deferred processing of transmit interrupt; special-cased
5407 * for a single hardware transmit queue (e.g. 5210 and 5211).
5408 */
5409static void
5410ath_tx_proc_q0(void *arg, int npending)
5411{
5412	struct ath_softc *sc = arg;
5413	struct ifnet *ifp = sc->sc_ifp;
5414
5415	if (txqactive(sc->sc_ah, 0) && ath_tx_processq(sc, &sc->sc_txq[0]))
5416		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5417	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
5418		ath_tx_processq(sc, sc->sc_cabq);
5419	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5420	ifp->if_timer = 0;
5421
5422	if (sc->sc_softled)
5423		ath_led_event(sc, sc->sc_txrix);
5424
5425	ath_start(ifp);
5426}
5427
5428/*
5429 * Deferred processing of transmit interrupt; special-cased
5430 * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
5431 */
5432static void
5433ath_tx_proc_q0123(void *arg, int npending)
5434{
5435	struct ath_softc *sc = arg;
5436	struct ifnet *ifp = sc->sc_ifp;
5437	int nacked;
5438
5439	/*
5440	 * Process each active queue.
5441	 */
5442	nacked = 0;
5443	if (txqactive(sc->sc_ah, 0))
5444		nacked += ath_tx_processq(sc, &sc->sc_txq[0]);
5445	if (txqactive(sc->sc_ah, 1))
5446		nacked += ath_tx_processq(sc, &sc->sc_txq[1]);
5447	if (txqactive(sc->sc_ah, 2))
5448		nacked += ath_tx_processq(sc, &sc->sc_txq[2]);
5449	if (txqactive(sc->sc_ah, 3))
5450		nacked += ath_tx_processq(sc, &sc->sc_txq[3]);
5451	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
5452		ath_tx_processq(sc, sc->sc_cabq);
5453	if (nacked)
5454		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5455
5456	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5457	ifp->if_timer = 0;
5458
5459	if (sc->sc_softled)
5460		ath_led_event(sc, sc->sc_txrix);
5461
5462	ath_start(ifp);
5463}
5464
5465/*
5466 * Deferred processing of transmit interrupt.
5467 */
5468static void
5469ath_tx_proc(void *arg, int npending)
5470{
5471	struct ath_softc *sc = arg;
5472	struct ifnet *ifp = sc->sc_ifp;
5473	int i, nacked;
5474
5475	/*
5476	 * Process each active queue.
5477	 */
5478	nacked = 0;
5479	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5480		if (ATH_TXQ_SETUP(sc, i) && txqactive(sc->sc_ah, i))
5481			nacked += ath_tx_processq(sc, &sc->sc_txq[i]);
5482	if (nacked)
5483		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5484
5485	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5486	ifp->if_timer = 0;
5487
5488	if (sc->sc_softled)
5489		ath_led_event(sc, sc->sc_txrix);
5490
5491	ath_start(ifp);
5492}
5493
5494static void
5495ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
5496{
5497#ifdef ATH_DEBUG
5498	struct ath_hal *ah = sc->sc_ah;
5499#endif
5500	struct ieee80211_node *ni;
5501	struct ath_buf *bf;
5502	u_int ix;
5503
5504	/*
5505	 * NB: this assumes output has been stopped and
5506	 *     we do not need to block ath_tx_proc
5507	 */
5508	ATH_TXBUF_LOCK(sc);
5509	bf = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
5510	if (bf != NULL)
5511		bf->bf_flags &= ~ATH_BUF_BUSY;
5512	ATH_TXBUF_UNLOCK(sc);
5513	for (ix = 0;; ix++) {
5514		ATH_TXQ_LOCK(txq);
5515		bf = STAILQ_FIRST(&txq->axq_q);
5516		if (bf == NULL) {
5517			txq->axq_link = NULL;
5518			ATH_TXQ_UNLOCK(txq);
5519			break;
5520		}
5521		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
5522		ATH_TXQ_UNLOCK(txq);
5523#ifdef ATH_DEBUG
5524		if (sc->sc_debug & ATH_DEBUG_RESET) {
5525			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
5526
5527			ath_printtxbuf(sc, bf, txq->axq_qnum, ix,
5528				ath_hal_txprocdesc(ah, bf->bf_desc,
5529				    &bf->bf_status.ds_txstat) == HAL_OK);
5530			ieee80211_dump_pkt(ic, mtod(bf->bf_m, caddr_t),
5531				bf->bf_m->m_len, 0, -1);
5532		}
5533#endif /* ATH_DEBUG */
5534		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
5535		ni = bf->bf_node;
5536		bf->bf_node = NULL;
5537		if (ni != NULL) {
5538			/*
5539			 * Do any callback and reclaim the node reference.
5540			 */
5541			if (bf->bf_m->m_flags & M_TXCB)
5542				ieee80211_process_callback(ni, bf->bf_m, -1);
5543			ieee80211_free_node(ni);
5544		}
5545		m_freem(bf->bf_m);
5546		bf->bf_m = NULL;
5547		bf->bf_flags &= ~ATH_BUF_BUSY;
5548
5549		ATH_TXBUF_LOCK(sc);
5550		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5551		ATH_TXBUF_UNLOCK(sc);
5552	}
5553}
5554
5555static void
5556ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
5557{
5558	struct ath_hal *ah = sc->sc_ah;
5559
5560	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5561	    __func__, txq->axq_qnum,
5562	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
5563	    txq->axq_link);
5564	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
5565}
5566
5567/*
5568 * Drain the transmit queues and reclaim resources.
5569 */
5570static void
5571ath_draintxq(struct ath_softc *sc)
5572{
5573	struct ath_hal *ah = sc->sc_ah;
5574	struct ifnet *ifp = sc->sc_ifp;
5575	int i;
5576
5577	/* XXX return value */
5578	if (!sc->sc_invalid) {
5579		/* don't touch the hardware if marked invalid */
5580		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5581		    __func__, sc->sc_bhalq,
5582		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
5583		    NULL);
5584		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
5585		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5586			if (ATH_TXQ_SETUP(sc, i))
5587				ath_tx_stopdma(sc, &sc->sc_txq[i]);
5588	}
5589	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5590		if (ATH_TXQ_SETUP(sc, i))
5591			ath_tx_draintxq(sc, &sc->sc_txq[i]);
5592#ifdef ATH_DEBUG
5593	if (sc->sc_debug & ATH_DEBUG_RESET) {
5594		struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
5595		if (bf != NULL && bf->bf_m != NULL) {
5596			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
5597				ath_hal_txprocdesc(ah, bf->bf_desc,
5598				    &bf->bf_status.ds_txstat) == HAL_OK);
5599			ieee80211_dump_pkt(ifp->if_l2com, mtod(bf->bf_m, caddr_t),
5600				bf->bf_m->m_len, 0, -1);
5601		}
5602	}
5603#endif /* ATH_DEBUG */
5604	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5605	ifp->if_timer = 0;
5606}
5607
5608/*
5609 * Disable the receive h/w in preparation for a reset.
5610 */
5611static void
5612ath_stoprecv(struct ath_softc *sc)
5613{
5614#define	PA2DESC(_sc, _pa) \
5615	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
5616		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
5617	struct ath_hal *ah = sc->sc_ah;
5618
5619	ath_hal_stoppcurecv(ah);	/* disable PCU */
5620	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
5621	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
5622	DELAY(3000);			/* 3ms is long enough for 1 frame */
5623#ifdef ATH_DEBUG
5624	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
5625		struct ath_buf *bf;
5626		u_int ix;
5627
5628		printf("%s: rx queue %p, link %p\n", __func__,
5629			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
5630		ix = 0;
5631		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
5632			struct ath_desc *ds = bf->bf_desc;
5633			struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
5634			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
5635				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
5636			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
5637				ath_printrxbuf(sc, bf, ix, status == HAL_OK);
5638			ix++;
5639		}
5640	}
5641#endif
5642	if (sc->sc_rxpending != NULL) {
5643		m_freem(sc->sc_rxpending);
5644		sc->sc_rxpending = NULL;
5645	}
5646	sc->sc_rxlink = NULL;		/* just in case */
5647#undef PA2DESC
5648}
5649
5650/*
5651 * Enable the receive h/w following a reset.
5652 */
5653static int
5654ath_startrecv(struct ath_softc *sc)
5655{
5656	struct ath_hal *ah = sc->sc_ah;
5657	struct ath_buf *bf;
5658
5659	sc->sc_rxlink = NULL;
5660	sc->sc_rxpending = NULL;
5661	STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
5662		int error = ath_rxbuf_init(sc, bf);
5663		if (error != 0) {
5664			DPRINTF(sc, ATH_DEBUG_RECV,
5665				"%s: ath_rxbuf_init failed %d\n",
5666				__func__, error);
5667			return error;
5668		}
5669	}
5670
5671	bf = STAILQ_FIRST(&sc->sc_rxbuf);
5672	ath_hal_putrxbuf(ah, bf->bf_daddr);
5673	ath_hal_rxena(ah);		/* enable recv descriptors */
5674	ath_mode_init(sc);		/* set filters, etc. */
5675	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
5676	return 0;
5677}
5678
5679/*
5680 * Update internal state after a channel change.
5681 */
5682static void
5683ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
5684{
5685	enum ieee80211_phymode mode;
5686
5687	/*
5688	 * Change channels and update the h/w rate map
5689	 * if we're switching; e.g. 11a to 11b/g.
5690	 */
5691	if (IEEE80211_IS_CHAN_HALF(chan))
5692		mode = IEEE80211_MODE_HALF;
5693	else if (IEEE80211_IS_CHAN_QUARTER(chan))
5694		mode = IEEE80211_MODE_QUARTER;
5695	else
5696		mode = ieee80211_chan2mode(chan);
5697	if (mode != sc->sc_curmode)
5698		ath_setcurmode(sc, mode);
5699
5700	sc->sc_rx_th.wr_chan_flags = htole32(chan->ic_flags);
5701	sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags;
5702	sc->sc_rx_th.wr_chan_freq = htole16(chan->ic_freq);
5703	sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq;
5704	sc->sc_rx_th.wr_chan_ieee = chan->ic_ieee;
5705	sc->sc_tx_th.wt_chan_ieee = sc->sc_rx_th.wr_chan_ieee;
5706	sc->sc_rx_th.wr_chan_maxpow = chan->ic_maxregpower;
5707	sc->sc_tx_th.wt_chan_maxpow = sc->sc_rx_th.wr_chan_maxpow;
5708}
5709
5710/*
5711 * Set/change channels.  If the channel is really being changed,
5712 * it's done by reseting the chip.  To accomplish this we must
5713 * first cleanup any pending DMA, then restart stuff after a la
5714 * ath_init.
5715 */
5716static int
5717ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
5718{
5719	struct ifnet *ifp = sc->sc_ifp;
5720	struct ieee80211com *ic = ifp->if_l2com;
5721	struct ath_hal *ah = sc->sc_ah;
5722	HAL_CHANNEL hchan;
5723
5724	/*
5725	 * Convert to a HAL channel description with
5726	 * the flags constrained to reflect the current
5727	 * operating mode.
5728	 */
5729	ath_mapchan(ic, &hchan, chan);
5730
5731	DPRINTF(sc, ATH_DEBUG_RESET,
5732	    "%s: %u (%u MHz, hal flags 0x%x) -> %u (%u MHz, hal flags 0x%x)\n",
5733	    __func__,
5734	    ath_hal_mhz2ieee(ah, sc->sc_curchan.channel,
5735		sc->sc_curchan.channelFlags),
5736	    	sc->sc_curchan.channel, sc->sc_curchan.channelFlags,
5737	    ath_hal_mhz2ieee(ah, hchan.channel, hchan.channelFlags),
5738	        hchan.channel, hchan.channelFlags);
5739	if (hchan.channel != sc->sc_curchan.channel ||
5740	    hchan.channelFlags != sc->sc_curchan.channelFlags) {
5741		HAL_STATUS status;
5742
5743		/*
5744		 * To switch channels clear any pending DMA operations;
5745		 * wait long enough for the RX fifo to drain, reset the
5746		 * hardware at the new frequency, and then re-enable
5747		 * the relevant bits of the h/w.
5748		 */
5749		ath_hal_intrset(ah, 0);		/* disable interrupts */
5750		ath_draintxq(sc);		/* clear pending tx frames */
5751		ath_stoprecv(sc);		/* turn off frame recv */
5752		if (!ath_hal_reset(ah, sc->sc_opmode, &hchan, AH_TRUE, &status)) {
5753			if_printf(ifp, "%s: unable to reset "
5754			    "channel %u (%u Mhz, flags 0x%x hal flags 0x%x), "
5755			    "hal status %u\n", __func__,
5756			    ieee80211_chan2ieee(ic, chan), chan->ic_freq,
5757			    chan->ic_flags, hchan.channelFlags, status);
5758			return EIO;
5759		}
5760		sc->sc_curchan = hchan;
5761		sc->sc_diversity = ath_hal_getdiversity(ah);
5762
5763		/*
5764		 * Re-enable rx framework.
5765		 */
5766		if (ath_startrecv(sc) != 0) {
5767			if_printf(ifp, "%s: unable to restart recv logic\n",
5768			    __func__);
5769			return EIO;
5770		}
5771
5772		/*
5773		 * Change channels and update the h/w rate map
5774		 * if we're switching; e.g. 11a to 11b/g.
5775		 */
5776		ath_chan_change(sc, chan);
5777
5778		/*
5779		 * Re-enable interrupts.
5780		 */
5781		ath_hal_intrset(ah, sc->sc_imask);
5782	}
5783	return 0;
5784}
5785
5786/*
5787 * Periodically recalibrate the PHY to account
5788 * for temperature/environment changes.
5789 */
5790static void
5791ath_calibrate(void *arg)
5792{
5793	struct ath_softc *sc = arg;
5794	struct ath_hal *ah = sc->sc_ah;
5795	struct ifnet *ifp = sc->sc_ifp;
5796	HAL_BOOL longCal, isCalDone;
5797	int nextcal;
5798
5799	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
5800	if (longCal) {
5801		sc->sc_stats.ast_per_cal++;
5802		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
5803			/*
5804			 * Rfgain is out of bounds, reset the chip
5805			 * to load new gain values.
5806			 */
5807			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5808				"%s: rfgain change\n", __func__);
5809			sc->sc_stats.ast_per_rfgain++;
5810			ath_reset(ifp);
5811		}
5812		/*
5813		 * If this long cal is after an idle period, then
5814		 * reset the data collection state so we start fresh.
5815		 */
5816		if (sc->sc_resetcal) {
5817			(void) ath_hal_calreset(ah, &sc->sc_curchan);
5818			sc->sc_lastcalreset = ticks;
5819			sc->sc_resetcal = 0;
5820		}
5821	}
5822	if (ath_hal_calibrateN(ah, &sc->sc_curchan, longCal, &isCalDone)) {
5823		if (longCal) {
5824			/*
5825			 * Calibrate noise floor data again in case of change.
5826			 */
5827			ath_hal_process_noisefloor(ah);
5828		}
5829	} else {
5830		DPRINTF(sc, ATH_DEBUG_ANY,
5831			"%s: calibration of channel %u failed\n",
5832			__func__, sc->sc_curchan.channel);
5833		sc->sc_stats.ast_per_calfail++;
5834	}
5835	if (!isCalDone) {
5836		/*
5837		 * Use a shorter interval to potentially collect multiple
5838		 * data samples required to complete calibration.  Once
5839		 * we're told the work is done we drop back to a longer
5840		 * interval between requests.  We're more aggressive doing
5841		 * work when operating as an AP to improve operation right
5842		 * after startup.
5843		 */
5844		nextcal = (1000*ath_shortcalinterval)/hz;
5845		if (sc->sc_opmode != HAL_M_HOSTAP)
5846			nextcal *= 10;
5847	} else {
5848		nextcal = ath_longcalinterval*hz;
5849		sc->sc_lastlongcal = ticks;
5850		if (sc->sc_lastcalreset == 0)
5851			sc->sc_lastcalreset = sc->sc_lastlongcal;
5852		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
5853			sc->sc_resetcal = 1;	/* setup reset next trip */
5854	}
5855
5856	if (nextcal != 0) {
5857		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
5858		    __func__, nextcal, isCalDone ? "" : "!");
5859		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
5860	} else {
5861		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
5862		    __func__);
5863		/* NB: don't rearm timer */
5864	}
5865}
5866
5867static void
5868ath_scan_start(struct ieee80211com *ic)
5869{
5870	struct ifnet *ifp = ic->ic_ifp;
5871	struct ath_softc *sc = ifp->if_softc;
5872	struct ath_hal *ah = sc->sc_ah;
5873	u_int32_t rfilt;
5874
5875	/* XXX calibration timer? */
5876
5877	sc->sc_scanning = 1;
5878	sc->sc_syncbeacon = 0;
5879	rfilt = ath_calcrxfilter(sc);
5880	ath_hal_setrxfilter(ah, rfilt);
5881	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
5882
5883	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
5884		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
5885}
5886
5887static void
5888ath_scan_end(struct ieee80211com *ic)
5889{
5890	struct ifnet *ifp = ic->ic_ifp;
5891	struct ath_softc *sc = ifp->if_softc;
5892	struct ath_hal *ah = sc->sc_ah;
5893	u_int32_t rfilt;
5894
5895	sc->sc_scanning = 0;
5896	rfilt = ath_calcrxfilter(sc);
5897	ath_hal_setrxfilter(ah, rfilt);
5898	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5899
5900	ath_hal_process_noisefloor(ah);
5901
5902	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5903		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
5904		 sc->sc_curaid);
5905}
5906
5907static void
5908ath_set_channel(struct ieee80211com *ic)
5909{
5910	struct ifnet *ifp = ic->ic_ifp;
5911	struct ath_softc *sc = ifp->if_softc;
5912
5913	(void) ath_chan_set(sc, ic->ic_curchan);
5914	/*
5915	 * If we are returning to our bss channel then mark state
5916	 * so the next recv'd beacon's tsf will be used to sync the
5917	 * beacon timers.  Note that since we only hear beacons in
5918	 * sta/ibss mode this has no effect in other operating modes.
5919	 */
5920	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
5921		sc->sc_syncbeacon = 1;
5922}
5923
5924/*
5925 * Walk the vap list and check if there any vap's in RUN state.
5926 */
5927static int
5928ath_isanyrunningvaps(struct ieee80211vap *this)
5929{
5930	struct ieee80211com *ic = this->iv_ic;
5931	struct ieee80211vap *vap;
5932
5933	IEEE80211_LOCK_ASSERT(ic);
5934
5935	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
5936		if (vap != this && vap->iv_state == IEEE80211_S_RUN)
5937			return 1;
5938	}
5939	return 0;
5940}
5941
5942static int
5943ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
5944{
5945	struct ieee80211com *ic = vap->iv_ic;
5946	struct ath_softc *sc = ic->ic_ifp->if_softc;
5947	struct ath_vap *avp = ATH_VAP(vap);
5948	struct ath_hal *ah = sc->sc_ah;
5949	struct ieee80211_node *ni = NULL;
5950	int i, error, stamode;
5951	u_int32_t rfilt;
5952	static const HAL_LED_STATE leds[] = {
5953	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
5954	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
5955	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
5956	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
5957	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
5958	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
5959	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
5960	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
5961	};
5962
5963	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
5964		ieee80211_state_name[vap->iv_state],
5965		ieee80211_state_name[nstate]);
5966
5967	callout_stop(&sc->sc_cal_ch);
5968	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
5969
5970	if (nstate == IEEE80211_S_SCAN) {
5971		/*
5972		 * Scanning: turn off beacon miss and don't beacon.
5973		 * Mark beacon state so when we reach RUN state we'll
5974		 * [re]setup beacons.  Unblock the task q thread so
5975		 * deferred interrupt processing is done.
5976		 */
5977		ath_hal_intrset(ah,
5978		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
5979		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5980		sc->sc_beacons = 0;
5981		taskqueue_unblock(sc->sc_tq);
5982	}
5983
5984	ni = vap->iv_bss;
5985	rfilt = ath_calcrxfilter(sc);
5986	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
5987		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
5988		   vap->iv_opmode == IEEE80211_M_IBSS);
5989	if (stamode && nstate == IEEE80211_S_RUN) {
5990		sc->sc_curaid = ni->ni_associd;
5991		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
5992		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5993	}
5994	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5995	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
5996	ath_hal_setrxfilter(ah, rfilt);
5997
5998	/* XXX is this to restore keycache on resume? */
5999	if (vap->iv_opmode != IEEE80211_M_STA &&
6000	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
6001		for (i = 0; i < IEEE80211_WEP_NKID; i++)
6002			if (ath_hal_keyisvalid(ah, i))
6003				ath_hal_keysetmac(ah, i, ni->ni_bssid);
6004	}
6005
6006	/*
6007	 * Invoke the parent method to do net80211 work.
6008	 */
6009	error = avp->av_newstate(vap, nstate, arg);
6010	if (error != 0)
6011		goto bad;
6012
6013	if (nstate == IEEE80211_S_RUN) {
6014		/* NB: collect bss node again, it may have changed */
6015		ni = vap->iv_bss;
6016
6017		DPRINTF(sc, ATH_DEBUG_STATE,
6018		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
6019		    "capinfo 0x%04x chan %d\n", __func__,
6020		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
6021		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
6022
6023		switch (vap->iv_opmode) {
6024#ifdef ATH_SUPPORT_TDMA
6025		case IEEE80211_M_AHDEMO:
6026			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
6027				break;
6028			/* fall thru... */
6029#endif
6030		case IEEE80211_M_HOSTAP:
6031		case IEEE80211_M_IBSS:
6032			/*
6033			 * Allocate and setup the beacon frame.
6034			 *
6035			 * Stop any previous beacon DMA.  This may be
6036			 * necessary, for example, when an ibss merge
6037			 * causes reconfiguration; there will be a state
6038			 * transition from RUN->RUN that means we may
6039			 * be called with beacon transmission active.
6040			 */
6041			ath_hal_stoptxdma(ah, sc->sc_bhalq);
6042
6043			error = ath_beacon_alloc(sc, ni);
6044			if (error != 0)
6045				goto bad;
6046			/*
6047			 * If joining an adhoc network defer beacon timer
6048			 * configuration to the next beacon frame so we
6049			 * have a current TSF to use.  Otherwise we're
6050			 * starting an ibss/bss so there's no need to delay;
6051			 * if this is the first vap moving to RUN state, then
6052			 * beacon state needs to be [re]configured.
6053			 */
6054			if (vap->iv_opmode == IEEE80211_M_IBSS &&
6055			    ni->ni_tstamp.tsf != 0) {
6056				sc->sc_syncbeacon = 1;
6057			} else if (!sc->sc_beacons) {
6058#ifdef ATH_SUPPORT_TDMA
6059				if (vap->iv_caps & IEEE80211_C_TDMA)
6060					ath_tdma_config(sc, vap);
6061				else
6062#endif
6063					ath_beacon_config(sc, vap);
6064				sc->sc_beacons = 1;
6065			}
6066			break;
6067		case IEEE80211_M_STA:
6068			/*
6069			 * Defer beacon timer configuration to the next
6070			 * beacon frame so we have a current TSF to use
6071			 * (any TSF collected when scanning is likely old).
6072			 */
6073			sc->sc_syncbeacon = 1;
6074			break;
6075		case IEEE80211_M_MONITOR:
6076			/*
6077			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
6078			 * transitions so we must re-enable interrupts here to
6079			 * handle the case of a single monitor mode vap.
6080			 */
6081			ath_hal_intrset(ah, sc->sc_imask);
6082			break;
6083		case IEEE80211_M_WDS:
6084			break;
6085		default:
6086			break;
6087		}
6088		/*
6089		 * Let the hal process statistics collected during a
6090		 * scan so it can provide calibrated noise floor data.
6091		 */
6092		ath_hal_process_noisefloor(ah);
6093		/*
6094		 * Reset rssi stats; maybe not the best place...
6095		 */
6096		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
6097		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
6098		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
6099		/*
6100		 * Finally, start any timers and the task q thread
6101		 * (in case we didn't go through SCAN state).
6102		 */
6103		if (ath_longcalinterval != 0) {
6104			/* start periodic recalibration timer */
6105			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
6106		} else {
6107			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
6108			    "%s: calibration disabled\n", __func__);
6109		}
6110		taskqueue_unblock(sc->sc_tq);
6111	} else if (nstate == IEEE80211_S_INIT) {
6112		/*
6113		 * If there are no vaps left in RUN state then
6114		 * shutdown host/driver operation:
6115		 * o disable interrupts
6116		 * o disable the task queue thread
6117		 * o mark beacon processing as stopped
6118		 */
6119		if (!ath_isanyrunningvaps(vap)) {
6120			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
6121			/* disable interrupts  */
6122			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
6123			taskqueue_block(sc->sc_tq);
6124			sc->sc_beacons = 0;
6125		}
6126#ifdef ATH_SUPPORT_TDMA
6127		ath_hal_setcca(ah, AH_TRUE);
6128#endif
6129	}
6130bad:
6131	return error;
6132}
6133
6134/*
6135 * Allocate a key cache slot to the station so we can
6136 * setup a mapping from key index to node. The key cache
6137 * slot is needed for managing antenna state and for
6138 * compression when stations do not use crypto.  We do
6139 * it uniliaterally here; if crypto is employed this slot
6140 * will be reassigned.
6141 */
6142static void
6143ath_setup_stationkey(struct ieee80211_node *ni)
6144{
6145	struct ieee80211vap *vap = ni->ni_vap;
6146	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
6147	ieee80211_keyix keyix, rxkeyix;
6148
6149	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
6150		/*
6151		 * Key cache is full; we'll fall back to doing
6152		 * the more expensive lookup in software.  Note
6153		 * this also means no h/w compression.
6154		 */
6155		/* XXX msg+statistic */
6156	} else {
6157		/* XXX locking? */
6158		ni->ni_ucastkey.wk_keyix = keyix;
6159		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
6160		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
6161		/* NB: this will create a pass-thru key entry */
6162		ath_keyset(sc, &ni->ni_ucastkey, vap->iv_bss);
6163	}
6164}
6165
6166/*
6167 * Setup driver-specific state for a newly associated node.
6168 * Note that we're called also on a re-associate, the isnew
6169 * param tells us if this is the first time or not.
6170 */
6171static void
6172ath_newassoc(struct ieee80211_node *ni, int isnew)
6173{
6174	struct ath_node *an = ATH_NODE(ni);
6175	struct ieee80211vap *vap = ni->ni_vap;
6176	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
6177	const struct ieee80211_txparam *tp = ni->ni_txparms;
6178
6179	an->an_mcastrix = ath_tx_findrix(sc->sc_currates, tp->mcastrate);
6180	an->an_mgmtrix = ath_tx_findrix(sc->sc_currates, tp->mgmtrate);
6181
6182	ath_rate_newassoc(sc, an, isnew);
6183	if (isnew &&
6184	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
6185	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
6186		ath_setup_stationkey(ni);
6187}
6188
6189static int
6190getchannels(struct ath_softc *sc, int *nchans, struct ieee80211_channel chans[],
6191	int cc, int ecm, int outdoor)
6192{
6193	struct ath_hal *ah = sc->sc_ah;
6194	HAL_CHANNEL *halchans;
6195	int i, nhalchans, error;
6196
6197	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: cc %u outdoor %u ecm %u\n",
6198	    __func__, cc, outdoor, ecm);
6199
6200	halchans = malloc(IEEE80211_CHAN_MAX * sizeof(HAL_CHANNEL),
6201			M_TEMP, M_NOWAIT | M_ZERO);
6202	if (halchans == NULL) {
6203		device_printf(sc->sc_dev,
6204		    "%s: unable to allocate channel table\n", __func__);
6205		return ENOMEM;
6206	}
6207	error = 0;
6208	if (!ath_hal_init_channels(ah, halchans, IEEE80211_CHAN_MAX, &nhalchans,
6209	    NULL, 0, NULL, cc, HAL_MODE_ALL, outdoor, ecm)) {
6210		u_int32_t rd;
6211		(void) ath_hal_getregdomain(ah, &rd);
6212		device_printf(sc->sc_dev, "ath_hal_init_channels failed, "
6213		    "rd %d cc %u outdoor %u ecm %u\n", rd, cc, outdoor, ecm);
6214		error = EINVAL;
6215		goto done;
6216	}
6217	if (nchans == NULL)		/* no table requested */
6218		goto done;
6219
6220	/*
6221	 * Convert HAL channels to ieee80211 ones.
6222	 */
6223	for (i = 0; i < nhalchans; i++) {
6224		HAL_CHANNEL *c = &halchans[i];
6225		struct ieee80211_channel *ichan = &chans[i];
6226
6227		ichan->ic_ieee = ath_hal_mhz2ieee(ah, c->channel,
6228					c->channelFlags);
6229		if (bootverbose)
6230			device_printf(sc->sc_dev, "hal channel %u/%x -> %u "
6231			    "maxpow %d minpow %d maxreg %d\n",
6232			    c->channel, c->channelFlags, ichan->ic_ieee,
6233			    c->maxTxPower, c->minTxPower, c->maxRegTxPower);
6234		ichan->ic_freq = c->channel;
6235
6236		if ((c->channelFlags & CHANNEL_PUREG) == CHANNEL_PUREG) {
6237			/*
6238			 * Except for AR5211, HAL's PUREG means mixed
6239			 * DSSS and OFDM.
6240			 */
6241			ichan->ic_flags = c->channelFlags &~ CHANNEL_PUREG;
6242			ichan->ic_flags |= IEEE80211_CHAN_G;
6243		} else {
6244			ichan->ic_flags = c->channelFlags;
6245		}
6246
6247		if (ath_hal_isgsmsku(ah)) {
6248			/*
6249			 * Remap to true frequencies: Ubiquiti XR9 cards use a
6250			 * frequency mapping different from their SR9 cards.
6251			 * We define special country codes to deal with this.
6252			 */
6253			if (cc == CTRY_XR9)
6254				ichan->ic_freq = ichan->ic_freq - 1520;
6255			else if (cc == CTRY_GZ901)
6256				ichan->ic_freq = ichan->ic_freq - 1544;
6257			else
6258				ichan->ic_freq = 3344 - ichan->ic_freq;
6259			ichan->ic_flags |= IEEE80211_CHAN_GSM;
6260			ichan->ic_ieee = ieee80211_mhz2ieee(ichan->ic_freq,
6261						    ichan->ic_flags);
6262		}
6263		ichan->ic_maxregpower = c->maxRegTxPower;	/* dBm */
6264		/* XXX: old hal's don't provide maxTxPower for some parts */
6265		ichan->ic_maxpower = (c->maxTxPower != 0) ?
6266		    c->maxTxPower : 2*c->maxRegTxPower;		/* 1/2 dBm */
6267		ichan->ic_minpower = c->minTxPower;		/* 1/2 dBm */
6268	}
6269	*nchans = nhalchans;
6270done:
6271	free(halchans, M_TEMP);
6272	return error;
6273}
6274
6275/* XXX hard to include ieee80211_regdomain.h right now */
6276#define	SKU_DEBUG	0x1ff
6277
6278static void
6279ath_maprd(const struct ieee80211_regdomain *rd,
6280	u_int32_t *ath_rd, u_int32_t *ath_cc)
6281{
6282	/* map SKU's to Atheros sku's */
6283	switch (rd->regdomain) {
6284	case SKU_DEBUG:
6285		if (rd->country == 0) {
6286			*ath_rd = 0;
6287			*ath_cc = CTRY_DEBUG;
6288			return;
6289		}
6290		break;
6291	}
6292	*ath_rd = rd->regdomain;
6293	*ath_cc = rd->country;
6294}
6295
6296static int
6297ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *rd,
6298	int nchans, struct ieee80211_channel chans[])
6299{
6300	struct ath_softc *sc = ic->ic_ifp->if_softc;
6301	struct ath_hal *ah = sc->sc_ah;
6302	u_int32_t ord, regdomain, cc;
6303	int error;
6304
6305	(void) ath_hal_getregdomain(ah, &ord);
6306	ath_maprd(rd, &regdomain, &cc);
6307	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
6308	    "%s: rd %u cc %u location %c ecm %u (mapped rd %u cc %u)\n",
6309	    __func__, rd->regdomain, rd->country, rd->location, rd->ecm,
6310	    regdomain, cc);
6311	ath_hal_setregdomain(ah, regdomain);
6312
6313	error = getchannels(sc, &nchans, chans, cc,
6314	     rd->ecm ? AH_TRUE : AH_FALSE,
6315	     rd->location != 'I' ? AH_TRUE : AH_FALSE);
6316	if (error != 0) {
6317		/*
6318		 * Restore previous state.
6319		 */
6320		ath_hal_setregdomain(ah, ord);
6321		(void) getchannels(sc, NULL, NULL, ic->ic_regdomain.country,
6322		     ic->ic_regdomain.ecm ? AH_TRUE : AH_FALSE,
6323		     ic->ic_regdomain.location != 'I' ? AH_TRUE : AH_FALSE);
6324		return error;
6325	}
6326	return 0;
6327}
6328
6329static void
6330ath_getradiocaps(struct ieee80211com *ic,
6331	int *nchans, struct ieee80211_channel chans[])
6332{
6333	struct ath_softc *sc = ic->ic_ifp->if_softc;
6334	struct ath_hal *ah = sc->sc_ah;
6335	u_int32_t ord;
6336
6337	(void) ath_hal_getregdomain(ah, &ord);
6338
6339	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d, ord %u\n",
6340	    __func__, 0, CTRY_DEBUG, ord);
6341
6342	ath_hal_setregdomain(ah, 0);
6343	/* XXX not quite right but close enough for now */
6344	getchannels(sc, nchans, chans, CTRY_DEBUG, AH_TRUE, AH_FALSE);
6345
6346	/* NB: restore previous state */
6347	ath_hal_setregdomain(ah, ord);
6348	(void) getchannels(sc, NULL, NULL, ic->ic_regdomain.country,
6349	     ic->ic_regdomain.ecm ? AH_TRUE : AH_FALSE,
6350	     ic->ic_regdomain.location != 'I' ? AH_TRUE : AH_FALSE);
6351}
6352
6353static void
6354ath_mapsku(u_int32_t ath_rd, u_int32_t ath_cc, struct ieee80211_regdomain *rd)
6355{
6356	rd->isocc[0] = ' ';	/* XXX don't know */
6357	rd->isocc[1] = ' ';
6358
6359	/* map Atheros sku's to SKU's */
6360	switch (ath_rd) {
6361	case 0:
6362		if (ath_cc == CTRY_DEBUG) {
6363			rd->regdomain = SKU_DEBUG;
6364			rd->country = 0;
6365			return;
6366		}
6367		break;
6368	}
6369	/* XXX net80211 types too small */
6370	rd->regdomain = (uint16_t) ath_rd;
6371	rd->country = (uint16_t) ath_cc;
6372}
6373
6374static int
6375ath_getchannels(struct ath_softc *sc)
6376{
6377	struct ifnet *ifp = sc->sc_ifp;
6378	struct ieee80211com *ic = ifp->if_l2com;
6379	struct ath_hal *ah = sc->sc_ah;
6380	int error;
6381
6382	/*
6383	 * Convert HAL channels to ieee80211 ones.
6384	 */
6385	error = getchannels(sc, &ic->ic_nchans, ic->ic_channels,
6386	    CTRY_DEFAULT, AH_TRUE, AH_FALSE);
6387	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
6388	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
6389	if (error) {
6390		if_printf(ifp, "%s: unable to collect channel list from hal, "
6391		    "error %d\n", __func__, error);
6392		if (error == EINVAL) {
6393			if_printf(ifp, "%s: regdomain likely %u country code %u\n",
6394			    __func__, sc->sc_eerd, sc->sc_eecc);
6395		}
6396		return error;
6397	}
6398	ic->ic_regdomain.ecm = 1;
6399	ic->ic_regdomain.location = 'I';
6400	ath_mapsku(sc->sc_eerd, sc->sc_eecc, &ic->ic_regdomain);
6401
6402	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
6403	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c ecm %u\n",
6404	    __func__, sc->sc_eerd, sc->sc_eecc,
6405	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
6406	    ic->ic_regdomain.location, ic->ic_regdomain.ecm);
6407	return 0;
6408}
6409
6410static void
6411ath_led_done(void *arg)
6412{
6413	struct ath_softc *sc = arg;
6414
6415	sc->sc_blinking = 0;
6416}
6417
6418/*
6419 * Turn the LED off: flip the pin and then set a timer so no
6420 * update will happen for the specified duration.
6421 */
6422static void
6423ath_led_off(void *arg)
6424{
6425	struct ath_softc *sc = arg;
6426
6427	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
6428	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
6429}
6430
6431/*
6432 * Blink the LED according to the specified on/off times.
6433 */
6434static void
6435ath_led_blink(struct ath_softc *sc, int on, int off)
6436{
6437	DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
6438	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
6439	sc->sc_blinking = 1;
6440	sc->sc_ledoff = off;
6441	callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
6442}
6443
6444static void
6445ath_led_event(struct ath_softc *sc, int rix)
6446{
6447	sc->sc_ledevent = ticks;	/* time of last event */
6448	if (sc->sc_blinking)		/* don't interrupt active blink */
6449		return;
6450	ath_led_blink(sc, sc->sc_hwmap[rix].ledon, sc->sc_hwmap[rix].ledoff);
6451}
6452
6453static int
6454ath_rate_setup(struct ath_softc *sc, u_int mode)
6455{
6456	struct ath_hal *ah = sc->sc_ah;
6457	const HAL_RATE_TABLE *rt;
6458
6459	switch (mode) {
6460	case IEEE80211_MODE_11A:
6461		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
6462		break;
6463	case IEEE80211_MODE_HALF:
6464		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
6465		break;
6466	case IEEE80211_MODE_QUARTER:
6467		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
6468		break;
6469	case IEEE80211_MODE_11B:
6470		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
6471		break;
6472	case IEEE80211_MODE_11G:
6473		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
6474		break;
6475	case IEEE80211_MODE_TURBO_A:
6476		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
6477#if HAL_ABI_VERSION < 0x07013100
6478		if (rt == NULL)		/* XXX bandaid for old hal's */
6479			rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
6480#endif
6481		break;
6482	case IEEE80211_MODE_TURBO_G:
6483		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
6484		break;
6485	case IEEE80211_MODE_STURBO_A:
6486		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
6487		break;
6488	case IEEE80211_MODE_11NA:
6489		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
6490		break;
6491	case IEEE80211_MODE_11NG:
6492		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
6493		break;
6494	default:
6495		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
6496			__func__, mode);
6497		return 0;
6498	}
6499	sc->sc_rates[mode] = rt;
6500	return (rt != NULL);
6501}
6502
6503static void
6504ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
6505{
6506#define	N(a)	(sizeof(a)/sizeof(a[0]))
6507	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
6508	static const struct {
6509		u_int		rate;		/* tx/rx 802.11 rate */
6510		u_int16_t	timeOn;		/* LED on time (ms) */
6511		u_int16_t	timeOff;	/* LED off time (ms) */
6512	} blinkrates[] = {
6513		{ 108,  40,  10 },
6514		{  96,  44,  11 },
6515		{  72,  50,  13 },
6516		{  48,  57,  14 },
6517		{  36,  67,  16 },
6518		{  24,  80,  20 },
6519		{  22, 100,  25 },
6520		{  18, 133,  34 },
6521		{  12, 160,  40 },
6522		{  10, 200,  50 },
6523		{   6, 240,  58 },
6524		{   4, 267,  66 },
6525		{   2, 400, 100 },
6526		{   0, 500, 130 },
6527		/* XXX half/quarter rates */
6528	};
6529	const HAL_RATE_TABLE *rt;
6530	int i, j;
6531
6532	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
6533	rt = sc->sc_rates[mode];
6534	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
6535	for (i = 0; i < rt->rateCount; i++) {
6536		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6537		if (rt->info[i].phy != IEEE80211_T_HT)
6538			sc->sc_rixmap[ieeerate] = i;
6539		else
6540			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
6541	}
6542	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
6543	for (i = 0; i < N(sc->sc_hwmap); i++) {
6544		if (i >= rt->rateCount) {
6545			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
6546			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
6547			continue;
6548		}
6549		sc->sc_hwmap[i].ieeerate =
6550			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6551		if (rt->info[i].phy == IEEE80211_T_HT)
6552			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
6553		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
6554		if (rt->info[i].shortPreamble ||
6555		    rt->info[i].phy == IEEE80211_T_OFDM)
6556			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
6557		/* NB: receive frames include FCS */
6558		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags |
6559			IEEE80211_RADIOTAP_F_FCS;
6560		/* setup blink rate table to avoid per-packet lookup */
6561		for (j = 0; j < N(blinkrates)-1; j++)
6562			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
6563				break;
6564		/* NB: this uses the last entry if the rate isn't found */
6565		/* XXX beware of overlow */
6566		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
6567		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
6568	}
6569	sc->sc_currates = rt;
6570	sc->sc_curmode = mode;
6571	/*
6572	 * All protection frames are transmited at 2Mb/s for
6573	 * 11g, otherwise at 1Mb/s.
6574	 */
6575	if (mode == IEEE80211_MODE_11G)
6576		sc->sc_protrix = ath_tx_findrix(rt, 2*2);
6577	else
6578		sc->sc_protrix = ath_tx_findrix(rt, 2*1);
6579	/* NB: caller is responsible for reseting rate control state */
6580#undef N
6581}
6582
6583#ifdef ATH_DEBUG
6584static void
6585ath_printrxbuf(struct ath_softc *sc, const struct ath_buf *bf,
6586	u_int ix, int done)
6587{
6588	const struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
6589	struct ath_hal *ah = sc->sc_ah;
6590	const struct ath_desc *ds;
6591	int i;
6592
6593	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
6594		printf("R[%2u] (DS.V:%p DS.P:%p) L:%08x D:%08x%s\n"
6595		       "      %08x %08x %08x %08x\n",
6596		    ix, ds, (const struct ath_desc *)bf->bf_daddr + i,
6597		    ds->ds_link, ds->ds_data,
6598		    !done ? "" : (rs->rs_status == 0) ? " *" : " !",
6599		    ds->ds_ctl0, ds->ds_ctl1,
6600		    ds->ds_hw[0], ds->ds_hw[1]);
6601		if (ah->ah_magic == 0x20065416) {
6602			printf("        %08x %08x %08x %08x %08x %08x %08x\n",
6603			    ds->ds_hw[2], ds->ds_hw[3], ds->ds_hw[4],
6604			    ds->ds_hw[5], ds->ds_hw[6], ds->ds_hw[7],
6605			    ds->ds_hw[8]);
6606		}
6607	}
6608}
6609
6610static void
6611ath_printtxbuf(struct ath_softc *sc, const struct ath_buf *bf,
6612	u_int qnum, u_int ix, int done)
6613{
6614	const struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
6615	struct ath_hal *ah = sc->sc_ah;
6616	const struct ath_desc *ds;
6617	int i;
6618
6619	printf("Q%u[%3u]", qnum, ix);
6620	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
6621		printf(" (DS.V:%p DS.P:%p) L:%08x D:%08x F:04%x%s\n"
6622		       "        %08x %08x %08x %08x %08x %08x\n",
6623		    ds, (const struct ath_desc *)bf->bf_daddr + i,
6624		    ds->ds_link, ds->ds_data, bf->bf_txflags,
6625		    !done ? "" : (ts->ts_status == 0) ? " *" : " !",
6626		    ds->ds_ctl0, ds->ds_ctl1,
6627		    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3]);
6628		if (ah->ah_magic == 0x20065416) {
6629			printf("        %08x %08x %08x %08x %08x %08x %08x %08x\n",
6630			    ds->ds_hw[4], ds->ds_hw[5], ds->ds_hw[6],
6631			    ds->ds_hw[7], ds->ds_hw[8], ds->ds_hw[9],
6632			    ds->ds_hw[10],ds->ds_hw[11]);
6633			printf("        %08x %08x %08x %08x %08x %08x %08x %08x\n",
6634			    ds->ds_hw[12],ds->ds_hw[13],ds->ds_hw[14],
6635			    ds->ds_hw[15],ds->ds_hw[16],ds->ds_hw[17],
6636			    ds->ds_hw[18], ds->ds_hw[19]);
6637		}
6638	}
6639}
6640#endif /* ATH_DEBUG */
6641
6642static void
6643ath_watchdog(struct ifnet *ifp)
6644{
6645	struct ath_softc *sc = ifp->if_softc;
6646
6647	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) && !sc->sc_invalid) {
6648		uint32_t hangs;
6649
6650		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
6651		    hangs != 0) {
6652			if_printf(ifp, "%s hang detected (0x%x)\n",
6653			    hangs & 0xff ? "bb" : "mac", hangs);
6654		} else
6655			if_printf(ifp, "device timeout\n");
6656		ath_reset(ifp);
6657		ifp->if_oerrors++;
6658		sc->sc_stats.ast_watchdog++;
6659	}
6660}
6661
6662#ifdef ATH_DIAGAPI
6663/*
6664 * Diagnostic interface to the HAL.  This is used by various
6665 * tools to do things like retrieve register contents for
6666 * debugging.  The mechanism is intentionally opaque so that
6667 * it can change frequently w/o concern for compatiblity.
6668 */
6669static int
6670ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
6671{
6672	struct ath_hal *ah = sc->sc_ah;
6673	u_int id = ad->ad_id & ATH_DIAG_ID;
6674	void *indata = NULL;
6675	void *outdata = NULL;
6676	u_int32_t insize = ad->ad_in_size;
6677	u_int32_t outsize = ad->ad_out_size;
6678	int error = 0;
6679
6680	if (ad->ad_id & ATH_DIAG_IN) {
6681		/*
6682		 * Copy in data.
6683		 */
6684		indata = malloc(insize, M_TEMP, M_NOWAIT);
6685		if (indata == NULL) {
6686			error = ENOMEM;
6687			goto bad;
6688		}
6689		error = copyin(ad->ad_in_data, indata, insize);
6690		if (error)
6691			goto bad;
6692	}
6693	if (ad->ad_id & ATH_DIAG_DYN) {
6694		/*
6695		 * Allocate a buffer for the results (otherwise the HAL
6696		 * returns a pointer to a buffer where we can read the
6697		 * results).  Note that we depend on the HAL leaving this
6698		 * pointer for us to use below in reclaiming the buffer;
6699		 * may want to be more defensive.
6700		 */
6701		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
6702		if (outdata == NULL) {
6703			error = ENOMEM;
6704			goto bad;
6705		}
6706	}
6707	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
6708		if (outsize < ad->ad_out_size)
6709			ad->ad_out_size = outsize;
6710		if (outdata != NULL)
6711			error = copyout(outdata, ad->ad_out_data,
6712					ad->ad_out_size);
6713	} else {
6714		error = EINVAL;
6715	}
6716bad:
6717	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
6718		free(indata, M_TEMP);
6719	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
6720		free(outdata, M_TEMP);
6721	return error;
6722}
6723#endif /* ATH_DIAGAPI */
6724
6725static int
6726ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
6727{
6728#define	IS_RUNNING(ifp) \
6729	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
6730	struct ath_softc *sc = ifp->if_softc;
6731	struct ieee80211com *ic = ifp->if_l2com;
6732	struct ifreq *ifr = (struct ifreq *)data;
6733	const HAL_RATE_TABLE *rt;
6734	int error = 0;
6735
6736	switch (cmd) {
6737	case SIOCSIFFLAGS:
6738		ATH_LOCK(sc);
6739		if (IS_RUNNING(ifp)) {
6740			/*
6741			 * To avoid rescanning another access point,
6742			 * do not call ath_init() here.  Instead,
6743			 * only reflect promisc mode settings.
6744			 */
6745			ath_mode_init(sc);
6746		} else if (ifp->if_flags & IFF_UP) {
6747			/*
6748			 * Beware of being called during attach/detach
6749			 * to reset promiscuous mode.  In that case we
6750			 * will still be marked UP but not RUNNING.
6751			 * However trying to re-init the interface
6752			 * is the wrong thing to do as we've already
6753			 * torn down much of our state.  There's
6754			 * probably a better way to deal with this.
6755			 */
6756			if (!sc->sc_invalid)
6757				ath_init(sc);	/* XXX lose error */
6758		} else {
6759			ath_stop_locked(ifp);
6760#ifdef notyet
6761			/* XXX must wakeup in places like ath_vap_delete */
6762			if (!sc->sc_invalid)
6763				ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
6764#endif
6765		}
6766		ATH_UNLOCK(sc);
6767		break;
6768	case SIOCGIFMEDIA:
6769	case SIOCSIFMEDIA:
6770		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
6771		break;
6772	case SIOCGATHSTATS:
6773		/* NB: embed these numbers to get a consistent view */
6774		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
6775		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
6776		sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
6777		sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
6778#ifdef ATH_SUPPORT_TDMA
6779		sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
6780		sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
6781#endif
6782		rt = sc->sc_currates;
6783		/* XXX HT rates */
6784		sc->sc_stats.ast_tx_rate =
6785		    rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
6786		return copyout(&sc->sc_stats,
6787		    ifr->ifr_data, sizeof (sc->sc_stats));
6788#ifdef ATH_DIAGAPI
6789	case SIOCGATHDIAG:
6790		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
6791		break;
6792#endif
6793	case SIOCGIFADDR:
6794		error = ether_ioctl(ifp, cmd, data);
6795		break;
6796	default:
6797		error = EINVAL;
6798		break;
6799	}
6800	return error;
6801#undef IS_RUNNING
6802}
6803
6804static int
6805ath_sysctl_slottime(SYSCTL_HANDLER_ARGS)
6806{
6807	struct ath_softc *sc = arg1;
6808	u_int slottime = ath_hal_getslottime(sc->sc_ah);
6809	int error;
6810
6811	error = sysctl_handle_int(oidp, &slottime, 0, req);
6812	if (error || !req->newptr)
6813		return error;
6814	return !ath_hal_setslottime(sc->sc_ah, slottime) ? EINVAL : 0;
6815}
6816
6817static int
6818ath_sysctl_acktimeout(SYSCTL_HANDLER_ARGS)
6819{
6820	struct ath_softc *sc = arg1;
6821	u_int acktimeout = ath_hal_getacktimeout(sc->sc_ah);
6822	int error;
6823
6824	error = sysctl_handle_int(oidp, &acktimeout, 0, req);
6825	if (error || !req->newptr)
6826		return error;
6827	return !ath_hal_setacktimeout(sc->sc_ah, acktimeout) ? EINVAL : 0;
6828}
6829
6830static int
6831ath_sysctl_ctstimeout(SYSCTL_HANDLER_ARGS)
6832{
6833	struct ath_softc *sc = arg1;
6834	u_int ctstimeout = ath_hal_getctstimeout(sc->sc_ah);
6835	int error;
6836
6837	error = sysctl_handle_int(oidp, &ctstimeout, 0, req);
6838	if (error || !req->newptr)
6839		return error;
6840	return !ath_hal_setctstimeout(sc->sc_ah, ctstimeout) ? EINVAL : 0;
6841}
6842
6843static int
6844ath_sysctl_softled(SYSCTL_HANDLER_ARGS)
6845{
6846	struct ath_softc *sc = arg1;
6847	int softled = sc->sc_softled;
6848	int error;
6849
6850	error = sysctl_handle_int(oidp, &softled, 0, req);
6851	if (error || !req->newptr)
6852		return error;
6853	softled = (softled != 0);
6854	if (softled != sc->sc_softled) {
6855		if (softled) {
6856			/* NB: handle any sc_ledpin change */
6857			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
6858			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
6859				!sc->sc_ledon);
6860		}
6861		sc->sc_softled = softled;
6862	}
6863	return 0;
6864}
6865
6866static int
6867ath_sysctl_ledpin(SYSCTL_HANDLER_ARGS)
6868{
6869	struct ath_softc *sc = arg1;
6870	int ledpin = sc->sc_ledpin;
6871	int error;
6872
6873	error = sysctl_handle_int(oidp, &ledpin, 0, req);
6874	if (error || !req->newptr)
6875		return error;
6876	if (ledpin != sc->sc_ledpin) {
6877		sc->sc_ledpin = ledpin;
6878		if (sc->sc_softled) {
6879			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
6880			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
6881				!sc->sc_ledon);
6882		}
6883	}
6884	return 0;
6885}
6886
6887static int
6888ath_sysctl_txantenna(SYSCTL_HANDLER_ARGS)
6889{
6890	struct ath_softc *sc = arg1;
6891	u_int txantenna = ath_hal_getantennaswitch(sc->sc_ah);
6892	int error;
6893
6894	error = sysctl_handle_int(oidp, &txantenna, 0, req);
6895	if (!error && req->newptr) {
6896		/* XXX assumes 2 antenna ports */
6897		if (txantenna < HAL_ANT_VARIABLE || txantenna > HAL_ANT_FIXED_B)
6898			return EINVAL;
6899		ath_hal_setantennaswitch(sc->sc_ah, txantenna);
6900		/*
6901		 * NB: with the switch locked this isn't meaningful,
6902		 *     but set it anyway so things like radiotap get
6903		 *     consistent info in their data.
6904		 */
6905		sc->sc_txantenna = txantenna;
6906	}
6907	return error;
6908}
6909
6910static int
6911ath_sysctl_rxantenna(SYSCTL_HANDLER_ARGS)
6912{
6913	struct ath_softc *sc = arg1;
6914	u_int defantenna = ath_hal_getdefantenna(sc->sc_ah);
6915	int error;
6916
6917	error = sysctl_handle_int(oidp, &defantenna, 0, req);
6918	if (!error && req->newptr)
6919		ath_hal_setdefantenna(sc->sc_ah, defantenna);
6920	return error;
6921}
6922
6923static int
6924ath_sysctl_diversity(SYSCTL_HANDLER_ARGS)
6925{
6926	struct ath_softc *sc = arg1;
6927	u_int diversity = ath_hal_getdiversity(sc->sc_ah);
6928	int error;
6929
6930	error = sysctl_handle_int(oidp, &diversity, 0, req);
6931	if (error || !req->newptr)
6932		return error;
6933	if (!ath_hal_setdiversity(sc->sc_ah, diversity))
6934		return EINVAL;
6935	sc->sc_diversity = diversity;
6936	return 0;
6937}
6938
6939static int
6940ath_sysctl_diag(SYSCTL_HANDLER_ARGS)
6941{
6942	struct ath_softc *sc = arg1;
6943	u_int32_t diag;
6944	int error;
6945
6946	if (!ath_hal_getdiag(sc->sc_ah, &diag))
6947		return EINVAL;
6948	error = sysctl_handle_int(oidp, &diag, 0, req);
6949	if (error || !req->newptr)
6950		return error;
6951	return !ath_hal_setdiag(sc->sc_ah, diag) ? EINVAL : 0;
6952}
6953
6954static int
6955ath_sysctl_tpscale(SYSCTL_HANDLER_ARGS)
6956{
6957	struct ath_softc *sc = arg1;
6958	struct ifnet *ifp = sc->sc_ifp;
6959	u_int32_t scale;
6960	int error;
6961
6962	(void) ath_hal_gettpscale(sc->sc_ah, &scale);
6963	error = sysctl_handle_int(oidp, &scale, 0, req);
6964	if (error || !req->newptr)
6965		return error;
6966	return !ath_hal_settpscale(sc->sc_ah, scale) ? EINVAL :
6967	    (ifp->if_drv_flags & IFF_DRV_RUNNING) ? ath_reset(ifp) : 0;
6968}
6969
6970static int
6971ath_sysctl_tpc(SYSCTL_HANDLER_ARGS)
6972{
6973	struct ath_softc *sc = arg1;
6974	u_int tpc = ath_hal_gettpc(sc->sc_ah);
6975	int error;
6976
6977	error = sysctl_handle_int(oidp, &tpc, 0, req);
6978	if (error || !req->newptr)
6979		return error;
6980	return !ath_hal_settpc(sc->sc_ah, tpc) ? EINVAL : 0;
6981}
6982
6983static int
6984ath_sysctl_rfkill(SYSCTL_HANDLER_ARGS)
6985{
6986	struct ath_softc *sc = arg1;
6987	struct ifnet *ifp = sc->sc_ifp;
6988	struct ath_hal *ah = sc->sc_ah;
6989	u_int rfkill = ath_hal_getrfkill(ah);
6990	int error;
6991
6992	error = sysctl_handle_int(oidp, &rfkill, 0, req);
6993	if (error || !req->newptr)
6994		return error;
6995	if (rfkill == ath_hal_getrfkill(ah))	/* unchanged */
6996		return 0;
6997	if (!ath_hal_setrfkill(ah, rfkill))
6998		return EINVAL;
6999	return (ifp->if_drv_flags & IFF_DRV_RUNNING) ? ath_reset(ifp) : 0;
7000}
7001
7002static int
7003ath_sysctl_rfsilent(SYSCTL_HANDLER_ARGS)
7004{
7005	struct ath_softc *sc = arg1;
7006	u_int rfsilent;
7007	int error;
7008
7009	(void) ath_hal_getrfsilent(sc->sc_ah, &rfsilent);
7010	error = sysctl_handle_int(oidp, &rfsilent, 0, req);
7011	if (error || !req->newptr)
7012		return error;
7013	if (!ath_hal_setrfsilent(sc->sc_ah, rfsilent))
7014		return EINVAL;
7015	sc->sc_rfsilentpin = rfsilent & 0x1c;
7016	sc->sc_rfsilentpol = (rfsilent & 0x2) != 0;
7017	return 0;
7018}
7019
7020static int
7021ath_sysctl_tpack(SYSCTL_HANDLER_ARGS)
7022{
7023	struct ath_softc *sc = arg1;
7024	u_int32_t tpack;
7025	int error;
7026
7027	(void) ath_hal_gettpack(sc->sc_ah, &tpack);
7028	error = sysctl_handle_int(oidp, &tpack, 0, req);
7029	if (error || !req->newptr)
7030		return error;
7031	return !ath_hal_settpack(sc->sc_ah, tpack) ? EINVAL : 0;
7032}
7033
7034static int
7035ath_sysctl_tpcts(SYSCTL_HANDLER_ARGS)
7036{
7037	struct ath_softc *sc = arg1;
7038	u_int32_t tpcts;
7039	int error;
7040
7041	(void) ath_hal_gettpcts(sc->sc_ah, &tpcts);
7042	error = sysctl_handle_int(oidp, &tpcts, 0, req);
7043	if (error || !req->newptr)
7044		return error;
7045	return !ath_hal_settpcts(sc->sc_ah, tpcts) ? EINVAL : 0;
7046}
7047
7048static int
7049ath_sysctl_intmit(SYSCTL_HANDLER_ARGS)
7050{
7051	struct ath_softc *sc = arg1;
7052	int intmit, error;
7053
7054	intmit = ath_hal_getintmit(sc->sc_ah);
7055	error = sysctl_handle_int(oidp, &intmit, 0, req);
7056	if (error || !req->newptr)
7057		return error;
7058	return !ath_hal_setintmit(sc->sc_ah, intmit) ? EINVAL : 0;
7059}
7060
7061static void
7062ath_sysctlattach(struct ath_softc *sc)
7063{
7064	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
7065	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
7066	struct ath_hal *ah = sc->sc_ah;
7067
7068	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7069		"countrycode", CTLFLAG_RD, &sc->sc_eecc, 0,
7070		"EEPROM country code");
7071	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7072		"regdomain", CTLFLAG_RD, &sc->sc_eerd, 0,
7073		"EEPROM regdomain code");
7074#ifdef	ATH_DEBUG
7075	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7076		"debug", CTLFLAG_RW, &sc->sc_debug, 0,
7077		"control debugging printfs");
7078#endif
7079	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7080		"slottime", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7081		ath_sysctl_slottime, "I", "802.11 slot time (us)");
7082	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7083		"acktimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7084		ath_sysctl_acktimeout, "I", "802.11 ACK timeout (us)");
7085	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7086		"ctstimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7087		ath_sysctl_ctstimeout, "I", "802.11 CTS timeout (us)");
7088	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7089		"softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7090		ath_sysctl_softled, "I", "enable/disable software LED support");
7091	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7092		"ledpin", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7093		ath_sysctl_ledpin, "I", "GPIO pin connected to LED");
7094	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7095		"ledon", CTLFLAG_RW, &sc->sc_ledon, 0,
7096		"setting to turn LED on");
7097	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7098		"ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
7099		"idle time for inactivity LED (ticks)");
7100	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7101		"txantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7102		ath_sysctl_txantenna, "I", "antenna switch");
7103	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7104		"rxantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7105		ath_sysctl_rxantenna, "I", "default/rx antenna");
7106	if (ath_hal_hasdiversity(ah))
7107		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7108			"diversity", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7109			ath_sysctl_diversity, "I", "antenna diversity");
7110	sc->sc_txintrperiod = ATH_TXINTR_PERIOD;
7111	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7112		"txintrperiod", CTLFLAG_RW, &sc->sc_txintrperiod, 0,
7113		"tx descriptor batching");
7114	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7115		"diag", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7116		ath_sysctl_diag, "I", "h/w diagnostic control");
7117	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7118		"tpscale", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7119		ath_sysctl_tpscale, "I", "tx power scaling");
7120	if (ath_hal_hastpc(ah)) {
7121		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7122			"tpc", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7123			ath_sysctl_tpc, "I", "enable/disable per-packet TPC");
7124		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7125			"tpack", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7126			ath_sysctl_tpack, "I", "tx power for ack frames");
7127		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7128			"tpcts", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7129			ath_sysctl_tpcts, "I", "tx power for cts frames");
7130	}
7131	if (ath_hal_hasfastframes(sc->sc_ah)) {
7132		sc->sc_fftxqmin = ATH_FF_TXQMIN;
7133		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7134			"fftxqmin", CTLFLAG_RW, &sc->sc_fftxqmin, 0,
7135			"min frames before fast-frame staging");
7136		sc->sc_fftxqmax = ATH_FF_TXQMAX;
7137		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7138			"fftxqmax", CTLFLAG_RW, &sc->sc_fftxqmax, 0,
7139			"max queued frames before tail drop");
7140	}
7141	if (ath_hal_hasrfsilent(ah)) {
7142		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7143			"rfsilent", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7144			ath_sysctl_rfsilent, "I", "h/w RF silent config");
7145		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7146			"rfkill", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7147			ath_sysctl_rfkill, "I", "enable/disable RF kill switch");
7148	}
7149	if (ath_hal_hasintmit(ah)) {
7150		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7151			"intmit", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7152			ath_sysctl_intmit, "I", "interference mitigation");
7153	}
7154	sc->sc_monpass = HAL_RXERR_DECRYPT | HAL_RXERR_MIC;
7155	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7156		"monpass", CTLFLAG_RW, &sc->sc_monpass, 0,
7157		"mask of error frames to pass when monitoring");
7158#ifdef ATH_SUPPORT_TDMA
7159	if (ath_hal_macversion(ah) > 0x78) {
7160		sc->sc_tdmadbaprep = 2;
7161		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7162			"dbaprep", CTLFLAG_RW, &sc->sc_tdmadbaprep, 0,
7163			"TDMA DBA preparation time");
7164		sc->sc_tdmaswbaprep = 10;
7165		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7166			"swbaprep", CTLFLAG_RW, &sc->sc_tdmaswbaprep, 0,
7167			"TDMA SWBA preparation time");
7168		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7169			"guardtime", CTLFLAG_RW, &sc->sc_tdmaguard, 0,
7170			"TDMA slot guard time");
7171		SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7172			"superframe", CTLFLAG_RD, &sc->sc_tdmabintval, 0,
7173			"TDMA calculated super frame");
7174	}
7175#endif
7176}
7177
7178static void
7179ath_bpfattach(struct ath_softc *sc)
7180{
7181	struct ifnet *ifp = sc->sc_ifp;
7182
7183	bpfattach(ifp, DLT_IEEE802_11_RADIO,
7184		sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th));
7185	/*
7186	 * Initialize constant fields.
7187	 * XXX make header lengths a multiple of 32-bits so subsequent
7188	 *     headers are properly aligned; this is a kludge to keep
7189	 *     certain applications happy.
7190	 *
7191	 * NB: the channel is setup each time we transition to the
7192	 *     RUN state to avoid filling it in for each frame.
7193	 */
7194	sc->sc_tx_th_len = roundup(sizeof(sc->sc_tx_th), sizeof(u_int32_t));
7195	sc->sc_tx_th.wt_ihdr.it_len = htole16(sc->sc_tx_th_len);
7196	sc->sc_tx_th.wt_ihdr.it_present = htole32(ATH_TX_RADIOTAP_PRESENT);
7197
7198	sc->sc_rx_th_len = roundup(sizeof(sc->sc_rx_th), sizeof(u_int32_t));
7199	sc->sc_rx_th.wr_ihdr.it_len = htole16(sc->sc_rx_th_len);
7200	sc->sc_rx_th.wr_ihdr.it_present = htole32(ATH_RX_RADIOTAP_PRESENT);
7201}
7202
7203static int
7204ath_tx_raw_start(struct ath_softc *sc, struct ieee80211_node *ni,
7205	struct ath_buf *bf, struct mbuf *m0,
7206	const struct ieee80211_bpf_params *params)
7207{
7208	struct ifnet *ifp = sc->sc_ifp;
7209	struct ieee80211com *ic = ifp->if_l2com;
7210	struct ath_hal *ah = sc->sc_ah;
7211	int error, ismcast, ismrr;
7212	int keyix, hdrlen, pktlen, try0, txantenna;
7213	u_int8_t rix, cix, txrate, ctsrate, rate1, rate2, rate3;
7214	struct ieee80211_frame *wh;
7215	u_int flags, ctsduration;
7216	HAL_PKT_TYPE atype;
7217	const HAL_RATE_TABLE *rt;
7218	struct ath_desc *ds;
7219	u_int pri;
7220
7221	wh = mtod(m0, struct ieee80211_frame *);
7222	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
7223	hdrlen = ieee80211_anyhdrsize(wh);
7224	/*
7225	 * Packet length must not include any
7226	 * pad bytes; deduct them here.
7227	 */
7228	/* XXX honor IEEE80211_BPF_DATAPAD */
7229	pktlen = m0->m_pkthdr.len - (hdrlen & 3) + IEEE80211_CRC_LEN;
7230
7231	if (params->ibp_flags & IEEE80211_BPF_CRYPTO) {
7232		const struct ieee80211_cipher *cip;
7233		struct ieee80211_key *k;
7234
7235		/*
7236		 * Construct the 802.11 header+trailer for an encrypted
7237		 * frame. The only reason this can fail is because of an
7238		 * unknown or unsupported cipher/key type.
7239		 */
7240		k = ieee80211_crypto_encap(ni, m0);
7241		if (k == NULL) {
7242			/*
7243			 * This can happen when the key is yanked after the
7244			 * frame was queued.  Just discard the frame; the
7245			 * 802.11 layer counts failures and provides
7246			 * debugging/diagnostics.
7247			 */
7248			ath_freetx(m0);
7249			return EIO;
7250		}
7251		/*
7252		 * Adjust the packet + header lengths for the crypto
7253		 * additions and calculate the h/w key index.  When
7254		 * a s/w mic is done the frame will have had any mic
7255		 * added to it prior to entry so m0->m_pkthdr.len will
7256		 * account for it. Otherwise we need to add it to the
7257		 * packet length.
7258		 */
7259		cip = k->wk_cipher;
7260		hdrlen += cip->ic_header;
7261		pktlen += cip->ic_header + cip->ic_trailer;
7262		/* NB: frags always have any TKIP MIC done in s/w */
7263		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0)
7264			pktlen += cip->ic_miclen;
7265		keyix = k->wk_keyix;
7266
7267		/* packet header may have moved, reset our local pointer */
7268		wh = mtod(m0, struct ieee80211_frame *);
7269	} else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
7270		/*
7271		 * Use station key cache slot, if assigned.
7272		 */
7273		keyix = ni->ni_ucastkey.wk_keyix;
7274		if (keyix == IEEE80211_KEYIX_NONE)
7275			keyix = HAL_TXKEYIX_INVALID;
7276	} else
7277		keyix = HAL_TXKEYIX_INVALID;
7278
7279	error = ath_tx_dmasetup(sc, bf, m0);
7280	if (error != 0)
7281		return error;
7282	m0 = bf->bf_m;				/* NB: may have changed */
7283	wh = mtod(m0, struct ieee80211_frame *);
7284	bf->bf_node = ni;			/* NB: held reference */
7285
7286	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
7287	flags |= HAL_TXDESC_INTREQ;		/* force interrupt */
7288	if (params->ibp_flags & IEEE80211_BPF_RTS)
7289		flags |= HAL_TXDESC_RTSENA;
7290	else if (params->ibp_flags & IEEE80211_BPF_CTS)
7291		flags |= HAL_TXDESC_CTSENA;
7292	/* XXX leave ismcast to injector? */
7293	if ((params->ibp_flags & IEEE80211_BPF_NOACK) || ismcast)
7294		flags |= HAL_TXDESC_NOACK;
7295
7296	rt = sc->sc_currates;
7297	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
7298	rix = ath_tx_findrix(rt, params->ibp_rate0);
7299	txrate = rt->info[rix].rateCode;
7300	if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
7301		txrate |= rt->info[rix].shortPreamble;
7302	sc->sc_txrix = rix;
7303	try0 = params->ibp_try0;
7304	ismrr = (params->ibp_try1 != 0);
7305	txantenna = params->ibp_pri >> 2;
7306	if (txantenna == 0)			/* XXX? */
7307		txantenna = sc->sc_txantenna;
7308	ctsduration = 0;
7309	if (flags & (HAL_TXDESC_CTSENA | HAL_TXDESC_RTSENA)) {
7310		cix = ath_tx_findrix(rt, params->ibp_ctsrate);
7311		ctsrate = rt->info[cix].rateCode;
7312		if (params->ibp_flags & IEEE80211_BPF_SHORTPRE) {
7313			ctsrate |= rt->info[cix].shortPreamble;
7314			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
7315				ctsduration += rt->info[cix].spAckDuration;
7316			ctsduration += ath_hal_computetxtime(ah,
7317				rt, pktlen, rix, AH_TRUE);
7318			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
7319				ctsduration += rt->info[rix].spAckDuration;
7320		} else {
7321			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
7322				ctsduration += rt->info[cix].lpAckDuration;
7323			ctsduration += ath_hal_computetxtime(ah,
7324				rt, pktlen, rix, AH_FALSE);
7325			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
7326				ctsduration += rt->info[rix].lpAckDuration;
7327		}
7328		ismrr = 0;			/* XXX */
7329	} else
7330		ctsrate = 0;
7331	pri = params->ibp_pri & 3;
7332	/*
7333	 * NB: we mark all packets as type PSPOLL so the h/w won't
7334	 * set the sequence number, duration, etc.
7335	 */
7336	atype = HAL_PKT_TYPE_PSPOLL;
7337
7338	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
7339		ieee80211_dump_pkt(ic, mtod(m0, caddr_t), m0->m_len,
7340			sc->sc_hwmap[rix].ieeerate, -1);
7341
7342	if (bpf_peers_present(ifp->if_bpf)) {
7343		u_int64_t tsf = ath_hal_gettsf64(ah);
7344
7345		sc->sc_tx_th.wt_tsf = htole64(tsf);
7346		sc->sc_tx_th.wt_flags = sc->sc_hwmap[rix].txflags;
7347		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
7348			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
7349		sc->sc_tx_th.wt_rate = sc->sc_hwmap[rix].ieeerate;
7350		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
7351		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
7352
7353		bpf_mtap2(ifp->if_bpf, &sc->sc_tx_th, sc->sc_tx_th_len, m0);
7354	}
7355
7356	/*
7357	 * Formulate first tx descriptor with tx controls.
7358	 */
7359	ds = bf->bf_desc;
7360	/* XXX check return value? */
7361	ath_hal_setuptxdesc(ah, ds
7362		, pktlen		/* packet length */
7363		, hdrlen		/* header length */
7364		, atype			/* Atheros packet type */
7365		, params->ibp_power	/* txpower */
7366		, txrate, try0		/* series 0 rate/tries */
7367		, keyix			/* key cache index */
7368		, txantenna		/* antenna mode */
7369		, flags			/* flags */
7370		, ctsrate		/* rts/cts rate */
7371		, ctsduration		/* rts/cts duration */
7372	);
7373	bf->bf_txflags = flags;
7374
7375	if (ismrr) {
7376		rix = ath_tx_findrix(rt, params->ibp_rate1);
7377		rate1 = rt->info[rix].rateCode;
7378		if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
7379			rate1 |= rt->info[rix].shortPreamble;
7380		if (params->ibp_try2) {
7381			rix = ath_tx_findrix(rt, params->ibp_rate2);
7382			rate2 = rt->info[rix].rateCode;
7383			if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
7384				rate2 |= rt->info[rix].shortPreamble;
7385		} else
7386			rate2 = 0;
7387		if (params->ibp_try3) {
7388			rix = ath_tx_findrix(rt, params->ibp_rate3);
7389			rate3 = rt->info[rix].rateCode;
7390			if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
7391				rate3 |= rt->info[rix].shortPreamble;
7392		} else
7393			rate3 = 0;
7394		ath_hal_setupxtxdesc(ah, ds
7395			, rate1, params->ibp_try1	/* series 1 */
7396			, rate2, params->ibp_try2	/* series 2 */
7397			, rate3, params->ibp_try3	/* series 3 */
7398		);
7399	}
7400
7401	/* NB: no buffered multicast in power save support */
7402	ath_tx_handoff(sc, sc->sc_ac2q[pri], bf);
7403	return 0;
7404}
7405
7406static int
7407ath_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
7408	const struct ieee80211_bpf_params *params)
7409{
7410	struct ieee80211com *ic = ni->ni_ic;
7411	struct ifnet *ifp = ic->ic_ifp;
7412	struct ath_softc *sc = ifp->if_softc;
7413	struct ath_buf *bf;
7414
7415	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid) {
7416		ieee80211_free_node(ni);
7417		m_freem(m);
7418		return ENETDOWN;
7419	}
7420	/*
7421	 * Grab a TX buffer and associated resources.
7422	 */
7423	bf = ath_getbuf(sc);
7424	if (bf == NULL) {
7425		ieee80211_free_node(ni);
7426		m_freem(m);
7427		return ENOBUFS;
7428	}
7429
7430	ifp->if_opackets++;
7431	sc->sc_stats.ast_tx_raw++;
7432
7433	if (params == NULL) {
7434		/*
7435		 * Legacy path; interpret frame contents to decide
7436		 * precisely how to send the frame.
7437		 */
7438		if (ath_tx_start(sc, ni, bf, m))
7439			goto bad;
7440	} else {
7441		/*
7442		 * Caller supplied explicit parameters to use in
7443		 * sending the frame.
7444		 */
7445		if (ath_tx_raw_start(sc, ni, bf, m, params))
7446			goto bad;
7447	}
7448	ifp->if_timer = 5;
7449
7450	return 0;
7451bad:
7452	ifp->if_oerrors++;
7453	ATH_TXBUF_LOCK(sc);
7454	STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
7455	ATH_TXBUF_UNLOCK(sc);
7456	ieee80211_free_node(ni);
7457	return EIO;		/* XXX */
7458}
7459
7460/*
7461 * Announce various information on device/driver attach.
7462 */
7463static void
7464ath_announce(struct ath_softc *sc)
7465{
7466#define	HAL_MODE_DUALBAND	(HAL_MODE_11A|HAL_MODE_11B)
7467	struct ifnet *ifp = sc->sc_ifp;
7468	struct ath_hal *ah = sc->sc_ah;
7469	u_int modes, cc;
7470
7471	if_printf(ifp, "mac %d.%d phy %d.%d",
7472		ah->ah_macVersion, ah->ah_macRev,
7473		ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
7474	/*
7475	 * Print radio revision(s).  We check the wireless modes
7476	 * to avoid falsely printing revs for inoperable parts.
7477	 * Dual-band radio revs are returned in the 5Ghz rev number.
7478	 */
7479	ath_hal_getcountrycode(ah, &cc);
7480	modes = ath_hal_getwirelessmodes(ah, cc);
7481	if ((modes & HAL_MODE_DUALBAND) == HAL_MODE_DUALBAND) {
7482		if (ah->ah_analog5GhzRev && ah->ah_analog2GhzRev)
7483			printf(" 5ghz radio %d.%d 2ghz radio %d.%d",
7484				ah->ah_analog5GhzRev >> 4,
7485				ah->ah_analog5GhzRev & 0xf,
7486				ah->ah_analog2GhzRev >> 4,
7487				ah->ah_analog2GhzRev & 0xf);
7488		else
7489			printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
7490				ah->ah_analog5GhzRev & 0xf);
7491	} else
7492		printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
7493			ah->ah_analog5GhzRev & 0xf);
7494	printf("\n");
7495	if (bootverbose) {
7496		int i;
7497		for (i = 0; i <= WME_AC_VO; i++) {
7498			struct ath_txq *txq = sc->sc_ac2q[i];
7499			if_printf(ifp, "Use hw queue %u for %s traffic\n",
7500				txq->axq_qnum, ieee80211_wme_acnames[i]);
7501		}
7502		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
7503			sc->sc_cabq->axq_qnum);
7504		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
7505	}
7506	if (ath_rxbuf != ATH_RXBUF)
7507		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
7508	if (ath_txbuf != ATH_TXBUF)
7509		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
7510#undef HAL_MODE_DUALBAND
7511}
7512
7513#ifdef ATH_SUPPORT_TDMA
7514static __inline uint32_t
7515ath_hal_getnexttbtt(struct ath_hal *ah)
7516{
7517#define	AR_TIMER0	0x8028
7518	return OS_REG_READ(ah, AR_TIMER0);
7519}
7520
7521static __inline void
7522ath_hal_adjusttsf(struct ath_hal *ah, int32_t tsfdelta)
7523{
7524	/* XXX handle wrap/overflow */
7525	OS_REG_WRITE(ah, AR_TSF_L32, OS_REG_READ(ah, AR_TSF_L32) + tsfdelta);
7526}
7527
7528static void
7529ath_tdma_settimers(struct ath_softc *sc, u_int32_t nexttbtt, u_int32_t bintval)
7530{
7531	struct ath_hal *ah = sc->sc_ah;
7532	HAL_BEACON_TIMERS bt;
7533
7534	bt.bt_intval = bintval | HAL_BEACON_ENA;
7535	bt.bt_nexttbtt = nexttbtt;
7536	bt.bt_nextdba = (nexttbtt<<3) - sc->sc_tdmadbaprep;
7537	bt.bt_nextswba = (nexttbtt<<3) - sc->sc_tdmaswbaprep;
7538	bt.bt_nextatim = nexttbtt+1;
7539	ath_hal_beaconsettimers(ah, &bt);
7540}
7541
7542/*
7543 * Calculate the beacon interval.  This is periodic in the
7544 * superframe for the bss.  We assume each station is configured
7545 * identically wrt transmit rate so the guard time we calculate
7546 * above will be the same on all stations.  Note we need to
7547 * factor in the xmit time because the hardware will schedule
7548 * a frame for transmit if the start of the frame is within
7549 * the burst time.  When we get hardware that properly kills
7550 * frames in the PCU we can reduce/eliminate the guard time.
7551 *
7552 * Roundup to 1024 is so we have 1 TU buffer in the guard time
7553 * to deal with the granularity of the nexttbtt timer.  11n MAC's
7554 * with 1us timer granularity should allow us to reduce/eliminate
7555 * this.
7556 */
7557static void
7558ath_tdma_bintvalsetup(struct ath_softc *sc,
7559	const struct ieee80211_tdma_state *tdma)
7560{
7561	/* copy from vap state (XXX check all vaps have same value?) */
7562	sc->sc_tdmaslotlen = tdma->tdma_slotlen;
7563	sc->sc_tdmabintcnt = tdma->tdma_bintval;
7564
7565	sc->sc_tdmabintval = roundup((sc->sc_tdmaslotlen+sc->sc_tdmaguard) *
7566		tdma->tdma_slotcnt, 1024);
7567	sc->sc_tdmabintval >>= 10;		/* TSF -> TU */
7568	if (sc->sc_tdmabintval & 1)
7569		sc->sc_tdmabintval++;
7570
7571	if (tdma->tdma_slot == 0) {
7572		/*
7573		 * Only slot 0 beacons; other slots respond.
7574		 */
7575		sc->sc_imask |= HAL_INT_SWBA;
7576		sc->sc_tdmaswba = 0;		/* beacon immediately */
7577	} else {
7578		/* XXX all vaps must be slot 0 or slot !0 */
7579		sc->sc_imask &= ~HAL_INT_SWBA;
7580	}
7581}
7582
7583/*
7584 * Max 802.11 overhead.  This assumes no 4-address frames and
7585 * the encapsulation done by ieee80211_encap (llc).  We also
7586 * include potential crypto overhead.
7587 */
7588#define	IEEE80211_MAXOVERHEAD \
7589	(sizeof(struct ieee80211_qosframe) \
7590	 + sizeof(struct llc) \
7591	 + IEEE80211_ADDR_LEN \
7592	 + IEEE80211_WEP_IVLEN \
7593	 + IEEE80211_WEP_KIDLEN \
7594	 + IEEE80211_WEP_CRCLEN \
7595	 + IEEE80211_WEP_MICLEN \
7596	 + IEEE80211_CRC_LEN)
7597
7598/*
7599 * Setup initially for tdma operation.  Start the beacon
7600 * timers and enable SWBA if we are slot 0.  Otherwise
7601 * we wait for slot 0 to arrive so we can sync up before
7602 * starting to transmit.
7603 */
7604static void
7605ath_tdma_config(struct ath_softc *sc, struct ieee80211vap *vap)
7606{
7607	struct ath_hal *ah = sc->sc_ah;
7608	struct ifnet *ifp = sc->sc_ifp;
7609	struct ieee80211com *ic = ifp->if_l2com;
7610	const struct ieee80211_txparam *tp;
7611	const struct ieee80211_tdma_state *tdma = NULL;
7612	int rix;
7613
7614	if (vap == NULL) {
7615		vap = TAILQ_FIRST(&ic->ic_vaps);   /* XXX */
7616		if (vap == NULL) {
7617			if_printf(ifp, "%s: no vaps?\n", __func__);
7618			return;
7619		}
7620	}
7621	tp = vap->iv_bss->ni_txparms;
7622	/*
7623	 * Calculate the guard time for each slot.  This is the
7624	 * time to send a maximal-size frame according to the
7625	 * fixed/lowest transmit rate.  Note that the interface
7626	 * mtu does not include the 802.11 overhead so we must
7627	 * tack that on (ath_hal_computetxtime includes the
7628	 * preamble and plcp in it's calculation).
7629	 */
7630	tdma = vap->iv_tdma;
7631	if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
7632		rix = ath_tx_findrix(sc->sc_currates, tp->ucastrate);
7633	else
7634		rix = ath_tx_findrix(sc->sc_currates, tp->mcastrate);
7635	/* XXX short preamble assumed */
7636	sc->sc_tdmaguard = ath_hal_computetxtime(ah, sc->sc_currates,
7637		ifp->if_mtu + IEEE80211_MAXOVERHEAD, rix, AH_TRUE);
7638
7639	ath_hal_intrset(ah, 0);
7640
7641	ath_beaconq_config(sc);			/* setup h/w beacon q */
7642	ath_hal_setcca(ah, AH_FALSE);		/* disable CCA */
7643	ath_tdma_bintvalsetup(sc, tdma);	/* calculate beacon interval */
7644	ath_tdma_settimers(sc, sc->sc_tdmabintval,
7645		sc->sc_tdmabintval | HAL_BEACON_RESET_TSF);
7646	sc->sc_syncbeacon = 0;
7647
7648	sc->sc_avgtsfdeltap = TDMA_DUMMY_MARKER;
7649	sc->sc_avgtsfdeltam = TDMA_DUMMY_MARKER;
7650
7651	ath_hal_intrset(ah, sc->sc_imask);
7652
7653	DPRINTF(sc, ATH_DEBUG_TDMA, "%s: slot %u len %uus cnt %u "
7654	    "bsched %u guard %uus bintval %u TU dba prep %u\n", __func__,
7655	    tdma->tdma_slot, tdma->tdma_slotlen, tdma->tdma_slotcnt,
7656	    tdma->tdma_bintval, sc->sc_tdmaguard, sc->sc_tdmabintval,
7657	    sc->sc_tdmadbaprep);
7658}
7659
7660/*
7661 * Update tdma operation.  Called from the 802.11 layer
7662 * when a beacon is received from the TDMA station operating
7663 * in the slot immediately preceding us in the bss.  Use
7664 * the rx timestamp for the beacon frame to update our
7665 * beacon timers so we follow their schedule.  Note that
7666 * by using the rx timestamp we implicitly include the
7667 * propagation delay in our schedule.
7668 */
7669static void
7670ath_tdma_update(struct ieee80211_node *ni,
7671	const struct ieee80211_tdma_param *tdma)
7672{
7673#define	TSF_TO_TU(_h,_l) \
7674	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
7675#define	TU_TO_TSF(_tu)	(((u_int64_t)(_tu)) << 10)
7676	struct ieee80211vap *vap = ni->ni_vap;
7677	struct ieee80211com *ic = ni->ni_ic;
7678	struct ath_softc *sc = ic->ic_ifp->if_softc;
7679	struct ath_hal *ah = sc->sc_ah;
7680	const HAL_RATE_TABLE *rt = sc->sc_currates;
7681	u_int64_t tsf, rstamp, nextslot;
7682	u_int32_t txtime, nextslottu, timer0;
7683	int32_t tudelta, tsfdelta;
7684	const struct ath_rx_status *rs;
7685	int rix;
7686
7687	sc->sc_stats.ast_tdma_update++;
7688
7689	/*
7690	 * Check for and adopt configuration changes.
7691	 */
7692	if (isset(ATH_VAP(vap)->av_boff.bo_flags, IEEE80211_BEACON_TDMA)) {
7693		const struct ieee80211_tdma_state *ts = vap->iv_tdma;
7694
7695		ath_tdma_bintvalsetup(sc, ts);
7696
7697		DPRINTF(sc, ATH_DEBUG_TDMA,
7698		    "%s: adopt slot %u slotcnt %u slotlen %u us "
7699		    "bintval %u TU\n", __func__,
7700		    ts->tdma_slot, ts->tdma_slotcnt, ts->tdma_slotlen,
7701		    sc->sc_tdmabintval);
7702
7703		ath_beaconq_config(sc);
7704		/* XXX right? */
7705		ath_hal_intrset(ah, sc->sc_imask);
7706		/* NB: beacon timers programmed below */
7707	}
7708
7709	/* extend rx timestamp to 64 bits */
7710	tsf = ath_hal_gettsf64(ah);
7711	rstamp = ath_extend_tsf(ni->ni_rstamp, tsf);
7712	/*
7713	 * The rx timestamp is set by the hardware on completing
7714	 * reception (at the point where the rx descriptor is DMA'd
7715	 * to the host).  To find the start of our next slot we
7716	 * must adjust this time by the time required to send
7717	 * the packet just received.
7718	 */
7719	rs = sc->sc_tdmars;
7720	rix = rt->rateCodeToIndex[rs->rs_rate];
7721	txtime = ath_hal_computetxtime(ah, rt, rs->rs_datalen, rix,
7722	    rt->info[rix].shortPreamble);
7723	/* NB: << 9 is to cvt to TU and /2 */
7724	nextslot = (rstamp - txtime) + (sc->sc_tdmabintval << 9);
7725	nextslottu = TSF_TO_TU(nextslot>>32, nextslot) & HAL_BEACON_PERIOD;
7726
7727	/*
7728	 * TIMER0 is the h/w's idea of NextTBTT (in TU's).  Convert
7729	 * to usecs and calculate the difference between what the
7730	 * other station thinks and what we have programmed.  This
7731	 * lets us figure how to adjust our timers to match.  The
7732	 * adjustments are done by pulling the TSF forward and possibly
7733	 * rewriting the beacon timers.
7734	 */
7735	timer0 = ath_hal_getnexttbtt(ah);
7736	tsfdelta = (int32_t)((nextslot % TU_TO_TSF(HAL_BEACON_PERIOD+1)) - TU_TO_TSF(timer0));
7737
7738	DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
7739	    "tsfdelta %d avg +%d/-%d\n", tsfdelta,
7740	    TDMA_AVG(sc->sc_avgtsfdeltap), TDMA_AVG(sc->sc_avgtsfdeltam));
7741
7742	if (tsfdelta < 0) {
7743		TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
7744		TDMA_SAMPLE(sc->sc_avgtsfdeltam, -tsfdelta);
7745		tsfdelta = -tsfdelta % 1024;
7746		nextslottu++;
7747	} else if (tsfdelta > 0) {
7748		TDMA_SAMPLE(sc->sc_avgtsfdeltap, tsfdelta);
7749		TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
7750		tsfdelta = 1024 - (tsfdelta % 1024);
7751		nextslottu++;
7752	} else {
7753		TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
7754		TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
7755	}
7756	tudelta = nextslottu - timer0;
7757
7758	/*
7759	 * Copy sender's timetstamp into tdma ie so they can
7760	 * calculate roundtrip time.  We submit a beacon frame
7761	 * below after any timer adjustment.  The frame goes out
7762	 * at the next TBTT so the sender can calculate the
7763	 * roundtrip by inspecting the tdma ie in our beacon frame.
7764	 *
7765	 * NB: This tstamp is subtlely preserved when
7766	 *     IEEE80211_BEACON_TDMA is marked (e.g. when the
7767	 *     slot position changes) because ieee80211_add_tdma
7768	 *     skips over the data.
7769	 */
7770	memcpy(ATH_VAP(vap)->av_boff.bo_tdma +
7771		__offsetof(struct ieee80211_tdma_param, tdma_tstamp),
7772		&ni->ni_tstamp.data, 8);
7773#if 0
7774	DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
7775	    "tsf %llu nextslot %llu (%d, %d) nextslottu %u timer0 %u (%d)\n",
7776	    (unsigned long long) tsf, (unsigned long long) nextslot,
7777	    (int)(nextslot - tsf), tsfdelta,
7778	    nextslottu, timer0, tudelta);
7779#endif
7780	/*
7781	 * Adjust the beacon timers only when pulling them forward
7782	 * or when going back by less than the beacon interval.
7783	 * Negative jumps larger than the beacon interval seem to
7784	 * cause the timers to stop and generally cause instability.
7785	 * This basically filters out jumps due to missed beacons.
7786	 */
7787	if (tudelta != 0 && (tudelta > 0 || -tudelta < sc->sc_tdmabintval)) {
7788		ath_tdma_settimers(sc, nextslottu, sc->sc_tdmabintval);
7789		sc->sc_stats.ast_tdma_timers++;
7790	}
7791	if (tsfdelta > 0) {
7792		ath_hal_adjusttsf(ah, tsfdelta);
7793		sc->sc_stats.ast_tdma_tsf++;
7794	}
7795	ath_tdma_beacon_send(sc, vap);		/* prepare response */
7796#undef TU_TO_TSF
7797#undef TSF_TO_TU
7798}
7799
7800/*
7801 * Transmit a beacon frame at SWBA.  Dynamic updates
7802 * to the frame contents are done as needed.
7803 */
7804static void
7805ath_tdma_beacon_send(struct ath_softc *sc, struct ieee80211vap *vap)
7806{
7807	struct ath_hal *ah = sc->sc_ah;
7808	struct ath_buf *bf;
7809	int otherant;
7810
7811	/*
7812	 * Check if the previous beacon has gone out.  If
7813	 * not don't try to post another, skip this period
7814	 * and wait for the next.  Missed beacons indicate
7815	 * a problem and should not occur.  If we miss too
7816	 * many consecutive beacons reset the device.
7817	 */
7818	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
7819		sc->sc_bmisscount++;
7820		DPRINTF(sc, ATH_DEBUG_BEACON,
7821			"%s: missed %u consecutive beacons\n",
7822			__func__, sc->sc_bmisscount);
7823		if (sc->sc_bmisscount > 3)		/* NB: 3 is a guess */
7824			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
7825		return;
7826	}
7827	if (sc->sc_bmisscount != 0) {
7828		DPRINTF(sc, ATH_DEBUG_BEACON,
7829			"%s: resume beacon xmit after %u misses\n",
7830			__func__, sc->sc_bmisscount);
7831		sc->sc_bmisscount = 0;
7832	}
7833
7834	/*
7835	 * Check recent per-antenna transmit statistics and flip
7836	 * the default antenna if noticeably more frames went out
7837	 * on the non-default antenna.
7838	 * XXX assumes 2 anntenae
7839	 */
7840	if (!sc->sc_diversity) {
7841		otherant = sc->sc_defant & 1 ? 2 : 1;
7842		if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
7843			ath_setdefantenna(sc, otherant);
7844		sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
7845	}
7846
7847	bf = ath_beacon_generate(sc, vap);
7848	if (bf != NULL) {
7849		/*
7850		 * Stop any current dma and put the new frame on the queue.
7851		 * This should never fail since we check above that no frames
7852		 * are still pending on the queue.
7853		 */
7854		if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
7855			DPRINTF(sc, ATH_DEBUG_ANY,
7856				"%s: beacon queue %u did not stop?\n",
7857				__func__, sc->sc_bhalq);
7858			/* NB: the HAL still stops DMA, so proceed */
7859		}
7860		ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
7861		ath_hal_txstart(ah, sc->sc_bhalq);
7862
7863		sc->sc_stats.ast_be_xmit++;		/* XXX per-vap? */
7864
7865		/*
7866		 * Record local TSF for our last send for use
7867		 * in arbitrating slot collisions.
7868		 */
7869		vap->iv_bss->ni_tstamp.tsf = ath_hal_gettsf64(ah);
7870	}
7871}
7872#endif /* ATH_SUPPORT_TDMA */
7873