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