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