if_ath.c revision 165571
1/*-
2 * Copyright (c) 2002-2006 Sam Leffler, Errno Consulting
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer,
10 *    without modification.
11 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12 *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13 *    redistribution must be conditioned upon including a substantially
14 *    similar Disclaimer requirement for further binary redistribution.
15 * 3. Neither the names of the above-listed copyright holders nor the names
16 *    of any contributors may be used to endorse or promote products derived
17 *    from this software without specific prior written permission.
18 *
19 * Alternatively, this software may be distributed under the terms of the
20 * GNU General Public License ("GPL") version 2 as published by the Free
21 * Software Foundation.
22 *
23 * NO WARRANTY
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26 * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
27 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
28 * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
29 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
32 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
34 * THE POSSIBILITY OF SUCH DAMAGES.
35 */
36
37#include <sys/cdefs.h>
38__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath.c 165571 2006-12-27 19:07:09Z sam $");
39
40/*
41 * Driver for the Atheros Wireless LAN controller.
42 *
43 * This software is derived from work of Atsushi Onoe; his contribution
44 * is greatly appreciated.
45 */
46
47#include "opt_inet.h"
48#include "opt_ath.h"
49
50#include <sys/param.h>
51#include <sys/systm.h>
52#include <sys/sysctl.h>
53#include <sys/mbuf.h>
54#include <sys/malloc.h>
55#include <sys/lock.h>
56#include <sys/mutex.h>
57#include <sys/kernel.h>
58#include <sys/socket.h>
59#include <sys/sockio.h>
60#include <sys/errno.h>
61#include <sys/callout.h>
62#include <sys/bus.h>
63#include <sys/endian.h>
64#include <sys/kthread.h>
65#include <sys/taskqueue.h>
66
67#include <machine/bus.h>
68
69#include <net/if.h>
70#include <net/if_dl.h>
71#include <net/if_media.h>
72#include <net/if_types.h>
73#include <net/if_arp.h>
74#include <net/ethernet.h>
75#include <net/if_llc.h>
76
77#include <net80211/ieee80211_var.h>
78
79#include <net/bpf.h>
80
81#ifdef INET
82#include <netinet/in.h>
83#include <netinet/if_ether.h>
84#endif
85
86#include <dev/ath/if_athvar.h>
87#include <contrib/dev/ath/ah_desc.h>
88#include <contrib/dev/ath/ah_devid.h>		/* XXX for softled */
89
90#ifdef ATH_TX99_DIAG
91#include <dev/ath/ath_tx99/ath_tx99.h>
92#endif
93
94/* unaligned little endian access */
95#define LE_READ_2(p)							\
96	((u_int16_t)							\
97	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
98#define LE_READ_4(p)							\
99	((u_int32_t)							\
100	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) |	\
101	  (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
102
103enum {
104	ATH_LED_TX,
105	ATH_LED_RX,
106	ATH_LED_POLL,
107};
108
109static void	ath_init(void *);
110static void	ath_stop_locked(struct ifnet *);
111static void	ath_stop(struct ifnet *);
112static void	ath_start(struct ifnet *);
113static int	ath_reset(struct ifnet *);
114static int	ath_media_change(struct ifnet *);
115static void	ath_watchdog(struct ifnet *);
116static int	ath_ioctl(struct ifnet *, u_long, caddr_t);
117static void	ath_fatal_proc(void *, int);
118static void	ath_rxorn_proc(void *, int);
119static void	ath_bmiss_proc(void *, int);
120static int	ath_key_alloc(struct ieee80211com *,
121			const struct ieee80211_key *,
122			ieee80211_keyix *, ieee80211_keyix *);
123static int	ath_key_delete(struct ieee80211com *,
124			const struct ieee80211_key *);
125static int	ath_key_set(struct ieee80211com *, const struct ieee80211_key *,
126			const u_int8_t mac[IEEE80211_ADDR_LEN]);
127static void	ath_key_update_begin(struct ieee80211com *);
128static void	ath_key_update_end(struct ieee80211com *);
129static void	ath_mode_init(struct ath_softc *);
130static void	ath_setslottime(struct ath_softc *);
131static void	ath_updateslot(struct ifnet *);
132static int	ath_beaconq_setup(struct ath_hal *);
133static int	ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
134static void	ath_beacon_setup(struct ath_softc *, struct ath_buf *);
135static void	ath_beacon_proc(void *, int);
136static void	ath_bstuck_proc(void *, int);
137static void	ath_beacon_free(struct ath_softc *);
138static void	ath_beacon_config(struct ath_softc *);
139static void	ath_descdma_cleanup(struct ath_softc *sc,
140			struct ath_descdma *, ath_bufhead *);
141static int	ath_desc_alloc(struct ath_softc *);
142static void	ath_desc_free(struct ath_softc *);
143static struct ieee80211_node *ath_node_alloc(struct ieee80211_node_table *);
144static void	ath_node_free(struct ieee80211_node *);
145static u_int8_t	ath_node_getrssi(const struct ieee80211_node *);
146static int	ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
147static void	ath_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
148			struct ieee80211_node *ni,
149			int subtype, int rssi, u_int32_t rstamp);
150static void	ath_setdefantenna(struct ath_softc *, u_int);
151static void	ath_rx_proc(void *, int);
152static void	ath_txq_init(struct ath_softc *sc, struct ath_txq *, int);
153static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
154static int	ath_tx_setup(struct ath_softc *, int, int);
155static int	ath_wme_update(struct ieee80211com *);
156static void	ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
157static void	ath_tx_cleanup(struct ath_softc *);
158static int	ath_tx_start(struct ath_softc *, struct ieee80211_node *,
159			     struct ath_buf *, struct mbuf *);
160static void	ath_tx_proc_q0(void *, int);
161static void	ath_tx_proc_q0123(void *, int);
162static void	ath_tx_proc(void *, int);
163static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
164static void	ath_draintxq(struct ath_softc *);
165static void	ath_stoprecv(struct ath_softc *);
166static int	ath_startrecv(struct ath_softc *);
167static void	ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
168static void	ath_next_scan(void *);
169static void	ath_calibrate(void *);
170static int	ath_newstate(struct ieee80211com *, enum ieee80211_state, int);
171static void	ath_setup_stationkey(struct ieee80211_node *);
172static void	ath_newassoc(struct ieee80211_node *, int);
173static int	ath_getchannels(struct ath_softc *,
174			HAL_REG_DOMAIN, HAL_CTRY_CODE, HAL_BOOL, HAL_BOOL);
175static void	ath_led_event(struct ath_softc *, int);
176static void	ath_update_txpow(struct ath_softc *);
177
178static int	ath_rate_setup(struct ath_softc *, u_int mode);
179static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
180
181static void	ath_sysctlattach(struct ath_softc *);
182static int	ath_raw_xmit(struct ieee80211_node *,
183			struct mbuf *, const struct ieee80211_bpf_params *);
184static void	ath_bpfattach(struct ath_softc *);
185static void	ath_announce(struct ath_softc *);
186
187SYSCTL_DECL(_hw_ath);
188
189/* XXX validate sysctl values */
190static	int ath_dwelltime = 200;		/* 5 channels/second */
191SYSCTL_INT(_hw_ath, OID_AUTO, dwell, CTLFLAG_RW, &ath_dwelltime,
192	    0, "channel dwell time (ms) for AP/station scanning");
193static	int ath_calinterval = 30;		/* calibrate every 30 secs */
194SYSCTL_INT(_hw_ath, OID_AUTO, calibrate, CTLFLAG_RW, &ath_calinterval,
195	    0, "chip calibration interval (secs)");
196static	int ath_outdoor = AH_TRUE;		/* outdoor operation */
197SYSCTL_INT(_hw_ath, OID_AUTO, outdoor, CTLFLAG_RW, &ath_outdoor,
198	    0, "outdoor operation");
199TUNABLE_INT("hw.ath.outdoor", &ath_outdoor);
200static	int ath_xchanmode = AH_TRUE;		/* extended channel use */
201SYSCTL_INT(_hw_ath, OID_AUTO, xchanmode, CTLFLAG_RW, &ath_xchanmode,
202	    0, "extended channel mode");
203TUNABLE_INT("hw.ath.xchanmode", &ath_xchanmode);
204static	int ath_countrycode = CTRY_DEFAULT;	/* country code */
205SYSCTL_INT(_hw_ath, OID_AUTO, countrycode, CTLFLAG_RW, &ath_countrycode,
206	    0, "country code");
207TUNABLE_INT("hw.ath.countrycode", &ath_countrycode);
208static	int ath_regdomain = 0;			/* regulatory domain */
209SYSCTL_INT(_hw_ath, OID_AUTO, regdomain, CTLFLAG_RD, &ath_regdomain,
210	    0, "regulatory domain");
211
212static	int ath_rxbuf = ATH_RXBUF;		/* # rx buffers to allocate */
213SYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RW, &ath_rxbuf,
214	    0, "rx buffers allocated");
215TUNABLE_INT("hw.ath.rxbuf", &ath_rxbuf);
216static	int ath_txbuf = ATH_TXBUF;		/* # tx buffers to allocate */
217SYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RW, &ath_txbuf,
218	    0, "tx buffers allocated");
219TUNABLE_INT("hw.ath.txbuf", &ath_txbuf);
220
221#ifdef ATH_DEBUG
222static	int ath_debug = 0;
223SYSCTL_INT(_hw_ath, OID_AUTO, debug, CTLFLAG_RW, &ath_debug,
224	    0, "control debugging printfs");
225TUNABLE_INT("hw.ath.debug", &ath_debug);
226enum {
227	ATH_DEBUG_XMIT		= 0x00000001,	/* basic xmit operation */
228	ATH_DEBUG_XMIT_DESC	= 0x00000002,	/* xmit descriptors */
229	ATH_DEBUG_RECV		= 0x00000004,	/* basic recv operation */
230	ATH_DEBUG_RECV_DESC	= 0x00000008,	/* recv descriptors */
231	ATH_DEBUG_RATE		= 0x00000010,	/* rate control */
232	ATH_DEBUG_RESET		= 0x00000020,	/* reset processing */
233	ATH_DEBUG_MODE		= 0x00000040,	/* mode init/setup */
234	ATH_DEBUG_BEACON 	= 0x00000080,	/* beacon handling */
235	ATH_DEBUG_WATCHDOG 	= 0x00000100,	/* watchdog timeout */
236	ATH_DEBUG_INTR		= 0x00001000,	/* ISR */
237	ATH_DEBUG_TX_PROC	= 0x00002000,	/* tx ISR proc */
238	ATH_DEBUG_RX_PROC	= 0x00004000,	/* rx ISR proc */
239	ATH_DEBUG_BEACON_PROC	= 0x00008000,	/* beacon ISR proc */
240	ATH_DEBUG_CALIBRATE	= 0x00010000,	/* periodic calibration */
241	ATH_DEBUG_KEYCACHE	= 0x00020000,	/* key cache management */
242	ATH_DEBUG_STATE		= 0x00040000,	/* 802.11 state transitions */
243	ATH_DEBUG_NODE		= 0x00080000,	/* node management */
244	ATH_DEBUG_LED		= 0x00100000,	/* led management */
245	ATH_DEBUG_FF		= 0x00200000,	/* fast frames */
246	ATH_DEBUG_DFS		= 0x00400000,	/* DFS processing */
247	ATH_DEBUG_FATAL		= 0x80000000,	/* fatal errors */
248	ATH_DEBUG_ANY		= 0xffffffff
249};
250#define	IFF_DUMPPKTS(sc, m) \
251	((sc->sc_debug & (m)) || \
252	    (sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
253#define	DPRINTF(sc, m, fmt, ...) do {				\
254	if (sc->sc_debug & (m))					\
255		printf(fmt, __VA_ARGS__);			\
256} while (0)
257#define	KEYPRINTF(sc, ix, hk, mac) do {				\
258	if (sc->sc_debug & ATH_DEBUG_KEYCACHE)			\
259		ath_keyprint(sc, __func__, ix, hk, mac);	\
260} while (0)
261static	void ath_printrxbuf(const struct ath_buf *bf, u_int ix, int);
262static	void ath_printtxbuf(const struct ath_buf *bf, u_int qnum, u_int ix, int done);
263#else
264#define	IFF_DUMPPKTS(sc, m) \
265	((sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
266#define	DPRINTF(sc, m, fmt, ...) do {				\
267	(void) sc;						\
268} while (0)
269#define	KEYPRINTF(sc, k, ix, mac) do {				\
270	(void) sc;						\
271} while (0)
272#endif
273
274MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
275
276int
277ath_attach(u_int16_t devid, struct ath_softc *sc)
278{
279	struct ifnet *ifp;
280	struct ieee80211com *ic = &sc->sc_ic;
281	struct ath_hal *ah = NULL;
282	HAL_STATUS status;
283	int error = 0, i;
284
285	DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
286
287	ifp = sc->sc_ifp = if_alloc(IFT_ETHER);
288	if (ifp == NULL) {
289		device_printf(sc->sc_dev, "can not if_alloc()\n");
290		error = ENOSPC;
291		goto bad;
292	}
293
294	/* set these up early for if_printf use */
295	if_initname(ifp, device_get_name(sc->sc_dev),
296		device_get_unit(sc->sc_dev));
297
298	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, &status);
299	if (ah == NULL) {
300		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
301			status);
302		error = ENXIO;
303		goto bad;
304	}
305	if (ah->ah_abi != HAL_ABI_VERSION) {
306		if_printf(ifp, "HAL ABI mismatch detected "
307			"(HAL:0x%x != driver:0x%x)\n",
308			ah->ah_abi, HAL_ABI_VERSION);
309		error = ENXIO;
310		goto bad;
311	}
312	sc->sc_ah = ah;
313	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
314
315	/*
316	 * Check if the MAC has multi-rate retry support.
317	 * We do this by trying to setup a fake extended
318	 * descriptor.  MAC's that don't have support will
319	 * return false w/o doing anything.  MAC's that do
320	 * support it will return true w/o doing anything.
321	 */
322	sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
323
324	/*
325	 * Check if the device has hardware counters for PHY
326	 * errors.  If so we need to enable the MIB interrupt
327	 * so we can act on stat triggers.
328	 */
329	if (ath_hal_hwphycounters(ah))
330		sc->sc_needmib = 1;
331
332	/*
333	 * Get the hardware key cache size.
334	 */
335	sc->sc_keymax = ath_hal_keycachesize(ah);
336	if (sc->sc_keymax > ATH_KEYMAX) {
337		if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
338			ATH_KEYMAX, sc->sc_keymax);
339		sc->sc_keymax = ATH_KEYMAX;
340	}
341	/*
342	 * Reset the key cache since some parts do not
343	 * reset the contents on initial power up.
344	 */
345	for (i = 0; i < sc->sc_keymax; i++)
346		ath_hal_keyreset(ah, i);
347
348	/*
349	 * Collect the channel list using the default country
350	 * code and including outdoor channels.  The 802.11 layer
351	 * is resposible for filtering this list based on settings
352	 * like the phy mode.
353	 */
354	error = ath_getchannels(sc, ath_regdomain, ath_countrycode,
355			ath_xchanmode != 0, ath_outdoor != 0);
356	if (error != 0)
357		goto bad;
358
359	/*
360	 * Setup rate tables for all potential media types.
361	 */
362	ath_rate_setup(sc, IEEE80211_MODE_11A);
363	ath_rate_setup(sc, IEEE80211_MODE_11B);
364	ath_rate_setup(sc, IEEE80211_MODE_11G);
365	ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
366	ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
367	ath_rate_setup(sc, IEEE80211_MODE_11A_HALF);
368	ath_rate_setup(sc, IEEE80211_MODE_11A_QUARTER);
369
370	/* NB: setup here so ath_rate_update is happy */
371	ath_setcurmode(sc, IEEE80211_MODE_11A);
372
373	/*
374	 * Allocate tx+rx descriptors and populate the lists.
375	 */
376	error = ath_desc_alloc(sc);
377	if (error != 0) {
378		if_printf(ifp, "failed to allocate descriptors: %d\n", error);
379		goto bad;
380	}
381	callout_init(&sc->sc_scan_ch, debug_mpsafenet ? CALLOUT_MPSAFE : 0);
382	callout_init(&sc->sc_cal_ch, CALLOUT_MPSAFE);
383	callout_init(&sc->sc_dfs_ch, CALLOUT_MPSAFE);
384
385	ATH_TXBUF_LOCK_INIT(sc);
386
387	sc->sc_tq = taskqueue_create("ath_taskq", M_NOWAIT,
388		taskqueue_thread_enqueue, &sc->sc_tq);
389	taskqueue_start_threads(&sc->sc_tq, 1, PI_NET,
390		"%s taskq", ifp->if_xname);
391
392	TASK_INIT(&sc->sc_rxtask, 0, ath_rx_proc, sc);
393	TASK_INIT(&sc->sc_rxorntask, 0, ath_rxorn_proc, sc);
394	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
395	TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_proc, sc);
396
397	/*
398	 * Allocate hardware transmit queues: one queue for
399	 * beacon frames and one data queue for each QoS
400	 * priority.  Note that the hal handles reseting
401	 * these queues at the needed time.
402	 *
403	 * XXX PS-Poll
404	 */
405	sc->sc_bhalq = ath_beaconq_setup(ah);
406	if (sc->sc_bhalq == (u_int) -1) {
407		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
408		error = EIO;
409		goto bad2;
410	}
411	sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
412	if (sc->sc_cabq == NULL) {
413		if_printf(ifp, "unable to setup CAB xmit queue!\n");
414		error = EIO;
415		goto bad2;
416	}
417	ath_txq_init(sc, &sc->sc_mcastq, -1);	/* NB: s/w q, qnum not used */
418	/* NB: insure BK queue is the lowest priority h/w queue */
419	if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
420		if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
421			ieee80211_wme_acnames[WME_AC_BK]);
422		error = EIO;
423		goto bad2;
424	}
425	if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
426	    !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
427	    !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
428		/*
429		 * Not enough hardware tx queues to properly do WME;
430		 * just punt and assign them all to the same h/w queue.
431		 * We could do a better job of this if, for example,
432		 * we allocate queues when we switch from station to
433		 * AP mode.
434		 */
435		if (sc->sc_ac2q[WME_AC_VI] != NULL)
436			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
437		if (sc->sc_ac2q[WME_AC_BE] != NULL)
438			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
439		sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
440		sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
441		sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
442	}
443
444	/*
445	 * Special case certain configurations.  Note the
446	 * CAB queue is handled by these specially so don't
447	 * include them when checking the txq setup mask.
448	 */
449	switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
450	case 0x01:
451		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
452		break;
453	case 0x0f:
454		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
455		break;
456	default:
457		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
458		break;
459	}
460
461	/*
462	 * Setup rate control.  Some rate control modules
463	 * call back to change the anntena state so expose
464	 * the necessary entry points.
465	 * XXX maybe belongs in struct ath_ratectrl?
466	 */
467	sc->sc_setdefantenna = ath_setdefantenna;
468	sc->sc_rc = ath_rate_attach(sc);
469	if (sc->sc_rc == NULL) {
470		error = EIO;
471		goto bad2;
472	}
473
474	sc->sc_blinking = 0;
475	sc->sc_ledstate = 1;
476	sc->sc_ledon = 0;			/* low true */
477	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
478	callout_init(&sc->sc_ledtimer, CALLOUT_MPSAFE);
479	/*
480	 * Auto-enable soft led processing for IBM cards and for
481	 * 5211 minipci cards.  Users can also manually enable/disable
482	 * support with a sysctl.
483	 */
484	sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
485	if (sc->sc_softled) {
486		ath_hal_gpioCfgOutput(ah, sc->sc_ledpin);
487		ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
488	}
489
490	ifp->if_softc = sc;
491	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
492	ifp->if_start = ath_start;
493	ifp->if_watchdog = ath_watchdog;
494	ifp->if_ioctl = ath_ioctl;
495	ifp->if_init = ath_init;
496	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
497	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
498	IFQ_SET_READY(&ifp->if_snd);
499
500	ic->ic_ifp = ifp;
501	ic->ic_reset = ath_reset;
502	ic->ic_newassoc = ath_newassoc;
503	ic->ic_updateslot = ath_updateslot;
504	ic->ic_wme.wme_update = ath_wme_update;
505	/* XXX not right but it's not used anywhere important */
506	ic->ic_phytype = IEEE80211_T_OFDM;
507	ic->ic_opmode = IEEE80211_M_STA;
508	ic->ic_caps =
509		  IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
510		| IEEE80211_C_HOSTAP		/* hostap mode */
511		| IEEE80211_C_MONITOR		/* monitor mode */
512		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
513		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
514		| IEEE80211_C_SHSLOT		/* short slot time supported */
515		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
516		;
517	/*
518	 * Query the hal to figure out h/w crypto support.
519	 */
520	if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
521		ic->ic_caps |= IEEE80211_C_WEP;
522	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
523		ic->ic_caps |= IEEE80211_C_AES;
524	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
525		ic->ic_caps |= IEEE80211_C_AES_CCM;
526	if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
527		ic->ic_caps |= IEEE80211_C_CKIP;
528	if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
529		ic->ic_caps |= IEEE80211_C_TKIP;
530		/*
531		 * Check if h/w does the MIC and/or whether the
532		 * separate key cache entries are required to
533		 * handle both tx+rx MIC keys.
534		 */
535		if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
536			ic->ic_caps |= IEEE80211_C_TKIPMIC;
537		/*
538		 * If the h/w supports storing tx+rx MIC keys
539		 * in one cache slot automatically enable use.
540		 */
541		if (ath_hal_hastkipsplit(ah) ||
542		    !ath_hal_settkipsplit(ah, AH_FALSE))
543			sc->sc_splitmic = 1;
544	}
545	sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
546	sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
547	/*
548	 * Mark key cache slots associated with global keys
549	 * as in use.  If we knew TKIP was not to be used we
550	 * could leave the +32, +64, and +32+64 slots free.
551	 */
552	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
553		setbit(sc->sc_keymap, i);
554		setbit(sc->sc_keymap, i+64);
555		if (sc->sc_splitmic) {
556			setbit(sc->sc_keymap, i+32);
557			setbit(sc->sc_keymap, i+32+64);
558		}
559	}
560	/*
561	 * TPC support can be done either with a global cap or
562	 * per-packet support.  The latter is not available on
563	 * all parts.  We're a bit pedantic here as all parts
564	 * support a global cap.
565	 */
566	if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
567		ic->ic_caps |= IEEE80211_C_TXPMGT;
568
569	/*
570	 * Mark WME capability only if we have sufficient
571	 * hardware queues to do proper priority scheduling.
572	 */
573	if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
574		ic->ic_caps |= IEEE80211_C_WME;
575	/*
576	 * Check for misc other capabilities.
577	 */
578	if (ath_hal_hasbursting(ah))
579		ic->ic_caps |= IEEE80211_C_BURST;
580
581	/*
582	 * Indicate we need the 802.11 header padded to a
583	 * 32-bit boundary for 4-address and QoS frames.
584	 */
585	ic->ic_flags |= IEEE80211_F_DATAPAD;
586
587	/*
588	 * Query the hal about antenna support.
589	 */
590	sc->sc_defant = ath_hal_getdefantenna(ah);
591
592	/*
593	 * Not all chips have the VEOL support we want to
594	 * use with IBSS beacons; check here for it.
595	 */
596	sc->sc_hasveol = ath_hal_hasveol(ah);
597
598	/* get mac address from hardware */
599	ath_hal_getmac(ah, ic->ic_myaddr);
600
601	/* call MI attach routine. */
602	ieee80211_ifattach(ic);
603	sc->sc_opmode = ic->ic_opmode;
604	/* override default methods */
605	ic->ic_node_alloc = ath_node_alloc;
606	sc->sc_node_free = ic->ic_node_free;
607	ic->ic_node_free = ath_node_free;
608	ic->ic_node_getrssi = ath_node_getrssi;
609	sc->sc_recv_mgmt = ic->ic_recv_mgmt;
610	ic->ic_recv_mgmt = ath_recv_mgmt;
611	sc->sc_newstate = ic->ic_newstate;
612	ic->ic_newstate = ath_newstate;
613	ic->ic_crypto.cs_max_keyix = sc->sc_keymax;
614	ic->ic_crypto.cs_key_alloc = ath_key_alloc;
615	ic->ic_crypto.cs_key_delete = ath_key_delete;
616	ic->ic_crypto.cs_key_set = ath_key_set;
617	ic->ic_crypto.cs_key_update_begin = ath_key_update_begin;
618	ic->ic_crypto.cs_key_update_end = ath_key_update_end;
619	ic->ic_raw_xmit = ath_raw_xmit;
620	/* complete initialization */
621	ieee80211_media_init(ic, ath_media_change, ieee80211_media_status);
622
623	ath_bpfattach(sc);
624	/*
625	 * Setup dynamic sysctl's now that country code and
626	 * regdomain are available from the hal.
627	 */
628	ath_sysctlattach(sc);
629
630	if (bootverbose)
631		ieee80211_announce(ic);
632	ath_announce(sc);
633	return 0;
634bad2:
635	ath_tx_cleanup(sc);
636	ath_desc_free(sc);
637bad:
638	if (ah)
639		ath_hal_detach(ah);
640	if (ifp != NULL)
641		if_free(ifp);
642	sc->sc_invalid = 1;
643	return error;
644}
645
646int
647ath_detach(struct ath_softc *sc)
648{
649	struct ifnet *ifp = sc->sc_ifp;
650
651	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
652		__func__, ifp->if_flags);
653
654	ath_stop(ifp);
655	bpfdetach(ifp);
656	/*
657	 * NB: the order of these is important:
658	 * o call the 802.11 layer before detaching the hal to
659	 *   insure callbacks into the driver to delete global
660	 *   key cache entries can be handled
661	 * o reclaim the tx queue data structures after calling
662	 *   the 802.11 layer as we'll get called back to reclaim
663	 *   node state and potentially want to use them
664	 * o to cleanup the tx queues the hal is called, so detach
665	 *   it last
666	 * Other than that, it's straightforward...
667	 */
668	ieee80211_ifdetach(&sc->sc_ic);
669#ifdef ATH_TX99_DIAG
670	if (sc->sc_tx99 != NULL)
671		sc->sc_tx99->detach(sc->sc_tx99);
672#endif
673	taskqueue_free(sc->sc_tq);
674	ath_rate_detach(sc->sc_rc);
675	ath_desc_free(sc);
676	ath_tx_cleanup(sc);
677	ath_hal_detach(sc->sc_ah);
678	if_free(ifp);
679
680	return 0;
681}
682
683void
684ath_suspend(struct ath_softc *sc)
685{
686	struct ifnet *ifp = sc->sc_ifp;
687
688	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
689		__func__, ifp->if_flags);
690
691	ath_stop(ifp);
692}
693
694void
695ath_resume(struct ath_softc *sc)
696{
697	struct ifnet *ifp = sc->sc_ifp;
698
699	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
700		__func__, ifp->if_flags);
701
702	if (ifp->if_flags & IFF_UP) {
703		ath_init(sc);
704		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
705			ath_start(ifp);
706	}
707	if (sc->sc_softled) {
708		ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
709		ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
710	}
711}
712
713void
714ath_shutdown(struct ath_softc *sc)
715{
716	struct ifnet *ifp = sc->sc_ifp;
717
718	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
719		__func__, ifp->if_flags);
720
721	ath_stop(ifp);
722}
723
724/*
725 * Interrupt handler.  Most of the actual processing is deferred.
726 */
727void
728ath_intr(void *arg)
729{
730	struct ath_softc *sc = arg;
731	struct ifnet *ifp = sc->sc_ifp;
732	struct ath_hal *ah = sc->sc_ah;
733	HAL_INT status;
734
735	if (sc->sc_invalid) {
736		/*
737		 * The hardware is not ready/present, don't touch anything.
738		 * Note this can happen early on if the IRQ is shared.
739		 */
740		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
741		return;
742	}
743	if (!ath_hal_intrpend(ah))		/* shared irq, not for us */
744		return;
745	if (!((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags &
746	    IFF_DRV_RUNNING))) {
747		DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
748			__func__, ifp->if_flags);
749		ath_hal_getisr(ah, &status);	/* clear ISR */
750		ath_hal_intrset(ah, 0);		/* disable further intr's */
751		return;
752	}
753	/*
754	 * Figure out the reason(s) for the interrupt.  Note
755	 * that the hal returns a pseudo-ISR that may include
756	 * bits we haven't explicitly enabled so we mask the
757	 * value to insure we only process bits we requested.
758	 */
759	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
760	DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
761	status &= sc->sc_imask;			/* discard unasked for bits */
762	if (status & HAL_INT_FATAL) {
763		sc->sc_stats.ast_hardware++;
764		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
765		ath_fatal_proc(sc, 0);
766	} else if (status & HAL_INT_RXORN) {
767		sc->sc_stats.ast_rxorn++;
768		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
769		taskqueue_enqueue(sc->sc_tq, &sc->sc_rxorntask);
770	} else {
771		if (status & HAL_INT_SWBA) {
772			/*
773			 * Software beacon alert--time to send a beacon.
774			 * Handle beacon transmission directly; deferring
775			 * this is too slow to meet timing constraints
776			 * under load.
777			 */
778			ath_beacon_proc(sc, 0);
779		}
780		if (status & HAL_INT_RXEOL) {
781			/*
782			 * NB: the hardware should re-read the link when
783			 *     RXE bit is written, but it doesn't work at
784			 *     least on older hardware revs.
785			 */
786			sc->sc_stats.ast_rxeol++;
787			sc->sc_rxlink = NULL;
788		}
789		if (status & HAL_INT_TXURN) {
790			sc->sc_stats.ast_txurn++;
791			/* bump tx trigger level */
792			ath_hal_updatetxtriglevel(ah, AH_TRUE);
793		}
794		if (status & HAL_INT_RX)
795			taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
796		if (status & HAL_INT_TX)
797			taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
798		if (status & HAL_INT_BMISS) {
799			sc->sc_stats.ast_bmiss++;
800			taskqueue_enqueue(sc->sc_tq, &sc->sc_bmisstask);
801		}
802		if (status & HAL_INT_MIB) {
803			sc->sc_stats.ast_mib++;
804			/*
805			 * Disable interrupts until we service the MIB
806			 * interrupt; otherwise it will continue to fire.
807			 */
808			ath_hal_intrset(ah, 0);
809			/*
810			 * Let the hal handle the event.  We assume it will
811			 * clear whatever condition caused the interrupt.
812			 */
813			ath_hal_mibevent(ah, &sc->sc_halstats);
814			ath_hal_intrset(ah, sc->sc_imask);
815		}
816	}
817}
818
819static void
820ath_fatal_proc(void *arg, int pending)
821{
822	struct ath_softc *sc = arg;
823	struct ifnet *ifp = sc->sc_ifp;
824	u_int32_t *state;
825	u_int32_t len;
826
827	if_printf(ifp, "hardware error; resetting\n");
828	/*
829	 * Fatal errors are unrecoverable.  Typically these
830	 * are caused by DMA errors.  Collect h/w state from
831	 * the hal so we can diagnose what's going on.
832	 */
833	if (ath_hal_getfatalstate(sc->sc_ah, &state, &len)) {
834		KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
835		if_printf(ifp, "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n",
836		    state[0], state[1] , state[2], state[3],
837		    state[4], state[5]);
838	}
839	ath_reset(ifp);
840}
841
842static void
843ath_rxorn_proc(void *arg, int pending)
844{
845	struct ath_softc *sc = arg;
846	struct ifnet *ifp = sc->sc_ifp;
847
848	if_printf(ifp, "rx FIFO overrun; resetting\n");
849	ath_reset(ifp);
850}
851
852static void
853ath_bmiss_proc(void *arg, int pending)
854{
855	struct ath_softc *sc = arg;
856	struct ieee80211com *ic = &sc->sc_ic;
857
858	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
859	KASSERT(ic->ic_opmode == IEEE80211_M_STA,
860		("unexpect operating mode %u", ic->ic_opmode));
861	if (ic->ic_state == IEEE80211_S_RUN) {
862		u_int64_t lastrx = sc->sc_lastrx;
863		u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
864		u_int bmisstimeout =
865			ic->ic_bmissthreshold * ic->ic_bss->ni_intval * 1024;
866
867		DPRINTF(sc, ATH_DEBUG_BEACON,
868		    "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
869		    __func__, (unsigned long long) tsf,
870		    (unsigned long long)(tsf - lastrx),
871		    (unsigned long long) lastrx, bmisstimeout);
872		/*
873		 * Workaround phantom bmiss interrupts by sanity-checking
874		 * the time of our last rx'd frame.  If it is within the
875		 * beacon miss interval then ignore the interrupt.  If it's
876		 * truly a bmiss we'll get another interrupt soon and that'll
877		 * be dispatched up for processing.
878		 */
879		if (tsf - lastrx > bmisstimeout) {
880			NET_LOCK_GIANT();
881			ieee80211_beacon_miss(ic);
882			NET_UNLOCK_GIANT();
883		} else
884			sc->sc_stats.ast_bmiss_phantom++;
885	}
886}
887
888static u_int
889ath_chan2flags(struct ieee80211com *ic, struct ieee80211_channel *chan)
890{
891#define	N(a)	(sizeof(a) / sizeof(a[0]))
892	static const u_int modeflags[] = {
893		0,			/* IEEE80211_MODE_AUTO */
894		CHANNEL_A,		/* IEEE80211_MODE_11A */
895		CHANNEL_B,		/* IEEE80211_MODE_11B */
896		CHANNEL_PUREG,		/* IEEE80211_MODE_11G */
897		0,			/* IEEE80211_MODE_FH */
898		CHANNEL_ST,		/* IEEE80211_MODE_TURBO_A */
899		CHANNEL_108G		/* IEEE80211_MODE_TURBO_G */
900	};
901	enum ieee80211_phymode mode = ieee80211_chan2mode(ic, chan);
902
903	KASSERT(mode < N(modeflags), ("unexpected phy mode %u", mode));
904	KASSERT(modeflags[mode] != 0, ("mode %u undefined", mode));
905	if (IEEE80211_IS_CHAN_HALF(chan))
906		return modeflags[mode] | CHANNEL_HALF;
907	if (IEEE80211_IS_CHAN_QUARTER(chan))
908		return modeflags[mode] | CHANNEL_QUARTER;
909	return modeflags[mode];
910#undef N
911}
912
913static void
914ath_init(void *arg)
915{
916	struct ath_softc *sc = (struct ath_softc *) arg;
917	struct ieee80211com *ic = &sc->sc_ic;
918	struct ifnet *ifp = sc->sc_ifp;
919	struct ath_hal *ah = sc->sc_ah;
920	HAL_STATUS status;
921
922	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
923		__func__, ifp->if_flags);
924
925	ATH_LOCK(sc);
926	/*
927	 * Stop anything previously setup.  This is safe
928	 * whether this is the first time through or not.
929	 */
930	ath_stop_locked(ifp);
931
932	/*
933	 * The basic interface to setting the hardware in a good
934	 * state is ``reset''.  On return the hardware is known to
935	 * be powered up and with interrupts disabled.  This must
936	 * be followed by initialization of the appropriate bits
937	 * and then setup of the interrupt mask.
938	 */
939	sc->sc_curchan.channel = ic->ic_curchan->ic_freq;
940	sc->sc_curchan.channelFlags = ath_chan2flags(ic, ic->ic_curchan);
941	if (!ath_hal_reset(ah, sc->sc_opmode, &sc->sc_curchan, AH_FALSE, &status)) {
942		if_printf(ifp, "unable to reset hardware; hal status %u\n",
943			status);
944		goto done;
945	}
946
947	/*
948	 * This is needed only to setup initial state
949	 * but it's best done after a reset.
950	 */
951	ath_update_txpow(sc);
952	/*
953	 * Likewise this is set during reset so update
954	 * state cached in the driver.
955	 */
956	sc->sc_diversity = ath_hal_getdiversity(ah);
957	sc->sc_calinterval = 1;
958	sc->sc_caltries = 0;
959
960	/*
961	 * Setup the hardware after reset: the key cache
962	 * is filled as needed and the receive engine is
963	 * set going.  Frame transmit is handled entirely
964	 * in the frame output path; there's nothing to do
965	 * here except setup the interrupt mask.
966	 */
967	if (ath_startrecv(sc) != 0) {
968		if_printf(ifp, "unable to start recv logic\n");
969		goto done;
970	}
971
972	/*
973	 * Enable interrupts.
974	 */
975	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
976		  | HAL_INT_RXEOL | HAL_INT_RXORN
977		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
978	/*
979	 * Enable MIB interrupts when there are hardware phy counters.
980	 * Note we only do this (at the moment) for station mode.
981	 */
982	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
983		sc->sc_imask |= HAL_INT_MIB;
984	ath_hal_intrset(ah, sc->sc_imask);
985
986	ifp->if_drv_flags |= IFF_DRV_RUNNING;
987	ic->ic_state = IEEE80211_S_INIT;
988
989	/*
990	 * The hardware should be ready to go now so it's safe
991	 * to kick the 802.11 state machine as it's likely to
992	 * immediately call back to us to send mgmt frames.
993	 */
994	ath_chan_change(sc, ic->ic_curchan);
995#ifdef ATH_TX99_DIAG
996	if (sc->sc_tx99 != NULL)
997		sc->sc_tx99->start(sc->sc_tx99);
998	else
999#endif
1000	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
1001		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
1002			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
1003	} else
1004		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
1005done:
1006	ATH_UNLOCK(sc);
1007}
1008
1009static void
1010ath_stop_locked(struct ifnet *ifp)
1011{
1012	struct ath_softc *sc = ifp->if_softc;
1013	struct ieee80211com *ic = &sc->sc_ic;
1014	struct ath_hal *ah = sc->sc_ah;
1015
1016	DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1017		__func__, sc->sc_invalid, ifp->if_flags);
1018
1019	ATH_LOCK_ASSERT(sc);
1020	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1021		/*
1022		 * Shutdown the hardware and driver:
1023		 *    reset 802.11 state machine
1024		 *    turn off timers
1025		 *    disable interrupts
1026		 *    turn off the radio
1027		 *    clear transmit machinery
1028		 *    clear receive machinery
1029		 *    drain and release tx queues
1030		 *    reclaim beacon resources
1031		 *    power down hardware
1032		 *
1033		 * Note that some of this work is not possible if the
1034		 * hardware is gone (invalid).
1035		 */
1036#ifdef ATH_TX99_DIAG
1037		if (sc->sc_tx99 != NULL)
1038			sc->sc_tx99->stop(sc->sc_tx99);
1039#endif
1040		ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
1041		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
1042		ifp->if_timer = 0;
1043		if (!sc->sc_invalid) {
1044			if (sc->sc_softled) {
1045				callout_stop(&sc->sc_ledtimer);
1046				ath_hal_gpioset(ah, sc->sc_ledpin,
1047					!sc->sc_ledon);
1048				sc->sc_blinking = 0;
1049			}
1050			ath_hal_intrset(ah, 0);
1051		}
1052		ath_draintxq(sc);
1053		if (!sc->sc_invalid) {
1054			ath_stoprecv(sc);
1055			ath_hal_phydisable(ah);
1056		} else
1057			sc->sc_rxlink = NULL;
1058		IFQ_DRV_PURGE(&ifp->if_snd);
1059		ath_beacon_free(sc);
1060	}
1061}
1062
1063static void
1064ath_stop(struct ifnet *ifp)
1065{
1066	struct ath_softc *sc = ifp->if_softc;
1067
1068	ATH_LOCK(sc);
1069	ath_stop_locked(ifp);
1070	if (!sc->sc_invalid) {
1071		/*
1072		 * Set the chip in full sleep mode.  Note that we are
1073		 * careful to do this only when bringing the interface
1074		 * completely to a stop.  When the chip is in this state
1075		 * it must be carefully woken up or references to
1076		 * registers in the PCI clock domain may freeze the bus
1077		 * (and system).  This varies by chip and is mostly an
1078		 * issue with newer parts that go to sleep more quickly.
1079		 */
1080		ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
1081	}
1082	ATH_UNLOCK(sc);
1083}
1084
1085/*
1086 * Reset the hardware w/o losing operational state.  This is
1087 * basically a more efficient way of doing ath_stop, ath_init,
1088 * followed by state transitions to the current 802.11
1089 * operational state.  Used to recover from various errors and
1090 * to reset or reload hardware state.
1091 */
1092static int
1093ath_reset(struct ifnet *ifp)
1094{
1095	struct ath_softc *sc = ifp->if_softc;
1096	struct ieee80211com *ic = &sc->sc_ic;
1097	struct ath_hal *ah = sc->sc_ah;
1098	struct ieee80211_channel *c;
1099	HAL_STATUS status;
1100
1101	/*
1102	 * Convert to a HAL channel description with the flags
1103	 * constrained to reflect the current operating mode.
1104	 */
1105	c = ic->ic_curchan;
1106	sc->sc_curchan.channel = c->ic_freq;
1107	sc->sc_curchan.channelFlags = ath_chan2flags(ic, c);
1108
1109	ath_hal_intrset(ah, 0);		/* disable interrupts */
1110	ath_draintxq(sc);		/* stop xmit side */
1111	ath_stoprecv(sc);		/* stop recv side */
1112	/* NB: indicate channel change so we do a full reset */
1113	if (!ath_hal_reset(ah, sc->sc_opmode, &sc->sc_curchan, AH_TRUE, &status))
1114		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
1115			__func__, status);
1116	ath_update_txpow(sc);		/* update tx power state */
1117	sc->sc_diversity = ath_hal_getdiversity(ah);
1118	sc->sc_calinterval = 1;
1119	sc->sc_caltries = 0;
1120	/*
1121	 * We may be doing a reset in response to an ioctl
1122	 * that changes the channel so update any state that
1123	 * might change as a result.
1124	 */
1125	ath_chan_change(sc, c);
1126	if (ath_startrecv(sc) != 0)	/* restart recv */
1127		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
1128	if (ic->ic_state == IEEE80211_S_RUN)
1129		ath_beacon_config(sc);	/* restart beacons */
1130	ath_hal_intrset(ah, sc->sc_imask);
1131
1132	ath_start(ifp);			/* restart xmit */
1133	return 0;
1134}
1135
1136static void
1137ath_start(struct ifnet *ifp)
1138{
1139	struct ath_softc *sc = ifp->if_softc;
1140	struct ath_hal *ah = sc->sc_ah;
1141	struct ieee80211com *ic = &sc->sc_ic;
1142	struct ieee80211_node *ni;
1143	struct ath_buf *bf;
1144	struct mbuf *m;
1145	struct ieee80211_frame *wh;
1146	struct ether_header *eh;
1147
1148	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
1149		return;
1150	for (;;) {
1151		/*
1152		 * Grab a TX buffer and associated resources.
1153		 */
1154		ATH_TXBUF_LOCK(sc);
1155		bf = STAILQ_FIRST(&sc->sc_txbuf);
1156		if (bf != NULL)
1157			STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
1158		ATH_TXBUF_UNLOCK(sc);
1159		if (bf == NULL) {
1160			DPRINTF(sc, ATH_DEBUG_XMIT, "%s: out of xmit buffers\n",
1161				__func__);
1162			sc->sc_stats.ast_tx_qstop++;
1163			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1164			break;
1165		}
1166		/*
1167		 * Poll the management queue for frames; they
1168		 * have priority over normal data frames.
1169		 */
1170		IF_DEQUEUE(&ic->ic_mgtq, m);
1171		if (m == NULL) {
1172			/*
1173			 * No data frames go out unless we're associated.
1174			 */
1175			if (ic->ic_state != IEEE80211_S_RUN) {
1176				DPRINTF(sc, ATH_DEBUG_XMIT,
1177				    "%s: discard data packet, state %s\n",
1178				    __func__,
1179				    ieee80211_state_name[ic->ic_state]);
1180				sc->sc_stats.ast_tx_discard++;
1181				ATH_TXBUF_LOCK(sc);
1182				STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1183				ATH_TXBUF_UNLOCK(sc);
1184				break;
1185			}
1186			IFQ_DRV_DEQUEUE(&ifp->if_snd, m);	/* XXX: LOCK */
1187			if (m == NULL) {
1188				ATH_TXBUF_LOCK(sc);
1189				STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1190				ATH_TXBUF_UNLOCK(sc);
1191				break;
1192			}
1193			/*
1194			 * Find the node for the destination so we can do
1195			 * things like power save and fast frames aggregation.
1196			 */
1197			if (m->m_len < sizeof(struct ether_header) &&
1198			   (m = m_pullup(m, sizeof(struct ether_header))) == NULL) {
1199				ic->ic_stats.is_tx_nobuf++;	/* XXX */
1200				ni = NULL;
1201				goto bad;
1202			}
1203			eh = mtod(m, struct ether_header *);
1204			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1205			if (ni == NULL) {
1206				/* NB: ieee80211_find_txnode does stat+msg */
1207				m_freem(m);
1208				goto bad;
1209			}
1210			if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
1211			    (m->m_flags & M_PWR_SAV) == 0) {
1212				/*
1213				 * Station in power save mode; pass the frame
1214				 * to the 802.11 layer and continue.  We'll get
1215				 * the frame back when the time is right.
1216				 */
1217				ieee80211_pwrsave(ic, ni, m);
1218				goto reclaim;
1219			}
1220			/* calculate priority so we can find the tx queue */
1221			if (ieee80211_classify(ic, m, ni)) {
1222				DPRINTF(sc, ATH_DEBUG_XMIT,
1223					"%s: discard, classification failure\n",
1224					__func__);
1225				m_freem(m);
1226				goto bad;
1227			}
1228			ifp->if_opackets++;
1229			BPF_MTAP(ifp, m);
1230			/*
1231			 * Encapsulate the packet in prep for transmission.
1232			 */
1233			m = ieee80211_encap(ic, m, ni);
1234			if (m == NULL) {
1235				DPRINTF(sc, ATH_DEBUG_XMIT,
1236					"%s: encapsulation failure\n",
1237					__func__);
1238				sc->sc_stats.ast_tx_encap++;
1239				goto bad;
1240			}
1241		} else {
1242			/*
1243			 * Hack!  The referenced node pointer is in the
1244			 * rcvif field of the packet header.  This is
1245			 * placed there by ieee80211_mgmt_output because
1246			 * we need to hold the reference with the frame
1247			 * and there's no other way (other than packet
1248			 * tags which we consider too expensive to use)
1249			 * to pass it along.
1250			 */
1251			ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1252			m->m_pkthdr.rcvif = NULL;
1253
1254			wh = mtod(m, struct ieee80211_frame *);
1255			if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1256			    IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
1257				/* fill time stamp */
1258				u_int64_t tsf;
1259				u_int32_t *tstamp;
1260
1261				tsf = ath_hal_gettsf64(ah);
1262				/* XXX: adjust 100us delay to xmit */
1263				tsf += 100;
1264				tstamp = (u_int32_t *)&wh[1];
1265				tstamp[0] = htole32(tsf & 0xffffffff);
1266				tstamp[1] = htole32(tsf >> 32);
1267			}
1268			sc->sc_stats.ast_tx_mgmt++;
1269		}
1270
1271		if (ath_tx_start(sc, ni, bf, m)) {
1272	bad:
1273			ifp->if_oerrors++;
1274	reclaim:
1275			ATH_TXBUF_LOCK(sc);
1276			STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1277			ATH_TXBUF_UNLOCK(sc);
1278			if (ni != NULL)
1279				ieee80211_free_node(ni);
1280			continue;
1281		}
1282
1283		sc->sc_tx_timer = 5;
1284		ifp->if_timer = 1;
1285	}
1286}
1287
1288static int
1289ath_media_change(struct ifnet *ifp)
1290{
1291#define	IS_UP(ifp) \
1292	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
1293	int error;
1294
1295	error = ieee80211_media_change(ifp);
1296	if (error == ENETRESET) {
1297		struct ath_softc *sc = ifp->if_softc;
1298		struct ieee80211com *ic = &sc->sc_ic;
1299
1300		if (ic->ic_opmode == IEEE80211_M_AHDEMO) {
1301			/*
1302			 * Adhoc demo mode is just ibss mode w/o beacons
1303			 * (mostly).  The hal knows nothing about it;
1304			 * tell it we're operating in ibss mode.
1305			 */
1306			sc->sc_opmode = HAL_M_IBSS;
1307		} else
1308			sc->sc_opmode = ic->ic_opmode;
1309		if (IS_UP(ifp))
1310			ath_init(ifp->if_softc);	/* XXX lose error */
1311		error = 0;
1312	}
1313	return error;
1314#undef IS_UP
1315}
1316
1317#ifdef ATH_DEBUG
1318static void
1319ath_keyprint(struct ath_softc *sc, const char *tag, u_int ix,
1320	const HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1321{
1322	static const char *ciphers[] = {
1323		"WEP",
1324		"AES-OCB",
1325		"AES-CCM",
1326		"CKIP",
1327		"TKIP",
1328		"CLR",
1329	};
1330	int i, n;
1331
1332	printf("%s: [%02u] %-7s ", tag, ix, ciphers[hk->kv_type]);
1333	for (i = 0, n = hk->kv_len; i < n; i++)
1334		printf("%02x", hk->kv_val[i]);
1335	printf(" mac %s", ether_sprintf(mac));
1336	if (hk->kv_type == HAL_CIPHER_TKIP) {
1337		printf(" %s ", sc->sc_splitmic ? "mic" : "rxmic");
1338		for (i = 0; i < sizeof(hk->kv_mic); i++)
1339			printf("%02x", hk->kv_mic[i]);
1340#if HAL_ABI_VERSION > 0x06052200
1341		if (!sc->sc_splitmic) {
1342			printf(" txmic ");
1343			for (i = 0; i < sizeof(hk->kv_txmic); i++)
1344				printf("%02x", hk->kv_txmic[i]);
1345		}
1346#endif
1347	}
1348	printf("\n");
1349}
1350#endif
1351
1352/*
1353 * Set a TKIP key into the hardware.  This handles the
1354 * potential distribution of key state to multiple key
1355 * cache slots for TKIP.
1356 */
1357static int
1358ath_keyset_tkip(struct ath_softc *sc, const struct ieee80211_key *k,
1359	HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1360{
1361#define	IEEE80211_KEY_XR	(IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV)
1362	static const u_int8_t zerobssid[IEEE80211_ADDR_LEN];
1363	struct ath_hal *ah = sc->sc_ah;
1364
1365	KASSERT(k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP,
1366		("got a non-TKIP key, cipher %u", k->wk_cipher->ic_cipher));
1367	if ((k->wk_flags & IEEE80211_KEY_XR) == IEEE80211_KEY_XR) {
1368		if (sc->sc_splitmic) {
1369			/*
1370			 * TX key goes at first index, RX key at the rx index.
1371			 * The hal handles the MIC keys at index+64.
1372			 */
1373			memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_mic));
1374			KEYPRINTF(sc, k->wk_keyix, hk, zerobssid);
1375			if (!ath_hal_keyset(ah, k->wk_keyix, hk, zerobssid))
1376				return 0;
1377
1378			memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1379			KEYPRINTF(sc, k->wk_keyix+32, hk, mac);
1380			/* XXX delete tx key on failure? */
1381			return ath_hal_keyset(ah, k->wk_keyix+32, hk, mac);
1382		} else {
1383			/*
1384			 * Room for both TX+RX MIC keys in one key cache
1385			 * slot, just set key at the first index; the hal
1386			 * will handle the reset.
1387			 */
1388			memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1389#if HAL_ABI_VERSION > 0x06052200
1390			memcpy(hk->kv_txmic, k->wk_txmic, sizeof(hk->kv_txmic));
1391#endif
1392			KEYPRINTF(sc, k->wk_keyix, hk, mac);
1393			return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1394		}
1395	} else if (k->wk_flags & IEEE80211_KEY_XR) {
1396		/*
1397		 * TX/RX key goes at first index.
1398		 * The hal handles the MIC keys are index+64.
1399		 */
1400		memcpy(hk->kv_mic, k->wk_flags & IEEE80211_KEY_XMIT ?
1401			k->wk_txmic : k->wk_rxmic, sizeof(hk->kv_mic));
1402		KEYPRINTF(sc, k->wk_keyix, hk, mac);
1403		return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1404	}
1405	return 0;
1406#undef IEEE80211_KEY_XR
1407}
1408
1409/*
1410 * Set a net80211 key into the hardware.  This handles the
1411 * potential distribution of key state to multiple key
1412 * cache slots for TKIP with hardware MIC support.
1413 */
1414static int
1415ath_keyset(struct ath_softc *sc, const struct ieee80211_key *k,
1416	const u_int8_t mac0[IEEE80211_ADDR_LEN],
1417	struct ieee80211_node *bss)
1418{
1419#define	N(a)	(sizeof(a)/sizeof(a[0]))
1420	static const u_int8_t ciphermap[] = {
1421		HAL_CIPHER_WEP,		/* IEEE80211_CIPHER_WEP */
1422		HAL_CIPHER_TKIP,	/* IEEE80211_CIPHER_TKIP */
1423		HAL_CIPHER_AES_OCB,	/* IEEE80211_CIPHER_AES_OCB */
1424		HAL_CIPHER_AES_CCM,	/* IEEE80211_CIPHER_AES_CCM */
1425		(u_int8_t) -1,		/* 4 is not allocated */
1426		HAL_CIPHER_CKIP,	/* IEEE80211_CIPHER_CKIP */
1427		HAL_CIPHER_CLR,		/* IEEE80211_CIPHER_NONE */
1428	};
1429	struct ath_hal *ah = sc->sc_ah;
1430	const struct ieee80211_cipher *cip = k->wk_cipher;
1431	u_int8_t gmac[IEEE80211_ADDR_LEN];
1432	const u_int8_t *mac;
1433	HAL_KEYVAL hk;
1434
1435	memset(&hk, 0, sizeof(hk));
1436	/*
1437	 * Software crypto uses a "clear key" so non-crypto
1438	 * state kept in the key cache are maintained and
1439	 * so that rx frames have an entry to match.
1440	 */
1441	if ((k->wk_flags & IEEE80211_KEY_SWCRYPT) == 0) {
1442		KASSERT(cip->ic_cipher < N(ciphermap),
1443			("invalid cipher type %u", cip->ic_cipher));
1444		hk.kv_type = ciphermap[cip->ic_cipher];
1445		hk.kv_len = k->wk_keylen;
1446		memcpy(hk.kv_val, k->wk_key, k->wk_keylen);
1447	} else
1448		hk.kv_type = HAL_CIPHER_CLR;
1449
1450	if ((k->wk_flags & IEEE80211_KEY_GROUP) && sc->sc_mcastkey) {
1451		/*
1452		 * Group keys on hardware that supports multicast frame
1453		 * key search use a mac that is the sender's address with
1454		 * the high bit set instead of the app-specified address.
1455		 */
1456		IEEE80211_ADDR_COPY(gmac, bss->ni_macaddr);
1457		gmac[0] |= 0x80;
1458		mac = gmac;
1459	} else
1460		mac = mac0;
1461
1462	if (hk.kv_type == HAL_CIPHER_TKIP &&
1463	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
1464		return ath_keyset_tkip(sc, k, &hk, mac);
1465	} else {
1466		KEYPRINTF(sc, k->wk_keyix, &hk, mac);
1467		return ath_hal_keyset(ah, k->wk_keyix, &hk, mac);
1468	}
1469#undef N
1470}
1471
1472/*
1473 * Allocate tx/rx key slots for TKIP.  We allocate two slots for
1474 * each key, one for decrypt/encrypt and the other for the MIC.
1475 */
1476static u_int16_t
1477key_alloc_2pair(struct ath_softc *sc,
1478	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
1479{
1480#define	N(a)	(sizeof(a)/sizeof(a[0]))
1481	u_int i, keyix;
1482
1483	KASSERT(sc->sc_splitmic, ("key cache !split"));
1484	/* XXX could optimize */
1485	for (i = 0; i < N(sc->sc_keymap)/4; i++) {
1486		u_int8_t b = sc->sc_keymap[i];
1487		if (b != 0xff) {
1488			/*
1489			 * One or more slots in this byte are free.
1490			 */
1491			keyix = i*NBBY;
1492			while (b & 1) {
1493		again:
1494				keyix++;
1495				b >>= 1;
1496			}
1497			/* XXX IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV */
1498			if (isset(sc->sc_keymap, keyix+32) ||
1499			    isset(sc->sc_keymap, keyix+64) ||
1500			    isset(sc->sc_keymap, keyix+32+64)) {
1501				/* full pair unavailable */
1502				/* XXX statistic */
1503				if (keyix == (i+1)*NBBY) {
1504					/* no slots were appropriate, advance */
1505					continue;
1506				}
1507				goto again;
1508			}
1509			setbit(sc->sc_keymap, keyix);
1510			setbit(sc->sc_keymap, keyix+64);
1511			setbit(sc->sc_keymap, keyix+32);
1512			setbit(sc->sc_keymap, keyix+32+64);
1513			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
1514				"%s: key pair %u,%u %u,%u\n",
1515				__func__, keyix, keyix+64,
1516				keyix+32, keyix+32+64);
1517			*txkeyix = keyix;
1518			*rxkeyix = keyix+32;
1519			return 1;
1520		}
1521	}
1522	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
1523	return 0;
1524#undef N
1525}
1526
1527/*
1528 * Allocate tx/rx key slots for TKIP.  We allocate two slots for
1529 * each key, one for decrypt/encrypt and the other for the MIC.
1530 */
1531static u_int16_t
1532key_alloc_pair(struct ath_softc *sc,
1533	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
1534{
1535#define	N(a)	(sizeof(a)/sizeof(a[0]))
1536	u_int i, keyix;
1537
1538	KASSERT(!sc->sc_splitmic, ("key cache split"));
1539	/* XXX could optimize */
1540	for (i = 0; i < N(sc->sc_keymap)/4; i++) {
1541		u_int8_t b = sc->sc_keymap[i];
1542		if (b != 0xff) {
1543			/*
1544			 * One or more slots in this byte are free.
1545			 */
1546			keyix = i*NBBY;
1547			while (b & 1) {
1548		again:
1549				keyix++;
1550				b >>= 1;
1551			}
1552			if (isset(sc->sc_keymap, keyix+64)) {
1553				/* full pair unavailable */
1554				/* XXX statistic */
1555				if (keyix == (i+1)*NBBY) {
1556					/* no slots were appropriate, advance */
1557					continue;
1558				}
1559				goto again;
1560			}
1561			setbit(sc->sc_keymap, keyix);
1562			setbit(sc->sc_keymap, keyix+64);
1563			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
1564				"%s: key pair %u,%u\n",
1565				__func__, keyix, keyix+64);
1566			*txkeyix = *rxkeyix = keyix;
1567			return 1;
1568		}
1569	}
1570	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
1571	return 0;
1572#undef N
1573}
1574
1575/*
1576 * Allocate a single key cache slot.
1577 */
1578static int
1579key_alloc_single(struct ath_softc *sc,
1580	ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
1581{
1582#define	N(a)	(sizeof(a)/sizeof(a[0]))
1583	u_int i, keyix;
1584
1585	/* XXX try i,i+32,i+64,i+32+64 to minimize key pair conflicts */
1586	for (i = 0; i < N(sc->sc_keymap); i++) {
1587		u_int8_t b = sc->sc_keymap[i];
1588		if (b != 0xff) {
1589			/*
1590			 * One or more slots are free.
1591			 */
1592			keyix = i*NBBY;
1593			while (b & 1)
1594				keyix++, b >>= 1;
1595			setbit(sc->sc_keymap, keyix);
1596			DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: key %u\n",
1597				__func__, keyix);
1598			*txkeyix = *rxkeyix = keyix;
1599			return 1;
1600		}
1601	}
1602	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of space\n", __func__);
1603	return 0;
1604#undef N
1605}
1606
1607/*
1608 * Allocate one or more key cache slots for a uniacst key.  The
1609 * key itself is needed only to identify the cipher.  For hardware
1610 * TKIP with split cipher+MIC keys we allocate two key cache slot
1611 * pairs so that we can setup separate TX and RX MIC keys.  Note
1612 * that the MIC key for a TKIP key at slot i is assumed by the
1613 * hardware to be at slot i+64.  This limits TKIP keys to the first
1614 * 64 entries.
1615 */
1616static int
1617ath_key_alloc(struct ieee80211com *ic, const struct ieee80211_key *k,
1618	ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
1619{
1620	struct ath_softc *sc = ic->ic_ifp->if_softc;
1621
1622	/*
1623	 * Group key allocation must be handled specially for
1624	 * parts that do not support multicast key cache search
1625	 * functionality.  For those parts the key id must match
1626	 * the h/w key index so lookups find the right key.  On
1627	 * parts w/ the key search facility we install the sender's
1628	 * mac address (with the high bit set) and let the hardware
1629	 * find the key w/o using the key id.  This is preferred as
1630	 * it permits us to support multiple users for adhoc and/or
1631	 * multi-station operation.
1632	 */
1633	if ((k->wk_flags & IEEE80211_KEY_GROUP) && !sc->sc_mcastkey) {
1634		if (!(&ic->ic_nw_keys[0] <= k &&
1635		      k < &ic->ic_nw_keys[IEEE80211_WEP_NKID])) {
1636			/* should not happen */
1637			DPRINTF(sc, ATH_DEBUG_KEYCACHE,
1638				"%s: bogus group key\n", __func__);
1639			return 0;
1640		}
1641		/*
1642		 * XXX we pre-allocate the global keys so
1643		 * have no way to check if they've already been allocated.
1644		 */
1645		*keyix = *rxkeyix = k - ic->ic_nw_keys;
1646		return 1;
1647	}
1648
1649	/*
1650	 * We allocate two pair for TKIP when using the h/w to do
1651	 * the MIC.  For everything else, including software crypto,
1652	 * we allocate a single entry.  Note that s/w crypto requires
1653	 * a pass-through slot on the 5211 and 5212.  The 5210 does
1654	 * not support pass-through cache entries and we map all
1655	 * those requests to slot 0.
1656	 */
1657	if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
1658		return key_alloc_single(sc, keyix, rxkeyix);
1659	} else if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP &&
1660	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
1661		if (sc->sc_splitmic)
1662			return key_alloc_2pair(sc, keyix, rxkeyix);
1663		else
1664			return key_alloc_pair(sc, keyix, rxkeyix);
1665	} else {
1666		return key_alloc_single(sc, keyix, rxkeyix);
1667	}
1668}
1669
1670/*
1671 * Delete an entry in the key cache allocated by ath_key_alloc.
1672 */
1673static int
1674ath_key_delete(struct ieee80211com *ic, const struct ieee80211_key *k)
1675{
1676	struct ath_softc *sc = ic->ic_ifp->if_softc;
1677	struct ath_hal *ah = sc->sc_ah;
1678	const struct ieee80211_cipher *cip = k->wk_cipher;
1679	u_int keyix = k->wk_keyix;
1680
1681	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: delete key %u\n", __func__, keyix);
1682
1683	ath_hal_keyreset(ah, keyix);
1684	/*
1685	 * Handle split tx/rx keying required for TKIP with h/w MIC.
1686	 */
1687	if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
1688	    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic)
1689		ath_hal_keyreset(ah, keyix+32);		/* RX key */
1690	if (keyix >= IEEE80211_WEP_NKID) {
1691		/*
1692		 * Don't touch keymap entries for global keys so
1693		 * they are never considered for dynamic allocation.
1694		 */
1695		clrbit(sc->sc_keymap, keyix);
1696		if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
1697		    (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
1698			clrbit(sc->sc_keymap, keyix+64);	/* TX key MIC */
1699			if (sc->sc_splitmic) {
1700				/* +32 for RX key, +32+64 for RX key MIC */
1701				clrbit(sc->sc_keymap, keyix+32);
1702				clrbit(sc->sc_keymap, keyix+32+64);
1703			}
1704		}
1705	}
1706	return 1;
1707}
1708
1709/*
1710 * Set the key cache contents for the specified key.  Key cache
1711 * slot(s) must already have been allocated by ath_key_alloc.
1712 */
1713static int
1714ath_key_set(struct ieee80211com *ic, const struct ieee80211_key *k,
1715	const u_int8_t mac[IEEE80211_ADDR_LEN])
1716{
1717	struct ath_softc *sc = ic->ic_ifp->if_softc;
1718
1719	return ath_keyset(sc, k, mac, ic->ic_bss);
1720}
1721
1722/*
1723 * Block/unblock tx+rx processing while a key change is done.
1724 * We assume the caller serializes key management operations
1725 * so we only need to worry about synchronization with other
1726 * uses that originate in the driver.
1727 */
1728static void
1729ath_key_update_begin(struct ieee80211com *ic)
1730{
1731	struct ifnet *ifp = ic->ic_ifp;
1732	struct ath_softc *sc = ifp->if_softc;
1733
1734	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
1735#if 0
1736	tasklet_disable(&sc->sc_rxtq);
1737#endif
1738	IF_LOCK(&ifp->if_snd);		/* NB: doesn't block mgmt frames */
1739}
1740
1741static void
1742ath_key_update_end(struct ieee80211com *ic)
1743{
1744	struct ifnet *ifp = ic->ic_ifp;
1745	struct ath_softc *sc = ifp->if_softc;
1746
1747	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
1748	IF_UNLOCK(&ifp->if_snd);
1749#if 0
1750	tasklet_enable(&sc->sc_rxtq);
1751#endif
1752}
1753
1754/*
1755 * Calculate the receive filter according to the
1756 * operating mode and state:
1757 *
1758 * o always accept unicast, broadcast, and multicast traffic
1759 * o maintain current state of phy error reception (the hal
1760 *   may enable phy error frames for noise immunity work)
1761 * o probe request frames are accepted only when operating in
1762 *   hostap, adhoc, or monitor modes
1763 * o enable promiscuous mode according to the interface state
1764 * o accept beacons:
1765 *   - when operating in adhoc mode so the 802.11 layer creates
1766 *     node table entries for peers,
1767 *   - when operating in station mode for collecting rssi data when
1768 *     the station is otherwise quiet, or
1769 *   - when scanning
1770 * o accept control frames:
1771 *   - when in monitor mode
1772 */
1773static u_int32_t
1774ath_calcrxfilter(struct ath_softc *sc, enum ieee80211_state state)
1775{
1776#define	RX_FILTER_PRESERVE	(HAL_RX_FILTER_PHYERR | HAL_RX_FILTER_PHYRADAR)
1777	struct ieee80211com *ic = &sc->sc_ic;
1778	struct ath_hal *ah = sc->sc_ah;
1779	struct ifnet *ifp = sc->sc_ifp;
1780	u_int32_t rfilt;
1781
1782	rfilt = (ath_hal_getrxfilter(ah) & RX_FILTER_PRESERVE)
1783	      | HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
1784	if (ic->ic_opmode != IEEE80211_M_STA)
1785		rfilt |= HAL_RX_FILTER_PROBEREQ;
1786	if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
1787	    (ifp->if_flags & IFF_PROMISC))
1788		rfilt |= HAL_RX_FILTER_PROM;
1789	if (ic->ic_opmode == IEEE80211_M_STA ||
1790	    ic->ic_opmode == IEEE80211_M_IBSS ||
1791	    state == IEEE80211_S_SCAN)
1792		rfilt |= HAL_RX_FILTER_BEACON;
1793	if (ic->ic_opmode == IEEE80211_M_MONITOR)
1794		rfilt |= HAL_RX_FILTER_CONTROL;
1795	return rfilt;
1796#undef RX_FILTER_PRESERVE
1797}
1798
1799static void
1800ath_mode_init(struct ath_softc *sc)
1801{
1802	struct ieee80211com *ic = &sc->sc_ic;
1803	struct ath_hal *ah = sc->sc_ah;
1804	struct ifnet *ifp = sc->sc_ifp;
1805	u_int32_t rfilt, mfilt[2], val;
1806	u_int8_t pos;
1807	struct ifmultiaddr *ifma;
1808
1809	/* configure rx filter */
1810	rfilt = ath_calcrxfilter(sc, ic->ic_state);
1811	ath_hal_setrxfilter(ah, rfilt);
1812
1813	/* configure operational mode */
1814	ath_hal_setopmode(ah);
1815
1816	/*
1817	 * Handle any link-level address change.  Note that we only
1818	 * need to force ic_myaddr; any other addresses are handled
1819	 * as a byproduct of the ifnet code marking the interface
1820	 * down then up.
1821	 *
1822	 * XXX should get from lladdr instead of arpcom but that's more work
1823	 */
1824	IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
1825	ath_hal_setmac(ah, ic->ic_myaddr);
1826
1827	/* calculate and install multicast filter */
1828	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
1829		mfilt[0] = mfilt[1] = 0;
1830		IF_ADDR_LOCK(ifp);
1831		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1832			caddr_t dl;
1833
1834			/* calculate XOR of eight 6bit values */
1835			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
1836			val = LE_READ_4(dl + 0);
1837			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
1838			val = LE_READ_4(dl + 3);
1839			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
1840			pos &= 0x3f;
1841			mfilt[pos / 32] |= (1 << (pos % 32));
1842		}
1843		IF_ADDR_UNLOCK(ifp);
1844	} else {
1845		mfilt[0] = mfilt[1] = ~0;
1846	}
1847	ath_hal_setmcastfilter(ah, mfilt[0], mfilt[1]);
1848	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, MC filter %08x:%08x\n",
1849		__func__, rfilt, mfilt[0], mfilt[1]);
1850}
1851
1852/*
1853 * Set the slot time based on the current setting.
1854 */
1855static void
1856ath_setslottime(struct ath_softc *sc)
1857{
1858	struct ieee80211com *ic = &sc->sc_ic;
1859	struct ath_hal *ah = sc->sc_ah;
1860	u_int usec;
1861
1862	if (IEEE80211_IS_CHAN_A(ic->ic_curchan)) {
1863		if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
1864			usec = 13;
1865		else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
1866			usec = 21;
1867		else
1868			usec = HAL_SLOT_TIME_9;
1869	} else if (ic->ic_flags & IEEE80211_F_SHSLOT)
1870		usec = HAL_SLOT_TIME_9;
1871	else
1872		usec = HAL_SLOT_TIME_20;
1873
1874	DPRINTF(sc, ATH_DEBUG_RESET,
1875	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
1876	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
1877	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
1878
1879	ath_hal_setslottime(ah, usec);
1880	sc->sc_updateslot = OK;
1881}
1882
1883/*
1884 * Callback from the 802.11 layer to update the
1885 * slot time based on the current setting.
1886 */
1887static void
1888ath_updateslot(struct ifnet *ifp)
1889{
1890	struct ath_softc *sc = ifp->if_softc;
1891	struct ieee80211com *ic = &sc->sc_ic;
1892
1893	/*
1894	 * When not coordinating the BSS, change the hardware
1895	 * immediately.  For other operation we defer the change
1896	 * until beacon updates have propagated to the stations.
1897	 */
1898	if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1899		sc->sc_updateslot = UPDATE;
1900	else
1901		ath_setslottime(sc);
1902}
1903
1904/*
1905 * Setup a h/w transmit queue for beacons.
1906 */
1907static int
1908ath_beaconq_setup(struct ath_hal *ah)
1909{
1910	HAL_TXQ_INFO qi;
1911
1912	memset(&qi, 0, sizeof(qi));
1913	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
1914	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
1915	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
1916	/* NB: for dynamic turbo, don't enable any other interrupts */
1917	qi.tqi_qflags = HAL_TXQ_TXDESCINT_ENABLE;
1918	return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
1919}
1920
1921/*
1922 * Setup the transmit queue parameters for the beacon queue.
1923 */
1924static int
1925ath_beaconq_config(struct ath_softc *sc)
1926{
1927#define	ATH_EXPONENT_TO_VALUE(v)	((1<<(v))-1)
1928	struct ieee80211com *ic = &sc->sc_ic;
1929	struct ath_hal *ah = sc->sc_ah;
1930	HAL_TXQ_INFO qi;
1931
1932	ath_hal_gettxqueueprops(ah, sc->sc_bhalq, &qi);
1933	if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1934		/*
1935		 * Always burst out beacon and CAB traffic.
1936		 */
1937		qi.tqi_aifs = ATH_BEACON_AIFS_DEFAULT;
1938		qi.tqi_cwmin = ATH_BEACON_CWMIN_DEFAULT;
1939		qi.tqi_cwmax = ATH_BEACON_CWMAX_DEFAULT;
1940	} else {
1941		struct wmeParams *wmep =
1942			&ic->ic_wme.wme_chanParams.cap_wmeParams[WME_AC_BE];
1943		/*
1944		 * Adhoc mode; important thing is to use 2x cwmin.
1945		 */
1946		qi.tqi_aifs = wmep->wmep_aifsn;
1947		qi.tqi_cwmin = 2*ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
1948		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
1949	}
1950
1951	if (!ath_hal_settxqueueprops(ah, sc->sc_bhalq, &qi)) {
1952		device_printf(sc->sc_dev, "unable to update parameters for "
1953			"beacon hardware queue!\n");
1954		return 0;
1955	} else {
1956		ath_hal_resettxqueue(ah, sc->sc_bhalq); /* push to h/w */
1957		return 1;
1958	}
1959#undef ATH_EXPONENT_TO_VALUE
1960}
1961
1962/*
1963 * Allocate and setup an initial beacon frame.
1964 */
1965static int
1966ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
1967{
1968	struct ieee80211com *ic = ni->ni_ic;
1969	struct ath_buf *bf;
1970	struct mbuf *m;
1971	int error;
1972
1973	bf = STAILQ_FIRST(&sc->sc_bbuf);
1974	if (bf == NULL) {
1975		DPRINTF(sc, ATH_DEBUG_BEACON, "%s: no dma buffers\n", __func__);
1976		sc->sc_stats.ast_be_nombuf++;	/* XXX */
1977		return ENOMEM;			/* XXX */
1978	}
1979	/*
1980	 * NB: the beacon data buffer must be 32-bit aligned;
1981	 * we assume the mbuf routines will return us something
1982	 * with this alignment (perhaps should assert).
1983	 */
1984	m = ieee80211_beacon_alloc(ic, ni, &sc->sc_boff);
1985	if (m == NULL) {
1986		DPRINTF(sc, ATH_DEBUG_BEACON, "%s: cannot get mbuf\n",
1987			__func__);
1988		sc->sc_stats.ast_be_nombuf++;
1989		return ENOMEM;
1990	}
1991	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
1992				     bf->bf_segs, &bf->bf_nseg,
1993				     BUS_DMA_NOWAIT);
1994	if (error == 0) {
1995		bf->bf_m = m;
1996		bf->bf_node = ieee80211_ref_node(ni);
1997	} else {
1998		m_freem(m);
1999	}
2000	return error;
2001}
2002
2003/*
2004 * Setup the beacon frame for transmit.
2005 */
2006static void
2007ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
2008{
2009#define	USE_SHPREAMBLE(_ic) \
2010	(((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
2011		== IEEE80211_F_SHPREAMBLE)
2012	struct ieee80211_node *ni = bf->bf_node;
2013	struct ieee80211com *ic = ni->ni_ic;
2014	struct mbuf *m = bf->bf_m;
2015	struct ath_hal *ah = sc->sc_ah;
2016	struct ath_desc *ds;
2017	int flags, antenna;
2018	const HAL_RATE_TABLE *rt;
2019	u_int8_t rix, rate;
2020
2021	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: m %p len %u\n",
2022		__func__, m, m->m_len);
2023
2024	/* setup descriptors */
2025	ds = bf->bf_desc;
2026
2027	flags = HAL_TXDESC_NOACK;
2028	if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
2029		ds->ds_link = bf->bf_daddr;	/* self-linked */
2030		flags |= HAL_TXDESC_VEOL;
2031		/*
2032		 * Let hardware handle antenna switching.
2033		 */
2034		antenna = sc->sc_txantenna;
2035	} else {
2036		ds->ds_link = 0;
2037		/*
2038		 * Switch antenna every 4 beacons.
2039		 * XXX assumes two antenna
2040		 */
2041		antenna = sc->sc_txantenna != 0 ? sc->sc_txantenna
2042			: (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
2043	}
2044
2045	KASSERT(bf->bf_nseg == 1,
2046		("multi-segment beacon frame; nseg %u", bf->bf_nseg));
2047	ds->ds_data = bf->bf_segs[0].ds_addr;
2048	/*
2049	 * Calculate rate code.
2050	 * XXX everything at min xmit rate
2051	 */
2052	rix = sc->sc_minrateix;
2053	rt = sc->sc_currates;
2054	rate = rt->info[rix].rateCode;
2055	if (USE_SHPREAMBLE(ic))
2056		rate |= rt->info[rix].shortPreamble;
2057	ath_hal_setuptxdesc(ah, ds
2058		, m->m_len + IEEE80211_CRC_LEN	/* frame length */
2059		, sizeof(struct ieee80211_frame)/* header length */
2060		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
2061		, ni->ni_txpower		/* txpower XXX */
2062		, rate, 1			/* series 0 rate/tries */
2063		, HAL_TXKEYIX_INVALID		/* no encryption */
2064		, antenna			/* antenna mode */
2065		, flags				/* no ack, veol for beacons */
2066		, 0				/* rts/cts rate */
2067		, 0				/* rts/cts duration */
2068	);
2069	/* NB: beacon's BufLen must be a multiple of 4 bytes */
2070	ath_hal_filltxdesc(ah, ds
2071		, roundup(m->m_len, 4)		/* buffer length */
2072		, AH_TRUE			/* first segment */
2073		, AH_TRUE			/* last segment */
2074		, ds				/* first descriptor */
2075	);
2076#undef USE_SHPREAMBLE
2077}
2078
2079/*
2080 * Append the contents of src to dst; both queues
2081 * are assumed to be locked.
2082 */
2083static void
2084ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
2085{
2086	STAILQ_CONCAT(&dst->axq_q, &src->axq_q);
2087	dst->axq_link = src->axq_link;
2088	src->axq_link = NULL;
2089	dst->axq_depth += src->axq_depth;
2090	src->axq_depth = 0;
2091}
2092
2093/*
2094 * Transmit a beacon frame at SWBA.  Dynamic updates to the
2095 * frame contents are done as needed and the slot time is
2096 * also adjusted based on current state.
2097 */
2098static void
2099ath_beacon_proc(void *arg, int pending)
2100{
2101	struct ath_softc *sc = arg;
2102	struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
2103	struct ieee80211_node *ni = bf->bf_node;
2104	struct ieee80211com *ic = ni->ni_ic;
2105	struct ath_hal *ah = sc->sc_ah;
2106	struct ath_txq *cabq = sc->sc_cabq;
2107	struct mbuf *m;
2108	int ncabq, nmcastq, error, otherant;
2109
2110	DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
2111		__func__, pending);
2112
2113	if (ic->ic_opmode == IEEE80211_M_STA ||
2114	    ic->ic_opmode == IEEE80211_M_MONITOR ||
2115	    bf == NULL || bf->bf_m == NULL) {
2116		DPRINTF(sc, ATH_DEBUG_ANY, "%s: ic_flags=%x bf=%p bf_m=%p\n",
2117			__func__, ic->ic_flags, bf, bf ? bf->bf_m : NULL);
2118		return;
2119	}
2120	/*
2121	 * Check if the previous beacon has gone out.  If
2122	 * not don't try to post another, skip this period
2123	 * and wait for the next.  Missed beacons indicate
2124	 * a problem and should not occur.  If we miss too
2125	 * many consecutive beacons reset the device.
2126	 */
2127	if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
2128		sc->sc_bmisscount++;
2129		DPRINTF(sc, ATH_DEBUG_BEACON,
2130			"%s: missed %u consecutive beacons\n",
2131			__func__, sc->sc_bmisscount);
2132		if (sc->sc_bmisscount > 3)		/* NB: 3 is a guess */
2133			taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
2134		return;
2135	}
2136	if (sc->sc_bmisscount != 0) {
2137		DPRINTF(sc, ATH_DEBUG_BEACON,
2138			"%s: resume beacon xmit after %u misses\n",
2139			__func__, sc->sc_bmisscount);
2140		sc->sc_bmisscount = 0;
2141	}
2142
2143	/*
2144	 * Update dynamic beacon contents.  If this returns
2145	 * non-zero then we need to remap the memory because
2146	 * the beacon frame changed size (probably because
2147	 * of the TIM bitmap).
2148	 */
2149	m = bf->bf_m;
2150	nmcastq = sc->sc_mcastq.axq_depth;
2151	ncabq = ath_hal_numtxpending(ah, cabq->axq_qnum);
2152	if (ieee80211_beacon_update(ic, bf->bf_node, &sc->sc_boff, m, ncabq+nmcastq)) {
2153		/* XXX too conservative? */
2154		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2155		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
2156					     bf->bf_segs, &bf->bf_nseg,
2157					     BUS_DMA_NOWAIT);
2158		if (error != 0) {
2159			if_printf(ic->ic_ifp,
2160			    "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
2161			    __func__, error);
2162			return;
2163		}
2164	}
2165	if (ncabq && (sc->sc_boff.bo_tim[4] & 1)) {
2166		/*
2167		 * CABQ traffic from the previous DTIM is still pending.
2168		 * This is ok for now but when there are multiple vap's
2169		 * and we are using staggered beacons we'll want to drain
2170		 * the cabq before loading frames for the different vap.
2171		 */
2172		DPRINTF(sc, ATH_DEBUG_BEACON,
2173		    "%s: cabq did not drain, mcastq %u cabq %u/%u\n",
2174		    __func__, nmcastq, ncabq, cabq->axq_depth);
2175		sc->sc_stats.ast_cabq_busy++;
2176	}
2177
2178	/*
2179	 * Handle slot time change when a non-ERP station joins/leaves
2180	 * an 11g network.  The 802.11 layer notifies us via callback,
2181	 * we mark updateslot, then wait one beacon before effecting
2182	 * the change.  This gives associated stations at least one
2183	 * beacon interval to note the state change.
2184	 */
2185	/* XXX locking */
2186	if (sc->sc_updateslot == UPDATE)
2187		sc->sc_updateslot = COMMIT;	/* commit next beacon */
2188	else if (sc->sc_updateslot == COMMIT)
2189		ath_setslottime(sc);		/* commit change to h/w */
2190
2191	/*
2192	 * Check recent per-antenna transmit statistics and flip
2193	 * the default antenna if noticeably more frames went out
2194	 * on the non-default antenna.
2195	 * XXX assumes 2 anntenae
2196	 */
2197	otherant = sc->sc_defant & 1 ? 2 : 1;
2198	if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
2199		ath_setdefantenna(sc, otherant);
2200	sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
2201
2202	/*
2203	 * Construct tx descriptor.
2204	 */
2205	ath_beacon_setup(sc, bf);
2206
2207	/*
2208	 * Stop any current dma and put the new frame on the queue.
2209	 * This should never fail since we check above that no frames
2210	 * are still pending on the queue.
2211	 */
2212	if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
2213		DPRINTF(sc, ATH_DEBUG_ANY,
2214			"%s: beacon queue %u did not stop?\n",
2215			__func__, sc->sc_bhalq);
2216	}
2217	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
2218
2219	/*
2220	 * Enable the CAB queue before the beacon queue to
2221	 * insure cab frames are triggered by this beacon.
2222	 */
2223	if (sc->sc_boff.bo_tim_len && (sc->sc_boff.bo_tim[4] & 1)) {
2224		/* NB: only at DTIM */
2225		ATH_TXQ_LOCK(cabq);
2226		ATH_TXQ_LOCK(&sc->sc_mcastq);
2227		if (nmcastq) {
2228			struct ath_buf *bfm;
2229
2230			/*
2231			 * Move frames from the s/w mcast q to the h/w cab q.
2232			 */
2233			bfm = STAILQ_FIRST(&sc->sc_mcastq.axq_q);
2234			if (cabq->axq_link != NULL) {
2235				*cabq->axq_link = bfm->bf_daddr;
2236			} else
2237				ath_hal_puttxbuf(ah, cabq->axq_qnum,
2238					bfm->bf_daddr);
2239			ath_txqmove(cabq, &sc->sc_mcastq);
2240
2241			sc->sc_stats.ast_cabq_xmit += nmcastq;
2242		}
2243		/* NB: gated by beacon so safe to start here */
2244		ath_hal_txstart(ah, cabq->axq_qnum);
2245		ATH_TXQ_UNLOCK(cabq);
2246		ATH_TXQ_UNLOCK(&sc->sc_mcastq);
2247	}
2248	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
2249	ath_hal_txstart(ah, sc->sc_bhalq);
2250	DPRINTF(sc, ATH_DEBUG_BEACON_PROC,
2251		"%s: TXDP[%u] = %p (%p)\n", __func__,
2252		sc->sc_bhalq, (caddr_t)bf->bf_daddr, bf->bf_desc);
2253
2254	sc->sc_stats.ast_be_xmit++;
2255}
2256
2257/*
2258 * Reset the hardware after detecting beacons have stopped.
2259 */
2260static void
2261ath_bstuck_proc(void *arg, int pending)
2262{
2263	struct ath_softc *sc = arg;
2264	struct ifnet *ifp = sc->sc_ifp;
2265
2266	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
2267		sc->sc_bmisscount);
2268	ath_reset(ifp);
2269}
2270
2271/*
2272 * Reclaim beacon resources.
2273 */
2274static void
2275ath_beacon_free(struct ath_softc *sc)
2276{
2277	struct ath_buf *bf;
2278
2279	STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
2280		if (bf->bf_m != NULL) {
2281			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2282			m_freem(bf->bf_m);
2283			bf->bf_m = NULL;
2284		}
2285		if (bf->bf_node != NULL) {
2286			ieee80211_free_node(bf->bf_node);
2287			bf->bf_node = NULL;
2288		}
2289	}
2290}
2291
2292/*
2293 * Configure the beacon and sleep timers.
2294 *
2295 * When operating as an AP this resets the TSF and sets
2296 * up the hardware to notify us when we need to issue beacons.
2297 *
2298 * When operating in station mode this sets up the beacon
2299 * timers according to the timestamp of the last received
2300 * beacon and the current TSF, configures PCF and DTIM
2301 * handling, programs the sleep registers so the hardware
2302 * will wakeup in time to receive beacons, and configures
2303 * the beacon miss handling so we'll receive a BMISS
2304 * interrupt when we stop seeing beacons from the AP
2305 * we've associated with.
2306 */
2307static void
2308ath_beacon_config(struct ath_softc *sc)
2309{
2310#define	TSF_TO_TU(_h,_l) \
2311	((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
2312#define	FUDGE	2
2313	struct ath_hal *ah = sc->sc_ah;
2314	struct ieee80211com *ic = &sc->sc_ic;
2315	struct ieee80211_node *ni = ic->ic_bss;
2316	u_int32_t nexttbtt, intval, tsftu;
2317	u_int64_t tsf;
2318
2319	/* extract tstamp from last beacon and convert to TU */
2320	nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
2321			     LE_READ_4(ni->ni_tstamp.data));
2322	/* NB: the beacon interval is kept internally in TU's */
2323	intval = ni->ni_intval & HAL_BEACON_PERIOD;
2324	if (nexttbtt == 0)		/* e.g. for ap mode */
2325		nexttbtt = intval;
2326	else if (intval)		/* NB: can be 0 for monitor mode */
2327		nexttbtt = roundup(nexttbtt, intval);
2328	DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
2329		__func__, nexttbtt, intval, ni->ni_intval);
2330	if (ic->ic_opmode == IEEE80211_M_STA) {
2331		HAL_BEACON_STATE bs;
2332		int dtimperiod, dtimcount;
2333		int cfpperiod, cfpcount;
2334
2335		/*
2336		 * Setup dtim and cfp parameters according to
2337		 * last beacon we received (which may be none).
2338		 */
2339		dtimperiod = ni->ni_dtim_period;
2340		if (dtimperiod <= 0)		/* NB: 0 if not known */
2341			dtimperiod = 1;
2342		dtimcount = ni->ni_dtim_count;
2343		if (dtimcount >= dtimperiod)	/* NB: sanity check */
2344			dtimcount = 0;		/* XXX? */
2345		cfpperiod = 1;			/* NB: no PCF support yet */
2346		cfpcount = 0;
2347		/*
2348		 * Pull nexttbtt forward to reflect the current
2349		 * TSF and calculate dtim+cfp state for the result.
2350		 */
2351		tsf = ath_hal_gettsf64(ah);
2352		tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
2353		do {
2354			nexttbtt += intval;
2355			if (--dtimcount < 0) {
2356				dtimcount = dtimperiod - 1;
2357				if (--cfpcount < 0)
2358					cfpcount = cfpperiod - 1;
2359			}
2360		} while (nexttbtt < tsftu);
2361		memset(&bs, 0, sizeof(bs));
2362		bs.bs_intval = intval;
2363		bs.bs_nexttbtt = nexttbtt;
2364		bs.bs_dtimperiod = dtimperiod*intval;
2365		bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
2366		bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
2367		bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
2368		bs.bs_cfpmaxduration = 0;
2369#if 0
2370		/*
2371		 * The 802.11 layer records the offset to the DTIM
2372		 * bitmap while receiving beacons; use it here to
2373		 * enable h/w detection of our AID being marked in
2374		 * the bitmap vector (to indicate frames for us are
2375		 * pending at the AP).
2376		 * XXX do DTIM handling in s/w to WAR old h/w bugs
2377		 * XXX enable based on h/w rev for newer chips
2378		 */
2379		bs.bs_timoffset = ni->ni_timoff;
2380#endif
2381		/*
2382		 * Calculate the number of consecutive beacons to miss
2383		 * before taking a BMISS interrupt.  The configuration
2384		 * is specified in ms, so we need to convert that to
2385		 * TU's and then calculate based on the beacon interval.
2386		 * Note that we clamp the result to at most 10 beacons.
2387		 */
2388		bs.bs_bmissthreshold = ic->ic_bmissthreshold;
2389		if (bs.bs_bmissthreshold > 10)
2390			bs.bs_bmissthreshold = 10;
2391		else if (bs.bs_bmissthreshold <= 0)
2392			bs.bs_bmissthreshold = 1;
2393
2394		/*
2395		 * Calculate sleep duration.  The configuration is
2396		 * given in ms.  We insure a multiple of the beacon
2397		 * period is used.  Also, if the sleep duration is
2398		 * greater than the DTIM period then it makes senses
2399		 * to make it a multiple of that.
2400		 *
2401		 * XXX fixed at 100ms
2402		 */
2403		bs.bs_sleepduration =
2404			roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
2405		if (bs.bs_sleepduration > bs.bs_dtimperiod)
2406			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
2407
2408		DPRINTF(sc, ATH_DEBUG_BEACON,
2409			"%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"
2410			, __func__
2411			, tsf, tsftu
2412			, bs.bs_intval
2413			, bs.bs_nexttbtt
2414			, bs.bs_dtimperiod
2415			, bs.bs_nextdtim
2416			, bs.bs_bmissthreshold
2417			, bs.bs_sleepduration
2418			, bs.bs_cfpperiod
2419			, bs.bs_cfpmaxduration
2420			, bs.bs_cfpnext
2421			, bs.bs_timoffset
2422		);
2423		ath_hal_intrset(ah, 0);
2424		ath_hal_beacontimers(ah, &bs);
2425		sc->sc_imask |= HAL_INT_BMISS;
2426		ath_hal_intrset(ah, sc->sc_imask);
2427	} else {
2428		ath_hal_intrset(ah, 0);
2429		if (nexttbtt == intval)
2430			intval |= HAL_BEACON_RESET_TSF;
2431		if (ic->ic_opmode == IEEE80211_M_IBSS) {
2432			/*
2433			 * In IBSS mode enable the beacon timers but only
2434			 * enable SWBA interrupts if we need to manually
2435			 * prepare beacon frames.  Otherwise we use a
2436			 * self-linked tx descriptor and let the hardware
2437			 * deal with things.
2438			 */
2439			intval |= HAL_BEACON_ENA;
2440			if (!sc->sc_hasveol)
2441				sc->sc_imask |= HAL_INT_SWBA;
2442			if ((intval & HAL_BEACON_RESET_TSF) == 0) {
2443				/*
2444				 * Pull nexttbtt forward to reflect
2445				 * the current TSF.
2446				 */
2447				tsf = ath_hal_gettsf64(ah);
2448				tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
2449				do {
2450					nexttbtt += intval;
2451				} while (nexttbtt < tsftu);
2452			}
2453			ath_beaconq_config(sc);
2454		} else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2455			/*
2456			 * In AP mode we enable the beacon timers and
2457			 * SWBA interrupts to prepare beacon frames.
2458			 */
2459			intval |= HAL_BEACON_ENA;
2460			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
2461			ath_beaconq_config(sc);
2462		}
2463		ath_hal_beaconinit(ah, nexttbtt, intval);
2464		sc->sc_bmisscount = 0;
2465		ath_hal_intrset(ah, sc->sc_imask);
2466		/*
2467		 * When using a self-linked beacon descriptor in
2468		 * ibss mode load it once here.
2469		 */
2470		if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
2471			ath_beacon_proc(sc, 0);
2472	}
2473	sc->sc_syncbeacon = 0;
2474#undef FUDGE
2475#undef TSF_TO_TU
2476}
2477
2478static void
2479ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2480{
2481	bus_addr_t *paddr = (bus_addr_t*) arg;
2482	KASSERT(error == 0, ("error %u on bus_dma callback", error));
2483	*paddr = segs->ds_addr;
2484}
2485
2486static int
2487ath_descdma_setup(struct ath_softc *sc,
2488	struct ath_descdma *dd, ath_bufhead *head,
2489	const char *name, int nbuf, int ndesc)
2490{
2491#define	DS2PHYS(_dd, _ds) \
2492	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
2493	struct ifnet *ifp = sc->sc_ifp;
2494	struct ath_desc *ds;
2495	struct ath_buf *bf;
2496	int i, bsize, error;
2497
2498	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
2499	    __func__, name, nbuf, ndesc);
2500
2501	dd->dd_name = name;
2502	dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
2503
2504	/*
2505	 * Setup DMA descriptor area.
2506	 */
2507	error = bus_dma_tag_create(NULL,	/* parent */
2508		       PAGE_SIZE, 0,		/* alignment, bounds */
2509		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
2510		       BUS_SPACE_MAXADDR,	/* highaddr */
2511		       NULL, NULL,		/* filter, filterarg */
2512		       dd->dd_desc_len,		/* maxsize */
2513		       1,			/* nsegments */
2514		       dd->dd_desc_len,		/* maxsegsize */
2515		       BUS_DMA_ALLOCNOW,	/* flags */
2516		       NULL,			/* lockfunc */
2517		       NULL,			/* lockarg */
2518		       &dd->dd_dmat);
2519	if (error != 0) {
2520		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
2521		return error;
2522	}
2523
2524	/* allocate descriptors */
2525	error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
2526	if (error != 0) {
2527		if_printf(ifp, "unable to create dmamap for %s descriptors, "
2528			"error %u\n", dd->dd_name, error);
2529		goto fail0;
2530	}
2531
2532	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
2533				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
2534				 &dd->dd_dmamap);
2535	if (error != 0) {
2536		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
2537			"error %u\n", nbuf * ndesc, dd->dd_name, error);
2538		goto fail1;
2539	}
2540
2541	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
2542				dd->dd_desc, dd->dd_desc_len,
2543				ath_load_cb, &dd->dd_desc_paddr,
2544				BUS_DMA_NOWAIT);
2545	if (error != 0) {
2546		if_printf(ifp, "unable to map %s descriptors, error %u\n",
2547			dd->dd_name, error);
2548		goto fail2;
2549	}
2550
2551	ds = dd->dd_desc;
2552	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
2553	    __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
2554	    (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
2555
2556	/* allocate rx buffers */
2557	bsize = sizeof(struct ath_buf) * nbuf;
2558	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
2559	if (bf == NULL) {
2560		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
2561			dd->dd_name, bsize);
2562		goto fail3;
2563	}
2564	dd->dd_bufptr = bf;
2565
2566	STAILQ_INIT(head);
2567	for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
2568		bf->bf_desc = ds;
2569		bf->bf_daddr = DS2PHYS(dd, ds);
2570		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
2571				&bf->bf_dmamap);
2572		if (error != 0) {
2573			if_printf(ifp, "unable to create dmamap for %s "
2574				"buffer %u, error %u\n", dd->dd_name, i, error);
2575			ath_descdma_cleanup(sc, dd, head);
2576			return error;
2577		}
2578		STAILQ_INSERT_TAIL(head, bf, bf_list);
2579	}
2580	return 0;
2581fail3:
2582	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2583fail2:
2584	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2585fail1:
2586	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2587fail0:
2588	bus_dma_tag_destroy(dd->dd_dmat);
2589	memset(dd, 0, sizeof(*dd));
2590	return error;
2591#undef DS2PHYS
2592}
2593
2594static void
2595ath_descdma_cleanup(struct ath_softc *sc,
2596	struct ath_descdma *dd, ath_bufhead *head)
2597{
2598	struct ath_buf *bf;
2599	struct ieee80211_node *ni;
2600
2601	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2602	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2603	bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2604	bus_dma_tag_destroy(dd->dd_dmat);
2605
2606	STAILQ_FOREACH(bf, head, bf_list) {
2607		if (bf->bf_m) {
2608			m_freem(bf->bf_m);
2609			bf->bf_m = NULL;
2610		}
2611		if (bf->bf_dmamap != NULL) {
2612			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
2613			bf->bf_dmamap = NULL;
2614		}
2615		ni = bf->bf_node;
2616		bf->bf_node = NULL;
2617		if (ni != NULL) {
2618			/*
2619			 * Reclaim node reference.
2620			 */
2621			ieee80211_free_node(ni);
2622		}
2623	}
2624
2625	STAILQ_INIT(head);
2626	free(dd->dd_bufptr, M_ATHDEV);
2627	memset(dd, 0, sizeof(*dd));
2628}
2629
2630static int
2631ath_desc_alloc(struct ath_softc *sc)
2632{
2633	int error;
2634
2635	error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
2636			"rx", ath_rxbuf, 1);
2637	if (error != 0)
2638		return error;
2639
2640	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
2641			"tx", ath_txbuf, ATH_TXDESC);
2642	if (error != 0) {
2643		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2644		return error;
2645	}
2646
2647	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
2648			"beacon", 1, 1);
2649	if (error != 0) {
2650		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2651		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2652		return error;
2653	}
2654	return 0;
2655}
2656
2657static void
2658ath_desc_free(struct ath_softc *sc)
2659{
2660
2661	if (sc->sc_bdma.dd_desc_len != 0)
2662		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
2663	if (sc->sc_txdma.dd_desc_len != 0)
2664		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2665	if (sc->sc_rxdma.dd_desc_len != 0)
2666		ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2667}
2668
2669static struct ieee80211_node *
2670ath_node_alloc(struct ieee80211_node_table *nt)
2671{
2672	struct ieee80211com *ic = nt->nt_ic;
2673	struct ath_softc *sc = ic->ic_ifp->if_softc;
2674	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
2675	struct ath_node *an;
2676
2677	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
2678	if (an == NULL) {
2679		/* XXX stat+msg */
2680		return NULL;
2681	}
2682	an->an_avgrssi = ATH_RSSI_DUMMY_MARKER;
2683	ath_rate_node_init(sc, an);
2684
2685	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
2686	return &an->an_node;
2687}
2688
2689static void
2690ath_node_free(struct ieee80211_node *ni)
2691{
2692	struct ieee80211com *ic = ni->ni_ic;
2693        struct ath_softc *sc = ic->ic_ifp->if_softc;
2694
2695	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
2696
2697	ath_rate_node_cleanup(sc, ATH_NODE(ni));
2698	sc->sc_node_free(ni);
2699}
2700
2701static u_int8_t
2702ath_node_getrssi(const struct ieee80211_node *ni)
2703{
2704#define	HAL_EP_RND(x, mul) \
2705	((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
2706	u_int32_t avgrssi = ATH_NODE_CONST(ni)->an_avgrssi;
2707	int32_t rssi;
2708
2709	/*
2710	 * When only one frame is received there will be no state in
2711	 * avgrssi so fallback on the value recorded by the 802.11 layer.
2712	 */
2713	if (avgrssi != ATH_RSSI_DUMMY_MARKER)
2714		rssi = HAL_EP_RND(avgrssi, HAL_RSSI_EP_MULTIPLIER);
2715	else
2716		rssi = ni->ni_rssi;
2717	return rssi < 0 ? 0 : rssi > 127 ? 127 : rssi;
2718#undef HAL_EP_RND
2719}
2720
2721static int
2722ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
2723{
2724	struct ath_hal *ah = sc->sc_ah;
2725	int error;
2726	struct mbuf *m;
2727	struct ath_desc *ds;
2728
2729	m = bf->bf_m;
2730	if (m == NULL) {
2731		/*
2732		 * NB: by assigning a page to the rx dma buffer we
2733		 * implicitly satisfy the Atheros requirement that
2734		 * this buffer be cache-line-aligned and sized to be
2735		 * multiple of the cache line size.  Not doing this
2736		 * causes weird stuff to happen (for the 5210 at least).
2737		 */
2738		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
2739		if (m == NULL) {
2740			DPRINTF(sc, ATH_DEBUG_ANY,
2741				"%s: no mbuf/cluster\n", __func__);
2742			sc->sc_stats.ast_rx_nombuf++;
2743			return ENOMEM;
2744		}
2745		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
2746
2747		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
2748					     bf->bf_dmamap, m,
2749					     bf->bf_segs, &bf->bf_nseg,
2750					     BUS_DMA_NOWAIT);
2751		if (error != 0) {
2752			DPRINTF(sc, ATH_DEBUG_ANY,
2753			    "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
2754			    __func__, error);
2755			sc->sc_stats.ast_rx_busdma++;
2756			m_freem(m);
2757			return error;
2758		}
2759		KASSERT(bf->bf_nseg == 1,
2760			("multi-segment packet; nseg %u", bf->bf_nseg));
2761		bf->bf_m = m;
2762	}
2763	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
2764
2765	/*
2766	 * Setup descriptors.  For receive we always terminate
2767	 * the descriptor list with a self-linked entry so we'll
2768	 * not get overrun under high load (as can happen with a
2769	 * 5212 when ANI processing enables PHY error frames).
2770	 *
2771	 * To insure the last descriptor is self-linked we create
2772	 * each descriptor as self-linked and add it to the end.  As
2773	 * each additional descriptor is added the previous self-linked
2774	 * entry is ``fixed'' naturally.  This should be safe even
2775	 * if DMA is happening.  When processing RX interrupts we
2776	 * never remove/process the last, self-linked, entry on the
2777	 * descriptor list.  This insures the hardware always has
2778	 * someplace to write a new frame.
2779	 */
2780	ds = bf->bf_desc;
2781	ds->ds_link = bf->bf_daddr;	/* link to self */
2782	ds->ds_data = bf->bf_segs[0].ds_addr;
2783	ath_hal_setuprxdesc(ah, ds
2784		, m->m_len		/* buffer size */
2785		, 0
2786	);
2787
2788	if (sc->sc_rxlink != NULL)
2789		*sc->sc_rxlink = bf->bf_daddr;
2790	sc->sc_rxlink = &ds->ds_link;
2791	return 0;
2792}
2793
2794/*
2795 * Extend 15-bit time stamp from rx descriptor to
2796 * a full 64-bit TSF using the specified TSF.
2797 */
2798static __inline u_int64_t
2799ath_extend_tsf(u_int32_t rstamp, u_int64_t tsf)
2800{
2801	if ((tsf & 0x7fff) < rstamp)
2802		tsf -= 0x8000;
2803	return ((tsf &~ 0x7fff) | rstamp);
2804}
2805
2806/*
2807 * Intercept management frames to collect beacon rssi data
2808 * and to do ibss merges.
2809 */
2810static void
2811ath_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
2812	struct ieee80211_node *ni,
2813	int subtype, int rssi, u_int32_t rstamp)
2814{
2815	struct ath_softc *sc = ic->ic_ifp->if_softc;
2816
2817	/*
2818	 * Call up first so subsequent work can use information
2819	 * potentially stored in the node (e.g. for ibss merge).
2820	 */
2821	sc->sc_recv_mgmt(ic, m, ni, subtype, rssi, rstamp);
2822	switch (subtype) {
2823	case IEEE80211_FC0_SUBTYPE_BEACON:
2824		/* update rssi statistics for use by the hal */
2825		ATH_RSSI_LPF(sc->sc_halstats.ns_avgbrssi, rssi);
2826		if (sc->sc_syncbeacon &&
2827		    ni == ic->ic_bss && ic->ic_state == IEEE80211_S_RUN) {
2828			/*
2829			 * Resync beacon timers using the tsf of the beacon
2830			 * frame we just received.
2831			 */
2832			ath_beacon_config(sc);
2833		}
2834		/* fall thru... */
2835	case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
2836		if (ic->ic_opmode == IEEE80211_M_IBSS &&
2837		    ic->ic_state == IEEE80211_S_RUN) {
2838			u_int64_t tsf = ath_extend_tsf(rstamp,
2839				ath_hal_gettsf64(sc->sc_ah));
2840			/*
2841			 * Handle ibss merge as needed; check the tsf on the
2842			 * frame before attempting the merge.  The 802.11 spec
2843			 * says the station should change it's bssid to match
2844			 * the oldest station with the same ssid, where oldest
2845			 * is determined by the tsf.  Note that hardware
2846			 * reconfiguration happens through callback to
2847			 * ath_newstate as the state machine will go from
2848			 * RUN -> RUN when this happens.
2849			 */
2850			if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
2851				DPRINTF(sc, ATH_DEBUG_STATE,
2852				    "ibss merge, rstamp %u tsf %ju "
2853				    "tstamp %ju\n", rstamp, (uintmax_t)tsf,
2854				    (uintmax_t)ni->ni_tstamp.tsf);
2855				(void) ieee80211_ibss_merge(ni);
2856			}
2857		}
2858		break;
2859	}
2860}
2861
2862/*
2863 * Set the default antenna.
2864 */
2865static void
2866ath_setdefantenna(struct ath_softc *sc, u_int antenna)
2867{
2868	struct ath_hal *ah = sc->sc_ah;
2869
2870	/* XXX block beacon interrupts */
2871	ath_hal_setdefantenna(ah, antenna);
2872	if (sc->sc_defant != antenna)
2873		sc->sc_stats.ast_ant_defswitch++;
2874	sc->sc_defant = antenna;
2875	sc->sc_rxotherant = 0;
2876}
2877
2878static int
2879ath_rx_tap(struct ath_softc *sc, struct mbuf *m,
2880	const struct ath_rx_status *rs, u_int64_t tsf, int16_t nf)
2881{
2882	u_int8_t rix;
2883
2884	KASSERT(sc->sc_drvbpf != NULL, ("no tap"));
2885
2886	/*
2887	 * Discard anything shorter than an ack or cts.
2888	 */
2889	if (m->m_pkthdr.len < IEEE80211_ACK_LEN) {
2890		DPRINTF(sc, ATH_DEBUG_RECV, "%s: runt packet %d\n",
2891			__func__, m->m_pkthdr.len);
2892		sc->sc_stats.ast_rx_tooshort++;
2893		return 0;
2894	}
2895	sc->sc_rx_th.wr_tsf = htole64(ath_extend_tsf(rs->rs_tstamp, tsf));
2896	rix = rs->rs_rate;
2897	sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
2898	if (rs->rs_status & HAL_RXERR_CRC)
2899		sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
2900	/* XXX propagate other error flags from descriptor */
2901	sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
2902	sc->sc_rx_th.wr_antsignal = rs->rs_rssi + nf;
2903	sc->sc_rx_th.wr_antnoise = nf;
2904	sc->sc_rx_th.wr_antenna = rs->rs_antenna;
2905
2906	bpf_mtap2(sc->sc_drvbpf, &sc->sc_rx_th, sc->sc_rx_th_len, m);
2907
2908	return 1;
2909}
2910
2911static void
2912ath_rx_proc(void *arg, int npending)
2913{
2914#define	PA2DESC(_sc, _pa) \
2915	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
2916		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
2917	struct ath_softc *sc = arg;
2918	struct ath_buf *bf;
2919	struct ieee80211com *ic = &sc->sc_ic;
2920	struct ifnet *ifp = sc->sc_ifp;
2921	struct ath_hal *ah = sc->sc_ah;
2922	struct ath_desc *ds;
2923	struct ath_rx_status *rs;
2924	struct mbuf *m;
2925	struct ieee80211_node *ni;
2926	struct ath_node *an;
2927	int len, type, ngood;
2928	u_int phyerr;
2929	HAL_STATUS status;
2930	int16_t nf;
2931	u_int64_t tsf;
2932
2933	NET_LOCK_GIANT();		/* XXX */
2934
2935	DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
2936	ngood = 0;
2937	nf = ath_hal_getchannoise(ah, &sc->sc_curchan);
2938	tsf = ath_hal_gettsf64(ah);
2939	do {
2940		bf = STAILQ_FIRST(&sc->sc_rxbuf);
2941		if (bf == NULL) {		/* NB: shouldn't happen */
2942			if_printf(ifp, "%s: no buffer!\n", __func__);
2943			break;
2944		}
2945		m = bf->bf_m;
2946		if (m == NULL) {		/* NB: shouldn't happen */
2947			/*
2948			 * If mbuf allocation failed previously there
2949			 * will be no mbuf; try again to re-populate it.
2950			 */
2951			/* XXX make debug msg */
2952			if_printf(ifp, "%s: no mbuf!\n", __func__);
2953			STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
2954			goto rx_next;
2955		}
2956		ds = bf->bf_desc;
2957		if (ds->ds_link == bf->bf_daddr) {
2958			/* NB: never process the self-linked entry at the end */
2959			break;
2960		}
2961		/* XXX sync descriptor memory */
2962		/*
2963		 * Must provide the virtual address of the current
2964		 * descriptor, the physical address, and the virtual
2965		 * address of the next descriptor in the h/w chain.
2966		 * This allows the HAL to look ahead to see if the
2967		 * hardware is done with a descriptor by checking the
2968		 * done bit in the following descriptor and the address
2969		 * of the current descriptor the DMA engine is working
2970		 * on.  All this is necessary because of our use of
2971		 * a self-linked list to avoid rx overruns.
2972		 */
2973		rs = &bf->bf_status.ds_rxstat;
2974		status = ath_hal_rxprocdesc(ah, ds,
2975				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
2976#ifdef ATH_DEBUG
2977		if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
2978			ath_printrxbuf(bf, 0, status == HAL_OK);
2979#endif
2980		if (status == HAL_EINPROGRESS)
2981			break;
2982		STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
2983		if (rs->rs_more) {
2984			/*
2985			 * Frame spans multiple descriptors; this
2986			 * cannot happen yet as we don't support
2987			 * jumbograms.  If not in monitor mode,
2988			 * discard the frame.
2989			 */
2990			if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2991				sc->sc_stats.ast_rx_toobig++;
2992				goto rx_next;
2993			}
2994			/* fall thru for monitor mode handling... */
2995		} else if (rs->rs_status != 0) {
2996			if (rs->rs_status & HAL_RXERR_CRC)
2997				sc->sc_stats.ast_rx_crcerr++;
2998			if (rs->rs_status & HAL_RXERR_FIFO)
2999				sc->sc_stats.ast_rx_fifoerr++;
3000			if (rs->rs_status & HAL_RXERR_PHY) {
3001				sc->sc_stats.ast_rx_phyerr++;
3002				phyerr = rs->rs_phyerr & 0x1f;
3003				sc->sc_stats.ast_rx_phy[phyerr]++;
3004				goto rx_next;
3005			}
3006			if (rs->rs_status & HAL_RXERR_DECRYPT) {
3007				/*
3008				 * Decrypt error.  If the error occurred
3009				 * because there was no hardware key, then
3010				 * let the frame through so the upper layers
3011				 * can process it.  This is necessary for 5210
3012				 * parts which have no way to setup a ``clear''
3013				 * key cache entry.
3014				 *
3015				 * XXX do key cache faulting
3016				 */
3017				if (rs->rs_keyix == HAL_RXKEYIX_INVALID)
3018					goto rx_accept;
3019				sc->sc_stats.ast_rx_badcrypt++;
3020			}
3021			if (rs->rs_status & HAL_RXERR_MIC) {
3022				sc->sc_stats.ast_rx_badmic++;
3023				/*
3024				 * Do minimal work required to hand off
3025				 * the 802.11 header for notifcation.
3026				 */
3027				/* XXX frag's and qos frames */
3028				len = rs->rs_datalen;
3029				if (len >= sizeof (struct ieee80211_frame)) {
3030					bus_dmamap_sync(sc->sc_dmat,
3031					    bf->bf_dmamap,
3032					    BUS_DMASYNC_POSTREAD);
3033					ieee80211_notify_michael_failure(ic,
3034					    mtod(m, struct ieee80211_frame *),
3035					    sc->sc_splitmic ?
3036					        rs->rs_keyix-32 : rs->rs_keyix
3037					);
3038				}
3039			}
3040			ifp->if_ierrors++;
3041			/*
3042			 * When a tap is present pass error frames
3043			 * that have been requested.  By default we
3044			 * pass decrypt+mic errors but others may be
3045			 * interesting (e.g. crc).
3046			 */
3047			if (bpf_peers_present(sc->sc_drvbpf) &&
3048			    (rs->rs_status & sc->sc_monpass)) {
3049				bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3050				    BUS_DMASYNC_POSTREAD);
3051				/* NB: bpf needs the mbuf length setup */
3052				len = rs->rs_datalen;
3053				m->m_pkthdr.len = m->m_len = len;
3054				(void) ath_rx_tap(sc, m, rs, tsf, nf);
3055			}
3056			/* XXX pass MIC errors up for s/w reclaculation */
3057			goto rx_next;
3058		}
3059rx_accept:
3060		/*
3061		 * Sync and unmap the frame.  At this point we're
3062		 * committed to passing the mbuf somewhere so clear
3063		 * bf_m; this means a new mbuf must be allocated
3064		 * when the rx descriptor is setup again to receive
3065		 * another frame.
3066		 */
3067		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3068		    BUS_DMASYNC_POSTREAD);
3069		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3070		bf->bf_m = NULL;
3071
3072		m->m_pkthdr.rcvif = ifp;
3073		len = rs->rs_datalen;
3074		m->m_pkthdr.len = m->m_len = len;
3075
3076		sc->sc_stats.ast_ant_rx[rs->rs_antenna]++;
3077
3078		if (bpf_peers_present(sc->sc_drvbpf) &&
3079		    !ath_rx_tap(sc, m, rs, tsf, nf)) {
3080			m_freem(m);		/* XXX reclaim */
3081			goto rx_next;
3082		}
3083
3084		/*
3085		 * From this point on we assume the frame is at least
3086		 * as large as ieee80211_frame_min; verify that.
3087		 */
3088		if (len < IEEE80211_MIN_LEN) {
3089			DPRINTF(sc, ATH_DEBUG_RECV, "%s: short packet %d\n",
3090				__func__, len);
3091			sc->sc_stats.ast_rx_tooshort++;
3092			m_freem(m);
3093			goto rx_next;
3094		}
3095
3096		if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
3097			ieee80211_dump_pkt(mtod(m, caddr_t), len,
3098				   sc->sc_hwmap[rs->rs_rate].ieeerate,
3099				   rs->rs_rssi);
3100		}
3101
3102		m_adj(m, -IEEE80211_CRC_LEN);
3103
3104		/*
3105		 * Locate the node for sender, track state, and then
3106		 * pass the (referenced) node up to the 802.11 layer
3107		 * for its use.
3108		 */
3109		ni = ieee80211_find_rxnode_withkey(ic,
3110			mtod(m, const struct ieee80211_frame_min *),
3111			rs->rs_keyix == HAL_RXKEYIX_INVALID ?
3112				IEEE80211_KEYIX_NONE : rs->rs_keyix);
3113		/*
3114		 * Track rx rssi and do any rx antenna management.
3115		 */
3116		an = ATH_NODE(ni);
3117		ATH_RSSI_LPF(an->an_avgrssi, rs->rs_rssi);
3118		ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, rs->rs_rssi);
3119		/*
3120		 * Send frame up for processing.
3121		 */
3122		type = ieee80211_input(ic, m, ni, rs->rs_rssi, rs->rs_tstamp);
3123		ieee80211_free_node(ni);
3124		if (sc->sc_diversity) {
3125			/*
3126			 * When using fast diversity, change the default rx
3127			 * antenna if diversity chooses the other antenna 3
3128			 * times in a row.
3129			 */
3130			if (sc->sc_defant != rs->rs_antenna) {
3131				if (++sc->sc_rxotherant >= 3)
3132					ath_setdefantenna(sc, rs->rs_antenna);
3133			} else
3134				sc->sc_rxotherant = 0;
3135		}
3136		if (sc->sc_softled) {
3137			/*
3138			 * Blink for any data frame.  Otherwise do a
3139			 * heartbeat-style blink when idle.  The latter
3140			 * is mainly for station mode where we depend on
3141			 * periodic beacon frames to trigger the poll event.
3142			 */
3143			if (type == IEEE80211_FC0_TYPE_DATA) {
3144				sc->sc_rxrate = rs->rs_rate;
3145				ath_led_event(sc, ATH_LED_RX);
3146			} else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
3147				ath_led_event(sc, ATH_LED_POLL);
3148		}
3149		/*
3150		 * Arrange to update the last rx timestamp only for
3151		 * frames from our ap when operating in station mode.
3152		 * This assumes the rx key is always setup when associated.
3153		 */
3154		if (ic->ic_opmode == IEEE80211_M_STA &&
3155		    rs->rs_keyix != HAL_RXKEYIX_INVALID)
3156			ngood++;
3157rx_next:
3158		STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
3159	} while (ath_rxbuf_init(sc, bf) == 0);
3160
3161	/* rx signal state monitoring */
3162	ath_hal_rxmonitor(ah, &sc->sc_halstats, &sc->sc_curchan);
3163	if (ngood)
3164		sc->sc_lastrx = tsf;
3165
3166	NET_UNLOCK_GIANT();		/* XXX */
3167#undef PA2DESC
3168}
3169
3170static void
3171ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
3172{
3173	txq->axq_qnum = qnum;
3174	txq->axq_depth = 0;
3175	txq->axq_intrcnt = 0;
3176	txq->axq_link = NULL;
3177	STAILQ_INIT(&txq->axq_q);
3178	ATH_TXQ_LOCK_INIT(sc, txq);
3179}
3180
3181/*
3182 * Setup a h/w transmit queue.
3183 */
3184static struct ath_txq *
3185ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
3186{
3187#define	N(a)	(sizeof(a)/sizeof(a[0]))
3188	struct ath_hal *ah = sc->sc_ah;
3189	HAL_TXQ_INFO qi;
3190	int qnum;
3191
3192	memset(&qi, 0, sizeof(qi));
3193	qi.tqi_subtype = subtype;
3194	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
3195	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
3196	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
3197	/*
3198	 * Enable interrupts only for EOL and DESC conditions.
3199	 * We mark tx descriptors to receive a DESC interrupt
3200	 * when a tx queue gets deep; otherwise waiting for the
3201	 * EOL to reap descriptors.  Note that this is done to
3202	 * reduce interrupt load and this only defers reaping
3203	 * descriptors, never transmitting frames.  Aside from
3204	 * reducing interrupts this also permits more concurrency.
3205	 * The only potential downside is if the tx queue backs
3206	 * up in which case the top half of the kernel may backup
3207	 * due to a lack of tx descriptors.
3208	 */
3209	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
3210	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
3211	if (qnum == -1) {
3212		/*
3213		 * NB: don't print a message, this happens
3214		 * normally on parts with too few tx queues
3215		 */
3216		return NULL;
3217	}
3218	if (qnum >= N(sc->sc_txq)) {
3219		device_printf(sc->sc_dev,
3220			"hal qnum %u out of range, max %zu!\n",
3221			qnum, N(sc->sc_txq));
3222		ath_hal_releasetxqueue(ah, qnum);
3223		return NULL;
3224	}
3225	if (!ATH_TXQ_SETUP(sc, qnum)) {
3226		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
3227		sc->sc_txqsetup |= 1<<qnum;
3228	}
3229	return &sc->sc_txq[qnum];
3230#undef N
3231}
3232
3233/*
3234 * Setup a hardware data transmit queue for the specified
3235 * access control.  The hal may not support all requested
3236 * queues in which case it will return a reference to a
3237 * previously setup queue.  We record the mapping from ac's
3238 * to h/w queues for use by ath_tx_start and also track
3239 * the set of h/w queues being used to optimize work in the
3240 * transmit interrupt handler and related routines.
3241 */
3242static int
3243ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
3244{
3245#define	N(a)	(sizeof(a)/sizeof(a[0]))
3246	struct ath_txq *txq;
3247
3248	if (ac >= N(sc->sc_ac2q)) {
3249		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
3250			ac, N(sc->sc_ac2q));
3251		return 0;
3252	}
3253	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
3254	if (txq != NULL) {
3255		sc->sc_ac2q[ac] = txq;
3256		return 1;
3257	} else
3258		return 0;
3259#undef N
3260}
3261
3262/*
3263 * Update WME parameters for a transmit queue.
3264 */
3265static int
3266ath_txq_update(struct ath_softc *sc, int ac)
3267{
3268#define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
3269#define	ATH_TXOP_TO_US(v)		(v<<5)
3270	struct ieee80211com *ic = &sc->sc_ic;
3271	struct ath_txq *txq = sc->sc_ac2q[ac];
3272	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
3273	struct ath_hal *ah = sc->sc_ah;
3274	HAL_TXQ_INFO qi;
3275
3276	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
3277	qi.tqi_aifs = wmep->wmep_aifsn;
3278	qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
3279	qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
3280	qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
3281
3282	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
3283		device_printf(sc->sc_dev, "unable to update hardware queue "
3284			"parameters for %s traffic!\n",
3285			ieee80211_wme_acnames[ac]);
3286		return 0;
3287	} else {
3288		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
3289		return 1;
3290	}
3291#undef ATH_TXOP_TO_US
3292#undef ATH_EXPONENT_TO_VALUE
3293}
3294
3295/*
3296 * Callback from the 802.11 layer to update WME parameters.
3297 */
3298static int
3299ath_wme_update(struct ieee80211com *ic)
3300{
3301	struct ath_softc *sc = ic->ic_ifp->if_softc;
3302
3303	return !ath_txq_update(sc, WME_AC_BE) ||
3304	    !ath_txq_update(sc, WME_AC_BK) ||
3305	    !ath_txq_update(sc, WME_AC_VI) ||
3306	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
3307}
3308
3309/*
3310 * Reclaim resources for a setup queue.
3311 */
3312static void
3313ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
3314{
3315
3316	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
3317	ATH_TXQ_LOCK_DESTROY(txq);
3318	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
3319}
3320
3321/*
3322 * Reclaim all tx queue resources.
3323 */
3324static void
3325ath_tx_cleanup(struct ath_softc *sc)
3326{
3327	int i;
3328
3329	ATH_TXBUF_LOCK_DESTROY(sc);
3330	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3331		if (ATH_TXQ_SETUP(sc, i))
3332			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
3333	ATH_TXQ_LOCK_DESTROY(&sc->sc_mcastq);
3334}
3335
3336/*
3337 * Defragment an mbuf chain, returning at most maxfrags separate
3338 * mbufs+clusters.  If this is not possible NULL is returned and
3339 * the original mbuf chain is left in it's present (potentially
3340 * modified) state.  We use two techniques: collapsing consecutive
3341 * mbufs and replacing consecutive mbufs by a cluster.
3342 */
3343static struct mbuf *
3344ath_defrag(struct mbuf *m0, int how, int maxfrags)
3345{
3346	struct mbuf *m, *n, *n2, **prev;
3347	u_int curfrags;
3348
3349	/*
3350	 * Calculate the current number of frags.
3351	 */
3352	curfrags = 0;
3353	for (m = m0; m != NULL; m = m->m_next)
3354		curfrags++;
3355	/*
3356	 * First, try to collapse mbufs.  Note that we always collapse
3357	 * towards the front so we don't need to deal with moving the
3358	 * pkthdr.  This may be suboptimal if the first mbuf has much
3359	 * less data than the following.
3360	 */
3361	m = m0;
3362again:
3363	for (;;) {
3364		n = m->m_next;
3365		if (n == NULL)
3366			break;
3367		if ((m->m_flags & M_RDONLY) == 0 &&
3368		    n->m_len < M_TRAILINGSPACE(m)) {
3369			bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
3370				n->m_len);
3371			m->m_len += n->m_len;
3372			m->m_next = n->m_next;
3373			m_free(n);
3374			if (--curfrags <= maxfrags)
3375				return m0;
3376		} else
3377			m = n;
3378	}
3379	KASSERT(maxfrags > 1,
3380		("maxfrags %u, but normal collapse failed", maxfrags));
3381	/*
3382	 * Collapse consecutive mbufs to a cluster.
3383	 */
3384	prev = &m0->m_next;		/* NB: not the first mbuf */
3385	while ((n = *prev) != NULL) {
3386		if ((n2 = n->m_next) != NULL &&
3387		    n->m_len + n2->m_len < MCLBYTES) {
3388			m = m_getcl(how, MT_DATA, 0);
3389			if (m == NULL)
3390				goto bad;
3391			bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
3392			bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
3393				n2->m_len);
3394			m->m_len = n->m_len + n2->m_len;
3395			m->m_next = n2->m_next;
3396			*prev = m;
3397			m_free(n);
3398			m_free(n2);
3399			if (--curfrags <= maxfrags)	/* +1 cl -2 mbufs */
3400				return m0;
3401			/*
3402			 * Still not there, try the normal collapse
3403			 * again before we allocate another cluster.
3404			 */
3405			goto again;
3406		}
3407		prev = &n->m_next;
3408	}
3409	/*
3410	 * No place where we can collapse to a cluster; punt.
3411	 * This can occur if, for example, you request 2 frags
3412	 * but the packet requires that both be clusters (we
3413	 * never reallocate the first mbuf to avoid moving the
3414	 * packet header).
3415	 */
3416bad:
3417	return NULL;
3418}
3419
3420/*
3421 * Return h/w rate index for an IEEE rate (w/o basic rate bit).
3422 */
3423static int
3424ath_tx_findrix(const HAL_RATE_TABLE *rt, int rate)
3425{
3426	int i;
3427
3428	for (i = 0; i < rt->rateCount; i++)
3429		if ((rt->info[i].dot11Rate & IEEE80211_RATE_VAL) == rate)
3430			return i;
3431	return 0;		/* NB: lowest rate */
3432}
3433
3434static int
3435ath_tx_dmasetup(struct ath_softc *sc, struct ath_buf *bf, struct mbuf *m0)
3436{
3437	struct mbuf *m;
3438	int error;
3439
3440	/*
3441	 * Load the DMA map so any coalescing is done.  This
3442	 * also calculates the number of descriptors we need.
3443	 */
3444	error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3445				     bf->bf_segs, &bf->bf_nseg,
3446				     BUS_DMA_NOWAIT);
3447	if (error == EFBIG) {
3448		/* XXX packet requires too many descriptors */
3449		bf->bf_nseg = ATH_TXDESC+1;
3450	} else if (error != 0) {
3451		sc->sc_stats.ast_tx_busdma++;
3452		m_freem(m0);
3453		return error;
3454	}
3455	/*
3456	 * Discard null packets and check for packets that
3457	 * require too many TX descriptors.  We try to convert
3458	 * the latter to a cluster.
3459	 */
3460	if (bf->bf_nseg > ATH_TXDESC) {		/* too many desc's, linearize */
3461		sc->sc_stats.ast_tx_linear++;
3462		m = ath_defrag(m0, M_DONTWAIT, ATH_TXDESC);
3463		if (m == NULL) {
3464			m_freem(m0);
3465			sc->sc_stats.ast_tx_nombuf++;
3466			return ENOMEM;
3467		}
3468		m0 = m;
3469		error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3470					     bf->bf_segs, &bf->bf_nseg,
3471					     BUS_DMA_NOWAIT);
3472		if (error != 0) {
3473			sc->sc_stats.ast_tx_busdma++;
3474			m_freem(m0);
3475			return error;
3476		}
3477		KASSERT(bf->bf_nseg <= ATH_TXDESC,
3478		    ("too many segments after defrag; nseg %u", bf->bf_nseg));
3479	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
3480		sc->sc_stats.ast_tx_nodata++;
3481		m_freem(m0);
3482		return EIO;
3483	}
3484	DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n",
3485		__func__, m0, m0->m_pkthdr.len);
3486	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3487	bf->bf_m = m0;
3488
3489	return 0;
3490}
3491
3492static void
3493ath_tx_handoff(struct ath_softc *sc, struct ath_txq *txq, struct ath_buf *bf)
3494{
3495	struct ath_hal *ah = sc->sc_ah;
3496	struct ath_desc *ds, *ds0;
3497	int i;
3498
3499	/*
3500	 * Fillin the remainder of the descriptor info.
3501	 */
3502	ds0 = ds = bf->bf_desc;
3503	for (i = 0; i < bf->bf_nseg; i++, ds++) {
3504		ds->ds_data = bf->bf_segs[i].ds_addr;
3505		if (i == bf->bf_nseg - 1)
3506			ds->ds_link = 0;
3507		else
3508			ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
3509		ath_hal_filltxdesc(ah, ds
3510			, bf->bf_segs[i].ds_len	/* segment length */
3511			, i == 0		/* first segment */
3512			, i == bf->bf_nseg - 1	/* last segment */
3513			, ds0			/* first descriptor */
3514		);
3515		DPRINTF(sc, ATH_DEBUG_XMIT,
3516			"%s: %d: %08x %08x %08x %08x %08x %08x\n",
3517			__func__, i, ds->ds_link, ds->ds_data,
3518			ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
3519	}
3520	/*
3521	 * Insert the frame on the outbound list and pass it on
3522	 * to the hardware.  Multicast frames buffered for power
3523	 * save stations and transmit from the CAB queue are stored
3524	 * on a s/w only queue and loaded on to the CAB queue in
3525	 * the SWBA handler since frames only go out on DTIM and
3526	 * to avoid possible races.
3527	 */
3528	ATH_TXQ_LOCK(txq);
3529	ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
3530	if (txq != &sc->sc_mcastq) {
3531		if (txq->axq_link == NULL) {
3532			ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
3533			DPRINTF(sc, ATH_DEBUG_XMIT,
3534			    "%s: TXDP[%u] = %p (%p) depth %d\n", __func__,
3535			    txq->axq_qnum, (caddr_t)bf->bf_daddr, bf->bf_desc,
3536			    txq->axq_depth);
3537		} else {
3538			*txq->axq_link = bf->bf_daddr;
3539			DPRINTF(sc, ATH_DEBUG_XMIT,
3540			    "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
3541			    txq->axq_qnum, txq->axq_link,
3542			    (caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
3543		}
3544		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
3545		ath_hal_txstart(ah, txq->axq_qnum);
3546	} else {
3547		if (txq->axq_link != NULL)
3548			*txq->axq_link = bf->bf_daddr;
3549		txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
3550	}
3551	ATH_TXQ_UNLOCK(txq);
3552}
3553
3554static int
3555ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
3556    struct mbuf *m0)
3557{
3558	struct ieee80211com *ic = &sc->sc_ic;
3559	struct ath_hal *ah = sc->sc_ah;
3560	struct ifnet *ifp = sc->sc_ifp;
3561	const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
3562	int error, iswep, ismcast, ismrr;
3563	int keyix, hdrlen, pktlen, try0;
3564	u_int8_t rix, txrate, ctsrate;
3565	u_int8_t cix = 0xff;		/* NB: silence compiler */
3566	struct ath_desc *ds;
3567	struct ath_txq *txq;
3568	struct ieee80211_frame *wh;
3569	u_int subtype, flags, ctsduration;
3570	HAL_PKT_TYPE atype;
3571	const HAL_RATE_TABLE *rt;
3572	HAL_BOOL shortPreamble;
3573	struct ath_node *an;
3574	u_int pri;
3575
3576	wh = mtod(m0, struct ieee80211_frame *);
3577	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
3578	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
3579	hdrlen = ieee80211_anyhdrsize(wh);
3580	/*
3581	 * Packet length must not include any
3582	 * pad bytes; deduct them here.
3583	 */
3584	pktlen = m0->m_pkthdr.len - (hdrlen & 3);
3585
3586	if (iswep) {
3587		const struct ieee80211_cipher *cip;
3588		struct ieee80211_key *k;
3589
3590		/*
3591		 * Construct the 802.11 header+trailer for an encrypted
3592		 * frame. The only reason this can fail is because of an
3593		 * unknown or unsupported cipher/key type.
3594		 */
3595		k = ieee80211_crypto_encap(ic, ni, m0);
3596		if (k == NULL) {
3597			/*
3598			 * This can happen when the key is yanked after the
3599			 * frame was queued.  Just discard the frame; the
3600			 * 802.11 layer counts failures and provides
3601			 * debugging/diagnostics.
3602			 */
3603			m_freem(m0);
3604			return EIO;
3605		}
3606		/*
3607		 * Adjust the packet + header lengths for the crypto
3608		 * additions and calculate the h/w key index.  When
3609		 * a s/w mic is done the frame will have had any mic
3610		 * added to it prior to entry so m0->m_pkthdr.len above will
3611		 * account for it. Otherwise we need to add it to the
3612		 * packet length.
3613		 */
3614		cip = k->wk_cipher;
3615		hdrlen += cip->ic_header;
3616		pktlen += cip->ic_header + cip->ic_trailer;
3617		if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0)
3618			pktlen += cip->ic_miclen;
3619		keyix = k->wk_keyix;
3620
3621		/* packet header may have moved, reset our local pointer */
3622		wh = mtod(m0, struct ieee80211_frame *);
3623	} else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
3624		/*
3625		 * Use station key cache slot, if assigned.
3626		 */
3627		keyix = ni->ni_ucastkey.wk_keyix;
3628		if (keyix == IEEE80211_KEYIX_NONE)
3629			keyix = HAL_TXKEYIX_INVALID;
3630	} else
3631		keyix = HAL_TXKEYIX_INVALID;
3632
3633	pktlen += IEEE80211_CRC_LEN;
3634
3635	/*
3636	 * Load the DMA map so any coalescing is done.  This
3637	 * also calculates the number of descriptors we need.
3638	 */
3639	error = ath_tx_dmasetup(sc, bf, m0);
3640	if (error != 0)
3641		return error;
3642	bf->bf_node = ni;			/* NB: held reference */
3643	m0 = bf->bf_m;				/* NB: may have changed */
3644	wh = mtod(m0, struct ieee80211_frame *);
3645
3646	/* setup descriptors */
3647	ds = bf->bf_desc;
3648	rt = sc->sc_currates;
3649	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
3650
3651	/*
3652	 * NB: the 802.11 layer marks whether or not we should
3653	 * use short preamble based on the current mode and
3654	 * negotiated parameters.
3655	 */
3656	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
3657	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
3658		shortPreamble = AH_TRUE;
3659		sc->sc_stats.ast_tx_shortpre++;
3660	} else {
3661		shortPreamble = AH_FALSE;
3662	}
3663
3664	an = ATH_NODE(ni);
3665	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
3666	ismrr = 0;				/* default no multi-rate retry*/
3667	/*
3668	 * Calculate Atheros packet type from IEEE80211 packet header,
3669	 * setup for rate calculations, and select h/w transmit queue.
3670	 */
3671	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
3672	case IEEE80211_FC0_TYPE_MGT:
3673		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
3674		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
3675			atype = HAL_PKT_TYPE_BEACON;
3676		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
3677			atype = HAL_PKT_TYPE_PROBE_RESP;
3678		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
3679			atype = HAL_PKT_TYPE_ATIM;
3680		else
3681			atype = HAL_PKT_TYPE_NORMAL;	/* XXX */
3682		rix = sc->sc_minrateix;
3683		txrate = rt->info[rix].rateCode;
3684		if (shortPreamble)
3685			txrate |= rt->info[rix].shortPreamble;
3686		try0 = ATH_TXMGTTRY;
3687		/* NB: force all management frames to highest queue */
3688		if (ni->ni_flags & IEEE80211_NODE_QOS) {
3689			/* NB: force all management frames to highest queue */
3690			pri = WME_AC_VO;
3691		} else
3692			pri = WME_AC_BE;
3693		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
3694		break;
3695	case IEEE80211_FC0_TYPE_CTL:
3696		atype = HAL_PKT_TYPE_PSPOLL;	/* stop setting of duration */
3697		rix = sc->sc_minrateix;
3698		txrate = rt->info[rix].rateCode;
3699		if (shortPreamble)
3700			txrate |= rt->info[rix].shortPreamble;
3701		try0 = ATH_TXMGTTRY;
3702		/* NB: force all ctl frames to highest queue */
3703		if (ni->ni_flags & IEEE80211_NODE_QOS) {
3704			/* NB: force all ctl frames to highest queue */
3705			pri = WME_AC_VO;
3706		} else
3707			pri = WME_AC_BE;
3708		flags |= HAL_TXDESC_INTREQ;	/* force interrupt */
3709		break;
3710	case IEEE80211_FC0_TYPE_DATA:
3711		atype = HAL_PKT_TYPE_NORMAL;		/* default */
3712		/*
3713		 * Data frames: multicast frames go out at a fixed rate,
3714		 * otherwise consult the rate control module for the
3715		 * rate to use.
3716		 */
3717		if (ismcast) {
3718			/*
3719			 * Check mcast rate setting in case it's changed.
3720			 * XXX move out of fastpath
3721			 */
3722			if (ic->ic_mcast_rate != sc->sc_mcastrate) {
3723				sc->sc_mcastrix =
3724					ath_tx_findrix(rt, ic->ic_mcast_rate);
3725				sc->sc_mcastrate = ic->ic_mcast_rate;
3726			}
3727			rix = sc->sc_mcastrix;
3728			txrate = rt->info[rix].rateCode;
3729			if (shortPreamble)
3730				txrate |= rt->info[rix].shortPreamble;
3731			try0 = 1;
3732		} else {
3733			ath_rate_findrate(sc, an, shortPreamble, pktlen,
3734				&rix, &try0, &txrate);
3735			sc->sc_txrate = txrate;		/* for LED blinking */
3736			if (try0 != ATH_TXMAXTRY)
3737				ismrr = 1;
3738		}
3739		pri = M_WME_GETAC(m0);
3740		if (cap->cap_wmeParams[pri].wmep_noackPolicy)
3741			flags |= HAL_TXDESC_NOACK;
3742		break;
3743	default:
3744		if_printf(ifp, "bogus frame type 0x%x (%s)\n",
3745			wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
3746		/* XXX statistic */
3747		m_freem(m0);
3748		return EIO;
3749	}
3750	txq = sc->sc_ac2q[pri];
3751
3752	/*
3753	 * When servicing one or more stations in power-save mode
3754	 * (or) if there is some mcast data waiting on the mcast
3755	 * queue (to prevent out of order delivery) multicast
3756	 * frames must be buffered until after the beacon.
3757	 */
3758	if (ismcast && (ic->ic_ps_sta || sc->sc_mcastq.axq_depth)) {
3759		txq = &sc->sc_mcastq;
3760		/* XXX? more bit in 802.11 frame header */
3761	}
3762
3763	/*
3764	 * Calculate miscellaneous flags.
3765	 */
3766	if (ismcast) {
3767		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
3768	} else if (pktlen > ic->ic_rtsthreshold) {
3769		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
3770		cix = rt->info[rix].controlRate;
3771		sc->sc_stats.ast_tx_rts++;
3772	}
3773	if (flags & HAL_TXDESC_NOACK)		/* NB: avoid double counting */
3774		sc->sc_stats.ast_tx_noack++;
3775
3776	/*
3777	 * If 802.11g protection is enabled, determine whether
3778	 * to use RTS/CTS or just CTS.  Note that this is only
3779	 * done for OFDM unicast frames.
3780	 */
3781	if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
3782	    rt->info[rix].phy == IEEE80211_T_OFDM &&
3783	    (flags & HAL_TXDESC_NOACK) == 0) {
3784		/* XXX fragments must use CCK rates w/ protection */
3785		if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
3786			flags |= HAL_TXDESC_RTSENA;
3787		else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
3788			flags |= HAL_TXDESC_CTSENA;
3789		cix = rt->info[sc->sc_protrix].controlRate;
3790		sc->sc_stats.ast_tx_protect++;
3791	}
3792
3793	/*
3794	 * Calculate duration.  This logically belongs in the 802.11
3795	 * layer but it lacks sufficient information to calculate it.
3796	 */
3797	if ((flags & HAL_TXDESC_NOACK) == 0 &&
3798	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
3799		u_int16_t dur;
3800		/*
3801		 * XXX not right with fragmentation.
3802		 */
3803		if (shortPreamble)
3804			dur = rt->info[rix].spAckDuration;
3805		else
3806			dur = rt->info[rix].lpAckDuration;
3807		*(u_int16_t *)wh->i_dur = htole16(dur);
3808	}
3809
3810	/*
3811	 * Calculate RTS/CTS rate and duration if needed.
3812	 */
3813	ctsduration = 0;
3814	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
3815		/*
3816		 * CTS transmit rate is derived from the transmit rate
3817		 * by looking in the h/w rate table.  We must also factor
3818		 * in whether or not a short preamble is to be used.
3819		 */
3820		/* NB: cix is set above where RTS/CTS is enabled */
3821		KASSERT(cix != 0xff, ("cix not setup"));
3822		ctsrate = rt->info[cix].rateCode;
3823		/*
3824		 * Compute the transmit duration based on the frame
3825		 * size and the size of an ACK frame.  We call into the
3826		 * HAL to do the computation since it depends on the
3827		 * characteristics of the actual PHY being used.
3828		 *
3829		 * NB: CTS is assumed the same size as an ACK so we can
3830		 *     use the precalculated ACK durations.
3831		 */
3832		if (shortPreamble) {
3833			ctsrate |= rt->info[cix].shortPreamble;
3834			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
3835				ctsduration += rt->info[cix].spAckDuration;
3836			ctsduration += ath_hal_computetxtime(ah,
3837				rt, pktlen, rix, AH_TRUE);
3838			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
3839				ctsduration += rt->info[rix].spAckDuration;
3840		} else {
3841			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
3842				ctsduration += rt->info[cix].lpAckDuration;
3843			ctsduration += ath_hal_computetxtime(ah,
3844				rt, pktlen, rix, AH_FALSE);
3845			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
3846				ctsduration += rt->info[rix].lpAckDuration;
3847		}
3848		/*
3849		 * Must disable multi-rate retry when using RTS/CTS.
3850		 */
3851		ismrr = 0;
3852		try0 = ATH_TXMGTTRY;		/* XXX */
3853	} else
3854		ctsrate = 0;
3855
3856	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
3857		ieee80211_dump_pkt(mtod(m0, caddr_t), m0->m_len,
3858			sc->sc_hwmap[txrate].ieeerate, -1);
3859
3860	if (bpf_peers_present(ic->ic_rawbpf))
3861		bpf_mtap(ic->ic_rawbpf, m0);
3862	if (bpf_peers_present(sc->sc_drvbpf)) {
3863		u_int64_t tsf = ath_hal_gettsf64(ah);
3864
3865		sc->sc_tx_th.wt_tsf = htole64(tsf);
3866		sc->sc_tx_th.wt_flags = sc->sc_hwmap[txrate].txflags;
3867		if (iswep)
3868			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3869		sc->sc_tx_th.wt_rate = sc->sc_hwmap[txrate].ieeerate;
3870		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
3871		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
3872
3873		bpf_mtap2(sc->sc_drvbpf,
3874			&sc->sc_tx_th, sc->sc_tx_th_len, m0);
3875	}
3876
3877	/*
3878	 * Determine if a tx interrupt should be generated for
3879	 * this descriptor.  We take a tx interrupt to reap
3880	 * descriptors when the h/w hits an EOL condition or
3881	 * when the descriptor is specifically marked to generate
3882	 * an interrupt.  We periodically mark descriptors in this
3883	 * way to insure timely replenishing of the supply needed
3884	 * for sending frames.  Defering interrupts reduces system
3885	 * load and potentially allows more concurrent work to be
3886	 * done but if done to aggressively can cause senders to
3887	 * backup.
3888	 *
3889	 * NB: use >= to deal with sc_txintrperiod changing
3890	 *     dynamically through sysctl.
3891	 */
3892	if (flags & HAL_TXDESC_INTREQ) {
3893		txq->axq_intrcnt = 0;
3894	} else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
3895		flags |= HAL_TXDESC_INTREQ;
3896		txq->axq_intrcnt = 0;
3897	}
3898
3899	/*
3900	 * Formulate first tx descriptor with tx controls.
3901	 */
3902	/* XXX check return value? */
3903	ath_hal_setuptxdesc(ah, ds
3904		, pktlen		/* packet length */
3905		, hdrlen		/* header length */
3906		, atype			/* Atheros packet type */
3907		, ni->ni_txpower	/* txpower */
3908		, txrate, try0		/* series 0 rate/tries */
3909		, keyix			/* key cache index */
3910		, sc->sc_txantenna	/* antenna mode */
3911		, flags			/* flags */
3912		, ctsrate		/* rts/cts rate */
3913		, ctsduration		/* rts/cts duration */
3914	);
3915	bf->bf_flags = flags;
3916	/*
3917	 * Setup the multi-rate retry state only when we're
3918	 * going to use it.  This assumes ath_hal_setuptxdesc
3919	 * initializes the descriptors (so we don't have to)
3920	 * when the hardware supports multi-rate retry and
3921	 * we don't use it.
3922	 */
3923	if (ismrr)
3924		ath_rate_setupxtxdesc(sc, an, ds, shortPreamble, rix);
3925
3926	ath_tx_handoff(sc, txq, bf);
3927	return 0;
3928}
3929
3930/*
3931 * Process completed xmit descriptors from the specified queue.
3932 */
3933static int
3934ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
3935{
3936	struct ath_hal *ah = sc->sc_ah;
3937	struct ieee80211com *ic = &sc->sc_ic;
3938	struct ath_buf *bf;
3939	struct ath_desc *ds, *ds0;
3940	struct ath_tx_status *ts;
3941	struct ieee80211_node *ni;
3942	struct ath_node *an;
3943	int sr, lr, pri, nacked;
3944	HAL_STATUS status;
3945
3946	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
3947		__func__, txq->axq_qnum,
3948		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
3949		txq->axq_link);
3950	nacked = 0;
3951	for (;;) {
3952		ATH_TXQ_LOCK(txq);
3953		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
3954		bf = STAILQ_FIRST(&txq->axq_q);
3955		if (bf == NULL) {
3956			ATH_TXQ_UNLOCK(txq);
3957			break;
3958		}
3959		ds0 = &bf->bf_desc[0];
3960		ds = &bf->bf_desc[bf->bf_nseg - 1];
3961		ts = &bf->bf_status.ds_txstat;
3962		status = ath_hal_txprocdesc(ah, ds, ts);
3963#ifdef ATH_DEBUG
3964		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
3965			ath_printtxbuf(bf, txq->axq_qnum, 0, status == HAL_OK);
3966#endif
3967		if (status == HAL_EINPROGRESS) {
3968			ATH_TXQ_UNLOCK(txq);
3969			break;
3970		}
3971		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
3972		if (txq->axq_depth == 0)
3973			txq->axq_link = NULL;
3974		ATH_TXQ_UNLOCK(txq);
3975
3976		ni = bf->bf_node;
3977		if (ni != NULL) {
3978			an = ATH_NODE(ni);
3979			if (ts->ts_status == 0) {
3980				u_int8_t txant = ts->ts_antenna;
3981				sc->sc_stats.ast_ant_tx[txant]++;
3982				sc->sc_ant_tx[txant]++;
3983				if (ts->ts_rate & HAL_TXSTAT_ALTRATE)
3984					sc->sc_stats.ast_tx_altrate++;
3985				sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
3986				ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
3987					ts->ts_rssi);
3988				pri = M_WME_GETAC(bf->bf_m);
3989				if (pri >= WME_AC_VO)
3990					ic->ic_wme.wme_hipri_traffic++;
3991				ni->ni_inact = ni->ni_inact_reload;
3992			} else {
3993				if (ts->ts_status & HAL_TXERR_XRETRY)
3994					sc->sc_stats.ast_tx_xretries++;
3995				if (ts->ts_status & HAL_TXERR_FIFO)
3996					sc->sc_stats.ast_tx_fifoerr++;
3997				if (ts->ts_status & HAL_TXERR_FILT)
3998					sc->sc_stats.ast_tx_filtered++;
3999			}
4000			sr = ts->ts_shortretry;
4001			lr = ts->ts_longretry;
4002			sc->sc_stats.ast_tx_shortretry += sr;
4003			sc->sc_stats.ast_tx_longretry += lr;
4004			/*
4005			 * Hand the descriptor to the rate control algorithm.
4006			 */
4007			if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
4008			    (bf->bf_flags & HAL_TXDESC_NOACK) == 0) {
4009				/*
4010				 * If frame was ack'd update the last rx time
4011				 * used to workaround phantom bmiss interrupts.
4012				 */
4013				if (ts->ts_status == 0)
4014					nacked++;
4015				ath_rate_tx_complete(sc, an, bf);
4016			}
4017			/*
4018			 * Reclaim reference to node.
4019			 *
4020			 * NB: the node may be reclaimed here if, for example
4021			 *     this is a DEAUTH message that was sent and the
4022			 *     node was timed out due to inactivity.
4023			 */
4024			ieee80211_free_node(ni);
4025		}
4026		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4027		    BUS_DMASYNC_POSTWRITE);
4028		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4029		m_freem(bf->bf_m);
4030		bf->bf_m = NULL;
4031		bf->bf_node = NULL;
4032
4033		ATH_TXBUF_LOCK(sc);
4034		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4035		ATH_TXBUF_UNLOCK(sc);
4036	}
4037	return nacked;
4038}
4039
4040static __inline int
4041txqactive(struct ath_hal *ah, int qnum)
4042{
4043	u_int32_t txqs = 1<<qnum;
4044	ath_hal_gettxintrtxqs(ah, &txqs);
4045	return (txqs & (1<<qnum));
4046}
4047
4048/*
4049 * Deferred processing of transmit interrupt; special-cased
4050 * for a single hardware transmit queue (e.g. 5210 and 5211).
4051 */
4052static void
4053ath_tx_proc_q0(void *arg, int npending)
4054{
4055	struct ath_softc *sc = arg;
4056	struct ifnet *ifp = sc->sc_ifp;
4057
4058	if (txqactive(sc->sc_ah, 0) && ath_tx_processq(sc, &sc->sc_txq[0]))
4059		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4060	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
4061		ath_tx_processq(sc, sc->sc_cabq);
4062	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4063	sc->sc_tx_timer = 0;
4064
4065	if (sc->sc_softled)
4066		ath_led_event(sc, ATH_LED_TX);
4067
4068	ath_start(ifp);
4069}
4070
4071/*
4072 * Deferred processing of transmit interrupt; special-cased
4073 * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
4074 */
4075static void
4076ath_tx_proc_q0123(void *arg, int npending)
4077{
4078	struct ath_softc *sc = arg;
4079	struct ifnet *ifp = sc->sc_ifp;
4080	int nacked;
4081
4082	/*
4083	 * Process each active queue.
4084	 */
4085	nacked = 0;
4086	if (txqactive(sc->sc_ah, 0))
4087		nacked += ath_tx_processq(sc, &sc->sc_txq[0]);
4088	if (txqactive(sc->sc_ah, 1))
4089		nacked += ath_tx_processq(sc, &sc->sc_txq[1]);
4090	if (txqactive(sc->sc_ah, 2))
4091		nacked += ath_tx_processq(sc, &sc->sc_txq[2]);
4092	if (txqactive(sc->sc_ah, 3))
4093		nacked += ath_tx_processq(sc, &sc->sc_txq[3]);
4094	if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
4095		ath_tx_processq(sc, sc->sc_cabq);
4096	if (nacked)
4097		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4098
4099	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4100	sc->sc_tx_timer = 0;
4101
4102	if (sc->sc_softled)
4103		ath_led_event(sc, ATH_LED_TX);
4104
4105	ath_start(ifp);
4106}
4107
4108/*
4109 * Deferred processing of transmit interrupt.
4110 */
4111static void
4112ath_tx_proc(void *arg, int npending)
4113{
4114	struct ath_softc *sc = arg;
4115	struct ifnet *ifp = sc->sc_ifp;
4116	int i, nacked;
4117
4118	/*
4119	 * Process each active queue.
4120	 */
4121	nacked = 0;
4122	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4123		if (ATH_TXQ_SETUP(sc, i) && txqactive(sc->sc_ah, i))
4124			nacked += ath_tx_processq(sc, &sc->sc_txq[i]);
4125	if (nacked)
4126		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4127
4128	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4129	sc->sc_tx_timer = 0;
4130
4131	if (sc->sc_softled)
4132		ath_led_event(sc, ATH_LED_TX);
4133
4134	ath_start(ifp);
4135}
4136
4137static void
4138ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
4139{
4140#ifdef ATH_DEBUG
4141	struct ath_hal *ah = sc->sc_ah;
4142#endif
4143	struct ieee80211_node *ni;
4144	struct ath_buf *bf;
4145	u_int ix;
4146
4147	/*
4148	 * NB: this assumes output has been stopped and
4149	 *     we do not need to block ath_tx_tasklet
4150	 */
4151	for (ix = 0;; ix++) {
4152		ATH_TXQ_LOCK(txq);
4153		bf = STAILQ_FIRST(&txq->axq_q);
4154		if (bf == NULL) {
4155			txq->axq_link = NULL;
4156			ATH_TXQ_UNLOCK(txq);
4157			break;
4158		}
4159		ATH_TXQ_REMOVE_HEAD(txq, bf_list);
4160		ATH_TXQ_UNLOCK(txq);
4161#ifdef ATH_DEBUG
4162		if (sc->sc_debug & ATH_DEBUG_RESET) {
4163			ath_printtxbuf(bf, txq->axq_qnum, ix,
4164				ath_hal_txprocdesc(ah, bf->bf_desc,
4165				    &bf->bf_status.ds_txstat) == HAL_OK);
4166			ieee80211_dump_pkt(mtod(bf->bf_m, caddr_t),
4167				bf->bf_m->m_len, 0, -1);
4168		}
4169#endif /* ATH_DEBUG */
4170		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4171		m_freem(bf->bf_m);
4172		bf->bf_m = NULL;
4173		ni = bf->bf_node;
4174		bf->bf_node = NULL;
4175		if (ni != NULL) {
4176			/*
4177			 * Reclaim node reference.
4178			 */
4179			ieee80211_free_node(ni);
4180		}
4181		ATH_TXBUF_LOCK(sc);
4182		STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4183		ATH_TXBUF_UNLOCK(sc);
4184	}
4185}
4186
4187static void
4188ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
4189{
4190	struct ath_hal *ah = sc->sc_ah;
4191
4192	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4193	    __func__, txq->axq_qnum,
4194	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
4195	    txq->axq_link);
4196	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
4197}
4198
4199/*
4200 * Drain the transmit queues and reclaim resources.
4201 */
4202static void
4203ath_draintxq(struct ath_softc *sc)
4204{
4205	struct ath_hal *ah = sc->sc_ah;
4206	struct ifnet *ifp = sc->sc_ifp;
4207	int i;
4208
4209	/* XXX return value */
4210	if (!sc->sc_invalid) {
4211		/* don't touch the hardware if marked invalid */
4212		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4213		    __func__, sc->sc_bhalq,
4214		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
4215		    NULL);
4216		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
4217		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4218			if (ATH_TXQ_SETUP(sc, i))
4219				ath_tx_stopdma(sc, &sc->sc_txq[i]);
4220	}
4221	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4222		if (ATH_TXQ_SETUP(sc, i))
4223			ath_tx_draintxq(sc, &sc->sc_txq[i]);
4224	ath_tx_draintxq(sc, &sc->sc_mcastq);
4225#ifdef ATH_DEBUG
4226	if (sc->sc_debug & ATH_DEBUG_RESET) {
4227		struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
4228		if (bf != NULL && bf->bf_m != NULL) {
4229			ath_printtxbuf(bf, sc->sc_bhalq, 0,
4230				ath_hal_txprocdesc(ah, bf->bf_desc,
4231				    &bf->bf_status.ds_txstat) == HAL_OK);
4232			ieee80211_dump_pkt(mtod(bf->bf_m, caddr_t),
4233				bf->bf_m->m_len, 0, -1);
4234		}
4235	}
4236#endif /* ATH_DEBUG */
4237	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4238	sc->sc_tx_timer = 0;
4239}
4240
4241/*
4242 * Disable the receive h/w in preparation for a reset.
4243 */
4244static void
4245ath_stoprecv(struct ath_softc *sc)
4246{
4247#define	PA2DESC(_sc, _pa) \
4248	((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
4249		((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
4250	struct ath_hal *ah = sc->sc_ah;
4251
4252	ath_hal_stoppcurecv(ah);	/* disable PCU */
4253	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
4254	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
4255	DELAY(3000);			/* 3ms is long enough for 1 frame */
4256#ifdef ATH_DEBUG
4257	if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
4258		struct ath_buf *bf;
4259		u_int ix;
4260
4261		printf("%s: rx queue %p, link %p\n", __func__,
4262			(caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
4263		ix = 0;
4264		STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4265			struct ath_desc *ds = bf->bf_desc;
4266			struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
4267			HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
4268				bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
4269			if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
4270				ath_printrxbuf(bf, ix, status == HAL_OK);
4271			ix++;
4272		}
4273	}
4274#endif
4275	sc->sc_rxlink = NULL;		/* just in case */
4276#undef PA2DESC
4277}
4278
4279/*
4280 * Enable the receive h/w following a reset.
4281 */
4282static int
4283ath_startrecv(struct ath_softc *sc)
4284{
4285	struct ath_hal *ah = sc->sc_ah;
4286	struct ath_buf *bf;
4287
4288	sc->sc_rxlink = NULL;
4289	STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
4290		int error = ath_rxbuf_init(sc, bf);
4291		if (error != 0) {
4292			DPRINTF(sc, ATH_DEBUG_RECV,
4293				"%s: ath_rxbuf_init failed %d\n",
4294				__func__, error);
4295			return error;
4296		}
4297	}
4298
4299	bf = STAILQ_FIRST(&sc->sc_rxbuf);
4300	ath_hal_putrxbuf(ah, bf->bf_daddr);
4301	ath_hal_rxena(ah);		/* enable recv descriptors */
4302	ath_mode_init(sc);		/* set filters, etc. */
4303	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
4304	return 0;
4305}
4306
4307/*
4308 * Update internal state after a channel change.
4309 */
4310static void
4311ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
4312{
4313	struct ieee80211com *ic = &sc->sc_ic;
4314	enum ieee80211_phymode mode;
4315	u_int16_t flags;
4316
4317	/*
4318	 * Change channels and update the h/w rate map
4319	 * if we're switching; e.g. 11a to 11b/g.
4320	 */
4321	mode = ieee80211_chan2mode(ic, chan);
4322	if (mode == IEEE80211_MODE_11A) {
4323		if (IEEE80211_IS_CHAN_HALF(chan))
4324			mode = IEEE80211_MODE_11A_HALF;
4325		else if (IEEE80211_IS_CHAN_QUARTER(chan))
4326			mode = IEEE80211_MODE_11A_QUARTER;
4327	}
4328	if (mode != sc->sc_curmode)
4329		ath_setcurmode(sc, mode);
4330	/*
4331	 * Update BPF state.  NB: ethereal et. al. don't handle
4332	 * merged flags well so pick a unique mode for their use.
4333	 */
4334	if (IEEE80211_IS_CHAN_A(chan))
4335		flags = IEEE80211_CHAN_A;
4336	/* XXX 11g schizophrenia */
4337	else if (IEEE80211_IS_CHAN_ANYG(chan))
4338		flags = IEEE80211_CHAN_G;
4339	else
4340		flags = IEEE80211_CHAN_B;
4341	if (IEEE80211_IS_CHAN_T(chan))
4342		flags |= IEEE80211_CHAN_TURBO;
4343	sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq =
4344		htole16(chan->ic_freq);
4345	sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags =
4346		htole16(flags);
4347}
4348
4349/*
4350 * Poll for a channel clear indication; this is required
4351 * for channels requiring DFS and not previously visited
4352 * and/or with a recent radar detection.
4353 */
4354static void
4355ath_dfswait(void *arg)
4356{
4357	struct ath_softc *sc = arg;
4358	struct ath_hal *ah = sc->sc_ah;
4359	HAL_CHANNEL hchan;
4360
4361	ath_hal_radar_wait(ah, &hchan);
4362	DPRINTF(sc, ATH_DEBUG_DFS, "%s: radar_wait %u/%x/%x\n",
4363	    __func__, hchan.channel, hchan.channelFlags, hchan.privFlags);
4364
4365	if (hchan.privFlags & CHANNEL_INTERFERENCE) {
4366		if_printf(sc->sc_ifp,
4367		    "channel %u/0x%x/0x%x has interference\n",
4368		    hchan.channel, hchan.channelFlags, hchan.privFlags);
4369		return;
4370	}
4371	if ((hchan.privFlags & CHANNEL_DFS) == 0) {
4372		/* XXX should not happen */
4373		return;
4374	}
4375	if (hchan.privFlags & CHANNEL_DFS_CLEAR) {
4376		sc->sc_curchan.privFlags |= CHANNEL_DFS_CLEAR;
4377		sc->sc_ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4378		if_printf(sc->sc_ifp,
4379		    "channel %u/0x%x/0x%x marked clear\n",
4380		    hchan.channel, hchan.channelFlags, hchan.privFlags);
4381	} else
4382		callout_reset(&sc->sc_dfs_ch, 2 * hz, ath_dfswait, sc);
4383}
4384
4385/*
4386 * Set/change channels.  If the channel is really being changed,
4387 * it's done by reseting the chip.  To accomplish this we must
4388 * first cleanup any pending DMA, then restart stuff after a la
4389 * ath_init.
4390 */
4391static int
4392ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
4393{
4394	struct ath_hal *ah = sc->sc_ah;
4395	struct ieee80211com *ic = &sc->sc_ic;
4396	HAL_CHANNEL hchan;
4397
4398	/*
4399	 * Convert to a HAL channel description with
4400	 * the flags constrained to reflect the current
4401	 * operating mode.
4402	 */
4403	hchan.channel = chan->ic_freq;
4404	hchan.channelFlags = ath_chan2flags(ic, chan);
4405
4406	DPRINTF(sc, ATH_DEBUG_RESET,
4407	    "%s: %u (%u MHz, hal flags 0x%x) -> %u (%u MHz, hal flags 0x%x)\n",
4408	    __func__,
4409	    ath_hal_mhz2ieee(ah, sc->sc_curchan.channel,
4410		sc->sc_curchan.channelFlags),
4411	    	sc->sc_curchan.channel, sc->sc_curchan.channelFlags,
4412	    ath_hal_mhz2ieee(ah, hchan.channel, hchan.channelFlags),
4413	        hchan.channel, hchan.channelFlags);
4414	if (hchan.channel != sc->sc_curchan.channel ||
4415	    hchan.channelFlags != sc->sc_curchan.channelFlags) {
4416		HAL_STATUS status;
4417
4418		/*
4419		 * To switch channels clear any pending DMA operations;
4420		 * wait long enough for the RX fifo to drain, reset the
4421		 * hardware at the new frequency, and then re-enable
4422		 * the relevant bits of the h/w.
4423		 */
4424		ath_hal_intrset(ah, 0);		/* disable interrupts */
4425		ath_draintxq(sc);		/* clear pending tx frames */
4426		ath_stoprecv(sc);		/* turn off frame recv */
4427		if (!ath_hal_reset(ah, sc->sc_opmode, &hchan, AH_TRUE, &status)) {
4428			if_printf(ic->ic_ifp, "%s: unable to reset "
4429			    "channel %u (%u Mhz, flags 0x%x hal flags 0x%x)\n",
4430			    __func__, ieee80211_chan2ieee(ic, chan),
4431			    chan->ic_freq, chan->ic_flags, hchan.channelFlags);
4432			return EIO;
4433		}
4434		sc->sc_curchan = hchan;
4435		ath_update_txpow(sc);		/* update tx power state */
4436		sc->sc_diversity = ath_hal_getdiversity(ah);
4437		sc->sc_calinterval = 1;
4438		sc->sc_caltries = 0;
4439
4440		/*
4441		 * Re-enable rx framework.
4442		 */
4443		if (ath_startrecv(sc) != 0) {
4444			if_printf(ic->ic_ifp,
4445				"%s: unable to restart recv logic\n", __func__);
4446			return EIO;
4447		}
4448
4449		/*
4450		 * Change channels and update the h/w rate map
4451		 * if we're switching; e.g. 11a to 11b/g.
4452		 */
4453		ic->ic_ibss_chan = chan;
4454		ath_chan_change(sc, chan);
4455
4456		/*
4457		 * Handle DFS required waiting period to determine
4458		 * if channel is clear of radar traffic.
4459		 */
4460		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
4461#define	DFS_AND_NOT_CLEAR(_c) \
4462	(((_c)->privFlags & (CHANNEL_DFS | CHANNEL_DFS_CLEAR)) == CHANNEL_DFS)
4463			if (DFS_AND_NOT_CLEAR(&sc->sc_curchan)) {
4464				if_printf(sc->sc_ifp,
4465					"wait for DFS clear channel signal\n");
4466				/* XXX stop sndq */
4467				sc->sc_ifp->if_drv_flags |= IFF_DRV_OACTIVE;
4468				callout_reset(&sc->sc_dfs_ch,
4469					2 * hz, ath_dfswait, sc);
4470			} else
4471				callout_stop(&sc->sc_dfs_ch);
4472#undef DFS_NOT_CLEAR
4473		}
4474
4475		/*
4476		 * Re-enable interrupts.
4477		 */
4478		ath_hal_intrset(ah, sc->sc_imask);
4479	}
4480	return 0;
4481}
4482
4483static void
4484ath_next_scan(void *arg)
4485{
4486	struct ath_softc *sc = arg;
4487	struct ieee80211com *ic = &sc->sc_ic;
4488
4489	if (ic->ic_state == IEEE80211_S_SCAN)
4490		ieee80211_next_scan(ic);
4491}
4492
4493/*
4494 * Periodically recalibrate the PHY to account
4495 * for temperature/environment changes.
4496 */
4497static void
4498ath_calibrate(void *arg)
4499{
4500	struct ath_softc *sc = arg;
4501	struct ath_hal *ah = sc->sc_ah;
4502	HAL_BOOL iqCalDone;
4503
4504	sc->sc_stats.ast_per_cal++;
4505
4506	if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
4507		/*
4508		 * Rfgain is out of bounds, reset the chip
4509		 * to load new gain values.
4510		 */
4511		DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4512			"%s: rfgain change\n", __func__);
4513		sc->sc_stats.ast_per_rfgain++;
4514		ath_reset(sc->sc_ifp);
4515	}
4516	if (!ath_hal_calibrate(ah, &sc->sc_curchan, &iqCalDone)) {
4517		DPRINTF(sc, ATH_DEBUG_ANY,
4518			"%s: calibration of channel %u failed\n",
4519			__func__, sc->sc_curchan.channel);
4520		sc->sc_stats.ast_per_calfail++;
4521	}
4522	/*
4523	 * Calibrate noise floor data again in case of change.
4524	 */
4525	ath_hal_process_noisefloor(ah);
4526	/*
4527	 * Poll more frequently when the IQ calibration is in
4528	 * progress to speedup loading the final settings.
4529	 * We temper this aggressive polling with an exponential
4530	 * back off after 4 tries up to ath_calinterval.
4531	 */
4532	if (iqCalDone || sc->sc_calinterval >= ath_calinterval) {
4533		sc->sc_caltries = 0;
4534		sc->sc_calinterval = ath_calinterval;
4535	} else if (sc->sc_caltries > 4) {
4536		sc->sc_caltries = 0;
4537		sc->sc_calinterval <<= 1;
4538		if (sc->sc_calinterval > ath_calinterval)
4539			sc->sc_calinterval = ath_calinterval;
4540	}
4541	KASSERT(0 < sc->sc_calinterval && sc->sc_calinterval <= ath_calinterval,
4542		("bad calibration interval %u", sc->sc_calinterval));
4543
4544	DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4545		"%s: next +%u (%siqCalDone tries %u)\n", __func__,
4546		sc->sc_calinterval, iqCalDone ? "" : "!", sc->sc_caltries);
4547	sc->sc_caltries++;
4548	callout_reset(&sc->sc_cal_ch, sc->sc_calinterval * hz,
4549		ath_calibrate, sc);
4550}
4551
4552static int
4553ath_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
4554{
4555	struct ifnet *ifp = ic->ic_ifp;
4556	struct ath_softc *sc = ifp->if_softc;
4557	struct ath_hal *ah = sc->sc_ah;
4558	struct ieee80211_node *ni;
4559	int i, error;
4560	const u_int8_t *bssid;
4561	u_int32_t rfilt;
4562	static const HAL_LED_STATE leds[] = {
4563	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
4564	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
4565	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
4566	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
4567	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
4568	};
4569
4570	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
4571		ieee80211_state_name[ic->ic_state],
4572		ieee80211_state_name[nstate]);
4573
4574	callout_stop(&sc->sc_scan_ch);
4575	callout_stop(&sc->sc_cal_ch);
4576	callout_stop(&sc->sc_dfs_ch);
4577	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
4578
4579	if (nstate == IEEE80211_S_INIT) {
4580		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4581		/*
4582		 * NB: disable interrupts so we don't rx frames.
4583		 */
4584		ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
4585		/*
4586		 * Notify the rate control algorithm.
4587		 */
4588		ath_rate_newstate(sc, nstate);
4589		goto done;
4590	}
4591	ni = ic->ic_bss;
4592	error = ath_chan_set(sc, ic->ic_curchan);
4593	if (error != 0)
4594		goto bad;
4595	rfilt = ath_calcrxfilter(sc, nstate);
4596	if (nstate == IEEE80211_S_SCAN)
4597		bssid = ifp->if_broadcastaddr;
4598	else
4599		bssid = ni->ni_bssid;
4600	ath_hal_setrxfilter(ah, rfilt);
4601	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s\n",
4602		 __func__, rfilt, ether_sprintf(bssid));
4603
4604	if (nstate == IEEE80211_S_RUN && ic->ic_opmode == IEEE80211_M_STA)
4605		ath_hal_setassocid(ah, bssid, ni->ni_associd);
4606	else
4607		ath_hal_setassocid(ah, bssid, 0);
4608	if (ic->ic_flags & IEEE80211_F_PRIVACY) {
4609		for (i = 0; i < IEEE80211_WEP_NKID; i++)
4610			if (ath_hal_keyisvalid(ah, i))
4611				ath_hal_keysetmac(ah, i, bssid);
4612	}
4613
4614	/*
4615	 * Notify the rate control algorithm so rates
4616	 * are setup should ath_beacon_alloc be called.
4617	 */
4618	ath_rate_newstate(sc, nstate);
4619
4620	if (ic->ic_opmode == IEEE80211_M_MONITOR) {
4621		/* nothing to do */;
4622	} else if (nstate == IEEE80211_S_RUN) {
4623		DPRINTF(sc, ATH_DEBUG_STATE,
4624			"%s(RUN): ic_flags=0x%08x iv=%d bssid=%s "
4625			"capinfo=0x%04x chan=%d\n"
4626			 , __func__
4627			 , ic->ic_flags
4628			 , ni->ni_intval
4629			 , ether_sprintf(ni->ni_bssid)
4630			 , ni->ni_capinfo
4631			 , ieee80211_chan2ieee(ic, ic->ic_curchan));
4632
4633		switch (ic->ic_opmode) {
4634		case IEEE80211_M_HOSTAP:
4635		case IEEE80211_M_IBSS:
4636			/*
4637			 * Allocate and setup the beacon frame.
4638			 *
4639			 * Stop any previous beacon DMA.  This may be
4640			 * necessary, for example, when an ibss merge
4641			 * causes reconfiguration; there will be a state
4642			 * transition from RUN->RUN that means we may
4643			 * be called with beacon transmission active.
4644			 */
4645			ath_hal_stoptxdma(ah, sc->sc_bhalq);
4646			ath_beacon_free(sc);
4647			error = ath_beacon_alloc(sc, ni);
4648			if (error != 0)
4649				goto bad;
4650			/*
4651			 * If joining an adhoc network defer beacon timer
4652			 * configuration to the next beacon frame so we
4653			 * have a current TSF to use.  Otherwise we're
4654			 * starting an ibss/bss so there's no need to delay.
4655			 */
4656			if (ic->ic_opmode == IEEE80211_M_IBSS &&
4657			    ic->ic_bss->ni_tstamp.tsf != 0)
4658				sc->sc_syncbeacon = 1;
4659			else
4660				ath_beacon_config(sc);
4661			break;
4662		case IEEE80211_M_STA:
4663			/*
4664			 * Allocate a key cache slot to the station.
4665			 */
4666			if ((ic->ic_flags & IEEE80211_F_PRIVACY) == 0 &&
4667			    sc->sc_hasclrkey &&
4668			    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
4669				ath_setup_stationkey(ni);
4670			/*
4671			 * Defer beacon timer configuration to the next
4672			 * beacon frame so we have a current TSF to use
4673			 * (any TSF collected when scanning is likely old).
4674			 */
4675			sc->sc_syncbeacon = 1;
4676			break;
4677		default:
4678			break;
4679		}
4680
4681		/*
4682		 * Let the hal process statistics collected during a
4683		 * scan so it can provide calibrated noise floor data.
4684		 */
4685		ath_hal_process_noisefloor(ah);
4686		/*
4687		 * Reset rssi stats; maybe not the best place...
4688		 */
4689		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
4690		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
4691		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
4692	} else {
4693		ath_hal_intrset(ah,
4694			sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
4695		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4696	}
4697done:
4698	/*
4699	 * Invoke the parent method to complete the work.
4700	 */
4701	error = sc->sc_newstate(ic, nstate, arg);
4702	/*
4703	 * Finally, start any timers.
4704	 */
4705	if (nstate == IEEE80211_S_RUN) {
4706		/* start periodic recalibration timer */
4707		callout_reset(&sc->sc_cal_ch, sc->sc_calinterval * hz,
4708			ath_calibrate, sc);
4709	} else if (nstate == IEEE80211_S_SCAN) {
4710		/* start ap/neighbor scan timer */
4711		callout_reset(&sc->sc_scan_ch, (ath_dwelltime * hz) / 1000,
4712			ath_next_scan, sc);
4713	}
4714bad:
4715	return error;
4716}
4717
4718/*
4719 * Allocate a key cache slot to the station so we can
4720 * setup a mapping from key index to node. The key cache
4721 * slot is needed for managing antenna state and for
4722 * compression when stations do not use crypto.  We do
4723 * it uniliaterally here; if crypto is employed this slot
4724 * will be reassigned.
4725 */
4726static void
4727ath_setup_stationkey(struct ieee80211_node *ni)
4728{
4729	struct ieee80211com *ic = ni->ni_ic;
4730	struct ath_softc *sc = ic->ic_ifp->if_softc;
4731	ieee80211_keyix keyix, rxkeyix;
4732
4733	if (!ath_key_alloc(ic, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
4734		/*
4735		 * Key cache is full; we'll fall back to doing
4736		 * the more expensive lookup in software.  Note
4737		 * this also means no h/w compression.
4738		 */
4739		/* XXX msg+statistic */
4740	} else {
4741		/* XXX locking? */
4742		ni->ni_ucastkey.wk_keyix = keyix;
4743		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
4744		/* NB: this will create a pass-thru key entry */
4745		ath_keyset(sc, &ni->ni_ucastkey, ni->ni_macaddr, ic->ic_bss);
4746	}
4747}
4748
4749/*
4750 * Setup driver-specific state for a newly associated node.
4751 * Note that we're called also on a re-associate, the isnew
4752 * param tells us if this is the first time or not.
4753 */
4754static void
4755ath_newassoc(struct ieee80211_node *ni, int isnew)
4756{
4757	struct ieee80211com *ic = ni->ni_ic;
4758	struct ath_softc *sc = ic->ic_ifp->if_softc;
4759
4760	ath_rate_newassoc(sc, ATH_NODE(ni), isnew);
4761	if (isnew &&
4762	    (ic->ic_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey) {
4763		KASSERT(ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE,
4764		    ("new assoc with a unicast key already setup (keyix %u)",
4765		    ni->ni_ucastkey.wk_keyix));
4766		ath_setup_stationkey(ni);
4767	}
4768}
4769
4770static int
4771ath_getchannels(struct ath_softc *sc,
4772    HAL_REG_DOMAIN rd, HAL_CTRY_CODE cc, HAL_BOOL outdoor, HAL_BOOL xchanmode)
4773{
4774#define	COMPAT \
4775	(CHANNEL_ALL_NOTURBO|CHANNEL_PASSIVE|CHANNEL_HALF|CHANNEL_QUARTER)
4776#define IS_CHAN_PUBLIC_SAFETY(_c) \
4777	(((_c)->channelFlags & CHANNEL_5GHZ) && \
4778	 ((_c)->channel > 4940 && (_c)->channel < 4990))
4779	struct ieee80211com *ic = &sc->sc_ic;
4780	struct ifnet *ifp = sc->sc_ifp;
4781	struct ath_hal *ah = sc->sc_ah;
4782	HAL_CHANNEL *chans;
4783	int i, ix, nchan;
4784	u_int32_t regdomain;
4785
4786	chans = malloc(IEEE80211_CHAN_MAX * sizeof(HAL_CHANNEL),
4787			M_TEMP, M_NOWAIT);
4788	if (chans == NULL) {
4789		if_printf(ifp, "unable to allocate channel table\n");
4790		return ENOMEM;
4791	}
4792	if (!ath_hal_init_channels(ah, chans, IEEE80211_CHAN_MAX, &nchan,
4793	    NULL, 0, NULL, cc, HAL_MODE_ALL, outdoor, xchanmode)) {
4794		ath_hal_getregdomain(ah, &regdomain);
4795		if_printf(ifp, "unable to collect channel list from hal; "
4796			"regdomain likely %u country code %u\n", regdomain, cc);
4797		free(chans, M_TEMP);
4798		return EINVAL;
4799	}
4800
4801	/*
4802	 * Convert HAL channels to ieee80211 ones and insert
4803	 * them in the table according to their channel number.
4804	 */
4805	memset(ic->ic_channels, 0, sizeof(ic->ic_channels));
4806	for (i = 0; i < nchan; i++) {
4807		HAL_CHANNEL *c = &chans[i];
4808		u_int16_t flags;
4809
4810		/*
4811		 * XXX we're not ready to handle the ieee number mapping
4812		 * for public safety channels as they overlap with any
4813		 * 2GHz channels; for now use a non-public safety
4814		 * numbering that is non-overlapping.
4815		 */
4816		ix = ath_hal_mhz2ieee(ah, c->channel, c->channelFlags);
4817		if (IS_CHAN_PUBLIC_SAFETY(c))
4818			ix += 37;		/* XXX */
4819		if (ix > IEEE80211_CHAN_MAX) {
4820			if_printf(ifp, "bad hal channel %d (%u/%x) ignored\n",
4821				ix, c->channel, c->channelFlags);
4822			continue;
4823		}
4824		if (ix < 0) {
4825			/* XXX can't handle stuff <2400 right now */
4826			if (bootverbose)
4827				if_printf(ifp, "hal channel %d (%u/%x) "
4828				    "cannot be handled; ignored\n",
4829				    ix, c->channel, c->channelFlags);
4830			continue;
4831		}
4832		/*
4833		 * Calculate net80211 flags; most are compatible
4834		 * but some need massaging.  Note the static turbo
4835		 * conversion can be removed once net80211 is updated
4836		 * to understand static vs. dynamic turbo.
4837		 */
4838		flags = c->channelFlags & COMPAT;
4839		if (c->channelFlags & CHANNEL_STURBO)
4840			flags |= IEEE80211_CHAN_TURBO;
4841		if (ic->ic_channels[ix].ic_freq == 0) {
4842			ic->ic_channels[ix].ic_freq = c->channel;
4843			ic->ic_channels[ix].ic_flags = flags;
4844		} else {
4845			/* channels overlap; e.g. 11g and 11b */
4846			ic->ic_channels[ix].ic_flags |= flags;
4847		}
4848	}
4849	free(chans, M_TEMP);
4850	ath_hal_getregdomain(ah, &sc->sc_regdomain);
4851	ath_hal_getcountrycode(ah, &sc->sc_countrycode);
4852	sc->sc_xchanmode = xchanmode;
4853	sc->sc_outdoor = outdoor;
4854	return 0;
4855#undef IS_CHAN_PUBLIC_SAFETY
4856#undef COMPAT
4857}
4858
4859static void
4860ath_led_done(void *arg)
4861{
4862	struct ath_softc *sc = arg;
4863
4864	sc->sc_blinking = 0;
4865}
4866
4867/*
4868 * Turn the LED off: flip the pin and then set a timer so no
4869 * update will happen for the specified duration.
4870 */
4871static void
4872ath_led_off(void *arg)
4873{
4874	struct ath_softc *sc = arg;
4875
4876	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
4877	callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
4878}
4879
4880/*
4881 * Blink the LED according to the specified on/off times.
4882 */
4883static void
4884ath_led_blink(struct ath_softc *sc, int on, int off)
4885{
4886	DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
4887	ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
4888	sc->sc_blinking = 1;
4889	sc->sc_ledoff = off;
4890	callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
4891}
4892
4893static void
4894ath_led_event(struct ath_softc *sc, int event)
4895{
4896
4897	sc->sc_ledevent = ticks;	/* time of last event */
4898	if (sc->sc_blinking)		/* don't interrupt active blink */
4899		return;
4900	switch (event) {
4901	case ATH_LED_POLL:
4902		ath_led_blink(sc, sc->sc_hwmap[0].ledon,
4903			sc->sc_hwmap[0].ledoff);
4904		break;
4905	case ATH_LED_TX:
4906		ath_led_blink(sc, sc->sc_hwmap[sc->sc_txrate].ledon,
4907			sc->sc_hwmap[sc->sc_txrate].ledoff);
4908		break;
4909	case ATH_LED_RX:
4910		ath_led_blink(sc, sc->sc_hwmap[sc->sc_rxrate].ledon,
4911			sc->sc_hwmap[sc->sc_rxrate].ledoff);
4912		break;
4913	}
4914}
4915
4916static void
4917ath_update_txpow(struct ath_softc *sc)
4918{
4919	struct ieee80211com *ic = &sc->sc_ic;
4920	struct ath_hal *ah = sc->sc_ah;
4921	u_int32_t txpow;
4922
4923	if (sc->sc_curtxpow != ic->ic_txpowlimit) {
4924		ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
4925		/* read back in case value is clamped */
4926		ath_hal_gettxpowlimit(ah, &txpow);
4927		ic->ic_txpowlimit = sc->sc_curtxpow = txpow;
4928	}
4929	/*
4930	 * Fetch max tx power level for status requests.
4931	 */
4932	ath_hal_getmaxtxpow(sc->sc_ah, &txpow);
4933	ic->ic_bss->ni_txpower = txpow;
4934}
4935
4936static int
4937ath_rate_setup(struct ath_softc *sc, u_int mode)
4938{
4939	struct ath_hal *ah = sc->sc_ah;
4940	const HAL_RATE_TABLE *rt;
4941
4942	switch (mode) {
4943	case IEEE80211_MODE_11A:
4944		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
4945		break;
4946	case IEEE80211_MODE_11A_HALF:
4947		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
4948		break;
4949	case IEEE80211_MODE_11A_QUARTER:
4950		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
4951		break;
4952	case IEEE80211_MODE_11B:
4953		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
4954		break;
4955	case IEEE80211_MODE_11G:
4956		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
4957		break;
4958	case IEEE80211_MODE_TURBO_A:
4959		/* XXX until static/dynamic turbo is fixed */
4960		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
4961		break;
4962	case IEEE80211_MODE_TURBO_G:
4963		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
4964		break;
4965	default:
4966		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
4967			__func__, mode);
4968		return 0;
4969	}
4970	sc->sc_rates[mode] = rt;
4971	return (rt != NULL);
4972}
4973
4974static void
4975ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
4976{
4977#define	N(a)	(sizeof(a)/sizeof(a[0]))
4978	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
4979	static const struct {
4980		u_int		rate;		/* tx/rx 802.11 rate */
4981		u_int16_t	timeOn;		/* LED on time (ms) */
4982		u_int16_t	timeOff;	/* LED off time (ms) */
4983	} blinkrates[] = {
4984		{ 108,  40,  10 },
4985		{  96,  44,  11 },
4986		{  72,  50,  13 },
4987		{  48,  57,  14 },
4988		{  36,  67,  16 },
4989		{  24,  80,  20 },
4990		{  22, 100,  25 },
4991		{  18, 133,  34 },
4992		{  12, 160,  40 },
4993		{  10, 200,  50 },
4994		{   6, 240,  58 },
4995		{   4, 267,  66 },
4996		{   2, 400, 100 },
4997		{   0, 500, 130 },
4998	};
4999	const HAL_RATE_TABLE *rt;
5000	int i, j;
5001
5002	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
5003	rt = sc->sc_rates[mode];
5004	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
5005	for (i = 0; i < rt->rateCount; i++)
5006		sc->sc_rixmap[rt->info[i].dot11Rate & IEEE80211_RATE_VAL] = i;
5007	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
5008	for (i = 0; i < 32; i++) {
5009		u_int8_t ix = rt->rateCodeToIndex[i];
5010		if (ix == 0xff) {
5011			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
5012			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
5013			continue;
5014		}
5015		sc->sc_hwmap[i].ieeerate =
5016			rt->info[ix].dot11Rate & IEEE80211_RATE_VAL;
5017		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
5018		if (rt->info[ix].shortPreamble ||
5019		    rt->info[ix].phy == IEEE80211_T_OFDM)
5020			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
5021		/* NB: receive frames include FCS */
5022		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags |
5023			IEEE80211_RADIOTAP_F_FCS;
5024		/* setup blink rate table to avoid per-packet lookup */
5025		for (j = 0; j < N(blinkrates)-1; j++)
5026			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
5027				break;
5028		/* NB: this uses the last entry if the rate isn't found */
5029		/* XXX beware of overlow */
5030		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
5031		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
5032	}
5033	sc->sc_currates = rt;
5034	sc->sc_curmode = mode;
5035	/*
5036	 * All protection frames are transmited at 2Mb/s for
5037	 * 11g, otherwise at 1Mb/s.
5038	 */
5039	if (mode == IEEE80211_MODE_11G)
5040		sc->sc_protrix = ath_tx_findrix(rt, 2*2);
5041	else
5042		sc->sc_protrix = ath_tx_findrix(rt, 2*1);
5043	/* rate index used to send management frames */
5044	sc->sc_minrateix = 0;
5045	/*
5046	 * Setup multicast rate state.
5047	 */
5048	/* XXX layering violation */
5049	sc->sc_mcastrix = ath_tx_findrix(rt, sc->sc_ic.ic_mcast_rate);
5050	sc->sc_mcastrate = sc->sc_ic.ic_mcast_rate;
5051	/* NB: caller is responsible for reseting rate control state */
5052#undef N
5053}
5054
5055#ifdef ATH_DEBUG
5056static void
5057ath_printrxbuf(const struct ath_buf *bf, u_int ix, int done)
5058{
5059	const struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
5060	const struct ath_desc *ds;
5061	int i;
5062
5063	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
5064		printf("R[%2u] (DS.V:%p DS.P:%p) L:%08x D:%08x%s\n"
5065		       "      %08x %08x %08x %08x\n",
5066		    ix, ds, (const struct ath_desc *)bf->bf_daddr + i,
5067		    ds->ds_link, ds->ds_data,
5068		    !done ? "" : (rs->rs_status == 0) ? " *" : " !",
5069		    ds->ds_ctl0, ds->ds_ctl1,
5070		    ds->ds_hw[0], ds->ds_hw[1]);
5071	}
5072}
5073
5074static void
5075ath_printtxbuf(const struct ath_buf *bf, u_int qnum, u_int ix, int done)
5076{
5077	const struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
5078	const struct ath_desc *ds;
5079	int i;
5080
5081	printf("Q%u[%3u]", qnum, ix);
5082	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
5083		printf(" (DS.V:%p DS.P:%p) L:%08x D:%08x F:04%x%s\n"
5084		       "        %08x %08x %08x %08x %08x %08x\n",
5085		    ds, (const struct ath_desc *)bf->bf_daddr + i,
5086		    ds->ds_link, ds->ds_data, bf->bf_flags,
5087		    !done ? "" : (ts->ts_status == 0) ? " *" : " !",
5088		    ds->ds_ctl0, ds->ds_ctl1,
5089		    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3]);
5090	}
5091}
5092#endif /* ATH_DEBUG */
5093
5094static void
5095ath_watchdog(struct ifnet *ifp)
5096{
5097	struct ath_softc *sc = ifp->if_softc;
5098	struct ieee80211com *ic = &sc->sc_ic;
5099
5100	ifp->if_timer = 0;
5101	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
5102		return;
5103	if (sc->sc_tx_timer) {
5104		if (--sc->sc_tx_timer == 0) {
5105			if_printf(ifp, "device timeout\n");
5106			ath_reset(ifp);
5107			ifp->if_oerrors++;
5108			sc->sc_stats.ast_watchdog++;
5109		} else
5110			ifp->if_timer = 1;
5111	}
5112	ieee80211_watchdog(ic);
5113}
5114
5115#ifdef ATH_DIAGAPI
5116/*
5117 * Diagnostic interface to the HAL.  This is used by various
5118 * tools to do things like retrieve register contents for
5119 * debugging.  The mechanism is intentionally opaque so that
5120 * it can change frequently w/o concern for compatiblity.
5121 */
5122static int
5123ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
5124{
5125	struct ath_hal *ah = sc->sc_ah;
5126	u_int id = ad->ad_id & ATH_DIAG_ID;
5127	void *indata = NULL;
5128	void *outdata = NULL;
5129	u_int32_t insize = ad->ad_in_size;
5130	u_int32_t outsize = ad->ad_out_size;
5131	int error = 0;
5132
5133	if (ad->ad_id & ATH_DIAG_IN) {
5134		/*
5135		 * Copy in data.
5136		 */
5137		indata = malloc(insize, M_TEMP, M_NOWAIT);
5138		if (indata == NULL) {
5139			error = ENOMEM;
5140			goto bad;
5141		}
5142		error = copyin(ad->ad_in_data, indata, insize);
5143		if (error)
5144			goto bad;
5145	}
5146	if (ad->ad_id & ATH_DIAG_DYN) {
5147		/*
5148		 * Allocate a buffer for the results (otherwise the HAL
5149		 * returns a pointer to a buffer where we can read the
5150		 * results).  Note that we depend on the HAL leaving this
5151		 * pointer for us to use below in reclaiming the buffer;
5152		 * may want to be more defensive.
5153		 */
5154		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
5155		if (outdata == NULL) {
5156			error = ENOMEM;
5157			goto bad;
5158		}
5159	}
5160	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
5161		if (outsize < ad->ad_out_size)
5162			ad->ad_out_size = outsize;
5163		if (outdata != NULL)
5164			error = copyout(outdata, ad->ad_out_data,
5165					ad->ad_out_size);
5166	} else {
5167		error = EINVAL;
5168	}
5169bad:
5170	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
5171		free(indata, M_TEMP);
5172	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
5173		free(outdata, M_TEMP);
5174	return error;
5175}
5176#endif /* ATH_DIAGAPI */
5177
5178static int
5179ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
5180{
5181#define	IS_RUNNING(ifp) \
5182	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
5183	struct ath_softc *sc = ifp->if_softc;
5184	struct ieee80211com *ic = &sc->sc_ic;
5185	struct ifreq *ifr = (struct ifreq *)data;
5186	int error = 0;
5187
5188	ATH_LOCK(sc);
5189	switch (cmd) {
5190	case SIOCSIFFLAGS:
5191		if (IS_RUNNING(ifp)) {
5192			/*
5193			 * To avoid rescanning another access point,
5194			 * do not call ath_init() here.  Instead,
5195			 * only reflect promisc mode settings.
5196			 */
5197			ath_mode_init(sc);
5198		} else if (ifp->if_flags & IFF_UP) {
5199			/*
5200			 * Beware of being called during attach/detach
5201			 * to reset promiscuous mode.  In that case we
5202			 * will still be marked UP but not RUNNING.
5203			 * However trying to re-init the interface
5204			 * is the wrong thing to do as we've already
5205			 * torn down much of our state.  There's
5206			 * probably a better way to deal with this.
5207			 */
5208			if (!sc->sc_invalid && ic->ic_bss != NULL)
5209				ath_init(sc);	/* XXX lose error */
5210		} else
5211			ath_stop_locked(ifp);
5212		break;
5213	case SIOCADDMULTI:
5214	case SIOCDELMULTI:
5215		/*
5216		 * The upper layer has already installed/removed
5217		 * the multicast address(es), just recalculate the
5218		 * multicast filter for the card.
5219		 */
5220		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
5221			ath_mode_init(sc);
5222		break;
5223	case SIOCGATHSTATS:
5224		/* NB: embed these numbers to get a consistent view */
5225		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
5226		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
5227		sc->sc_stats.ast_rx_rssi = ieee80211_getrssi(ic);
5228		sc->sc_stats.ast_rx_noise =
5229			ath_hal_getchannoise(sc->sc_ah, &sc->sc_curchan);
5230		sc->sc_stats.ast_tx_rate = sc->sc_hwmap[sc->sc_txrate].ieeerate;
5231		ATH_UNLOCK(sc);
5232		/*
5233		 * NB: Drop the softc lock in case of a page fault;
5234		 * we'll accept any potential inconsisentcy in the
5235		 * statistics.  The alternative is to copy the data
5236		 * to a local structure.
5237		 */
5238		return copyout(&sc->sc_stats,
5239				ifr->ifr_data, sizeof (sc->sc_stats));
5240#ifdef ATH_DIAGAPI
5241	case SIOCGATHDIAG:
5242		ATH_UNLOCK(sc);
5243		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
5244		ATH_LOCK(sc);
5245		break;
5246#endif
5247	default:
5248		error = ieee80211_ioctl(ic, cmd, data);
5249		if (error == ENETRESET) {
5250			if (IS_RUNNING(ifp) &&
5251			    ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
5252				ath_init(sc);	/* XXX lose error */
5253			error = 0;
5254		}
5255		if (error == ERESTART)
5256			error = IS_RUNNING(ifp) ? ath_reset(ifp) : 0;
5257		break;
5258	}
5259	ATH_UNLOCK(sc);
5260	return error;
5261#undef IS_RUNNING
5262}
5263
5264static int
5265ath_sysctl_slottime(SYSCTL_HANDLER_ARGS)
5266{
5267	struct ath_softc *sc = arg1;
5268	u_int slottime = ath_hal_getslottime(sc->sc_ah);
5269	int error;
5270
5271	error = sysctl_handle_int(oidp, &slottime, 0, req);
5272	if (error || !req->newptr)
5273		return error;
5274	return !ath_hal_setslottime(sc->sc_ah, slottime) ? EINVAL : 0;
5275}
5276
5277static int
5278ath_sysctl_acktimeout(SYSCTL_HANDLER_ARGS)
5279{
5280	struct ath_softc *sc = arg1;
5281	u_int acktimeout = ath_hal_getacktimeout(sc->sc_ah);
5282	int error;
5283
5284	error = sysctl_handle_int(oidp, &acktimeout, 0, req);
5285	if (error || !req->newptr)
5286		return error;
5287	return !ath_hal_setacktimeout(sc->sc_ah, acktimeout) ? EINVAL : 0;
5288}
5289
5290static int
5291ath_sysctl_ctstimeout(SYSCTL_HANDLER_ARGS)
5292{
5293	struct ath_softc *sc = arg1;
5294	u_int ctstimeout = ath_hal_getctstimeout(sc->sc_ah);
5295	int error;
5296
5297	error = sysctl_handle_int(oidp, &ctstimeout, 0, req);
5298	if (error || !req->newptr)
5299		return error;
5300	return !ath_hal_setctstimeout(sc->sc_ah, ctstimeout) ? EINVAL : 0;
5301}
5302
5303static int
5304ath_sysctl_softled(SYSCTL_HANDLER_ARGS)
5305{
5306	struct ath_softc *sc = arg1;
5307	int softled = sc->sc_softled;
5308	int error;
5309
5310	error = sysctl_handle_int(oidp, &softled, 0, req);
5311	if (error || !req->newptr)
5312		return error;
5313	softled = (softled != 0);
5314	if (softled != sc->sc_softled) {
5315		if (softled) {
5316			/* NB: handle any sc_ledpin change */
5317			ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
5318			ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
5319				!sc->sc_ledon);
5320		}
5321		sc->sc_softled = softled;
5322	}
5323	return 0;
5324}
5325
5326static int
5327ath_sysctl_rxantenna(SYSCTL_HANDLER_ARGS)
5328{
5329	struct ath_softc *sc = arg1;
5330	u_int defantenna = ath_hal_getdefantenna(sc->sc_ah);
5331	int error;
5332
5333	error = sysctl_handle_int(oidp, &defantenna, 0, req);
5334	if (!error && req->newptr)
5335		ath_hal_setdefantenna(sc->sc_ah, defantenna);
5336	return error;
5337}
5338
5339static int
5340ath_sysctl_diversity(SYSCTL_HANDLER_ARGS)
5341{
5342	struct ath_softc *sc = arg1;
5343	u_int diversity = ath_hal_getdiversity(sc->sc_ah);
5344	int error;
5345
5346	error = sysctl_handle_int(oidp, &diversity, 0, req);
5347	if (error || !req->newptr)
5348		return error;
5349	if (!ath_hal_setdiversity(sc->sc_ah, diversity))
5350		return EINVAL;
5351	sc->sc_diversity = diversity;
5352	return 0;
5353}
5354
5355static int
5356ath_sysctl_diag(SYSCTL_HANDLER_ARGS)
5357{
5358	struct ath_softc *sc = arg1;
5359	u_int32_t diag;
5360	int error;
5361
5362	if (!ath_hal_getdiag(sc->sc_ah, &diag))
5363		return EINVAL;
5364	error = sysctl_handle_int(oidp, &diag, 0, req);
5365	if (error || !req->newptr)
5366		return error;
5367	return !ath_hal_setdiag(sc->sc_ah, diag) ? EINVAL : 0;
5368}
5369
5370static int
5371ath_sysctl_tpscale(SYSCTL_HANDLER_ARGS)
5372{
5373	struct ath_softc *sc = arg1;
5374	struct ifnet *ifp = sc->sc_ifp;
5375	u_int32_t scale;
5376	int error;
5377
5378	ath_hal_gettpscale(sc->sc_ah, &scale);
5379	error = sysctl_handle_int(oidp, &scale, 0, req);
5380	if (error || !req->newptr)
5381		return error;
5382	return !ath_hal_settpscale(sc->sc_ah, scale) ? EINVAL : ath_reset(ifp);
5383}
5384
5385static int
5386ath_sysctl_tpc(SYSCTL_HANDLER_ARGS)
5387{
5388	struct ath_softc *sc = arg1;
5389	u_int tpc = ath_hal_gettpc(sc->sc_ah);
5390	int error;
5391
5392	error = sysctl_handle_int(oidp, &tpc, 0, req);
5393	if (error || !req->newptr)
5394		return error;
5395	return !ath_hal_settpc(sc->sc_ah, tpc) ? EINVAL : 0;
5396}
5397
5398static int
5399ath_sysctl_rfkill(SYSCTL_HANDLER_ARGS)
5400{
5401	struct ath_softc *sc = arg1;
5402	struct ath_hal *ah = sc->sc_ah;
5403	u_int rfkill = ath_hal_getrfkill(ah);
5404	int error;
5405
5406	error = sysctl_handle_int(oidp, &rfkill, 0, req);
5407	if (error || !req->newptr)
5408		return error;
5409	if (rfkill == ath_hal_getrfkill(ah))	/* unchanged */
5410		return 0;
5411	if (!ath_hal_setrfkill(ah, rfkill) || ath_reset(sc->sc_ifp) != 0)
5412		return EINVAL;
5413	else
5414		return 0;
5415}
5416
5417static int
5418ath_sysctl_rfsilent(SYSCTL_HANDLER_ARGS)
5419{
5420	struct ath_softc *sc = arg1;
5421	u_int rfsilent;
5422	int error;
5423
5424	ath_hal_getrfsilent(sc->sc_ah, &rfsilent);
5425	error = sysctl_handle_int(oidp, &rfsilent, 0, req);
5426	if (error || !req->newptr)
5427		return error;
5428	if (!ath_hal_setrfsilent(sc->sc_ah, rfsilent))
5429		return EINVAL;
5430	sc->sc_rfsilentpin = rfsilent & 0x1c;
5431	sc->sc_rfsilentpol = (rfsilent & 0x2) != 0;
5432	return 0;
5433}
5434
5435static int
5436ath_sysctl_countrycode(SYSCTL_HANDLER_ARGS)
5437{
5438	struct ath_softc *sc = arg1;
5439	u_int32_t cc = sc->sc_countrycode;
5440	struct ieee80211com *ic = &sc->sc_ic;
5441	int error;
5442
5443	error = sysctl_handle_int(oidp, &cc, 0, req);
5444	if (error || !req->newptr)
5445		return error;
5446	error = ath_getchannels(sc, sc->sc_regdomain, cc,
5447			sc->sc_outdoor, sc->sc_xchanmode);
5448	if (error != 0)
5449		return error;
5450	ieee80211_media_init(ic, ath_media_change, ieee80211_media_status);
5451	/* setcurmode? */
5452	return 0;
5453}
5454
5455static int
5456ath_sysctl_regdomain(SYSCTL_HANDLER_ARGS)
5457{
5458	struct ath_softc *sc = arg1;
5459	u_int32_t rd = sc->sc_regdomain;
5460	struct ieee80211com *ic = &sc->sc_ic;
5461	int error;
5462
5463	error = sysctl_handle_int(oidp, &rd, 0, req);
5464	if (error || !req->newptr)
5465		return error;
5466	if (!ath_hal_setregdomain(sc->sc_ah, rd))
5467		return EINVAL;
5468	error = ath_getchannels(sc, rd, sc->sc_countrycode,
5469			sc->sc_outdoor, sc->sc_xchanmode);
5470	if (error != 0)
5471		return error;
5472	ieee80211_media_init(ic, ath_media_change, ieee80211_media_status);
5473	/* setcurmode? */
5474	return 0;
5475}
5476
5477static int
5478ath_sysctl_tpack(SYSCTL_HANDLER_ARGS)
5479{
5480	struct ath_softc *sc = arg1;
5481	u_int32_t tpack;
5482	int error;
5483
5484	ath_hal_gettpack(sc->sc_ah, &tpack);
5485	error = sysctl_handle_int(oidp, &tpack, 0, req);
5486	if (error || !req->newptr)
5487		return error;
5488	return !ath_hal_settpack(sc->sc_ah, tpack) ? EINVAL : 0;
5489}
5490
5491static int
5492ath_sysctl_tpcts(SYSCTL_HANDLER_ARGS)
5493{
5494	struct ath_softc *sc = arg1;
5495	u_int32_t tpcts;
5496	int error;
5497
5498	ath_hal_gettpcts(sc->sc_ah, &tpcts);
5499	error = sysctl_handle_int(oidp, &tpcts, 0, req);
5500	if (error || !req->newptr)
5501		return error;
5502	return !ath_hal_settpcts(sc->sc_ah, tpcts) ? EINVAL : 0;
5503}
5504
5505static void
5506ath_sysctlattach(struct ath_softc *sc)
5507{
5508	struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
5509	struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
5510	struct ath_hal *ah = sc->sc_ah;
5511
5512	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5513		"countrycode", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5514		ath_sysctl_countrycode, "I", "country code");
5515	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5516		"regdomain", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5517		ath_sysctl_regdomain, "I", "EEPROM regdomain code");
5518#ifdef	ATH_DEBUG
5519	sc->sc_debug = ath_debug;
5520	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5521		"debug", CTLFLAG_RW, &sc->sc_debug, 0,
5522		"control debugging printfs");
5523#endif
5524	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5525		"slottime", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5526		ath_sysctl_slottime, "I", "802.11 slot time (us)");
5527	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5528		"acktimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5529		ath_sysctl_acktimeout, "I", "802.11 ACK timeout (us)");
5530	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5531		"ctstimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5532		ath_sysctl_ctstimeout, "I", "802.11 CTS timeout (us)");
5533	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5534		"softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5535		ath_sysctl_softled, "I", "enable/disable software LED support");
5536	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5537		"ledpin", CTLFLAG_RW, &sc->sc_ledpin, 0,
5538		"GPIO pin connected to LED");
5539	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5540		"ledon", CTLFLAG_RW, &sc->sc_ledon, 0,
5541		"setting to turn LED on");
5542	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5543		"ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
5544		"idle time for inactivity LED (ticks)");
5545	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5546		"txantenna", CTLFLAG_RW, &sc->sc_txantenna, 0,
5547		"tx antenna (0=auto)");
5548	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5549		"rxantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5550		ath_sysctl_rxantenna, "I", "default/rx antenna");
5551	if (ath_hal_hasdiversity(ah))
5552		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5553			"diversity", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5554			ath_sysctl_diversity, "I", "antenna diversity");
5555	sc->sc_txintrperiod = ATH_TXINTR_PERIOD;
5556	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5557		"txintrperiod", CTLFLAG_RW, &sc->sc_txintrperiod, 0,
5558		"tx descriptor batching");
5559	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5560		"diag", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5561		ath_sysctl_diag, "I", "h/w diagnostic control");
5562	SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5563		"tpscale", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5564		ath_sysctl_tpscale, "I", "tx power scaling");
5565	if (ath_hal_hastpc(ah)) {
5566		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5567			"tpc", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5568			ath_sysctl_tpc, "I", "enable/disable per-packet TPC");
5569		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5570			"tpack", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5571			ath_sysctl_tpack, "I", "tx power for ack frames");
5572		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5573			"tpcts", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5574			ath_sysctl_tpcts, "I", "tx power for cts frames");
5575	}
5576	if (ath_hal_hasrfsilent(ah)) {
5577		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5578			"rfsilent", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5579			ath_sysctl_rfsilent, "I", "h/w RF silent config");
5580		SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5581			"rfkill", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
5582			ath_sysctl_rfkill, "I", "enable/disable RF kill switch");
5583	}
5584	sc->sc_monpass = HAL_RXERR_DECRYPT | HAL_RXERR_MIC;
5585	SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
5586		"monpass", CTLFLAG_RW, &sc->sc_monpass, 0,
5587		"mask of error frames to pass when monitoring");
5588}
5589
5590static void
5591ath_bpfattach(struct ath_softc *sc)
5592{
5593	struct ifnet *ifp = sc->sc_ifp;
5594
5595	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
5596		sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th),
5597		&sc->sc_drvbpf);
5598	/*
5599	 * Initialize constant fields.
5600	 * XXX make header lengths a multiple of 32-bits so subsequent
5601	 *     headers are properly aligned; this is a kludge to keep
5602	 *     certain applications happy.
5603	 *
5604	 * NB: the channel is setup each time we transition to the
5605	 *     RUN state to avoid filling it in for each frame.
5606	 */
5607	sc->sc_tx_th_len = roundup(sizeof(sc->sc_tx_th), sizeof(u_int32_t));
5608	sc->sc_tx_th.wt_ihdr.it_len = htole16(sc->sc_tx_th_len);
5609	sc->sc_tx_th.wt_ihdr.it_present = htole32(ATH_TX_RADIOTAP_PRESENT);
5610
5611	sc->sc_rx_th_len = roundup(sizeof(sc->sc_rx_th), sizeof(u_int32_t));
5612	sc->sc_rx_th.wr_ihdr.it_len = htole16(sc->sc_rx_th_len);
5613	sc->sc_rx_th.wr_ihdr.it_present = htole32(ATH_RX_RADIOTAP_PRESENT);
5614}
5615
5616static int
5617ath_tx_raw_start(struct ath_softc *sc, struct ieee80211_node *ni,
5618	struct ath_buf *bf, struct mbuf *m0,
5619	const struct ieee80211_bpf_params *params)
5620{
5621	struct ieee80211com *ic = &sc->sc_ic;
5622	struct ath_hal *ah = sc->sc_ah;
5623	int error, ismcast, ismrr;
5624	int hdrlen, pktlen, try0, txantenna;
5625	u_int8_t rix, cix, txrate, ctsrate, rate1, rate2, rate3;
5626	struct ath_txq *txq;
5627	struct ieee80211_frame *wh;
5628	u_int flags, ctsduration;
5629	HAL_PKT_TYPE atype;
5630	const HAL_RATE_TABLE *rt;
5631	struct ath_desc *ds;
5632	u_int pri;
5633
5634	wh = mtod(m0, struct ieee80211_frame *);
5635	ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
5636	hdrlen = ieee80211_anyhdrsize(wh);
5637	/*
5638	 * Packet length must not include any
5639	 * pad bytes; deduct them here.
5640	 */
5641	/* XXX honor IEEE80211_BPF_DATAPAD */
5642	pktlen = m0->m_pkthdr.len - (hdrlen & 3) + IEEE80211_CRC_LEN;
5643
5644	error = ath_tx_dmasetup(sc, bf, m0);
5645	if (error != 0)
5646		return error;
5647	m0 = bf->bf_m;				/* NB: may have changed */
5648	wh = mtod(m0, struct ieee80211_frame *);
5649	bf->bf_node = ni;			/* NB: held reference */
5650
5651	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for crypto errs */
5652	flags |= HAL_TXDESC_INTREQ;		/* force interrupt */
5653	if (params->ibp_flags & IEEE80211_BPF_RTS)
5654		flags |= HAL_TXDESC_RTSENA;
5655	else if (params->ibp_flags & IEEE80211_BPF_CTS)
5656		flags |= HAL_TXDESC_CTSENA;
5657	/* XXX leave ismcast to injector? */
5658	if ((params->ibp_flags & IEEE80211_BPF_NOACK) || ismcast)
5659		flags |= HAL_TXDESC_NOACK;
5660
5661	rt = sc->sc_currates;
5662	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
5663	rix = ath_tx_findrix(rt, params->ibp_rate0);
5664	txrate = rt->info[rix].rateCode;
5665	if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
5666		txrate |= rt->info[rix].shortPreamble;
5667	sc->sc_txrate = txrate;
5668	try0 = params->ibp_try0;
5669	ismrr = (params->ibp_try1 != 0);
5670	txantenna = params->ibp_pri >> 2;
5671	if (txantenna == 0)			/* XXX? */
5672		txantenna = sc->sc_txantenna;
5673	ctsduration = 0;
5674	if (flags & (HAL_TXDESC_CTSENA | HAL_TXDESC_RTSENA)) {
5675		cix = ath_tx_findrix(rt, params->ibp_ctsrate);
5676		ctsrate = rt->info[cix].rateCode;
5677		if (params->ibp_flags & IEEE80211_BPF_SHORTPRE) {
5678			ctsrate |= rt->info[cix].shortPreamble;
5679			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
5680				ctsduration += rt->info[cix].spAckDuration;
5681			ctsduration += ath_hal_computetxtime(ah,
5682				rt, pktlen, rix, AH_TRUE);
5683			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
5684				ctsduration += rt->info[rix].spAckDuration;
5685		} else {
5686			if (flags & HAL_TXDESC_RTSENA)		/* SIFS + CTS */
5687				ctsduration += rt->info[cix].lpAckDuration;
5688			ctsduration += ath_hal_computetxtime(ah,
5689				rt, pktlen, rix, AH_FALSE);
5690			if ((flags & HAL_TXDESC_NOACK) == 0)	/* SIFS + ACK */
5691				ctsduration += rt->info[rix].lpAckDuration;
5692		}
5693		ismrr = 0;			/* XXX */
5694	} else
5695		ctsrate = 0;
5696	pri = params->ibp_pri & 3;
5697	/*
5698	 * NB: we mark all packets as type PSPOLL so the h/w won't
5699	 * set the sequence number, duration, etc.
5700	 */
5701	atype = HAL_PKT_TYPE_PSPOLL;
5702
5703	if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
5704		ieee80211_dump_pkt(mtod(m0, caddr_t), m0->m_len,
5705			sc->sc_hwmap[txrate].ieeerate, -1);
5706
5707	if (bpf_peers_present(ic->ic_rawbpf))
5708		bpf_mtap(ic->ic_rawbpf, m0);
5709	if (bpf_peers_present(sc->sc_drvbpf)) {
5710		u_int64_t tsf = ath_hal_gettsf64(ah);
5711
5712		sc->sc_tx_th.wt_tsf = htole64(tsf);
5713		sc->sc_tx_th.wt_flags = sc->sc_hwmap[txrate].txflags;
5714		if (wh->i_fc[1] & IEEE80211_FC1_WEP)
5715			sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
5716		sc->sc_tx_th.wt_rate = sc->sc_hwmap[txrate].ieeerate;
5717		sc->sc_tx_th.wt_txpower = ni->ni_txpower;
5718		sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
5719
5720		bpf_mtap2(sc->sc_drvbpf,
5721			&sc->sc_tx_th, sc->sc_tx_th_len, m0);
5722	}
5723
5724	/*
5725	 * Formulate first tx descriptor with tx controls.
5726	 */
5727	ds = bf->bf_desc;
5728	/* XXX check return value? */
5729	ath_hal_setuptxdesc(ah, ds
5730		, pktlen		/* packet length */
5731		, hdrlen		/* header length */
5732		, atype			/* Atheros packet type */
5733		, params->ibp_power	/* txpower */
5734		, txrate, try0		/* series 0 rate/tries */
5735		, HAL_TXKEYIX_INVALID	/* key cache index */
5736		, txantenna		/* antenna mode */
5737		, flags			/* flags */
5738		, ctsrate		/* rts/cts rate */
5739		, ctsduration		/* rts/cts duration */
5740	);
5741	bf->bf_flags = flags;
5742
5743	if (ismrr) {
5744		rix = ath_tx_findrix(rt, params->ibp_rate1);
5745		rate1 = rt->info[rix].rateCode;
5746		if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
5747			rate1 |= rt->info[rix].shortPreamble;
5748		if (params->ibp_try2) {
5749			rix = ath_tx_findrix(rt, params->ibp_rate2);
5750			rate2 = rt->info[rix].rateCode;
5751			if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
5752				rate2 |= rt->info[rix].shortPreamble;
5753		} else
5754			rate2 = 0;
5755		if (params->ibp_try3) {
5756			rix = ath_tx_findrix(rt, params->ibp_rate3);
5757			rate3 = rt->info[rix].rateCode;
5758			if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
5759				rate3 |= rt->info[rix].shortPreamble;
5760		} else
5761			rate3 = 0;
5762		ath_hal_setupxtxdesc(ah, ds
5763			, rate1, params->ibp_try1	/* series 1 */
5764			, rate2, params->ibp_try2	/* series 2 */
5765			, rate3, params->ibp_try3	/* series 3 */
5766		);
5767	}
5768
5769	/*
5770	 * When servicing one or more stations in power-save mode
5771	 * (or) if there is some mcast data waiting on the mcast
5772	 * queue (to prevent out of order delivery) multicast
5773	 * frames must be buffered until after the beacon.
5774	 */
5775	txq = sc->sc_ac2q[pri];
5776	if (ismcast && (ic->ic_ps_sta || sc->sc_mcastq.axq_depth))
5777		txq = &sc->sc_mcastq;
5778	ath_tx_handoff(sc, txq, bf);
5779	return 0;
5780}
5781
5782static int
5783ath_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
5784	const struct ieee80211_bpf_params *params)
5785{
5786	struct ieee80211com *ic = ni->ni_ic;
5787	struct ifnet *ifp = ic->ic_ifp;
5788	struct ath_softc *sc = ifp->if_softc;
5789	struct ath_buf *bf;
5790
5791	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid) {
5792		m_freem(m);
5793		return ENETDOWN;
5794	}
5795	/*
5796	 * Grab a TX buffer and associated resources.
5797	 */
5798	ATH_TXBUF_LOCK(sc);
5799	bf = STAILQ_FIRST(&sc->sc_txbuf);
5800	if (bf != NULL)
5801		STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
5802	ATH_TXBUF_UNLOCK(sc);
5803	if (bf == NULL) {
5804		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: out of xmit buffers\n",
5805			__func__);
5806		sc->sc_stats.ast_tx_qstop++;
5807		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
5808		m_freem(m);
5809		return ENOBUFS;
5810	}
5811
5812	ifp->if_opackets++;
5813	sc->sc_stats.ast_tx_raw++;
5814
5815	if (params == NULL) {
5816		/*
5817		 * Legacy path; interpret frame contents to decide
5818		 * precisely how to send the frame.
5819		 */
5820		if (ath_tx_start(sc, ni, bf, m))
5821			goto bad;
5822	} else {
5823		/*
5824		 * Caller supplied explicit parameters to use in
5825		 * sending the frame.
5826		 */
5827		if (ath_tx_raw_start(sc, ni, bf, m, params))
5828			goto bad;
5829	}
5830	sc->sc_tx_timer = 5;
5831	ifp->if_timer = 1;
5832
5833	return 0;
5834bad:
5835	ifp->if_oerrors++;
5836	ATH_TXBUF_LOCK(sc);
5837	STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5838	ATH_TXBUF_UNLOCK(sc);
5839	ieee80211_free_node(ni);
5840	return EIO;		/* XXX */
5841}
5842
5843/*
5844 * Announce various information on device/driver attach.
5845 */
5846static void
5847ath_announce(struct ath_softc *sc)
5848{
5849#define	HAL_MODE_DUALBAND	(HAL_MODE_11A|HAL_MODE_11B)
5850	struct ifnet *ifp = sc->sc_ifp;
5851	struct ath_hal *ah = sc->sc_ah;
5852	u_int modes, cc;
5853
5854	if_printf(ifp, "mac %d.%d phy %d.%d",
5855		ah->ah_macVersion, ah->ah_macRev,
5856		ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
5857	/*
5858	 * Print radio revision(s).  We check the wireless modes
5859	 * to avoid falsely printing revs for inoperable parts.
5860	 * Dual-band radio revs are returned in the 5Ghz rev number.
5861	 */
5862	ath_hal_getcountrycode(ah, &cc);
5863	modes = ath_hal_getwirelessmodes(ah, cc);
5864	if ((modes & HAL_MODE_DUALBAND) == HAL_MODE_DUALBAND) {
5865		if (ah->ah_analog5GhzRev && ah->ah_analog2GhzRev)
5866			printf(" 5ghz radio %d.%d 2ghz radio %d.%d",
5867				ah->ah_analog5GhzRev >> 4,
5868				ah->ah_analog5GhzRev & 0xf,
5869				ah->ah_analog2GhzRev >> 4,
5870				ah->ah_analog2GhzRev & 0xf);
5871		else
5872			printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
5873				ah->ah_analog5GhzRev & 0xf);
5874	} else
5875		printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
5876			ah->ah_analog5GhzRev & 0xf);
5877	printf("\n");
5878	if (bootverbose) {
5879		int i;
5880		for (i = 0; i <= WME_AC_VO; i++) {
5881			struct ath_txq *txq = sc->sc_ac2q[i];
5882			if_printf(ifp, "Use hw queue %u for %s traffic\n",
5883				txq->axq_qnum, ieee80211_wme_acnames[i]);
5884		}
5885		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
5886			sc->sc_cabq->axq_qnum);
5887		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
5888	}
5889	if (ath_rxbuf != ATH_RXBUF)
5890		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
5891	if (ath_txbuf != ATH_TXBUF)
5892		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
5893#undef HAL_MODE_DUALBAND
5894}
5895