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