if_ath.c revision 218146
1123474Swpaul/*-
2123474Swpaul * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3123474Swpaul * All rights reserved.
4123474Swpaul *
5123474Swpaul * Redistribution and use in source and binary forms, with or without
6123474Swpaul * modification, are permitted provided that the following conditions
7123474Swpaul * are met:
8123474Swpaul * 1. Redistributions of source code must retain the above copyright
9123474Swpaul *    notice, this list of conditions and the following disclaimer,
10123474Swpaul *    without modification.
11123474Swpaul * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12123474Swpaul *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13123474Swpaul *    redistribution must be conditioned upon including a substantially
14123474Swpaul *    similar Disclaimer requirement for further binary redistribution.
15123474Swpaul *
16123474Swpaul * NO WARRANTY
17123474Swpaul * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18123474Swpaul * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19123474Swpaul * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
20123474Swpaul * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21123474Swpaul * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
22123474Swpaul * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23123474Swpaul * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24123474Swpaul * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25123474Swpaul * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26123474Swpaul * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27123474Swpaul * THE POSSIBILITY OF SUCH DAMAGES.
28123474Swpaul */
29123474Swpaul
30123474Swpaul#include <sys/cdefs.h>
31123474Swpaul__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath.c 218146 2011-01-31 22:45:14Z adrian $");
32123474Swpaul
33123474Swpaul/*
34123474Swpaul * Driver for the Atheros Wireless LAN controller.
35123474Swpaul *
36123474Swpaul * This software is derived from work of Atsushi Onoe; his contribution
37123474Swpaul * is greatly appreciated.
38123474Swpaul */
39123474Swpaul
40123474Swpaul#include "opt_inet.h"
41123474Swpaul#include "opt_ath.h"
42123474Swpaul#include "opt_wlan.h"
43123474Swpaul
44123474Swpaul#include <sys/param.h>
45123474Swpaul#include <sys/systm.h>
46123474Swpaul#include <sys/sysctl.h>
47123474Swpaul#include <sys/mbuf.h>
48123474Swpaul#include <sys/malloc.h>
49123474Swpaul#include <sys/lock.h>
50123474Swpaul#include <sys/mutex.h>
51123474Swpaul#include <sys/kernel.h>
52123474Swpaul#include <sys/socket.h>
53123474Swpaul#include <sys/sockio.h>
54123474Swpaul#include <sys/errno.h>
55123474Swpaul#include <sys/callout.h>
56123474Swpaul#include <sys/bus.h>
57123474Swpaul#include <sys/endian.h>
58123474Swpaul#include <sys/kthread.h>
59123474Swpaul#include <sys/taskqueue.h>
60123474Swpaul#include <sys/priv.h>
61123695Swpaul
62123695Swpaul#include <machine/bus.h>
63123695Swpaul
64123474Swpaul#include <net/if.h>
65123474Swpaul#include <net/if_dl.h>
66123474Swpaul#include <net/if_media.h>
67123474Swpaul#include <net/if_types.h>
68123474Swpaul#include <net/if_arp.h>
69123474Swpaul#include <net/ethernet.h>
70123474Swpaul#include <net/if_llc.h>
71123474Swpaul
72123474Swpaul#include <net80211/ieee80211_var.h>
73123474Swpaul#include <net80211/ieee80211_regdomain.h>
74123474Swpaul#ifdef IEEE80211_SUPPORT_SUPERG
75123474Swpaul#include <net80211/ieee80211_superg.h>
76123474Swpaul#endif
77123474Swpaul#ifdef IEEE80211_SUPPORT_TDMA
78123474Swpaul#include <net80211/ieee80211_tdma.h>
79123474Swpaul#endif
80123474Swpaul
81123474Swpaul#include <net/bpf.h>
82123535Swpaul
83123474Swpaul#ifdef INET
84123474Swpaul#include <netinet/in.h>
85123474Swpaul#include <netinet/if_ether.h>
86123474Swpaul#endif
87123474Swpaul
88123474Swpaul#include <dev/ath/if_athvar.h>
89123474Swpaul#include <dev/ath/ath_hal/ah_devid.h>		/* XXX for softled */
90123474Swpaul#include <dev/ath/ath_hal/ah_diagcodes.h>
91123474Swpaul
92123474Swpaul#include <dev/ath/if_ath_debug.h>
93123474Swpaul#include <dev/ath/if_ath_misc.h>
94123474Swpaul#include <dev/ath/if_ath_tx.h>
95123474Swpaul
96123474Swpaul#ifdef ATH_TX99_DIAG
97123474Swpaul#include <dev/ath/ath_tx99/ath_tx99.h>
98123474Swpaul#endif
99123474Swpaul
100123474Swpaul/*
101123474Swpaul * ATH_BCBUF determines the number of vap's that can transmit
102123474Swpaul * beacons and also (currently) the number of vap's that can
103123474Swpaul * have unique mac addresses/bssid.  When staggering beacons
104123474Swpaul * 4 is probably a good max as otherwise the beacons become
105123474Swpaul * very closely spaced and there is limited time for cab q traffic
106123474Swpaul * to go out.  You can burst beacons instead but that is not good
107123474Swpaul * for stations in power save and at some point you really want
108123474Swpaul * another radio (and channel).
109123474Swpaul *
110123474Swpaul * The limit on the number of mac addresses is tied to our use of
111123474Swpaul * the U/L bit and tracking addresses in a byte; it would be
112123474Swpaul * worthwhile to allow more for applications like proxy sta.
113123474Swpaul */
114123474SwpaulCTASSERT(ATH_BCBUF <= 8);
115123474Swpaul
116123474Swpaulstatic struct ieee80211vap *ath_vap_create(struct ieee80211com *,
117123474Swpaul		    const char name[IFNAMSIZ], int unit, int opmode,
118123474Swpaul		    int flags, const uint8_t bssid[IEEE80211_ADDR_LEN],
119123474Swpaul		    const uint8_t mac[IEEE80211_ADDR_LEN]);
120123474Swpaulstatic void	ath_vap_delete(struct ieee80211vap *);
121123474Swpaulstatic void	ath_init(void *);
122123474Swpaulstatic void	ath_stop_locked(struct ifnet *);
123123474Swpaulstatic void	ath_stop(struct ifnet *);
124123695Swpaulstatic void	ath_start(struct ifnet *);
125123695Swpaulstatic int	ath_reset(struct ifnet *);
126123695Swpaulstatic int	ath_reset_vap(struct ieee80211vap *, u_long);
127123695Swpaulstatic int	ath_media_change(struct ifnet *);
128123695Swpaulstatic void	ath_watchdog(void *);
129123474Swpaulstatic int	ath_ioctl(struct ifnet *, u_long, caddr_t);
130123474Swpaulstatic void	ath_fatal_proc(void *, int);
131123474Swpaulstatic void	ath_bmiss_vap(struct ieee80211vap *);
132123474Swpaulstatic void	ath_bmiss_proc(void *, int);
133123535Swpaulstatic int	ath_keyset(struct ath_softc *, const struct ieee80211_key *,
134123535Swpaul			struct ieee80211_node *);
135123535Swpaulstatic int	ath_key_alloc(struct ieee80211vap *,
136123535Swpaul			struct ieee80211_key *,
137123695Swpaul			ieee80211_keyix *, ieee80211_keyix *);
138123695Swpaulstatic int	ath_key_delete(struct ieee80211vap *,
139123695Swpaul			const struct ieee80211_key *);
140123695Swpaulstatic int	ath_key_set(struct ieee80211vap *, const struct ieee80211_key *,
141123695Swpaul			const u_int8_t mac[IEEE80211_ADDR_LEN]);
142123535Swpaulstatic void	ath_key_update_begin(struct ieee80211vap *);
143123535Swpaulstatic void	ath_key_update_end(struct ieee80211vap *);
144123535Swpaulstatic void	ath_update_mcast(struct ifnet *);
145123535Swpaulstatic void	ath_update_promisc(struct ifnet *);
146123474Swpaulstatic void	ath_mode_init(struct ath_softc *);
147123474Swpaulstatic void	ath_setslottime(struct ath_softc *);
148123474Swpaulstatic void	ath_updateslot(struct ifnet *);
149123474Swpaulstatic int	ath_beaconq_setup(struct ath_hal *);
150123474Swpaulstatic int	ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
151123474Swpaulstatic void	ath_beacon_update(struct ieee80211vap *, int item);
152123474Swpaulstatic void	ath_beacon_setup(struct ath_softc *, struct ath_buf *);
153123474Swpaulstatic void	ath_beacon_proc(void *, int);
154123474Swpaulstatic struct ath_buf *ath_beacon_generate(struct ath_softc *,
155123474Swpaul			struct ieee80211vap *);
156123474Swpaulstatic void	ath_bstuck_proc(void *, int);
157123474Swpaulstatic void	ath_beacon_return(struct ath_softc *, struct ath_buf *);
158123474Swpaulstatic void	ath_beacon_free(struct ath_softc *);
159123474Swpaulstatic void	ath_beacon_config(struct ath_softc *, struct ieee80211vap *);
160123474Swpaulstatic void	ath_descdma_cleanup(struct ath_softc *sc,
161123474Swpaul			struct ath_descdma *, ath_bufhead *);
162123474Swpaulstatic int	ath_desc_alloc(struct ath_softc *);
163123474Swpaulstatic void	ath_desc_free(struct ath_softc *);
164123474Swpaulstatic struct ieee80211_node *ath_node_alloc(struct ieee80211vap *,
165123474Swpaul			const uint8_t [IEEE80211_ADDR_LEN]);
166123474Swpaulstatic void	ath_node_free(struct ieee80211_node *);
167123474Swpaulstatic void	ath_node_getsignal(const struct ieee80211_node *,
168123474Swpaul			int8_t *, int8_t *);
169123474Swpaulstatic int	ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
170123474Swpaulstatic void	ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
171123474Swpaul			int subtype, int rssi, int nf);
172123474Swpaulstatic void	ath_setdefantenna(struct ath_softc *, u_int);
173123474Swpaulstatic void	ath_rx_proc(void *, int);
174123474Swpaulstatic void	ath_txq_init(struct ath_softc *sc, struct ath_txq *, int);
175123474Swpaulstatic struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
176123474Swpaulstatic int	ath_tx_setup(struct ath_softc *, int, int);
177123474Swpaulstatic int	ath_wme_update(struct ieee80211com *);
178123474Swpaulstatic void	ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
179123474Swpaulstatic void	ath_tx_cleanup(struct ath_softc *);
180123474Swpaulstatic void	ath_tx_proc_q0(void *, int);
181123474Swpaulstatic void	ath_tx_proc_q0123(void *, int);
182123474Swpaulstatic void	ath_tx_proc(void *, int);
183123474Swpaulstatic void	ath_tx_draintxq(struct ath_softc *, struct ath_txq *);
184123474Swpaulstatic int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
185123474Swpaulstatic void	ath_draintxq(struct ath_softc *);
186123474Swpaulstatic void	ath_stoprecv(struct ath_softc *);
187123474Swpaulstatic int	ath_startrecv(struct ath_softc *);
188123474Swpaulstatic void	ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
189123474Swpaulstatic void	ath_scan_start(struct ieee80211com *);
190123474Swpaulstatic void	ath_scan_end(struct ieee80211com *);
191123474Swpaulstatic void	ath_set_channel(struct ieee80211com *);
192123474Swpaulstatic void	ath_calibrate(void *);
193123474Swpaulstatic int	ath_newstate(struct ieee80211vap *, enum ieee80211_state, int);
194123474Swpaulstatic void	ath_setup_stationkey(struct ieee80211_node *);
195123474Swpaulstatic void	ath_newassoc(struct ieee80211_node *, int);
196123474Swpaulstatic int	ath_setregdomain(struct ieee80211com *,
197123474Swpaul		    struct ieee80211_regdomain *, int,
198123474Swpaul		    struct ieee80211_channel []);
199123474Swpaulstatic void	ath_getradiocaps(struct ieee80211com *, int, int *,
200123474Swpaul		    struct ieee80211_channel []);
201123474Swpaulstatic int	ath_getchannels(struct ath_softc *);
202123474Swpaulstatic void	ath_led_event(struct ath_softc *, int);
203123474Swpaul
204123474Swpaulstatic int	ath_rate_setup(struct ath_softc *, u_int mode);
205123474Swpaulstatic void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
206123474Swpaul
207123474Swpaulstatic void	ath_sysctlattach(struct ath_softc *);
208123474Swpaulstatic void	ath_announce(struct ath_softc *);
209123474Swpaulstatic void	ath_sysctl_stats_attach(struct ath_softc *sc);
210123474Swpaul
211123474Swpaul#ifdef IEEE80211_SUPPORT_TDMA
212123474Swpaulstatic void	ath_tdma_settimers(struct ath_softc *sc, u_int32_t nexttbtt,
213123474Swpaul		    u_int32_t bintval);
214123474Swpaulstatic void	ath_tdma_bintvalsetup(struct ath_softc *sc,
215123474Swpaul		    const struct ieee80211_tdma_state *tdma);
216123474Swpaulstatic void	ath_tdma_config(struct ath_softc *sc, struct ieee80211vap *vap);
217123474Swpaulstatic void	ath_tdma_update(struct ieee80211_node *ni,
218123474Swpaul		    const struct ieee80211_tdma_param *tdma, int);
219123474Swpaulstatic void	ath_tdma_beacon_send(struct ath_softc *sc,
220123474Swpaul		    struct ieee80211vap *vap);
221123474Swpaul
222123474Swpaulstatic __inline void
223123474Swpaulath_hal_setcca(struct ath_hal *ah, int ena)
224123474Swpaul{
225123474Swpaul	/*
226123474Swpaul	 * NB: fill me in; this is not provided by default because disabling
227123474Swpaul	 *     CCA in most locales violates regulatory.
228123620Swpaul	 */
229123620Swpaul}
230123620Swpaul
231123620Swpaulstatic __inline int
232123474Swpaulath_hal_getcca(struct ath_hal *ah)
233123474Swpaul{
234123474Swpaul	u_int32_t diag;
235123474Swpaul	if (ath_hal_getcapability(ah, HAL_CAP_DIAG, 0, &diag) != HAL_OK)
236123474Swpaul		return 1;
237123474Swpaul	return ((diag & 0x500000) == 0);
238123474Swpaul}
239123474Swpaul
240123474Swpaul#define	TDMA_EP_MULTIPLIER	(1<<10) /* pow2 to optimize out * and / */
241123474Swpaul#define	TDMA_LPF_LEN		6
242123474Swpaul#define	TDMA_DUMMY_MARKER	0x127
243123474Swpaul#define	TDMA_EP_MUL(x, mul)	((x) * (mul))
244123474Swpaul#define	TDMA_IN(x)		(TDMA_EP_MUL((x), TDMA_EP_MULTIPLIER))
245123474Swpaul#define	TDMA_LPF(x, y, len) \
246123474Swpaul    ((x != TDMA_DUMMY_MARKER) ? (((x) * ((len)-1) + (y)) / (len)) : (y))
247123474Swpaul#define	TDMA_SAMPLE(x, y) do {					\
248123474Swpaul	x = TDMA_LPF((x), TDMA_IN(y), TDMA_LPF_LEN);		\
249123474Swpaul} while (0)
250123474Swpaul#define	TDMA_EP_RND(x,mul) \
251123474Swpaul	((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
252123474Swpaul#define	TDMA_AVG(x)		TDMA_EP_RND(x, TDMA_EP_MULTIPLIER)
253123474Swpaul#endif /* IEEE80211_SUPPORT_TDMA */
254123474Swpaul
255123474SwpaulSYSCTL_DECL(_hw_ath);
256123474Swpaul
257123474Swpaul/* XXX validate sysctl values */
258123474Swpaulstatic	int ath_longcalinterval = 30;		/* long cals every 30 secs */
259123474SwpaulSYSCTL_INT(_hw_ath, OID_AUTO, longcal, CTLFLAG_RW, &ath_longcalinterval,
260123474Swpaul	    0, "long chip calibration interval (secs)");
261123474Swpaulstatic	int ath_shortcalinterval = 100;		/* short cals every 100 ms */
262123474SwpaulSYSCTL_INT(_hw_ath, OID_AUTO, shortcal, CTLFLAG_RW, &ath_shortcalinterval,
263123474Swpaul	    0, "short chip calibration interval (msecs)");
264123474Swpaulstatic	int ath_resetcalinterval = 20*60;	/* reset cal state 20 mins */
265123474SwpaulSYSCTL_INT(_hw_ath, OID_AUTO, resetcal, CTLFLAG_RW, &ath_resetcalinterval,
266123474Swpaul	    0, "reset chip calibration results (secs)");
267123474Swpaulstatic	int ath_anicalinterval = 100;		/* ANI calibration - 100 msec */
268123474SwpaulSYSCTL_INT(_hw_ath, OID_AUTO, anical, CTLFLAG_RW, &ath_anicalinterval,
269123474Swpaul	    0, "ANI calibration (msecs)");
270123474Swpaul
271123474Swpaulstatic	int ath_rxbuf = ATH_RXBUF;		/* # rx buffers to allocate */
272123474SwpaulSYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RW, &ath_rxbuf,
273123474Swpaul	    0, "rx buffers allocated");
274123474SwpaulTUNABLE_INT("hw.ath.rxbuf", &ath_rxbuf);
275123474Swpaulstatic	int ath_txbuf = ATH_TXBUF;		/* # tx buffers to allocate */
276123474SwpaulSYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RW, &ath_txbuf,
277123474Swpaul	    0, "tx buffers allocated");
278123474SwpaulTUNABLE_INT("hw.ath.txbuf", &ath_txbuf);
279123474Swpaul
280123474Swpaulstatic	int ath_bstuck_threshold = 4;		/* max missed beacons */
281123474SwpaulSYSCTL_INT(_hw_ath, OID_AUTO, bstuck, CTLFLAG_RW, &ath_bstuck_threshold,
282123474Swpaul	    0, "max missed beacon xmits before chip reset");
283123474Swpaul
284123474SwpaulMALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
285123474Swpaul
286123474Swpaulint
287123474Swpaulath_attach(u_int16_t devid, struct ath_softc *sc)
288123474Swpaul{
289123474Swpaul	struct ifnet *ifp;
290123474Swpaul	struct ieee80211com *ic;
291123474Swpaul	struct ath_hal *ah = NULL;
292123474Swpaul	HAL_STATUS status;
293123474Swpaul	int error = 0, i;
294123474Swpaul	u_int wmodes;
295123474Swpaul	uint8_t macaddr[IEEE80211_ADDR_LEN];
296123474Swpaul
297123474Swpaul	DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
298123474Swpaul
299123474Swpaul	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
300123474Swpaul	if (ifp == NULL) {
301123474Swpaul		device_printf(sc->sc_dev, "can not if_alloc()\n");
302123474Swpaul		error = ENOSPC;
303123474Swpaul		goto bad;
304123474Swpaul	}
305123474Swpaul	ic = ifp->if_l2com;
306123474Swpaul
307123474Swpaul	/* set these up early for if_printf use */
308123474Swpaul	if_initname(ifp, device_get_name(sc->sc_dev),
309123474Swpaul		device_get_unit(sc->sc_dev));
310123474Swpaul
311123474Swpaul	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, sc->sc_eepromdata, &status);
312123474Swpaul	if (ah == NULL) {
313123474Swpaul		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
314123474Swpaul			status);
315123474Swpaul		error = ENXIO;
316123474Swpaul		goto bad;
317123474Swpaul	}
318123474Swpaul	sc->sc_ah = ah;
319123474Swpaul	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
320123474Swpaul#ifdef	ATH_DEBUG
321123474Swpaul	sc->sc_debug = ath_debug;
322123474Swpaul#endif
323123474Swpaul
324123474Swpaul	/*
325123474Swpaul	 * Check if the MAC has multi-rate retry support.
326123474Swpaul	 * We do this by trying to setup a fake extended
327123474Swpaul	 * descriptor.  MAC's that don't have support will
328123474Swpaul	 * return false w/o doing anything.  MAC's that do
329123474Swpaul	 * support it will return true w/o doing anything.
330123474Swpaul	 */
331123474Swpaul	sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
332123474Swpaul
333123474Swpaul	/*
334123474Swpaul	 * Check if the device has hardware counters for PHY
335123474Swpaul	 * errors.  If so we need to enable the MIB interrupt
336123474Swpaul	 * so we can act on stat triggers.
337123535Swpaul	 */
338123474Swpaul	if (ath_hal_hwphycounters(ah))
339123474Swpaul		sc->sc_needmib = 1;
340123474Swpaul
341123474Swpaul	/*
342123474Swpaul	 * Get the hardware key cache size.
343123535Swpaul	 */
344123535Swpaul	sc->sc_keymax = ath_hal_keycachesize(ah);
345123535Swpaul	if (sc->sc_keymax > ATH_KEYMAX) {
346123535Swpaul		if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
347123535Swpaul			ATH_KEYMAX, sc->sc_keymax);
348123535Swpaul		sc->sc_keymax = ATH_KEYMAX;
349123535Swpaul	}
350123535Swpaul	/*
351123536Swpaul	 * Reset the key cache since some parts do not
352123474Swpaul	 * reset the contents on initial power up.
353123474Swpaul	 */
354123474Swpaul	for (i = 0; i < sc->sc_keymax; i++)
355123474Swpaul		ath_hal_keyreset(ah, i);
356123474Swpaul
357123474Swpaul	/*
358123474Swpaul	 * Collect the default channel list.
359123474Swpaul	 */
360123474Swpaul	error = ath_getchannels(sc);
361123474Swpaul	if (error != 0)
362123474Swpaul		goto bad;
363123474Swpaul
364123474Swpaul	/*
365123474Swpaul	 * Setup rate tables for all potential media types.
366123474Swpaul	 */
367123474Swpaul	ath_rate_setup(sc, IEEE80211_MODE_11A);
368123474Swpaul	ath_rate_setup(sc, IEEE80211_MODE_11B);
369123474Swpaul	ath_rate_setup(sc, IEEE80211_MODE_11G);
370123474Swpaul	ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
371123474Swpaul	ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
372123474Swpaul	ath_rate_setup(sc, IEEE80211_MODE_STURBO_A);
373123474Swpaul	ath_rate_setup(sc, IEEE80211_MODE_11NA);
374123474Swpaul	ath_rate_setup(sc, IEEE80211_MODE_11NG);
375123474Swpaul	ath_rate_setup(sc, IEEE80211_MODE_HALF);
376123474Swpaul	ath_rate_setup(sc, IEEE80211_MODE_QUARTER);
377123474Swpaul
378123474Swpaul	/* NB: setup here so ath_rate_update is happy */
379123474Swpaul	ath_setcurmode(sc, IEEE80211_MODE_11A);
380123474Swpaul
381123474Swpaul	/*
382123474Swpaul	 * Allocate tx+rx descriptors and populate the lists.
383123474Swpaul	 */
384123474Swpaul	error = ath_desc_alloc(sc);
385123474Swpaul	if (error != 0) {
386123474Swpaul		if_printf(ifp, "failed to allocate descriptors: %d\n", error);
387123474Swpaul		goto bad;
388123474Swpaul	}
389123474Swpaul	callout_init_mtx(&sc->sc_cal_ch, &sc->sc_mtx, 0);
390123474Swpaul	callout_init_mtx(&sc->sc_wd_ch, &sc->sc_mtx, 0);
391123474Swpaul
392123474Swpaul	ATH_TXBUF_LOCK_INIT(sc);
393123474Swpaul
394123474Swpaul	sc->sc_tq = taskqueue_create("ath_taskq", M_NOWAIT,
395123474Swpaul		taskqueue_thread_enqueue, &sc->sc_tq);
396123474Swpaul	taskqueue_start_threads(&sc->sc_tq, 1, PI_NET,
397123474Swpaul		"%s taskq", ifp->if_xname);
398123474Swpaul
399123474Swpaul	TASK_INIT(&sc->sc_rxtask, 0, ath_rx_proc, sc);
400123474Swpaul	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
401123474Swpaul	TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_proc, sc);
402123474Swpaul
403123474Swpaul	/*
404123474Swpaul	 * Allocate hardware transmit queues: one queue for
405123474Swpaul	 * beacon frames and one data queue for each QoS
406123474Swpaul	 * priority.  Note that the hal handles resetting
407123474Swpaul	 * these queues at the needed time.
408123474Swpaul	 *
409123474Swpaul	 * XXX PS-Poll
410123474Swpaul	 */
411123474Swpaul	sc->sc_bhalq = ath_beaconq_setup(ah);
412123474Swpaul	if (sc->sc_bhalq == (u_int) -1) {
413123474Swpaul		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
414123474Swpaul		error = EIO;
415123474Swpaul		goto bad2;
416123474Swpaul	}
417123474Swpaul	sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
418123474Swpaul	if (sc->sc_cabq == NULL) {
419123474Swpaul		if_printf(ifp, "unable to setup CAB xmit queue!\n");
420123474Swpaul		error = EIO;
421123474Swpaul		goto bad2;
422123474Swpaul	}
423123474Swpaul	/* NB: insure BK queue is the lowest priority h/w queue */
424123474Swpaul	if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
425123474Swpaul		if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
426123474Swpaul			ieee80211_wme_acnames[WME_AC_BK]);
427123474Swpaul		error = EIO;
428123474Swpaul		goto bad2;
429123474Swpaul	}
430123474Swpaul	if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
431123474Swpaul	    !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
432123474Swpaul	    !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
433123474Swpaul		/*
434123474Swpaul		 * Not enough hardware tx queues to properly do WME;
435123474Swpaul		 * just punt and assign them all to the same h/w queue.
436123474Swpaul		 * We could do a better job of this if, for example,
437123474Swpaul		 * we allocate queues when we switch from station to
438123474Swpaul		 * AP mode.
439123474Swpaul		 */
440123474Swpaul		if (sc->sc_ac2q[WME_AC_VI] != NULL)
441123474Swpaul			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
442123474Swpaul		if (sc->sc_ac2q[WME_AC_BE] != NULL)
443123474Swpaul			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
444123474Swpaul		sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
445123474Swpaul		sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
446123474Swpaul		sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
447123474Swpaul	}
448123474Swpaul
449123474Swpaul	/*
450123474Swpaul	 * Special case certain configurations.  Note the
451123474Swpaul	 * CAB queue is handled by these specially so don't
452123474Swpaul	 * include them when checking the txq setup mask.
453123474Swpaul	 */
454123474Swpaul	switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
455123474Swpaul	case 0x01:
456123474Swpaul		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
457123474Swpaul		break;
458123474Swpaul	case 0x0f:
459123474Swpaul		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
460123474Swpaul		break;
461123474Swpaul	default:
462123474Swpaul		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
463123474Swpaul		break;
464123474Swpaul	}
465123474Swpaul
466123474Swpaul	/*
467123474Swpaul	 * Setup rate control.  Some rate control modules
468123474Swpaul	 * call back to change the anntena state so expose
469123474Swpaul	 * the necessary entry points.
470123474Swpaul	 * XXX maybe belongs in struct ath_ratectrl?
471123474Swpaul	 */
472123474Swpaul	sc->sc_setdefantenna = ath_setdefantenna;
473123474Swpaul	sc->sc_rc = ath_rate_attach(sc);
474123474Swpaul	if (sc->sc_rc == NULL) {
475123474Swpaul		error = EIO;
476123474Swpaul		goto bad2;
477123535Swpaul	}
478123474Swpaul
479123474Swpaul	sc->sc_blinking = 0;
480123474Swpaul	sc->sc_ledstate = 1;
481123474Swpaul	sc->sc_ledon = 0;			/* low true */
482123474Swpaul	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
483123474Swpaul	callout_init(&sc->sc_ledtimer, CALLOUT_MPSAFE);
484123474Swpaul	/*
485123474Swpaul	 * Auto-enable soft led processing for IBM cards and for
486123474Swpaul	 * 5211 minipci cards.  Users can also manually enable/disable
487123474Swpaul	 * support with a sysctl.
488123474Swpaul	 */
489123757Swpaul	sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
490123757Swpaul	if (sc->sc_softled) {
491123535Swpaul		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin,
492123535Swpaul		    HAL_GPIO_MUX_MAC_NETWORK_LED);
493123535Swpaul		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
494123535Swpaul	}
495123474Swpaul
496123474Swpaul	ifp->if_softc = sc;
497123474Swpaul	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
498123474Swpaul	ifp->if_start = ath_start;
499123474Swpaul	ifp->if_ioctl = ath_ioctl;
500123474Swpaul	ifp->if_init = ath_init;
501123474Swpaul	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
502123474Swpaul	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
503123474Swpaul	IFQ_SET_READY(&ifp->if_snd);
504123474Swpaul
505123474Swpaul	ic->ic_ifp = ifp;
506123474Swpaul	/* XXX not right but it's not used anywhere important */
507123474Swpaul	ic->ic_phytype = IEEE80211_T_OFDM;
508123474Swpaul	ic->ic_opmode = IEEE80211_M_STA;
509123474Swpaul	ic->ic_caps =
510123474Swpaul		  IEEE80211_C_STA		/* station mode */
511123474Swpaul		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
512123474Swpaul		| IEEE80211_C_HOSTAP		/* hostap mode */
513123474Swpaul		| IEEE80211_C_MONITOR		/* monitor mode */
514123474Swpaul		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
515123474Swpaul		| IEEE80211_C_WDS		/* 4-address traffic works */
516123474Swpaul		| IEEE80211_C_MBSS		/* mesh point link mode */
517123474Swpaul		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
518123474Swpaul		| IEEE80211_C_SHSLOT		/* short slot time supported */
519123474Swpaul		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
520123474Swpaul		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
521123474Swpaul		| IEEE80211_C_TXFRAG		/* handle tx frags */
522123474Swpaul		;
523123474Swpaul	/*
524123474Swpaul	 * Query the hal to figure out h/w crypto support.
525123474Swpaul	 */
526123474Swpaul	if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
527123474Swpaul		ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP;
528123474Swpaul	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
529123474Swpaul		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_OCB;
530123474Swpaul	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
531123474Swpaul		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_CCM;
532123474Swpaul	if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
533123474Swpaul		ic->ic_cryptocaps |= IEEE80211_CRYPTO_CKIP;
534123474Swpaul	if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
535123474Swpaul		ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIP;
536123474Swpaul		/*
537123474Swpaul		 * Check if h/w does the MIC and/or whether the
538123474Swpaul		 * separate key cache entries are required to
539123474Swpaul		 * handle both tx+rx MIC keys.
540123474Swpaul		 */
541123474Swpaul		if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
542123474Swpaul			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
543123474Swpaul		/*
544123474Swpaul		 * If the h/w supports storing tx+rx MIC keys
545123474Swpaul		 * in one cache slot automatically enable use.
546123474Swpaul		 */
547123474Swpaul		if (ath_hal_hastkipsplit(ah) ||
548123810Salfred		    !ath_hal_settkipsplit(ah, AH_FALSE))
549123474Swpaul			sc->sc_splitmic = 1;
550123474Swpaul		/*
551123474Swpaul		 * If the h/w can do TKIP MIC together with WME then
552123474Swpaul		 * we use it; otherwise we force the MIC to be done
553123474Swpaul		 * in software by the net80211 layer.
554123474Swpaul		 */
555123474Swpaul		if (ath_hal_haswmetkipmic(ah))
556123474Swpaul			sc->sc_wmetkipmic = 1;
557123757Swpaul	}
558123474Swpaul	sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
559123474Swpaul	/*
560123474Swpaul	 * Check for multicast key search support.
561123474Swpaul	 */
562123474Swpaul	if (ath_hal_hasmcastkeysearch(sc->sc_ah) &&
563123474Swpaul	    !ath_hal_getmcastkeysearch(sc->sc_ah)) {
564123474Swpaul		ath_hal_setmcastkeysearch(sc->sc_ah, 1);
565123474Swpaul	}
566123474Swpaul	sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
567123474Swpaul	/*
568123474Swpaul	 * Mark key cache slots associated with global keys
569123474Swpaul	 * as in use.  If we knew TKIP was not to be used we
570123474Swpaul	 * could leave the +32, +64, and +32+64 slots free.
571123474Swpaul	 */
572123474Swpaul	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
573123474Swpaul		setbit(sc->sc_keymap, i);
574123474Swpaul		setbit(sc->sc_keymap, i+64);
575123474Swpaul		if (sc->sc_splitmic) {
576123474Swpaul			setbit(sc->sc_keymap, i+32);
577123474Swpaul			setbit(sc->sc_keymap, i+32+64);
578123474Swpaul		}
579123474Swpaul	}
580123474Swpaul	/*
581123474Swpaul	 * TPC support can be done either with a global cap or
582123474Swpaul	 * per-packet support.  The latter is not available on
583123474Swpaul	 * all parts.  We're a bit pedantic here as all parts
584123474Swpaul	 * support a global cap.
585123474Swpaul	 */
586123474Swpaul	if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
587123474Swpaul		ic->ic_caps |= IEEE80211_C_TXPMGT;
588123474Swpaul
589123474Swpaul	/*
590123474Swpaul	 * Mark WME capability only if we have sufficient
591123474Swpaul	 * hardware queues to do proper priority scheduling.
592123474Swpaul	 */
593123474Swpaul	if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
594123474Swpaul		ic->ic_caps |= IEEE80211_C_WME;
595123474Swpaul	/*
596123474Swpaul	 * Check for misc other capabilities.
597123474Swpaul	 */
598123474Swpaul	if (ath_hal_hasbursting(ah))
599123474Swpaul		ic->ic_caps |= IEEE80211_C_BURST;
600123474Swpaul	sc->sc_hasbmask = ath_hal_hasbssidmask(ah);
601123474Swpaul	sc->sc_hasbmatch = ath_hal_hasbssidmatch(ah);
602123474Swpaul	sc->sc_hastsfadd = ath_hal_hastsfadjust(ah);
603123474Swpaul	if (ath_hal_hasfastframes(ah))
604123474Swpaul		ic->ic_caps |= IEEE80211_C_FF;
605123474Swpaul	wmodes = ath_hal_getwirelessmodes(ah);
606123474Swpaul	if (wmodes & (HAL_MODE_108G|HAL_MODE_TURBO))
607123474Swpaul		ic->ic_caps |= IEEE80211_C_TURBOP;
608123474Swpaul#ifdef IEEE80211_SUPPORT_TDMA
609123474Swpaul	if (ath_hal_macversion(ah) > 0x78) {
610123474Swpaul		ic->ic_caps |= IEEE80211_C_TDMA; /* capable of TDMA */
611123474Swpaul		ic->ic_tdma_update = ath_tdma_update;
612123474Swpaul	}
613123695Swpaul#endif
614123695Swpaul	/*
615123474Swpaul	 * Indicate we need the 802.11 header padded to a
616123474Swpaul	 * 32-bit boundary for 4-address and QoS frames.
617123474Swpaul	 */
618123474Swpaul	ic->ic_flags |= IEEE80211_F_DATAPAD;
619123474Swpaul
620123474Swpaul	/*
621123474Swpaul	 * Query the hal about antenna support.
622123474Swpaul	 */
623123695Swpaul	sc->sc_defant = ath_hal_getdefantenna(ah);
624123695Swpaul
625123695Swpaul	/*
626123695Swpaul	 * Not all chips have the VEOL support we want to
627123757Swpaul	 * use with IBSS beacons; check here for it.
628123695Swpaul	 */
629123695Swpaul	sc->sc_hasveol = ath_hal_hasveol(ah);
630123695Swpaul
631123474Swpaul	/* get mac address from hardware */
632123474Swpaul	ath_hal_getmac(ah, macaddr);
633123474Swpaul	if (sc->sc_hasbmask)
634123474Swpaul		ath_hal_getbssidmask(ah, sc->sc_hwbssidmask);
635123474Swpaul
636123474Swpaul	/* NB: used to size node table key mapping array */
637123474Swpaul	ic->ic_max_keyix = sc->sc_keymax;
638123474Swpaul	/* call MI attach routine. */
639123474Swpaul	ieee80211_ifattach(ic, macaddr);
640123474Swpaul	ic->ic_setregdomain = ath_setregdomain;
641123474Swpaul	ic->ic_getradiocaps = ath_getradiocaps;
642123474Swpaul	sc->sc_opmode = HAL_M_STA;
643123474Swpaul
644123474Swpaul	/* override default methods */
645123474Swpaul	ic->ic_newassoc = ath_newassoc;
646123474Swpaul	ic->ic_updateslot = ath_updateslot;
647123474Swpaul	ic->ic_wme.wme_update = ath_wme_update;
648123474Swpaul	ic->ic_vap_create = ath_vap_create;
649123474Swpaul	ic->ic_vap_delete = ath_vap_delete;
650123474Swpaul	ic->ic_raw_xmit = ath_raw_xmit;
651123474Swpaul	ic->ic_update_mcast = ath_update_mcast;
652123474Swpaul	ic->ic_update_promisc = ath_update_promisc;
653123474Swpaul	ic->ic_node_alloc = ath_node_alloc;
654123474Swpaul	sc->sc_node_free = ic->ic_node_free;
655123474Swpaul	ic->ic_node_free = ath_node_free;
656123474Swpaul	ic->ic_node_getsignal = ath_node_getsignal;
657123474Swpaul	ic->ic_scan_start = ath_scan_start;
658123474Swpaul	ic->ic_scan_end = ath_scan_end;
659123474Swpaul	ic->ic_set_channel = ath_set_channel;
660123474Swpaul
661123474Swpaul	ieee80211_radiotap_attach(ic,
662123474Swpaul	    &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
663123474Swpaul		ATH_TX_RADIOTAP_PRESENT,
664123474Swpaul	    &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th),
665123474Swpaul		ATH_RX_RADIOTAP_PRESENT);
666123474Swpaul
667123474Swpaul	/*
668123474Swpaul	 * Setup dynamic sysctl's now that country code and
669123474Swpaul	 * regdomain are available from the hal.
670123474Swpaul	 */
671123474Swpaul	ath_sysctlattach(sc);
672123474Swpaul	ath_sysctl_stats_attach(sc);
673123474Swpaul
674123474Swpaul	if (bootverbose)
675123474Swpaul		ieee80211_announce(ic);
676123474Swpaul	ath_announce(sc);
677123474Swpaul	return 0;
678123474Swpaulbad2:
679123474Swpaul	ath_tx_cleanup(sc);
680123474Swpaul	ath_desc_free(sc);
681123474Swpaulbad:
682123474Swpaul	if (ah)
683123474Swpaul		ath_hal_detach(ah);
684123474Swpaul	if (ifp != NULL)
685123474Swpaul		if_free(ifp);
686123474Swpaul	sc->sc_invalid = 1;
687123474Swpaul	return error;
688123474Swpaul}
689123474Swpaul
690123474Swpaulint
691123474Swpaulath_detach(struct ath_softc *sc)
692123474Swpaul{
693123474Swpaul	struct ifnet *ifp = sc->sc_ifp;
694123474Swpaul
695123474Swpaul	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
696123474Swpaul		__func__, ifp->if_flags);
697123474Swpaul
698123474Swpaul	/*
699123535Swpaul	 * NB: the order of these is important:
700123535Swpaul	 * o stop the chip so no more interrupts will fire
701123474Swpaul	 * o call the 802.11 layer before detaching the hal to
702123474Swpaul	 *   insure callbacks into the driver to delete global
703123474Swpaul	 *   key cache entries can be handled
704123474Swpaul	 * o free the taskqueue which drains any pending tasks
705123474Swpaul	 * o reclaim the tx queue data structures after calling
706123535Swpaul	 *   the 802.11 layer as we'll get called back to reclaim
707123535Swpaul	 *   node state and potentially want to use them
708123535Swpaul	 * o to cleanup the tx queues the hal is called, so detach
709123535Swpaul	 *   it last
710123535Swpaul	 * Other than that, it's straightforward...
711123535Swpaul	 */
712123535Swpaul	ath_stop(ifp);
713123474Swpaul	ieee80211_ifdetach(ifp->if_l2com);
714123474Swpaul	taskqueue_free(sc->sc_tq);
715123474Swpaul#ifdef ATH_TX99_DIAG
716123474Swpaul	if (sc->sc_tx99 != NULL)
717123474Swpaul		sc->sc_tx99->detach(sc->sc_tx99);
718123474Swpaul#endif
719123474Swpaul	ath_rate_detach(sc->sc_rc);
720123474Swpaul	ath_desc_free(sc);
721123474Swpaul	ath_tx_cleanup(sc);
722123474Swpaul	ath_hal_detach(sc->sc_ah);	/* NB: sets chip in full sleep */
723123474Swpaul	if_free(ifp);
724123474Swpaul
725123474Swpaul	return 0;
726123474Swpaul}
727123474Swpaul
728123474Swpaul/*
729123474Swpaul * MAC address handling for multiple BSS on the same radio.
730123474Swpaul * The first vap uses the MAC address from the EEPROM.  For
731123474Swpaul * subsequent vap's we set the U/L bit (bit 1) in the MAC
732123474Swpaul * address and use the next six bits as an index.
733123474Swpaul */
734123474Swpaulstatic void
735123474Swpaulassign_address(struct ath_softc *sc, uint8_t mac[IEEE80211_ADDR_LEN], int clone)
736123474Swpaul{
737123474Swpaul	int i;
738123474Swpaul
739123474Swpaul	if (clone && sc->sc_hasbmask) {
740123474Swpaul		/* NB: we only do this if h/w supports multiple bssid */
741123474Swpaul		for (i = 0; i < 8; i++)
742123474Swpaul			if ((sc->sc_bssidmask & (1<<i)) == 0)
743123474Swpaul				break;
744123474Swpaul		if (i != 0)
745123474Swpaul			mac[0] |= (i << 2)|0x2;
746123474Swpaul	} else
747123474Swpaul		i = 0;
748123474Swpaul	sc->sc_bssidmask |= 1<<i;
749123474Swpaul	sc->sc_hwbssidmask[0] &= ~mac[0];
750123474Swpaul	if (i == 0)
751123474Swpaul		sc->sc_nbssid0++;
752123474Swpaul}
753123474Swpaul
754123474Swpaulstatic void
755123474Swpaulreclaim_address(struct ath_softc *sc, const uint8_t mac[IEEE80211_ADDR_LEN])
756123474Swpaul{
757123474Swpaul	int i = mac[0] >> 2;
758123474Swpaul	uint8_t mask;
759123474Swpaul
760123474Swpaul	if (i != 0 || --sc->sc_nbssid0 == 0) {
761123474Swpaul		sc->sc_bssidmask &= ~(1<<i);
762123474Swpaul		/* recalculate bssid mask from remaining addresses */
763123474Swpaul		mask = 0xff;
764123474Swpaul		for (i = 1; i < 8; i++)
765123474Swpaul			if (sc->sc_bssidmask & (1<<i))
766123474Swpaul				mask &= ~((i<<2)|0x2);
767123474Swpaul		sc->sc_hwbssidmask[0] |= mask;
768123474Swpaul	}
769123474Swpaul}
770123474Swpaul
771123474Swpaul/*
772123474Swpaul * Assign a beacon xmit slot.  We try to space out
773123474Swpaul * assignments so when beacons are staggered the
774123474Swpaul * traffic coming out of the cab q has maximal time
775123474Swpaul * to go out before the next beacon is scheduled.
776123474Swpaul */
777123474Swpaulstatic int
778123474Swpaulassign_bslot(struct ath_softc *sc)
779123474Swpaul{
780123474Swpaul	u_int slot, free;
781123474Swpaul
782123474Swpaul	free = 0;
783123474Swpaul	for (slot = 0; slot < ATH_BCBUF; slot++)
784123474Swpaul		if (sc->sc_bslot[slot] == NULL) {
785123474Swpaul			if (sc->sc_bslot[(slot+1)%ATH_BCBUF] == NULL &&
786123474Swpaul			    sc->sc_bslot[(slot-1)%ATH_BCBUF] == NULL)
787123474Swpaul				return slot;
788123474Swpaul			free = slot;
789123474Swpaul			/* NB: keep looking for a double slot */
790123474Swpaul		}
791123474Swpaul	return free;
792123474Swpaul}
793123474Swpaul
794123474Swpaulstatic struct ieee80211vap *
795123474Swpaulath_vap_create(struct ieee80211com *ic,
796123474Swpaul	const char name[IFNAMSIZ], int unit, int opmode, int flags,
797123474Swpaul	const uint8_t bssid[IEEE80211_ADDR_LEN],
798123485Swpaul	const uint8_t mac0[IEEE80211_ADDR_LEN])
799123485Swpaul{
800123485Swpaul	struct ath_softc *sc = ic->ic_ifp->if_softc;
801123485Swpaul	struct ath_vap *avp;
802123474Swpaul	struct ieee80211vap *vap;
803123474Swpaul	uint8_t mac[IEEE80211_ADDR_LEN];
804123474Swpaul	int ic_opmode, needbeacon, error;
805123474Swpaul
806123474Swpaul	avp = (struct ath_vap *) malloc(sizeof(struct ath_vap),
807123474Swpaul	    M_80211_VAP, M_WAITOK | M_ZERO);
808123474Swpaul	needbeacon = 0;
809123474Swpaul	IEEE80211_ADDR_COPY(mac, mac0);
810123474Swpaul
811123474Swpaul	ATH_LOCK(sc);
812123474Swpaul	ic_opmode = opmode;		/* default to opmode of new vap */
813123474Swpaul	switch (opmode) {
814123474Swpaul	case IEEE80211_M_STA:
815123474Swpaul		if (sc->sc_nstavaps != 0) {	/* XXX only 1 for now */
816123474Swpaul			device_printf(sc->sc_dev, "only 1 sta vap supported\n");
817123474Swpaul			goto bad;
818123474Swpaul		}
819123474Swpaul		if (sc->sc_nvaps) {
820123474Swpaul			/*
821123474Swpaul			 * With multiple vaps we must fall back
822123474Swpaul			 * to s/w beacon miss handling.
823123474Swpaul			 */
824123474Swpaul			flags |= IEEE80211_CLONE_NOBEACONS;
825123474Swpaul		}
826123474Swpaul		if (flags & IEEE80211_CLONE_NOBEACONS) {
827123474Swpaul			/*
828123474Swpaul			 * Station mode w/o beacons are implemented w/ AP mode.
829123474Swpaul			 */
830123474Swpaul			ic_opmode = IEEE80211_M_HOSTAP;
831123474Swpaul		}
832123474Swpaul		break;
833123474Swpaul	case IEEE80211_M_IBSS:
834123474Swpaul		if (sc->sc_nvaps != 0) {	/* XXX only 1 for now */
835123474Swpaul			device_printf(sc->sc_dev,
836123474Swpaul			    "only 1 ibss vap supported\n");
837123474Swpaul			goto bad;
838123474Swpaul		}
839123474Swpaul		needbeacon = 1;
840123474Swpaul		break;
841123474Swpaul	case IEEE80211_M_AHDEMO:
842123474Swpaul#ifdef IEEE80211_SUPPORT_TDMA
843123474Swpaul		if (flags & IEEE80211_CLONE_TDMA) {
844123474Swpaul			if (sc->sc_nvaps != 0) {
845123474Swpaul				device_printf(sc->sc_dev,
846123474Swpaul				    "only 1 tdma vap supported\n");
847123474Swpaul				goto bad;
848123474Swpaul			}
849123474Swpaul			needbeacon = 1;
850123474Swpaul			flags |= IEEE80211_CLONE_NOBEACONS;
851123474Swpaul		}
852123474Swpaul		/* fall thru... */
853123474Swpaul#endif
854123474Swpaul	case IEEE80211_M_MONITOR:
855123474Swpaul		if (sc->sc_nvaps != 0 && ic->ic_opmode != opmode) {
856123474Swpaul			/*
857123474Swpaul			 * Adopt existing mode.  Adding a monitor or ahdemo
858123474Swpaul			 * vap to an existing configuration is of dubious
859123474Swpaul			 * value but should be ok.
860123474Swpaul			 */
861123474Swpaul			/* XXX not right for monitor mode */
862123474Swpaul			ic_opmode = ic->ic_opmode;
863123474Swpaul		}
864123474Swpaul		break;
865123474Swpaul	case IEEE80211_M_HOSTAP:
866123474Swpaul	case IEEE80211_M_MBSS:
867123474Swpaul		needbeacon = 1;
868123474Swpaul		break;
869123474Swpaul	case IEEE80211_M_WDS:
870123474Swpaul		if (sc->sc_nvaps != 0 && ic->ic_opmode == IEEE80211_M_STA) {
871123474Swpaul			device_printf(sc->sc_dev,
872123474Swpaul			    "wds not supported in sta mode\n");
873123474Swpaul			goto bad;
874123474Swpaul		}
875123474Swpaul		/*
876123474Swpaul		 * Silently remove any request for a unique
877123474Swpaul		 * bssid; WDS vap's always share the local
878123474Swpaul		 * mac address.
879123474Swpaul		 */
880123474Swpaul		flags &= ~IEEE80211_CLONE_BSSID;
881123474Swpaul		if (sc->sc_nvaps == 0)
882123474Swpaul			ic_opmode = IEEE80211_M_HOSTAP;
883123474Swpaul		else
884123474Swpaul			ic_opmode = ic->ic_opmode;
885123474Swpaul		break;
886123474Swpaul	default:
887123474Swpaul		device_printf(sc->sc_dev, "unknown opmode %d\n", opmode);
888123474Swpaul		goto bad;
889123474Swpaul	}
890123474Swpaul	/*
891123474Swpaul	 * Check that a beacon buffer is available; the code below assumes it.
892123474Swpaul	 */
893123474Swpaul	if (needbeacon & STAILQ_EMPTY(&sc->sc_bbuf)) {
894123474Swpaul		device_printf(sc->sc_dev, "no beacon buffer available\n");
895123474Swpaul		goto bad;
896123474Swpaul	}
897123474Swpaul
898123474Swpaul	/* STA, AHDEMO? */
899123474Swpaul	if (opmode == IEEE80211_M_HOSTAP || opmode == IEEE80211_M_MBSS) {
900123474Swpaul		assign_address(sc, mac, flags & IEEE80211_CLONE_BSSID);
901123474Swpaul		ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
902123474Swpaul	}
903123474Swpaul
904123474Swpaul	vap = &avp->av_vap;
905123474Swpaul	/* XXX can't hold mutex across if_alloc */
906123474Swpaul	ATH_UNLOCK(sc);
907123474Swpaul	error = ieee80211_vap_setup(ic, vap, name, unit, opmode, flags,
908123474Swpaul	    bssid, mac);
909123474Swpaul	ATH_LOCK(sc);
910123474Swpaul	if (error != 0) {
911123474Swpaul		device_printf(sc->sc_dev, "%s: error %d creating vap\n",
912123474Swpaul		    __func__, error);
913123474Swpaul		goto bad2;
914123474Swpaul	}
915123474Swpaul
916123474Swpaul	/* h/w crypto support */
917123474Swpaul	vap->iv_key_alloc = ath_key_alloc;
918123474Swpaul	vap->iv_key_delete = ath_key_delete;
919123474Swpaul	vap->iv_key_set = ath_key_set;
920123474Swpaul	vap->iv_key_update_begin = ath_key_update_begin;
921123474Swpaul	vap->iv_key_update_end = ath_key_update_end;
922123474Swpaul
923123474Swpaul	/* override various methods */
924123474Swpaul	avp->av_recv_mgmt = vap->iv_recv_mgmt;
925123474Swpaul	vap->iv_recv_mgmt = ath_recv_mgmt;
926123474Swpaul	vap->iv_reset = ath_reset_vap;
927123474Swpaul	vap->iv_update_beacon = ath_beacon_update;
928123474Swpaul	avp->av_newstate = vap->iv_newstate;
929123474Swpaul	vap->iv_newstate = ath_newstate;
930123474Swpaul	avp->av_bmiss = vap->iv_bmiss;
931123474Swpaul	vap->iv_bmiss = ath_bmiss_vap;
932123474Swpaul
933123474Swpaul	avp->av_bslot = -1;
934123474Swpaul	if (needbeacon) {
935123474Swpaul		/*
936123474Swpaul		 * Allocate beacon state and setup the q for buffered
937123474Swpaul		 * multicast frames.  We know a beacon buffer is
938123474Swpaul		 * available because we checked above.
939123695Swpaul		 */
940123695Swpaul		avp->av_bcbuf = STAILQ_FIRST(&sc->sc_bbuf);
941123474Swpaul		STAILQ_REMOVE_HEAD(&sc->sc_bbuf, bf_list);
942123474Swpaul		if (opmode != IEEE80211_M_IBSS || !sc->sc_hasveol) {
943123474Swpaul			/*
944123474Swpaul			 * Assign the vap to a beacon xmit slot.  As above
945123474Swpaul			 * this cannot fail to find a free one.
946123474Swpaul			 */
947123474Swpaul			avp->av_bslot = assign_bslot(sc);
948123474Swpaul			KASSERT(sc->sc_bslot[avp->av_bslot] == NULL,
949123695Swpaul			    ("beacon slot %u not empty", avp->av_bslot));
950123695Swpaul			sc->sc_bslot[avp->av_bslot] = vap;
951123695Swpaul			sc->sc_nbcnvaps++;
952123695Swpaul		}
953123695Swpaul		if (sc->sc_hastsfadd && sc->sc_nbcnvaps > 0) {
954123695Swpaul			/*
955123757Swpaul			 * Multple vaps are to transmit beacons and we
956123695Swpaul			 * have h/w support for TSF adjusting; enable
957123695Swpaul			 * use of staggered beacons.
958123695Swpaul			 */
959123474Swpaul			sc->sc_stagbeacons = 1;
960123474Swpaul		}
961123474Swpaul		ath_txq_init(sc, &avp->av_mcastq, ATH_TXQ_SWQ);
962123474Swpaul	}
963123474Swpaul
964123474Swpaul	ic->ic_opmode = ic_opmode;
965123474Swpaul	if (opmode != IEEE80211_M_WDS) {
966123474Swpaul		sc->sc_nvaps++;
967123474Swpaul		if (opmode == IEEE80211_M_STA)
968123474Swpaul			sc->sc_nstavaps++;
969123474Swpaul		if (opmode == IEEE80211_M_MBSS)
970123474Swpaul			sc->sc_nmeshvaps++;
971123474Swpaul	}
972123474Swpaul	switch (ic_opmode) {
973123474Swpaul	case IEEE80211_M_IBSS:
974123474Swpaul		sc->sc_opmode = HAL_M_IBSS;
975123474Swpaul		break;
976123474Swpaul	case IEEE80211_M_STA:
977123474Swpaul		sc->sc_opmode = HAL_M_STA;
978123474Swpaul		break;
979123474Swpaul	case IEEE80211_M_AHDEMO:
980123474Swpaul#ifdef IEEE80211_SUPPORT_TDMA
981123474Swpaul		if (vap->iv_caps & IEEE80211_C_TDMA) {
982123474Swpaul			sc->sc_tdma = 1;
983123474Swpaul			/* NB: disable tsf adjust */
984123474Swpaul			sc->sc_stagbeacons = 0;
985123474Swpaul		}
986123474Swpaul		/*
987123474Swpaul		 * NB: adhoc demo mode is a pseudo mode; to the hal it's
988123474Swpaul		 * just ap mode.
989123474Swpaul		 */
990123474Swpaul		/* fall thru... */
991123474Swpaul#endif
992123474Swpaul	case IEEE80211_M_HOSTAP:
993123474Swpaul	case IEEE80211_M_MBSS:
994123474Swpaul		sc->sc_opmode = HAL_M_HOSTAP;
995123474Swpaul		break;
996123474Swpaul	case IEEE80211_M_MONITOR:
997123474Swpaul		sc->sc_opmode = HAL_M_MONITOR;
998123474Swpaul		break;
999123474Swpaul	default:
1000123474Swpaul		/* XXX should not happen */
1001123474Swpaul		break;
1002123474Swpaul	}
1003123474Swpaul	if (sc->sc_hastsfadd) {
1004123474Swpaul		/*
1005123474Swpaul		 * Configure whether or not TSF adjust should be done.
1006123474Swpaul		 */
1007123474Swpaul		ath_hal_settsfadjust(sc->sc_ah, sc->sc_stagbeacons);
1008123474Swpaul	}
1009123474Swpaul	if (flags & IEEE80211_CLONE_NOBEACONS) {
1010123474Swpaul		/*
1011123474Swpaul		 * Enable s/w beacon miss handling.
1012123474Swpaul		 */
1013123474Swpaul		sc->sc_swbmiss = 1;
1014123474Swpaul	}
1015123474Swpaul	ATH_UNLOCK(sc);
1016123474Swpaul
1017123474Swpaul	/* complete setup */
1018123474Swpaul	ieee80211_vap_attach(vap, ath_media_change, ieee80211_media_status);
1019123474Swpaul	return vap;
1020123474Swpaulbad2:
1021123474Swpaul	reclaim_address(sc, mac);
1022123474Swpaul	ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
1023123474Swpaulbad:
1024123474Swpaul	free(avp, M_80211_VAP);
1025123474Swpaul	ATH_UNLOCK(sc);
1026123474Swpaul	return NULL;
1027123474Swpaul}
1028123474Swpaul
1029123474Swpaulstatic void
1030123474Swpaulath_vap_delete(struct ieee80211vap *vap)
1031123474Swpaul{
1032123474Swpaul	struct ieee80211com *ic = vap->iv_ic;
1033123474Swpaul	struct ifnet *ifp = ic->ic_ifp;
1034123474Swpaul	struct ath_softc *sc = ifp->if_softc;
1035123474Swpaul	struct ath_hal *ah = sc->sc_ah;
1036123474Swpaul	struct ath_vap *avp = ATH_VAP(vap);
1037123474Swpaul
1038123474Swpaul	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1039123474Swpaul		/*
1040123474Swpaul		 * Quiesce the hardware while we remove the vap.  In
1041123474Swpaul		 * particular we need to reclaim all references to
1042123474Swpaul		 * the vap state by any frames pending on the tx queues.
1043123474Swpaul		 */
1044123474Swpaul		ath_hal_intrset(ah, 0);		/* disable interrupts */
1045123474Swpaul		ath_draintxq(sc);		/* stop xmit side */
1046123474Swpaul		ath_stoprecv(sc);		/* stop recv side */
1047123474Swpaul	}
1048123474Swpaul
1049123474Swpaul	ieee80211_vap_detach(vap);
1050123474Swpaul	ATH_LOCK(sc);
1051123474Swpaul	/*
1052123474Swpaul	 * Reclaim beacon state.  Note this must be done before
1053123474Swpaul	 * the vap instance is reclaimed as we may have a reference
1054123474Swpaul	 * to it in the buffer for the beacon frame.
1055123474Swpaul	 */
1056123474Swpaul	if (avp->av_bcbuf != NULL) {
1057123474Swpaul		if (avp->av_bslot != -1) {
1058123474Swpaul			sc->sc_bslot[avp->av_bslot] = NULL;
1059123474Swpaul			sc->sc_nbcnvaps--;
1060123474Swpaul		}
1061123474Swpaul		ath_beacon_return(sc, avp->av_bcbuf);
1062123474Swpaul		avp->av_bcbuf = NULL;
1063123474Swpaul		if (sc->sc_nbcnvaps == 0) {
1064123474Swpaul			sc->sc_stagbeacons = 0;
1065123474Swpaul			if (sc->sc_hastsfadd)
1066123474Swpaul				ath_hal_settsfadjust(sc->sc_ah, 0);
1067123474Swpaul		}
1068123474Swpaul		/*
1069123474Swpaul		 * Reclaim any pending mcast frames for the vap.
1070123474Swpaul		 */
1071123474Swpaul		ath_tx_draintxq(sc, &avp->av_mcastq);
1072123474Swpaul		ATH_TXQ_LOCK_DESTROY(&avp->av_mcastq);
1073123474Swpaul	}
1074123474Swpaul	/*
1075123474Swpaul	 * Update bookkeeping.
1076123474Swpaul	 */
1077123474Swpaul	if (vap->iv_opmode == IEEE80211_M_STA) {
1078123535Swpaul		sc->sc_nstavaps--;
1079123474Swpaul		if (sc->sc_nstavaps == 0 && sc->sc_swbmiss)
1080123474Swpaul			sc->sc_swbmiss = 0;
1081123474Swpaul	} else if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1082123474Swpaul	    vap->iv_opmode == IEEE80211_M_MBSS) {
1083123474Swpaul		reclaim_address(sc, vap->iv_myaddr);
1084123474Swpaul		ath_hal_setbssidmask(ah, sc->sc_hwbssidmask);
1085123474Swpaul		if (vap->iv_opmode == IEEE80211_M_MBSS)
1086123474Swpaul			sc->sc_nmeshvaps--;
1087123474Swpaul	}
1088	if (vap->iv_opmode != IEEE80211_M_WDS)
1089		sc->sc_nvaps--;
1090#ifdef IEEE80211_SUPPORT_TDMA
1091	/* TDMA operation ceases when the last vap is destroyed */
1092	if (sc->sc_tdma && sc->sc_nvaps == 0) {
1093		sc->sc_tdma = 0;
1094		sc->sc_swbmiss = 0;
1095	}
1096#endif
1097	ATH_UNLOCK(sc);
1098	free(avp, M_80211_VAP);
1099
1100	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1101		/*
1102		 * Restart rx+tx machines if still running (RUNNING will
1103		 * be reset if we just destroyed the last vap).
1104		 */
1105		if (ath_startrecv(sc) != 0)
1106			if_printf(ifp, "%s: unable to restart recv logic\n",
1107			    __func__);
1108		if (sc->sc_beacons) {		/* restart beacons */
1109#ifdef IEEE80211_SUPPORT_TDMA
1110			if (sc->sc_tdma)
1111				ath_tdma_config(sc, NULL);
1112			else
1113#endif
1114				ath_beacon_config(sc, NULL);
1115		}
1116		ath_hal_intrset(ah, sc->sc_imask);
1117	}
1118}
1119
1120void
1121ath_suspend(struct ath_softc *sc)
1122{
1123	struct ifnet *ifp = sc->sc_ifp;
1124	struct ieee80211com *ic = ifp->if_l2com;
1125
1126	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1127		__func__, ifp->if_flags);
1128
1129	sc->sc_resume_up = (ifp->if_flags & IFF_UP) != 0;
1130	if (ic->ic_opmode == IEEE80211_M_STA)
1131		ath_stop(ifp);
1132	else
1133		ieee80211_suspend_all(ic);
1134	/*
1135	 * NB: don't worry about putting the chip in low power
1136	 * mode; pci will power off our socket on suspend and
1137	 * CardBus detaches the device.
1138	 */
1139}
1140
1141/*
1142 * Reset the key cache since some parts do not reset the
1143 * contents on resume.  First we clear all entries, then
1144 * re-load keys that the 802.11 layer assumes are setup
1145 * in h/w.
1146 */
1147static void
1148ath_reset_keycache(struct ath_softc *sc)
1149{
1150	struct ifnet *ifp = sc->sc_ifp;
1151	struct ieee80211com *ic = ifp->if_l2com;
1152	struct ath_hal *ah = sc->sc_ah;
1153	int i;
1154
1155	for (i = 0; i < sc->sc_keymax; i++)
1156		ath_hal_keyreset(ah, i);
1157	ieee80211_crypto_reload_keys(ic);
1158}
1159
1160void
1161ath_resume(struct ath_softc *sc)
1162{
1163	struct ifnet *ifp = sc->sc_ifp;
1164	struct ieee80211com *ic = ifp->if_l2com;
1165	struct ath_hal *ah = sc->sc_ah;
1166	HAL_STATUS status;
1167
1168	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1169		__func__, ifp->if_flags);
1170
1171	/*
1172	 * Must reset the chip before we reload the
1173	 * keycache as we were powered down on suspend.
1174	 */
1175	ath_hal_reset(ah, sc->sc_opmode,
1176	    sc->sc_curchan != NULL ? sc->sc_curchan : ic->ic_curchan,
1177	    AH_FALSE, &status);
1178	ath_reset_keycache(sc);
1179	if (sc->sc_resume_up) {
1180		if (ic->ic_opmode == IEEE80211_M_STA) {
1181			ath_init(sc);
1182			/*
1183			 * Program the beacon registers using the last rx'd
1184			 * beacon frame and enable sync on the next beacon
1185			 * we see.  This should handle the case where we
1186			 * wakeup and find the same AP and also the case where
1187			 * we wakeup and need to roam.  For the latter we
1188			 * should get bmiss events that trigger a roam.
1189			 */
1190			ath_beacon_config(sc, NULL);
1191			sc->sc_syncbeacon = 1;
1192		} else
1193			ieee80211_resume_all(ic);
1194	}
1195	if (sc->sc_softled) {
1196		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin,
1197		    HAL_GPIO_MUX_MAC_NETWORK_LED);
1198		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
1199	}
1200}
1201
1202void
1203ath_shutdown(struct ath_softc *sc)
1204{
1205	struct ifnet *ifp = sc->sc_ifp;
1206
1207	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1208		__func__, ifp->if_flags);
1209
1210	ath_stop(ifp);
1211	/* NB: no point powering down chip as we're about to reboot */
1212}
1213
1214/*
1215 * Interrupt handler.  Most of the actual processing is deferred.
1216 */
1217void
1218ath_intr(void *arg)
1219{
1220	struct ath_softc *sc = arg;
1221	struct ifnet *ifp = sc->sc_ifp;
1222	struct ath_hal *ah = sc->sc_ah;
1223	HAL_INT status;
1224
1225	if (sc->sc_invalid) {
1226		/*
1227		 * The hardware is not ready/present, don't touch anything.
1228		 * Note this can happen early on if the IRQ is shared.
1229		 */
1230		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
1231		return;
1232	}
1233	if (!ath_hal_intrpend(ah))		/* shared irq, not for us */
1234		return;
1235	if ((ifp->if_flags & IFF_UP) == 0 ||
1236	    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1237		HAL_INT status;
1238
1239		DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1240			__func__, ifp->if_flags);
1241		ath_hal_getisr(ah, &status);	/* clear ISR */
1242		ath_hal_intrset(ah, 0);		/* disable further intr's */
1243		return;
1244	}
1245	/*
1246	 * Figure out the reason(s) for the interrupt.  Note
1247	 * that the hal returns a pseudo-ISR that may include
1248	 * bits we haven't explicitly enabled so we mask the
1249	 * value to insure we only process bits we requested.
1250	 */
1251	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
1252	DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
1253	status &= sc->sc_imask;			/* discard unasked for bits */
1254	if (status & HAL_INT_FATAL) {
1255		sc->sc_stats.ast_hardware++;
1256		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
1257		ath_fatal_proc(sc, 0);
1258	} else {
1259		if (status & HAL_INT_SWBA) {
1260			/*
1261			 * Software beacon alert--time to send a beacon.
1262			 * Handle beacon transmission directly; deferring
1263			 * this is too slow to meet timing constraints
1264			 * under load.
1265			 */
1266#ifdef IEEE80211_SUPPORT_TDMA
1267			if (sc->sc_tdma) {
1268				if (sc->sc_tdmaswba == 0) {
1269					struct ieee80211com *ic = ifp->if_l2com;
1270					struct ieee80211vap *vap =
1271					    TAILQ_FIRST(&ic->ic_vaps);
1272					ath_tdma_beacon_send(sc, vap);
1273					sc->sc_tdmaswba =
1274					    vap->iv_tdma->tdma_bintval;
1275				} else
1276					sc->sc_tdmaswba--;
1277			} else
1278#endif
1279			{
1280				ath_beacon_proc(sc, 0);
1281#ifdef IEEE80211_SUPPORT_SUPERG
1282				/*
1283				 * Schedule the rx taskq in case there's no
1284				 * traffic so any frames held on the staging
1285				 * queue are aged and potentially flushed.
1286				 */
1287				taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1288#endif
1289			}
1290		}
1291		if (status & HAL_INT_RXEOL) {
1292			/*
1293			 * NB: the hardware should re-read the link when
1294			 *     RXE bit is written, but it doesn't work at
1295			 *     least on older hardware revs.
1296			 */
1297			sc->sc_stats.ast_rxeol++;
1298			sc->sc_rxlink = NULL;
1299		}
1300		if (status & HAL_INT_TXURN) {
1301			sc->sc_stats.ast_txurn++;
1302			/* bump tx trigger level */
1303			ath_hal_updatetxtriglevel(ah, AH_TRUE);
1304		}
1305		if (status & HAL_INT_RX)
1306			taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1307		if (status & HAL_INT_TX)
1308			taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
1309		if (status & HAL_INT_BMISS) {
1310			sc->sc_stats.ast_bmiss++;
1311			taskqueue_enqueue(sc->sc_tq, &sc->sc_bmisstask);
1312		}
1313		if (status & HAL_INT_MIB) {
1314			sc->sc_stats.ast_mib++;
1315			/*
1316			 * Disable interrupts until we service the MIB
1317			 * interrupt; otherwise it will continue to fire.
1318			 */
1319			ath_hal_intrset(ah, 0);
1320			/*
1321			 * Let the hal handle the event.  We assume it will
1322			 * clear whatever condition caused the interrupt.
1323			 */
1324			ath_hal_mibevent(ah, &sc->sc_halstats);
1325			ath_hal_intrset(ah, sc->sc_imask);
1326		}
1327		if (status & HAL_INT_RXORN) {
1328			/* NB: hal marks HAL_INT_FATAL when RXORN is fatal */
1329			sc->sc_stats.ast_rxorn++;
1330		}
1331	}
1332}
1333
1334static void
1335ath_fatal_proc(void *arg, int pending)
1336{
1337	struct ath_softc *sc = arg;
1338	struct ifnet *ifp = sc->sc_ifp;
1339	u_int32_t *state;
1340	u_int32_t len;
1341	void *sp;
1342
1343	if_printf(ifp, "hardware error; resetting\n");
1344	/*
1345	 * Fatal errors are unrecoverable.  Typically these
1346	 * are caused by DMA errors.  Collect h/w state from
1347	 * the hal so we can diagnose what's going on.
1348	 */
1349	if (ath_hal_getfatalstate(sc->sc_ah, &sp, &len)) {
1350		KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
1351		state = sp;
1352		if_printf(ifp, "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n",
1353		    state[0], state[1] , state[2], state[3],
1354		    state[4], state[5]);
1355	}
1356	ath_reset(ifp);
1357}
1358
1359static void
1360ath_bmiss_vap(struct ieee80211vap *vap)
1361{
1362	/*
1363	 * Workaround phantom bmiss interrupts by sanity-checking
1364	 * the time of our last rx'd frame.  If it is within the
1365	 * beacon miss interval then ignore the interrupt.  If it's
1366	 * truly a bmiss we'll get another interrupt soon and that'll
1367	 * be dispatched up for processing.  Note this applies only
1368	 * for h/w beacon miss events.
1369	 */
1370	if ((vap->iv_flags_ext & IEEE80211_FEXT_SWBMISS) == 0) {
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		if (tsf - lastrx <= bmisstimeout) {
1385			sc->sc_stats.ast_bmiss_phantom++;
1386			return;
1387		}
1388	}
1389	ATH_VAP(vap)->av_bmiss(vap);
1390}
1391
1392static int
1393ath_hal_gethangstate(struct ath_hal *ah, uint32_t mask, uint32_t *hangs)
1394{
1395	uint32_t rsize;
1396	void *sp;
1397
1398	if (!ath_hal_getdiagstate(ah, HAL_DIAG_CHECK_HANGS, &mask, sizeof(mask), &sp, &rsize))
1399		return 0;
1400	KASSERT(rsize == sizeof(uint32_t), ("resultsize %u", rsize));
1401	*hangs = *(uint32_t *)sp;
1402	return 1;
1403}
1404
1405static void
1406ath_bmiss_proc(void *arg, int pending)
1407{
1408	struct ath_softc *sc = arg;
1409	struct ifnet *ifp = sc->sc_ifp;
1410	uint32_t hangs;
1411
1412	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
1413
1414	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0) {
1415		if_printf(ifp, "bb hang detected (0x%x), resetting\n", hangs);
1416		ath_reset(ifp);
1417	} else
1418		ieee80211_beacon_miss(ifp->if_l2com);
1419}
1420
1421/*
1422 * Handle TKIP MIC setup to deal hardware that doesn't do MIC
1423 * calcs together with WME.  If necessary disable the crypto
1424 * hardware and mark the 802.11 state so keys will be setup
1425 * with the MIC work done in software.
1426 */
1427static void
1428ath_settkipmic(struct ath_softc *sc)
1429{
1430	struct ifnet *ifp = sc->sc_ifp;
1431	struct ieee80211com *ic = ifp->if_l2com;
1432
1433	if ((ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIP) && !sc->sc_wmetkipmic) {
1434		if (ic->ic_flags & IEEE80211_F_WME) {
1435			ath_hal_settkipmic(sc->sc_ah, AH_FALSE);
1436			ic->ic_cryptocaps &= ~IEEE80211_CRYPTO_TKIPMIC;
1437		} else {
1438			ath_hal_settkipmic(sc->sc_ah, AH_TRUE);
1439			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
1440		}
1441	}
1442}
1443
1444static void
1445ath_init(void *arg)
1446{
1447	struct ath_softc *sc = (struct ath_softc *) arg;
1448	struct ifnet *ifp = sc->sc_ifp;
1449	struct ieee80211com *ic = ifp->if_l2com;
1450	struct ath_hal *ah = sc->sc_ah;
1451	HAL_STATUS status;
1452
1453	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1454		__func__, ifp->if_flags);
1455
1456	ATH_LOCK(sc);
1457	/*
1458	 * Stop anything previously setup.  This is safe
1459	 * whether this is the first time through or not.
1460	 */
1461	ath_stop_locked(ifp);
1462
1463	/*
1464	 * The basic interface to setting the hardware in a good
1465	 * state is ``reset''.  On return the hardware is known to
1466	 * be powered up and with interrupts disabled.  This must
1467	 * be followed by initialization of the appropriate bits
1468	 * and then setup of the interrupt mask.
1469	 */
1470	ath_settkipmic(sc);
1471	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_FALSE, &status)) {
1472		if_printf(ifp, "unable to reset hardware; hal status %u\n",
1473			status);
1474		ATH_UNLOCK(sc);
1475		return;
1476	}
1477	ath_chan_change(sc, ic->ic_curchan);
1478
1479	/*
1480	 * Likewise this is set during reset so update
1481	 * state cached in the driver.
1482	 */
1483	sc->sc_diversity = ath_hal_getdiversity(ah);
1484	sc->sc_lastlongcal = 0;
1485	sc->sc_resetcal = 1;
1486	sc->sc_lastcalreset = 0;
1487	sc->sc_lastani = 0;
1488	sc->sc_lastshortcal = 0;
1489	sc->sc_doresetcal = AH_FALSE;
1490
1491	/*
1492	 * Setup the hardware after reset: the key cache
1493	 * is filled as needed and the receive engine is
1494	 * set going.  Frame transmit is handled entirely
1495	 * in the frame output path; there's nothing to do
1496	 * here except setup the interrupt mask.
1497	 */
1498	if (ath_startrecv(sc) != 0) {
1499		if_printf(ifp, "unable to start recv logic\n");
1500		ATH_UNLOCK(sc);
1501		return;
1502	}
1503
1504	/*
1505	 * Enable interrupts.
1506	 */
1507	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
1508		  | HAL_INT_RXEOL | HAL_INT_RXORN
1509		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
1510	/*
1511	 * Enable MIB interrupts when there are hardware phy counters.
1512	 * Note we only do this (at the moment) for station mode.
1513	 */
1514	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
1515		sc->sc_imask |= HAL_INT_MIB;
1516
1517	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1518	callout_reset(&sc->sc_wd_ch, hz, ath_watchdog, sc);
1519	ath_hal_intrset(ah, sc->sc_imask);
1520
1521	ATH_UNLOCK(sc);
1522
1523#ifdef ATH_TX99_DIAG
1524	if (sc->sc_tx99 != NULL)
1525		sc->sc_tx99->start(sc->sc_tx99);
1526	else
1527#endif
1528	ieee80211_start_all(ic);		/* start all vap's */
1529}
1530
1531static void
1532ath_stop_locked(struct ifnet *ifp)
1533{
1534	struct ath_softc *sc = ifp->if_softc;
1535	struct ath_hal *ah = sc->sc_ah;
1536
1537	DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1538		__func__, sc->sc_invalid, ifp->if_flags);
1539
1540	ATH_LOCK_ASSERT(sc);
1541	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1542		/*
1543		 * Shutdown the hardware and driver:
1544		 *    reset 802.11 state machine
1545		 *    turn off timers
1546		 *    disable interrupts
1547		 *    turn off the radio
1548		 *    clear transmit machinery
1549		 *    clear receive machinery
1550		 *    drain and release tx queues
1551		 *    reclaim beacon resources
1552		 *    power down hardware
1553		 *
1554		 * Note that some of this work is not possible if the
1555		 * hardware is gone (invalid).
1556		 */
1557#ifdef ATH_TX99_DIAG
1558		if (sc->sc_tx99 != NULL)
1559			sc->sc_tx99->stop(sc->sc_tx99);
1560#endif
1561		callout_stop(&sc->sc_wd_ch);
1562		sc->sc_wd_timer = 0;
1563		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1564		if (!sc->sc_invalid) {
1565			if (sc->sc_softled) {
1566				callout_stop(&sc->sc_ledtimer);
1567				ath_hal_gpioset(ah, sc->sc_ledpin,
1568					!sc->sc_ledon);
1569				sc->sc_blinking = 0;
1570			}
1571			ath_hal_intrset(ah, 0);
1572		}
1573		ath_draintxq(sc);
1574		if (!sc->sc_invalid) {
1575			ath_stoprecv(sc);
1576			ath_hal_phydisable(ah);
1577		} else
1578			sc->sc_rxlink = NULL;
1579		ath_beacon_free(sc);	/* XXX not needed */
1580	}
1581}
1582
1583static void
1584ath_stop(struct ifnet *ifp)
1585{
1586	struct ath_softc *sc = ifp->if_softc;
1587
1588	ATH_LOCK(sc);
1589	ath_stop_locked(ifp);
1590	ATH_UNLOCK(sc);
1591}
1592
1593/*
1594 * Reset the hardware w/o losing operational state.  This is
1595 * basically a more efficient way of doing ath_stop, ath_init,
1596 * followed by state transitions to the current 802.11
1597 * operational state.  Used to recover from various errors and
1598 * to reset or reload hardware state.
1599 */
1600static int
1601ath_reset(struct ifnet *ifp)
1602{
1603	struct ath_softc *sc = ifp->if_softc;
1604	struct ieee80211com *ic = ifp->if_l2com;
1605	struct ath_hal *ah = sc->sc_ah;
1606	HAL_STATUS status;
1607
1608	ath_hal_intrset(ah, 0);		/* disable interrupts */
1609	ath_draintxq(sc);		/* stop xmit side */
1610	ath_stoprecv(sc);		/* stop recv side */
1611	ath_settkipmic(sc);		/* configure TKIP MIC handling */
1612	/* NB: indicate channel change so we do a full reset */
1613	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_TRUE, &status))
1614		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
1615			__func__, status);
1616	sc->sc_diversity = ath_hal_getdiversity(ah);
1617	if (ath_startrecv(sc) != 0)	/* restart recv */
1618		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
1619	/*
1620	 * We may be doing a reset in response to an ioctl
1621	 * that changes the channel so update any state that
1622	 * might change as a result.
1623	 */
1624	ath_chan_change(sc, ic->ic_curchan);
1625	if (sc->sc_beacons) {		/* restart beacons */
1626#ifdef IEEE80211_SUPPORT_TDMA
1627		if (sc->sc_tdma)
1628			ath_tdma_config(sc, NULL);
1629		else
1630#endif
1631			ath_beacon_config(sc, NULL);
1632	}
1633	ath_hal_intrset(ah, sc->sc_imask);
1634
1635	ath_start(ifp);			/* restart xmit */
1636	return 0;
1637}
1638
1639static int
1640ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
1641{
1642	struct ieee80211com *ic = vap->iv_ic;
1643	struct ifnet *ifp = ic->ic_ifp;
1644	struct ath_softc *sc = ifp->if_softc;
1645	struct ath_hal *ah = sc->sc_ah;
1646
1647	switch (cmd) {
1648	case IEEE80211_IOC_TXPOWER:
1649		/*
1650		 * If per-packet TPC is enabled, then we have nothing
1651		 * to do; otherwise we need to force the global limit.
1652		 * All this can happen directly; no need to reset.
1653		 */
1654		if (!ath_hal_gettpc(ah))
1655			ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
1656		return 0;
1657	}
1658	return ath_reset(ifp);
1659}
1660
1661struct ath_buf *
1662_ath_getbuf_locked(struct ath_softc *sc)
1663{
1664	struct ath_buf *bf;
1665
1666	ATH_TXBUF_LOCK_ASSERT(sc);
1667
1668	bf = STAILQ_FIRST(&sc->sc_txbuf);
1669	if (bf != NULL && (bf->bf_flags & ATH_BUF_BUSY) == 0)
1670		STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
1671	else
1672		bf = NULL;
1673	if (bf == NULL) {
1674		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: %s\n", __func__,
1675		    STAILQ_FIRST(&sc->sc_txbuf) == NULL ?
1676			"out of xmit buffers" : "xmit buffer busy");
1677	}
1678	return bf;
1679}
1680
1681struct ath_buf *
1682ath_getbuf(struct ath_softc *sc)
1683{
1684	struct ath_buf *bf;
1685
1686	ATH_TXBUF_LOCK(sc);
1687	bf = _ath_getbuf_locked(sc);
1688	if (bf == NULL) {
1689		struct ifnet *ifp = sc->sc_ifp;
1690
1691		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
1692		sc->sc_stats.ast_tx_qstop++;
1693		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1694	}
1695	ATH_TXBUF_UNLOCK(sc);
1696	return bf;
1697}
1698
1699static void
1700ath_start(struct ifnet *ifp)
1701{
1702	struct ath_softc *sc = ifp->if_softc;
1703	struct ieee80211_node *ni;
1704	struct ath_buf *bf;
1705	struct mbuf *m, *next;
1706	ath_bufhead frags;
1707
1708	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
1709		return;
1710	for (;;) {
1711		/*
1712		 * Grab a TX buffer and associated resources.
1713		 */
1714		bf = ath_getbuf(sc);
1715		if (bf == NULL)
1716			break;
1717
1718		IFQ_DEQUEUE(&ifp->if_snd, m);
1719		if (m == NULL) {
1720			ATH_TXBUF_LOCK(sc);
1721			STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1722			ATH_TXBUF_UNLOCK(sc);
1723			break;
1724		}
1725		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1726		/*
1727		 * Check for fragmentation.  If this frame
1728		 * has been broken up verify we have enough
1729		 * buffers to send all the fragments so all
1730		 * go out or none...
1731		 */
1732		STAILQ_INIT(&frags);
1733		if ((m->m_flags & M_FRAG) &&
1734		    !ath_txfrag_setup(sc, &frags, m, ni)) {
1735			DPRINTF(sc, ATH_DEBUG_XMIT,
1736			    "%s: out of txfrag buffers\n", __func__);
1737			sc->sc_stats.ast_tx_nofrag++;
1738			ifp->if_oerrors++;
1739			ath_freetx(m);
1740			goto bad;
1741		}
1742		ifp->if_opackets++;
1743	nextfrag:
1744		/*
1745		 * Pass the frame to the h/w for transmission.
1746		 * Fragmented frames have each frag chained together
1747		 * with m_nextpkt.  We know there are sufficient ath_buf's
1748		 * to send all the frags because of work done by
1749		 * ath_txfrag_setup.  We leave m_nextpkt set while
1750		 * calling ath_tx_start so it can use it to extend the
1751		 * the tx duration to cover the subsequent frag and
1752		 * so it can reclaim all the mbufs in case of an error;
1753		 * ath_tx_start clears m_nextpkt once it commits to
1754		 * handing the frame to the hardware.
1755		 */
1756		next = m->m_nextpkt;
1757		if (ath_tx_start(sc, ni, bf, m)) {
1758	bad:
1759			ifp->if_oerrors++;
1760	reclaim:
1761			bf->bf_m = NULL;
1762			bf->bf_node = NULL;
1763			ATH_TXBUF_LOCK(sc);
1764			STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1765			ath_txfrag_cleanup(sc, &frags, ni);
1766			ATH_TXBUF_UNLOCK(sc);
1767			if (ni != NULL)
1768				ieee80211_free_node(ni);
1769			continue;
1770		}
1771		if (next != NULL) {
1772			/*
1773			 * Beware of state changing between frags.
1774			 * XXX check sta power-save state?
1775			 */
1776			if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
1777				DPRINTF(sc, ATH_DEBUG_XMIT,
1778				    "%s: flush fragmented packet, state %s\n",
1779				    __func__,
1780				    ieee80211_state_name[ni->ni_vap->iv_state]);
1781				ath_freetx(next);
1782				goto reclaim;
1783			}
1784			m = next;
1785			bf = STAILQ_FIRST(&frags);
1786			KASSERT(bf != NULL, ("no buf for txfrag"));
1787			STAILQ_REMOVE_HEAD(&frags, bf_list);
1788			goto nextfrag;
1789		}
1790
1791		sc->sc_wd_timer = 5;
1792	}
1793}
1794
1795static int
1796ath_media_change(struct ifnet *ifp)
1797{
1798	int error = ieee80211_media_change(ifp);
1799	/* NB: only the fixed rate can change and that doesn't need a reset */
1800	return (error == ENETRESET ? 0 : error);
1801}
1802
1803#ifdef ATH_DEBUG
1804static void
1805ath_keyprint(struct ath_softc *sc, const char *tag, u_int ix,
1806	const HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1807{
1808	static const char *ciphers[] = {
1809		"WEP",
1810		"AES-OCB",
1811		"AES-CCM",
1812		"CKIP",
1813		"TKIP",
1814		"CLR",
1815	};
1816	int i, n;
1817
1818	printf("%s: [%02u] %-7s ", tag, ix, ciphers[hk->kv_type]);
1819	for (i = 0, n = hk->kv_len; i < n; i++)
1820		printf("%02x", hk->kv_val[i]);
1821	printf(" mac %s", ether_sprintf(mac));
1822	if (hk->kv_type == HAL_CIPHER_TKIP) {
1823		printf(" %s ", sc->sc_splitmic ? "mic" : "rxmic");
1824		for (i = 0; i < sizeof(hk->kv_mic); i++)
1825			printf("%02x", hk->kv_mic[i]);
1826		if (!sc->sc_splitmic) {
1827			printf(" txmic ");
1828			for (i = 0; i < sizeof(hk->kv_txmic); i++)
1829				printf("%02x", hk->kv_txmic[i]);
1830		}
1831	}
1832	printf("\n");
1833}
1834#endif
1835
1836/*
1837 * Set a TKIP key into the hardware.  This handles the
1838 * potential distribution of key state to multiple key
1839 * cache slots for TKIP.
1840 */
1841static int
1842ath_keyset_tkip(struct ath_softc *sc, const struct ieee80211_key *k,
1843	HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1844{
1845#define	IEEE80211_KEY_XR	(IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV)
1846	static const u_int8_t zerobssid[IEEE80211_ADDR_LEN];
1847	struct ath_hal *ah = sc->sc_ah;
1848
1849	KASSERT(k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP,
1850		("got a non-TKIP key, cipher %u", k->wk_cipher->ic_cipher));
1851	if ((k->wk_flags & IEEE80211_KEY_XR) == IEEE80211_KEY_XR) {
1852		if (sc->sc_splitmic) {
1853			/*
1854			 * TX key goes at first index, RX key at the rx index.
1855			 * The hal handles the MIC keys at index+64.
1856			 */
1857			memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_mic));
1858			KEYPRINTF(sc, k->wk_keyix, hk, zerobssid);
1859			if (!ath_hal_keyset(ah, k->wk_keyix, hk, zerobssid))
1860				return 0;
1861
1862			memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1863			KEYPRINTF(sc, k->wk_keyix+32, hk, mac);
1864			/* XXX delete tx key on failure? */
1865			return ath_hal_keyset(ah, k->wk_keyix+32, hk, mac);
1866		} else {
1867			/*
1868			 * Room for both TX+RX MIC keys in one key cache
1869			 * slot, just set key at the first index; the hal
1870			 * will handle the rest.
1871			 */
1872			memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1873			memcpy(hk->kv_txmic, k->wk_txmic, sizeof(hk->kv_txmic));
1874			KEYPRINTF(sc, k->wk_keyix, hk, mac);
1875			return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1876		}
1877	} else if (k->wk_flags & IEEE80211_KEY_XMIT) {
1878		if (sc->sc_splitmic) {
1879			/*
1880			 * NB: must pass MIC key in expected location when
1881			 * the keycache only holds one MIC key per entry.
1882			 */
1883			memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_txmic));
1884		} else
1885			memcpy(hk->kv_txmic, k->wk_txmic, sizeof(hk->kv_txmic));
1886		KEYPRINTF(sc, k->wk_keyix, hk, mac);
1887		return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1888	} else if (k->wk_flags & IEEE80211_KEY_RECV) {
1889		memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1890		KEYPRINTF(sc, k->wk_keyix, hk, mac);
1891		return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1892	}
1893	return 0;
1894#undef IEEE80211_KEY_XR
1895}
1896
1897/*
1898 * Set a net80211 key into the hardware.  This handles the
1899 * potential distribution of key state to multiple key
1900 * cache slots for TKIP with hardware MIC support.
1901 */
1902static int
1903ath_keyset(struct ath_softc *sc, const struct ieee80211_key *k,
1904	struct ieee80211_node *bss)
1905{
1906#define	N(a)	(sizeof(a)/sizeof(a[0]))
1907	static const u_int8_t ciphermap[] = {
1908		HAL_CIPHER_WEP,		/* IEEE80211_CIPHER_WEP */
1909		HAL_CIPHER_TKIP,	/* IEEE80211_CIPHER_TKIP */
1910		HAL_CIPHER_AES_OCB,	/* IEEE80211_CIPHER_AES_OCB */
1911		HAL_CIPHER_AES_CCM,	/* IEEE80211_CIPHER_AES_CCM */
1912		(u_int8_t) -1,		/* 4 is not allocated */
1913		HAL_CIPHER_CKIP,	/* IEEE80211_CIPHER_CKIP */
1914		HAL_CIPHER_CLR,		/* IEEE80211_CIPHER_NONE */
1915	};
1916	struct ath_hal *ah = sc->sc_ah;
1917	const struct ieee80211_cipher *cip = k->wk_cipher;
1918	u_int8_t gmac[IEEE80211_ADDR_LEN];
1919	const u_int8_t *mac;
1920	HAL_KEYVAL hk;
1921
1922	memset(&hk, 0, sizeof(hk));
1923	/*
1924	 * Software crypto uses a "clear key" so non-crypto
1925	 * state kept in the key cache are maintained and
1926	 * so that rx frames have an entry to match.
1927	 */
1928	if ((k->wk_flags & IEEE80211_KEY_SWCRYPT) == 0) {
1929		KASSERT(cip->ic_cipher < N(ciphermap),
1930			("invalid cipher type %u", cip->ic_cipher));
1931		hk.kv_type = ciphermap[cip->ic_cipher];
1932		hk.kv_len = k->wk_keylen;
1933		memcpy(hk.kv_val, k->wk_key, k->wk_keylen);
1934	} else
1935		hk.kv_type = HAL_CIPHER_CLR;
1936
1937	if ((k->wk_flags & IEEE80211_KEY_GROUP) && sc->sc_mcastkey) {
1938		/*
1939		 * Group keys on hardware that supports multicast frame
1940		 * key search use a MAC that is the sender's address with
1941		 * the high bit set instead of the app-specified address.
1942		 */
1943		IEEE80211_ADDR_COPY(gmac, bss->ni_macaddr);
1944		gmac[0] |= 0x80;
1945		mac = gmac;
1946	} else
1947		mac = k->wk_macaddr;
1948
1949	if (hk.kv_type == HAL_CIPHER_TKIP &&
1950	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
1951		return ath_keyset_tkip(sc, k, &hk, mac);
1952	} else {
1953		KEYPRINTF(sc, k->wk_keyix, &hk, mac);
1954		return ath_hal_keyset(ah, k->wk_keyix, &hk, mac);
1955	}
1956#undef N
1957}
1958
1959/*
1960 * Allocate tx/rx key slots for TKIP.  We allocate two slots for
1961 * each key, one for decrypt/encrypt and the other for the MIC.
1962 */
1963static u_int16_t
1964key_alloc_2pair(struct ath_softc *sc,
1965	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
1966{
1967#define	N(a)	(sizeof(a)/sizeof(a[0]))
1968	u_int i, keyix;
1969
1970	KASSERT(sc->sc_splitmic, ("key cache !split"));
1971	/* XXX could optimize */
1972	for (i = 0; i < N(sc->sc_keymap)/4; i++) {
1973		u_int8_t b = sc->sc_keymap[i];
1974		if (b != 0xff) {
1975			/*
1976			 * One or more slots in this byte are free.
1977			 */
1978			keyix = i*NBBY;
1979			while (b & 1) {
1980		again:
1981				keyix++;
1982				b >>= 1;
1983			}
1984			/* XXX IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV */
1985			if (isset(sc->sc_keymap, keyix+32) ||
1986			    isset(sc->sc_keymap, keyix+64) ||
1987			    isset(sc->sc_keymap, keyix+32+64)) {
1988				/* full pair unavailable */
1989				/* XXX statistic */
1990				if (keyix == (i+1)*NBBY) {
1991					/* no slots were appropriate, advance */
1992					continue;
1993				}
1994				goto again;
1995			}
1996			setbit(sc->sc_keymap, keyix);
1997			setbit(sc->sc_keymap, keyix+64);
1998			setbit(sc->sc_keymap, keyix+32);
1999			setbit(sc->sc_keymap, keyix+32+64);
2000			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2001				"%s: key pair %u,%u %u,%u\n",
2002				__func__, keyix, keyix+64,
2003				keyix+32, keyix+32+64);
2004			*txkeyix = keyix;
2005			*rxkeyix = keyix+32;
2006			return 1;
2007		}
2008	}
2009	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
2010	return 0;
2011#undef N
2012}
2013
2014/*
2015 * Allocate tx/rx key slots for TKIP.  We allocate two slots for
2016 * each key, one for decrypt/encrypt and the other for the MIC.
2017 */
2018static u_int16_t
2019key_alloc_pair(struct ath_softc *sc,
2020	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2021{
2022#define	N(a)	(sizeof(a)/sizeof(a[0]))
2023	u_int i, keyix;
2024
2025	KASSERT(!sc->sc_splitmic, ("key cache split"));
2026	/* XXX could optimize */
2027	for (i = 0; i < N(sc->sc_keymap)/4; i++) {
2028		u_int8_t b = sc->sc_keymap[i];
2029		if (b != 0xff) {
2030			/*
2031			 * One or more slots in this byte are free.
2032			 */
2033			keyix = i*NBBY;
2034			while (b & 1) {
2035		again:
2036				keyix++;
2037				b >>= 1;
2038			}
2039			if (isset(sc->sc_keymap, keyix+64)) {
2040				/* full pair unavailable */
2041				/* XXX statistic */
2042				if (keyix == (i+1)*NBBY) {
2043					/* no slots were appropriate, advance */
2044					continue;
2045				}
2046				goto again;
2047			}
2048			setbit(sc->sc_keymap, keyix);
2049			setbit(sc->sc_keymap, keyix+64);
2050			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2051				"%s: key pair %u,%u\n",
2052				__func__, keyix, keyix+64);
2053			*txkeyix = *rxkeyix = keyix;
2054			return 1;
2055		}
2056	}
2057	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
2058	return 0;
2059#undef N
2060}
2061
2062/*
2063 * Allocate a single key cache slot.
2064 */
2065static int
2066key_alloc_single(struct ath_softc *sc,
2067	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2068{
2069#define	N(a)	(sizeof(a)/sizeof(a[0]))
2070	u_int i, keyix;
2071
2072	/* XXX try i,i+32,i+64,i+32+64 to minimize key pair conflicts */
2073	for (i = 0; i < N(sc->sc_keymap); i++) {
2074		u_int8_t b = sc->sc_keymap[i];
2075		if (b != 0xff) {
2076			/*
2077			 * One or more slots are free.
2078			 */
2079			keyix = i*NBBY;
2080			while (b & 1)
2081				keyix++, b >>= 1;
2082			setbit(sc->sc_keymap, keyix);
2083			DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: key %u\n",
2084				__func__, keyix);
2085			*txkeyix = *rxkeyix = keyix;
2086			return 1;
2087		}
2088	}
2089	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of space\n", __func__);
2090	return 0;
2091#undef N
2092}
2093
2094/*
2095 * Allocate one or more key cache slots for a uniacst key.  The
2096 * key itself is needed only to identify the cipher.  For hardware
2097 * TKIP with split cipher+MIC keys we allocate two key cache slot
2098 * pairs so that we can setup separate TX and RX MIC keys.  Note
2099 * that the MIC key for a TKIP key at slot i is assumed by the
2100 * hardware to be at slot i+64.  This limits TKIP keys to the first
2101 * 64 entries.
2102 */
2103static int
2104ath_key_alloc(struct ieee80211vap *vap, struct ieee80211_key *k,
2105	ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
2106{
2107	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2108
2109	/*
2110	 * Group key allocation must be handled specially for
2111	 * parts that do not support multicast key cache search
2112	 * functionality.  For those parts the key id must match
2113	 * the h/w key index so lookups find the right key.  On
2114	 * parts w/ the key search facility we install the sender's
2115	 * mac address (with the high bit set) and let the hardware
2116	 * find the key w/o using the key id.  This is preferred as
2117	 * it permits us to support multiple users for adhoc and/or
2118	 * multi-station operation.
2119	 */
2120	if (k->wk_keyix != IEEE80211_KEYIX_NONE) {
2121		/*
2122		 * Only global keys should have key index assigned.
2123		 */
2124		if (!(&vap->iv_nw_keys[0] <= k &&
2125		      k < &vap->iv_nw_keys[IEEE80211_WEP_NKID])) {
2126			/* should not happen */
2127			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2128				"%s: bogus group key\n", __func__);
2129			return 0;
2130		}
2131		if (vap->iv_opmode != IEEE80211_M_HOSTAP ||
2132		    !(k->wk_flags & IEEE80211_KEY_GROUP) ||
2133		    !sc->sc_mcastkey) {
2134			/*
2135			 * XXX we pre-allocate the global keys so
2136			 * have no way to check if they've already
2137			 * been allocated.
2138			 */
2139			*keyix = *rxkeyix = k - vap->iv_nw_keys;
2140			return 1;
2141		}
2142		/*
2143		 * Group key and device supports multicast key search.
2144		 */
2145		k->wk_keyix = IEEE80211_KEYIX_NONE;
2146	}
2147
2148	/*
2149	 * We allocate two pair for TKIP when using the h/w to do
2150	 * the MIC.  For everything else, including software crypto,
2151	 * we allocate a single entry.  Note that s/w crypto requires
2152	 * a pass-through slot on the 5211 and 5212.  The 5210 does
2153	 * not support pass-through cache entries and we map all
2154	 * those requests to slot 0.
2155	 */
2156	if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
2157		return key_alloc_single(sc, keyix, rxkeyix);
2158	} else if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP &&
2159	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2160		if (sc->sc_splitmic)
2161			return key_alloc_2pair(sc, keyix, rxkeyix);
2162		else
2163			return key_alloc_pair(sc, keyix, rxkeyix);
2164	} else {
2165		return key_alloc_single(sc, keyix, rxkeyix);
2166	}
2167}
2168
2169/*
2170 * Delete an entry in the key cache allocated by ath_key_alloc.
2171 */
2172static int
2173ath_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
2174{
2175	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2176	struct ath_hal *ah = sc->sc_ah;
2177	const struct ieee80211_cipher *cip = k->wk_cipher;
2178	u_int keyix = k->wk_keyix;
2179
2180	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: delete key %u\n", __func__, keyix);
2181
2182	ath_hal_keyreset(ah, keyix);
2183	/*
2184	 * Handle split tx/rx keying required for TKIP with h/w MIC.
2185	 */
2186	if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
2187	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic)
2188		ath_hal_keyreset(ah, keyix+32);		/* RX key */
2189	if (keyix >= IEEE80211_WEP_NKID) {
2190		/*
2191		 * Don't touch keymap entries for global keys so
2192		 * they are never considered for dynamic allocation.
2193		 */
2194		clrbit(sc->sc_keymap, keyix);
2195		if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
2196		    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2197			clrbit(sc->sc_keymap, keyix+64);	/* TX key MIC */
2198			if (sc->sc_splitmic) {
2199				/* +32 for RX key, +32+64 for RX key MIC */
2200				clrbit(sc->sc_keymap, keyix+32);
2201				clrbit(sc->sc_keymap, keyix+32+64);
2202			}
2203		}
2204	}
2205	return 1;
2206}
2207
2208/*
2209 * Set the key cache contents for the specified key.  Key cache
2210 * slot(s) must already have been allocated by ath_key_alloc.
2211 */
2212static int
2213ath_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k,
2214	const u_int8_t mac[IEEE80211_ADDR_LEN])
2215{
2216	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2217
2218	return ath_keyset(sc, k, vap->iv_bss);
2219}
2220
2221/*
2222 * Block/unblock tx+rx processing while a key change is done.
2223 * We assume the caller serializes key management operations
2224 * so we only need to worry about synchronization with other
2225 * uses that originate in the driver.
2226 */
2227static void
2228ath_key_update_begin(struct ieee80211vap *vap)
2229{
2230	struct ifnet *ifp = vap->iv_ic->ic_ifp;
2231	struct ath_softc *sc = ifp->if_softc;
2232
2233	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2234	taskqueue_block(sc->sc_tq);
2235	IF_LOCK(&ifp->if_snd);		/* NB: doesn't block mgmt frames */
2236}
2237
2238static void
2239ath_key_update_end(struct ieee80211vap *vap)
2240{
2241	struct ifnet *ifp = vap->iv_ic->ic_ifp;
2242	struct ath_softc *sc = ifp->if_softc;
2243
2244	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2245	IF_UNLOCK(&ifp->if_snd);
2246	taskqueue_unblock(sc->sc_tq);
2247}
2248
2249/*
2250 * Calculate the receive filter according to the
2251 * operating mode and state:
2252 *
2253 * o always accept unicast, broadcast, and multicast traffic
2254 * o accept PHY error frames when hardware doesn't have MIB support
2255 *   to count and we need them for ANI (sta mode only until recently)
2256 *   and we are not scanning (ANI is disabled)
2257 *   NB: older hal's add rx filter bits out of sight and we need to
2258 *	 blindly preserve them
2259 * o probe request frames are accepted only when operating in
2260 *   hostap, adhoc, mesh, or monitor modes
2261 * o enable promiscuous mode
2262 *   - when in monitor mode
2263 *   - if interface marked PROMISC (assumes bridge setting is filtered)
2264 * o accept beacons:
2265 *   - when operating in station mode for collecting rssi data when
2266 *     the station is otherwise quiet, or
2267 *   - when operating in adhoc mode so the 802.11 layer creates
2268 *     node table entries for peers,
2269 *   - when scanning
2270 *   - when doing s/w beacon miss (e.g. for ap+sta)
2271 *   - when operating in ap mode in 11g to detect overlapping bss that
2272 *     require protection
2273 *   - when operating in mesh mode to detect neighbors
2274 * o accept control frames:
2275 *   - when in monitor mode
2276 * XXX HT protection for 11n
2277 */
2278static u_int32_t
2279ath_calcrxfilter(struct ath_softc *sc)
2280{
2281	struct ifnet *ifp = sc->sc_ifp;
2282	struct ieee80211com *ic = ifp->if_l2com;
2283	u_int32_t rfilt;
2284
2285	rfilt = HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
2286	if (!sc->sc_needmib && !sc->sc_scanning)
2287		rfilt |= HAL_RX_FILTER_PHYERR;
2288	if (ic->ic_opmode != IEEE80211_M_STA)
2289		rfilt |= HAL_RX_FILTER_PROBEREQ;
2290	/* XXX ic->ic_monvaps != 0? */
2291	if (ic->ic_opmode == IEEE80211_M_MONITOR || (ifp->if_flags & IFF_PROMISC))
2292		rfilt |= HAL_RX_FILTER_PROM;
2293	if (ic->ic_opmode == IEEE80211_M_STA ||
2294	    ic->ic_opmode == IEEE80211_M_IBSS ||
2295	    sc->sc_swbmiss || sc->sc_scanning)
2296		rfilt |= HAL_RX_FILTER_BEACON;
2297	/*
2298	 * NB: We don't recalculate the rx filter when
2299	 * ic_protmode changes; otherwise we could do
2300	 * this only when ic_protmode != NONE.
2301	 */
2302	if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
2303	    IEEE80211_IS_CHAN_ANYG(ic->ic_curchan))
2304		rfilt |= HAL_RX_FILTER_BEACON;
2305	if (sc->sc_nmeshvaps) {
2306		rfilt |= HAL_RX_FILTER_BEACON;
2307		if (sc->sc_hasbmatch)
2308			rfilt |= HAL_RX_FILTER_BSSID;
2309		else
2310			rfilt |= HAL_RX_FILTER_PROM;
2311	}
2312	if (ic->ic_opmode == IEEE80211_M_MONITOR)
2313		rfilt |= HAL_RX_FILTER_CONTROL;
2314	if (IEEE80211_IS_CHAN_HT(ic->ic_curchan))
2315		rfilt |= HAL_RX_FILTER_COMPBAR;
2316	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, %s if_flags 0x%x\n",
2317	    __func__, rfilt, ieee80211_opmode_name[ic->ic_opmode], ifp->if_flags);
2318	return rfilt;
2319}
2320
2321static void
2322ath_update_promisc(struct ifnet *ifp)
2323{
2324	struct ath_softc *sc = ifp->if_softc;
2325	u_int32_t rfilt;
2326
2327	/* configure rx filter */
2328	rfilt = ath_calcrxfilter(sc);
2329	ath_hal_setrxfilter(sc->sc_ah, rfilt);
2330
2331	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
2332}
2333
2334static void
2335ath_update_mcast(struct ifnet *ifp)
2336{
2337	struct ath_softc *sc = ifp->if_softc;
2338	u_int32_t mfilt[2];
2339
2340	/* calculate and install multicast filter */
2341	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
2342		struct ifmultiaddr *ifma;
2343		/*
2344		 * Merge multicast addresses to form the hardware filter.
2345		 */
2346		mfilt[0] = mfilt[1] = 0;
2347		if_maddr_rlock(ifp);	/* XXX need some fiddling to remove? */
2348		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2349			caddr_t dl;
2350			u_int32_t val;
2351			u_int8_t pos;
2352
2353			/* calculate XOR of eight 6bit values */
2354			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
2355			val = LE_READ_4(dl + 0);
2356			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2357			val = LE_READ_4(dl + 3);
2358			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2359			pos &= 0x3f;
2360			mfilt[pos / 32] |= (1 << (pos % 32));
2361		}
2362		if_maddr_runlock(ifp);
2363	} else
2364		mfilt[0] = mfilt[1] = ~0;
2365	ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
2366	DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
2367		__func__, mfilt[0], mfilt[1]);
2368}
2369
2370static void
2371ath_mode_init(struct ath_softc *sc)
2372{
2373	struct ifnet *ifp = sc->sc_ifp;
2374	struct ath_hal *ah = sc->sc_ah;
2375	u_int32_t rfilt;
2376
2377	/* configure rx filter */
2378	rfilt = ath_calcrxfilter(sc);
2379	ath_hal_setrxfilter(ah, rfilt);
2380
2381	/* configure operational mode */
2382	ath_hal_setopmode(ah);
2383
2384	/* handle any link-level address change */
2385	ath_hal_setmac(ah, IF_LLADDR(ifp));
2386
2387	/* calculate and install multicast filter */
2388	ath_update_mcast(ifp);
2389}
2390
2391/*
2392 * Set the slot time based on the current setting.
2393 */
2394static void
2395ath_setslottime(struct ath_softc *sc)
2396{
2397	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2398	struct ath_hal *ah = sc->sc_ah;
2399	u_int usec;
2400
2401	if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
2402		usec = 13;
2403	else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
2404		usec = 21;
2405	else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
2406		/* honor short/long slot time only in 11g */
2407		/* XXX shouldn't honor on pure g or turbo g channel */
2408		if (ic->ic_flags & IEEE80211_F_SHSLOT)
2409			usec = HAL_SLOT_TIME_9;
2410		else
2411			usec = HAL_SLOT_TIME_20;
2412	} else
2413		usec = HAL_SLOT_TIME_9;
2414
2415	DPRINTF(sc, ATH_DEBUG_RESET,
2416	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
2417	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
2418	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
2419
2420	ath_hal_setslottime(ah, usec);
2421	sc->sc_updateslot = OK;
2422}
2423
2424/*
2425 * Callback from the 802.11 layer to update the
2426 * slot time based on the current setting.
2427 */
2428static void
2429ath_updateslot(struct ifnet *ifp)
2430{
2431	struct ath_softc *sc = ifp->if_softc;
2432	struct ieee80211com *ic = ifp->if_l2com;
2433
2434	/*
2435	 * When not coordinating the BSS, change the hardware
2436	 * immediately.  For other operation we defer the change
2437	 * until beacon updates have propagated to the stations.
2438	 */
2439	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2440	    ic->ic_opmode == IEEE80211_M_MBSS)
2441		sc->sc_updateslot = UPDATE;
2442	else
2443		ath_setslottime(sc);
2444}
2445
2446/*
2447 * Setup a h/w transmit queue for beacons.
2448 */
2449static int
2450ath_beaconq_setup(struct ath_hal *ah)
2451{
2452	HAL_TXQ_INFO qi;
2453
2454	memset(&qi, 0, sizeof(qi));
2455	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
2456	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
2457	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
2458	/* NB: for dynamic turbo, don't enable any other interrupts */
2459	qi.tqi_qflags = HAL_TXQ_TXDESCINT_ENABLE;
2460	return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
2461}
2462
2463/*
2464 * Setup the transmit queue parameters for the beacon queue.
2465 */
2466static int
2467ath_beaconq_config(struct ath_softc *sc)
2468{
2469#define	ATH_EXPONENT_TO_VALUE(v)	((1<<(v))-1)
2470	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2471	struct ath_hal *ah = sc->sc_ah;
2472	HAL_TXQ_INFO qi;
2473
2474	ath_hal_gettxqueueprops(ah, sc->sc_bhalq, &qi);
2475	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2476	    ic->ic_opmode == IEEE80211_M_MBSS) {
2477		/*
2478		 * Always burst out beacon and CAB traffic.
2479		 */
2480		qi.tqi_aifs = ATH_BEACON_AIFS_DEFAULT;
2481		qi.tqi_cwmin = ATH_BEACON_CWMIN_DEFAULT;
2482		qi.tqi_cwmax = ATH_BEACON_CWMAX_DEFAULT;
2483	} else {
2484		struct wmeParams *wmep =
2485			&ic->ic_wme.wme_chanParams.cap_wmeParams[WME_AC_BE];
2486		/*
2487		 * Adhoc mode; important thing is to use 2x cwmin.
2488		 */
2489		qi.tqi_aifs = wmep->wmep_aifsn;
2490		qi.tqi_cwmin = 2*ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
2491		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
2492	}
2493
2494	if (!ath_hal_settxqueueprops(ah, sc->sc_bhalq, &qi)) {
2495		device_printf(sc->sc_dev, "unable to update parameters for "
2496			"beacon hardware queue!\n");
2497		return 0;
2498	} else {
2499		ath_hal_resettxqueue(ah, sc->sc_bhalq); /* push to h/w */
2500		return 1;
2501	}
2502#undef ATH_EXPONENT_TO_VALUE
2503}
2504
2505/*
2506 * Allocate and setup an initial beacon frame.
2507 */
2508static int
2509ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
2510{
2511	struct ieee80211vap *vap = ni->ni_vap;
2512	struct ath_vap *avp = ATH_VAP(vap);
2513	struct ath_buf *bf;
2514	struct mbuf *m;
2515	int error;
2516
2517	bf = avp->av_bcbuf;
2518	if (bf->bf_m != NULL) {
2519		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2520		m_freem(bf->bf_m);
2521		bf->bf_m = NULL;
2522	}
2523	if (bf->bf_node != NULL) {
2524		ieee80211_free_node(bf->bf_node);
2525		bf->bf_node = NULL;
2526	}
2527
2528	/*
2529	 * NB: the beacon data buffer must be 32-bit aligned;
2530	 * we assume the mbuf routines will return us something
2531	 * with this alignment (perhaps should assert).
2532	 */
2533	m = ieee80211_beacon_alloc(ni, &avp->av_boff);
2534	if (m == NULL) {
2535		device_printf(sc->sc_dev, "%s: cannot get mbuf\n", __func__);
2536		sc->sc_stats.ast_be_nombuf++;
2537		return ENOMEM;
2538	}
2539	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2540				     bf->bf_segs, &bf->bf_nseg,
2541				     BUS_DMA_NOWAIT);
2542	if (error != 0) {
2543		device_printf(sc->sc_dev,
2544		    "%s: cannot map mbuf, bus_dmamap_load_mbuf_sg returns %d\n",
2545		    __func__, error);
2546		m_freem(m);
2547		return error;
2548	}
2549
2550	/*
2551	 * Calculate a TSF adjustment factor required for staggered
2552	 * beacons.  Note that we assume the format of the beacon
2553	 * frame leaves the tstamp field immediately following the
2554	 * header.
2555	 */
2556	if (sc->sc_stagbeacons && avp->av_bslot > 0) {
2557		uint64_t tsfadjust;
2558		struct ieee80211_frame *wh;
2559
2560		/*
2561		 * The beacon interval is in TU's; the TSF is in usecs.
2562		 * We figure out how many TU's to add to align the timestamp
2563		 * then convert to TSF units and handle byte swapping before
2564		 * inserting it in the frame.  The hardware will then add this
2565		 * each time a beacon frame is sent.  Note that we align vap's
2566		 * 1..N and leave vap 0 untouched.  This means vap 0 has a
2567		 * timestamp in one beacon interval while the others get a
2568		 * timstamp aligned to the next interval.
2569		 */
2570		tsfadjust = ni->ni_intval *
2571		    (ATH_BCBUF - avp->av_bslot) / ATH_BCBUF;
2572		tsfadjust = htole64(tsfadjust << 10);	/* TU -> TSF */
2573
2574		DPRINTF(sc, ATH_DEBUG_BEACON,
2575		    "%s: %s beacons bslot %d intval %u tsfadjust %llu\n",
2576		    __func__, sc->sc_stagbeacons ? "stagger" : "burst",
2577		    avp->av_bslot, ni->ni_intval,
2578		    (long long unsigned) le64toh(tsfadjust));
2579
2580		wh = mtod(m, struct ieee80211_frame *);
2581		memcpy(&wh[1], &tsfadjust, sizeof(tsfadjust));
2582	}
2583	bf->bf_m = m;
2584	bf->bf_node = ieee80211_ref_node(ni);
2585
2586	return 0;
2587}
2588
2589/*
2590 * Setup the beacon frame for transmit.
2591 */
2592static void
2593ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
2594{
2595#define	USE_SHPREAMBLE(_ic) \
2596	(((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
2597		== IEEE80211_F_SHPREAMBLE)
2598	struct ieee80211_node *ni = bf->bf_node;
2599	struct ieee80211com *ic = ni->ni_ic;
2600	struct mbuf *m = bf->bf_m;
2601	struct ath_hal *ah = sc->sc_ah;
2602	struct ath_desc *ds;
2603	int flags, antenna;
2604	const HAL_RATE_TABLE *rt;
2605	u_int8_t rix, rate;
2606
2607	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: m %p len %u\n",
2608		__func__, m, m->m_len);
2609
2610	/* setup descriptors */
2611	ds = bf->bf_desc;
2612
2613	flags = HAL_TXDESC_NOACK;
2614	if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
2615		ds->ds_link = bf->bf_daddr;	/* self-linked */
2616		flags |= HAL_TXDESC_VEOL;
2617		/*
2618		 * Let hardware handle antenna switching.
2619		 */
2620		antenna = sc->sc_txantenna;
2621	} else {
2622		ds->ds_link = 0;
2623		/*
2624		 * Switch antenna every 4 beacons.
2625		 * XXX assumes two antenna
2626		 */
2627		if (sc->sc_txantenna != 0)
2628			antenna = sc->sc_txantenna;
2629		else if (sc->sc_stagbeacons && sc->sc_nbcnvaps != 0)
2630			antenna = ((sc->sc_stats.ast_be_xmit / sc->sc_nbcnvaps) & 4 ? 2 : 1);
2631		else
2632			antenna = (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
2633	}
2634
2635	KASSERT(bf->bf_nseg == 1,
2636		("multi-segment beacon frame; nseg %u", bf->bf_nseg));
2637	ds->ds_data = bf->bf_segs[0].ds_addr;
2638	/*
2639	 * Calculate rate code.
2640	 * XXX everything at min xmit rate
2641	 */
2642	rix = 0;
2643	rt = sc->sc_currates;
2644	rate = rt->info[rix].rateCode;
2645	if (USE_SHPREAMBLE(ic))
2646		rate |= rt->info[rix].shortPreamble;
2647	ath_hal_setuptxdesc(ah, ds
2648		, m->m_len + IEEE80211_CRC_LEN	/* frame length */
2649		, sizeof(struct ieee80211_frame)/* header length */
2650		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
2651		, ni->ni_txpower		/* txpower XXX */
2652		, rate, 1			/* series 0 rate/tries */
2653		, HAL_TXKEYIX_INVALID		/* no encryption */
2654		, antenna			/* antenna mode */
2655		, flags				/* no ack, veol for beacons */
2656		, 0				/* rts/cts rate */
2657		, 0				/* rts/cts duration */
2658	);
2659	/* NB: beacon's BufLen must be a multiple of 4 bytes */
2660	ath_hal_filltxdesc(ah, ds
2661		, roundup(m->m_len, 4)		/* buffer length */
2662		, AH_TRUE			/* first segment */
2663		, AH_TRUE			/* last segment */
2664		, ds				/* first descriptor */
2665	);
2666#if 0
2667	ath_desc_swap(ds);
2668#endif
2669#undef USE_SHPREAMBLE
2670}
2671
2672static void
2673ath_beacon_update(struct ieee80211vap *vap, int item)
2674{
2675	struct ieee80211_beacon_offsets *bo = &ATH_VAP(vap)->av_boff;
2676
2677	setbit(bo->bo_flags, item);
2678}
2679
2680/*
2681 * Append the contents of src to dst; both queues
2682 * are assumed to be locked.
2683 */
2684static void
2685ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
2686{
2687	STAILQ_CONCAT(&dst->axq_q, &src->axq_q);
2688	dst->axq_link = src->axq_link;
2689	src->axq_link = NULL;
2690	dst->axq_depth += src->axq_depth;
2691	src->axq_depth = 0;
2692}
2693
2694/*
2695 * Transmit a beacon frame at SWBA.  Dynamic updates to the
2696 * frame contents are done as needed and the slot time is
2697 * also adjusted based on current state.
2698 */
2699static void
2700ath_beacon_proc(void *arg, int pending)
2701{
2702	struct ath_softc *sc = arg;
2703	struct ath_hal *ah = sc->sc_ah;
2704	struct ieee80211vap *vap;
2705	struct ath_buf *bf;
2706	int slot, otherant;
2707	uint32_t bfaddr;
2708
2709	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
2710		__func__, pending);
2711	/*
2712	 * Check if the previous beacon has gone out.  If
2713	 * not don't try to post another, skip this period
2714	 * and wait for the next.  Missed beacons indicate
2715	 * a problem and should not occur.  If we miss too
2716	 * many consecutive beacons reset the device.
2717	 */
2718	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
2719		sc->sc_bmisscount++;
2720		sc->sc_stats.ast_be_missed++;
2721		DPRINTF(sc, ATH_DEBUG_BEACON,
2722			"%s: missed %u consecutive beacons\n",
2723			__func__, sc->sc_bmisscount);
2724		if (sc->sc_bmisscount >= ath_bstuck_threshold)
2725			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
2726		return;
2727	}
2728	if (sc->sc_bmisscount != 0) {
2729		DPRINTF(sc, ATH_DEBUG_BEACON,
2730			"%s: resume beacon xmit after %u misses\n",
2731			__func__, sc->sc_bmisscount);
2732		sc->sc_bmisscount = 0;
2733	}
2734
2735	if (sc->sc_stagbeacons) {			/* staggered beacons */
2736		struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2737		uint32_t tsftu;
2738
2739		tsftu = ath_hal_gettsf32(ah) >> 10;
2740		/* XXX lintval */
2741		slot = ((tsftu % ic->ic_lintval) * ATH_BCBUF) / ic->ic_lintval;
2742		vap = sc->sc_bslot[(slot+1) % ATH_BCBUF];
2743		bfaddr = 0;
2744		if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2745			bf = ath_beacon_generate(sc, vap);
2746			if (bf != NULL)
2747				bfaddr = bf->bf_daddr;
2748		}
2749	} else {					/* burst'd beacons */
2750		uint32_t *bflink = &bfaddr;
2751
2752		for (slot = 0; slot < ATH_BCBUF; slot++) {
2753			vap = sc->sc_bslot[slot];
2754			if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2755				bf = ath_beacon_generate(sc, vap);
2756				if (bf != NULL) {
2757					*bflink = bf->bf_daddr;
2758					bflink = &bf->bf_desc->ds_link;
2759				}
2760			}
2761		}
2762		*bflink = 0;				/* terminate list */
2763	}
2764
2765	/*
2766	 * Handle slot time change when a non-ERP station joins/leaves
2767	 * an 11g network.  The 802.11 layer notifies us via callback,
2768	 * we mark updateslot, then wait one beacon before effecting
2769	 * the change.  This gives associated stations at least one
2770	 * beacon interval to note the state change.
2771	 */
2772	/* XXX locking */
2773	if (sc->sc_updateslot == UPDATE) {
2774		sc->sc_updateslot = COMMIT;	/* commit next beacon */
2775		sc->sc_slotupdate = slot;
2776	} else if (sc->sc_updateslot == COMMIT && sc->sc_slotupdate == slot)
2777		ath_setslottime(sc);		/* commit change to h/w */
2778
2779	/*
2780	 * Check recent per-antenna transmit statistics and flip
2781	 * the default antenna if noticeably more frames went out
2782	 * on the non-default antenna.
2783	 * XXX assumes 2 anntenae
2784	 */
2785	if (!sc->sc_diversity && (!sc->sc_stagbeacons || slot == 0)) {
2786		otherant = sc->sc_defant & 1 ? 2 : 1;
2787		if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
2788			ath_setdefantenna(sc, otherant);
2789		sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
2790	}
2791
2792	if (bfaddr != 0) {
2793		/*
2794		 * Stop any current dma and put the new frame on the queue.
2795		 * This should never fail since we check above that no frames
2796		 * are still pending on the queue.
2797		 */
2798		if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
2799			DPRINTF(sc, ATH_DEBUG_ANY,
2800				"%s: beacon queue %u did not stop?\n",
2801				__func__, sc->sc_bhalq);
2802		}
2803		/* NB: cabq traffic should already be queued and primed */
2804		ath_hal_puttxbuf(ah, sc->sc_bhalq, bfaddr);
2805		ath_hal_txstart(ah, sc->sc_bhalq);
2806
2807		sc->sc_stats.ast_be_xmit++;
2808	}
2809}
2810
2811static struct ath_buf *
2812ath_beacon_generate(struct ath_softc *sc, struct ieee80211vap *vap)
2813{
2814	struct ath_vap *avp = ATH_VAP(vap);
2815	struct ath_txq *cabq = sc->sc_cabq;
2816	struct ath_buf *bf;
2817	struct mbuf *m;
2818	int nmcastq, error;
2819
2820	KASSERT(vap->iv_state >= IEEE80211_S_RUN,
2821	    ("not running, state %d", vap->iv_state));
2822	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
2823
2824	/*
2825	 * Update dynamic beacon contents.  If this returns
2826	 * non-zero then we need to remap the memory because
2827	 * the beacon frame changed size (probably because
2828	 * of the TIM bitmap).
2829	 */
2830	bf = avp->av_bcbuf;
2831	m = bf->bf_m;
2832	nmcastq = avp->av_mcastq.axq_depth;
2833	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, nmcastq)) {
2834		/* XXX too conservative? */
2835		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2836		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2837					     bf->bf_segs, &bf->bf_nseg,
2838					     BUS_DMA_NOWAIT);
2839		if (error != 0) {
2840			if_printf(vap->iv_ifp,
2841			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
2842			    __func__, error);
2843			return NULL;
2844		}
2845	}
2846	if ((avp->av_boff.bo_tim[4] & 1) && cabq->axq_depth) {
2847		DPRINTF(sc, ATH_DEBUG_BEACON,
2848		    "%s: cabq did not drain, mcastq %u cabq %u\n",
2849		    __func__, nmcastq, cabq->axq_depth);
2850		sc->sc_stats.ast_cabq_busy++;
2851		if (sc->sc_nvaps > 1 && sc->sc_stagbeacons) {
2852			/*
2853			 * CABQ traffic from a previous vap is still pending.
2854			 * We must drain the q before this beacon frame goes
2855			 * out as otherwise this vap's stations will get cab
2856			 * frames from a different vap.
2857			 * XXX could be slow causing us to miss DBA
2858			 */
2859			ath_tx_draintxq(sc, cabq);
2860		}
2861	}
2862	ath_beacon_setup(sc, bf);
2863	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
2864
2865	/*
2866	 * Enable the CAB queue before the beacon queue to
2867	 * insure cab frames are triggered by this beacon.
2868	 */
2869	if (avp->av_boff.bo_tim[4] & 1) {
2870		struct ath_hal *ah = sc->sc_ah;
2871
2872		/* NB: only at DTIM */
2873		ATH_TXQ_LOCK(cabq);
2874		ATH_TXQ_LOCK(&avp->av_mcastq);
2875		if (nmcastq) {
2876			struct ath_buf *bfm;
2877
2878			/*
2879			 * Move frames from the s/w mcast q to the h/w cab q.
2880			 * XXX MORE_DATA bit
2881			 */
2882			bfm = STAILQ_FIRST(&avp->av_mcastq.axq_q);
2883			if (cabq->axq_link != NULL) {
2884				*cabq->axq_link = bfm->bf_daddr;
2885			} else
2886				ath_hal_puttxbuf(ah, cabq->axq_qnum,
2887					bfm->bf_daddr);
2888			ath_txqmove(cabq, &avp->av_mcastq);
2889
2890			sc->sc_stats.ast_cabq_xmit += nmcastq;
2891		}
2892		/* NB: gated by beacon so safe to start here */
2893		ath_hal_txstart(ah, cabq->axq_qnum);
2894		ATH_TXQ_UNLOCK(cabq);
2895		ATH_TXQ_UNLOCK(&avp->av_mcastq);
2896	}
2897	return bf;
2898}
2899
2900static void
2901ath_beacon_start_adhoc(struct ath_softc *sc, struct ieee80211vap *vap)
2902{
2903	struct ath_vap *avp = ATH_VAP(vap);
2904	struct ath_hal *ah = sc->sc_ah;
2905	struct ath_buf *bf;
2906	struct mbuf *m;
2907	int error;
2908
2909	KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
2910
2911	/*
2912	 * Update dynamic beacon contents.  If this returns
2913	 * non-zero then we need to remap the memory because
2914	 * the beacon frame changed size (probably because
2915	 * of the TIM bitmap).
2916	 */
2917	bf = avp->av_bcbuf;
2918	m = bf->bf_m;
2919	if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, 0)) {
2920		/* XXX too conservative? */
2921		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2922		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2923					     bf->bf_segs, &bf->bf_nseg,
2924					     BUS_DMA_NOWAIT);
2925		if (error != 0) {
2926			if_printf(vap->iv_ifp,
2927			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
2928			    __func__, error);
2929			return;
2930		}
2931	}
2932	ath_beacon_setup(sc, bf);
2933	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
2934
2935	/* NB: caller is known to have already stopped tx dma */
2936	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
2937	ath_hal_txstart(ah, sc->sc_bhalq);
2938}
2939
2940/*
2941 * Reset the hardware after detecting beacons have stopped.
2942 */
2943static void
2944ath_bstuck_proc(void *arg, int pending)
2945{
2946	struct ath_softc *sc = arg;
2947	struct ifnet *ifp = sc->sc_ifp;
2948
2949	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
2950		sc->sc_bmisscount);
2951	sc->sc_stats.ast_bstuck++;
2952	ath_reset(ifp);
2953}
2954
2955/*
2956 * Reclaim beacon resources and return buffer to the pool.
2957 */
2958static void
2959ath_beacon_return(struct ath_softc *sc, struct ath_buf *bf)
2960{
2961
2962	if (bf->bf_m != NULL) {
2963		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2964		m_freem(bf->bf_m);
2965		bf->bf_m = NULL;
2966	}
2967	if (bf->bf_node != NULL) {
2968		ieee80211_free_node(bf->bf_node);
2969		bf->bf_node = NULL;
2970	}
2971	STAILQ_INSERT_TAIL(&sc->sc_bbuf, bf, bf_list);
2972}
2973
2974/*
2975 * Reclaim beacon resources.
2976 */
2977static void
2978ath_beacon_free(struct ath_softc *sc)
2979{
2980	struct ath_buf *bf;
2981
2982	STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
2983		if (bf->bf_m != NULL) {
2984			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2985			m_freem(bf->bf_m);
2986			bf->bf_m = NULL;
2987		}
2988		if (bf->bf_node != NULL) {
2989			ieee80211_free_node(bf->bf_node);
2990			bf->bf_node = NULL;
2991		}
2992	}
2993}
2994
2995/*
2996 * Configure the beacon and sleep timers.
2997 *
2998 * When operating as an AP this resets the TSF and sets
2999 * up the hardware to notify us when we need to issue beacons.
3000 *
3001 * When operating in station mode this sets up the beacon
3002 * timers according to the timestamp of the last received
3003 * beacon and the current TSF, configures PCF and DTIM
3004 * handling, programs the sleep registers so the hardware
3005 * will wakeup in time to receive beacons, and configures
3006 * the beacon miss handling so we'll receive a BMISS
3007 * interrupt when we stop seeing beacons from the AP
3008 * we've associated with.
3009 */
3010static void
3011ath_beacon_config(struct ath_softc *sc, struct ieee80211vap *vap)
3012{
3013#define	TSF_TO_TU(_h,_l) \
3014	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
3015#define	FUDGE	2
3016	struct ath_hal *ah = sc->sc_ah;
3017	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3018	struct ieee80211_node *ni;
3019	u_int32_t nexttbtt, intval, tsftu;
3020	u_int64_t tsf;
3021
3022	if (vap == NULL)
3023		vap = TAILQ_FIRST(&ic->ic_vaps);	/* XXX */
3024	ni = vap->iv_bss;
3025
3026	/* extract tstamp from last beacon and convert to TU */
3027	nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
3028			     LE_READ_4(ni->ni_tstamp.data));
3029	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3030	    ic->ic_opmode == IEEE80211_M_MBSS) {
3031		/*
3032		 * For multi-bss ap/mesh support beacons are either staggered
3033		 * evenly over N slots or burst together.  For the former
3034		 * arrange for the SWBA to be delivered for each slot.
3035		 * Slots that are not occupied will generate nothing.
3036		 */
3037		/* NB: the beacon interval is kept internally in TU's */
3038		intval = ni->ni_intval & HAL_BEACON_PERIOD;
3039		if (sc->sc_stagbeacons)
3040			intval /= ATH_BCBUF;
3041	} else {
3042		/* NB: the beacon interval is kept internally in TU's */
3043		intval = ni->ni_intval & HAL_BEACON_PERIOD;
3044	}
3045	if (nexttbtt == 0)		/* e.g. for ap mode */
3046		nexttbtt = intval;
3047	else if (intval)		/* NB: can be 0 for monitor mode */
3048		nexttbtt = roundup(nexttbtt, intval);
3049	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
3050		__func__, nexttbtt, intval, ni->ni_intval);
3051	if (ic->ic_opmode == IEEE80211_M_STA && !sc->sc_swbmiss) {
3052		HAL_BEACON_STATE bs;
3053		int dtimperiod, dtimcount;
3054		int cfpperiod, cfpcount;
3055
3056		/*
3057		 * Setup dtim and cfp parameters according to
3058		 * last beacon we received (which may be none).
3059		 */
3060		dtimperiod = ni->ni_dtim_period;
3061		if (dtimperiod <= 0)		/* NB: 0 if not known */
3062			dtimperiod = 1;
3063		dtimcount = ni->ni_dtim_count;
3064		if (dtimcount >= dtimperiod)	/* NB: sanity check */
3065			dtimcount = 0;		/* XXX? */
3066		cfpperiod = 1;			/* NB: no PCF support yet */
3067		cfpcount = 0;
3068		/*
3069		 * Pull nexttbtt forward to reflect the current
3070		 * TSF and calculate dtim+cfp state for the result.
3071		 */
3072		tsf = ath_hal_gettsf64(ah);
3073		tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3074		do {
3075			nexttbtt += intval;
3076			if (--dtimcount < 0) {
3077				dtimcount = dtimperiod - 1;
3078				if (--cfpcount < 0)
3079					cfpcount = cfpperiod - 1;
3080			}
3081		} while (nexttbtt < tsftu);
3082		memset(&bs, 0, sizeof(bs));
3083		bs.bs_intval = intval;
3084		bs.bs_nexttbtt = nexttbtt;
3085		bs.bs_dtimperiod = dtimperiod*intval;
3086		bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
3087		bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
3088		bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
3089		bs.bs_cfpmaxduration = 0;
3090#if 0
3091		/*
3092		 * The 802.11 layer records the offset to the DTIM
3093		 * bitmap while receiving beacons; use it here to
3094		 * enable h/w detection of our AID being marked in
3095		 * the bitmap vector (to indicate frames for us are
3096		 * pending at the AP).
3097		 * XXX do DTIM handling in s/w to WAR old h/w bugs
3098		 * XXX enable based on h/w rev for newer chips
3099		 */
3100		bs.bs_timoffset = ni->ni_timoff;
3101#endif
3102		/*
3103		 * Calculate the number of consecutive beacons to miss
3104		 * before taking a BMISS interrupt.
3105		 * Note that we clamp the result to at most 10 beacons.
3106		 */
3107		bs.bs_bmissthreshold = vap->iv_bmissthreshold;
3108		if (bs.bs_bmissthreshold > 10)
3109			bs.bs_bmissthreshold = 10;
3110		else if (bs.bs_bmissthreshold <= 0)
3111			bs.bs_bmissthreshold = 1;
3112
3113		/*
3114		 * Calculate sleep duration.  The configuration is
3115		 * given in ms.  We insure a multiple of the beacon
3116		 * period is used.  Also, if the sleep duration is
3117		 * greater than the DTIM period then it makes senses
3118		 * to make it a multiple of that.
3119		 *
3120		 * XXX fixed at 100ms
3121		 */
3122		bs.bs_sleepduration =
3123			roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
3124		if (bs.bs_sleepduration > bs.bs_dtimperiod)
3125			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
3126
3127		DPRINTF(sc, ATH_DEBUG_BEACON,
3128			"%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"
3129			, __func__
3130			, tsf, tsftu
3131			, bs.bs_intval
3132			, bs.bs_nexttbtt
3133			, bs.bs_dtimperiod
3134			, bs.bs_nextdtim
3135			, bs.bs_bmissthreshold
3136			, bs.bs_sleepduration
3137			, bs.bs_cfpperiod
3138			, bs.bs_cfpmaxduration
3139			, bs.bs_cfpnext
3140			, bs.bs_timoffset
3141		);
3142		ath_hal_intrset(ah, 0);
3143		ath_hal_beacontimers(ah, &bs);
3144		sc->sc_imask |= HAL_INT_BMISS;
3145		ath_hal_intrset(ah, sc->sc_imask);
3146	} else {
3147		ath_hal_intrset(ah, 0);
3148		if (nexttbtt == intval)
3149			intval |= HAL_BEACON_RESET_TSF;
3150		if (ic->ic_opmode == IEEE80211_M_IBSS) {
3151			/*
3152			 * In IBSS mode enable the beacon timers but only
3153			 * enable SWBA interrupts if we need to manually
3154			 * prepare beacon frames.  Otherwise we use a
3155			 * self-linked tx descriptor and let the hardware
3156			 * deal with things.
3157			 */
3158			intval |= HAL_BEACON_ENA;
3159			if (!sc->sc_hasveol)
3160				sc->sc_imask |= HAL_INT_SWBA;
3161			if ((intval & HAL_BEACON_RESET_TSF) == 0) {
3162				/*
3163				 * Pull nexttbtt forward to reflect
3164				 * the current TSF.
3165				 */
3166				tsf = ath_hal_gettsf64(ah);
3167				tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3168				do {
3169					nexttbtt += intval;
3170				} while (nexttbtt < tsftu);
3171			}
3172			ath_beaconq_config(sc);
3173		} else if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3174		    ic->ic_opmode == IEEE80211_M_MBSS) {
3175			/*
3176			 * In AP/mesh mode we enable the beacon timers
3177			 * and SWBA interrupts to prepare beacon frames.
3178			 */
3179			intval |= HAL_BEACON_ENA;
3180			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
3181			ath_beaconq_config(sc);
3182		}
3183		ath_hal_beaconinit(ah, nexttbtt, intval);
3184		sc->sc_bmisscount = 0;
3185		ath_hal_intrset(ah, sc->sc_imask);
3186		/*
3187		 * When using a self-linked beacon descriptor in
3188		 * ibss mode load it once here.
3189		 */
3190		if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
3191			ath_beacon_start_adhoc(sc, vap);
3192	}
3193	sc->sc_syncbeacon = 0;
3194#undef FUDGE
3195#undef TSF_TO_TU
3196}
3197
3198static void
3199ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3200{
3201	bus_addr_t *paddr = (bus_addr_t*) arg;
3202	KASSERT(error == 0, ("error %u on bus_dma callback", error));
3203	*paddr = segs->ds_addr;
3204}
3205
3206static int
3207ath_descdma_setup(struct ath_softc *sc,
3208	struct ath_descdma *dd, ath_bufhead *head,
3209	const char *name, int nbuf, int ndesc)
3210{
3211#define	DS2PHYS(_dd, _ds) \
3212	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3213	struct ifnet *ifp = sc->sc_ifp;
3214	struct ath_desc *ds;
3215	struct ath_buf *bf;
3216	int i, bsize, error;
3217
3218	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
3219	    __func__, name, nbuf, ndesc);
3220
3221	dd->dd_name = name;
3222	dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
3223
3224	/*
3225	 * Setup DMA descriptor area.
3226	 */
3227	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
3228		       PAGE_SIZE, 0,		/* alignment, bounds */
3229		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
3230		       BUS_SPACE_MAXADDR,	/* highaddr */
3231		       NULL, NULL,		/* filter, filterarg */
3232		       dd->dd_desc_len,		/* maxsize */
3233		       1,			/* nsegments */
3234		       dd->dd_desc_len,		/* maxsegsize */
3235		       BUS_DMA_ALLOCNOW,	/* flags */
3236		       NULL,			/* lockfunc */
3237		       NULL,			/* lockarg */
3238		       &dd->dd_dmat);
3239	if (error != 0) {
3240		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
3241		return error;
3242	}
3243
3244	/* allocate descriptors */
3245	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
3246	if (error != 0) {
3247		if_printf(ifp, "unable to create dmamap for %s descriptors, "
3248			"error %u\n", dd->dd_name, error);
3249		goto fail0;
3250	}
3251
3252	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
3253				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
3254				 &dd->dd_dmamap);
3255	if (error != 0) {
3256		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
3257			"error %u\n", nbuf * ndesc, dd->dd_name, error);
3258		goto fail1;
3259	}
3260
3261	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
3262				dd->dd_desc, dd->dd_desc_len,
3263				ath_load_cb, &dd->dd_desc_paddr,
3264				BUS_DMA_NOWAIT);
3265	if (error != 0) {
3266		if_printf(ifp, "unable to map %s descriptors, error %u\n",
3267			dd->dd_name, error);
3268		goto fail2;
3269	}
3270
3271	ds = dd->dd_desc;
3272	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
3273	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
3274	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
3275
3276	/* allocate rx buffers */
3277	bsize = sizeof(struct ath_buf) * nbuf;
3278	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
3279	if (bf == NULL) {
3280		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
3281			dd->dd_name, bsize);
3282		goto fail3;
3283	}
3284	dd->dd_bufptr = bf;
3285
3286	STAILQ_INIT(head);
3287	for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
3288		bf->bf_desc = ds;
3289		bf->bf_daddr = DS2PHYS(dd, ds);
3290		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3291				&bf->bf_dmamap);
3292		if (error != 0) {
3293			if_printf(ifp, "unable to create dmamap for %s "
3294				"buffer %u, error %u\n", dd->dd_name, i, error);
3295			ath_descdma_cleanup(sc, dd, head);
3296			return error;
3297		}
3298		STAILQ_INSERT_TAIL(head, bf, bf_list);
3299	}
3300	return 0;
3301fail3:
3302	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3303fail2:
3304	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3305fail1:
3306	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3307fail0:
3308	bus_dma_tag_destroy(dd->dd_dmat);
3309	memset(dd, 0, sizeof(*dd));
3310	return error;
3311#undef DS2PHYS
3312}
3313
3314static void
3315ath_descdma_cleanup(struct ath_softc *sc,
3316	struct ath_descdma *dd, ath_bufhead *head)
3317{
3318	struct ath_buf *bf;
3319	struct ieee80211_node *ni;
3320
3321	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3322	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3323	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3324	bus_dma_tag_destroy(dd->dd_dmat);
3325
3326	STAILQ_FOREACH(bf, head, bf_list) {
3327		if (bf->bf_m) {
3328			m_freem(bf->bf_m);
3329			bf->bf_m = NULL;
3330		}
3331		if (bf->bf_dmamap != NULL) {
3332			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
3333			bf->bf_dmamap = NULL;
3334		}
3335		ni = bf->bf_node;
3336		bf->bf_node = NULL;
3337		if (ni != NULL) {
3338			/*
3339			 * Reclaim node reference.
3340			 */
3341			ieee80211_free_node(ni);
3342		}
3343	}
3344
3345	STAILQ_INIT(head);
3346	free(dd->dd_bufptr, M_ATHDEV);
3347	memset(dd, 0, sizeof(*dd));
3348}
3349
3350static int
3351ath_desc_alloc(struct ath_softc *sc)
3352{
3353	int error;
3354
3355	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
3356			"rx", ath_rxbuf, 1);
3357	if (error != 0)
3358		return error;
3359
3360	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
3361			"tx", ath_txbuf, ATH_TXDESC);
3362	if (error != 0) {
3363		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3364		return error;
3365	}
3366
3367	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
3368			"beacon", ATH_BCBUF, 1);
3369	if (error != 0) {
3370		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3371		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3372		return error;
3373	}
3374	return 0;
3375}
3376
3377static void
3378ath_desc_free(struct ath_softc *sc)
3379{
3380
3381	if (sc->sc_bdma.dd_desc_len != 0)
3382		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
3383	if (sc->sc_txdma.dd_desc_len != 0)
3384		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3385	if (sc->sc_rxdma.dd_desc_len != 0)
3386		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3387}
3388
3389static struct ieee80211_node *
3390ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
3391{
3392	struct ieee80211com *ic = vap->iv_ic;
3393	struct ath_softc *sc = ic->ic_ifp->if_softc;
3394	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
3395	struct ath_node *an;
3396
3397	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
3398	if (an == NULL) {
3399		/* XXX stat+msg */
3400		return NULL;
3401	}
3402	ath_rate_node_init(sc, an);
3403
3404	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
3405	return &an->an_node;
3406}
3407
3408static void
3409ath_node_free(struct ieee80211_node *ni)
3410{
3411	struct ieee80211com *ic = ni->ni_ic;
3412        struct ath_softc *sc = ic->ic_ifp->if_softc;
3413
3414	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
3415
3416	ath_rate_node_cleanup(sc, ATH_NODE(ni));
3417	sc->sc_node_free(ni);
3418}
3419
3420static void
3421ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
3422{
3423	struct ieee80211com *ic = ni->ni_ic;
3424	struct ath_softc *sc = ic->ic_ifp->if_softc;
3425	struct ath_hal *ah = sc->sc_ah;
3426
3427	*rssi = ic->ic_node_getrssi(ni);
3428	if (ni->ni_chan != IEEE80211_CHAN_ANYC)
3429		*noise = ath_hal_getchannoise(ah, ni->ni_chan);
3430	else
3431		*noise = -95;		/* nominally correct */
3432}
3433
3434static int
3435ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
3436{
3437	struct ath_hal *ah = sc->sc_ah;
3438	int error;
3439	struct mbuf *m;
3440	struct ath_desc *ds;
3441
3442	m = bf->bf_m;
3443	if (m == NULL) {
3444		/*
3445		 * NB: by assigning a page to the rx dma buffer we
3446		 * implicitly satisfy the Atheros requirement that
3447		 * this buffer be cache-line-aligned and sized to be
3448		 * multiple of the cache line size.  Not doing this
3449		 * causes weird stuff to happen (for the 5210 at least).
3450		 */
3451		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
3452		if (m == NULL) {
3453			DPRINTF(sc, ATH_DEBUG_ANY,
3454				"%s: no mbuf/cluster\n", __func__);
3455			sc->sc_stats.ast_rx_nombuf++;
3456			return ENOMEM;
3457		}
3458		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
3459
3460		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
3461					     bf->bf_dmamap, m,
3462					     bf->bf_segs, &bf->bf_nseg,
3463					     BUS_DMA_NOWAIT);
3464		if (error != 0) {
3465			DPRINTF(sc, ATH_DEBUG_ANY,
3466			    "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
3467			    __func__, error);
3468			sc->sc_stats.ast_rx_busdma++;
3469			m_freem(m);
3470			return error;
3471		}
3472		KASSERT(bf->bf_nseg == 1,
3473			("multi-segment packet; nseg %u", bf->bf_nseg));
3474		bf->bf_m = m;
3475	}
3476	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
3477
3478	/*
3479	 * Setup descriptors.  For receive we always terminate
3480	 * the descriptor list with a self-linked entry so we'll
3481	 * not get overrun under high load (as can happen with a
3482	 * 5212 when ANI processing enables PHY error frames).
3483	 *
3484	 * To insure the last descriptor is self-linked we create
3485	 * each descriptor as self-linked and add it to the end.  As
3486	 * each additional descriptor is added the previous self-linked
3487	 * entry is ``fixed'' naturally.  This should be safe even
3488	 * if DMA is happening.  When processing RX interrupts we
3489	 * never remove/process the last, self-linked, entry on the
3490	 * descriptor list.  This insures the hardware always has
3491	 * someplace to write a new frame.
3492	 */
3493	ds = bf->bf_desc;
3494	ds->ds_link = bf->bf_daddr;	/* link to self */
3495	ds->ds_data = bf->bf_segs[0].ds_addr;
3496	ath_hal_setuprxdesc(ah, ds
3497		, m->m_len		/* buffer size */
3498		, 0
3499	);
3500
3501	if (sc->sc_rxlink != NULL)
3502		*sc->sc_rxlink = bf->bf_daddr;
3503	sc->sc_rxlink = &ds->ds_link;
3504	return 0;
3505}
3506
3507/*
3508 * Extend 15-bit time stamp from rx descriptor to
3509 * a full 64-bit TSF using the specified TSF.
3510 */
3511static __inline u_int64_t
3512ath_extend_tsf(u_int32_t rstamp, u_int64_t tsf)
3513{
3514	if ((tsf & 0x7fff) < rstamp)
3515		tsf -= 0x8000;
3516	return ((tsf &~ 0x7fff) | rstamp);
3517}
3518
3519/*
3520 * Intercept management frames to collect beacon rssi data
3521 * and to do ibss merges.
3522 */
3523static void
3524ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
3525	int subtype, int rssi, int nf)
3526{
3527	struct ieee80211vap *vap = ni->ni_vap;
3528	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
3529
3530	/*
3531	 * Call up first so subsequent work can use information
3532	 * potentially stored in the node (e.g. for ibss merge).
3533	 */
3534	ATH_VAP(vap)->av_recv_mgmt(ni, m, subtype, rssi, nf);
3535	switch (subtype) {
3536	case IEEE80211_FC0_SUBTYPE_BEACON:
3537		/* update rssi statistics for use by the hal */
3538		ATH_RSSI_LPF(sc->sc_halstats.ns_avgbrssi, rssi);
3539		if (sc->sc_syncbeacon &&
3540		    ni == vap->iv_bss && vap->iv_state == IEEE80211_S_RUN) {
3541			/*
3542			 * Resync beacon timers using the tsf of the beacon
3543			 * frame we just received.
3544			 */
3545			ath_beacon_config(sc, vap);
3546		}
3547		/* fall thru... */
3548	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
3549		if (vap->iv_opmode == IEEE80211_M_IBSS &&
3550		    vap->iv_state == IEEE80211_S_RUN) {
3551			uint32_t rstamp = sc->sc_lastrs->rs_tstamp;
3552			uint64_t tsf = ath_extend_tsf(rstamp,
3553				ath_hal_gettsf64(sc->sc_ah));
3554			/*
3555			 * Handle ibss merge as needed; check the tsf on the
3556			 * frame before attempting the merge.  The 802.11 spec
3557			 * says the station should change it's bssid to match
3558			 * the oldest station with the same ssid, where oldest
3559			 * is determined by the tsf.  Note that hardware
3560			 * reconfiguration happens through callback to
3561			 * ath_newstate as the state machine will go from
3562			 * RUN -> RUN when this happens.
3563			 */
3564			if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
3565				DPRINTF(sc, ATH_DEBUG_STATE,
3566				    "ibss merge, rstamp %u tsf %ju "
3567				    "tstamp %ju\n", rstamp, (uintmax_t)tsf,
3568				    (uintmax_t)ni->ni_tstamp.tsf);
3569				(void) ieee80211_ibss_merge(ni);
3570			}
3571		}
3572		break;
3573	}
3574}
3575
3576/*
3577 * Set the default antenna.
3578 */
3579static void
3580ath_setdefantenna(struct ath_softc *sc, u_int antenna)
3581{
3582	struct ath_hal *ah = sc->sc_ah;
3583
3584	/* XXX block beacon interrupts */
3585	ath_hal_setdefantenna(ah, antenna);
3586	if (sc->sc_defant != antenna)
3587		sc->sc_stats.ast_ant_defswitch++;
3588	sc->sc_defant = antenna;
3589	sc->sc_rxotherant = 0;
3590}
3591
3592static void
3593ath_rx_tap(struct ifnet *ifp, struct mbuf *m,
3594	const struct ath_rx_status *rs, u_int64_t tsf, int16_t nf)
3595{
3596#define	CHAN_HT20	htole32(IEEE80211_CHAN_HT20)
3597#define	CHAN_HT40U	htole32(IEEE80211_CHAN_HT40U)
3598#define	CHAN_HT40D	htole32(IEEE80211_CHAN_HT40D)
3599#define	CHAN_HT		(CHAN_HT20|CHAN_HT40U|CHAN_HT40D)
3600	struct ath_softc *sc = ifp->if_softc;
3601	const HAL_RATE_TABLE *rt;
3602	uint8_t rix;
3603
3604	rt = sc->sc_currates;
3605	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
3606	rix = rt->rateCodeToIndex[rs->rs_rate];
3607	sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
3608	sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
3609#ifdef AH_SUPPORT_AR5416
3610	sc->sc_rx_th.wr_chan_flags &= ~CHAN_HT;
3611	if (sc->sc_rx_th.wr_rate & IEEE80211_RATE_MCS) {	/* HT rate */
3612		struct ieee80211com *ic = ifp->if_l2com;
3613
3614		if ((rs->rs_flags & HAL_RX_2040) == 0)
3615			sc->sc_rx_th.wr_chan_flags |= CHAN_HT20;
3616		else if (IEEE80211_IS_CHAN_HT40U(ic->ic_curchan))
3617			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40U;
3618		else
3619			sc->sc_rx_th.wr_chan_flags |= CHAN_HT40D;
3620		if ((rs->rs_flags & HAL_RX_GI) == 0)
3621			sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_SHORTGI;
3622	}
3623#endif
3624	sc->sc_rx_th.wr_tsf = htole64(ath_extend_tsf(rs->rs_tstamp, tsf));
3625	if (rs->rs_status & HAL_RXERR_CRC)
3626		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
3627	/* XXX propagate other error flags from descriptor */
3628	sc->sc_rx_th.wr_antnoise = nf;
3629	sc->sc_rx_th.wr_antsignal = nf + rs->rs_rssi;
3630	sc->sc_rx_th.wr_antenna = rs->rs_antenna;
3631#undef CHAN_HT
3632#undef CHAN_HT20
3633#undef CHAN_HT40U
3634#undef CHAN_HT40D
3635}
3636
3637static void
3638ath_handle_micerror(struct ieee80211com *ic,
3639	struct ieee80211_frame *wh, int keyix)
3640{
3641	struct ieee80211_node *ni;
3642
3643	/* XXX recheck MIC to deal w/ chips that lie */
3644	/* XXX discard MIC errors on !data frames */
3645	ni = ieee80211_find_rxnode(ic, (const struct ieee80211_frame_min *) wh);
3646	if (ni != NULL) {
3647		ieee80211_notify_michael_failure(ni->ni_vap, wh, keyix);
3648		ieee80211_free_node(ni);
3649	}
3650}
3651
3652static void
3653ath_rx_proc(void *arg, int npending)
3654{
3655#define	PA2DESC(_sc, _pa) \
3656	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
3657		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
3658	struct ath_softc *sc = arg;
3659	struct ath_buf *bf;
3660	struct ifnet *ifp = sc->sc_ifp;
3661	struct ieee80211com *ic = ifp->if_l2com;
3662	struct ath_hal *ah = sc->sc_ah;
3663	struct ath_desc *ds;
3664	struct ath_rx_status *rs;
3665	struct mbuf *m;
3666	struct ieee80211_node *ni;
3667	int len, type, ngood;
3668	u_int phyerr;
3669	HAL_STATUS status;
3670	int16_t nf;
3671	u_int64_t tsf;
3672
3673	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
3674	ngood = 0;
3675	nf = ath_hal_getchannoise(ah, sc->sc_curchan);
3676	sc->sc_stats.ast_rx_noise = nf;
3677	tsf = ath_hal_gettsf64(ah);
3678	do {
3679		bf = STAILQ_FIRST(&sc->sc_rxbuf);
3680		if (bf == NULL) {		/* NB: shouldn't happen */
3681			if_printf(ifp, "%s: no buffer!\n", __func__);
3682			break;
3683		}
3684		m = bf->bf_m;
3685		if (m == NULL) {		/* NB: shouldn't happen */
3686			/*
3687			 * If mbuf allocation failed previously there
3688			 * will be no mbuf; try again to re-populate it.
3689			 */
3690			/* XXX make debug msg */
3691			if_printf(ifp, "%s: no mbuf!\n", __func__);
3692			STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
3693			goto rx_next;
3694		}
3695		ds = bf->bf_desc;
3696		if (ds->ds_link == bf->bf_daddr) {
3697			/* NB: never process the self-linked entry at the end */
3698			break;
3699		}
3700		/* XXX sync descriptor memory */
3701		/*
3702		 * Must provide the virtual address of the current
3703		 * descriptor, the physical address, and the virtual
3704		 * address of the next descriptor in the h/w chain.
3705		 * This allows the HAL to look ahead to see if the
3706		 * hardware is done with a descriptor by checking the
3707		 * done bit in the following descriptor and the address
3708		 * of the current descriptor the DMA engine is working
3709		 * on.  All this is necessary because of our use of
3710		 * a self-linked list to avoid rx overruns.
3711		 */
3712		rs = &bf->bf_status.ds_rxstat;
3713		status = ath_hal_rxprocdesc(ah, ds,
3714				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
3715#ifdef ATH_DEBUG
3716		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
3717			ath_printrxbuf(sc, bf, 0, status == HAL_OK);
3718#endif
3719		if (status == HAL_EINPROGRESS)
3720			break;
3721		STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
3722		if (rs->rs_status != 0) {
3723			if (rs->rs_status & HAL_RXERR_CRC)
3724				sc->sc_stats.ast_rx_crcerr++;
3725			if (rs->rs_status & HAL_RXERR_FIFO)
3726				sc->sc_stats.ast_rx_fifoerr++;
3727			if (rs->rs_status & HAL_RXERR_PHY) {
3728				sc->sc_stats.ast_rx_phyerr++;
3729				phyerr = rs->rs_phyerr & 0x1f;
3730				sc->sc_stats.ast_rx_phy[phyerr]++;
3731				goto rx_error;	/* NB: don't count in ierrors */
3732			}
3733			if (rs->rs_status & HAL_RXERR_DECRYPT) {
3734				/*
3735				 * Decrypt error.  If the error occurred
3736				 * because there was no hardware key, then
3737				 * let the frame through so the upper layers
3738				 * can process it.  This is necessary for 5210
3739				 * parts which have no way to setup a ``clear''
3740				 * key cache entry.
3741				 *
3742				 * XXX do key cache faulting
3743				 */
3744				if (rs->rs_keyix == HAL_RXKEYIX_INVALID)
3745					goto rx_accept;
3746				sc->sc_stats.ast_rx_badcrypt++;
3747			}
3748			if (rs->rs_status & HAL_RXERR_MIC) {
3749				sc->sc_stats.ast_rx_badmic++;
3750				/*
3751				 * Do minimal work required to hand off
3752				 * the 802.11 header for notification.
3753				 */
3754				/* XXX frag's and qos frames */
3755				len = rs->rs_datalen;
3756				if (len >= sizeof (struct ieee80211_frame)) {
3757					bus_dmamap_sync(sc->sc_dmat,
3758					    bf->bf_dmamap,
3759					    BUS_DMASYNC_POSTREAD);
3760					ath_handle_micerror(ic,
3761					    mtod(m, struct ieee80211_frame *),
3762					    sc->sc_splitmic ?
3763						rs->rs_keyix-32 : rs->rs_keyix);
3764				}
3765			}
3766			ifp->if_ierrors++;
3767rx_error:
3768			/*
3769			 * Cleanup any pending partial frame.
3770			 */
3771			if (sc->sc_rxpending != NULL) {
3772				m_freem(sc->sc_rxpending);
3773				sc->sc_rxpending = NULL;
3774			}
3775			/*
3776			 * When a tap is present pass error frames
3777			 * that have been requested.  By default we
3778			 * pass decrypt+mic errors but others may be
3779			 * interesting (e.g. crc).
3780			 */
3781			if (ieee80211_radiotap_active(ic) &&
3782			    (rs->rs_status & sc->sc_monpass)) {
3783				bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3784				    BUS_DMASYNC_POSTREAD);
3785				/* NB: bpf needs the mbuf length setup */
3786				len = rs->rs_datalen;
3787				m->m_pkthdr.len = m->m_len = len;
3788				ath_rx_tap(ifp, m, rs, tsf, nf);
3789				ieee80211_radiotap_rx_all(ic, m);
3790			}
3791			/* XXX pass MIC errors up for s/w reclaculation */
3792			goto rx_next;
3793		}
3794rx_accept:
3795		/*
3796		 * Sync and unmap the frame.  At this point we're
3797		 * committed to passing the mbuf somewhere so clear
3798		 * bf_m; this means a new mbuf must be allocated
3799		 * when the rx descriptor is setup again to receive
3800		 * another frame.
3801		 */
3802		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3803		    BUS_DMASYNC_POSTREAD);
3804		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3805		bf->bf_m = NULL;
3806
3807		len = rs->rs_datalen;
3808		m->m_len = len;
3809
3810		if (rs->rs_more) {
3811			/*
3812			 * Frame spans multiple descriptors; save
3813			 * it for the next completed descriptor, it
3814			 * will be used to construct a jumbogram.
3815			 */
3816			if (sc->sc_rxpending != NULL) {
3817				/* NB: max frame size is currently 2 clusters */
3818				sc->sc_stats.ast_rx_toobig++;
3819				m_freem(sc->sc_rxpending);
3820			}
3821			m->m_pkthdr.rcvif = ifp;
3822			m->m_pkthdr.len = len;
3823			sc->sc_rxpending = m;
3824			goto rx_next;
3825		} else if (sc->sc_rxpending != NULL) {
3826			/*
3827			 * This is the second part of a jumbogram,
3828			 * chain it to the first mbuf, adjust the
3829			 * frame length, and clear the rxpending state.
3830			 */
3831			sc->sc_rxpending->m_next = m;
3832			sc->sc_rxpending->m_pkthdr.len += len;
3833			m = sc->sc_rxpending;
3834			sc->sc_rxpending = NULL;
3835		} else {
3836			/*
3837			 * Normal single-descriptor receive; setup
3838			 * the rcvif and packet length.
3839			 */
3840			m->m_pkthdr.rcvif = ifp;
3841			m->m_pkthdr.len = len;
3842		}
3843
3844		ifp->if_ipackets++;
3845		sc->sc_stats.ast_ant_rx[rs->rs_antenna]++;
3846
3847		/*
3848		 * Populate the rx status block.  When there are bpf
3849		 * listeners we do the additional work to provide
3850		 * complete status.  Otherwise we fill in only the
3851		 * material required by ieee80211_input.  Note that
3852		 * noise setting is filled in above.
3853		 */
3854		if (ieee80211_radiotap_active(ic))
3855			ath_rx_tap(ifp, m, rs, tsf, nf);
3856
3857		/*
3858		 * From this point on we assume the frame is at least
3859		 * as large as ieee80211_frame_min; verify that.
3860		 */
3861		if (len < IEEE80211_MIN_LEN) {
3862			if (!ieee80211_radiotap_active(ic)) {
3863				DPRINTF(sc, ATH_DEBUG_RECV,
3864				    "%s: short packet %d\n", __func__, len);
3865				sc->sc_stats.ast_rx_tooshort++;
3866			} else {
3867				/* NB: in particular this captures ack's */
3868				ieee80211_radiotap_rx_all(ic, m);
3869			}
3870			m_freem(m);
3871			goto rx_next;
3872		}
3873
3874		if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
3875			const HAL_RATE_TABLE *rt = sc->sc_currates;
3876			uint8_t rix = rt->rateCodeToIndex[rs->rs_rate];
3877
3878			ieee80211_dump_pkt(ic, mtod(m, caddr_t), len,
3879			    sc->sc_hwmap[rix].ieeerate, rs->rs_rssi);
3880		}
3881
3882		m_adj(m, -IEEE80211_CRC_LEN);
3883
3884		/*
3885		 * Locate the node for sender, track state, and then
3886		 * pass the (referenced) node up to the 802.11 layer
3887		 * for its use.
3888		 */
3889		ni = ieee80211_find_rxnode_withkey(ic,
3890			mtod(m, const struct ieee80211_frame_min *),
3891			rs->rs_keyix == HAL_RXKEYIX_INVALID ?
3892				IEEE80211_KEYIX_NONE : rs->rs_keyix);
3893		sc->sc_lastrs = rs;
3894		if (ni != NULL) {
3895		/* tag AMPDU aggregates for reorder processing */
3896		if (ni->ni_flags & IEEE80211_NODE_HT)
3897			m->m_flags |= M_AMPDU;
3898
3899			/*
3900			 * Sending station is known, dispatch directly.
3901			 */
3902			type = ieee80211_input(ni, m, rs->rs_rssi, nf);
3903			ieee80211_free_node(ni);
3904			/*
3905			 * Arrange to update the last rx timestamp only for
3906			 * frames from our ap when operating in station mode.
3907			 * This assumes the rx key is always setup when
3908			 * associated.
3909			 */
3910			if (ic->ic_opmode == IEEE80211_M_STA &&
3911			    rs->rs_keyix != HAL_RXKEYIX_INVALID)
3912				ngood++;
3913		} else {
3914			type = ieee80211_input_all(ic, m, rs->rs_rssi, nf);
3915		}
3916		/*
3917		 * Track rx rssi and do any rx antenna management.
3918		 */
3919		ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, rs->rs_rssi);
3920		if (sc->sc_diversity) {
3921			/*
3922			 * When using fast diversity, change the default rx
3923			 * antenna if diversity chooses the other antenna 3
3924			 * times in a row.
3925			 */
3926			if (sc->sc_defant != rs->rs_antenna) {
3927				if (++sc->sc_rxotherant >= 3)
3928					ath_setdefantenna(sc, rs->rs_antenna);
3929			} else
3930				sc->sc_rxotherant = 0;
3931		}
3932		if (sc->sc_softled) {
3933			/*
3934			 * Blink for any data frame.  Otherwise do a
3935			 * heartbeat-style blink when idle.  The latter
3936			 * is mainly for station mode where we depend on
3937			 * periodic beacon frames to trigger the poll event.
3938			 */
3939			if (type == IEEE80211_FC0_TYPE_DATA) {
3940				const HAL_RATE_TABLE *rt = sc->sc_currates;
3941				ath_led_event(sc,
3942				    rt->rateCodeToIndex[rs->rs_rate]);
3943			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
3944				ath_led_event(sc, 0);
3945		}
3946rx_next:
3947		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
3948	} while (ath_rxbuf_init(sc, bf) == 0);
3949
3950	/* rx signal state monitoring */
3951	ath_hal_rxmonitor(ah, &sc->sc_halstats, sc->sc_curchan);
3952	if (ngood)
3953		sc->sc_lastrx = tsf;
3954
3955	if ((ifp->if_drv_flags & IFF_DRV_OACTIVE) == 0) {
3956#ifdef IEEE80211_SUPPORT_SUPERG
3957		ieee80211_ff_age_all(ic, 100);
3958#endif
3959		if (!IFQ_IS_EMPTY(&ifp->if_snd))
3960			ath_start(ifp);
3961	}
3962#undef PA2DESC
3963}
3964
3965static void
3966ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
3967{
3968	txq->axq_qnum = qnum;
3969	txq->axq_ac = 0;
3970	txq->axq_depth = 0;
3971	txq->axq_intrcnt = 0;
3972	txq->axq_link = NULL;
3973	STAILQ_INIT(&txq->axq_q);
3974	ATH_TXQ_LOCK_INIT(sc, txq);
3975}
3976
3977/*
3978 * Setup a h/w transmit queue.
3979 */
3980static struct ath_txq *
3981ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
3982{
3983#define	N(a)	(sizeof(a)/sizeof(a[0]))
3984	struct ath_hal *ah = sc->sc_ah;
3985	HAL_TXQ_INFO qi;
3986	int qnum;
3987
3988	memset(&qi, 0, sizeof(qi));
3989	qi.tqi_subtype = subtype;
3990	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
3991	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
3992	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
3993	/*
3994	 * Enable interrupts only for EOL and DESC conditions.
3995	 * We mark tx descriptors to receive a DESC interrupt
3996	 * when a tx queue gets deep; otherwise waiting for the
3997	 * EOL to reap descriptors.  Note that this is done to
3998	 * reduce interrupt load and this only defers reaping
3999	 * descriptors, never transmitting frames.  Aside from
4000	 * reducing interrupts this also permits more concurrency.
4001	 * The only potential downside is if the tx queue backs
4002	 * up in which case the top half of the kernel may backup
4003	 * due to a lack of tx descriptors.
4004	 */
4005	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
4006	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
4007	if (qnum == -1) {
4008		/*
4009		 * NB: don't print a message, this happens
4010		 * normally on parts with too few tx queues
4011		 */
4012		return NULL;
4013	}
4014	if (qnum >= N(sc->sc_txq)) {
4015		device_printf(sc->sc_dev,
4016			"hal qnum %u out of range, max %zu!\n",
4017			qnum, N(sc->sc_txq));
4018		ath_hal_releasetxqueue(ah, qnum);
4019		return NULL;
4020	}
4021	if (!ATH_TXQ_SETUP(sc, qnum)) {
4022		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
4023		sc->sc_txqsetup |= 1<<qnum;
4024	}
4025	return &sc->sc_txq[qnum];
4026#undef N
4027}
4028
4029/*
4030 * Setup a hardware data transmit queue for the specified
4031 * access control.  The hal may not support all requested
4032 * queues in which case it will return a reference to a
4033 * previously setup queue.  We record the mapping from ac's
4034 * to h/w queues for use by ath_tx_start and also track
4035 * the set of h/w queues being used to optimize work in the
4036 * transmit interrupt handler and related routines.
4037 */
4038static int
4039ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
4040{
4041#define	N(a)	(sizeof(a)/sizeof(a[0]))
4042	struct ath_txq *txq;
4043
4044	if (ac >= N(sc->sc_ac2q)) {
4045		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
4046			ac, N(sc->sc_ac2q));
4047		return 0;
4048	}
4049	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
4050	if (txq != NULL) {
4051		txq->axq_ac = ac;
4052		sc->sc_ac2q[ac] = txq;
4053		return 1;
4054	} else
4055		return 0;
4056#undef N
4057}
4058
4059/*
4060 * Update WME parameters for a transmit queue.
4061 */
4062static int
4063ath_txq_update(struct ath_softc *sc, int ac)
4064{
4065#define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
4066#define	ATH_TXOP_TO_US(v)		(v<<5)
4067	struct ifnet *ifp = sc->sc_ifp;
4068	struct ieee80211com *ic = ifp->if_l2com;
4069	struct ath_txq *txq = sc->sc_ac2q[ac];
4070	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
4071	struct ath_hal *ah = sc->sc_ah;
4072	HAL_TXQ_INFO qi;
4073
4074	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
4075#ifdef IEEE80211_SUPPORT_TDMA
4076	if (sc->sc_tdma) {
4077		/*
4078		 * AIFS is zero so there's no pre-transmit wait.  The
4079		 * burst time defines the slot duration and is configured
4080		 * through net80211.  The QCU is setup to not do post-xmit
4081		 * back off, lockout all lower-priority QCU's, and fire
4082		 * off the DMA beacon alert timer which is setup based
4083		 * on the slot configuration.
4084		 */
4085		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4086			      | HAL_TXQ_TXERRINT_ENABLE
4087			      | HAL_TXQ_TXURNINT_ENABLE
4088			      | HAL_TXQ_TXEOLINT_ENABLE
4089			      | HAL_TXQ_DBA_GATED
4090			      | HAL_TXQ_BACKOFF_DISABLE
4091			      | HAL_TXQ_ARB_LOCKOUT_GLOBAL
4092			      ;
4093		qi.tqi_aifs = 0;
4094		/* XXX +dbaprep? */
4095		qi.tqi_readyTime = sc->sc_tdmaslotlen;
4096		qi.tqi_burstTime = qi.tqi_readyTime;
4097	} else {
4098#endif
4099		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4100			      | HAL_TXQ_TXERRINT_ENABLE
4101			      | HAL_TXQ_TXDESCINT_ENABLE
4102			      | HAL_TXQ_TXURNINT_ENABLE
4103			      ;
4104		qi.tqi_aifs = wmep->wmep_aifsn;
4105		qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
4106		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
4107		qi.tqi_readyTime = 0;
4108		qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
4109#ifdef IEEE80211_SUPPORT_TDMA
4110	}
4111#endif
4112
4113	DPRINTF(sc, ATH_DEBUG_RESET,
4114	    "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
4115	    __func__, txq->axq_qnum, qi.tqi_qflags,
4116	    qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
4117
4118	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
4119		if_printf(ifp, "unable to update hardware queue "
4120			"parameters for %s traffic!\n",
4121			ieee80211_wme_acnames[ac]);
4122		return 0;
4123	} else {
4124		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
4125		return 1;
4126	}
4127#undef ATH_TXOP_TO_US
4128#undef ATH_EXPONENT_TO_VALUE
4129}
4130
4131/*
4132 * Callback from the 802.11 layer to update WME parameters.
4133 */
4134static int
4135ath_wme_update(struct ieee80211com *ic)
4136{
4137	struct ath_softc *sc = ic->ic_ifp->if_softc;
4138
4139	return !ath_txq_update(sc, WME_AC_BE) ||
4140	    !ath_txq_update(sc, WME_AC_BK) ||
4141	    !ath_txq_update(sc, WME_AC_VI) ||
4142	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
4143}
4144
4145/*
4146 * Reclaim resources for a setup queue.
4147 */
4148static void
4149ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
4150{
4151
4152	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
4153	ATH_TXQ_LOCK_DESTROY(txq);
4154	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
4155}
4156
4157/*
4158 * Reclaim all tx queue resources.
4159 */
4160static void
4161ath_tx_cleanup(struct ath_softc *sc)
4162{
4163	int i;
4164
4165	ATH_TXBUF_LOCK_DESTROY(sc);
4166	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4167		if (ATH_TXQ_SETUP(sc, i))
4168			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
4169}
4170
4171/*
4172 * Return h/w rate index for an IEEE rate (w/o basic rate bit)
4173 * using the current rates in sc_rixmap.
4174 */
4175int
4176ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
4177{
4178	int rix = sc->sc_rixmap[rate];
4179	/* NB: return lowest rix for invalid rate */
4180	return (rix == 0xff ? 0 : rix);
4181}
4182
4183/*
4184 * Process completed xmit descriptors from the specified queue.
4185 */
4186static int
4187ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
4188{
4189	struct ath_hal *ah = sc->sc_ah;
4190	struct ifnet *ifp = sc->sc_ifp;
4191	struct ieee80211com *ic = ifp->if_l2com;
4192	struct ath_buf *bf, *last;
4193	struct ath_desc *ds, *ds0;
4194	struct ath_tx_status *ts;
4195	struct ieee80211_node *ni;
4196	struct ath_node *an;
4197	int sr, lr, pri, nacked;
4198	HAL_STATUS status;
4199
4200	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
4201		__func__, txq->axq_qnum,
4202		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4203		txq->axq_link);
4204	nacked = 0;
4205	for (;;) {
4206		ATH_TXQ_LOCK(txq);
4207		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
4208		bf = STAILQ_FIRST(&txq->axq_q);
4209		if (bf == NULL) {
4210			ATH_TXQ_UNLOCK(txq);
4211			break;
4212		}
4213		ds0 = &bf->bf_desc[0];
4214		ds = &bf->bf_desc[bf->bf_nseg - 1];
4215		ts = &bf->bf_status.ds_txstat;
4216		status = ath_hal_txprocdesc(ah, ds, ts);
4217#ifdef ATH_DEBUG
4218		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
4219			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4220			    status == HAL_OK);
4221#endif
4222		if (status == HAL_EINPROGRESS) {
4223			ATH_TXQ_UNLOCK(txq);
4224			break;
4225		}
4226		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
4227#ifdef IEEE80211_SUPPORT_TDMA
4228		if (txq->axq_depth > 0) {
4229			/*
4230			 * More frames follow.  Mark the buffer busy
4231			 * so it's not re-used while the hardware may
4232			 * still re-read the link field in the descriptor.
4233			 */
4234			bf->bf_flags |= ATH_BUF_BUSY;
4235		} else
4236#else
4237		if (txq->axq_depth == 0)
4238#endif
4239			txq->axq_link = NULL;
4240		ATH_TXQ_UNLOCK(txq);
4241
4242		ni = bf->bf_node;
4243		if (ni != NULL) {
4244			an = ATH_NODE(ni);
4245			if (ts->ts_status == 0) {
4246				u_int8_t txant = ts->ts_antenna;
4247				sc->sc_stats.ast_ant_tx[txant]++;
4248				sc->sc_ant_tx[txant]++;
4249				if (ts->ts_finaltsi != 0)
4250					sc->sc_stats.ast_tx_altrate++;
4251				pri = M_WME_GETAC(bf->bf_m);
4252				if (pri >= WME_AC_VO)
4253					ic->ic_wme.wme_hipri_traffic++;
4254				if ((bf->bf_txflags & HAL_TXDESC_NOACK) == 0)
4255					ni->ni_inact = ni->ni_inact_reload;
4256			} else {
4257				if (ts->ts_status & HAL_TXERR_XRETRY)
4258					sc->sc_stats.ast_tx_xretries++;
4259				if (ts->ts_status & HAL_TXERR_FIFO)
4260					sc->sc_stats.ast_tx_fifoerr++;
4261				if (ts->ts_status & HAL_TXERR_FILT)
4262					sc->sc_stats.ast_tx_filtered++;
4263				if (bf->bf_m->m_flags & M_FF)
4264					sc->sc_stats.ast_ff_txerr++;
4265			}
4266			sr = ts->ts_shortretry;
4267			lr = ts->ts_longretry;
4268			sc->sc_stats.ast_tx_shortretry += sr;
4269			sc->sc_stats.ast_tx_longretry += lr;
4270			/*
4271			 * Hand the descriptor to the rate control algorithm.
4272			 */
4273			if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
4274			    (bf->bf_txflags & HAL_TXDESC_NOACK) == 0) {
4275				/*
4276				 * If frame was ack'd update statistics,
4277				 * including the last rx time used to
4278				 * workaround phantom bmiss interrupts.
4279				 */
4280				if (ts->ts_status == 0) {
4281					nacked++;
4282					sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
4283					ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
4284						ts->ts_rssi);
4285				}
4286				ath_rate_tx_complete(sc, an, bf);
4287			}
4288			/*
4289			 * Do any tx complete callback.  Note this must
4290			 * be done before releasing the node reference.
4291			 */
4292			if (bf->bf_m->m_flags & M_TXCB)
4293				ieee80211_process_callback(ni, bf->bf_m,
4294				    (bf->bf_txflags & HAL_TXDESC_NOACK) == 0 ?
4295				        ts->ts_status : HAL_TXERR_XRETRY);
4296			ieee80211_free_node(ni);
4297		}
4298		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4299		    BUS_DMASYNC_POSTWRITE);
4300		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4301
4302		m_freem(bf->bf_m);
4303		bf->bf_m = NULL;
4304		bf->bf_node = NULL;
4305
4306		ATH_TXBUF_LOCK(sc);
4307		last = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
4308		if (last != NULL)
4309			last->bf_flags &= ~ATH_BUF_BUSY;
4310		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4311		ATH_TXBUF_UNLOCK(sc);
4312	}
4313#ifdef IEEE80211_SUPPORT_SUPERG
4314	/*
4315	 * Flush fast-frame staging queue when traffic slows.
4316	 */
4317	if (txq->axq_depth <= 1)
4318		ieee80211_ff_flush(ic, txq->axq_ac);
4319#endif
4320	return nacked;
4321}
4322
4323static __inline int
4324txqactive(struct ath_hal *ah, int qnum)
4325{
4326	u_int32_t txqs = 1<<qnum;
4327	ath_hal_gettxintrtxqs(ah, &txqs);
4328	return (txqs & (1<<qnum));
4329}
4330
4331/*
4332 * Deferred processing of transmit interrupt; special-cased
4333 * for a single hardware transmit queue (e.g. 5210 and 5211).
4334 */
4335static void
4336ath_tx_proc_q0(void *arg, int npending)
4337{
4338	struct ath_softc *sc = arg;
4339	struct ifnet *ifp = sc->sc_ifp;
4340
4341	if (txqactive(sc->sc_ah, 0) && ath_tx_processq(sc, &sc->sc_txq[0]))
4342		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4343	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
4344		ath_tx_processq(sc, sc->sc_cabq);
4345	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4346	sc->sc_wd_timer = 0;
4347
4348	if (sc->sc_softled)
4349		ath_led_event(sc, sc->sc_txrix);
4350
4351	ath_start(ifp);
4352}
4353
4354/*
4355 * Deferred processing of transmit interrupt; special-cased
4356 * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
4357 */
4358static void
4359ath_tx_proc_q0123(void *arg, int npending)
4360{
4361	struct ath_softc *sc = arg;
4362	struct ifnet *ifp = sc->sc_ifp;
4363	int nacked;
4364
4365	/*
4366	 * Process each active queue.
4367	 */
4368	nacked = 0;
4369	if (txqactive(sc->sc_ah, 0))
4370		nacked += ath_tx_processq(sc, &sc->sc_txq[0]);
4371	if (txqactive(sc->sc_ah, 1))
4372		nacked += ath_tx_processq(sc, &sc->sc_txq[1]);
4373	if (txqactive(sc->sc_ah, 2))
4374		nacked += ath_tx_processq(sc, &sc->sc_txq[2]);
4375	if (txqactive(sc->sc_ah, 3))
4376		nacked += ath_tx_processq(sc, &sc->sc_txq[3]);
4377	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
4378		ath_tx_processq(sc, sc->sc_cabq);
4379	if (nacked)
4380		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4381
4382	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4383	sc->sc_wd_timer = 0;
4384
4385	if (sc->sc_softled)
4386		ath_led_event(sc, sc->sc_txrix);
4387
4388	ath_start(ifp);
4389}
4390
4391/*
4392 * Deferred processing of transmit interrupt.
4393 */
4394static void
4395ath_tx_proc(void *arg, int npending)
4396{
4397	struct ath_softc *sc = arg;
4398	struct ifnet *ifp = sc->sc_ifp;
4399	int i, nacked;
4400
4401	/*
4402	 * Process each active queue.
4403	 */
4404	nacked = 0;
4405	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4406		if (ATH_TXQ_SETUP(sc, i) && txqactive(sc->sc_ah, i))
4407			nacked += ath_tx_processq(sc, &sc->sc_txq[i]);
4408	if (nacked)
4409		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4410
4411	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4412	sc->sc_wd_timer = 0;
4413
4414	if (sc->sc_softled)
4415		ath_led_event(sc, sc->sc_txrix);
4416
4417	ath_start(ifp);
4418}
4419
4420static void
4421ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
4422{
4423#ifdef ATH_DEBUG
4424	struct ath_hal *ah = sc->sc_ah;
4425#endif
4426	struct ieee80211_node *ni;
4427	struct ath_buf *bf;
4428	u_int ix;
4429
4430	/*
4431	 * NB: this assumes output has been stopped and
4432	 *     we do not need to block ath_tx_proc
4433	 */
4434	ATH_TXBUF_LOCK(sc);
4435	bf = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
4436	if (bf != NULL)
4437		bf->bf_flags &= ~ATH_BUF_BUSY;
4438	ATH_TXBUF_UNLOCK(sc);
4439	for (ix = 0;; ix++) {
4440		ATH_TXQ_LOCK(txq);
4441		bf = STAILQ_FIRST(&txq->axq_q);
4442		if (bf == NULL) {
4443			txq->axq_link = NULL;
4444			ATH_TXQ_UNLOCK(txq);
4445			break;
4446		}
4447		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
4448		ATH_TXQ_UNLOCK(txq);
4449#ifdef ATH_DEBUG
4450		if (sc->sc_debug & ATH_DEBUG_RESET) {
4451			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4452
4453			ath_printtxbuf(sc, bf, txq->axq_qnum, ix,
4454				ath_hal_txprocdesc(ah, bf->bf_desc,
4455				    &bf->bf_status.ds_txstat) == HAL_OK);
4456			ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
4457			    bf->bf_m->m_len, 0, -1);
4458		}
4459#endif /* ATH_DEBUG */
4460		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4461		ni = bf->bf_node;
4462		bf->bf_node = NULL;
4463		if (ni != NULL) {
4464			/*
4465			 * Do any callback and reclaim the node reference.
4466			 */
4467			if (bf->bf_m->m_flags & M_TXCB)
4468				ieee80211_process_callback(ni, bf->bf_m, -1);
4469			ieee80211_free_node(ni);
4470		}
4471		m_freem(bf->bf_m);
4472		bf->bf_m = NULL;
4473		bf->bf_flags &= ~ATH_BUF_BUSY;
4474
4475		ATH_TXBUF_LOCK(sc);
4476		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4477		ATH_TXBUF_UNLOCK(sc);
4478	}
4479}
4480
4481static void
4482ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
4483{
4484	struct ath_hal *ah = sc->sc_ah;
4485
4486	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4487	    __func__, txq->axq_qnum,
4488	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
4489	    txq->axq_link);
4490	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
4491}
4492
4493/*
4494 * Drain the transmit queues and reclaim resources.
4495 */
4496static void
4497ath_draintxq(struct ath_softc *sc)
4498{
4499	struct ath_hal *ah = sc->sc_ah;
4500	struct ifnet *ifp = sc->sc_ifp;
4501	int i;
4502
4503	/* XXX return value */
4504	if (!sc->sc_invalid) {
4505		/* don't touch the hardware if marked invalid */
4506		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4507		    __func__, sc->sc_bhalq,
4508		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
4509		    NULL);
4510		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
4511		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4512			if (ATH_TXQ_SETUP(sc, i))
4513				ath_tx_stopdma(sc, &sc->sc_txq[i]);
4514	}
4515	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4516		if (ATH_TXQ_SETUP(sc, i))
4517			ath_tx_draintxq(sc, &sc->sc_txq[i]);
4518#ifdef ATH_DEBUG
4519	if (sc->sc_debug & ATH_DEBUG_RESET) {
4520		struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
4521		if (bf != NULL && bf->bf_m != NULL) {
4522			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
4523				ath_hal_txprocdesc(ah, bf->bf_desc,
4524				    &bf->bf_status.ds_txstat) == HAL_OK);
4525			ieee80211_dump_pkt(ifp->if_l2com,
4526			    mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
4527			    0, -1);
4528		}
4529	}
4530#endif /* ATH_DEBUG */
4531	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4532	sc->sc_wd_timer = 0;
4533}
4534
4535/*
4536 * Disable the receive h/w in preparation for a reset.
4537 */
4538static void
4539ath_stoprecv(struct ath_softc *sc)
4540{
4541#define	PA2DESC(_sc, _pa) \
4542	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
4543		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
4544	struct ath_hal *ah = sc->sc_ah;
4545
4546	ath_hal_stoppcurecv(ah);	/* disable PCU */
4547	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
4548	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
4549	DELAY(3000);			/* 3ms is long enough for 1 frame */
4550#ifdef ATH_DEBUG
4551	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
4552		struct ath_buf *bf;
4553		u_int ix;
4554
4555		printf("%s: rx queue %p, link %p\n", __func__,
4556			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
4557		ix = 0;
4558		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4559			struct ath_desc *ds = bf->bf_desc;
4560			struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
4561			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
4562				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
4563			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
4564				ath_printrxbuf(sc, bf, ix, status == HAL_OK);
4565			ix++;
4566		}
4567	}
4568#endif
4569	if (sc->sc_rxpending != NULL) {
4570		m_freem(sc->sc_rxpending);
4571		sc->sc_rxpending = NULL;
4572	}
4573	sc->sc_rxlink = NULL;		/* just in case */
4574#undef PA2DESC
4575}
4576
4577/*
4578 * Enable the receive h/w following a reset.
4579 */
4580static int
4581ath_startrecv(struct ath_softc *sc)
4582{
4583	struct ath_hal *ah = sc->sc_ah;
4584	struct ath_buf *bf;
4585
4586	sc->sc_rxlink = NULL;
4587	sc->sc_rxpending = NULL;
4588	STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4589		int error = ath_rxbuf_init(sc, bf);
4590		if (error != 0) {
4591			DPRINTF(sc, ATH_DEBUG_RECV,
4592				"%s: ath_rxbuf_init failed %d\n",
4593				__func__, error);
4594			return error;
4595		}
4596	}
4597
4598	bf = STAILQ_FIRST(&sc->sc_rxbuf);
4599	ath_hal_putrxbuf(ah, bf->bf_daddr);
4600	ath_hal_rxena(ah);		/* enable recv descriptors */
4601	ath_mode_init(sc);		/* set filters, etc. */
4602	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
4603	return 0;
4604}
4605
4606/*
4607 * Update internal state after a channel change.
4608 */
4609static void
4610ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
4611{
4612	enum ieee80211_phymode mode;
4613
4614	/*
4615	 * Change channels and update the h/w rate map
4616	 * if we're switching; e.g. 11a to 11b/g.
4617	 */
4618	mode = ieee80211_chan2mode(chan);
4619	if (mode != sc->sc_curmode)
4620		ath_setcurmode(sc, mode);
4621	sc->sc_curchan = chan;
4622}
4623
4624/*
4625 * Set/change channels.  If the channel is really being changed,
4626 * it's done by resetting the chip.  To accomplish this we must
4627 * first cleanup any pending DMA, then restart stuff after a la
4628 * ath_init.
4629 */
4630static int
4631ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
4632{
4633	struct ifnet *ifp = sc->sc_ifp;
4634	struct ieee80211com *ic = ifp->if_l2com;
4635	struct ath_hal *ah = sc->sc_ah;
4636
4637	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
4638	    __func__, ieee80211_chan2ieee(ic, chan),
4639	    chan->ic_freq, chan->ic_flags);
4640	if (chan != sc->sc_curchan) {
4641		HAL_STATUS status;
4642		/*
4643		 * To switch channels clear any pending DMA operations;
4644		 * wait long enough for the RX fifo to drain, reset the
4645		 * hardware at the new frequency, and then re-enable
4646		 * the relevant bits of the h/w.
4647		 */
4648		ath_hal_intrset(ah, 0);		/* disable interrupts */
4649		ath_draintxq(sc);		/* clear pending tx frames */
4650		ath_stoprecv(sc);		/* turn off frame recv */
4651		if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
4652			if_printf(ifp, "%s: unable to reset "
4653			    "channel %u (%u MHz, flags 0x%x), hal status %u\n",
4654			    __func__, ieee80211_chan2ieee(ic, chan),
4655			    chan->ic_freq, chan->ic_flags, status);
4656			return EIO;
4657		}
4658		sc->sc_diversity = ath_hal_getdiversity(ah);
4659
4660		/*
4661		 * Re-enable rx framework.
4662		 */
4663		if (ath_startrecv(sc) != 0) {
4664			if_printf(ifp, "%s: unable to restart recv logic\n",
4665			    __func__);
4666			return EIO;
4667		}
4668
4669		/*
4670		 * Change channels and update the h/w rate map
4671		 * if we're switching; e.g. 11a to 11b/g.
4672		 */
4673		ath_chan_change(sc, chan);
4674
4675		/*
4676		 * Re-enable interrupts.
4677		 */
4678		ath_hal_intrset(ah, sc->sc_imask);
4679	}
4680	return 0;
4681}
4682
4683/*
4684 * Periodically recalibrate the PHY to account
4685 * for temperature/environment changes.
4686 */
4687static void
4688ath_calibrate(void *arg)
4689{
4690	struct ath_softc *sc = arg;
4691	struct ath_hal *ah = sc->sc_ah;
4692	struct ifnet *ifp = sc->sc_ifp;
4693	struct ieee80211com *ic = ifp->if_l2com;
4694	HAL_BOOL longCal, isCalDone;
4695	HAL_BOOL aniCal, shortCal = AH_FALSE;
4696	int nextcal;
4697
4698	if (ic->ic_flags & IEEE80211_F_SCAN)	/* defer, off channel */
4699		goto restart;
4700	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
4701	aniCal = (ticks - sc->sc_lastani >= ath_anicalinterval*hz/1000);
4702	if (sc->sc_doresetcal)
4703		shortCal = (ticks - sc->sc_lastshortcal >= ath_shortcalinterval*hz/1000);
4704
4705	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: shortCal=%d; longCal=%d; aniCal=%d\n", __func__, shortCal, longCal, aniCal);
4706	if (aniCal) {
4707		sc->sc_stats.ast_ani_cal++;
4708		sc->sc_lastani = ticks;
4709		ath_hal_ani_poll(ah, sc->sc_curchan);
4710	}
4711
4712	if (longCal) {
4713		sc->sc_stats.ast_per_cal++;
4714		sc->sc_lastlongcal = ticks;
4715		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
4716			/*
4717			 * Rfgain is out of bounds, reset the chip
4718			 * to load new gain values.
4719			 */
4720			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4721				"%s: rfgain change\n", __func__);
4722			sc->sc_stats.ast_per_rfgain++;
4723			ath_reset(ifp);
4724		}
4725		/*
4726		 * If this long cal is after an idle period, then
4727		 * reset the data collection state so we start fresh.
4728		 */
4729		if (sc->sc_resetcal) {
4730			(void) ath_hal_calreset(ah, sc->sc_curchan);
4731			sc->sc_lastcalreset = ticks;
4732			sc->sc_lastshortcal = ticks;
4733			sc->sc_resetcal = 0;
4734			sc->sc_doresetcal = AH_TRUE;
4735		}
4736	}
4737
4738	/* Only call if we're doing a short/long cal, not for ANI calibration */
4739	if (shortCal || longCal) {
4740		if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
4741			if (longCal) {
4742				/*
4743				 * Calibrate noise floor data again in case of change.
4744				 */
4745				ath_hal_process_noisefloor(ah);
4746			}
4747		} else {
4748			DPRINTF(sc, ATH_DEBUG_ANY,
4749				"%s: calibration of channel %u failed\n",
4750				__func__, sc->sc_curchan->ic_freq);
4751			sc->sc_stats.ast_per_calfail++;
4752		}
4753		if (shortCal)
4754			sc->sc_lastshortcal = ticks;
4755	}
4756	if (!isCalDone) {
4757restart:
4758		/*
4759		 * Use a shorter interval to potentially collect multiple
4760		 * data samples required to complete calibration.  Once
4761		 * we're told the work is done we drop back to a longer
4762		 * interval between requests.  We're more aggressive doing
4763		 * work when operating as an AP to improve operation right
4764		 * after startup.
4765		 */
4766		sc->sc_lastshortcal = ticks;
4767		nextcal = ath_shortcalinterval*hz/1000;
4768		if (sc->sc_opmode != HAL_M_HOSTAP)
4769			nextcal *= 10;
4770		sc->sc_doresetcal = AH_TRUE;
4771	} else {
4772		/* nextcal should be the shortest time for next event */
4773		nextcal = ath_longcalinterval*hz;
4774		if (sc->sc_lastcalreset == 0)
4775			sc->sc_lastcalreset = sc->sc_lastlongcal;
4776		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
4777			sc->sc_resetcal = 1;	/* setup reset next trip */
4778		sc->sc_doresetcal = AH_FALSE;
4779	}
4780	/* ANI calibration may occur more often than short/long/resetcal */
4781	if (ath_anicalinterval > 0)
4782		nextcal = MIN(nextcal, ath_anicalinterval*hz/1000);
4783
4784	if (nextcal != 0) {
4785		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
4786		    __func__, nextcal, isCalDone ? "" : "!");
4787		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
4788	} else {
4789		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
4790		    __func__);
4791		/* NB: don't rearm timer */
4792	}
4793}
4794
4795static void
4796ath_scan_start(struct ieee80211com *ic)
4797{
4798	struct ifnet *ifp = ic->ic_ifp;
4799	struct ath_softc *sc = ifp->if_softc;
4800	struct ath_hal *ah = sc->sc_ah;
4801	u_int32_t rfilt;
4802
4803	/* XXX calibration timer? */
4804
4805	sc->sc_scanning = 1;
4806	sc->sc_syncbeacon = 0;
4807	rfilt = ath_calcrxfilter(sc);
4808	ath_hal_setrxfilter(ah, rfilt);
4809	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
4810
4811	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
4812		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
4813}
4814
4815static void
4816ath_scan_end(struct ieee80211com *ic)
4817{
4818	struct ifnet *ifp = ic->ic_ifp;
4819	struct ath_softc *sc = ifp->if_softc;
4820	struct ath_hal *ah = sc->sc_ah;
4821	u_int32_t rfilt;
4822
4823	sc->sc_scanning = 0;
4824	rfilt = ath_calcrxfilter(sc);
4825	ath_hal_setrxfilter(ah, rfilt);
4826	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
4827
4828	ath_hal_process_noisefloor(ah);
4829
4830	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
4831		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
4832		 sc->sc_curaid);
4833}
4834
4835static void
4836ath_set_channel(struct ieee80211com *ic)
4837{
4838	struct ifnet *ifp = ic->ic_ifp;
4839	struct ath_softc *sc = ifp->if_softc;
4840
4841	(void) ath_chan_set(sc, ic->ic_curchan);
4842	/*
4843	 * If we are returning to our bss channel then mark state
4844	 * so the next recv'd beacon's tsf will be used to sync the
4845	 * beacon timers.  Note that since we only hear beacons in
4846	 * sta/ibss mode this has no effect in other operating modes.
4847	 */
4848	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
4849		sc->sc_syncbeacon = 1;
4850}
4851
4852/*
4853 * Walk the vap list and check if there any vap's in RUN state.
4854 */
4855static int
4856ath_isanyrunningvaps(struct ieee80211vap *this)
4857{
4858	struct ieee80211com *ic = this->iv_ic;
4859	struct ieee80211vap *vap;
4860
4861	IEEE80211_LOCK_ASSERT(ic);
4862
4863	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
4864		if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
4865			return 1;
4866	}
4867	return 0;
4868}
4869
4870static int
4871ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
4872{
4873	struct ieee80211com *ic = vap->iv_ic;
4874	struct ath_softc *sc = ic->ic_ifp->if_softc;
4875	struct ath_vap *avp = ATH_VAP(vap);
4876	struct ath_hal *ah = sc->sc_ah;
4877	struct ieee80211_node *ni = NULL;
4878	int i, error, stamode;
4879	u_int32_t rfilt;
4880	static const HAL_LED_STATE leds[] = {
4881	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
4882	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
4883	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
4884	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
4885	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
4886	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
4887	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
4888	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
4889	};
4890
4891	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
4892		ieee80211_state_name[vap->iv_state],
4893		ieee80211_state_name[nstate]);
4894
4895	callout_drain(&sc->sc_cal_ch);
4896	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
4897
4898	if (nstate == IEEE80211_S_SCAN) {
4899		/*
4900		 * Scanning: turn off beacon miss and don't beacon.
4901		 * Mark beacon state so when we reach RUN state we'll
4902		 * [re]setup beacons.  Unblock the task q thread so
4903		 * deferred interrupt processing is done.
4904		 */
4905		ath_hal_intrset(ah,
4906		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
4907		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4908		sc->sc_beacons = 0;
4909		taskqueue_unblock(sc->sc_tq);
4910	}
4911
4912	ni = vap->iv_bss;
4913	rfilt = ath_calcrxfilter(sc);
4914	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
4915		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
4916		   vap->iv_opmode == IEEE80211_M_IBSS);
4917	if (stamode && nstate == IEEE80211_S_RUN) {
4918		sc->sc_curaid = ni->ni_associd;
4919		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
4920		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
4921	}
4922	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
4923	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
4924	ath_hal_setrxfilter(ah, rfilt);
4925
4926	/* XXX is this to restore keycache on resume? */
4927	if (vap->iv_opmode != IEEE80211_M_STA &&
4928	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
4929		for (i = 0; i < IEEE80211_WEP_NKID; i++)
4930			if (ath_hal_keyisvalid(ah, i))
4931				ath_hal_keysetmac(ah, i, ni->ni_bssid);
4932	}
4933
4934	/*
4935	 * Invoke the parent method to do net80211 work.
4936	 */
4937	error = avp->av_newstate(vap, nstate, arg);
4938	if (error != 0)
4939		goto bad;
4940
4941	if (nstate == IEEE80211_S_RUN) {
4942		/* NB: collect bss node again, it may have changed */
4943		ni = vap->iv_bss;
4944
4945		DPRINTF(sc, ATH_DEBUG_STATE,
4946		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
4947		    "capinfo 0x%04x chan %d\n", __func__,
4948		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
4949		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
4950
4951		switch (vap->iv_opmode) {
4952#ifdef IEEE80211_SUPPORT_TDMA
4953		case IEEE80211_M_AHDEMO:
4954			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
4955				break;
4956			/* fall thru... */
4957#endif
4958		case IEEE80211_M_HOSTAP:
4959		case IEEE80211_M_IBSS:
4960		case IEEE80211_M_MBSS:
4961			/*
4962			 * Allocate and setup the beacon frame.
4963			 *
4964			 * Stop any previous beacon DMA.  This may be
4965			 * necessary, for example, when an ibss merge
4966			 * causes reconfiguration; there will be a state
4967			 * transition from RUN->RUN that means we may
4968			 * be called with beacon transmission active.
4969			 */
4970			ath_hal_stoptxdma(ah, sc->sc_bhalq);
4971
4972			error = ath_beacon_alloc(sc, ni);
4973			if (error != 0)
4974				goto bad;
4975			/*
4976			 * If joining an adhoc network defer beacon timer
4977			 * configuration to the next beacon frame so we
4978			 * have a current TSF to use.  Otherwise we're
4979			 * starting an ibss/bss so there's no need to delay;
4980			 * if this is the first vap moving to RUN state, then
4981			 * beacon state needs to be [re]configured.
4982			 */
4983			if (vap->iv_opmode == IEEE80211_M_IBSS &&
4984			    ni->ni_tstamp.tsf != 0) {
4985				sc->sc_syncbeacon = 1;
4986			} else if (!sc->sc_beacons) {
4987#ifdef IEEE80211_SUPPORT_TDMA
4988				if (vap->iv_caps & IEEE80211_C_TDMA)
4989					ath_tdma_config(sc, vap);
4990				else
4991#endif
4992					ath_beacon_config(sc, vap);
4993				sc->sc_beacons = 1;
4994			}
4995			break;
4996		case IEEE80211_M_STA:
4997			/*
4998			 * Defer beacon timer configuration to the next
4999			 * beacon frame so we have a current TSF to use
5000			 * (any TSF collected when scanning is likely old).
5001			 */
5002			sc->sc_syncbeacon = 1;
5003			break;
5004		case IEEE80211_M_MONITOR:
5005			/*
5006			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
5007			 * transitions so we must re-enable interrupts here to
5008			 * handle the case of a single monitor mode vap.
5009			 */
5010			ath_hal_intrset(ah, sc->sc_imask);
5011			break;
5012		case IEEE80211_M_WDS:
5013			break;
5014		default:
5015			break;
5016		}
5017		/*
5018		 * Let the hal process statistics collected during a
5019		 * scan so it can provide calibrated noise floor data.
5020		 */
5021		ath_hal_process_noisefloor(ah);
5022		/*
5023		 * Reset rssi stats; maybe not the best place...
5024		 */
5025		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
5026		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
5027		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
5028		/*
5029		 * Finally, start any timers and the task q thread
5030		 * (in case we didn't go through SCAN state).
5031		 */
5032		if (ath_longcalinterval != 0) {
5033			/* start periodic recalibration timer */
5034			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
5035		} else {
5036			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5037			    "%s: calibration disabled\n", __func__);
5038		}
5039		taskqueue_unblock(sc->sc_tq);
5040	} else if (nstate == IEEE80211_S_INIT) {
5041		/*
5042		 * If there are no vaps left in RUN state then
5043		 * shutdown host/driver operation:
5044		 * o disable interrupts
5045		 * o disable the task queue thread
5046		 * o mark beacon processing as stopped
5047		 */
5048		if (!ath_isanyrunningvaps(vap)) {
5049			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5050			/* disable interrupts  */
5051			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
5052			taskqueue_block(sc->sc_tq);
5053			sc->sc_beacons = 0;
5054		}
5055#ifdef IEEE80211_SUPPORT_TDMA
5056		ath_hal_setcca(ah, AH_TRUE);
5057#endif
5058	}
5059bad:
5060	return error;
5061}
5062
5063/*
5064 * Allocate a key cache slot to the station so we can
5065 * setup a mapping from key index to node. The key cache
5066 * slot is needed for managing antenna state and for
5067 * compression when stations do not use crypto.  We do
5068 * it uniliaterally here; if crypto is employed this slot
5069 * will be reassigned.
5070 */
5071static void
5072ath_setup_stationkey(struct ieee80211_node *ni)
5073{
5074	struct ieee80211vap *vap = ni->ni_vap;
5075	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
5076	ieee80211_keyix keyix, rxkeyix;
5077
5078	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
5079		/*
5080		 * Key cache is full; we'll fall back to doing
5081		 * the more expensive lookup in software.  Note
5082		 * this also means no h/w compression.
5083		 */
5084		/* XXX msg+statistic */
5085	} else {
5086		/* XXX locking? */
5087		ni->ni_ucastkey.wk_keyix = keyix;
5088		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
5089		/* NB: must mark device key to get called back on delete */
5090		ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
5091		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
5092		/* NB: this will create a pass-thru key entry */
5093		ath_keyset(sc, &ni->ni_ucastkey, vap->iv_bss);
5094	}
5095}
5096
5097/*
5098 * Setup driver-specific state for a newly associated node.
5099 * Note that we're called also on a re-associate, the isnew
5100 * param tells us if this is the first time or not.
5101 */
5102static void
5103ath_newassoc(struct ieee80211_node *ni, int isnew)
5104{
5105	struct ath_node *an = ATH_NODE(ni);
5106	struct ieee80211vap *vap = ni->ni_vap;
5107	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
5108	const struct ieee80211_txparam *tp = ni->ni_txparms;
5109
5110	an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
5111	an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
5112
5113	ath_rate_newassoc(sc, an, isnew);
5114	if (isnew &&
5115	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
5116	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
5117		ath_setup_stationkey(ni);
5118}
5119
5120static int
5121ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
5122	int nchans, struct ieee80211_channel chans[])
5123{
5124	struct ath_softc *sc = ic->ic_ifp->if_softc;
5125	struct ath_hal *ah = sc->sc_ah;
5126	HAL_STATUS status;
5127
5128	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
5129	    "%s: rd %u cc %u location %c%s\n",
5130	    __func__, reg->regdomain, reg->country, reg->location,
5131	    reg->ecm ? " ecm" : "");
5132
5133	status = ath_hal_set_channels(ah, chans, nchans,
5134	    reg->country, reg->regdomain);
5135	if (status != HAL_OK) {
5136		DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
5137		    __func__, status);
5138		return EINVAL;		/* XXX */
5139	}
5140	return 0;
5141}
5142
5143static void
5144ath_getradiocaps(struct ieee80211com *ic,
5145	int maxchans, int *nchans, struct ieee80211_channel chans[])
5146{
5147	struct ath_softc *sc = ic->ic_ifp->if_softc;
5148	struct ath_hal *ah = sc->sc_ah;
5149
5150	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
5151	    __func__, SKU_DEBUG, CTRY_DEFAULT);
5152
5153	/* XXX check return */
5154	(void) ath_hal_getchannels(ah, chans, maxchans, nchans,
5155	    HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
5156
5157}
5158
5159static int
5160ath_getchannels(struct ath_softc *sc)
5161{
5162	struct ifnet *ifp = sc->sc_ifp;
5163	struct ieee80211com *ic = ifp->if_l2com;
5164	struct ath_hal *ah = sc->sc_ah;
5165	HAL_STATUS status;
5166
5167	/*
5168	 * Collect channel set based on EEPROM contents.
5169	 */
5170	status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
5171	    &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
5172	if (status != HAL_OK) {
5173		if_printf(ifp, "%s: unable to collect channel list from hal, "
5174		    "status %d\n", __func__, status);
5175		return EINVAL;
5176	}
5177	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
5178	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
5179	/* XXX map Atheros sku's to net80211 SKU's */
5180	/* XXX net80211 types too small */
5181	ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
5182	ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
5183	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
5184	ic->ic_regdomain.isocc[1] = ' ';
5185
5186	ic->ic_regdomain.ecm = 1;
5187	ic->ic_regdomain.location = 'I';
5188
5189	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
5190	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
5191	    __func__, sc->sc_eerd, sc->sc_eecc,
5192	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
5193	    ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
5194	return 0;
5195}
5196
5197static void
5198ath_led_done(void *arg)
5199{
5200	struct ath_softc *sc = arg;
5201
5202	sc->sc_blinking = 0;
5203}
5204
5205/*
5206 * Turn the LED off: flip the pin and then set a timer so no
5207 * update will happen for the specified duration.
5208 */
5209static void
5210ath_led_off(void *arg)
5211{
5212	struct ath_softc *sc = arg;
5213
5214	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
5215	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
5216}
5217
5218/*
5219 * Blink the LED according to the specified on/off times.
5220 */
5221static void
5222ath_led_blink(struct ath_softc *sc, int on, int off)
5223{
5224	DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
5225	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
5226	sc->sc_blinking = 1;
5227	sc->sc_ledoff = off;
5228	callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
5229}
5230
5231static void
5232ath_led_event(struct ath_softc *sc, int rix)
5233{
5234	sc->sc_ledevent = ticks;	/* time of last event */
5235	if (sc->sc_blinking)		/* don't interrupt active blink */
5236		return;
5237	ath_led_blink(sc, sc->sc_hwmap[rix].ledon, sc->sc_hwmap[rix].ledoff);
5238}
5239
5240static int
5241ath_rate_setup(struct ath_softc *sc, u_int mode)
5242{
5243	struct ath_hal *ah = sc->sc_ah;
5244	const HAL_RATE_TABLE *rt;
5245
5246	switch (mode) {
5247	case IEEE80211_MODE_11A:
5248		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
5249		break;
5250	case IEEE80211_MODE_HALF:
5251		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
5252		break;
5253	case IEEE80211_MODE_QUARTER:
5254		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
5255		break;
5256	case IEEE80211_MODE_11B:
5257		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
5258		break;
5259	case IEEE80211_MODE_11G:
5260		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
5261		break;
5262	case IEEE80211_MODE_TURBO_A:
5263		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
5264		break;
5265	case IEEE80211_MODE_TURBO_G:
5266		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
5267		break;
5268	case IEEE80211_MODE_STURBO_A:
5269		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
5270		break;
5271	case IEEE80211_MODE_11NA:
5272		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
5273		break;
5274	case IEEE80211_MODE_11NG:
5275		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
5276		break;
5277	default:
5278		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
5279			__func__, mode);
5280		return 0;
5281	}
5282	sc->sc_rates[mode] = rt;
5283	return (rt != NULL);
5284}
5285
5286static void
5287ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
5288{
5289#define	N(a)	(sizeof(a)/sizeof(a[0]))
5290	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
5291	static const struct {
5292		u_int		rate;		/* tx/rx 802.11 rate */
5293		u_int16_t	timeOn;		/* LED on time (ms) */
5294		u_int16_t	timeOff;	/* LED off time (ms) */
5295	} blinkrates[] = {
5296		{ 108,  40,  10 },
5297		{  96,  44,  11 },
5298		{  72,  50,  13 },
5299		{  48,  57,  14 },
5300		{  36,  67,  16 },
5301		{  24,  80,  20 },
5302		{  22, 100,  25 },
5303		{  18, 133,  34 },
5304		{  12, 160,  40 },
5305		{  10, 200,  50 },
5306		{   6, 240,  58 },
5307		{   4, 267,  66 },
5308		{   2, 400, 100 },
5309		{   0, 500, 130 },
5310		/* XXX half/quarter rates */
5311	};
5312	const HAL_RATE_TABLE *rt;
5313	int i, j;
5314
5315	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
5316	rt = sc->sc_rates[mode];
5317	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
5318	for (i = 0; i < rt->rateCount; i++) {
5319		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
5320		if (rt->info[i].phy != IEEE80211_T_HT)
5321			sc->sc_rixmap[ieeerate] = i;
5322		else
5323			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
5324	}
5325	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
5326	for (i = 0; i < N(sc->sc_hwmap); i++) {
5327		if (i >= rt->rateCount) {
5328			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
5329			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
5330			continue;
5331		}
5332		sc->sc_hwmap[i].ieeerate =
5333			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
5334		if (rt->info[i].phy == IEEE80211_T_HT)
5335			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
5336		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
5337		if (rt->info[i].shortPreamble ||
5338		    rt->info[i].phy == IEEE80211_T_OFDM)
5339			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
5340		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
5341		for (j = 0; j < N(blinkrates)-1; j++)
5342			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
5343				break;
5344		/* NB: this uses the last entry if the rate isn't found */
5345		/* XXX beware of overlow */
5346		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
5347		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
5348	}
5349	sc->sc_currates = rt;
5350	sc->sc_curmode = mode;
5351	/*
5352	 * All protection frames are transmited at 2Mb/s for
5353	 * 11g, otherwise at 1Mb/s.
5354	 */
5355	if (mode == IEEE80211_MODE_11G)
5356		sc->sc_protrix = ath_tx_findrix(sc, 2*2);
5357	else
5358		sc->sc_protrix = ath_tx_findrix(sc, 2*1);
5359	/* NB: caller is responsible for resetting rate control state */
5360#undef N
5361}
5362
5363static void
5364ath_watchdog(void *arg)
5365{
5366	struct ath_softc *sc = arg;
5367
5368	if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
5369		struct ifnet *ifp = sc->sc_ifp;
5370		uint32_t hangs;
5371
5372		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
5373		    hangs != 0) {
5374			if_printf(ifp, "%s hang detected (0x%x)\n",
5375			    hangs & 0xff ? "bb" : "mac", hangs);
5376		} else
5377			if_printf(ifp, "device timeout\n");
5378		ath_reset(ifp);
5379		ifp->if_oerrors++;
5380		sc->sc_stats.ast_watchdog++;
5381	}
5382	callout_schedule(&sc->sc_wd_ch, hz);
5383}
5384
5385#ifdef ATH_DIAGAPI
5386/*
5387 * Diagnostic interface to the HAL.  This is used by various
5388 * tools to do things like retrieve register contents for
5389 * debugging.  The mechanism is intentionally opaque so that
5390 * it can change frequently w/o concern for compatiblity.
5391 */
5392static int
5393ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
5394{
5395	struct ath_hal *ah = sc->sc_ah;
5396	u_int id = ad->ad_id & ATH_DIAG_ID;
5397	void *indata = NULL;
5398	void *outdata = NULL;
5399	u_int32_t insize = ad->ad_in_size;
5400	u_int32_t outsize = ad->ad_out_size;
5401	int error = 0;
5402
5403	if (ad->ad_id & ATH_DIAG_IN) {
5404		/*
5405		 * Copy in data.
5406		 */
5407		indata = malloc(insize, M_TEMP, M_NOWAIT);
5408		if (indata == NULL) {
5409			error = ENOMEM;
5410			goto bad;
5411		}
5412		error = copyin(ad->ad_in_data, indata, insize);
5413		if (error)
5414			goto bad;
5415	}
5416	if (ad->ad_id & ATH_DIAG_DYN) {
5417		/*
5418		 * Allocate a buffer for the results (otherwise the HAL
5419		 * returns a pointer to a buffer where we can read the
5420		 * results).  Note that we depend on the HAL leaving this
5421		 * pointer for us to use below in reclaiming the buffer;
5422		 * may want to be more defensive.
5423		 */
5424		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
5425		if (outdata == NULL) {
5426			error = ENOMEM;
5427			goto bad;
5428		}
5429	}
5430	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
5431		if (outsize < ad->ad_out_size)
5432			ad->ad_out_size = outsize;
5433		if (outdata != NULL)
5434			error = copyout(outdata, ad->ad_out_data,
5435					ad->ad_out_size);
5436	} else {
5437		error = EINVAL;
5438	}
5439bad:
5440	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
5441		free(indata, M_TEMP);
5442	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
5443		free(outdata, M_TEMP);
5444	return error;
5445}
5446#endif /* ATH_DIAGAPI */
5447
5448static int
5449ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
5450{
5451#define	IS_RUNNING(ifp) \
5452	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
5453	struct ath_softc *sc = ifp->if_softc;
5454	struct ieee80211com *ic = ifp->if_l2com;
5455	struct ifreq *ifr = (struct ifreq *)data;
5456	const HAL_RATE_TABLE *rt;
5457	int error = 0;
5458
5459	switch (cmd) {
5460	case SIOCSIFFLAGS:
5461		ATH_LOCK(sc);
5462		if (IS_RUNNING(ifp)) {
5463			/*
5464			 * To avoid rescanning another access point,
5465			 * do not call ath_init() here.  Instead,
5466			 * only reflect promisc mode settings.
5467			 */
5468			ath_mode_init(sc);
5469		} else if (ifp->if_flags & IFF_UP) {
5470			/*
5471			 * Beware of being called during attach/detach
5472			 * to reset promiscuous mode.  In that case we
5473			 * will still be marked UP but not RUNNING.
5474			 * However trying to re-init the interface
5475			 * is the wrong thing to do as we've already
5476			 * torn down much of our state.  There's
5477			 * probably a better way to deal with this.
5478			 */
5479			if (!sc->sc_invalid)
5480				ath_init(sc);	/* XXX lose error */
5481		} else {
5482			ath_stop_locked(ifp);
5483#ifdef notyet
5484			/* XXX must wakeup in places like ath_vap_delete */
5485			if (!sc->sc_invalid)
5486				ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
5487#endif
5488		}
5489		ATH_UNLOCK(sc);
5490		break;
5491	case SIOCGIFMEDIA:
5492	case SIOCSIFMEDIA:
5493		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
5494		break;
5495	case SIOCGATHSTATS:
5496		/* NB: embed these numbers to get a consistent view */
5497		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
5498		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
5499		sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
5500		sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
5501#ifdef IEEE80211_SUPPORT_TDMA
5502		sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
5503		sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
5504#endif
5505		rt = sc->sc_currates;
5506		/* XXX HT rates */
5507		sc->sc_stats.ast_tx_rate =
5508		    rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
5509		return copyout(&sc->sc_stats,
5510		    ifr->ifr_data, sizeof (sc->sc_stats));
5511	case SIOCZATHSTATS:
5512		error = priv_check(curthread, PRIV_DRIVER);
5513		if (error == 0)
5514			memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
5515		break;
5516#ifdef ATH_DIAGAPI
5517	case SIOCGATHDIAG:
5518		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
5519		break;
5520#endif
5521	case SIOCGIFADDR:
5522		error = ether_ioctl(ifp, cmd, data);
5523		break;
5524	default:
5525		error = EINVAL;
5526		break;
5527	}
5528	return error;
5529#undef IS_RUNNING
5530}
5531
5532static int
5533ath_sysctl_slottime(SYSCTL_HANDLER_ARGS)
5534{
5535	struct ath_softc *sc = arg1;
5536	u_int slottime = ath_hal_getslottime(sc->sc_ah);
5537	int error;
5538
5539	error = sysctl_handle_int(oidp, &slottime, 0, req);
5540	if (error || !req->newptr)
5541		return error;
5542	return !ath_hal_setslottime(sc->sc_ah, slottime) ? EINVAL : 0;
5543}
5544
5545static int
5546ath_sysctl_acktimeout(SYSCTL_HANDLER_ARGS)
5547{
5548	struct ath_softc *sc = arg1;
5549	u_int acktimeout = ath_hal_getacktimeout(sc->sc_ah);
5550	int error;
5551
5552	error = sysctl_handle_int(oidp, &acktimeout, 0, req);
5553	if (error || !req->newptr)
5554		return error;
5555	return !ath_hal_setacktimeout(sc->sc_ah, acktimeout) ? EINVAL : 0;
5556}
5557
5558static int
5559ath_sysctl_ctstimeout(SYSCTL_HANDLER_ARGS)
5560{
5561	struct ath_softc *sc = arg1;
5562	u_int ctstimeout = ath_hal_getctstimeout(sc->sc_ah);
5563	int error;
5564
5565	error = sysctl_handle_int(oidp, &ctstimeout, 0, req);
5566	if (error || !req->newptr)
5567		return error;
5568	return !ath_hal_setctstimeout(sc->sc_ah, ctstimeout) ? EINVAL : 0;
5569}
5570
5571static int
5572ath_sysctl_softled(SYSCTL_HANDLER_ARGS)
5573{
5574	struct ath_softc *sc = arg1;
5575	int softled = sc->sc_softled;
5576	int error;
5577
5578	error = sysctl_handle_int(oidp, &softled, 0, req);
5579	if (error || !req->newptr)
5580		return error;
5581	softled = (softled != 0);
5582	if (softled != sc->sc_softled) {
5583		if (softled) {
5584			/* NB: handle any sc_ledpin change */
5585			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin,
5586			    HAL_GPIO_MUX_MAC_NETWORK_LED);
5587			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
5588				!sc->sc_ledon);
5589		}
5590		sc->sc_softled = softled;
5591	}
5592	return 0;
5593}
5594
5595static int
5596ath_sysctl_ledpin(SYSCTL_HANDLER_ARGS)
5597{
5598	struct ath_softc *sc = arg1;
5599	int ledpin = sc->sc_ledpin;
5600	int error;
5601
5602	error = sysctl_handle_int(oidp, &ledpin, 0, req);
5603	if (error || !req->newptr)
5604		return error;
5605	if (ledpin != sc->sc_ledpin) {
5606		sc->sc_ledpin = ledpin;
5607		if (sc->sc_softled) {
5608			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin,
5609			    HAL_GPIO_MUX_MAC_NETWORK_LED);
5610			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
5611				!sc->sc_ledon);
5612		}
5613	}
5614	return 0;
5615}
5616
5617static int
5618ath_sysctl_txantenna(SYSCTL_HANDLER_ARGS)
5619{
5620	struct ath_softc *sc = arg1;
5621	u_int txantenna = ath_hal_getantennaswitch(sc->sc_ah);
5622	int error;
5623
5624	error = sysctl_handle_int(oidp, &txantenna, 0, req);
5625	if (!error && req->newptr) {
5626		/* XXX assumes 2 antenna ports */
5627		if (txantenna < HAL_ANT_VARIABLE || txantenna > HAL_ANT_FIXED_B)
5628			return EINVAL;
5629		ath_hal_setantennaswitch(sc->sc_ah, txantenna);
5630		/*
5631		 * NB: with the switch locked this isn't meaningful,
5632		 *     but set it anyway so things like radiotap get
5633		 *     consistent info in their data.
5634		 */
5635		sc->sc_txantenna = txantenna;
5636	}
5637	return error;
5638}
5639
5640static int
5641ath_sysctl_rxantenna(SYSCTL_HANDLER_ARGS)
5642{
5643	struct ath_softc *sc = arg1;
5644	u_int defantenna = ath_hal_getdefantenna(sc->sc_ah);
5645	int error;
5646
5647	error = sysctl_handle_int(oidp, &defantenna, 0, req);
5648	if (!error && req->newptr)
5649		ath_hal_setdefantenna(sc->sc_ah, defantenna);
5650	return error;
5651}
5652
5653static int
5654ath_sysctl_diversity(SYSCTL_HANDLER_ARGS)
5655{
5656	struct ath_softc *sc = arg1;
5657	u_int diversity = ath_hal_getdiversity(sc->sc_ah);
5658	int error;
5659
5660	error = sysctl_handle_int(oidp, &diversity, 0, req);
5661	if (error || !req->newptr)
5662		return error;
5663	if (!ath_hal_setdiversity(sc->sc_ah, diversity))
5664		return EINVAL;
5665	sc->sc_diversity = diversity;
5666	return 0;
5667}
5668
5669static int
5670ath_sysctl_diag(SYSCTL_HANDLER_ARGS)
5671{
5672	struct ath_softc *sc = arg1;
5673	u_int32_t diag;
5674	int error;
5675
5676	if (!ath_hal_getdiag(sc->sc_ah, &diag))
5677		return EINVAL;
5678	error = sysctl_handle_int(oidp, &diag, 0, req);
5679	if (error || !req->newptr)
5680		return error;
5681	return !ath_hal_setdiag(sc->sc_ah, diag) ? EINVAL : 0;
5682}
5683
5684static int
5685ath_sysctl_tpscale(SYSCTL_HANDLER_ARGS)
5686{
5687	struct ath_softc *sc = arg1;
5688	struct ifnet *ifp = sc->sc_ifp;
5689	u_int32_t scale;
5690	int error;
5691
5692	(void) ath_hal_gettpscale(sc->sc_ah, &scale);
5693	error = sysctl_handle_int(oidp, &scale, 0, req);
5694	if (error || !req->newptr)
5695		return error;
5696	return !ath_hal_settpscale(sc->sc_ah, scale) ? EINVAL :
5697	    (ifp->if_drv_flags & IFF_DRV_RUNNING) ? ath_reset(ifp) : 0;
5698}
5699
5700static int
5701ath_sysctl_tpc(SYSCTL_HANDLER_ARGS)
5702{
5703	struct ath_softc *sc = arg1;
5704	u_int tpc = ath_hal_gettpc(sc->sc_ah);
5705	int error;
5706
5707	error = sysctl_handle_int(oidp, &tpc, 0, req);
5708	if (error || !req->newptr)
5709		return error;
5710	return !ath_hal_settpc(sc->sc_ah, tpc) ? EINVAL : 0;
5711}
5712
5713static int
5714ath_sysctl_rfkill(SYSCTL_HANDLER_ARGS)
5715{
5716	struct ath_softc *sc = arg1;
5717	struct ifnet *ifp = sc->sc_ifp;
5718	struct ath_hal *ah = sc->sc_ah;
5719	u_int rfkill = ath_hal_getrfkill(ah);
5720	int error;
5721
5722	error = sysctl_handle_int(oidp, &rfkill, 0, req);
5723	if (error || !req->newptr)
5724		return error;
5725	if (rfkill == ath_hal_getrfkill(ah))	/* unchanged */
5726		return 0;
5727	if (!ath_hal_setrfkill(ah, rfkill))
5728		return EINVAL;
5729	return (ifp->if_drv_flags & IFF_DRV_RUNNING) ? ath_reset(ifp) : 0;
5730}
5731
5732static int
5733ath_sysctl_rfsilent(SYSCTL_HANDLER_ARGS)
5734{
5735	struct ath_softc *sc = arg1;
5736	u_int rfsilent;
5737	int error;
5738
5739	(void) ath_hal_getrfsilent(sc->sc_ah, &rfsilent);
5740	error = sysctl_handle_int(oidp, &rfsilent, 0, req);
5741	if (error || !req->newptr)
5742		return error;
5743	if (!ath_hal_setrfsilent(sc->sc_ah, rfsilent))
5744		return EINVAL;
5745	sc->sc_rfsilentpin = rfsilent & 0x1c;
5746	sc->sc_rfsilentpol = (rfsilent & 0x2) != 0;
5747	return 0;
5748}
5749
5750static int
5751ath_sysctl_tpack(SYSCTL_HANDLER_ARGS)
5752{
5753	struct ath_softc *sc = arg1;
5754	u_int32_t tpack;
5755	int error;
5756
5757	(void) ath_hal_gettpack(sc->sc_ah, &tpack);
5758	error = sysctl_handle_int(oidp, &tpack, 0, req);
5759	if (error || !req->newptr)
5760		return error;
5761	return !ath_hal_settpack(sc->sc_ah, tpack) ? EINVAL : 0;
5762}
5763
5764static int
5765ath_sysctl_tpcts(SYSCTL_HANDLER_ARGS)
5766{
5767	struct ath_softc *sc = arg1;
5768	u_int32_t tpcts;
5769	int error;
5770
5771	(void) ath_hal_gettpcts(sc->sc_ah, &tpcts);
5772	error = sysctl_handle_int(oidp, &tpcts, 0, req);
5773	if (error || !req->newptr)
5774		return error;
5775	return !ath_hal_settpcts(sc->sc_ah, tpcts) ? EINVAL : 0;
5776}
5777
5778static int
5779ath_sysctl_intmit(SYSCTL_HANDLER_ARGS)
5780{
5781	struct ath_softc *sc = arg1;
5782	int intmit, error;
5783
5784	intmit = ath_hal_getintmit(sc->sc_ah);
5785	error = sysctl_handle_int(oidp, &intmit, 0, req);
5786	if (error || !req->newptr)
5787		return error;
5788	return !ath_hal_setintmit(sc->sc_ah, intmit) ? EINVAL : 0;
5789}
5790
5791#ifdef IEEE80211_SUPPORT_TDMA
5792static int
5793ath_sysctl_setcca(SYSCTL_HANDLER_ARGS)
5794{
5795	struct ath_softc *sc = arg1;
5796	int setcca, error;
5797
5798	setcca = sc->sc_setcca;
5799	error = sysctl_handle_int(oidp, &setcca, 0, req);
5800	if (error || !req->newptr)
5801		return error;
5802	sc->sc_setcca = (setcca != 0);
5803	return 0;
5804}
5805#endif /* IEEE80211_SUPPORT_TDMA */
5806
5807static void
5808ath_sysctlattach(struct ath_softc *sc)
5809{
5810	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
5811	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
5812	struct ath_hal *ah = sc->sc_ah;
5813
5814	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5815		"countrycode", CTLFLAG_RD, &sc->sc_eecc, 0,
5816		"EEPROM country code");
5817	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5818		"regdomain", CTLFLAG_RD, &sc->sc_eerd, 0,
5819		"EEPROM regdomain code");
5820#ifdef	ATH_DEBUG
5821	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5822		"debug", CTLFLAG_RW, &sc->sc_debug, 0,
5823		"control debugging printfs");
5824#endif
5825	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5826		"slottime", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5827		ath_sysctl_slottime, "I", "802.11 slot time (us)");
5828	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5829		"acktimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5830		ath_sysctl_acktimeout, "I", "802.11 ACK timeout (us)");
5831	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5832		"ctstimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5833		ath_sysctl_ctstimeout, "I", "802.11 CTS timeout (us)");
5834	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5835		"softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5836		ath_sysctl_softled, "I", "enable/disable software LED support");
5837	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5838		"ledpin", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5839		ath_sysctl_ledpin, "I", "GPIO pin connected to LED");
5840	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5841		"ledon", CTLFLAG_RW, &sc->sc_ledon, 0,
5842		"setting to turn LED on");
5843	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5844		"ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
5845		"idle time for inactivity LED (ticks)");
5846	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5847		"txantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5848		ath_sysctl_txantenna, "I", "antenna switch");
5849	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5850		"rxantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5851		ath_sysctl_rxantenna, "I", "default/rx antenna");
5852	if (ath_hal_hasdiversity(ah))
5853		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5854			"diversity", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5855			ath_sysctl_diversity, "I", "antenna diversity");
5856	sc->sc_txintrperiod = ATH_TXINTR_PERIOD;
5857	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5858		"txintrperiod", CTLFLAG_RW, &sc->sc_txintrperiod, 0,
5859		"tx descriptor batching");
5860	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5861		"diag", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5862		ath_sysctl_diag, "I", "h/w diagnostic control");
5863	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5864		"tpscale", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5865		ath_sysctl_tpscale, "I", "tx power scaling");
5866	if (ath_hal_hastpc(ah)) {
5867		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5868			"tpc", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5869			ath_sysctl_tpc, "I", "enable/disable per-packet TPC");
5870		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5871			"tpack", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5872			ath_sysctl_tpack, "I", "tx power for ack frames");
5873		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5874			"tpcts", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5875			ath_sysctl_tpcts, "I", "tx power for cts frames");
5876	}
5877	if (ath_hal_hasrfsilent(ah)) {
5878		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5879			"rfsilent", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5880			ath_sysctl_rfsilent, "I", "h/w RF silent config");
5881		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5882			"rfkill", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5883			ath_sysctl_rfkill, "I", "enable/disable RF kill switch");
5884	}
5885	if (ath_hal_hasintmit(ah)) {
5886		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5887			"intmit", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5888			ath_sysctl_intmit, "I", "interference mitigation");
5889	}
5890	sc->sc_monpass = HAL_RXERR_DECRYPT | HAL_RXERR_MIC;
5891	SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5892		"monpass", CTLFLAG_RW, &sc->sc_monpass, 0,
5893		"mask of error frames to pass when monitoring");
5894#ifdef IEEE80211_SUPPORT_TDMA
5895	if (ath_hal_macversion(ah) > 0x78) {
5896		sc->sc_tdmadbaprep = 2;
5897		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5898			"dbaprep", CTLFLAG_RW, &sc->sc_tdmadbaprep, 0,
5899			"TDMA DBA preparation time");
5900		sc->sc_tdmaswbaprep = 10;
5901		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5902			"swbaprep", CTLFLAG_RW, &sc->sc_tdmaswbaprep, 0,
5903			"TDMA SWBA preparation time");
5904		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5905			"guardtime", CTLFLAG_RW, &sc->sc_tdmaguard, 0,
5906			"TDMA slot guard time");
5907		SYSCTL_ADD_UINT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5908			"superframe", CTLFLAG_RD, &sc->sc_tdmabintval, 0,
5909			"TDMA calculated super frame");
5910		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5911			"setcca", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5912			ath_sysctl_setcca, "I", "enable CCA control");
5913	}
5914#endif
5915}
5916
5917/*
5918 * Announce various information on device/driver attach.
5919 */
5920static void
5921ath_announce(struct ath_softc *sc)
5922{
5923	struct ifnet *ifp = sc->sc_ifp;
5924	struct ath_hal *ah = sc->sc_ah;
5925
5926	if_printf(ifp, "AR%s mac %d.%d RF%s phy %d.%d\n",
5927		ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
5928		ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
5929	if (bootverbose) {
5930		int i;
5931		for (i = 0; i <= WME_AC_VO; i++) {
5932			struct ath_txq *txq = sc->sc_ac2q[i];
5933			if_printf(ifp, "Use hw queue %u for %s traffic\n",
5934				txq->axq_qnum, ieee80211_wme_acnames[i]);
5935		}
5936		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
5937			sc->sc_cabq->axq_qnum);
5938		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
5939	}
5940	if (ath_rxbuf != ATH_RXBUF)
5941		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
5942	if (ath_txbuf != ATH_TXBUF)
5943		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
5944	if (sc->sc_mcastkey && bootverbose)
5945		if_printf(ifp, "using multicast key search\n");
5946}
5947
5948#ifdef IEEE80211_SUPPORT_TDMA
5949static __inline uint32_t
5950ath_hal_getnexttbtt(struct ath_hal *ah)
5951{
5952#define	AR_TIMER0	0x8028
5953	return OS_REG_READ(ah, AR_TIMER0);
5954}
5955
5956static __inline void
5957ath_hal_adjusttsf(struct ath_hal *ah, int32_t tsfdelta)
5958{
5959	/* XXX handle wrap/overflow */
5960	OS_REG_WRITE(ah, AR_TSF_L32, OS_REG_READ(ah, AR_TSF_L32) + tsfdelta);
5961}
5962
5963static void
5964ath_tdma_settimers(struct ath_softc *sc, u_int32_t nexttbtt, u_int32_t bintval)
5965{
5966	struct ath_hal *ah = sc->sc_ah;
5967	HAL_BEACON_TIMERS bt;
5968
5969	bt.bt_intval = bintval | HAL_BEACON_ENA;
5970	bt.bt_nexttbtt = nexttbtt;
5971	bt.bt_nextdba = (nexttbtt<<3) - sc->sc_tdmadbaprep;
5972	bt.bt_nextswba = (nexttbtt<<3) - sc->sc_tdmaswbaprep;
5973	bt.bt_nextatim = nexttbtt+1;
5974	ath_hal_beaconsettimers(ah, &bt);
5975}
5976
5977/*
5978 * Calculate the beacon interval.  This is periodic in the
5979 * superframe for the bss.  We assume each station is configured
5980 * identically wrt transmit rate so the guard time we calculate
5981 * above will be the same on all stations.  Note we need to
5982 * factor in the xmit time because the hardware will schedule
5983 * a frame for transmit if the start of the frame is within
5984 * the burst time.  When we get hardware that properly kills
5985 * frames in the PCU we can reduce/eliminate the guard time.
5986 *
5987 * Roundup to 1024 is so we have 1 TU buffer in the guard time
5988 * to deal with the granularity of the nexttbtt timer.  11n MAC's
5989 * with 1us timer granularity should allow us to reduce/eliminate
5990 * this.
5991 */
5992static void
5993ath_tdma_bintvalsetup(struct ath_softc *sc,
5994	const struct ieee80211_tdma_state *tdma)
5995{
5996	/* copy from vap state (XXX check all vaps have same value?) */
5997	sc->sc_tdmaslotlen = tdma->tdma_slotlen;
5998
5999	sc->sc_tdmabintval = roundup((sc->sc_tdmaslotlen+sc->sc_tdmaguard) *
6000		tdma->tdma_slotcnt, 1024);
6001	sc->sc_tdmabintval >>= 10;		/* TSF -> TU */
6002	if (sc->sc_tdmabintval & 1)
6003		sc->sc_tdmabintval++;
6004
6005	if (tdma->tdma_slot == 0) {
6006		/*
6007		 * Only slot 0 beacons; other slots respond.
6008		 */
6009		sc->sc_imask |= HAL_INT_SWBA;
6010		sc->sc_tdmaswba = 0;		/* beacon immediately */
6011	} else {
6012		/* XXX all vaps must be slot 0 or slot !0 */
6013		sc->sc_imask &= ~HAL_INT_SWBA;
6014	}
6015}
6016
6017/*
6018 * Max 802.11 overhead.  This assumes no 4-address frames and
6019 * the encapsulation done by ieee80211_encap (llc).  We also
6020 * include potential crypto overhead.
6021 */
6022#define	IEEE80211_MAXOVERHEAD \
6023	(sizeof(struct ieee80211_qosframe) \
6024	 + sizeof(struct llc) \
6025	 + IEEE80211_ADDR_LEN \
6026	 + IEEE80211_WEP_IVLEN \
6027	 + IEEE80211_WEP_KIDLEN \
6028	 + IEEE80211_WEP_CRCLEN \
6029	 + IEEE80211_WEP_MICLEN \
6030	 + IEEE80211_CRC_LEN)
6031
6032/*
6033 * Setup initially for tdma operation.  Start the beacon
6034 * timers and enable SWBA if we are slot 0.  Otherwise
6035 * we wait for slot 0 to arrive so we can sync up before
6036 * starting to transmit.
6037 */
6038static void
6039ath_tdma_config(struct ath_softc *sc, struct ieee80211vap *vap)
6040{
6041	struct ath_hal *ah = sc->sc_ah;
6042	struct ifnet *ifp = sc->sc_ifp;
6043	struct ieee80211com *ic = ifp->if_l2com;
6044	const struct ieee80211_txparam *tp;
6045	const struct ieee80211_tdma_state *tdma = NULL;
6046	int rix;
6047
6048	if (vap == NULL) {
6049		vap = TAILQ_FIRST(&ic->ic_vaps);   /* XXX */
6050		if (vap == NULL) {
6051			if_printf(ifp, "%s: no vaps?\n", __func__);
6052			return;
6053		}
6054	}
6055	tp = vap->iv_bss->ni_txparms;
6056	/*
6057	 * Calculate the guard time for each slot.  This is the
6058	 * time to send a maximal-size frame according to the
6059	 * fixed/lowest transmit rate.  Note that the interface
6060	 * mtu does not include the 802.11 overhead so we must
6061	 * tack that on (ath_hal_computetxtime includes the
6062	 * preamble and plcp in it's calculation).
6063	 */
6064	tdma = vap->iv_tdma;
6065	if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
6066		rix = ath_tx_findrix(sc, tp->ucastrate);
6067	else
6068		rix = ath_tx_findrix(sc, tp->mcastrate);
6069	/* XXX short preamble assumed */
6070	sc->sc_tdmaguard = ath_hal_computetxtime(ah, sc->sc_currates,
6071		ifp->if_mtu + IEEE80211_MAXOVERHEAD, rix, AH_TRUE);
6072
6073	ath_hal_intrset(ah, 0);
6074
6075	ath_beaconq_config(sc);			/* setup h/w beacon q */
6076	if (sc->sc_setcca)
6077		ath_hal_setcca(ah, AH_FALSE);	/* disable CCA */
6078	ath_tdma_bintvalsetup(sc, tdma);	/* calculate beacon interval */
6079	ath_tdma_settimers(sc, sc->sc_tdmabintval,
6080		sc->sc_tdmabintval | HAL_BEACON_RESET_TSF);
6081	sc->sc_syncbeacon = 0;
6082
6083	sc->sc_avgtsfdeltap = TDMA_DUMMY_MARKER;
6084	sc->sc_avgtsfdeltam = TDMA_DUMMY_MARKER;
6085
6086	ath_hal_intrset(ah, sc->sc_imask);
6087
6088	DPRINTF(sc, ATH_DEBUG_TDMA, "%s: slot %u len %uus cnt %u "
6089	    "bsched %u guard %uus bintval %u TU dba prep %u\n", __func__,
6090	    tdma->tdma_slot, tdma->tdma_slotlen, tdma->tdma_slotcnt,
6091	    tdma->tdma_bintval, sc->sc_tdmaguard, sc->sc_tdmabintval,
6092	    sc->sc_tdmadbaprep);
6093}
6094
6095/*
6096 * Update tdma operation.  Called from the 802.11 layer
6097 * when a beacon is received from the TDMA station operating
6098 * in the slot immediately preceding us in the bss.  Use
6099 * the rx timestamp for the beacon frame to update our
6100 * beacon timers so we follow their schedule.  Note that
6101 * by using the rx timestamp we implicitly include the
6102 * propagation delay in our schedule.
6103 */
6104static void
6105ath_tdma_update(struct ieee80211_node *ni,
6106	const struct ieee80211_tdma_param *tdma, int changed)
6107{
6108#define	TSF_TO_TU(_h,_l) \
6109	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
6110#define	TU_TO_TSF(_tu)	(((u_int64_t)(_tu)) << 10)
6111	struct ieee80211vap *vap = ni->ni_vap;
6112	struct ieee80211com *ic = ni->ni_ic;
6113	struct ath_softc *sc = ic->ic_ifp->if_softc;
6114	struct ath_hal *ah = sc->sc_ah;
6115	const HAL_RATE_TABLE *rt = sc->sc_currates;
6116	u_int64_t tsf, rstamp, nextslot;
6117	u_int32_t txtime, nextslottu, timer0;
6118	int32_t tudelta, tsfdelta;
6119	const struct ath_rx_status *rs;
6120	int rix;
6121
6122	sc->sc_stats.ast_tdma_update++;
6123
6124	/*
6125	 * Check for and adopt configuration changes.
6126	 */
6127	if (changed != 0) {
6128		const struct ieee80211_tdma_state *ts = vap->iv_tdma;
6129
6130		ath_tdma_bintvalsetup(sc, ts);
6131		if (changed & TDMA_UPDATE_SLOTLEN)
6132			ath_wme_update(ic);
6133
6134		DPRINTF(sc, ATH_DEBUG_TDMA,
6135		    "%s: adopt slot %u slotcnt %u slotlen %u us "
6136		    "bintval %u TU\n", __func__,
6137		    ts->tdma_slot, ts->tdma_slotcnt, ts->tdma_slotlen,
6138		    sc->sc_tdmabintval);
6139
6140		/* XXX right? */
6141		ath_hal_intrset(ah, sc->sc_imask);
6142		/* NB: beacon timers programmed below */
6143	}
6144
6145	/* extend rx timestamp to 64 bits */
6146	rs = sc->sc_lastrs;
6147	tsf = ath_hal_gettsf64(ah);
6148	rstamp = ath_extend_tsf(rs->rs_tstamp, tsf);
6149	/*
6150	 * The rx timestamp is set by the hardware on completing
6151	 * reception (at the point where the rx descriptor is DMA'd
6152	 * to the host).  To find the start of our next slot we
6153	 * must adjust this time by the time required to send
6154	 * the packet just received.
6155	 */
6156	rix = rt->rateCodeToIndex[rs->rs_rate];
6157	txtime = ath_hal_computetxtime(ah, rt, rs->rs_datalen, rix,
6158	    rt->info[rix].shortPreamble);
6159	/* NB: << 9 is to cvt to TU and /2 */
6160	nextslot = (rstamp - txtime) + (sc->sc_tdmabintval << 9);
6161	nextslottu = TSF_TO_TU(nextslot>>32, nextslot) & HAL_BEACON_PERIOD;
6162
6163	/*
6164	 * TIMER0 is the h/w's idea of NextTBTT (in TU's).  Convert
6165	 * to usecs and calculate the difference between what the
6166	 * other station thinks and what we have programmed.  This
6167	 * lets us figure how to adjust our timers to match.  The
6168	 * adjustments are done by pulling the TSF forward and possibly
6169	 * rewriting the beacon timers.
6170	 */
6171	timer0 = ath_hal_getnexttbtt(ah);
6172	tsfdelta = (int32_t)((nextslot % TU_TO_TSF(HAL_BEACON_PERIOD+1)) - TU_TO_TSF(timer0));
6173
6174	DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
6175	    "tsfdelta %d avg +%d/-%d\n", tsfdelta,
6176	    TDMA_AVG(sc->sc_avgtsfdeltap), TDMA_AVG(sc->sc_avgtsfdeltam));
6177
6178	if (tsfdelta < 0) {
6179		TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
6180		TDMA_SAMPLE(sc->sc_avgtsfdeltam, -tsfdelta);
6181		tsfdelta = -tsfdelta % 1024;
6182		nextslottu++;
6183	} else if (tsfdelta > 0) {
6184		TDMA_SAMPLE(sc->sc_avgtsfdeltap, tsfdelta);
6185		TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
6186		tsfdelta = 1024 - (tsfdelta % 1024);
6187		nextslottu++;
6188	} else {
6189		TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
6190		TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
6191	}
6192	tudelta = nextslottu - timer0;
6193
6194	/*
6195	 * Copy sender's timetstamp into tdma ie so they can
6196	 * calculate roundtrip time.  We submit a beacon frame
6197	 * below after any timer adjustment.  The frame goes out
6198	 * at the next TBTT so the sender can calculate the
6199	 * roundtrip by inspecting the tdma ie in our beacon frame.
6200	 *
6201	 * NB: This tstamp is subtlely preserved when
6202	 *     IEEE80211_BEACON_TDMA is marked (e.g. when the
6203	 *     slot position changes) because ieee80211_add_tdma
6204	 *     skips over the data.
6205	 */
6206	memcpy(ATH_VAP(vap)->av_boff.bo_tdma +
6207		__offsetof(struct ieee80211_tdma_param, tdma_tstamp),
6208		&ni->ni_tstamp.data, 8);
6209#if 0
6210	DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
6211	    "tsf %llu nextslot %llu (%d, %d) nextslottu %u timer0 %u (%d)\n",
6212	    (unsigned long long) tsf, (unsigned long long) nextslot,
6213	    (int)(nextslot - tsf), tsfdelta,
6214	    nextslottu, timer0, tudelta);
6215#endif
6216	/*
6217	 * Adjust the beacon timers only when pulling them forward
6218	 * or when going back by less than the beacon interval.
6219	 * Negative jumps larger than the beacon interval seem to
6220	 * cause the timers to stop and generally cause instability.
6221	 * This basically filters out jumps due to missed beacons.
6222	 */
6223	if (tudelta != 0 && (tudelta > 0 || -tudelta < sc->sc_tdmabintval)) {
6224		ath_tdma_settimers(sc, nextslottu, sc->sc_tdmabintval);
6225		sc->sc_stats.ast_tdma_timers++;
6226	}
6227	if (tsfdelta > 0) {
6228		ath_hal_adjusttsf(ah, tsfdelta);
6229		sc->sc_stats.ast_tdma_tsf++;
6230	}
6231	ath_tdma_beacon_send(sc, vap);		/* prepare response */
6232#undef TU_TO_TSF
6233#undef TSF_TO_TU
6234}
6235
6236/*
6237 * Transmit a beacon frame at SWBA.  Dynamic updates
6238 * to the frame contents are done as needed.
6239 */
6240static void
6241ath_tdma_beacon_send(struct ath_softc *sc, struct ieee80211vap *vap)
6242{
6243	struct ath_hal *ah = sc->sc_ah;
6244	struct ath_buf *bf;
6245	int otherant;
6246
6247	/*
6248	 * Check if the previous beacon has gone out.  If
6249	 * not don't try to post another, skip this period
6250	 * and wait for the next.  Missed beacons indicate
6251	 * a problem and should not occur.  If we miss too
6252	 * many consecutive beacons reset the device.
6253	 */
6254	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
6255		sc->sc_bmisscount++;
6256		DPRINTF(sc, ATH_DEBUG_BEACON,
6257			"%s: missed %u consecutive beacons\n",
6258			__func__, sc->sc_bmisscount);
6259		if (sc->sc_bmisscount >= ath_bstuck_threshold)
6260			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
6261		return;
6262	}
6263	if (sc->sc_bmisscount != 0) {
6264		DPRINTF(sc, ATH_DEBUG_BEACON,
6265			"%s: resume beacon xmit after %u misses\n",
6266			__func__, sc->sc_bmisscount);
6267		sc->sc_bmisscount = 0;
6268	}
6269
6270	/*
6271	 * Check recent per-antenna transmit statistics and flip
6272	 * the default antenna if noticeably more frames went out
6273	 * on the non-default antenna.
6274	 * XXX assumes 2 anntenae
6275	 */
6276	if (!sc->sc_diversity) {
6277		otherant = sc->sc_defant & 1 ? 2 : 1;
6278		if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
6279			ath_setdefantenna(sc, otherant);
6280		sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
6281	}
6282
6283	bf = ath_beacon_generate(sc, vap);
6284	if (bf != NULL) {
6285		/*
6286		 * Stop any current dma and put the new frame on the queue.
6287		 * This should never fail since we check above that no frames
6288		 * are still pending on the queue.
6289		 */
6290		if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
6291			DPRINTF(sc, ATH_DEBUG_ANY,
6292				"%s: beacon queue %u did not stop?\n",
6293				__func__, sc->sc_bhalq);
6294			/* NB: the HAL still stops DMA, so proceed */
6295		}
6296		ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
6297		ath_hal_txstart(ah, sc->sc_bhalq);
6298
6299		sc->sc_stats.ast_be_xmit++;		/* XXX per-vap? */
6300
6301		/*
6302		 * Record local TSF for our last send for use
6303		 * in arbitrating slot collisions.
6304		 */
6305		vap->iv_bss->ni_tstamp.tsf = ath_hal_gettsf64(ah);
6306	}
6307}
6308#endif /* IEEE80211_SUPPORT_TDMA */
6309
6310static int
6311ath_sysctl_clearstats(SYSCTL_HANDLER_ARGS)
6312{
6313	struct ath_softc *sc = arg1;
6314	int val = 0;
6315	int error;
6316
6317	error = sysctl_handle_int(oidp, &val, 0, req);
6318	if (error || !req->newptr)
6319		return error;
6320	if (val == 0)
6321		return 0;       /* Not clearing the stats is still valid */
6322	memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
6323	val = 0;
6324	return 0;
6325}
6326
6327static void
6328ath_sysctl_stats_attach(struct ath_softc *sc)
6329{
6330	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
6331	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
6332	struct sysctl_oid_list *child = SYSCTL_CHILDREN(tree);
6333
6334	/* Create "clear" node */
6335	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6336	    "clear_stats", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6337	    ath_sysctl_clearstats, "I", "clear stats");
6338
6339	/* Create stats node */
6340	tree = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, "stats", CTLFLAG_RD,
6341	    NULL, "Statistics");
6342	child = SYSCTL_CHILDREN(tree);
6343
6344	/* This was generated from if_athioctl.h */
6345
6346	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_watchdog", CTLFLAG_RD,
6347	    &sc->sc_stats.ast_watchdog, 0, "device reset by watchdog");
6348	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_hardware", CTLFLAG_RD,
6349	    &sc->sc_stats.ast_hardware, 0, "fatal hardware error interrupts");
6350	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_bmiss", CTLFLAG_RD,
6351	    &sc->sc_stats.ast_bmiss, 0, "beacon miss interrupts");
6352	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_bmiss_phantom", CTLFLAG_RD,
6353	    &sc->sc_stats.ast_bmiss_phantom, 0, "beacon miss interrupts");
6354	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_bstuck", CTLFLAG_RD,
6355	    &sc->sc_stats.ast_bstuck, 0, "beacon stuck interrupts");
6356	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rxorn", CTLFLAG_RD,
6357	    &sc->sc_stats.ast_rxorn, 0, "rx overrun interrupts");
6358	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rxeol", CTLFLAG_RD,
6359	    &sc->sc_stats.ast_rxeol, 0, "rx eol interrupts");
6360	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_txurn", CTLFLAG_RD,
6361	    &sc->sc_stats.ast_txurn, 0, "tx underrun interrupts");
6362	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_mib", CTLFLAG_RD,
6363	    &sc->sc_stats.ast_mib, 0, "mib interrupts");
6364	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_intrcoal", CTLFLAG_RD,
6365	    &sc->sc_stats.ast_intrcoal, 0, "interrupts coalesced");
6366	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_packets", CTLFLAG_RD,
6367	    &sc->sc_stats.ast_tx_packets, 0, "packet sent on the interface");
6368	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_mgmt", CTLFLAG_RD,
6369	    &sc->sc_stats.ast_tx_mgmt, 0, "management frames transmitted");
6370	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_discard", CTLFLAG_RD,
6371	    &sc->sc_stats.ast_tx_discard, 0, "frames discarded prior to assoc");
6372	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_qstop", CTLFLAG_RD,
6373	    &sc->sc_stats.ast_tx_qstop, 0, "output stopped 'cuz no buffer");
6374	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_encap", CTLFLAG_RD,
6375	    &sc->sc_stats.ast_tx_encap, 0, "tx encapsulation failed");
6376	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nonode", CTLFLAG_RD,
6377	    &sc->sc_stats.ast_tx_nonode, 0, "tx failed 'cuz no node");
6378	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nombuf", CTLFLAG_RD,
6379	    &sc->sc_stats.ast_tx_nombuf, 0, "tx failed 'cuz no mbuf");
6380	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nomcl", CTLFLAG_RD,
6381	    &sc->sc_stats.ast_tx_nomcl, 0, "tx failed 'cuz no cluster");
6382	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_linear", CTLFLAG_RD,
6383	    &sc->sc_stats.ast_tx_linear, 0, "tx linearized to cluster");
6384	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nodata", CTLFLAG_RD,
6385	    &sc->sc_stats.ast_tx_nodata, 0, "tx discarded empty frame");
6386	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_busdma", CTLFLAG_RD,
6387	    &sc->sc_stats.ast_tx_busdma, 0, "tx failed for dma resrcs");
6388	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_xretries", CTLFLAG_RD,
6389	    &sc->sc_stats.ast_tx_xretries, 0, "tx failed 'cuz too many retries");
6390	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_fifoerr", CTLFLAG_RD,
6391	    &sc->sc_stats.ast_tx_fifoerr, 0, "tx failed 'cuz FIFO underrun");
6392	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_filtered", CTLFLAG_RD,
6393	    &sc->sc_stats.ast_tx_filtered, 0, "tx failed 'cuz xmit filtered");
6394	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_shortretry", CTLFLAG_RD,
6395	    &sc->sc_stats.ast_tx_shortretry, 0, "tx on-chip retries (short)");
6396	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_longretry", CTLFLAG_RD,
6397	    &sc->sc_stats.ast_tx_longretry, 0, "tx on-chip retries (long)");
6398	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_badrate", CTLFLAG_RD,
6399	    &sc->sc_stats.ast_tx_badrate, 0, "tx failed 'cuz bogus xmit rate");
6400	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_noack", CTLFLAG_RD,
6401	    &sc->sc_stats.ast_tx_noack, 0, "tx frames with no ack marked");
6402	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_rts", CTLFLAG_RD,
6403	    &sc->sc_stats.ast_tx_rts, 0, "tx frames with rts enabled");
6404	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_cts", CTLFLAG_RD,
6405	    &sc->sc_stats.ast_tx_cts, 0, "tx frames with cts enabled");
6406	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_shortpre", CTLFLAG_RD,
6407	    &sc->sc_stats.ast_tx_shortpre, 0, "tx frames with short preamble");
6408	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_altrate", CTLFLAG_RD,
6409	    &sc->sc_stats.ast_tx_altrate, 0, "tx frames with alternate rate");
6410	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_protect", CTLFLAG_RD,
6411	    &sc->sc_stats.ast_tx_protect, 0, "tx frames with protection");
6412	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_ctsburst", CTLFLAG_RD,
6413	    &sc->sc_stats.ast_tx_ctsburst, 0, "tx frames with cts and bursting");
6414	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_ctsext", CTLFLAG_RD,
6415	    &sc->sc_stats.ast_tx_ctsext, 0, "tx frames with cts extension");
6416	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_nombuf", CTLFLAG_RD,
6417	    &sc->sc_stats.ast_rx_nombuf, 0, "rx setup failed 'cuz no mbuf");
6418	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_busdma", CTLFLAG_RD,
6419	    &sc->sc_stats.ast_rx_busdma, 0, "rx setup failed for dma resrcs");
6420	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_orn", CTLFLAG_RD,
6421	    &sc->sc_stats.ast_rx_orn, 0, "rx failed 'cuz of desc overrun");
6422	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_crcerr", CTLFLAG_RD,
6423	    &sc->sc_stats.ast_rx_crcerr, 0, "rx failed 'cuz of bad CRC");
6424	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_fifoerr", CTLFLAG_RD,
6425	    &sc->sc_stats.ast_rx_fifoerr, 0, "rx failed 'cuz of FIFO overrun");
6426	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_badcrypt", CTLFLAG_RD,
6427	    &sc->sc_stats.ast_rx_badcrypt, 0, "rx failed 'cuz decryption");
6428	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_badmic", CTLFLAG_RD,
6429	    &sc->sc_stats.ast_rx_badmic, 0, "rx failed 'cuz MIC failure");
6430	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_phyerr", CTLFLAG_RD,
6431	    &sc->sc_stats.ast_rx_phyerr, 0, "rx failed 'cuz of PHY err");
6432	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_tooshort", CTLFLAG_RD,
6433	    &sc->sc_stats.ast_rx_tooshort, 0, "rx discarded 'cuz frame too short");
6434	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_toobig", CTLFLAG_RD,
6435	    &sc->sc_stats.ast_rx_toobig, 0, "rx discarded 'cuz frame too large");
6436	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_packets", CTLFLAG_RD,
6437	    &sc->sc_stats.ast_rx_packets, 0, "packet recv on the interface");
6438	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_mgt", CTLFLAG_RD,
6439	    &sc->sc_stats.ast_rx_mgt, 0, "management frames received");
6440	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_ctl", CTLFLAG_RD,
6441	    &sc->sc_stats.ast_rx_ctl, 0, "rx discarded 'cuz ctl frame");
6442	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_be_xmit", CTLFLAG_RD,
6443	    &sc->sc_stats.ast_be_xmit, 0, "beacons transmitted");
6444	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_be_nombuf", CTLFLAG_RD,
6445	    &sc->sc_stats.ast_be_nombuf, 0, "beacon setup failed 'cuz no mbuf");
6446	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_per_cal", CTLFLAG_RD,
6447	    &sc->sc_stats.ast_per_cal, 0, "periodic calibration calls");
6448	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_per_calfail", CTLFLAG_RD,
6449	    &sc->sc_stats.ast_per_calfail, 0, "periodic calibration failed");
6450	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_per_rfgain", CTLFLAG_RD,
6451	    &sc->sc_stats.ast_per_rfgain, 0, "periodic calibration rfgain reset");
6452	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rate_calls", CTLFLAG_RD,
6453	    &sc->sc_stats.ast_rate_calls, 0, "rate control checks");
6454	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rate_raise", CTLFLAG_RD,
6455	    &sc->sc_stats.ast_rate_raise, 0, "rate control raised xmit rate");
6456	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rate_drop", CTLFLAG_RD,
6457	    &sc->sc_stats.ast_rate_drop, 0, "rate control dropped xmit rate");
6458	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ant_defswitch", CTLFLAG_RD,
6459	    &sc->sc_stats.ast_ant_defswitch, 0, "rx/default antenna switches");
6460	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ant_txswitch", CTLFLAG_RD,
6461	    &sc->sc_stats.ast_ant_txswitch, 0, "tx antenna switches");
6462	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_cabq_xmit", CTLFLAG_RD,
6463	    &sc->sc_stats.ast_cabq_xmit, 0, "cabq frames transmitted");
6464	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_cabq_busy", CTLFLAG_RD,
6465	    &sc->sc_stats.ast_cabq_busy, 0, "cabq found busy");
6466	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_raw", CTLFLAG_RD,
6467	    &sc->sc_stats.ast_tx_raw, 0, "tx frames through raw api");
6468	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ff_txok", CTLFLAG_RD,
6469	    &sc->sc_stats.ast_ff_txok, 0, "fast frames tx'd successfully");
6470	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ff_txerr", CTLFLAG_RD,
6471	    &sc->sc_stats.ast_ff_txerr, 0, "fast frames tx'd w/ error");
6472	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ff_rx", CTLFLAG_RD,
6473	    &sc->sc_stats.ast_ff_rx, 0, "fast frames rx'd");
6474	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ff_flush", CTLFLAG_RD,
6475	    &sc->sc_stats.ast_ff_flush, 0, "fast frames flushed from staging q");
6476	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_qfull", CTLFLAG_RD,
6477	    &sc->sc_stats.ast_tx_qfull, 0, "tx dropped 'cuz of queue limit");
6478	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nobuf", CTLFLAG_RD,
6479	    &sc->sc_stats.ast_tx_nobuf, 0, "tx dropped 'cuz no ath buffer");
6480	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tdma_update", CTLFLAG_RD,
6481	    &sc->sc_stats.ast_tdma_update, 0, "TDMA slot timing updates");
6482	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tdma_timers", CTLFLAG_RD,
6483	    &sc->sc_stats.ast_tdma_timers, 0, "TDMA slot update set beacon timers");
6484	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tdma_tsf", CTLFLAG_RD,
6485	    &sc->sc_stats.ast_tdma_tsf, 0, "TDMA slot update set TSF");
6486	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tdma_ack", CTLFLAG_RD,
6487	    &sc->sc_stats.ast_tdma_ack, 0, "TDMA tx failed 'cuz ACK required");
6488	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_raw_fail", CTLFLAG_RD,
6489	    &sc->sc_stats.ast_tx_raw_fail, 0, "raw tx failed 'cuz h/w down");
6490	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nofrag", CTLFLAG_RD,
6491	    &sc->sc_stats.ast_tx_nofrag, 0, "tx dropped 'cuz no ath frag buffer");
6492	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_be_missed", CTLFLAG_RD,
6493	    &sc->sc_stats.ast_be_missed, 0, "number of -missed- beacons");
6494	SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ani_cal", CTLFLAG_RD,
6495	    &sc->sc_stats.ast_ani_cal, 0, "number of ANI polls");
6496}
6497