if_ath.c revision 242899
1/*-
2 * Copyright (c) 2002-2009 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 *
16 * NO WARRANTY
17 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19 * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
20 * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21 * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
22 * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27 * THE POSSIBILITY OF SUCH DAMAGES.
28 */
29
30#include <sys/cdefs.h>
31__FBSDID("$FreeBSD: head/sys/dev/ath/if_ath.c 242899 2012-11-11 21:58:18Z adrian $");
32
33/*
34 * Driver for the Atheros Wireless LAN controller.
35 *
36 * This software is derived from work of Atsushi Onoe; his contribution
37 * is greatly appreciated.
38 */
39
40#include "opt_inet.h"
41#include "opt_ath.h"
42/*
43 * This is needed for register operations which are performed
44 * by the driver - eg, calls to ath_hal_gettsf32().
45 *
46 * It's also required for any AH_DEBUG checks in here, eg the
47 * module dependencies.
48 */
49#include "opt_ah.h"
50#include "opt_wlan.h"
51
52#include <sys/param.h>
53#include <sys/systm.h>
54#include <sys/sysctl.h>
55#include <sys/mbuf.h>
56#include <sys/malloc.h>
57#include <sys/lock.h>
58#include <sys/mutex.h>
59#include <sys/kernel.h>
60#include <sys/socket.h>
61#include <sys/sockio.h>
62#include <sys/errno.h>
63#include <sys/callout.h>
64#include <sys/bus.h>
65#include <sys/endian.h>
66#include <sys/kthread.h>
67#include <sys/taskqueue.h>
68#include <sys/priv.h>
69#include <sys/module.h>
70#include <sys/ktr.h>
71#include <sys/smp.h>	/* for mp_ncpus */
72
73#include <machine/bus.h>
74
75#include <net/if.h>
76#include <net/if_dl.h>
77#include <net/if_media.h>
78#include <net/if_types.h>
79#include <net/if_arp.h>
80#include <net/ethernet.h>
81#include <net/if_llc.h>
82
83#include <net80211/ieee80211_var.h>
84#include <net80211/ieee80211_regdomain.h>
85#ifdef IEEE80211_SUPPORT_SUPERG
86#include <net80211/ieee80211_superg.h>
87#endif
88#ifdef IEEE80211_SUPPORT_TDMA
89#include <net80211/ieee80211_tdma.h>
90#endif
91
92#include <net/bpf.h>
93
94#ifdef INET
95#include <netinet/in.h>
96#include <netinet/if_ether.h>
97#endif
98
99#include <dev/ath/if_athvar.h>
100#include <dev/ath/ath_hal/ah_devid.h>		/* XXX for softled */
101#include <dev/ath/ath_hal/ah_diagcodes.h>
102
103#include <dev/ath/if_ath_debug.h>
104#include <dev/ath/if_ath_misc.h>
105#include <dev/ath/if_ath_tsf.h>
106#include <dev/ath/if_ath_tx.h>
107#include <dev/ath/if_ath_sysctl.h>
108#include <dev/ath/if_ath_led.h>
109#include <dev/ath/if_ath_keycache.h>
110#include <dev/ath/if_ath_rx.h>
111#include <dev/ath/if_ath_rx_edma.h>
112#include <dev/ath/if_ath_tx_edma.h>
113#include <dev/ath/if_ath_beacon.h>
114#include <dev/ath/if_athdfs.h>
115
116#ifdef ATH_TX99_DIAG
117#include <dev/ath/ath_tx99/ath_tx99.h>
118#endif
119
120#ifdef	ATH_DEBUG_ALQ
121#include <dev/ath/if_ath_alq.h>
122#endif
123
124/*
125 * Only enable this if you're working on PS-POLL support.
126 */
127#undef	ATH_SW_PSQ
128
129/*
130 * ATH_BCBUF determines the number of vap's that can transmit
131 * beacons and also (currently) the number of vap's that can
132 * have unique mac addresses/bssid.  When staggering beacons
133 * 4 is probably a good max as otherwise the beacons become
134 * very closely spaced and there is limited time for cab q traffic
135 * to go out.  You can burst beacons instead but that is not good
136 * for stations in power save and at some point you really want
137 * another radio (and channel).
138 *
139 * The limit on the number of mac addresses is tied to our use of
140 * the U/L bit and tracking addresses in a byte; it would be
141 * worthwhile to allow more for applications like proxy sta.
142 */
143CTASSERT(ATH_BCBUF <= 8);
144
145static struct ieee80211vap *ath_vap_create(struct ieee80211com *,
146		    const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
147		    const uint8_t [IEEE80211_ADDR_LEN],
148		    const uint8_t [IEEE80211_ADDR_LEN]);
149static void	ath_vap_delete(struct ieee80211vap *);
150static void	ath_init(void *);
151static void	ath_stop_locked(struct ifnet *);
152static void	ath_stop(struct ifnet *);
153static int	ath_reset_vap(struct ieee80211vap *, u_long);
154static void	ath_start_queue(struct ifnet *ifp);
155static int	ath_media_change(struct ifnet *);
156static void	ath_watchdog(void *);
157static int	ath_ioctl(struct ifnet *, u_long, caddr_t);
158static void	ath_fatal_proc(void *, int);
159static void	ath_bmiss_vap(struct ieee80211vap *);
160static void	ath_bmiss_proc(void *, int);
161static void	ath_key_update_begin(struct ieee80211vap *);
162static void	ath_key_update_end(struct ieee80211vap *);
163static void	ath_update_mcast(struct ifnet *);
164static void	ath_update_promisc(struct ifnet *);
165static void	ath_updateslot(struct ifnet *);
166static void	ath_bstuck_proc(void *, int);
167static void	ath_reset_proc(void *, int);
168static int	ath_desc_alloc(struct ath_softc *);
169static void	ath_desc_free(struct ath_softc *);
170static struct ieee80211_node *ath_node_alloc(struct ieee80211vap *,
171			const uint8_t [IEEE80211_ADDR_LEN]);
172static void	ath_node_cleanup(struct ieee80211_node *);
173static void	ath_node_free(struct ieee80211_node *);
174static void	ath_node_getsignal(const struct ieee80211_node *,
175			int8_t *, int8_t *);
176static void	ath_txq_init(struct ath_softc *sc, struct ath_txq *, int);
177static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
178static int	ath_tx_setup(struct ath_softc *, int, int);
179static void	ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
180static void	ath_tx_cleanup(struct ath_softc *);
181static int	ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq,
182		    int dosched);
183static void	ath_tx_proc_q0(void *, int);
184static void	ath_tx_proc_q0123(void *, int);
185static void	ath_tx_proc(void *, int);
186static void	ath_txq_sched_tasklet(void *, int);
187static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
188static void	ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
189static void	ath_scan_start(struct ieee80211com *);
190static void	ath_scan_end(struct ieee80211com *);
191static void	ath_set_channel(struct ieee80211com *);
192#ifdef	ATH_ENABLE_11N
193static void	ath_update_chw(struct ieee80211com *);
194#endif	/* ATH_ENABLE_11N */
195static void	ath_calibrate(void *);
196static int	ath_newstate(struct ieee80211vap *, enum ieee80211_state, int);
197static void	ath_setup_stationkey(struct ieee80211_node *);
198static void	ath_newassoc(struct ieee80211_node *, int);
199static int	ath_setregdomain(struct ieee80211com *,
200		    struct ieee80211_regdomain *, int,
201		    struct ieee80211_channel []);
202static void	ath_getradiocaps(struct ieee80211com *, int, int *,
203		    struct ieee80211_channel []);
204static int	ath_getchannels(struct ath_softc *);
205
206static int	ath_rate_setup(struct ath_softc *, u_int mode);
207static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
208
209static void	ath_announce(struct ath_softc *);
210
211static void	ath_dfs_tasklet(void *, int);
212static void	ath_node_powersave(struct ieee80211_node *, int);
213static int	ath_node_set_tim(struct ieee80211_node *, int);
214
215#ifdef IEEE80211_SUPPORT_TDMA
216#include <dev/ath/if_ath_tdma.h>
217#endif
218
219SYSCTL_DECL(_hw_ath);
220
221/* XXX validate sysctl values */
222static	int ath_longcalinterval = 30;		/* long cals every 30 secs */
223SYSCTL_INT(_hw_ath, OID_AUTO, longcal, CTLFLAG_RW, &ath_longcalinterval,
224	    0, "long chip calibration interval (secs)");
225static	int ath_shortcalinterval = 100;		/* short cals every 100 ms */
226SYSCTL_INT(_hw_ath, OID_AUTO, shortcal, CTLFLAG_RW, &ath_shortcalinterval,
227	    0, "short chip calibration interval (msecs)");
228static	int ath_resetcalinterval = 20*60;	/* reset cal state 20 mins */
229SYSCTL_INT(_hw_ath, OID_AUTO, resetcal, CTLFLAG_RW, &ath_resetcalinterval,
230	    0, "reset chip calibration results (secs)");
231static	int ath_anicalinterval = 100;		/* ANI calibration - 100 msec */
232SYSCTL_INT(_hw_ath, OID_AUTO, anical, CTLFLAG_RW, &ath_anicalinterval,
233	    0, "ANI calibration (msecs)");
234
235int ath_rxbuf = ATH_RXBUF;		/* # rx buffers to allocate */
236SYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RW, &ath_rxbuf,
237	    0, "rx buffers allocated");
238TUNABLE_INT("hw.ath.rxbuf", &ath_rxbuf);
239int ath_txbuf = ATH_TXBUF;		/* # tx buffers to allocate */
240SYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RW, &ath_txbuf,
241	    0, "tx buffers allocated");
242TUNABLE_INT("hw.ath.txbuf", &ath_txbuf);
243int ath_txbuf_mgmt = ATH_MGMT_TXBUF;	/* # mgmt tx buffers to allocate */
244SYSCTL_INT(_hw_ath, OID_AUTO, txbuf_mgmt, CTLFLAG_RW, &ath_txbuf_mgmt,
245	    0, "tx (mgmt) buffers allocated");
246TUNABLE_INT("hw.ath.txbuf_mgmt", &ath_txbuf_mgmt);
247
248int ath_bstuck_threshold = 4;		/* max missed beacons */
249SYSCTL_INT(_hw_ath, OID_AUTO, bstuck, CTLFLAG_RW, &ath_bstuck_threshold,
250	    0, "max missed beacon xmits before chip reset");
251
252MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
253
254void
255ath_legacy_attach_comp_func(struct ath_softc *sc)
256{
257
258	/*
259	 * Special case certain configurations.  Note the
260	 * CAB queue is handled by these specially so don't
261	 * include them when checking the txq setup mask.
262	 */
263	switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
264	case 0x01:
265		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
266		break;
267	case 0x0f:
268		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
269		break;
270	default:
271		TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
272		break;
273	}
274}
275
276#define	HAL_MODE_HT20 (HAL_MODE_11NG_HT20 | HAL_MODE_11NA_HT20)
277#define	HAL_MODE_HT40 \
278	(HAL_MODE_11NG_HT40PLUS | HAL_MODE_11NG_HT40MINUS | \
279	HAL_MODE_11NA_HT40PLUS | HAL_MODE_11NA_HT40MINUS)
280int
281ath_attach(u_int16_t devid, struct ath_softc *sc)
282{
283	struct ifnet *ifp;
284	struct ieee80211com *ic;
285	struct ath_hal *ah = NULL;
286	HAL_STATUS status;
287	int error = 0, i;
288	u_int wmodes;
289	uint8_t macaddr[IEEE80211_ADDR_LEN];
290	int rx_chainmask, tx_chainmask;
291
292	DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
293
294	CURVNET_SET(vnet0);
295	ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
296	if (ifp == NULL) {
297		device_printf(sc->sc_dev, "can not if_alloc()\n");
298		error = ENOSPC;
299		goto bad;
300	}
301	ic = ifp->if_l2com;
302
303	/* set these up early for if_printf use */
304	if_initname(ifp, device_get_name(sc->sc_dev),
305		device_get_unit(sc->sc_dev));
306	CURVNET_RESTORE();
307
308	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh,
309	    sc->sc_eepromdata, &status);
310	if (ah == NULL) {
311		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
312			status);
313		error = ENXIO;
314		goto bad;
315	}
316	sc->sc_ah = ah;
317	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
318#ifdef	ATH_DEBUG
319	sc->sc_debug = ath_debug;
320#endif
321
322	/*
323	 * Setup the DMA/EDMA functions based on the current
324	 * hardware support.
325	 *
326	 * This is required before the descriptors are allocated.
327	 */
328	if (ath_hal_hasedma(sc->sc_ah)) {
329		sc->sc_isedma = 1;
330		ath_recv_setup_edma(sc);
331		ath_xmit_setup_edma(sc);
332	} else {
333		ath_recv_setup_legacy(sc);
334		ath_xmit_setup_legacy(sc);
335	}
336
337	/*
338	 * Check if the MAC has multi-rate retry support.
339	 * We do this by trying to setup a fake extended
340	 * descriptor.  MAC's that don't have support will
341	 * return false w/o doing anything.  MAC's that do
342	 * support it will return true w/o doing anything.
343	 */
344	sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
345
346	/*
347	 * Check if the device has hardware counters for PHY
348	 * errors.  If so we need to enable the MIB interrupt
349	 * so we can act on stat triggers.
350	 */
351	if (ath_hal_hwphycounters(ah))
352		sc->sc_needmib = 1;
353
354	/*
355	 * Get the hardware key cache size.
356	 */
357	sc->sc_keymax = ath_hal_keycachesize(ah);
358	if (sc->sc_keymax > ATH_KEYMAX) {
359		if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
360			ATH_KEYMAX, sc->sc_keymax);
361		sc->sc_keymax = ATH_KEYMAX;
362	}
363	/*
364	 * Reset the key cache since some parts do not
365	 * reset the contents on initial power up.
366	 */
367	for (i = 0; i < sc->sc_keymax; i++)
368		ath_hal_keyreset(ah, i);
369
370	/*
371	 * Collect the default channel list.
372	 */
373	error = ath_getchannels(sc);
374	if (error != 0)
375		goto bad;
376
377	/*
378	 * Setup rate tables for all potential media types.
379	 */
380	ath_rate_setup(sc, IEEE80211_MODE_11A);
381	ath_rate_setup(sc, IEEE80211_MODE_11B);
382	ath_rate_setup(sc, IEEE80211_MODE_11G);
383	ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
384	ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
385	ath_rate_setup(sc, IEEE80211_MODE_STURBO_A);
386	ath_rate_setup(sc, IEEE80211_MODE_11NA);
387	ath_rate_setup(sc, IEEE80211_MODE_11NG);
388	ath_rate_setup(sc, IEEE80211_MODE_HALF);
389	ath_rate_setup(sc, IEEE80211_MODE_QUARTER);
390
391	/* NB: setup here so ath_rate_update is happy */
392	ath_setcurmode(sc, IEEE80211_MODE_11A);
393
394	/*
395	 * Allocate TX descriptors and populate the lists.
396	 */
397	error = ath_desc_alloc(sc);
398	if (error != 0) {
399		if_printf(ifp, "failed to allocate TX descriptors: %d\n",
400		    error);
401		goto bad;
402	}
403	error = ath_txdma_setup(sc);
404	if (error != 0) {
405		if_printf(ifp, "failed to allocate TX descriptors: %d\n",
406		    error);
407		goto bad;
408	}
409
410	/*
411	 * Allocate RX descriptors and populate the lists.
412	 */
413	error = ath_rxdma_setup(sc);
414	if (error != 0) {
415		if_printf(ifp, "failed to allocate RX descriptors: %d\n",
416		    error);
417		goto bad;
418	}
419
420	callout_init_mtx(&sc->sc_cal_ch, &sc->sc_mtx, 0);
421	callout_init_mtx(&sc->sc_wd_ch, &sc->sc_mtx, 0);
422
423	ATH_TXBUF_LOCK_INIT(sc);
424
425	sc->sc_tq = taskqueue_create("ath_taskq", M_NOWAIT,
426		taskqueue_thread_enqueue, &sc->sc_tq);
427	taskqueue_start_threads(&sc->sc_tq, 1, PI_NET,
428		"%s taskq", ifp->if_xname);
429
430	TASK_INIT(&sc->sc_rxtask, 0, sc->sc_rx.recv_tasklet, sc);
431	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
432	TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_proc, sc);
433	TASK_INIT(&sc->sc_resettask,0, ath_reset_proc, sc);
434	TASK_INIT(&sc->sc_txqtask,0, ath_txq_sched_tasklet, sc);
435	TASK_INIT(&sc->sc_fataltask,0, ath_fatal_proc, sc);
436
437	/*
438	 * Allocate hardware transmit queues: one queue for
439	 * beacon frames and one data queue for each QoS
440	 * priority.  Note that the hal handles resetting
441	 * these queues at the needed time.
442	 *
443	 * XXX PS-Poll
444	 */
445	sc->sc_bhalq = ath_beaconq_setup(sc);
446	if (sc->sc_bhalq == (u_int) -1) {
447		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
448		error = EIO;
449		goto bad2;
450	}
451	sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
452	if (sc->sc_cabq == NULL) {
453		if_printf(ifp, "unable to setup CAB xmit queue!\n");
454		error = EIO;
455		goto bad2;
456	}
457	/* NB: insure BK queue is the lowest priority h/w queue */
458	if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
459		if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
460			ieee80211_wme_acnames[WME_AC_BK]);
461		error = EIO;
462		goto bad2;
463	}
464	if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
465	    !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
466	    !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
467		/*
468		 * Not enough hardware tx queues to properly do WME;
469		 * just punt and assign them all to the same h/w queue.
470		 * We could do a better job of this if, for example,
471		 * we allocate queues when we switch from station to
472		 * AP mode.
473		 */
474		if (sc->sc_ac2q[WME_AC_VI] != NULL)
475			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
476		if (sc->sc_ac2q[WME_AC_BE] != NULL)
477			ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
478		sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
479		sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
480		sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
481	}
482
483	/*
484	 * Attach the TX completion function.
485	 *
486	 * The non-EDMA chips may have some special case optimisations;
487	 * this method gives everyone a chance to attach cleanly.
488	 */
489	sc->sc_tx.xmit_attach_comp_func(sc);
490
491	/*
492	 * Setup rate control.  Some rate control modules
493	 * call back to change the anntena state so expose
494	 * the necessary entry points.
495	 * XXX maybe belongs in struct ath_ratectrl?
496	 */
497	sc->sc_setdefantenna = ath_setdefantenna;
498	sc->sc_rc = ath_rate_attach(sc);
499	if (sc->sc_rc == NULL) {
500		error = EIO;
501		goto bad2;
502	}
503
504	/* Attach DFS module */
505	if (! ath_dfs_attach(sc)) {
506		device_printf(sc->sc_dev,
507		    "%s: unable to attach DFS\n", __func__);
508		error = EIO;
509		goto bad2;
510	}
511
512	/* Start DFS processing tasklet */
513	TASK_INIT(&sc->sc_dfstask, 0, ath_dfs_tasklet, sc);
514
515	/* Configure LED state */
516	sc->sc_blinking = 0;
517	sc->sc_ledstate = 1;
518	sc->sc_ledon = 0;			/* low true */
519	sc->sc_ledidle = (2700*hz)/1000;	/* 2.7sec */
520	callout_init(&sc->sc_ledtimer, CALLOUT_MPSAFE);
521
522	/*
523	 * Don't setup hardware-based blinking.
524	 *
525	 * Although some NICs may have this configured in the
526	 * default reset register values, the user may wish
527	 * to alter which pins have which function.
528	 *
529	 * The reference driver attaches the MAC network LED to GPIO1 and
530	 * the MAC power LED to GPIO2.  However, the DWA-552 cardbus
531	 * NIC has these reversed.
532	 */
533	sc->sc_hardled = (1 == 0);
534	sc->sc_led_net_pin = -1;
535	sc->sc_led_pwr_pin = -1;
536	/*
537	 * Auto-enable soft led processing for IBM cards and for
538	 * 5211 minipci cards.  Users can also manually enable/disable
539	 * support with a sysctl.
540	 */
541	sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
542	ath_led_config(sc);
543	ath_hal_setledstate(ah, HAL_LED_INIT);
544
545	ifp->if_softc = sc;
546	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
547	ifp->if_start = ath_start_queue;
548	ifp->if_ioctl = ath_ioctl;
549	ifp->if_init = ath_init;
550	IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
551	ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
552	IFQ_SET_READY(&ifp->if_snd);
553
554	ic->ic_ifp = ifp;
555	/* XXX not right but it's not used anywhere important */
556	ic->ic_phytype = IEEE80211_T_OFDM;
557	ic->ic_opmode = IEEE80211_M_STA;
558	ic->ic_caps =
559		  IEEE80211_C_STA		/* station mode */
560		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
561		| IEEE80211_C_HOSTAP		/* hostap mode */
562		| IEEE80211_C_MONITOR		/* monitor mode */
563		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
564		| IEEE80211_C_WDS		/* 4-address traffic works */
565		| IEEE80211_C_MBSS		/* mesh point link mode */
566		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
567		| IEEE80211_C_SHSLOT		/* short slot time supported */
568		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
569#ifndef	ATH_ENABLE_11N
570		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
571#endif
572		| IEEE80211_C_TXFRAG		/* handle tx frags */
573#ifdef	ATH_ENABLE_DFS
574		| IEEE80211_C_DFS		/* Enable radar detection */
575#endif
576		;
577	/*
578	 * Query the hal to figure out h/w crypto support.
579	 */
580	if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
581		ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP;
582	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
583		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_OCB;
584	if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
585		ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_CCM;
586	if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
587		ic->ic_cryptocaps |= IEEE80211_CRYPTO_CKIP;
588	if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
589		ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIP;
590		/*
591		 * Check if h/w does the MIC and/or whether the
592		 * separate key cache entries are required to
593		 * handle both tx+rx MIC keys.
594		 */
595		if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
596			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
597		/*
598		 * If the h/w supports storing tx+rx MIC keys
599		 * in one cache slot automatically enable use.
600		 */
601		if (ath_hal_hastkipsplit(ah) ||
602		    !ath_hal_settkipsplit(ah, AH_FALSE))
603			sc->sc_splitmic = 1;
604		/*
605		 * If the h/w can do TKIP MIC together with WME then
606		 * we use it; otherwise we force the MIC to be done
607		 * in software by the net80211 layer.
608		 */
609		if (ath_hal_haswmetkipmic(ah))
610			sc->sc_wmetkipmic = 1;
611	}
612	sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
613	/*
614	 * Check for multicast key search support.
615	 */
616	if (ath_hal_hasmcastkeysearch(sc->sc_ah) &&
617	    !ath_hal_getmcastkeysearch(sc->sc_ah)) {
618		ath_hal_setmcastkeysearch(sc->sc_ah, 1);
619	}
620	sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
621	/*
622	 * Mark key cache slots associated with global keys
623	 * as in use.  If we knew TKIP was not to be used we
624	 * could leave the +32, +64, and +32+64 slots free.
625	 */
626	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
627		setbit(sc->sc_keymap, i);
628		setbit(sc->sc_keymap, i+64);
629		if (sc->sc_splitmic) {
630			setbit(sc->sc_keymap, i+32);
631			setbit(sc->sc_keymap, i+32+64);
632		}
633	}
634	/*
635	 * TPC support can be done either with a global cap or
636	 * per-packet support.  The latter is not available on
637	 * all parts.  We're a bit pedantic here as all parts
638	 * support a global cap.
639	 */
640	if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
641		ic->ic_caps |= IEEE80211_C_TXPMGT;
642
643	/*
644	 * Mark WME capability only if we have sufficient
645	 * hardware queues to do proper priority scheduling.
646	 */
647	if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
648		ic->ic_caps |= IEEE80211_C_WME;
649	/*
650	 * Check for misc other capabilities.
651	 */
652	if (ath_hal_hasbursting(ah))
653		ic->ic_caps |= IEEE80211_C_BURST;
654	sc->sc_hasbmask = ath_hal_hasbssidmask(ah);
655	sc->sc_hasbmatch = ath_hal_hasbssidmatch(ah);
656	sc->sc_hastsfadd = ath_hal_hastsfadjust(ah);
657	sc->sc_rxslink = ath_hal_self_linked_final_rxdesc(ah);
658	sc->sc_rxtsf32 = ath_hal_has_long_rxdesc_tsf(ah);
659	if (ath_hal_hasfastframes(ah))
660		ic->ic_caps |= IEEE80211_C_FF;
661	wmodes = ath_hal_getwirelessmodes(ah);
662	if (wmodes & (HAL_MODE_108G|HAL_MODE_TURBO))
663		ic->ic_caps |= IEEE80211_C_TURBOP;
664#ifdef IEEE80211_SUPPORT_TDMA
665	if (ath_hal_macversion(ah) > 0x78) {
666		ic->ic_caps |= IEEE80211_C_TDMA; /* capable of TDMA */
667		ic->ic_tdma_update = ath_tdma_update;
668	}
669#endif
670
671	/*
672	 * TODO: enforce that at least this many frames are available
673	 * in the txbuf list before allowing data frames (raw or
674	 * otherwise) to be transmitted.
675	 */
676	sc->sc_txq_data_minfree = 10;
677	/*
678	 * Leave this as default to maintain legacy behaviour.
679	 * Shortening the cabq/mcastq may end up causing some
680	 * undesirable behaviour.
681	 */
682	sc->sc_txq_mcastq_maxdepth = ath_txbuf;
683
684	/*
685	 * Allow the TX and RX chainmasks to be overridden by
686	 * environment variables and/or device.hints.
687	 *
688	 * This must be done early - before the hardware is
689	 * calibrated or before the 802.11n stream calculation
690	 * is done.
691	 */
692	if (resource_int_value(device_get_name(sc->sc_dev),
693	    device_get_unit(sc->sc_dev), "rx_chainmask",
694	    &rx_chainmask) == 0) {
695		device_printf(sc->sc_dev, "Setting RX chainmask to 0x%x\n",
696		    rx_chainmask);
697		(void) ath_hal_setrxchainmask(sc->sc_ah, rx_chainmask);
698	}
699	if (resource_int_value(device_get_name(sc->sc_dev),
700	    device_get_unit(sc->sc_dev), "tx_chainmask",
701	    &tx_chainmask) == 0) {
702		device_printf(sc->sc_dev, "Setting TX chainmask to 0x%x\n",
703		    tx_chainmask);
704		(void) ath_hal_settxchainmask(sc->sc_ah, tx_chainmask);
705	}
706
707	/*
708	 * Disable MRR with protected frames by default.
709	 * Only 802.11n series NICs can handle this.
710	 */
711	sc->sc_mrrprot = 0;	/* XXX should be a capability */
712
713	/*
714	 * Query the enterprise mode information the HAL.
715	 */
716	if (ath_hal_getcapability(ah, HAL_CAP_ENTERPRISE_MODE, 0,
717	    &sc->sc_ent_cfg) == HAL_OK)
718		sc->sc_use_ent = 1;
719
720#ifdef	ATH_ENABLE_11N
721	/*
722	 * Query HT capabilities
723	 */
724	if (ath_hal_getcapability(ah, HAL_CAP_HT, 0, NULL) == HAL_OK &&
725	    (wmodes & (HAL_MODE_HT20 | HAL_MODE_HT40))) {
726		int rxs, txs;
727
728		device_printf(sc->sc_dev, "[HT] enabling HT modes\n");
729
730		sc->sc_mrrprot = 1;	/* XXX should be a capability */
731
732		ic->ic_htcaps = IEEE80211_HTC_HT	/* HT operation */
733			    | IEEE80211_HTC_AMPDU	/* A-MPDU tx/rx */
734			    | IEEE80211_HTC_AMSDU	/* A-MSDU tx/rx */
735			    | IEEE80211_HTCAP_MAXAMSDU_3839
736			    				/* max A-MSDU length */
737			    | IEEE80211_HTCAP_SMPS_OFF;	/* SM power save off */
738			;
739
740		/*
741		 * Enable short-GI for HT20 only if the hardware
742		 * advertises support.
743		 * Notably, anything earlier than the AR9287 doesn't.
744		 */
745		if ((ath_hal_getcapability(ah,
746		    HAL_CAP_HT20_SGI, 0, NULL) == HAL_OK) &&
747		    (wmodes & HAL_MODE_HT20)) {
748			device_printf(sc->sc_dev,
749			    "[HT] enabling short-GI in 20MHz mode\n");
750			ic->ic_htcaps |= IEEE80211_HTCAP_SHORTGI20;
751		}
752
753		if (wmodes & HAL_MODE_HT40)
754			ic->ic_htcaps |= IEEE80211_HTCAP_CHWIDTH40
755			    |  IEEE80211_HTCAP_SHORTGI40;
756
757		/*
758		 * TX/RX streams need to be taken into account when
759		 * negotiating which MCS rates it'll receive and
760		 * what MCS rates are available for TX.
761		 */
762		(void) ath_hal_getcapability(ah, HAL_CAP_STREAMS, 0, &txs);
763		(void) ath_hal_getcapability(ah, HAL_CAP_STREAMS, 1, &rxs);
764
765		ath_hal_getrxchainmask(ah, &sc->sc_rxchainmask);
766		ath_hal_gettxchainmask(ah, &sc->sc_txchainmask);
767
768		ic->ic_txstream = txs;
769		ic->ic_rxstream = rxs;
770
771		(void) ath_hal_getcapability(ah, HAL_CAP_RTS_AGGR_LIMIT, 1,
772		    &sc->sc_rts_aggr_limit);
773		if (sc->sc_rts_aggr_limit != (64 * 1024))
774			device_printf(sc->sc_dev,
775			    "[HT] RTS aggregates limited to %d KiB\n",
776			    sc->sc_rts_aggr_limit / 1024);
777
778		device_printf(sc->sc_dev,
779		    "[HT] %d RX streams; %d TX streams\n", rxs, txs);
780	}
781#endif
782
783	/*
784	 * Initial aggregation settings.
785	 */
786	sc->sc_hwq_limit = ATH_AGGR_MIN_QDEPTH;
787	sc->sc_tid_hwq_lo = ATH_AGGR_SCHED_LOW;
788	sc->sc_tid_hwq_hi = ATH_AGGR_SCHED_HIGH;
789
790	/*
791	 * Check if the hardware requires PCI register serialisation.
792	 * Some of the Owl based MACs require this.
793	 */
794	if (mp_ncpus > 1 &&
795	    ath_hal_getcapability(ah, HAL_CAP_SERIALISE_WAR,
796	     0, NULL) == HAL_OK) {
797		sc->sc_ah->ah_config.ah_serialise_reg_war = 1;
798		device_printf(sc->sc_dev,
799		    "Enabling register serialisation\n");
800	}
801
802	/*
803	 * Indicate we need the 802.11 header padded to a
804	 * 32-bit boundary for 4-address and QoS frames.
805	 */
806	ic->ic_flags |= IEEE80211_F_DATAPAD;
807
808	/*
809	 * Query the hal about antenna support.
810	 */
811	sc->sc_defant = ath_hal_getdefantenna(ah);
812
813	/*
814	 * Not all chips have the VEOL support we want to
815	 * use with IBSS beacons; check here for it.
816	 */
817	sc->sc_hasveol = ath_hal_hasveol(ah);
818
819	/* get mac address from hardware */
820	ath_hal_getmac(ah, macaddr);
821	if (sc->sc_hasbmask)
822		ath_hal_getbssidmask(ah, sc->sc_hwbssidmask);
823
824	/* NB: used to size node table key mapping array */
825	ic->ic_max_keyix = sc->sc_keymax;
826	/* call MI attach routine. */
827	ieee80211_ifattach(ic, macaddr);
828	ic->ic_setregdomain = ath_setregdomain;
829	ic->ic_getradiocaps = ath_getradiocaps;
830	sc->sc_opmode = HAL_M_STA;
831
832	/* override default methods */
833	ic->ic_newassoc = ath_newassoc;
834	ic->ic_updateslot = ath_updateslot;
835	ic->ic_wme.wme_update = ath_wme_update;
836	ic->ic_vap_create = ath_vap_create;
837	ic->ic_vap_delete = ath_vap_delete;
838	ic->ic_raw_xmit = ath_raw_xmit;
839	ic->ic_update_mcast = ath_update_mcast;
840	ic->ic_update_promisc = ath_update_promisc;
841	ic->ic_node_alloc = ath_node_alloc;
842	sc->sc_node_free = ic->ic_node_free;
843	ic->ic_node_free = ath_node_free;
844	sc->sc_node_cleanup = ic->ic_node_cleanup;
845	ic->ic_node_cleanup = ath_node_cleanup;
846	ic->ic_node_getsignal = ath_node_getsignal;
847	ic->ic_scan_start = ath_scan_start;
848	ic->ic_scan_end = ath_scan_end;
849	ic->ic_set_channel = ath_set_channel;
850#ifdef	ATH_ENABLE_11N
851	/* 802.11n specific - but just override anyway */
852	sc->sc_addba_request = ic->ic_addba_request;
853	sc->sc_addba_response = ic->ic_addba_response;
854	sc->sc_addba_stop = ic->ic_addba_stop;
855	sc->sc_bar_response = ic->ic_bar_response;
856	sc->sc_addba_response_timeout = ic->ic_addba_response_timeout;
857
858	ic->ic_addba_request = ath_addba_request;
859	ic->ic_addba_response = ath_addba_response;
860	ic->ic_addba_response_timeout = ath_addba_response_timeout;
861	ic->ic_addba_stop = ath_addba_stop;
862	ic->ic_bar_response = ath_bar_response;
863
864	ic->ic_update_chw = ath_update_chw;
865#endif	/* ATH_ENABLE_11N */
866
867#ifdef	ATH_ENABLE_RADIOTAP_VENDOR_EXT
868	/*
869	 * There's one vendor bitmap entry in the RX radiotap
870	 * header; make sure that's taken into account.
871	 */
872	ieee80211_radiotap_attachv(ic,
873	    &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th), 0,
874		ATH_TX_RADIOTAP_PRESENT,
875	    &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th), 1,
876		ATH_RX_RADIOTAP_PRESENT);
877#else
878	/*
879	 * No vendor bitmap/extensions are present.
880	 */
881	ieee80211_radiotap_attach(ic,
882	    &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
883		ATH_TX_RADIOTAP_PRESENT,
884	    &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th),
885		ATH_RX_RADIOTAP_PRESENT);
886#endif	/* ATH_ENABLE_RADIOTAP_VENDOR_EXT */
887
888	/*
889	 * Setup the ALQ logging if required
890	 */
891#ifdef	ATH_DEBUG_ALQ
892	if_ath_alq_init(&sc->sc_alq, device_get_nameunit(sc->sc_dev));
893#endif
894
895	/*
896	 * Setup dynamic sysctl's now that country code and
897	 * regdomain are available from the hal.
898	 */
899	ath_sysctlattach(sc);
900	ath_sysctl_stats_attach(sc);
901	ath_sysctl_hal_attach(sc);
902
903	if (bootverbose)
904		ieee80211_announce(ic);
905	ath_announce(sc);
906	return 0;
907bad2:
908	ath_tx_cleanup(sc);
909	ath_desc_free(sc);
910	ath_txdma_teardown(sc);
911	ath_rxdma_teardown(sc);
912bad:
913	if (ah)
914		ath_hal_detach(ah);
915	if (ifp != NULL) {
916		CURVNET_SET(ifp->if_vnet);
917		if_free(ifp);
918		CURVNET_RESTORE();
919	}
920	sc->sc_invalid = 1;
921	return error;
922}
923
924int
925ath_detach(struct ath_softc *sc)
926{
927	struct ifnet *ifp = sc->sc_ifp;
928
929	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
930		__func__, ifp->if_flags);
931
932	/*
933	 * NB: the order of these is important:
934	 * o stop the chip so no more interrupts will fire
935	 * o call the 802.11 layer before detaching the hal to
936	 *   insure callbacks into the driver to delete global
937	 *   key cache entries can be handled
938	 * o free the taskqueue which drains any pending tasks
939	 * o reclaim the tx queue data structures after calling
940	 *   the 802.11 layer as we'll get called back to reclaim
941	 *   node state and potentially want to use them
942	 * o to cleanup the tx queues the hal is called, so detach
943	 *   it last
944	 * Other than that, it's straightforward...
945	 */
946	ath_stop(ifp);
947	ieee80211_ifdetach(ifp->if_l2com);
948	taskqueue_free(sc->sc_tq);
949#ifdef ATH_TX99_DIAG
950	if (sc->sc_tx99 != NULL)
951		sc->sc_tx99->detach(sc->sc_tx99);
952#endif
953	ath_rate_detach(sc->sc_rc);
954
955#ifdef	ATH_DEBUG_ALQ
956	if_ath_alq_tidyup(&sc->sc_alq);
957#endif
958
959	ath_dfs_detach(sc);
960	ath_desc_free(sc);
961	ath_txdma_teardown(sc);
962	ath_rxdma_teardown(sc);
963	ath_tx_cleanup(sc);
964	ath_hal_detach(sc->sc_ah);	/* NB: sets chip in full sleep */
965
966	CURVNET_SET(ifp->if_vnet);
967	if_free(ifp);
968	CURVNET_RESTORE();
969
970	return 0;
971}
972
973/*
974 * MAC address handling for multiple BSS on the same radio.
975 * The first vap uses the MAC address from the EEPROM.  For
976 * subsequent vap's we set the U/L bit (bit 1) in the MAC
977 * address and use the next six bits as an index.
978 */
979static void
980assign_address(struct ath_softc *sc, uint8_t mac[IEEE80211_ADDR_LEN], int clone)
981{
982	int i;
983
984	if (clone && sc->sc_hasbmask) {
985		/* NB: we only do this if h/w supports multiple bssid */
986		for (i = 0; i < 8; i++)
987			if ((sc->sc_bssidmask & (1<<i)) == 0)
988				break;
989		if (i != 0)
990			mac[0] |= (i << 2)|0x2;
991	} else
992		i = 0;
993	sc->sc_bssidmask |= 1<<i;
994	sc->sc_hwbssidmask[0] &= ~mac[0];
995	if (i == 0)
996		sc->sc_nbssid0++;
997}
998
999static void
1000reclaim_address(struct ath_softc *sc, const uint8_t mac[IEEE80211_ADDR_LEN])
1001{
1002	int i = mac[0] >> 2;
1003	uint8_t mask;
1004
1005	if (i != 0 || --sc->sc_nbssid0 == 0) {
1006		sc->sc_bssidmask &= ~(1<<i);
1007		/* recalculate bssid mask from remaining addresses */
1008		mask = 0xff;
1009		for (i = 1; i < 8; i++)
1010			if (sc->sc_bssidmask & (1<<i))
1011				mask &= ~((i<<2)|0x2);
1012		sc->sc_hwbssidmask[0] |= mask;
1013	}
1014}
1015
1016/*
1017 * Assign a beacon xmit slot.  We try to space out
1018 * assignments so when beacons are staggered the
1019 * traffic coming out of the cab q has maximal time
1020 * to go out before the next beacon is scheduled.
1021 */
1022static int
1023assign_bslot(struct ath_softc *sc)
1024{
1025	u_int slot, free;
1026
1027	free = 0;
1028	for (slot = 0; slot < ATH_BCBUF; slot++)
1029		if (sc->sc_bslot[slot] == NULL) {
1030			if (sc->sc_bslot[(slot+1)%ATH_BCBUF] == NULL &&
1031			    sc->sc_bslot[(slot-1)%ATH_BCBUF] == NULL)
1032				return slot;
1033			free = slot;
1034			/* NB: keep looking for a double slot */
1035		}
1036	return free;
1037}
1038
1039static struct ieee80211vap *
1040ath_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
1041    enum ieee80211_opmode opmode, int flags,
1042    const uint8_t bssid[IEEE80211_ADDR_LEN],
1043    const uint8_t mac0[IEEE80211_ADDR_LEN])
1044{
1045	struct ath_softc *sc = ic->ic_ifp->if_softc;
1046	struct ath_vap *avp;
1047	struct ieee80211vap *vap;
1048	uint8_t mac[IEEE80211_ADDR_LEN];
1049	int needbeacon, error;
1050	enum ieee80211_opmode ic_opmode;
1051
1052	avp = (struct ath_vap *) malloc(sizeof(struct ath_vap),
1053	    M_80211_VAP, M_WAITOK | M_ZERO);
1054	needbeacon = 0;
1055	IEEE80211_ADDR_COPY(mac, mac0);
1056
1057	ATH_LOCK(sc);
1058	ic_opmode = opmode;		/* default to opmode of new vap */
1059	switch (opmode) {
1060	case IEEE80211_M_STA:
1061		if (sc->sc_nstavaps != 0) {	/* XXX only 1 for now */
1062			device_printf(sc->sc_dev, "only 1 sta vap supported\n");
1063			goto bad;
1064		}
1065		if (sc->sc_nvaps) {
1066			/*
1067			 * With multiple vaps we must fall back
1068			 * to s/w beacon miss handling.
1069			 */
1070			flags |= IEEE80211_CLONE_NOBEACONS;
1071		}
1072		if (flags & IEEE80211_CLONE_NOBEACONS) {
1073			/*
1074			 * Station mode w/o beacons are implemented w/ AP mode.
1075			 */
1076			ic_opmode = IEEE80211_M_HOSTAP;
1077		}
1078		break;
1079	case IEEE80211_M_IBSS:
1080		if (sc->sc_nvaps != 0) {	/* XXX only 1 for now */
1081			device_printf(sc->sc_dev,
1082			    "only 1 ibss vap supported\n");
1083			goto bad;
1084		}
1085		needbeacon = 1;
1086		break;
1087	case IEEE80211_M_AHDEMO:
1088#ifdef IEEE80211_SUPPORT_TDMA
1089		if (flags & IEEE80211_CLONE_TDMA) {
1090			if (sc->sc_nvaps != 0) {
1091				device_printf(sc->sc_dev,
1092				    "only 1 tdma vap supported\n");
1093				goto bad;
1094			}
1095			needbeacon = 1;
1096			flags |= IEEE80211_CLONE_NOBEACONS;
1097		}
1098		/* fall thru... */
1099#endif
1100	case IEEE80211_M_MONITOR:
1101		if (sc->sc_nvaps != 0 && ic->ic_opmode != opmode) {
1102			/*
1103			 * Adopt existing mode.  Adding a monitor or ahdemo
1104			 * vap to an existing configuration is of dubious
1105			 * value but should be ok.
1106			 */
1107			/* XXX not right for monitor mode */
1108			ic_opmode = ic->ic_opmode;
1109		}
1110		break;
1111	case IEEE80211_M_HOSTAP:
1112	case IEEE80211_M_MBSS:
1113		needbeacon = 1;
1114		break;
1115	case IEEE80211_M_WDS:
1116		if (sc->sc_nvaps != 0 && ic->ic_opmode == IEEE80211_M_STA) {
1117			device_printf(sc->sc_dev,
1118			    "wds not supported in sta mode\n");
1119			goto bad;
1120		}
1121		/*
1122		 * Silently remove any request for a unique
1123		 * bssid; WDS vap's always share the local
1124		 * mac address.
1125		 */
1126		flags &= ~IEEE80211_CLONE_BSSID;
1127		if (sc->sc_nvaps == 0)
1128			ic_opmode = IEEE80211_M_HOSTAP;
1129		else
1130			ic_opmode = ic->ic_opmode;
1131		break;
1132	default:
1133		device_printf(sc->sc_dev, "unknown opmode %d\n", opmode);
1134		goto bad;
1135	}
1136	/*
1137	 * Check that a beacon buffer is available; the code below assumes it.
1138	 */
1139	if (needbeacon & TAILQ_EMPTY(&sc->sc_bbuf)) {
1140		device_printf(sc->sc_dev, "no beacon buffer available\n");
1141		goto bad;
1142	}
1143
1144	/* STA, AHDEMO? */
1145	if (opmode == IEEE80211_M_HOSTAP || opmode == IEEE80211_M_MBSS) {
1146		assign_address(sc, mac, flags & IEEE80211_CLONE_BSSID);
1147		ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
1148	}
1149
1150	vap = &avp->av_vap;
1151	/* XXX can't hold mutex across if_alloc */
1152	ATH_UNLOCK(sc);
1153	error = ieee80211_vap_setup(ic, vap, name, unit, opmode, flags,
1154	    bssid, mac);
1155	ATH_LOCK(sc);
1156	if (error != 0) {
1157		device_printf(sc->sc_dev, "%s: error %d creating vap\n",
1158		    __func__, error);
1159		goto bad2;
1160	}
1161
1162	/* h/w crypto support */
1163	vap->iv_key_alloc = ath_key_alloc;
1164	vap->iv_key_delete = ath_key_delete;
1165	vap->iv_key_set = ath_key_set;
1166	vap->iv_key_update_begin = ath_key_update_begin;
1167	vap->iv_key_update_end = ath_key_update_end;
1168
1169	/* override various methods */
1170	avp->av_recv_mgmt = vap->iv_recv_mgmt;
1171	vap->iv_recv_mgmt = ath_recv_mgmt;
1172	vap->iv_reset = ath_reset_vap;
1173	vap->iv_update_beacon = ath_beacon_update;
1174	avp->av_newstate = vap->iv_newstate;
1175	vap->iv_newstate = ath_newstate;
1176	avp->av_bmiss = vap->iv_bmiss;
1177	vap->iv_bmiss = ath_bmiss_vap;
1178
1179	avp->av_node_ps = vap->iv_node_ps;
1180	vap->iv_node_ps = ath_node_powersave;
1181
1182	avp->av_set_tim = vap->iv_set_tim;
1183	vap->iv_set_tim = ath_node_set_tim;
1184
1185	/* Set default parameters */
1186
1187	/*
1188	 * Anything earlier than some AR9300 series MACs don't
1189	 * support a smaller MPDU density.
1190	 */
1191	vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_8;
1192	/*
1193	 * All NICs can handle the maximum size, however
1194	 * AR5416 based MACs can only TX aggregates w/ RTS
1195	 * protection when the total aggregate size is <= 8k.
1196	 * However, for now that's enforced by the TX path.
1197	 */
1198	vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_64K;
1199
1200	avp->av_bslot = -1;
1201	if (needbeacon) {
1202		/*
1203		 * Allocate beacon state and setup the q for buffered
1204		 * multicast frames.  We know a beacon buffer is
1205		 * available because we checked above.
1206		 */
1207		avp->av_bcbuf = TAILQ_FIRST(&sc->sc_bbuf);
1208		TAILQ_REMOVE(&sc->sc_bbuf, avp->av_bcbuf, bf_list);
1209		if (opmode != IEEE80211_M_IBSS || !sc->sc_hasveol) {
1210			/*
1211			 * Assign the vap to a beacon xmit slot.  As above
1212			 * this cannot fail to find a free one.
1213			 */
1214			avp->av_bslot = assign_bslot(sc);
1215			KASSERT(sc->sc_bslot[avp->av_bslot] == NULL,
1216			    ("beacon slot %u not empty", avp->av_bslot));
1217			sc->sc_bslot[avp->av_bslot] = vap;
1218			sc->sc_nbcnvaps++;
1219		}
1220		if (sc->sc_hastsfadd && sc->sc_nbcnvaps > 0) {
1221			/*
1222			 * Multple vaps are to transmit beacons and we
1223			 * have h/w support for TSF adjusting; enable
1224			 * use of staggered beacons.
1225			 */
1226			sc->sc_stagbeacons = 1;
1227		}
1228		ath_txq_init(sc, &avp->av_mcastq, ATH_TXQ_SWQ);
1229	}
1230
1231	ic->ic_opmode = ic_opmode;
1232	if (opmode != IEEE80211_M_WDS) {
1233		sc->sc_nvaps++;
1234		if (opmode == IEEE80211_M_STA)
1235			sc->sc_nstavaps++;
1236		if (opmode == IEEE80211_M_MBSS)
1237			sc->sc_nmeshvaps++;
1238	}
1239	switch (ic_opmode) {
1240	case IEEE80211_M_IBSS:
1241		sc->sc_opmode = HAL_M_IBSS;
1242		break;
1243	case IEEE80211_M_STA:
1244		sc->sc_opmode = HAL_M_STA;
1245		break;
1246	case IEEE80211_M_AHDEMO:
1247#ifdef IEEE80211_SUPPORT_TDMA
1248		if (vap->iv_caps & IEEE80211_C_TDMA) {
1249			sc->sc_tdma = 1;
1250			/* NB: disable tsf adjust */
1251			sc->sc_stagbeacons = 0;
1252		}
1253		/*
1254		 * NB: adhoc demo mode is a pseudo mode; to the hal it's
1255		 * just ap mode.
1256		 */
1257		/* fall thru... */
1258#endif
1259	case IEEE80211_M_HOSTAP:
1260	case IEEE80211_M_MBSS:
1261		sc->sc_opmode = HAL_M_HOSTAP;
1262		break;
1263	case IEEE80211_M_MONITOR:
1264		sc->sc_opmode = HAL_M_MONITOR;
1265		break;
1266	default:
1267		/* XXX should not happen */
1268		break;
1269	}
1270	if (sc->sc_hastsfadd) {
1271		/*
1272		 * Configure whether or not TSF adjust should be done.
1273		 */
1274		ath_hal_settsfadjust(sc->sc_ah, sc->sc_stagbeacons);
1275	}
1276	if (flags & IEEE80211_CLONE_NOBEACONS) {
1277		/*
1278		 * Enable s/w beacon miss handling.
1279		 */
1280		sc->sc_swbmiss = 1;
1281	}
1282	ATH_UNLOCK(sc);
1283
1284	/* complete setup */
1285	ieee80211_vap_attach(vap, ath_media_change, ieee80211_media_status);
1286	return vap;
1287bad2:
1288	reclaim_address(sc, mac);
1289	ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
1290bad:
1291	free(avp, M_80211_VAP);
1292	ATH_UNLOCK(sc);
1293	return NULL;
1294}
1295
1296static void
1297ath_vap_delete(struct ieee80211vap *vap)
1298{
1299	struct ieee80211com *ic = vap->iv_ic;
1300	struct ifnet *ifp = ic->ic_ifp;
1301	struct ath_softc *sc = ifp->if_softc;
1302	struct ath_hal *ah = sc->sc_ah;
1303	struct ath_vap *avp = ATH_VAP(vap);
1304
1305	DPRINTF(sc, ATH_DEBUG_RESET, "%s: called\n", __func__);
1306	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1307		/*
1308		 * Quiesce the hardware while we remove the vap.  In
1309		 * particular we need to reclaim all references to
1310		 * the vap state by any frames pending on the tx queues.
1311		 */
1312		ath_hal_intrset(ah, 0);		/* disable interrupts */
1313		ath_draintxq(sc, ATH_RESET_DEFAULT);		/* stop hw xmit side */
1314		/* XXX Do all frames from all vaps/nodes need draining here? */
1315		ath_stoprecv(sc, 1);		/* stop recv side */
1316	}
1317
1318	ieee80211_vap_detach(vap);
1319
1320	/*
1321	 * XXX Danger Will Robinson! Danger!
1322	 *
1323	 * Because ieee80211_vap_detach() can queue a frame (the station
1324	 * diassociate message?) after we've drained the TXQ and
1325	 * flushed the software TXQ, we will end up with a frame queued
1326	 * to a node whose vap is about to be freed.
1327	 *
1328	 * To work around this, flush the hardware/software again.
1329	 * This may be racy - the ath task may be running and the packet
1330	 * may be being scheduled between sw->hw txq. Tsk.
1331	 *
1332	 * TODO: figure out why a new node gets allocated somewhere around
1333	 * here (after the ath_tx_swq() call; and after an ath_stop_locked()
1334	 * call!)
1335	 */
1336
1337	ath_draintxq(sc, ATH_RESET_DEFAULT);
1338
1339	ATH_LOCK(sc);
1340	/*
1341	 * Reclaim beacon state.  Note this must be done before
1342	 * the vap instance is reclaimed as we may have a reference
1343	 * to it in the buffer for the beacon frame.
1344	 */
1345	if (avp->av_bcbuf != NULL) {
1346		if (avp->av_bslot != -1) {
1347			sc->sc_bslot[avp->av_bslot] = NULL;
1348			sc->sc_nbcnvaps--;
1349		}
1350		ath_beacon_return(sc, avp->av_bcbuf);
1351		avp->av_bcbuf = NULL;
1352		if (sc->sc_nbcnvaps == 0) {
1353			sc->sc_stagbeacons = 0;
1354			if (sc->sc_hastsfadd)
1355				ath_hal_settsfadjust(sc->sc_ah, 0);
1356		}
1357		/*
1358		 * Reclaim any pending mcast frames for the vap.
1359		 */
1360		ath_tx_draintxq(sc, &avp->av_mcastq);
1361		ATH_TXQ_LOCK_DESTROY(&avp->av_mcastq);
1362	}
1363	/*
1364	 * Update bookkeeping.
1365	 */
1366	if (vap->iv_opmode == IEEE80211_M_STA) {
1367		sc->sc_nstavaps--;
1368		if (sc->sc_nstavaps == 0 && sc->sc_swbmiss)
1369			sc->sc_swbmiss = 0;
1370	} else if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1371	    vap->iv_opmode == IEEE80211_M_MBSS) {
1372		reclaim_address(sc, vap->iv_myaddr);
1373		ath_hal_setbssidmask(ah, sc->sc_hwbssidmask);
1374		if (vap->iv_opmode == IEEE80211_M_MBSS)
1375			sc->sc_nmeshvaps--;
1376	}
1377	if (vap->iv_opmode != IEEE80211_M_WDS)
1378		sc->sc_nvaps--;
1379#ifdef IEEE80211_SUPPORT_TDMA
1380	/* TDMA operation ceases when the last vap is destroyed */
1381	if (sc->sc_tdma && sc->sc_nvaps == 0) {
1382		sc->sc_tdma = 0;
1383		sc->sc_swbmiss = 0;
1384	}
1385#endif
1386	free(avp, M_80211_VAP);
1387
1388	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1389		/*
1390		 * Restart rx+tx machines if still running (RUNNING will
1391		 * be reset if we just destroyed the last vap).
1392		 */
1393		if (ath_startrecv(sc) != 0)
1394			if_printf(ifp, "%s: unable to restart recv logic\n",
1395			    __func__);
1396		if (sc->sc_beacons) {		/* restart beacons */
1397#ifdef IEEE80211_SUPPORT_TDMA
1398			if (sc->sc_tdma)
1399				ath_tdma_config(sc, NULL);
1400			else
1401#endif
1402				ath_beacon_config(sc, NULL);
1403		}
1404		ath_hal_intrset(ah, sc->sc_imask);
1405	}
1406	ATH_UNLOCK(sc);
1407}
1408
1409void
1410ath_suspend(struct ath_softc *sc)
1411{
1412	struct ifnet *ifp = sc->sc_ifp;
1413	struct ieee80211com *ic = ifp->if_l2com;
1414
1415	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1416		__func__, ifp->if_flags);
1417
1418	sc->sc_resume_up = (ifp->if_flags & IFF_UP) != 0;
1419
1420	ieee80211_suspend_all(ic);
1421	/*
1422	 * NB: don't worry about putting the chip in low power
1423	 * mode; pci will power off our socket on suspend and
1424	 * CardBus detaches the device.
1425	 */
1426
1427	/*
1428	 * XXX ensure none of the taskqueues are running
1429	 * XXX ensure sc_invalid is 1
1430	 * XXX ensure the calibration callout is disabled
1431	 */
1432
1433	/* Disable the PCIe PHY, complete with workarounds */
1434	ath_hal_enablepcie(sc->sc_ah, 1, 1);
1435}
1436
1437/*
1438 * Reset the key cache since some parts do not reset the
1439 * contents on resume.  First we clear all entries, then
1440 * re-load keys that the 802.11 layer assumes are setup
1441 * in h/w.
1442 */
1443static void
1444ath_reset_keycache(struct ath_softc *sc)
1445{
1446	struct ifnet *ifp = sc->sc_ifp;
1447	struct ieee80211com *ic = ifp->if_l2com;
1448	struct ath_hal *ah = sc->sc_ah;
1449	int i;
1450
1451	for (i = 0; i < sc->sc_keymax; i++)
1452		ath_hal_keyreset(ah, i);
1453	ieee80211_crypto_reload_keys(ic);
1454}
1455
1456void
1457ath_resume(struct ath_softc *sc)
1458{
1459	struct ifnet *ifp = sc->sc_ifp;
1460	struct ieee80211com *ic = ifp->if_l2com;
1461	struct ath_hal *ah = sc->sc_ah;
1462	HAL_STATUS status;
1463
1464	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1465		__func__, ifp->if_flags);
1466
1467	/* Re-enable PCIe, re-enable the PCIe bus */
1468	ath_hal_enablepcie(ah, 0, 0);
1469
1470	/*
1471	 * Must reset the chip before we reload the
1472	 * keycache as we were powered down on suspend.
1473	 */
1474	ath_hal_reset(ah, sc->sc_opmode,
1475	    sc->sc_curchan != NULL ? sc->sc_curchan : ic->ic_curchan,
1476	    AH_FALSE, &status);
1477	ath_reset_keycache(sc);
1478
1479	/* Let DFS at it in case it's a DFS channel */
1480	ath_dfs_radar_enable(sc, ic->ic_curchan);
1481
1482	/* Restore the LED configuration */
1483	ath_led_config(sc);
1484	ath_hal_setledstate(ah, HAL_LED_INIT);
1485
1486	if (sc->sc_resume_up)
1487		ieee80211_resume_all(ic);
1488
1489	/* XXX beacons ? */
1490}
1491
1492void
1493ath_shutdown(struct ath_softc *sc)
1494{
1495	struct ifnet *ifp = sc->sc_ifp;
1496
1497	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1498		__func__, ifp->if_flags);
1499
1500	ath_stop(ifp);
1501	/* NB: no point powering down chip as we're about to reboot */
1502}
1503
1504/*
1505 * Interrupt handler.  Most of the actual processing is deferred.
1506 */
1507void
1508ath_intr(void *arg)
1509{
1510	struct ath_softc *sc = arg;
1511	struct ifnet *ifp = sc->sc_ifp;
1512	struct ath_hal *ah = sc->sc_ah;
1513	HAL_INT status = 0;
1514	uint32_t txqs;
1515
1516	/*
1517	 * If we're inside a reset path, just print a warning and
1518	 * clear the ISR. The reset routine will finish it for us.
1519	 */
1520	ATH_PCU_LOCK(sc);
1521	if (sc->sc_inreset_cnt) {
1522		HAL_INT status;
1523		ath_hal_getisr(ah, &status);	/* clear ISR */
1524		ath_hal_intrset(ah, 0);		/* disable further intr's */
1525		DPRINTF(sc, ATH_DEBUG_ANY,
1526		    "%s: in reset, ignoring: status=0x%x\n",
1527		    __func__, status);
1528		ATH_PCU_UNLOCK(sc);
1529		return;
1530	}
1531
1532	if (sc->sc_invalid) {
1533		/*
1534		 * The hardware is not ready/present, don't touch anything.
1535		 * Note this can happen early on if the IRQ is shared.
1536		 */
1537		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
1538		ATH_PCU_UNLOCK(sc);
1539		return;
1540	}
1541	if (!ath_hal_intrpend(ah)) {		/* shared irq, not for us */
1542		ATH_PCU_UNLOCK(sc);
1543		return;
1544	}
1545
1546	if ((ifp->if_flags & IFF_UP) == 0 ||
1547	    (ifp->if_drv_flags & IFF_DRV_RUNNING) == 0) {
1548		HAL_INT status;
1549
1550		DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1551			__func__, ifp->if_flags);
1552		ath_hal_getisr(ah, &status);	/* clear ISR */
1553		ath_hal_intrset(ah, 0);		/* disable further intr's */
1554		ATH_PCU_UNLOCK(sc);
1555		return;
1556	}
1557
1558	/*
1559	 * Figure out the reason(s) for the interrupt.  Note
1560	 * that the hal returns a pseudo-ISR that may include
1561	 * bits we haven't explicitly enabled so we mask the
1562	 * value to insure we only process bits we requested.
1563	 */
1564	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
1565	DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
1566	ATH_KTR(sc, ATH_KTR_INTERRUPTS, 1, "ath_intr: mask=0x%.8x", status);
1567#ifdef	ATH_KTR_INTR_DEBUG
1568	ATH_KTR(sc, ATH_KTR_INTERRUPTS, 5,
1569	    "ath_intr: ISR=0x%.8x, ISR_S0=0x%.8x, ISR_S1=0x%.8x, ISR_S2=0x%.8x, ISR_S5=0x%.8x",
1570	    ah->ah_intrstate[0],
1571	    ah->ah_intrstate[1],
1572	    ah->ah_intrstate[2],
1573	    ah->ah_intrstate[3],
1574	    ah->ah_intrstate[6]);
1575#endif
1576
1577	/* Squirrel away SYNC interrupt debugging */
1578	if (ah->ah_syncstate != 0) {
1579		int i;
1580		for (i = 0; i < 32; i++)
1581			if (ah->ah_syncstate & (i << i))
1582				sc->sc_intr_stats.sync_intr[i]++;
1583	}
1584
1585	status &= sc->sc_imask;			/* discard unasked for bits */
1586
1587	/* Short-circuit un-handled interrupts */
1588	if (status == 0x0) {
1589		ATH_PCU_UNLOCK(sc);
1590		return;
1591	}
1592
1593	/*
1594	 * Take a note that we're inside the interrupt handler, so
1595	 * the reset routines know to wait.
1596	 */
1597	sc->sc_intr_cnt++;
1598	ATH_PCU_UNLOCK(sc);
1599
1600	/*
1601	 * Handle the interrupt. We won't run concurrent with the reset
1602	 * or channel change routines as they'll wait for sc_intr_cnt
1603	 * to be 0 before continuing.
1604	 */
1605	if (status & HAL_INT_FATAL) {
1606		sc->sc_stats.ast_hardware++;
1607		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
1608		taskqueue_enqueue(sc->sc_tq, &sc->sc_fataltask);
1609	} else {
1610		if (status & HAL_INT_SWBA) {
1611			/*
1612			 * Software beacon alert--time to send a beacon.
1613			 * Handle beacon transmission directly; deferring
1614			 * this is too slow to meet timing constraints
1615			 * under load.
1616			 */
1617#ifdef IEEE80211_SUPPORT_TDMA
1618			if (sc->sc_tdma) {
1619				if (sc->sc_tdmaswba == 0) {
1620					struct ieee80211com *ic = ifp->if_l2com;
1621					struct ieee80211vap *vap =
1622					    TAILQ_FIRST(&ic->ic_vaps);
1623					ath_tdma_beacon_send(sc, vap);
1624					sc->sc_tdmaswba =
1625					    vap->iv_tdma->tdma_bintval;
1626				} else
1627					sc->sc_tdmaswba--;
1628			} else
1629#endif
1630			{
1631				ath_beacon_proc(sc, 0);
1632#ifdef IEEE80211_SUPPORT_SUPERG
1633				/*
1634				 * Schedule the rx taskq in case there's no
1635				 * traffic so any frames held on the staging
1636				 * queue are aged and potentially flushed.
1637				 */
1638				taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1639#endif
1640			}
1641		}
1642		if (status & HAL_INT_RXEOL) {
1643			int imask;
1644			ATH_KTR(sc, ATH_KTR_ERROR, 0, "ath_intr: RXEOL");
1645			ATH_PCU_LOCK(sc);
1646			/*
1647			 * NB: the hardware should re-read the link when
1648			 *     RXE bit is written, but it doesn't work at
1649			 *     least on older hardware revs.
1650			 */
1651			sc->sc_stats.ast_rxeol++;
1652			/*
1653			 * Disable RXEOL/RXORN - prevent an interrupt
1654			 * storm until the PCU logic can be reset.
1655			 * In case the interface is reset some other
1656			 * way before "sc_kickpcu" is called, don't
1657			 * modify sc_imask - that way if it is reset
1658			 * by a call to ath_reset() somehow, the
1659			 * interrupt mask will be correctly reprogrammed.
1660			 */
1661			imask = sc->sc_imask;
1662			imask &= ~(HAL_INT_RXEOL | HAL_INT_RXORN);
1663			ath_hal_intrset(ah, imask);
1664			/*
1665			 * Only blank sc_rxlink if we've not yet kicked
1666			 * the PCU.
1667			 *
1668			 * This isn't entirely correct - the correct solution
1669			 * would be to have a PCU lock and engage that for
1670			 * the duration of the PCU fiddling; which would include
1671			 * running the RX process. Otherwise we could end up
1672			 * messing up the RX descriptor chain and making the
1673			 * RX desc list much shorter.
1674			 */
1675			if (! sc->sc_kickpcu)
1676				sc->sc_rxlink = NULL;
1677			sc->sc_kickpcu = 1;
1678			/*
1679			 * Enqueue an RX proc, to handled whatever
1680			 * is in the RX queue.
1681			 * This will then kick the PCU.
1682			 */
1683			taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1684			ATH_PCU_UNLOCK(sc);
1685		}
1686		if (status & HAL_INT_TXURN) {
1687			sc->sc_stats.ast_txurn++;
1688			/* bump tx trigger level */
1689			ath_hal_updatetxtriglevel(ah, AH_TRUE);
1690		}
1691		/*
1692		 * Handle both the legacy and RX EDMA interrupt bits.
1693		 * Note that HAL_INT_RXLP is also HAL_INT_RXDESC.
1694		 */
1695		if (status & (HAL_INT_RX | HAL_INT_RXHP | HAL_INT_RXLP)) {
1696			sc->sc_stats.ast_rx_intr++;
1697			taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1698		}
1699		if (status & HAL_INT_TX) {
1700			sc->sc_stats.ast_tx_intr++;
1701			/*
1702			 * Grab all the currently set bits in the HAL txq bitmap
1703			 * and blank them. This is the only place we should be
1704			 * doing this.
1705			 */
1706			if (! sc->sc_isedma) {
1707				ATH_PCU_LOCK(sc);
1708				txqs = 0xffffffff;
1709				ath_hal_gettxintrtxqs(sc->sc_ah, &txqs);
1710				ATH_KTR(sc, ATH_KTR_INTERRUPTS, 3,
1711				    "ath_intr: TX; txqs=0x%08x, txq_active was 0x%08x, now 0x%08x",
1712				    txqs,
1713				    sc->sc_txq_active,
1714				    sc->sc_txq_active | txqs);
1715				sc->sc_txq_active |= txqs;
1716				ATH_PCU_UNLOCK(sc);
1717			}
1718			taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
1719		}
1720		if (status & HAL_INT_BMISS) {
1721			sc->sc_stats.ast_bmiss++;
1722			taskqueue_enqueue(sc->sc_tq, &sc->sc_bmisstask);
1723		}
1724		if (status & HAL_INT_GTT)
1725			sc->sc_stats.ast_tx_timeout++;
1726		if (status & HAL_INT_CST)
1727			sc->sc_stats.ast_tx_cst++;
1728		if (status & HAL_INT_MIB) {
1729			sc->sc_stats.ast_mib++;
1730			ATH_PCU_LOCK(sc);
1731			/*
1732			 * Disable interrupts until we service the MIB
1733			 * interrupt; otherwise it will continue to fire.
1734			 */
1735			ath_hal_intrset(ah, 0);
1736			/*
1737			 * Let the hal handle the event.  We assume it will
1738			 * clear whatever condition caused the interrupt.
1739			 */
1740			ath_hal_mibevent(ah, &sc->sc_halstats);
1741			/*
1742			 * Don't reset the interrupt if we've just
1743			 * kicked the PCU, or we may get a nested
1744			 * RXEOL before the rxproc has had a chance
1745			 * to run.
1746			 */
1747			if (sc->sc_kickpcu == 0)
1748				ath_hal_intrset(ah, sc->sc_imask);
1749			ATH_PCU_UNLOCK(sc);
1750		}
1751		if (status & HAL_INT_RXORN) {
1752			/* NB: hal marks HAL_INT_FATAL when RXORN is fatal */
1753			ATH_KTR(sc, ATH_KTR_ERROR, 0, "ath_intr: RXORN");
1754			sc->sc_stats.ast_rxorn++;
1755		}
1756	}
1757	ATH_PCU_LOCK(sc);
1758	sc->sc_intr_cnt--;
1759	ATH_PCU_UNLOCK(sc);
1760}
1761
1762static void
1763ath_fatal_proc(void *arg, int pending)
1764{
1765	struct ath_softc *sc = arg;
1766	struct ifnet *ifp = sc->sc_ifp;
1767	u_int32_t *state;
1768	u_int32_t len;
1769	void *sp;
1770
1771	if_printf(ifp, "hardware error; resetting\n");
1772	/*
1773	 * Fatal errors are unrecoverable.  Typically these
1774	 * are caused by DMA errors.  Collect h/w state from
1775	 * the hal so we can diagnose what's going on.
1776	 */
1777	if (ath_hal_getfatalstate(sc->sc_ah, &sp, &len)) {
1778		KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
1779		state = sp;
1780		if_printf(ifp, "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n",
1781		    state[0], state[1] , state[2], state[3],
1782		    state[4], state[5]);
1783	}
1784	ath_reset(ifp, ATH_RESET_NOLOSS);
1785}
1786
1787static void
1788ath_bmiss_vap(struct ieee80211vap *vap)
1789{
1790	/*
1791	 * Workaround phantom bmiss interrupts by sanity-checking
1792	 * the time of our last rx'd frame.  If it is within the
1793	 * beacon miss interval then ignore the interrupt.  If it's
1794	 * truly a bmiss we'll get another interrupt soon and that'll
1795	 * be dispatched up for processing.  Note this applies only
1796	 * for h/w beacon miss events.
1797	 */
1798	if ((vap->iv_flags_ext & IEEE80211_FEXT_SWBMISS) == 0) {
1799		struct ifnet *ifp = vap->iv_ic->ic_ifp;
1800		struct ath_softc *sc = ifp->if_softc;
1801		u_int64_t lastrx = sc->sc_lastrx;
1802		u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
1803		/* XXX should take a locked ref to iv_bss */
1804		u_int bmisstimeout =
1805			vap->iv_bmissthreshold * vap->iv_bss->ni_intval * 1024;
1806
1807		DPRINTF(sc, ATH_DEBUG_BEACON,
1808		    "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
1809		    __func__, (unsigned long long) tsf,
1810		    (unsigned long long)(tsf - lastrx),
1811		    (unsigned long long) lastrx, bmisstimeout);
1812
1813		if (tsf - lastrx <= bmisstimeout) {
1814			sc->sc_stats.ast_bmiss_phantom++;
1815			return;
1816		}
1817	}
1818	ATH_VAP(vap)->av_bmiss(vap);
1819}
1820
1821static int
1822ath_hal_gethangstate(struct ath_hal *ah, uint32_t mask, uint32_t *hangs)
1823{
1824	uint32_t rsize;
1825	void *sp;
1826
1827	if (!ath_hal_getdiagstate(ah, HAL_DIAG_CHECK_HANGS, &mask, sizeof(mask), &sp, &rsize))
1828		return 0;
1829	KASSERT(rsize == sizeof(uint32_t), ("resultsize %u", rsize));
1830	*hangs = *(uint32_t *)sp;
1831	return 1;
1832}
1833
1834static void
1835ath_bmiss_proc(void *arg, int pending)
1836{
1837	struct ath_softc *sc = arg;
1838	struct ifnet *ifp = sc->sc_ifp;
1839	uint32_t hangs;
1840
1841	DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
1842
1843	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0) {
1844		if_printf(ifp, "bb hang detected (0x%x), resetting\n", hangs);
1845		ath_reset(ifp, ATH_RESET_NOLOSS);
1846	} else
1847		ieee80211_beacon_miss(ifp->if_l2com);
1848}
1849
1850/*
1851 * Handle TKIP MIC setup to deal hardware that doesn't do MIC
1852 * calcs together with WME.  If necessary disable the crypto
1853 * hardware and mark the 802.11 state so keys will be setup
1854 * with the MIC work done in software.
1855 */
1856static void
1857ath_settkipmic(struct ath_softc *sc)
1858{
1859	struct ifnet *ifp = sc->sc_ifp;
1860	struct ieee80211com *ic = ifp->if_l2com;
1861
1862	if ((ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIP) && !sc->sc_wmetkipmic) {
1863		if (ic->ic_flags & IEEE80211_F_WME) {
1864			ath_hal_settkipmic(sc->sc_ah, AH_FALSE);
1865			ic->ic_cryptocaps &= ~IEEE80211_CRYPTO_TKIPMIC;
1866		} else {
1867			ath_hal_settkipmic(sc->sc_ah, AH_TRUE);
1868			ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
1869		}
1870	}
1871}
1872
1873static void
1874ath_init(void *arg)
1875{
1876	struct ath_softc *sc = (struct ath_softc *) arg;
1877	struct ifnet *ifp = sc->sc_ifp;
1878	struct ieee80211com *ic = ifp->if_l2com;
1879	struct ath_hal *ah = sc->sc_ah;
1880	HAL_STATUS status;
1881
1882	DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1883		__func__, ifp->if_flags);
1884
1885	ATH_LOCK(sc);
1886	/*
1887	 * Stop anything previously setup.  This is safe
1888	 * whether this is the first time through or not.
1889	 */
1890	ath_stop_locked(ifp);
1891
1892	/*
1893	 * The basic interface to setting the hardware in a good
1894	 * state is ``reset''.  On return the hardware is known to
1895	 * be powered up and with interrupts disabled.  This must
1896	 * be followed by initialization of the appropriate bits
1897	 * and then setup of the interrupt mask.
1898	 */
1899	ath_settkipmic(sc);
1900	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_FALSE, &status)) {
1901		if_printf(ifp, "unable to reset hardware; hal status %u\n",
1902			status);
1903		ATH_UNLOCK(sc);
1904		return;
1905	}
1906	ath_chan_change(sc, ic->ic_curchan);
1907
1908	/* Let DFS at it in case it's a DFS channel */
1909	ath_dfs_radar_enable(sc, ic->ic_curchan);
1910
1911	/*
1912	 * Likewise this is set during reset so update
1913	 * state cached in the driver.
1914	 */
1915	sc->sc_diversity = ath_hal_getdiversity(ah);
1916	sc->sc_lastlongcal = 0;
1917	sc->sc_resetcal = 1;
1918	sc->sc_lastcalreset = 0;
1919	sc->sc_lastani = 0;
1920	sc->sc_lastshortcal = 0;
1921	sc->sc_doresetcal = AH_FALSE;
1922	/*
1923	 * Beacon timers were cleared here; give ath_newstate()
1924	 * a hint that the beacon timers should be poked when
1925	 * things transition to the RUN state.
1926	 */
1927	sc->sc_beacons = 0;
1928
1929	/*
1930	 * Setup the hardware after reset: the key cache
1931	 * is filled as needed and the receive engine is
1932	 * set going.  Frame transmit is handled entirely
1933	 * in the frame output path; there's nothing to do
1934	 * here except setup the interrupt mask.
1935	 */
1936	if (ath_startrecv(sc) != 0) {
1937		if_printf(ifp, "unable to start recv logic\n");
1938		ATH_UNLOCK(sc);
1939		return;
1940	}
1941
1942	/*
1943	 * Enable interrupts.
1944	 */
1945	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
1946		  | HAL_INT_RXEOL | HAL_INT_RXORN
1947		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
1948
1949	/*
1950	 * Enable RX EDMA bits.  Note these overlap with
1951	 * HAL_INT_RX and HAL_INT_RXDESC respectively.
1952	 */
1953	if (sc->sc_isedma)
1954		sc->sc_imask |= (HAL_INT_RXHP | HAL_INT_RXLP);
1955
1956	/*
1957	 * Enable MIB interrupts when there are hardware phy counters.
1958	 * Note we only do this (at the moment) for station mode.
1959	 */
1960	if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
1961		sc->sc_imask |= HAL_INT_MIB;
1962
1963	/* Enable global TX timeout and carrier sense timeout if available */
1964	if (ath_hal_gtxto_supported(ah))
1965		sc->sc_imask |= HAL_INT_GTT;
1966
1967	DPRINTF(sc, ATH_DEBUG_RESET, "%s: imask=0x%x\n",
1968		__func__, sc->sc_imask);
1969
1970	ifp->if_drv_flags |= IFF_DRV_RUNNING;
1971	callout_reset(&sc->sc_wd_ch, hz, ath_watchdog, sc);
1972	ath_hal_intrset(ah, sc->sc_imask);
1973
1974	ATH_UNLOCK(sc);
1975
1976#ifdef ATH_TX99_DIAG
1977	if (sc->sc_tx99 != NULL)
1978		sc->sc_tx99->start(sc->sc_tx99);
1979	else
1980#endif
1981	ieee80211_start_all(ic);		/* start all vap's */
1982}
1983
1984static void
1985ath_stop_locked(struct ifnet *ifp)
1986{
1987	struct ath_softc *sc = ifp->if_softc;
1988	struct ath_hal *ah = sc->sc_ah;
1989
1990	DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1991		__func__, sc->sc_invalid, ifp->if_flags);
1992
1993	ATH_LOCK_ASSERT(sc);
1994	if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
1995		/*
1996		 * Shutdown the hardware and driver:
1997		 *    reset 802.11 state machine
1998		 *    turn off timers
1999		 *    disable interrupts
2000		 *    turn off the radio
2001		 *    clear transmit machinery
2002		 *    clear receive machinery
2003		 *    drain and release tx queues
2004		 *    reclaim beacon resources
2005		 *    power down hardware
2006		 *
2007		 * Note that some of this work is not possible if the
2008		 * hardware is gone (invalid).
2009		 */
2010#ifdef ATH_TX99_DIAG
2011		if (sc->sc_tx99 != NULL)
2012			sc->sc_tx99->stop(sc->sc_tx99);
2013#endif
2014		callout_stop(&sc->sc_wd_ch);
2015		sc->sc_wd_timer = 0;
2016		ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
2017		if (!sc->sc_invalid) {
2018			if (sc->sc_softled) {
2019				callout_stop(&sc->sc_ledtimer);
2020				ath_hal_gpioset(ah, sc->sc_ledpin,
2021					!sc->sc_ledon);
2022				sc->sc_blinking = 0;
2023			}
2024			ath_hal_intrset(ah, 0);
2025		}
2026		ath_draintxq(sc, ATH_RESET_DEFAULT);
2027		if (!sc->sc_invalid) {
2028			ath_stoprecv(sc, 1);
2029			ath_hal_phydisable(ah);
2030		} else
2031			sc->sc_rxlink = NULL;
2032		ath_beacon_free(sc);	/* XXX not needed */
2033	}
2034}
2035
2036#define	MAX_TXRX_ITERATIONS	1000
2037static void
2038ath_txrx_stop_locked(struct ath_softc *sc)
2039{
2040	int i = MAX_TXRX_ITERATIONS;
2041
2042	ATH_UNLOCK_ASSERT(sc);
2043	ATH_PCU_LOCK_ASSERT(sc);
2044
2045	/*
2046	 * Sleep until all the pending operations have completed.
2047	 *
2048	 * The caller must ensure that reset has been incremented
2049	 * or the pending operations may continue being queued.
2050	 */
2051	while (sc->sc_rxproc_cnt || sc->sc_txproc_cnt ||
2052	    sc->sc_txstart_cnt || sc->sc_intr_cnt) {
2053		if (i <= 0)
2054			break;
2055		msleep(sc, &sc->sc_pcu_mtx, 0, "ath_txrx_stop", 1);
2056		i--;
2057	}
2058
2059	if (i <= 0)
2060		device_printf(sc->sc_dev,
2061		    "%s: didn't finish after %d iterations\n",
2062		    __func__, MAX_TXRX_ITERATIONS);
2063}
2064#undef	MAX_TXRX_ITERATIONS
2065
2066#if 0
2067static void
2068ath_txrx_stop(struct ath_softc *sc)
2069{
2070	ATH_UNLOCK_ASSERT(sc);
2071	ATH_PCU_UNLOCK_ASSERT(sc);
2072
2073	ATH_PCU_LOCK(sc);
2074	ath_txrx_stop_locked(sc);
2075	ATH_PCU_UNLOCK(sc);
2076}
2077#endif
2078
2079static void
2080ath_txrx_start(struct ath_softc *sc)
2081{
2082
2083	taskqueue_unblock(sc->sc_tq);
2084}
2085
2086/*
2087 * Grab the reset lock, and wait around until noone else
2088 * is trying to do anything with it.
2089 *
2090 * This is totally horrible but we can't hold this lock for
2091 * long enough to do TX/RX or we end up with net80211/ip stack
2092 * LORs and eventual deadlock.
2093 *
2094 * "dowait" signals whether to spin, waiting for the reset
2095 * lock count to reach 0. This should (for now) only be used
2096 * during the reset path, as the rest of the code may not
2097 * be locking-reentrant enough to behave correctly.
2098 *
2099 * Another, cleaner way should be found to serialise all of
2100 * these operations.
2101 */
2102#define	MAX_RESET_ITERATIONS	10
2103static int
2104ath_reset_grablock(struct ath_softc *sc, int dowait)
2105{
2106	int w = 0;
2107	int i = MAX_RESET_ITERATIONS;
2108
2109	ATH_PCU_LOCK_ASSERT(sc);
2110	do {
2111		if (sc->sc_inreset_cnt == 0) {
2112			w = 1;
2113			break;
2114		}
2115		if (dowait == 0) {
2116			w = 0;
2117			break;
2118		}
2119		ATH_PCU_UNLOCK(sc);
2120		pause("ath_reset_grablock", 1);
2121		i--;
2122		ATH_PCU_LOCK(sc);
2123	} while (i > 0);
2124
2125	/*
2126	 * We always increment the refcounter, regardless
2127	 * of whether we succeeded to get it in an exclusive
2128	 * way.
2129	 */
2130	sc->sc_inreset_cnt++;
2131
2132	if (i <= 0)
2133		device_printf(sc->sc_dev,
2134		    "%s: didn't finish after %d iterations\n",
2135		    __func__, MAX_RESET_ITERATIONS);
2136
2137	if (w == 0)
2138		device_printf(sc->sc_dev,
2139		    "%s: warning, recursive reset path!\n",
2140		    __func__);
2141
2142	return w;
2143}
2144#undef MAX_RESET_ITERATIONS
2145
2146/*
2147 * XXX TODO: write ath_reset_releaselock
2148 */
2149
2150static void
2151ath_stop(struct ifnet *ifp)
2152{
2153	struct ath_softc *sc = ifp->if_softc;
2154
2155	ATH_LOCK(sc);
2156	ath_stop_locked(ifp);
2157	ATH_UNLOCK(sc);
2158}
2159
2160/*
2161 * Reset the hardware w/o losing operational state.  This is
2162 * basically a more efficient way of doing ath_stop, ath_init,
2163 * followed by state transitions to the current 802.11
2164 * operational state.  Used to recover from various errors and
2165 * to reset or reload hardware state.
2166 */
2167int
2168ath_reset(struct ifnet *ifp, ATH_RESET_TYPE reset_type)
2169{
2170	struct ath_softc *sc = ifp->if_softc;
2171	struct ieee80211com *ic = ifp->if_l2com;
2172	struct ath_hal *ah = sc->sc_ah;
2173	HAL_STATUS status;
2174	int i;
2175
2176	DPRINTF(sc, ATH_DEBUG_RESET, "%s: called\n", __func__);
2177
2178	/* Ensure ATH_LOCK isn't held; ath_rx_proc can't be locked */
2179	ATH_PCU_UNLOCK_ASSERT(sc);
2180	ATH_UNLOCK_ASSERT(sc);
2181
2182	/* Try to (stop any further TX/RX from occuring */
2183	taskqueue_block(sc->sc_tq);
2184
2185	ATH_PCU_LOCK(sc);
2186	ath_hal_intrset(ah, 0);		/* disable interrupts */
2187	ath_txrx_stop_locked(sc);	/* Ensure TX/RX is stopped */
2188	if (ath_reset_grablock(sc, 1) == 0) {
2189		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
2190		    __func__);
2191	}
2192	ATH_PCU_UNLOCK(sc);
2193
2194	/*
2195	 * Should now wait for pending TX/RX to complete
2196	 * and block future ones from occuring. This needs to be
2197	 * done before the TX queue is drained.
2198	 */
2199	ath_draintxq(sc, reset_type);	/* stop xmit side */
2200
2201	/*
2202	 * Regardless of whether we're doing a no-loss flush or
2203	 * not, stop the PCU and handle what's in the RX queue.
2204	 * That way frames aren't dropped which shouldn't be.
2205	 */
2206	ath_stoprecv(sc, (reset_type != ATH_RESET_NOLOSS));
2207	ath_rx_flush(sc);
2208
2209	ath_settkipmic(sc);		/* configure TKIP MIC handling */
2210	/* NB: indicate channel change so we do a full reset */
2211	if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_TRUE, &status))
2212		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
2213			__func__, status);
2214	sc->sc_diversity = ath_hal_getdiversity(ah);
2215
2216	/* Let DFS at it in case it's a DFS channel */
2217	ath_dfs_radar_enable(sc, ic->ic_curchan);
2218
2219	if (ath_startrecv(sc) != 0)	/* restart recv */
2220		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
2221	/*
2222	 * We may be doing a reset in response to an ioctl
2223	 * that changes the channel so update any state that
2224	 * might change as a result.
2225	 */
2226	ath_chan_change(sc, ic->ic_curchan);
2227	if (sc->sc_beacons) {		/* restart beacons */
2228#ifdef IEEE80211_SUPPORT_TDMA
2229		if (sc->sc_tdma)
2230			ath_tdma_config(sc, NULL);
2231		else
2232#endif
2233			ath_beacon_config(sc, NULL);
2234	}
2235
2236	/*
2237	 * Release the reset lock and re-enable interrupts here.
2238	 * If an interrupt was being processed in ath_intr(),
2239	 * it would disable interrupts at this point. So we have
2240	 * to atomically enable interrupts and decrement the
2241	 * reset counter - this way ath_intr() doesn't end up
2242	 * disabling interrupts without a corresponding enable
2243	 * in the rest or channel change path.
2244	 */
2245	ATH_PCU_LOCK(sc);
2246	sc->sc_inreset_cnt--;
2247	/* XXX only do this if sc_inreset_cnt == 0? */
2248	ath_hal_intrset(ah, sc->sc_imask);
2249	ATH_PCU_UNLOCK(sc);
2250
2251	/*
2252	 * TX and RX can be started here. If it were started with
2253	 * sc_inreset_cnt > 0, the TX and RX path would abort.
2254	 * Thus if this is a nested call through the reset or
2255	 * channel change code, TX completion will occur but
2256	 * RX completion and ath_start / ath_tx_start will not
2257	 * run.
2258	 */
2259
2260	/* Restart TX/RX as needed */
2261	ath_txrx_start(sc);
2262
2263	/* XXX Restart TX completion and pending TX */
2264	if (reset_type == ATH_RESET_NOLOSS) {
2265		for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
2266			if (ATH_TXQ_SETUP(sc, i)) {
2267				ATH_TXQ_LOCK(&sc->sc_txq[i]);
2268				ath_txq_restart_dma(sc, &sc->sc_txq[i]);
2269				ath_txq_sched(sc, &sc->sc_txq[i]);
2270				ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
2271			}
2272		}
2273	}
2274
2275	/*
2276	 * This may have been set during an ath_start() call which
2277	 * set this once it detected a concurrent TX was going on.
2278	 * So, clear it.
2279	 */
2280	IF_LOCK(&ifp->if_snd);
2281	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2282	IF_UNLOCK(&ifp->if_snd);
2283
2284	/* Handle any frames in the TX queue */
2285	/*
2286	 * XXX should this be done by the caller, rather than
2287	 * ath_reset() ?
2288	 */
2289	ath_tx_kick(sc);		/* restart xmit */
2290	return 0;
2291}
2292
2293static int
2294ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
2295{
2296	struct ieee80211com *ic = vap->iv_ic;
2297	struct ifnet *ifp = ic->ic_ifp;
2298	struct ath_softc *sc = ifp->if_softc;
2299	struct ath_hal *ah = sc->sc_ah;
2300
2301	switch (cmd) {
2302	case IEEE80211_IOC_TXPOWER:
2303		/*
2304		 * If per-packet TPC is enabled, then we have nothing
2305		 * to do; otherwise we need to force the global limit.
2306		 * All this can happen directly; no need to reset.
2307		 */
2308		if (!ath_hal_gettpc(ah))
2309			ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
2310		return 0;
2311	}
2312	/* XXX? Full or NOLOSS? */
2313	return ath_reset(ifp, ATH_RESET_FULL);
2314}
2315
2316struct ath_buf *
2317_ath_getbuf_locked(struct ath_softc *sc, ath_buf_type_t btype)
2318{
2319	struct ath_buf *bf;
2320
2321	ATH_TXBUF_LOCK_ASSERT(sc);
2322
2323	if (btype == ATH_BUFTYPE_MGMT)
2324		bf = TAILQ_FIRST(&sc->sc_txbuf_mgmt);
2325	else
2326		bf = TAILQ_FIRST(&sc->sc_txbuf);
2327
2328	if (bf == NULL) {
2329		sc->sc_stats.ast_tx_getnobuf++;
2330	} else {
2331		if (bf->bf_flags & ATH_BUF_BUSY) {
2332			sc->sc_stats.ast_tx_getbusybuf++;
2333			bf = NULL;
2334		}
2335	}
2336
2337	if (bf != NULL && (bf->bf_flags & ATH_BUF_BUSY) == 0) {
2338		if (btype == ATH_BUFTYPE_MGMT)
2339			TAILQ_REMOVE(&sc->sc_txbuf_mgmt, bf, bf_list);
2340		else {
2341			TAILQ_REMOVE(&sc->sc_txbuf, bf, bf_list);
2342			sc->sc_txbuf_cnt--;
2343
2344			/*
2345			 * This shuldn't happen; however just to be
2346			 * safe print a warning and fudge the txbuf
2347			 * count.
2348			 */
2349			if (sc->sc_txbuf_cnt < 0) {
2350				device_printf(sc->sc_dev,
2351				    "%s: sc_txbuf_cnt < 0?\n",
2352				    __func__);
2353				sc->sc_txbuf_cnt = 0;
2354			}
2355		}
2356	} else
2357		bf = NULL;
2358
2359	if (bf == NULL) {
2360		/* XXX should check which list, mgmt or otherwise */
2361		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: %s\n", __func__,
2362		    TAILQ_FIRST(&sc->sc_txbuf) == NULL ?
2363			"out of xmit buffers" : "xmit buffer busy");
2364		return NULL;
2365	}
2366
2367	/* XXX TODO: should do this at buffer list initialisation */
2368	/* XXX (then, ensure the buffer has the right flag set) */
2369	if (btype == ATH_BUFTYPE_MGMT)
2370		bf->bf_flags |= ATH_BUF_MGMT;
2371	else
2372		bf->bf_flags &= (~ATH_BUF_MGMT);
2373
2374	/* Valid bf here; clear some basic fields */
2375	bf->bf_next = NULL;	/* XXX just to be sure */
2376	bf->bf_last = NULL;	/* XXX again, just to be sure */
2377	bf->bf_comp = NULL;	/* XXX again, just to be sure */
2378	bzero(&bf->bf_state, sizeof(bf->bf_state));
2379
2380	/*
2381	 * Track the descriptor ID only if doing EDMA
2382	 */
2383	if (sc->sc_isedma) {
2384		bf->bf_descid = sc->sc_txbuf_descid;
2385		sc->sc_txbuf_descid++;
2386	}
2387
2388	return bf;
2389}
2390
2391/*
2392 * When retrying a software frame, buffers marked ATH_BUF_BUSY
2393 * can't be thrown back on the queue as they could still be
2394 * in use by the hardware.
2395 *
2396 * This duplicates the buffer, or returns NULL.
2397 *
2398 * The descriptor is also copied but the link pointers and
2399 * the DMA segments aren't copied; this frame should thus
2400 * be again passed through the descriptor setup/chain routines
2401 * so the link is correct.
2402 *
2403 * The caller must free the buffer using ath_freebuf().
2404 *
2405 * XXX TODO: this call shouldn't fail as it'll cause packet loss
2406 * XXX in the TX pathway when retries are needed.
2407 * XXX Figure out how to keep some buffers free, or factor the
2408 * XXX number of busy buffers into the xmit path (ath_start())
2409 * XXX so we don't over-commit.
2410 */
2411struct ath_buf *
2412ath_buf_clone(struct ath_softc *sc, const struct ath_buf *bf)
2413{
2414	struct ath_buf *tbf;
2415
2416	tbf = ath_getbuf(sc,
2417	    (bf->bf_flags & ATH_BUF_MGMT) ?
2418	     ATH_BUFTYPE_MGMT : ATH_BUFTYPE_NORMAL);
2419	if (tbf == NULL)
2420		return NULL;	/* XXX failure? Why? */
2421
2422	/* Copy basics */
2423	tbf->bf_next = NULL;
2424	tbf->bf_nseg = bf->bf_nseg;
2425	tbf->bf_flags = bf->bf_flags & ~ATH_BUF_BUSY;
2426	tbf->bf_status = bf->bf_status;
2427	tbf->bf_m = bf->bf_m;
2428	tbf->bf_node = bf->bf_node;
2429	/* will be setup by the chain/setup function */
2430	tbf->bf_lastds = NULL;
2431	/* for now, last == self */
2432	tbf->bf_last = tbf;
2433	tbf->bf_comp = bf->bf_comp;
2434
2435	/* NOTE: DMA segments will be setup by the setup/chain functions */
2436
2437	/* The caller has to re-init the descriptor + links */
2438
2439	/* Copy state */
2440	memcpy(&tbf->bf_state, &bf->bf_state, sizeof(bf->bf_state));
2441
2442	return tbf;
2443}
2444
2445struct ath_buf *
2446ath_getbuf(struct ath_softc *sc, ath_buf_type_t btype)
2447{
2448	struct ath_buf *bf;
2449
2450	ATH_TXBUF_LOCK(sc);
2451	bf = _ath_getbuf_locked(sc, btype);
2452	/*
2453	 * If a mgmt buffer was requested but we're out of those,
2454	 * try requesting a normal one.
2455	 */
2456	if (bf == NULL && btype == ATH_BUFTYPE_MGMT)
2457		bf = _ath_getbuf_locked(sc, ATH_BUFTYPE_NORMAL);
2458	ATH_TXBUF_UNLOCK(sc);
2459	if (bf == NULL) {
2460		struct ifnet *ifp = sc->sc_ifp;
2461
2462		DPRINTF(sc, ATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
2463		sc->sc_stats.ast_tx_qstop++;
2464		IF_LOCK(&ifp->if_snd);
2465		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2466		IF_UNLOCK(&ifp->if_snd);
2467	}
2468	return bf;
2469}
2470
2471static void
2472ath_start_queue(struct ifnet *ifp)
2473{
2474	struct ath_softc *sc = ifp->if_softc;
2475
2476	ATH_KTR(sc, ATH_KTR_TX, 0, "ath_start_queue: start");
2477	ath_tx_kick(sc);
2478	ATH_KTR(sc, ATH_KTR_TX, 0, "ath_start_queue: finished");
2479}
2480
2481void
2482ath_start_task(void *arg, int npending)
2483{
2484	struct ath_softc *sc = (struct ath_softc *) arg;
2485	struct ifnet *ifp = sc->sc_ifp;
2486
2487	ATH_KTR(sc, ATH_KTR_TX, 0, "ath_start_task: start");
2488
2489	/* XXX is it ok to hold the ATH_LOCK here? */
2490	ATH_PCU_LOCK(sc);
2491	if (sc->sc_inreset_cnt > 0) {
2492		device_printf(sc->sc_dev,
2493		    "%s: sc_inreset_cnt > 0; bailing\n", __func__);
2494		ATH_PCU_UNLOCK(sc);
2495		IF_LOCK(&ifp->if_snd);
2496		sc->sc_stats.ast_tx_qstop++;
2497		ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2498		IF_UNLOCK(&ifp->if_snd);
2499		ATH_KTR(sc, ATH_KTR_TX, 0, "ath_start_task: OACTIVE, finish");
2500		return;
2501	}
2502	sc->sc_txstart_cnt++;
2503	ATH_PCU_UNLOCK(sc);
2504
2505	ath_start(sc->sc_ifp);
2506
2507	ATH_PCU_LOCK(sc);
2508	sc->sc_txstart_cnt--;
2509	ATH_PCU_UNLOCK(sc);
2510	ATH_KTR(sc, ATH_KTR_TX, 0, "ath_start_task: finished");
2511}
2512
2513void
2514ath_start(struct ifnet *ifp)
2515{
2516	struct ath_softc *sc = ifp->if_softc;
2517	struct ieee80211_node *ni;
2518	struct ath_buf *bf;
2519	struct mbuf *m, *next;
2520	ath_bufhead frags;
2521	int npkts = 0;
2522
2523	if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
2524		return;
2525
2526	ATH_KTR(sc, ATH_KTR_TX, 0, "ath_start: called");
2527
2528	for (;;) {
2529		ATH_TXBUF_LOCK(sc);
2530		if (sc->sc_txbuf_cnt <= sc->sc_txq_data_minfree) {
2531			/* XXX increment counter? */
2532			ATH_TXBUF_UNLOCK(sc);
2533			IF_LOCK(&ifp->if_snd);
2534			ifp->if_drv_flags |= IFF_DRV_OACTIVE;
2535			IF_UNLOCK(&ifp->if_snd);
2536			break;
2537		}
2538		ATH_TXBUF_UNLOCK(sc);
2539
2540		/*
2541		 * Grab a TX buffer and associated resources.
2542		 */
2543		bf = ath_getbuf(sc, ATH_BUFTYPE_NORMAL);
2544		if (bf == NULL)
2545			break;
2546
2547		IFQ_DEQUEUE(&ifp->if_snd, m);
2548		if (m == NULL) {
2549			ATH_TXBUF_LOCK(sc);
2550			ath_returnbuf_head(sc, bf);
2551			ATH_TXBUF_UNLOCK(sc);
2552			break;
2553		}
2554		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
2555		npkts ++;
2556		/*
2557		 * Check for fragmentation.  If this frame
2558		 * has been broken up verify we have enough
2559		 * buffers to send all the fragments so all
2560		 * go out or none...
2561		 */
2562		TAILQ_INIT(&frags);
2563		if ((m->m_flags & M_FRAG) &&
2564		    !ath_txfrag_setup(sc, &frags, m, ni)) {
2565			DPRINTF(sc, ATH_DEBUG_XMIT,
2566			    "%s: out of txfrag buffers\n", __func__);
2567			sc->sc_stats.ast_tx_nofrag++;
2568			ifp->if_oerrors++;
2569			ath_freetx(m);
2570			goto bad;
2571		}
2572		ifp->if_opackets++;
2573	nextfrag:
2574		/*
2575		 * Pass the frame to the h/w for transmission.
2576		 * Fragmented frames have each frag chained together
2577		 * with m_nextpkt.  We know there are sufficient ath_buf's
2578		 * to send all the frags because of work done by
2579		 * ath_txfrag_setup.  We leave m_nextpkt set while
2580		 * calling ath_tx_start so it can use it to extend the
2581		 * the tx duration to cover the subsequent frag and
2582		 * so it can reclaim all the mbufs in case of an error;
2583		 * ath_tx_start clears m_nextpkt once it commits to
2584		 * handing the frame to the hardware.
2585		 */
2586		next = m->m_nextpkt;
2587		if (ath_tx_start(sc, ni, bf, m)) {
2588	bad:
2589			ifp->if_oerrors++;
2590	reclaim:
2591			bf->bf_m = NULL;
2592			bf->bf_node = NULL;
2593			ATH_TXBUF_LOCK(sc);
2594			ath_returnbuf_head(sc, bf);
2595			ath_txfrag_cleanup(sc, &frags, ni);
2596			ATH_TXBUF_UNLOCK(sc);
2597			if (ni != NULL)
2598				ieee80211_free_node(ni);
2599			continue;
2600		}
2601
2602		/*
2603		 * Check here if the node is in power save state.
2604		 */
2605		ath_tx_update_tim(sc, ni, 1);
2606
2607		if (next != NULL) {
2608			/*
2609			 * Beware of state changing between frags.
2610			 * XXX check sta power-save state?
2611			 */
2612			if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
2613				DPRINTF(sc, ATH_DEBUG_XMIT,
2614				    "%s: flush fragmented packet, state %s\n",
2615				    __func__,
2616				    ieee80211_state_name[ni->ni_vap->iv_state]);
2617				ath_freetx(next);
2618				goto reclaim;
2619			}
2620			m = next;
2621			bf = TAILQ_FIRST(&frags);
2622			KASSERT(bf != NULL, ("no buf for txfrag"));
2623			TAILQ_REMOVE(&frags, bf, bf_list);
2624			goto nextfrag;
2625		}
2626
2627		sc->sc_wd_timer = 5;
2628	}
2629	ATH_KTR(sc, ATH_KTR_TX, 1, "ath_start: finished; npkts=%d", npkts);
2630}
2631
2632static int
2633ath_media_change(struct ifnet *ifp)
2634{
2635	int error = ieee80211_media_change(ifp);
2636	/* NB: only the fixed rate can change and that doesn't need a reset */
2637	return (error == ENETRESET ? 0 : error);
2638}
2639
2640/*
2641 * Block/unblock tx+rx processing while a key change is done.
2642 * We assume the caller serializes key management operations
2643 * so we only need to worry about synchronization with other
2644 * uses that originate in the driver.
2645 */
2646static void
2647ath_key_update_begin(struct ieee80211vap *vap)
2648{
2649	struct ifnet *ifp = vap->iv_ic->ic_ifp;
2650	struct ath_softc *sc = ifp->if_softc;
2651
2652	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2653	taskqueue_block(sc->sc_tq);
2654	IF_LOCK(&ifp->if_snd);		/* NB: doesn't block mgmt frames */
2655}
2656
2657static void
2658ath_key_update_end(struct ieee80211vap *vap)
2659{
2660	struct ifnet *ifp = vap->iv_ic->ic_ifp;
2661	struct ath_softc *sc = ifp->if_softc;
2662
2663	DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2664	IF_UNLOCK(&ifp->if_snd);
2665	taskqueue_unblock(sc->sc_tq);
2666}
2667
2668static void
2669ath_update_promisc(struct ifnet *ifp)
2670{
2671	struct ath_softc *sc = ifp->if_softc;
2672	u_int32_t rfilt;
2673
2674	/* configure rx filter */
2675	rfilt = ath_calcrxfilter(sc);
2676	ath_hal_setrxfilter(sc->sc_ah, rfilt);
2677
2678	DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
2679}
2680
2681static void
2682ath_update_mcast(struct ifnet *ifp)
2683{
2684	struct ath_softc *sc = ifp->if_softc;
2685	u_int32_t mfilt[2];
2686
2687	/* calculate and install multicast filter */
2688	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
2689		struct ifmultiaddr *ifma;
2690		/*
2691		 * Merge multicast addresses to form the hardware filter.
2692		 */
2693		mfilt[0] = mfilt[1] = 0;
2694		if_maddr_rlock(ifp);	/* XXX need some fiddling to remove? */
2695		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2696			caddr_t dl;
2697			u_int32_t val;
2698			u_int8_t pos;
2699
2700			/* calculate XOR of eight 6bit values */
2701			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
2702			val = LE_READ_4(dl + 0);
2703			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2704			val = LE_READ_4(dl + 3);
2705			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2706			pos &= 0x3f;
2707			mfilt[pos / 32] |= (1 << (pos % 32));
2708		}
2709		if_maddr_runlock(ifp);
2710	} else
2711		mfilt[0] = mfilt[1] = ~0;
2712	ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
2713	DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
2714		__func__, mfilt[0], mfilt[1]);
2715}
2716
2717void
2718ath_mode_init(struct ath_softc *sc)
2719{
2720	struct ifnet *ifp = sc->sc_ifp;
2721	struct ath_hal *ah = sc->sc_ah;
2722	u_int32_t rfilt;
2723
2724	/* configure rx filter */
2725	rfilt = ath_calcrxfilter(sc);
2726	ath_hal_setrxfilter(ah, rfilt);
2727
2728	/* configure operational mode */
2729	ath_hal_setopmode(ah);
2730
2731	DPRINTF(sc, ATH_DEBUG_STATE | ATH_DEBUG_MODE,
2732	    "%s: ah=%p, ifp=%p, if_addr=%p\n",
2733	    __func__,
2734	    ah,
2735	    ifp,
2736	    (ifp == NULL) ? NULL : ifp->if_addr);
2737
2738	/* handle any link-level address change */
2739	ath_hal_setmac(ah, IF_LLADDR(ifp));
2740
2741	/* calculate and install multicast filter */
2742	ath_update_mcast(ifp);
2743}
2744
2745/*
2746 * Set the slot time based on the current setting.
2747 */
2748void
2749ath_setslottime(struct ath_softc *sc)
2750{
2751	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2752	struct ath_hal *ah = sc->sc_ah;
2753	u_int usec;
2754
2755	if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
2756		usec = 13;
2757	else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
2758		usec = 21;
2759	else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
2760		/* honor short/long slot time only in 11g */
2761		/* XXX shouldn't honor on pure g or turbo g channel */
2762		if (ic->ic_flags & IEEE80211_F_SHSLOT)
2763			usec = HAL_SLOT_TIME_9;
2764		else
2765			usec = HAL_SLOT_TIME_20;
2766	} else
2767		usec = HAL_SLOT_TIME_9;
2768
2769	DPRINTF(sc, ATH_DEBUG_RESET,
2770	    "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
2771	    __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
2772	    ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
2773
2774	ath_hal_setslottime(ah, usec);
2775	sc->sc_updateslot = OK;
2776}
2777
2778/*
2779 * Callback from the 802.11 layer to update the
2780 * slot time based on the current setting.
2781 */
2782static void
2783ath_updateslot(struct ifnet *ifp)
2784{
2785	struct ath_softc *sc = ifp->if_softc;
2786	struct ieee80211com *ic = ifp->if_l2com;
2787
2788	/*
2789	 * When not coordinating the BSS, change the hardware
2790	 * immediately.  For other operation we defer the change
2791	 * until beacon updates have propagated to the stations.
2792	 */
2793	if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2794	    ic->ic_opmode == IEEE80211_M_MBSS)
2795		sc->sc_updateslot = UPDATE;
2796	else
2797		ath_setslottime(sc);
2798}
2799
2800/*
2801 * Append the contents of src to dst; both queues
2802 * are assumed to be locked.
2803 */
2804void
2805ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
2806{
2807
2808	ATH_TXQ_LOCK_ASSERT(dst);
2809	ATH_TXQ_LOCK_ASSERT(src);
2810
2811	TAILQ_CONCAT(&dst->axq_q, &src->axq_q, bf_list);
2812	dst->axq_link = src->axq_link;
2813	src->axq_link = NULL;
2814	dst->axq_depth += src->axq_depth;
2815	dst->axq_aggr_depth += src->axq_aggr_depth;
2816	src->axq_depth = 0;
2817	src->axq_aggr_depth = 0;
2818}
2819
2820/*
2821 * Reset the hardware, with no loss.
2822 *
2823 * This can't be used for a general case reset.
2824 */
2825static void
2826ath_reset_proc(void *arg, int pending)
2827{
2828	struct ath_softc *sc = arg;
2829	struct ifnet *ifp = sc->sc_ifp;
2830
2831#if 0
2832	if_printf(ifp, "%s: resetting\n", __func__);
2833#endif
2834	ath_reset(ifp, ATH_RESET_NOLOSS);
2835}
2836
2837/*
2838 * Reset the hardware after detecting beacons have stopped.
2839 */
2840static void
2841ath_bstuck_proc(void *arg, int pending)
2842{
2843	struct ath_softc *sc = arg;
2844	struct ifnet *ifp = sc->sc_ifp;
2845	uint32_t hangs = 0;
2846
2847	if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0)
2848		if_printf(ifp, "bb hang detected (0x%x)\n", hangs);
2849
2850	if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
2851		sc->sc_bmisscount);
2852	sc->sc_stats.ast_bstuck++;
2853	/*
2854	 * This assumes that there's no simultaneous channel mode change
2855	 * occuring.
2856	 */
2857	ath_reset(ifp, ATH_RESET_NOLOSS);
2858}
2859
2860static void
2861ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2862{
2863	bus_addr_t *paddr = (bus_addr_t*) arg;
2864	KASSERT(error == 0, ("error %u on bus_dma callback", error));
2865	*paddr = segs->ds_addr;
2866}
2867
2868/*
2869 * Allocate the descriptors and appropriate DMA tag/setup.
2870 *
2871 * For some situations (eg EDMA TX completion), there isn't a requirement
2872 * for the ath_buf entries to be allocated.
2873 */
2874int
2875ath_descdma_alloc_desc(struct ath_softc *sc,
2876	struct ath_descdma *dd, ath_bufhead *head,
2877	const char *name, int ds_size, int ndesc)
2878{
2879#define	DS2PHYS(_dd, _ds) \
2880	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
2881#define	ATH_DESC_4KB_BOUND_CHECK(_daddr, _len) \
2882	((((u_int32_t)(_daddr) & 0xFFF) > (0x1000 - (_len))) ? 1 : 0)
2883	struct ifnet *ifp = sc->sc_ifp;
2884	int error;
2885
2886	dd->dd_descsize = ds_size;
2887
2888	DPRINTF(sc, ATH_DEBUG_RESET,
2889	    "%s: %s DMA: %u desc, %d bytes per descriptor\n",
2890	    __func__, name, ndesc, dd->dd_descsize);
2891
2892	dd->dd_name = name;
2893	dd->dd_desc_len = dd->dd_descsize * ndesc;
2894
2895	/*
2896	 * Merlin work-around:
2897	 * Descriptors that cross the 4KB boundary can't be used.
2898	 * Assume one skipped descriptor per 4KB page.
2899	 */
2900	if (! ath_hal_split4ktrans(sc->sc_ah)) {
2901		int numpages = dd->dd_desc_len / 4096;
2902		dd->dd_desc_len += ds_size * numpages;
2903	}
2904
2905	/*
2906	 * Setup DMA descriptor area.
2907	 */
2908	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev),	/* parent */
2909		       PAGE_SIZE, 0,		/* alignment, bounds */
2910		       BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
2911		       BUS_SPACE_MAXADDR,	/* highaddr */
2912		       NULL, NULL,		/* filter, filterarg */
2913		       dd->dd_desc_len,		/* maxsize */
2914		       1,			/* nsegments */
2915		       dd->dd_desc_len,		/* maxsegsize */
2916		       BUS_DMA_ALLOCNOW,	/* flags */
2917		       NULL,			/* lockfunc */
2918		       NULL,			/* lockarg */
2919		       &dd->dd_dmat);
2920	if (error != 0) {
2921		if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
2922		return error;
2923	}
2924
2925	/* allocate descriptors */
2926	error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
2927				 BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
2928				 &dd->dd_dmamap);
2929	if (error != 0) {
2930		if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
2931			"error %u\n", ndesc, dd->dd_name, error);
2932		goto fail1;
2933	}
2934
2935	error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
2936				dd->dd_desc, dd->dd_desc_len,
2937				ath_load_cb, &dd->dd_desc_paddr,
2938				BUS_DMA_NOWAIT);
2939	if (error != 0) {
2940		if_printf(ifp, "unable to map %s descriptors, error %u\n",
2941			dd->dd_name, error);
2942		goto fail2;
2943	}
2944
2945	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
2946	    __func__, dd->dd_name, (uint8_t *) dd->dd_desc,
2947	    (u_long) dd->dd_desc_len, (caddr_t) dd->dd_desc_paddr,
2948	    /*XXX*/ (u_long) dd->dd_desc_len);
2949
2950	return (0);
2951
2952fail2:
2953	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2954fail1:
2955	bus_dma_tag_destroy(dd->dd_dmat);
2956	memset(dd, 0, sizeof(*dd));
2957	return error;
2958#undef DS2PHYS
2959#undef ATH_DESC_4KB_BOUND_CHECK
2960}
2961
2962int
2963ath_descdma_setup(struct ath_softc *sc,
2964	struct ath_descdma *dd, ath_bufhead *head,
2965	const char *name, int ds_size, int nbuf, int ndesc)
2966{
2967#define	DS2PHYS(_dd, _ds) \
2968	((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
2969#define	ATH_DESC_4KB_BOUND_CHECK(_daddr, _len) \
2970	((((u_int32_t)(_daddr) & 0xFFF) > (0x1000 - (_len))) ? 1 : 0)
2971	struct ifnet *ifp = sc->sc_ifp;
2972	uint8_t *ds;
2973	struct ath_buf *bf;
2974	int i, bsize, error;
2975
2976	/* Allocate descriptors */
2977	error = ath_descdma_alloc_desc(sc, dd, head, name, ds_size,
2978	    nbuf * ndesc);
2979
2980	/* Assume any errors during allocation were dealt with */
2981	if (error != 0) {
2982		return (error);
2983	}
2984
2985	ds = (uint8_t *) dd->dd_desc;
2986
2987	/* allocate rx buffers */
2988	bsize = sizeof(struct ath_buf) * nbuf;
2989	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
2990	if (bf == NULL) {
2991		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
2992			dd->dd_name, bsize);
2993		goto fail3;
2994	}
2995	dd->dd_bufptr = bf;
2996
2997	TAILQ_INIT(head);
2998	for (i = 0; i < nbuf; i++, bf++, ds += (ndesc * dd->dd_descsize)) {
2999		bf->bf_desc = (struct ath_desc *) ds;
3000		bf->bf_daddr = DS2PHYS(dd, ds);
3001		if (! ath_hal_split4ktrans(sc->sc_ah)) {
3002			/*
3003			 * Merlin WAR: Skip descriptor addresses which
3004			 * cause 4KB boundary crossing along any point
3005			 * in the descriptor.
3006			 */
3007			 if (ATH_DESC_4KB_BOUND_CHECK(bf->bf_daddr,
3008			     dd->dd_descsize)) {
3009				/* Start at the next page */
3010				ds += 0x1000 - (bf->bf_daddr & 0xFFF);
3011				bf->bf_desc = (struct ath_desc *) ds;
3012				bf->bf_daddr = DS2PHYS(dd, ds);
3013			}
3014		}
3015		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3016				&bf->bf_dmamap);
3017		if (error != 0) {
3018			if_printf(ifp, "unable to create dmamap for %s "
3019				"buffer %u, error %u\n", dd->dd_name, i, error);
3020			ath_descdma_cleanup(sc, dd, head);
3021			return error;
3022		}
3023		bf->bf_lastds = bf->bf_desc;	/* Just an initial value */
3024		TAILQ_INSERT_TAIL(head, bf, bf_list);
3025	}
3026
3027	/*
3028	 * XXX TODO: ensure that ds doesn't overflow the descriptor
3029	 * allocation otherwise weird stuff will occur and crash your
3030	 * machine.
3031	 */
3032	return 0;
3033	/* XXX this should likely just call ath_descdma_cleanup() */
3034fail3:
3035	bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3036	bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3037	bus_dma_tag_destroy(dd->dd_dmat);
3038	memset(dd, 0, sizeof(*dd));
3039	return error;
3040#undef DS2PHYS
3041#undef ATH_DESC_4KB_BOUND_CHECK
3042}
3043
3044/*
3045 * Allocate ath_buf entries but no descriptor contents.
3046 *
3047 * This is for RX EDMA where the descriptors are the header part of
3048 * the RX buffer.
3049 */
3050int
3051ath_descdma_setup_rx_edma(struct ath_softc *sc,
3052	struct ath_descdma *dd, ath_bufhead *head,
3053	const char *name, int nbuf, int rx_status_len)
3054{
3055	struct ifnet *ifp = sc->sc_ifp;
3056	struct ath_buf *bf;
3057	int i, bsize, error;
3058
3059	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers\n",
3060	    __func__, name, nbuf);
3061
3062	dd->dd_name = name;
3063	/*
3064	 * This is (mostly) purely for show.  We're not allocating any actual
3065	 * descriptors here as EDMA RX has the descriptor be part
3066	 * of the RX buffer.
3067	 *
3068	 * However, dd_desc_len is used by ath_descdma_free() to determine
3069	 * whether we have already freed this DMA mapping.
3070	 */
3071	dd->dd_desc_len = rx_status_len * nbuf;
3072	dd->dd_descsize = rx_status_len;
3073
3074	/* allocate rx buffers */
3075	bsize = sizeof(struct ath_buf) * nbuf;
3076	bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
3077	if (bf == NULL) {
3078		if_printf(ifp, "malloc of %s buffers failed, size %u\n",
3079			dd->dd_name, bsize);
3080		error = ENOMEM;
3081		goto fail3;
3082	}
3083	dd->dd_bufptr = bf;
3084
3085	TAILQ_INIT(head);
3086	for (i = 0; i < nbuf; i++, bf++) {
3087		bf->bf_desc = NULL;
3088		bf->bf_daddr = 0;
3089		bf->bf_lastds = NULL;	/* Just an initial value */
3090
3091		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3092				&bf->bf_dmamap);
3093		if (error != 0) {
3094			if_printf(ifp, "unable to create dmamap for %s "
3095				"buffer %u, error %u\n", dd->dd_name, i, error);
3096			ath_descdma_cleanup(sc, dd, head);
3097			return error;
3098		}
3099		TAILQ_INSERT_TAIL(head, bf, bf_list);
3100	}
3101	return 0;
3102fail3:
3103	memset(dd, 0, sizeof(*dd));
3104	return error;
3105}
3106
3107void
3108ath_descdma_cleanup(struct ath_softc *sc,
3109	struct ath_descdma *dd, ath_bufhead *head)
3110{
3111	struct ath_buf *bf;
3112	struct ieee80211_node *ni;
3113
3114	if (dd->dd_dmamap != 0) {
3115		bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3116		bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3117		bus_dma_tag_destroy(dd->dd_dmat);
3118	}
3119
3120	if (head != NULL) {
3121		TAILQ_FOREACH(bf, head, bf_list) {
3122			if (bf->bf_m) {
3123				m_freem(bf->bf_m);
3124				bf->bf_m = NULL;
3125			}
3126			if (bf->bf_dmamap != NULL) {
3127				bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
3128				bf->bf_dmamap = NULL;
3129			}
3130			ni = bf->bf_node;
3131			bf->bf_node = NULL;
3132			if (ni != NULL) {
3133				/*
3134				 * Reclaim node reference.
3135				 */
3136				ieee80211_free_node(ni);
3137			}
3138		}
3139	}
3140
3141	if (head != NULL)
3142		TAILQ_INIT(head);
3143
3144	if (dd->dd_bufptr != NULL)
3145		free(dd->dd_bufptr, M_ATHDEV);
3146	memset(dd, 0, sizeof(*dd));
3147}
3148
3149static int
3150ath_desc_alloc(struct ath_softc *sc)
3151{
3152	int error;
3153
3154	error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
3155		    "tx", sc->sc_tx_desclen, ath_txbuf, ATH_TXDESC);
3156	if (error != 0) {
3157		return error;
3158	}
3159	sc->sc_txbuf_cnt = ath_txbuf;
3160
3161	error = ath_descdma_setup(sc, &sc->sc_txdma_mgmt, &sc->sc_txbuf_mgmt,
3162		    "tx_mgmt", sc->sc_tx_desclen, ath_txbuf_mgmt,
3163		    ATH_TXDESC);
3164	if (error != 0) {
3165		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3166		return error;
3167	}
3168
3169	/*
3170	 * XXX mark txbuf_mgmt frames with ATH_BUF_MGMT, so the
3171	 * flag doesn't have to be set in ath_getbuf_locked().
3172	 */
3173
3174	error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
3175			"beacon", sc->sc_tx_desclen, ATH_BCBUF, 1);
3176	if (error != 0) {
3177		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3178		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
3179		    &sc->sc_txbuf_mgmt);
3180		return error;
3181	}
3182	return 0;
3183}
3184
3185static void
3186ath_desc_free(struct ath_softc *sc)
3187{
3188
3189	if (sc->sc_bdma.dd_desc_len != 0)
3190		ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
3191	if (sc->sc_txdma.dd_desc_len != 0)
3192		ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3193	if (sc->sc_txdma_mgmt.dd_desc_len != 0)
3194		ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
3195		    &sc->sc_txbuf_mgmt);
3196}
3197
3198static struct ieee80211_node *
3199ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
3200{
3201	struct ieee80211com *ic = vap->iv_ic;
3202	struct ath_softc *sc = ic->ic_ifp->if_softc;
3203	const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
3204	struct ath_node *an;
3205
3206	an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
3207	if (an == NULL) {
3208		/* XXX stat+msg */
3209		return NULL;
3210	}
3211	ath_rate_node_init(sc, an);
3212
3213	/* Setup the mutex - there's no associd yet so set the name to NULL */
3214	snprintf(an->an_name, sizeof(an->an_name), "%s: node %p",
3215	    device_get_nameunit(sc->sc_dev), an);
3216	mtx_init(&an->an_mtx, an->an_name, NULL, MTX_DEF);
3217
3218	/* XXX setup ath_tid */
3219	ath_tx_tid_init(sc, an);
3220
3221	DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
3222	return &an->an_node;
3223}
3224
3225static void
3226ath_node_cleanup(struct ieee80211_node *ni)
3227{
3228	struct ieee80211com *ic = ni->ni_ic;
3229	struct ath_softc *sc = ic->ic_ifp->if_softc;
3230
3231	/* Cleanup ath_tid, free unused bufs, unlink bufs in TXQ */
3232	ath_tx_node_flush(sc, ATH_NODE(ni));
3233	ath_rate_node_cleanup(sc, ATH_NODE(ni));
3234	sc->sc_node_cleanup(ni);
3235}
3236
3237static void
3238ath_node_free(struct ieee80211_node *ni)
3239{
3240	struct ieee80211com *ic = ni->ni_ic;
3241	struct ath_softc *sc = ic->ic_ifp->if_softc;
3242
3243	DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
3244	mtx_destroy(&ATH_NODE(ni)->an_mtx);
3245	sc->sc_node_free(ni);
3246}
3247
3248static void
3249ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
3250{
3251	struct ieee80211com *ic = ni->ni_ic;
3252	struct ath_softc *sc = ic->ic_ifp->if_softc;
3253	struct ath_hal *ah = sc->sc_ah;
3254
3255	*rssi = ic->ic_node_getrssi(ni);
3256	if (ni->ni_chan != IEEE80211_CHAN_ANYC)
3257		*noise = ath_hal_getchannoise(ah, ni->ni_chan);
3258	else
3259		*noise = -95;		/* nominally correct */
3260}
3261
3262/*
3263 * Set the default antenna.
3264 */
3265void
3266ath_setdefantenna(struct ath_softc *sc, u_int antenna)
3267{
3268	struct ath_hal *ah = sc->sc_ah;
3269
3270	/* XXX block beacon interrupts */
3271	ath_hal_setdefantenna(ah, antenna);
3272	if (sc->sc_defant != antenna)
3273		sc->sc_stats.ast_ant_defswitch++;
3274	sc->sc_defant = antenna;
3275	sc->sc_rxotherant = 0;
3276}
3277
3278static void
3279ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
3280{
3281	txq->axq_qnum = qnum;
3282	txq->axq_ac = 0;
3283	txq->axq_depth = 0;
3284	txq->axq_aggr_depth = 0;
3285	txq->axq_intrcnt = 0;
3286	txq->axq_link = NULL;
3287	txq->axq_softc = sc;
3288	TAILQ_INIT(&txq->axq_q);
3289	TAILQ_INIT(&txq->axq_tidq);
3290	ATH_TXQ_LOCK_INIT(sc, txq);
3291}
3292
3293/*
3294 * Setup a h/w transmit queue.
3295 */
3296static struct ath_txq *
3297ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
3298{
3299#define	N(a)	(sizeof(a)/sizeof(a[0]))
3300	struct ath_hal *ah = sc->sc_ah;
3301	HAL_TXQ_INFO qi;
3302	int qnum;
3303
3304	memset(&qi, 0, sizeof(qi));
3305	qi.tqi_subtype = subtype;
3306	qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
3307	qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
3308	qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
3309	/*
3310	 * Enable interrupts only for EOL and DESC conditions.
3311	 * We mark tx descriptors to receive a DESC interrupt
3312	 * when a tx queue gets deep; otherwise waiting for the
3313	 * EOL to reap descriptors.  Note that this is done to
3314	 * reduce interrupt load and this only defers reaping
3315	 * descriptors, never transmitting frames.  Aside from
3316	 * reducing interrupts this also permits more concurrency.
3317	 * The only potential downside is if the tx queue backs
3318	 * up in which case the top half of the kernel may backup
3319	 * due to a lack of tx descriptors.
3320	 */
3321	qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
3322	qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
3323	if (qnum == -1) {
3324		/*
3325		 * NB: don't print a message, this happens
3326		 * normally on parts with too few tx queues
3327		 */
3328		return NULL;
3329	}
3330	if (qnum >= N(sc->sc_txq)) {
3331		device_printf(sc->sc_dev,
3332			"hal qnum %u out of range, max %zu!\n",
3333			qnum, N(sc->sc_txq));
3334		ath_hal_releasetxqueue(ah, qnum);
3335		return NULL;
3336	}
3337	if (!ATH_TXQ_SETUP(sc, qnum)) {
3338		ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
3339		sc->sc_txqsetup |= 1<<qnum;
3340	}
3341	return &sc->sc_txq[qnum];
3342#undef N
3343}
3344
3345/*
3346 * Setup a hardware data transmit queue for the specified
3347 * access control.  The hal may not support all requested
3348 * queues in which case it will return a reference to a
3349 * previously setup queue.  We record the mapping from ac's
3350 * to h/w queues for use by ath_tx_start and also track
3351 * the set of h/w queues being used to optimize work in the
3352 * transmit interrupt handler and related routines.
3353 */
3354static int
3355ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
3356{
3357#define	N(a)	(sizeof(a)/sizeof(a[0]))
3358	struct ath_txq *txq;
3359
3360	if (ac >= N(sc->sc_ac2q)) {
3361		device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
3362			ac, N(sc->sc_ac2q));
3363		return 0;
3364	}
3365	txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
3366	if (txq != NULL) {
3367		txq->axq_ac = ac;
3368		sc->sc_ac2q[ac] = txq;
3369		return 1;
3370	} else
3371		return 0;
3372#undef N
3373}
3374
3375/*
3376 * Update WME parameters for a transmit queue.
3377 */
3378static int
3379ath_txq_update(struct ath_softc *sc, int ac)
3380{
3381#define	ATH_EXPONENT_TO_VALUE(v)	((1<<v)-1)
3382#define	ATH_TXOP_TO_US(v)		(v<<5)
3383	struct ifnet *ifp = sc->sc_ifp;
3384	struct ieee80211com *ic = ifp->if_l2com;
3385	struct ath_txq *txq = sc->sc_ac2q[ac];
3386	struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
3387	struct ath_hal *ah = sc->sc_ah;
3388	HAL_TXQ_INFO qi;
3389
3390	ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
3391#ifdef IEEE80211_SUPPORT_TDMA
3392	if (sc->sc_tdma) {
3393		/*
3394		 * AIFS is zero so there's no pre-transmit wait.  The
3395		 * burst time defines the slot duration and is configured
3396		 * through net80211.  The QCU is setup to not do post-xmit
3397		 * back off, lockout all lower-priority QCU's, and fire
3398		 * off the DMA beacon alert timer which is setup based
3399		 * on the slot configuration.
3400		 */
3401		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
3402			      | HAL_TXQ_TXERRINT_ENABLE
3403			      | HAL_TXQ_TXURNINT_ENABLE
3404			      | HAL_TXQ_TXEOLINT_ENABLE
3405			      | HAL_TXQ_DBA_GATED
3406			      | HAL_TXQ_BACKOFF_DISABLE
3407			      | HAL_TXQ_ARB_LOCKOUT_GLOBAL
3408			      ;
3409		qi.tqi_aifs = 0;
3410		/* XXX +dbaprep? */
3411		qi.tqi_readyTime = sc->sc_tdmaslotlen;
3412		qi.tqi_burstTime = qi.tqi_readyTime;
3413	} else {
3414#endif
3415		/*
3416		 * XXX shouldn't this just use the default flags
3417		 * used in the previous queue setup?
3418		 */
3419		qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
3420			      | HAL_TXQ_TXERRINT_ENABLE
3421			      | HAL_TXQ_TXDESCINT_ENABLE
3422			      | HAL_TXQ_TXURNINT_ENABLE
3423			      | HAL_TXQ_TXEOLINT_ENABLE
3424			      ;
3425		qi.tqi_aifs = wmep->wmep_aifsn;
3426		qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
3427		qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
3428		qi.tqi_readyTime = 0;
3429		qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
3430#ifdef IEEE80211_SUPPORT_TDMA
3431	}
3432#endif
3433
3434	DPRINTF(sc, ATH_DEBUG_RESET,
3435	    "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
3436	    __func__, txq->axq_qnum, qi.tqi_qflags,
3437	    qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
3438
3439	if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
3440		if_printf(ifp, "unable to update hardware queue "
3441			"parameters for %s traffic!\n",
3442			ieee80211_wme_acnames[ac]);
3443		return 0;
3444	} else {
3445		ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
3446		return 1;
3447	}
3448#undef ATH_TXOP_TO_US
3449#undef ATH_EXPONENT_TO_VALUE
3450}
3451
3452/*
3453 * Callback from the 802.11 layer to update WME parameters.
3454 */
3455int
3456ath_wme_update(struct ieee80211com *ic)
3457{
3458	struct ath_softc *sc = ic->ic_ifp->if_softc;
3459
3460	return !ath_txq_update(sc, WME_AC_BE) ||
3461	    !ath_txq_update(sc, WME_AC_BK) ||
3462	    !ath_txq_update(sc, WME_AC_VI) ||
3463	    !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
3464}
3465
3466/*
3467 * Reclaim resources for a setup queue.
3468 */
3469static void
3470ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
3471{
3472
3473	ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
3474	ATH_TXQ_LOCK_DESTROY(txq);
3475	sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
3476}
3477
3478/*
3479 * Reclaim all tx queue resources.
3480 */
3481static void
3482ath_tx_cleanup(struct ath_softc *sc)
3483{
3484	int i;
3485
3486	ATH_TXBUF_LOCK_DESTROY(sc);
3487	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3488		if (ATH_TXQ_SETUP(sc, i))
3489			ath_tx_cleanupq(sc, &sc->sc_txq[i]);
3490}
3491
3492/*
3493 * Return h/w rate index for an IEEE rate (w/o basic rate bit)
3494 * using the current rates in sc_rixmap.
3495 */
3496int
3497ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
3498{
3499	int rix = sc->sc_rixmap[rate];
3500	/* NB: return lowest rix for invalid rate */
3501	return (rix == 0xff ? 0 : rix);
3502}
3503
3504static void
3505ath_tx_update_stats(struct ath_softc *sc, struct ath_tx_status *ts,
3506    struct ath_buf *bf)
3507{
3508	struct ieee80211_node *ni = bf->bf_node;
3509	struct ifnet *ifp = sc->sc_ifp;
3510	struct ieee80211com *ic = ifp->if_l2com;
3511	int sr, lr, pri;
3512
3513	if (ts->ts_status == 0) {
3514		u_int8_t txant = ts->ts_antenna;
3515		sc->sc_stats.ast_ant_tx[txant]++;
3516		sc->sc_ant_tx[txant]++;
3517		if (ts->ts_finaltsi != 0)
3518			sc->sc_stats.ast_tx_altrate++;
3519		pri = M_WME_GETAC(bf->bf_m);
3520		if (pri >= WME_AC_VO)
3521			ic->ic_wme.wme_hipri_traffic++;
3522		if ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)
3523			ni->ni_inact = ni->ni_inact_reload;
3524	} else {
3525		if (ts->ts_status & HAL_TXERR_XRETRY)
3526			sc->sc_stats.ast_tx_xretries++;
3527		if (ts->ts_status & HAL_TXERR_FIFO)
3528			sc->sc_stats.ast_tx_fifoerr++;
3529		if (ts->ts_status & HAL_TXERR_FILT)
3530			sc->sc_stats.ast_tx_filtered++;
3531		if (ts->ts_status & HAL_TXERR_XTXOP)
3532			sc->sc_stats.ast_tx_xtxop++;
3533		if (ts->ts_status & HAL_TXERR_TIMER_EXPIRED)
3534			sc->sc_stats.ast_tx_timerexpired++;
3535
3536		if (ts->ts_status & HAL_TX_DATA_UNDERRUN)
3537			sc->sc_stats.ast_tx_data_underrun++;
3538		if (ts->ts_status & HAL_TX_DELIM_UNDERRUN)
3539			sc->sc_stats.ast_tx_delim_underrun++;
3540
3541		if (bf->bf_m->m_flags & M_FF)
3542			sc->sc_stats.ast_ff_txerr++;
3543	}
3544	/* XXX when is this valid? */
3545	if (ts->ts_status & HAL_TX_DESC_CFG_ERR)
3546		sc->sc_stats.ast_tx_desccfgerr++;
3547
3548	sr = ts->ts_shortretry;
3549	lr = ts->ts_longretry;
3550	sc->sc_stats.ast_tx_shortretry += sr;
3551	sc->sc_stats.ast_tx_longretry += lr;
3552
3553}
3554
3555/*
3556 * The default completion. If fail is 1, this means
3557 * "please don't retry the frame, and just return -1 status
3558 * to the net80211 stack.
3559 */
3560void
3561ath_tx_default_comp(struct ath_softc *sc, struct ath_buf *bf, int fail)
3562{
3563	struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
3564	int st;
3565
3566	if (fail == 1)
3567		st = -1;
3568	else
3569		st = ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) ?
3570		    ts->ts_status : HAL_TXERR_XRETRY;
3571
3572	if (bf->bf_state.bfs_dobaw)
3573		device_printf(sc->sc_dev,
3574		    "%s: bf %p: seqno %d: dobaw should've been cleared!\n",
3575		    __func__,
3576		    bf,
3577		    SEQNO(bf->bf_state.bfs_seqno));
3578	if (bf->bf_next != NULL)
3579		device_printf(sc->sc_dev,
3580		    "%s: bf %p: seqno %d: bf_next not NULL!\n",
3581		    __func__,
3582		    bf,
3583		    SEQNO(bf->bf_state.bfs_seqno));
3584
3585	/*
3586	 * Check if the node software queue is empty; if so
3587	 * then clear the TIM.
3588	 *
3589	 * This needs to be done before the buffer is freed as
3590	 * otherwise the node reference will have been released
3591	 * and the node may not actually exist any longer.
3592	 *
3593	 * XXX I don't like this belonging here, but it's cleaner
3594	 * to do it here right now then all the other places
3595	 * where ath_tx_default_comp() is called.
3596	 *
3597	 * XXX TODO: during drain, ensure that the callback is
3598	 * being called so we get a chance to update the TIM.
3599	 */
3600	if (bf->bf_node)
3601		ath_tx_update_tim(sc, bf->bf_node, 0);
3602
3603	/*
3604	 * Do any tx complete callback.  Note this must
3605	 * be done before releasing the node reference.
3606	 * This will free the mbuf, release the net80211
3607	 * node and recycle the ath_buf.
3608	 */
3609	ath_tx_freebuf(sc, bf, st);
3610}
3611
3612/*
3613 * Update rate control with the given completion status.
3614 */
3615void
3616ath_tx_update_ratectrl(struct ath_softc *sc, struct ieee80211_node *ni,
3617    struct ath_rc_series *rc, struct ath_tx_status *ts, int frmlen,
3618    int nframes, int nbad)
3619{
3620	struct ath_node *an;
3621
3622	/* Only for unicast frames */
3623	if (ni == NULL)
3624		return;
3625
3626	an = ATH_NODE(ni);
3627	ATH_NODE_UNLOCK_ASSERT(an);
3628
3629	if ((ts->ts_status & HAL_TXERR_FILT) == 0) {
3630		ATH_NODE_LOCK(an);
3631		ath_rate_tx_complete(sc, an, rc, ts, frmlen, nframes, nbad);
3632		ATH_NODE_UNLOCK(an);
3633	}
3634}
3635
3636/*
3637 * Update the busy status of the last frame on the free list.
3638 * When doing TDMA, the busy flag tracks whether the hardware
3639 * currently points to this buffer or not, and thus gated DMA
3640 * may restart by re-reading the last descriptor in this
3641 * buffer.
3642 *
3643 * This should be called in the completion function once one
3644 * of the buffers has been used.
3645 */
3646static void
3647ath_tx_update_busy(struct ath_softc *sc)
3648{
3649	struct ath_buf *last;
3650
3651	/*
3652	 * Since the last frame may still be marked
3653	 * as ATH_BUF_BUSY, unmark it here before
3654	 * finishing the frame processing.
3655	 * Since we've completed a frame (aggregate
3656	 * or otherwise), the hardware has moved on
3657	 * and is no longer referencing the previous
3658	 * descriptor.
3659	 */
3660	ATH_TXBUF_LOCK_ASSERT(sc);
3661	last = TAILQ_LAST(&sc->sc_txbuf_mgmt, ath_bufhead_s);
3662	if (last != NULL)
3663		last->bf_flags &= ~ATH_BUF_BUSY;
3664	last = TAILQ_LAST(&sc->sc_txbuf, ath_bufhead_s);
3665	if (last != NULL)
3666		last->bf_flags &= ~ATH_BUF_BUSY;
3667}
3668
3669/*
3670 * Process the completion of the given buffer.
3671 *
3672 * This calls the rate control update and then the buffer completion.
3673 * This will either free the buffer or requeue it.  In any case, the
3674 * bf pointer should be treated as invalid after this function is called.
3675 */
3676void
3677ath_tx_process_buf_completion(struct ath_softc *sc, struct ath_txq *txq,
3678    struct ath_tx_status *ts, struct ath_buf *bf)
3679{
3680	struct ieee80211_node *ni = bf->bf_node;
3681	struct ath_node *an = NULL;
3682
3683	ATH_TXQ_UNLOCK_ASSERT(txq);
3684
3685	/* If unicast frame, update general statistics */
3686	if (ni != NULL) {
3687		an = ATH_NODE(ni);
3688		/* update statistics */
3689		ath_tx_update_stats(sc, ts, bf);
3690	}
3691
3692	/*
3693	 * Call the completion handler.
3694	 * The completion handler is responsible for
3695	 * calling the rate control code.
3696	 *
3697	 * Frames with no completion handler get the
3698	 * rate control code called here.
3699	 */
3700	if (bf->bf_comp == NULL) {
3701		if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
3702		    (bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) {
3703			/*
3704			 * XXX assume this isn't an aggregate
3705			 * frame.
3706			 */
3707			ath_tx_update_ratectrl(sc, ni,
3708			     bf->bf_state.bfs_rc, ts,
3709			    bf->bf_state.bfs_pktlen, 1,
3710			    (ts->ts_status == 0 ? 0 : 1));
3711		}
3712		ath_tx_default_comp(sc, bf, 0);
3713	} else
3714		bf->bf_comp(sc, bf, 0);
3715}
3716
3717
3718
3719/*
3720 * Process completed xmit descriptors from the specified queue.
3721 * Kick the packet scheduler if needed. This can occur from this
3722 * particular task.
3723 */
3724static int
3725ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq, int dosched)
3726{
3727	struct ath_hal *ah = sc->sc_ah;
3728	struct ath_buf *bf;
3729	struct ath_desc *ds;
3730	struct ath_tx_status *ts;
3731	struct ieee80211_node *ni;
3732#ifdef	IEEE80211_SUPPORT_SUPERG
3733	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3734#endif	/* IEEE80211_SUPPORT_SUPERG */
3735	int nacked;
3736	HAL_STATUS status;
3737
3738	DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
3739		__func__, txq->axq_qnum,
3740		(caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
3741		txq->axq_link);
3742
3743	ATH_KTR(sc, ATH_KTR_TXCOMP, 4,
3744	    "ath_tx_processq: txq=%u head %p link %p depth %p",
3745	    txq->axq_qnum,
3746	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
3747	    txq->axq_link,
3748	    txq->axq_depth);
3749
3750	nacked = 0;
3751	for (;;) {
3752		ATH_TXQ_LOCK(txq);
3753		txq->axq_intrcnt = 0;	/* reset periodic desc intr count */
3754		bf = TAILQ_FIRST(&txq->axq_q);
3755		if (bf == NULL) {
3756			ATH_TXQ_UNLOCK(txq);
3757			break;
3758		}
3759		ds = bf->bf_lastds;	/* XXX must be setup correctly! */
3760		ts = &bf->bf_status.ds_txstat;
3761
3762		status = ath_hal_txprocdesc(ah, ds, ts);
3763#ifdef ATH_DEBUG
3764		if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
3765			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
3766			    status == HAL_OK);
3767		else if ((sc->sc_debug & ATH_DEBUG_RESET) && (dosched == 0))
3768			ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
3769			    status == HAL_OK);
3770#endif
3771
3772		if (status == HAL_EINPROGRESS) {
3773			ATH_KTR(sc, ATH_KTR_TXCOMP, 3,
3774			    "ath_tx_processq: txq=%u, bf=%p ds=%p, HAL_EINPROGRESS",
3775			    txq->axq_qnum, bf, ds);
3776			ATH_TXQ_UNLOCK(txq);
3777			break;
3778		}
3779		ATH_TXQ_REMOVE(txq, bf, bf_list);
3780#ifdef IEEE80211_SUPPORT_TDMA
3781		if (txq->axq_depth > 0) {
3782			/*
3783			 * More frames follow.  Mark the buffer busy
3784			 * so it's not re-used while the hardware may
3785			 * still re-read the link field in the descriptor.
3786			 *
3787			 * Use the last buffer in an aggregate as that
3788			 * is where the hardware may be - intermediate
3789			 * descriptors won't be "busy".
3790			 */
3791			bf->bf_last->bf_flags |= ATH_BUF_BUSY;
3792		} else
3793#else
3794		if (txq->axq_depth == 0)
3795#endif
3796			txq->axq_link = NULL;
3797		if (bf->bf_state.bfs_aggr)
3798			txq->axq_aggr_depth--;
3799
3800		ni = bf->bf_node;
3801
3802		ATH_KTR(sc, ATH_KTR_TXCOMP, 5,
3803		    "ath_tx_processq: txq=%u, bf=%p, ds=%p, ni=%p, ts_status=0x%08x",
3804		    txq->axq_qnum, bf, ds, ni, ts->ts_status);
3805		/*
3806		 * If unicast frame was ack'd update RSSI,
3807		 * including the last rx time used to
3808		 * workaround phantom bmiss interrupts.
3809		 */
3810		if (ni != NULL && ts->ts_status == 0 &&
3811		    ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)) {
3812			nacked++;
3813			sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
3814			ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
3815				ts->ts_rssi);
3816		}
3817		ATH_TXQ_UNLOCK(txq);
3818
3819		/*
3820		 * Update statistics and call completion
3821		 */
3822		ath_tx_process_buf_completion(sc, txq, ts, bf);
3823
3824		/* XXX at this point, bf and ni may be totally invalid */
3825	}
3826#ifdef IEEE80211_SUPPORT_SUPERG
3827	/*
3828	 * Flush fast-frame staging queue when traffic slows.
3829	 */
3830	if (txq->axq_depth <= 1)
3831		ieee80211_ff_flush(ic, txq->axq_ac);
3832#endif
3833
3834	/* Kick the TXQ scheduler */
3835	if (dosched) {
3836		ATH_TXQ_LOCK(txq);
3837		ath_txq_sched(sc, txq);
3838		ATH_TXQ_UNLOCK(txq);
3839	}
3840
3841	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
3842	    "ath_tx_processq: txq=%u: done",
3843	    txq->axq_qnum);
3844
3845	return nacked;
3846}
3847
3848#define	TXQACTIVE(t, q)		( (t) & (1 << (q)))
3849
3850/*
3851 * Deferred processing of transmit interrupt; special-cased
3852 * for a single hardware transmit queue (e.g. 5210 and 5211).
3853 */
3854static void
3855ath_tx_proc_q0(void *arg, int npending)
3856{
3857	struct ath_softc *sc = arg;
3858	struct ifnet *ifp = sc->sc_ifp;
3859	uint32_t txqs;
3860
3861	ATH_PCU_LOCK(sc);
3862	sc->sc_txproc_cnt++;
3863	txqs = sc->sc_txq_active;
3864	sc->sc_txq_active &= ~txqs;
3865	ATH_PCU_UNLOCK(sc);
3866
3867	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
3868	    "ath_tx_proc_q0: txqs=0x%08x", txqs);
3869
3870	if (TXQACTIVE(txqs, 0) && ath_tx_processq(sc, &sc->sc_txq[0], 1))
3871		/* XXX why is lastrx updated in tx code? */
3872		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
3873	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
3874		ath_tx_processq(sc, sc->sc_cabq, 1);
3875	IF_LOCK(&ifp->if_snd);
3876	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3877	IF_UNLOCK(&ifp->if_snd);
3878	sc->sc_wd_timer = 0;
3879
3880	if (sc->sc_softled)
3881		ath_led_event(sc, sc->sc_txrix);
3882
3883	ATH_PCU_LOCK(sc);
3884	sc->sc_txproc_cnt--;
3885	ATH_PCU_UNLOCK(sc);
3886
3887	ath_tx_kick(sc);
3888}
3889
3890/*
3891 * Deferred processing of transmit interrupt; special-cased
3892 * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
3893 */
3894static void
3895ath_tx_proc_q0123(void *arg, int npending)
3896{
3897	struct ath_softc *sc = arg;
3898	struct ifnet *ifp = sc->sc_ifp;
3899	int nacked;
3900	uint32_t txqs;
3901
3902	ATH_PCU_LOCK(sc);
3903	sc->sc_txproc_cnt++;
3904	txqs = sc->sc_txq_active;
3905	sc->sc_txq_active &= ~txqs;
3906	ATH_PCU_UNLOCK(sc);
3907
3908	ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
3909	    "ath_tx_proc_q0123: txqs=0x%08x", txqs);
3910
3911	/*
3912	 * Process each active queue.
3913	 */
3914	nacked = 0;
3915	if (TXQACTIVE(txqs, 0))
3916		nacked += ath_tx_processq(sc, &sc->sc_txq[0], 1);
3917	if (TXQACTIVE(txqs, 1))
3918		nacked += ath_tx_processq(sc, &sc->sc_txq[1], 1);
3919	if (TXQACTIVE(txqs, 2))
3920		nacked += ath_tx_processq(sc, &sc->sc_txq[2], 1);
3921	if (TXQACTIVE(txqs, 3))
3922		nacked += ath_tx_processq(sc, &sc->sc_txq[3], 1);
3923	if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
3924		ath_tx_processq(sc, sc->sc_cabq, 1);
3925	if (nacked)
3926		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
3927
3928	IF_LOCK(&ifp->if_snd);
3929	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3930	IF_UNLOCK(&ifp->if_snd);
3931	sc->sc_wd_timer = 0;
3932
3933	if (sc->sc_softled)
3934		ath_led_event(sc, sc->sc_txrix);
3935
3936	ATH_PCU_LOCK(sc);
3937	sc->sc_txproc_cnt--;
3938	ATH_PCU_UNLOCK(sc);
3939
3940	ath_tx_kick(sc);
3941}
3942
3943/*
3944 * Deferred processing of transmit interrupt.
3945 */
3946static void
3947ath_tx_proc(void *arg, int npending)
3948{
3949	struct ath_softc *sc = arg;
3950	struct ifnet *ifp = sc->sc_ifp;
3951	int i, nacked;
3952	uint32_t txqs;
3953
3954	ATH_PCU_LOCK(sc);
3955	sc->sc_txproc_cnt++;
3956	txqs = sc->sc_txq_active;
3957	sc->sc_txq_active &= ~txqs;
3958	ATH_PCU_UNLOCK(sc);
3959
3960	ATH_KTR(sc, ATH_KTR_TXCOMP, 1, "ath_tx_proc: txqs=0x%08x", txqs);
3961
3962	/*
3963	 * Process each active queue.
3964	 */
3965	nacked = 0;
3966	for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3967		if (ATH_TXQ_SETUP(sc, i) && TXQACTIVE(txqs, i))
3968			nacked += ath_tx_processq(sc, &sc->sc_txq[i], 1);
3969	if (nacked)
3970		sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
3971
3972	/* XXX check this inside of IF_LOCK? */
3973	IF_LOCK(&ifp->if_snd);
3974	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3975	IF_UNLOCK(&ifp->if_snd);
3976	sc->sc_wd_timer = 0;
3977
3978	if (sc->sc_softled)
3979		ath_led_event(sc, sc->sc_txrix);
3980
3981	ATH_PCU_LOCK(sc);
3982	sc->sc_txproc_cnt--;
3983	ATH_PCU_UNLOCK(sc);
3984
3985	ath_tx_kick(sc);
3986}
3987#undef	TXQACTIVE
3988
3989/*
3990 * Deferred processing of TXQ rescheduling.
3991 */
3992static void
3993ath_txq_sched_tasklet(void *arg, int npending)
3994{
3995	struct ath_softc *sc = arg;
3996	int i;
3997
3998	/* XXX is skipping ok? */
3999	ATH_PCU_LOCK(sc);
4000#if 0
4001	if (sc->sc_inreset_cnt > 0) {
4002		device_printf(sc->sc_dev,
4003		    "%s: sc_inreset_cnt > 0; skipping\n", __func__);
4004		ATH_PCU_UNLOCK(sc);
4005		return;
4006	}
4007#endif
4008	sc->sc_txproc_cnt++;
4009	ATH_PCU_UNLOCK(sc);
4010
4011	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
4012		if (ATH_TXQ_SETUP(sc, i)) {
4013			ATH_TXQ_LOCK(&sc->sc_txq[i]);
4014			ath_txq_sched(sc, &sc->sc_txq[i]);
4015			ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
4016		}
4017	}
4018
4019	ATH_PCU_LOCK(sc);
4020	sc->sc_txproc_cnt--;
4021	ATH_PCU_UNLOCK(sc);
4022}
4023
4024void
4025ath_returnbuf_tail(struct ath_softc *sc, struct ath_buf *bf)
4026{
4027
4028	ATH_TXBUF_LOCK_ASSERT(sc);
4029
4030	if (bf->bf_flags & ATH_BUF_MGMT)
4031		TAILQ_INSERT_TAIL(&sc->sc_txbuf_mgmt, bf, bf_list);
4032	else {
4033		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
4034		sc->sc_txbuf_cnt++;
4035		if (sc->sc_txbuf_cnt > ath_txbuf) {
4036			device_printf(sc->sc_dev,
4037			    "%s: sc_txbuf_cnt > %d?\n",
4038			    __func__,
4039			    ath_txbuf);
4040			sc->sc_txbuf_cnt = ath_txbuf;
4041		}
4042	}
4043}
4044
4045void
4046ath_returnbuf_head(struct ath_softc *sc, struct ath_buf *bf)
4047{
4048
4049	ATH_TXBUF_LOCK_ASSERT(sc);
4050
4051	if (bf->bf_flags & ATH_BUF_MGMT)
4052		TAILQ_INSERT_HEAD(&sc->sc_txbuf_mgmt, bf, bf_list);
4053	else {
4054		TAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
4055		sc->sc_txbuf_cnt++;
4056		if (sc->sc_txbuf_cnt > ATH_TXBUF) {
4057			device_printf(sc->sc_dev,
4058			    "%s: sc_txbuf_cnt > %d?\n",
4059			    __func__,
4060			    ATH_TXBUF);
4061			sc->sc_txbuf_cnt = ATH_TXBUF;
4062		}
4063	}
4064}
4065
4066/*
4067 * Return a buffer to the pool and update the 'busy' flag on the
4068 * previous 'tail' entry.
4069 *
4070 * This _must_ only be called when the buffer is involved in a completed
4071 * TX. The logic is that if it was part of an active TX, the previous
4072 * buffer on the list is now not involved in a halted TX DMA queue, waiting
4073 * for restart (eg for TDMA.)
4074 *
4075 * The caller must free the mbuf and recycle the node reference.
4076 */
4077void
4078ath_freebuf(struct ath_softc *sc, struct ath_buf *bf)
4079{
4080	bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4081	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_POSTWRITE);
4082
4083	KASSERT((bf->bf_node == NULL), ("%s: bf->bf_node != NULL\n", __func__));
4084	KASSERT((bf->bf_m == NULL), ("%s: bf->bf_m != NULL\n", __func__));
4085
4086	ATH_TXBUF_LOCK(sc);
4087	ath_tx_update_busy(sc);
4088	ath_returnbuf_tail(sc, bf);
4089	ATH_TXBUF_UNLOCK(sc);
4090}
4091
4092/*
4093 * This is currently used by ath_tx_draintxq() and
4094 * ath_tx_tid_free_pkts().
4095 *
4096 * It recycles a single ath_buf.
4097 */
4098void
4099ath_tx_freebuf(struct ath_softc *sc, struct ath_buf *bf, int status)
4100{
4101	struct ieee80211_node *ni = bf->bf_node;
4102	struct mbuf *m0 = bf->bf_m;
4103
4104	bf->bf_node = NULL;
4105	bf->bf_m = NULL;
4106
4107	/* Free the buffer, it's not needed any longer */
4108	ath_freebuf(sc, bf);
4109
4110	if (ni != NULL) {
4111		/*
4112		 * Do any callback and reclaim the node reference.
4113		 */
4114		if (m0->m_flags & M_TXCB)
4115			ieee80211_process_callback(ni, m0, status);
4116		ieee80211_free_node(ni);
4117	}
4118	m_freem(m0);
4119
4120	/*
4121	 * XXX the buffer used to be freed -after-, but the DMA map was
4122	 * freed where ath_freebuf() now is. I've no idea what this
4123	 * will do.
4124	 */
4125}
4126
4127void
4128ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
4129{
4130#ifdef ATH_DEBUG
4131	struct ath_hal *ah = sc->sc_ah;
4132#endif
4133	struct ath_buf *bf;
4134	u_int ix;
4135
4136	/*
4137	 * NB: this assumes output has been stopped and
4138	 *     we do not need to block ath_tx_proc
4139	 */
4140	ATH_TXBUF_LOCK(sc);
4141	bf = TAILQ_LAST(&sc->sc_txbuf, ath_bufhead_s);
4142	if (bf != NULL)
4143		bf->bf_flags &= ~ATH_BUF_BUSY;
4144	bf = TAILQ_LAST(&sc->sc_txbuf_mgmt, ath_bufhead_s);
4145	if (bf != NULL)
4146		bf->bf_flags &= ~ATH_BUF_BUSY;
4147	ATH_TXBUF_UNLOCK(sc);
4148
4149	for (ix = 0;; ix++) {
4150		ATH_TXQ_LOCK(txq);
4151		bf = TAILQ_FIRST(&txq->axq_q);
4152		if (bf == NULL) {
4153			txq->axq_link = NULL;
4154			/*
4155			 * There's currently no flag that indicates
4156			 * a buffer is on the FIFO.  So until that
4157			 * occurs, just clear the FIFO counter here.
4158			 *
4159			 * Yes, this means that if something in parallel
4160			 * is pushing things onto this TXQ and pushing
4161			 * _that_ into the hardware, things will get
4162			 * very fruity very quickly.
4163			 */
4164			txq->axq_fifo_depth = 0;
4165			ATH_TXQ_UNLOCK(txq);
4166			break;
4167		}
4168		ATH_TXQ_REMOVE(txq, bf, bf_list);
4169		if (bf->bf_state.bfs_aggr)
4170			txq->axq_aggr_depth--;
4171#ifdef ATH_DEBUG
4172		if (sc->sc_debug & ATH_DEBUG_RESET) {
4173			struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4174			int status = 0;
4175
4176			/*
4177			 * EDMA operation has a TX completion FIFO
4178			 * separate from the TX descriptor, so this
4179			 * method of checking the "completion" status
4180			 * is wrong.
4181			 */
4182			if (! sc->sc_isedma) {
4183				status = (ath_hal_txprocdesc(ah,
4184				    bf->bf_lastds,
4185				    &bf->bf_status.ds_txstat) == HAL_OK);
4186			}
4187			ath_printtxbuf(sc, bf, txq->axq_qnum, ix, status);
4188			ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
4189			    bf->bf_m->m_len, 0, -1);
4190		}
4191#endif /* ATH_DEBUG */
4192		/*
4193		 * Since we're now doing magic in the completion
4194		 * functions, we -must- call it for aggregation
4195		 * destinations or BAW tracking will get upset.
4196		 */
4197		/*
4198		 * Clear ATH_BUF_BUSY; the completion handler
4199		 * will free the buffer.
4200		 */
4201		ATH_TXQ_UNLOCK(txq);
4202		bf->bf_flags &= ~ATH_BUF_BUSY;
4203		if (bf->bf_comp)
4204			bf->bf_comp(sc, bf, 1);
4205		else
4206			ath_tx_default_comp(sc, bf, 1);
4207	}
4208
4209	/*
4210	 * Drain software queued frames which are on
4211	 * active TIDs.
4212	 */
4213	ath_tx_txq_drain(sc, txq);
4214}
4215
4216static void
4217ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
4218{
4219	struct ath_hal *ah = sc->sc_ah;
4220
4221	DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4222	    __func__, txq->axq_qnum,
4223	    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
4224	    txq->axq_link);
4225	(void) ath_hal_stoptxdma(ah, txq->axq_qnum);
4226}
4227
4228int
4229ath_stoptxdma(struct ath_softc *sc)
4230{
4231	struct ath_hal *ah = sc->sc_ah;
4232	int i;
4233
4234	/* XXX return value */
4235	if (sc->sc_invalid)
4236		return 0;
4237
4238	if (!sc->sc_invalid) {
4239		/* don't touch the hardware if marked invalid */
4240		DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
4241		    __func__, sc->sc_bhalq,
4242		    (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
4243		    NULL);
4244		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
4245		for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4246			if (ATH_TXQ_SETUP(sc, i))
4247				ath_tx_stopdma(sc, &sc->sc_txq[i]);
4248	}
4249
4250	return 1;
4251}
4252
4253/*
4254 * Drain the transmit queues and reclaim resources.
4255 */
4256void
4257ath_legacy_tx_drain(struct ath_softc *sc, ATH_RESET_TYPE reset_type)
4258{
4259#ifdef	ATH_DEBUG
4260	struct ath_hal *ah = sc->sc_ah;
4261#endif
4262	struct ifnet *ifp = sc->sc_ifp;
4263	int i;
4264
4265	(void) ath_stoptxdma(sc);
4266
4267	for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
4268		/*
4269		 * XXX TODO: should we just handle the completed TX frames
4270		 * here, whether or not the reset is a full one or not?
4271		 */
4272		if (ATH_TXQ_SETUP(sc, i)) {
4273			if (reset_type == ATH_RESET_NOLOSS)
4274				ath_tx_processq(sc, &sc->sc_txq[i], 0);
4275			else
4276				ath_tx_draintxq(sc, &sc->sc_txq[i]);
4277		}
4278	}
4279#ifdef ATH_DEBUG
4280	if (sc->sc_debug & ATH_DEBUG_RESET) {
4281		struct ath_buf *bf = TAILQ_FIRST(&sc->sc_bbuf);
4282		if (bf != NULL && bf->bf_m != NULL) {
4283			ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
4284				ath_hal_txprocdesc(ah, bf->bf_lastds,
4285				    &bf->bf_status.ds_txstat) == HAL_OK);
4286			ieee80211_dump_pkt(ifp->if_l2com,
4287			    mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
4288			    0, -1);
4289		}
4290	}
4291#endif /* ATH_DEBUG */
4292	IF_LOCK(&ifp->if_snd);
4293	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4294	IF_UNLOCK(&ifp->if_snd);
4295	sc->sc_wd_timer = 0;
4296}
4297
4298/*
4299 * Update internal state after a channel change.
4300 */
4301static void
4302ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
4303{
4304	enum ieee80211_phymode mode;
4305
4306	/*
4307	 * Change channels and update the h/w rate map
4308	 * if we're switching; e.g. 11a to 11b/g.
4309	 */
4310	mode = ieee80211_chan2mode(chan);
4311	if (mode != sc->sc_curmode)
4312		ath_setcurmode(sc, mode);
4313	sc->sc_curchan = chan;
4314}
4315
4316/*
4317 * Set/change channels.  If the channel is really being changed,
4318 * it's done by resetting the chip.  To accomplish this we must
4319 * first cleanup any pending DMA, then restart stuff after a la
4320 * ath_init.
4321 */
4322static int
4323ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
4324{
4325	struct ifnet *ifp = sc->sc_ifp;
4326	struct ieee80211com *ic = ifp->if_l2com;
4327	struct ath_hal *ah = sc->sc_ah;
4328	int ret = 0;
4329
4330	/* Treat this as an interface reset */
4331	ATH_PCU_UNLOCK_ASSERT(sc);
4332	ATH_UNLOCK_ASSERT(sc);
4333
4334	/* (Try to) stop TX/RX from occuring */
4335	taskqueue_block(sc->sc_tq);
4336
4337	ATH_PCU_LOCK(sc);
4338	ath_hal_intrset(ah, 0);		/* Stop new RX/TX completion */
4339	ath_txrx_stop_locked(sc);	/* Stop pending RX/TX completion */
4340	if (ath_reset_grablock(sc, 1) == 0) {
4341		device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
4342		    __func__);
4343	}
4344	ATH_PCU_UNLOCK(sc);
4345
4346	DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
4347	    __func__, ieee80211_chan2ieee(ic, chan),
4348	    chan->ic_freq, chan->ic_flags);
4349	if (chan != sc->sc_curchan) {
4350		HAL_STATUS status;
4351		/*
4352		 * To switch channels clear any pending DMA operations;
4353		 * wait long enough for the RX fifo to drain, reset the
4354		 * hardware at the new frequency, and then re-enable
4355		 * the relevant bits of the h/w.
4356		 */
4357#if 0
4358		ath_hal_intrset(ah, 0);		/* disable interrupts */
4359#endif
4360		ath_stoprecv(sc, 1);		/* turn off frame recv */
4361		/*
4362		 * First, handle completed TX/RX frames.
4363		 */
4364		ath_rx_flush(sc);
4365		ath_draintxq(sc, ATH_RESET_NOLOSS);
4366		/*
4367		 * Next, flush the non-scheduled frames.
4368		 */
4369		ath_draintxq(sc, ATH_RESET_FULL);	/* clear pending tx frames */
4370
4371		if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
4372			if_printf(ifp, "%s: unable to reset "
4373			    "channel %u (%u MHz, flags 0x%x), hal status %u\n",
4374			    __func__, ieee80211_chan2ieee(ic, chan),
4375			    chan->ic_freq, chan->ic_flags, status);
4376			ret = EIO;
4377			goto finish;
4378		}
4379		sc->sc_diversity = ath_hal_getdiversity(ah);
4380
4381		/* Let DFS at it in case it's a DFS channel */
4382		ath_dfs_radar_enable(sc, chan);
4383
4384		/*
4385		 * Re-enable rx framework.
4386		 */
4387		if (ath_startrecv(sc) != 0) {
4388			if_printf(ifp, "%s: unable to restart recv logic\n",
4389			    __func__);
4390			ret = EIO;
4391			goto finish;
4392		}
4393
4394		/*
4395		 * Change channels and update the h/w rate map
4396		 * if we're switching; e.g. 11a to 11b/g.
4397		 */
4398		ath_chan_change(sc, chan);
4399
4400		/*
4401		 * Reset clears the beacon timers; reset them
4402		 * here if needed.
4403		 */
4404		if (sc->sc_beacons) {		/* restart beacons */
4405#ifdef IEEE80211_SUPPORT_TDMA
4406			if (sc->sc_tdma)
4407				ath_tdma_config(sc, NULL);
4408			else
4409#endif
4410			ath_beacon_config(sc, NULL);
4411		}
4412
4413		/*
4414		 * Re-enable interrupts.
4415		 */
4416#if 0
4417		ath_hal_intrset(ah, sc->sc_imask);
4418#endif
4419	}
4420
4421finish:
4422	ATH_PCU_LOCK(sc);
4423	sc->sc_inreset_cnt--;
4424	/* XXX only do this if sc_inreset_cnt == 0? */
4425	ath_hal_intrset(ah, sc->sc_imask);
4426	ATH_PCU_UNLOCK(sc);
4427
4428	IF_LOCK(&ifp->if_snd);
4429	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4430	IF_UNLOCK(&ifp->if_snd);
4431	ath_txrx_start(sc);
4432	/* XXX ath_start? */
4433
4434	return ret;
4435}
4436
4437/*
4438 * Periodically recalibrate the PHY to account
4439 * for temperature/environment changes.
4440 */
4441static void
4442ath_calibrate(void *arg)
4443{
4444	struct ath_softc *sc = arg;
4445	struct ath_hal *ah = sc->sc_ah;
4446	struct ifnet *ifp = sc->sc_ifp;
4447	struct ieee80211com *ic = ifp->if_l2com;
4448	HAL_BOOL longCal, isCalDone = AH_TRUE;
4449	HAL_BOOL aniCal, shortCal = AH_FALSE;
4450	int nextcal;
4451
4452	if (ic->ic_flags & IEEE80211_F_SCAN)	/* defer, off channel */
4453		goto restart;
4454	longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
4455	aniCal = (ticks - sc->sc_lastani >= ath_anicalinterval*hz/1000);
4456	if (sc->sc_doresetcal)
4457		shortCal = (ticks - sc->sc_lastshortcal >= ath_shortcalinterval*hz/1000);
4458
4459	DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: shortCal=%d; longCal=%d; aniCal=%d\n", __func__, shortCal, longCal, aniCal);
4460	if (aniCal) {
4461		sc->sc_stats.ast_ani_cal++;
4462		sc->sc_lastani = ticks;
4463		ath_hal_ani_poll(ah, sc->sc_curchan);
4464	}
4465
4466	if (longCal) {
4467		sc->sc_stats.ast_per_cal++;
4468		sc->sc_lastlongcal = ticks;
4469		if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
4470			/*
4471			 * Rfgain is out of bounds, reset the chip
4472			 * to load new gain values.
4473			 */
4474			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4475				"%s: rfgain change\n", __func__);
4476			sc->sc_stats.ast_per_rfgain++;
4477			sc->sc_resetcal = 0;
4478			sc->sc_doresetcal = AH_TRUE;
4479			taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
4480			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
4481			return;
4482		}
4483		/*
4484		 * If this long cal is after an idle period, then
4485		 * reset the data collection state so we start fresh.
4486		 */
4487		if (sc->sc_resetcal) {
4488			(void) ath_hal_calreset(ah, sc->sc_curchan);
4489			sc->sc_lastcalreset = ticks;
4490			sc->sc_lastshortcal = ticks;
4491			sc->sc_resetcal = 0;
4492			sc->sc_doresetcal = AH_TRUE;
4493		}
4494	}
4495
4496	/* Only call if we're doing a short/long cal, not for ANI calibration */
4497	if (shortCal || longCal) {
4498		isCalDone = AH_FALSE;
4499		if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
4500			if (longCal) {
4501				/*
4502				 * Calibrate noise floor data again in case of change.
4503				 */
4504				ath_hal_process_noisefloor(ah);
4505			}
4506		} else {
4507			DPRINTF(sc, ATH_DEBUG_ANY,
4508				"%s: calibration of channel %u failed\n",
4509				__func__, sc->sc_curchan->ic_freq);
4510			sc->sc_stats.ast_per_calfail++;
4511		}
4512		if (shortCal)
4513			sc->sc_lastshortcal = ticks;
4514	}
4515	if (!isCalDone) {
4516restart:
4517		/*
4518		 * Use a shorter interval to potentially collect multiple
4519		 * data samples required to complete calibration.  Once
4520		 * we're told the work is done we drop back to a longer
4521		 * interval between requests.  We're more aggressive doing
4522		 * work when operating as an AP to improve operation right
4523		 * after startup.
4524		 */
4525		sc->sc_lastshortcal = ticks;
4526		nextcal = ath_shortcalinterval*hz/1000;
4527		if (sc->sc_opmode != HAL_M_HOSTAP)
4528			nextcal *= 10;
4529		sc->sc_doresetcal = AH_TRUE;
4530	} else {
4531		/* nextcal should be the shortest time for next event */
4532		nextcal = ath_longcalinterval*hz;
4533		if (sc->sc_lastcalreset == 0)
4534			sc->sc_lastcalreset = sc->sc_lastlongcal;
4535		else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
4536			sc->sc_resetcal = 1;	/* setup reset next trip */
4537		sc->sc_doresetcal = AH_FALSE;
4538	}
4539	/* ANI calibration may occur more often than short/long/resetcal */
4540	if (ath_anicalinterval > 0)
4541		nextcal = MIN(nextcal, ath_anicalinterval*hz/1000);
4542
4543	if (nextcal != 0) {
4544		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
4545		    __func__, nextcal, isCalDone ? "" : "!");
4546		callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
4547	} else {
4548		DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
4549		    __func__);
4550		/* NB: don't rearm timer */
4551	}
4552}
4553
4554static void
4555ath_scan_start(struct ieee80211com *ic)
4556{
4557	struct ifnet *ifp = ic->ic_ifp;
4558	struct ath_softc *sc = ifp->if_softc;
4559	struct ath_hal *ah = sc->sc_ah;
4560	u_int32_t rfilt;
4561
4562	/* XXX calibration timer? */
4563
4564	ATH_LOCK(sc);
4565	sc->sc_scanning = 1;
4566	sc->sc_syncbeacon = 0;
4567	rfilt = ath_calcrxfilter(sc);
4568	ATH_UNLOCK(sc);
4569
4570	ATH_PCU_LOCK(sc);
4571	ath_hal_setrxfilter(ah, rfilt);
4572	ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
4573	ATH_PCU_UNLOCK(sc);
4574
4575	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
4576		 __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
4577}
4578
4579static void
4580ath_scan_end(struct ieee80211com *ic)
4581{
4582	struct ifnet *ifp = ic->ic_ifp;
4583	struct ath_softc *sc = ifp->if_softc;
4584	struct ath_hal *ah = sc->sc_ah;
4585	u_int32_t rfilt;
4586
4587	ATH_LOCK(sc);
4588	sc->sc_scanning = 0;
4589	rfilt = ath_calcrxfilter(sc);
4590	ATH_UNLOCK(sc);
4591
4592	ATH_PCU_LOCK(sc);
4593	ath_hal_setrxfilter(ah, rfilt);
4594	ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
4595
4596	ath_hal_process_noisefloor(ah);
4597	ATH_PCU_UNLOCK(sc);
4598
4599	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
4600		 __func__, rfilt, ether_sprintf(sc->sc_curbssid),
4601		 sc->sc_curaid);
4602}
4603
4604#ifdef	ATH_ENABLE_11N
4605/*
4606 * For now, just do a channel change.
4607 *
4608 * Later, we'll go through the hard slog of suspending tx/rx, changing rate
4609 * control state and resetting the hardware without dropping frames out
4610 * of the queue.
4611 *
4612 * The unfortunate trouble here is making absolutely sure that the
4613 * channel width change has propagated enough so the hardware
4614 * absolutely isn't handed bogus frames for it's current operating
4615 * mode. (Eg, 40MHz frames in 20MHz mode.) Since TX and RX can and
4616 * does occur in parallel, we need to make certain we've blocked
4617 * any further ongoing TX (and RX, that can cause raw TX)
4618 * before we do this.
4619 */
4620static void
4621ath_update_chw(struct ieee80211com *ic)
4622{
4623	struct ifnet *ifp = ic->ic_ifp;
4624	struct ath_softc *sc = ifp->if_softc;
4625
4626	DPRINTF(sc, ATH_DEBUG_STATE, "%s: called\n", __func__);
4627	ath_set_channel(ic);
4628}
4629#endif	/* ATH_ENABLE_11N */
4630
4631static void
4632ath_set_channel(struct ieee80211com *ic)
4633{
4634	struct ifnet *ifp = ic->ic_ifp;
4635	struct ath_softc *sc = ifp->if_softc;
4636
4637	(void) ath_chan_set(sc, ic->ic_curchan);
4638	/*
4639	 * If we are returning to our bss channel then mark state
4640	 * so the next recv'd beacon's tsf will be used to sync the
4641	 * beacon timers.  Note that since we only hear beacons in
4642	 * sta/ibss mode this has no effect in other operating modes.
4643	 */
4644	ATH_LOCK(sc);
4645	if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
4646		sc->sc_syncbeacon = 1;
4647	ATH_UNLOCK(sc);
4648}
4649
4650/*
4651 * Walk the vap list and check if there any vap's in RUN state.
4652 */
4653static int
4654ath_isanyrunningvaps(struct ieee80211vap *this)
4655{
4656	struct ieee80211com *ic = this->iv_ic;
4657	struct ieee80211vap *vap;
4658
4659	IEEE80211_LOCK_ASSERT(ic);
4660
4661	TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
4662		if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
4663			return 1;
4664	}
4665	return 0;
4666}
4667
4668static int
4669ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
4670{
4671	struct ieee80211com *ic = vap->iv_ic;
4672	struct ath_softc *sc = ic->ic_ifp->if_softc;
4673	struct ath_vap *avp = ATH_VAP(vap);
4674	struct ath_hal *ah = sc->sc_ah;
4675	struct ieee80211_node *ni = NULL;
4676	int i, error, stamode;
4677	u_int32_t rfilt;
4678	int csa_run_transition = 0;
4679	static const HAL_LED_STATE leds[] = {
4680	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
4681	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
4682	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
4683	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
4684	    HAL_LED_RUN, 	/* IEEE80211_S_CAC */
4685	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
4686	    HAL_LED_RUN, 	/* IEEE80211_S_CSA */
4687	    HAL_LED_RUN, 	/* IEEE80211_S_SLEEP */
4688	};
4689
4690	DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
4691		ieee80211_state_name[vap->iv_state],
4692		ieee80211_state_name[nstate]);
4693
4694	/*
4695	 * net80211 _should_ have the comlock asserted at this point.
4696	 * There are some comments around the calls to vap->iv_newstate
4697	 * which indicate that it (newstate) may end up dropping the
4698	 * lock.  This and the subsequent lock assert check after newstate
4699	 * are an attempt to catch these and figure out how/why.
4700	 */
4701	IEEE80211_LOCK_ASSERT(ic);
4702
4703	if (vap->iv_state == IEEE80211_S_CSA && nstate == IEEE80211_S_RUN)
4704		csa_run_transition = 1;
4705
4706	callout_drain(&sc->sc_cal_ch);
4707	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
4708
4709	if (nstate == IEEE80211_S_SCAN) {
4710		/*
4711		 * Scanning: turn off beacon miss and don't beacon.
4712		 * Mark beacon state so when we reach RUN state we'll
4713		 * [re]setup beacons.  Unblock the task q thread so
4714		 * deferred interrupt processing is done.
4715		 */
4716		ath_hal_intrset(ah,
4717		    sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
4718		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4719		sc->sc_beacons = 0;
4720		taskqueue_unblock(sc->sc_tq);
4721	}
4722
4723	ni = ieee80211_ref_node(vap->iv_bss);
4724	rfilt = ath_calcrxfilter(sc);
4725	stamode = (vap->iv_opmode == IEEE80211_M_STA ||
4726		   vap->iv_opmode == IEEE80211_M_AHDEMO ||
4727		   vap->iv_opmode == IEEE80211_M_IBSS);
4728	if (stamode && nstate == IEEE80211_S_RUN) {
4729		sc->sc_curaid = ni->ni_associd;
4730		IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
4731		ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
4732	}
4733	DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
4734	   __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
4735	ath_hal_setrxfilter(ah, rfilt);
4736
4737	/* XXX is this to restore keycache on resume? */
4738	if (vap->iv_opmode != IEEE80211_M_STA &&
4739	    (vap->iv_flags & IEEE80211_F_PRIVACY)) {
4740		for (i = 0; i < IEEE80211_WEP_NKID; i++)
4741			if (ath_hal_keyisvalid(ah, i))
4742				ath_hal_keysetmac(ah, i, ni->ni_bssid);
4743	}
4744
4745	/*
4746	 * Invoke the parent method to do net80211 work.
4747	 */
4748	error = avp->av_newstate(vap, nstate, arg);
4749	if (error != 0)
4750		goto bad;
4751
4752	/*
4753	 * See above: ensure av_newstate() doesn't drop the lock
4754	 * on us.
4755	 */
4756	IEEE80211_LOCK_ASSERT(ic);
4757
4758	if (nstate == IEEE80211_S_RUN) {
4759		/* NB: collect bss node again, it may have changed */
4760		ieee80211_free_node(ni);
4761		ni = ieee80211_ref_node(vap->iv_bss);
4762
4763		DPRINTF(sc, ATH_DEBUG_STATE,
4764		    "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
4765		    "capinfo 0x%04x chan %d\n", __func__,
4766		    vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
4767		    ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
4768
4769		switch (vap->iv_opmode) {
4770#ifdef IEEE80211_SUPPORT_TDMA
4771		case IEEE80211_M_AHDEMO:
4772			if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
4773				break;
4774			/* fall thru... */
4775#endif
4776		case IEEE80211_M_HOSTAP:
4777		case IEEE80211_M_IBSS:
4778		case IEEE80211_M_MBSS:
4779			/*
4780			 * Allocate and setup the beacon frame.
4781			 *
4782			 * Stop any previous beacon DMA.  This may be
4783			 * necessary, for example, when an ibss merge
4784			 * causes reconfiguration; there will be a state
4785			 * transition from RUN->RUN that means we may
4786			 * be called with beacon transmission active.
4787			 */
4788			ath_hal_stoptxdma(ah, sc->sc_bhalq);
4789
4790			error = ath_beacon_alloc(sc, ni);
4791			if (error != 0)
4792				goto bad;
4793			/*
4794			 * If joining an adhoc network defer beacon timer
4795			 * configuration to the next beacon frame so we
4796			 * have a current TSF to use.  Otherwise we're
4797			 * starting an ibss/bss so there's no need to delay;
4798			 * if this is the first vap moving to RUN state, then
4799			 * beacon state needs to be [re]configured.
4800			 */
4801			if (vap->iv_opmode == IEEE80211_M_IBSS &&
4802			    ni->ni_tstamp.tsf != 0) {
4803				sc->sc_syncbeacon = 1;
4804			} else if (!sc->sc_beacons) {
4805#ifdef IEEE80211_SUPPORT_TDMA
4806				if (vap->iv_caps & IEEE80211_C_TDMA)
4807					ath_tdma_config(sc, vap);
4808				else
4809#endif
4810					ath_beacon_config(sc, vap);
4811				sc->sc_beacons = 1;
4812			}
4813			break;
4814		case IEEE80211_M_STA:
4815			/*
4816			 * Defer beacon timer configuration to the next
4817			 * beacon frame so we have a current TSF to use
4818			 * (any TSF collected when scanning is likely old).
4819			 * However if it's due to a CSA -> RUN transition,
4820			 * force a beacon update so we pick up a lack of
4821			 * beacons from an AP in CAC and thus force a
4822			 * scan.
4823			 */
4824			sc->sc_syncbeacon = 1;
4825			if (csa_run_transition)
4826				ath_beacon_config(sc, vap);
4827			break;
4828		case IEEE80211_M_MONITOR:
4829			/*
4830			 * Monitor mode vaps have only INIT->RUN and RUN->RUN
4831			 * transitions so we must re-enable interrupts here to
4832			 * handle the case of a single monitor mode vap.
4833			 */
4834			ath_hal_intrset(ah, sc->sc_imask);
4835			break;
4836		case IEEE80211_M_WDS:
4837			break;
4838		default:
4839			break;
4840		}
4841		/*
4842		 * Let the hal process statistics collected during a
4843		 * scan so it can provide calibrated noise floor data.
4844		 */
4845		ath_hal_process_noisefloor(ah);
4846		/*
4847		 * Reset rssi stats; maybe not the best place...
4848		 */
4849		sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
4850		sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
4851		sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
4852		/*
4853		 * Finally, start any timers and the task q thread
4854		 * (in case we didn't go through SCAN state).
4855		 */
4856		if (ath_longcalinterval != 0) {
4857			/* start periodic recalibration timer */
4858			callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
4859		} else {
4860			DPRINTF(sc, ATH_DEBUG_CALIBRATE,
4861			    "%s: calibration disabled\n", __func__);
4862		}
4863		taskqueue_unblock(sc->sc_tq);
4864	} else if (nstate == IEEE80211_S_INIT) {
4865		/*
4866		 * If there are no vaps left in RUN state then
4867		 * shutdown host/driver operation:
4868		 * o disable interrupts
4869		 * o disable the task queue thread
4870		 * o mark beacon processing as stopped
4871		 */
4872		if (!ath_isanyrunningvaps(vap)) {
4873			sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4874			/* disable interrupts  */
4875			ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
4876			taskqueue_block(sc->sc_tq);
4877			sc->sc_beacons = 0;
4878		}
4879#ifdef IEEE80211_SUPPORT_TDMA
4880		ath_hal_setcca(ah, AH_TRUE);
4881#endif
4882	}
4883bad:
4884	ieee80211_free_node(ni);
4885	return error;
4886}
4887
4888/*
4889 * Allocate a key cache slot to the station so we can
4890 * setup a mapping from key index to node. The key cache
4891 * slot is needed for managing antenna state and for
4892 * compression when stations do not use crypto.  We do
4893 * it uniliaterally here; if crypto is employed this slot
4894 * will be reassigned.
4895 */
4896static void
4897ath_setup_stationkey(struct ieee80211_node *ni)
4898{
4899	struct ieee80211vap *vap = ni->ni_vap;
4900	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4901	ieee80211_keyix keyix, rxkeyix;
4902
4903	/* XXX should take a locked ref to vap->iv_bss */
4904	if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
4905		/*
4906		 * Key cache is full; we'll fall back to doing
4907		 * the more expensive lookup in software.  Note
4908		 * this also means no h/w compression.
4909		 */
4910		/* XXX msg+statistic */
4911	} else {
4912		/* XXX locking? */
4913		ni->ni_ucastkey.wk_keyix = keyix;
4914		ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
4915		/* NB: must mark device key to get called back on delete */
4916		ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
4917		IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
4918		/* NB: this will create a pass-thru key entry */
4919		ath_keyset(sc, vap, &ni->ni_ucastkey, vap->iv_bss);
4920	}
4921}
4922
4923/*
4924 * Setup driver-specific state for a newly associated node.
4925 * Note that we're called also on a re-associate, the isnew
4926 * param tells us if this is the first time or not.
4927 */
4928static void
4929ath_newassoc(struct ieee80211_node *ni, int isnew)
4930{
4931	struct ath_node *an = ATH_NODE(ni);
4932	struct ieee80211vap *vap = ni->ni_vap;
4933	struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
4934	const struct ieee80211_txparam *tp = ni->ni_txparms;
4935
4936	an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
4937	an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
4938
4939	ath_rate_newassoc(sc, an, isnew);
4940	if (isnew &&
4941	    (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
4942	    ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
4943		ath_setup_stationkey(ni);
4944}
4945
4946static int
4947ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
4948	int nchans, struct ieee80211_channel chans[])
4949{
4950	struct ath_softc *sc = ic->ic_ifp->if_softc;
4951	struct ath_hal *ah = sc->sc_ah;
4952	HAL_STATUS status;
4953
4954	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
4955	    "%s: rd %u cc %u location %c%s\n",
4956	    __func__, reg->regdomain, reg->country, reg->location,
4957	    reg->ecm ? " ecm" : "");
4958
4959	status = ath_hal_set_channels(ah, chans, nchans,
4960	    reg->country, reg->regdomain);
4961	if (status != HAL_OK) {
4962		DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
4963		    __func__, status);
4964		return EINVAL;		/* XXX */
4965	}
4966
4967	return 0;
4968}
4969
4970static void
4971ath_getradiocaps(struct ieee80211com *ic,
4972	int maxchans, int *nchans, struct ieee80211_channel chans[])
4973{
4974	struct ath_softc *sc = ic->ic_ifp->if_softc;
4975	struct ath_hal *ah = sc->sc_ah;
4976
4977	DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
4978	    __func__, SKU_DEBUG, CTRY_DEFAULT);
4979
4980	/* XXX check return */
4981	(void) ath_hal_getchannels(ah, chans, maxchans, nchans,
4982	    HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
4983
4984}
4985
4986static int
4987ath_getchannels(struct ath_softc *sc)
4988{
4989	struct ifnet *ifp = sc->sc_ifp;
4990	struct ieee80211com *ic = ifp->if_l2com;
4991	struct ath_hal *ah = sc->sc_ah;
4992	HAL_STATUS status;
4993
4994	/*
4995	 * Collect channel set based on EEPROM contents.
4996	 */
4997	status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
4998	    &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
4999	if (status != HAL_OK) {
5000		if_printf(ifp, "%s: unable to collect channel list from hal, "
5001		    "status %d\n", __func__, status);
5002		return EINVAL;
5003	}
5004	(void) ath_hal_getregdomain(ah, &sc->sc_eerd);
5005	ath_hal_getcountrycode(ah, &sc->sc_eecc);	/* NB: cannot fail */
5006	/* XXX map Atheros sku's to net80211 SKU's */
5007	/* XXX net80211 types too small */
5008	ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
5009	ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
5010	ic->ic_regdomain.isocc[0] = ' ';	/* XXX don't know */
5011	ic->ic_regdomain.isocc[1] = ' ';
5012
5013	ic->ic_regdomain.ecm = 1;
5014	ic->ic_regdomain.location = 'I';
5015
5016	DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
5017	    "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
5018	    __func__, sc->sc_eerd, sc->sc_eecc,
5019	    ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
5020	    ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
5021	return 0;
5022}
5023
5024static int
5025ath_rate_setup(struct ath_softc *sc, u_int mode)
5026{
5027	struct ath_hal *ah = sc->sc_ah;
5028	const HAL_RATE_TABLE *rt;
5029
5030	switch (mode) {
5031	case IEEE80211_MODE_11A:
5032		rt = ath_hal_getratetable(ah, HAL_MODE_11A);
5033		break;
5034	case IEEE80211_MODE_HALF:
5035		rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
5036		break;
5037	case IEEE80211_MODE_QUARTER:
5038		rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
5039		break;
5040	case IEEE80211_MODE_11B:
5041		rt = ath_hal_getratetable(ah, HAL_MODE_11B);
5042		break;
5043	case IEEE80211_MODE_11G:
5044		rt = ath_hal_getratetable(ah, HAL_MODE_11G);
5045		break;
5046	case IEEE80211_MODE_TURBO_A:
5047		rt = ath_hal_getratetable(ah, HAL_MODE_108A);
5048		break;
5049	case IEEE80211_MODE_TURBO_G:
5050		rt = ath_hal_getratetable(ah, HAL_MODE_108G);
5051		break;
5052	case IEEE80211_MODE_STURBO_A:
5053		rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
5054		break;
5055	case IEEE80211_MODE_11NA:
5056		rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
5057		break;
5058	case IEEE80211_MODE_11NG:
5059		rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
5060		break;
5061	default:
5062		DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
5063			__func__, mode);
5064		return 0;
5065	}
5066	sc->sc_rates[mode] = rt;
5067	return (rt != NULL);
5068}
5069
5070static void
5071ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
5072{
5073#define	N(a)	(sizeof(a)/sizeof(a[0]))
5074	/* NB: on/off times from the Atheros NDIS driver, w/ permission */
5075	static const struct {
5076		u_int		rate;		/* tx/rx 802.11 rate */
5077		u_int16_t	timeOn;		/* LED on time (ms) */
5078		u_int16_t	timeOff;	/* LED off time (ms) */
5079	} blinkrates[] = {
5080		{ 108,  40,  10 },
5081		{  96,  44,  11 },
5082		{  72,  50,  13 },
5083		{  48,  57,  14 },
5084		{  36,  67,  16 },
5085		{  24,  80,  20 },
5086		{  22, 100,  25 },
5087		{  18, 133,  34 },
5088		{  12, 160,  40 },
5089		{  10, 200,  50 },
5090		{   6, 240,  58 },
5091		{   4, 267,  66 },
5092		{   2, 400, 100 },
5093		{   0, 500, 130 },
5094		/* XXX half/quarter rates */
5095	};
5096	const HAL_RATE_TABLE *rt;
5097	int i, j;
5098
5099	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
5100	rt = sc->sc_rates[mode];
5101	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
5102	for (i = 0; i < rt->rateCount; i++) {
5103		uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
5104		if (rt->info[i].phy != IEEE80211_T_HT)
5105			sc->sc_rixmap[ieeerate] = i;
5106		else
5107			sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
5108	}
5109	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
5110	for (i = 0; i < N(sc->sc_hwmap); i++) {
5111		if (i >= rt->rateCount) {
5112			sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
5113			sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
5114			continue;
5115		}
5116		sc->sc_hwmap[i].ieeerate =
5117			rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
5118		if (rt->info[i].phy == IEEE80211_T_HT)
5119			sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
5120		sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
5121		if (rt->info[i].shortPreamble ||
5122		    rt->info[i].phy == IEEE80211_T_OFDM)
5123			sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
5124		sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
5125		for (j = 0; j < N(blinkrates)-1; j++)
5126			if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
5127				break;
5128		/* NB: this uses the last entry if the rate isn't found */
5129		/* XXX beware of overlow */
5130		sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
5131		sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
5132	}
5133	sc->sc_currates = rt;
5134	sc->sc_curmode = mode;
5135	/*
5136	 * All protection frames are transmited at 2Mb/s for
5137	 * 11g, otherwise at 1Mb/s.
5138	 */
5139	if (mode == IEEE80211_MODE_11G)
5140		sc->sc_protrix = ath_tx_findrix(sc, 2*2);
5141	else
5142		sc->sc_protrix = ath_tx_findrix(sc, 2*1);
5143	/* NB: caller is responsible for resetting rate control state */
5144#undef N
5145}
5146
5147static void
5148ath_watchdog(void *arg)
5149{
5150	struct ath_softc *sc = arg;
5151	int do_reset = 0;
5152
5153	if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
5154		struct ifnet *ifp = sc->sc_ifp;
5155		uint32_t hangs;
5156
5157		if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
5158		    hangs != 0) {
5159			if_printf(ifp, "%s hang detected (0x%x)\n",
5160			    hangs & 0xff ? "bb" : "mac", hangs);
5161		} else
5162			if_printf(ifp, "device timeout\n");
5163		do_reset = 1;
5164		ifp->if_oerrors++;
5165		sc->sc_stats.ast_watchdog++;
5166	}
5167
5168	/*
5169	 * We can't hold the lock across the ath_reset() call.
5170	 *
5171	 * And since this routine can't hold a lock and sleep,
5172	 * do the reset deferred.
5173	 */
5174	if (do_reset) {
5175		taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
5176	}
5177
5178	callout_schedule(&sc->sc_wd_ch, hz);
5179}
5180
5181/*
5182 * Fetch the rate control statistics for the given node.
5183 */
5184static int
5185ath_ioctl_ratestats(struct ath_softc *sc, struct ath_rateioctl *rs)
5186{
5187	struct ath_node *an;
5188	struct ieee80211com *ic = sc->sc_ifp->if_l2com;
5189	struct ieee80211_node *ni;
5190	int error = 0;
5191
5192	/* Perform a lookup on the given node */
5193	ni = ieee80211_find_node(&ic->ic_sta, rs->is_u.macaddr);
5194	if (ni == NULL) {
5195		error = EINVAL;
5196		goto bad;
5197	}
5198
5199	/* Lock the ath_node */
5200	an = ATH_NODE(ni);
5201	ATH_NODE_LOCK(an);
5202
5203	/* Fetch the rate control stats for this node */
5204	error = ath_rate_fetch_node_stats(sc, an, rs);
5205
5206	/* No matter what happens here, just drop through */
5207
5208	/* Unlock the ath_node */
5209	ATH_NODE_UNLOCK(an);
5210
5211	/* Unref the node */
5212	ieee80211_node_decref(ni);
5213
5214bad:
5215	return (error);
5216}
5217
5218#ifdef ATH_DIAGAPI
5219/*
5220 * Diagnostic interface to the HAL.  This is used by various
5221 * tools to do things like retrieve register contents for
5222 * debugging.  The mechanism is intentionally opaque so that
5223 * it can change frequently w/o concern for compatiblity.
5224 */
5225static int
5226ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
5227{
5228	struct ath_hal *ah = sc->sc_ah;
5229	u_int id = ad->ad_id & ATH_DIAG_ID;
5230	void *indata = NULL;
5231	void *outdata = NULL;
5232	u_int32_t insize = ad->ad_in_size;
5233	u_int32_t outsize = ad->ad_out_size;
5234	int error = 0;
5235
5236	if (ad->ad_id & ATH_DIAG_IN) {
5237		/*
5238		 * Copy in data.
5239		 */
5240		indata = malloc(insize, M_TEMP, M_NOWAIT);
5241		if (indata == NULL) {
5242			error = ENOMEM;
5243			goto bad;
5244		}
5245		error = copyin(ad->ad_in_data, indata, insize);
5246		if (error)
5247			goto bad;
5248	}
5249	if (ad->ad_id & ATH_DIAG_DYN) {
5250		/*
5251		 * Allocate a buffer for the results (otherwise the HAL
5252		 * returns a pointer to a buffer where we can read the
5253		 * results).  Note that we depend on the HAL leaving this
5254		 * pointer for us to use below in reclaiming the buffer;
5255		 * may want to be more defensive.
5256		 */
5257		outdata = malloc(outsize, M_TEMP, M_NOWAIT);
5258		if (outdata == NULL) {
5259			error = ENOMEM;
5260			goto bad;
5261		}
5262	}
5263	if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
5264		if (outsize < ad->ad_out_size)
5265			ad->ad_out_size = outsize;
5266		if (outdata != NULL)
5267			error = copyout(outdata, ad->ad_out_data,
5268					ad->ad_out_size);
5269	} else {
5270		error = EINVAL;
5271	}
5272bad:
5273	if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
5274		free(indata, M_TEMP);
5275	if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
5276		free(outdata, M_TEMP);
5277	return error;
5278}
5279#endif /* ATH_DIAGAPI */
5280
5281static int
5282ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
5283{
5284#define	IS_RUNNING(ifp) \
5285	((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
5286	struct ath_softc *sc = ifp->if_softc;
5287	struct ieee80211com *ic = ifp->if_l2com;
5288	struct ifreq *ifr = (struct ifreq *)data;
5289	const HAL_RATE_TABLE *rt;
5290	int error = 0;
5291
5292	switch (cmd) {
5293	case SIOCSIFFLAGS:
5294		ATH_LOCK(sc);
5295		if (IS_RUNNING(ifp)) {
5296			/*
5297			 * To avoid rescanning another access point,
5298			 * do not call ath_init() here.  Instead,
5299			 * only reflect promisc mode settings.
5300			 */
5301			ath_mode_init(sc);
5302		} else if (ifp->if_flags & IFF_UP) {
5303			/*
5304			 * Beware of being called during attach/detach
5305			 * to reset promiscuous mode.  In that case we
5306			 * will still be marked UP but not RUNNING.
5307			 * However trying to re-init the interface
5308			 * is the wrong thing to do as we've already
5309			 * torn down much of our state.  There's
5310			 * probably a better way to deal with this.
5311			 */
5312			if (!sc->sc_invalid)
5313				ath_init(sc);	/* XXX lose error */
5314		} else {
5315			ath_stop_locked(ifp);
5316#ifdef notyet
5317			/* XXX must wakeup in places like ath_vap_delete */
5318			if (!sc->sc_invalid)
5319				ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
5320#endif
5321		}
5322		ATH_UNLOCK(sc);
5323		break;
5324	case SIOCGIFMEDIA:
5325	case SIOCSIFMEDIA:
5326		error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
5327		break;
5328	case SIOCGATHSTATS:
5329		/* NB: embed these numbers to get a consistent view */
5330		sc->sc_stats.ast_tx_packets = ifp->if_opackets;
5331		sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
5332		sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
5333		sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
5334#ifdef IEEE80211_SUPPORT_TDMA
5335		sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
5336		sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
5337#endif
5338		rt = sc->sc_currates;
5339		sc->sc_stats.ast_tx_rate =
5340		    rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
5341		if (rt->info[sc->sc_txrix].phy & IEEE80211_T_HT)
5342			sc->sc_stats.ast_tx_rate |= IEEE80211_RATE_MCS;
5343		return copyout(&sc->sc_stats,
5344		    ifr->ifr_data, sizeof (sc->sc_stats));
5345	case SIOCGATHAGSTATS:
5346		return copyout(&sc->sc_aggr_stats,
5347		    ifr->ifr_data, sizeof (sc->sc_aggr_stats));
5348	case SIOCZATHSTATS:
5349		error = priv_check(curthread, PRIV_DRIVER);
5350		if (error == 0) {
5351			memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
5352			memset(&sc->sc_aggr_stats, 0,
5353			    sizeof(sc->sc_aggr_stats));
5354			memset(&sc->sc_intr_stats, 0,
5355			    sizeof(sc->sc_intr_stats));
5356		}
5357		break;
5358#ifdef ATH_DIAGAPI
5359	case SIOCGATHDIAG:
5360		error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
5361		break;
5362	case SIOCGATHPHYERR:
5363		error = ath_ioctl_phyerr(sc,(struct ath_diag*) ifr);
5364		break;
5365#endif
5366	case SIOCGATHNODERATESTATS:
5367		error = ath_ioctl_ratestats(sc, (struct ath_rateioctl *) ifr);
5368		break;
5369	case SIOCGIFADDR:
5370		error = ether_ioctl(ifp, cmd, data);
5371		break;
5372	default:
5373		error = EINVAL;
5374		break;
5375	}
5376	return error;
5377#undef IS_RUNNING
5378}
5379
5380/*
5381 * Announce various information on device/driver attach.
5382 */
5383static void
5384ath_announce(struct ath_softc *sc)
5385{
5386	struct ifnet *ifp = sc->sc_ifp;
5387	struct ath_hal *ah = sc->sc_ah;
5388
5389	if_printf(ifp, "AR%s mac %d.%d RF%s phy %d.%d\n",
5390		ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
5391		ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
5392	if_printf(ifp, "2GHz radio: 0x%.4x; 5GHz radio: 0x%.4x\n",
5393		ah->ah_analog2GhzRev, ah->ah_analog5GhzRev);
5394	if (bootverbose) {
5395		int i;
5396		for (i = 0; i <= WME_AC_VO; i++) {
5397			struct ath_txq *txq = sc->sc_ac2q[i];
5398			if_printf(ifp, "Use hw queue %u for %s traffic\n",
5399				txq->axq_qnum, ieee80211_wme_acnames[i]);
5400		}
5401		if_printf(ifp, "Use hw queue %u for CAB traffic\n",
5402			sc->sc_cabq->axq_qnum);
5403		if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
5404	}
5405	if (ath_rxbuf != ATH_RXBUF)
5406		if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
5407	if (ath_txbuf != ATH_TXBUF)
5408		if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
5409	if (sc->sc_mcastkey && bootverbose)
5410		if_printf(ifp, "using multicast key search\n");
5411}
5412
5413static void
5414ath_dfs_tasklet(void *p, int npending)
5415{
5416	struct ath_softc *sc = (struct ath_softc *) p;
5417	struct ifnet *ifp = sc->sc_ifp;
5418	struct ieee80211com *ic = ifp->if_l2com;
5419
5420	/*
5421	 * If previous processing has found a radar event,
5422	 * signal this to the net80211 layer to begin DFS
5423	 * processing.
5424	 */
5425	if (ath_dfs_process_radar_event(sc, sc->sc_curchan)) {
5426		/* DFS event found, initiate channel change */
5427		/*
5428		 * XXX doesn't currently tell us whether the event
5429		 * XXX was found in the primary or extension
5430		 * XXX channel!
5431		 */
5432		IEEE80211_LOCK(ic);
5433		ieee80211_dfs_notify_radar(ic, sc->sc_curchan);
5434		IEEE80211_UNLOCK(ic);
5435	}
5436}
5437
5438/*
5439 * Enable/disable power save.  This must be called with
5440 * no TX driver locks currently held, so it should only
5441 * be called from the RX path (which doesn't hold any
5442 * TX driver locks.)
5443 */
5444static void
5445ath_node_powersave(struct ieee80211_node *ni, int enable)
5446{
5447#ifdef	ATH_SW_PSQ
5448	struct ath_node *an = ATH_NODE(ni);
5449	struct ieee80211com *ic = ni->ni_ic;
5450	struct ath_softc *sc = ic->ic_ifp->if_softc;
5451	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
5452
5453	ATH_NODE_UNLOCK_ASSERT(an);
5454	/* XXX and no TXQ locks should be held here */
5455
5456	DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE, "%s: ni=%p, enable=%d\n",
5457	    __func__, ni, enable);
5458
5459	/* Suspend or resume software queue handling */
5460	if (enable)
5461		ath_tx_node_sleep(sc, an);
5462	else
5463		ath_tx_node_wakeup(sc, an);
5464
5465	/* Update net80211 state */
5466	avp->av_node_ps(ni, enable);
5467#else
5468	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
5469
5470	/* Update net80211 state */
5471	avp->av_node_ps(ni, enable);
5472#endif/* ATH_SW_PSQ */
5473}
5474
5475/*
5476 * Notification from net80211 that the powersave queue state has
5477 * changed.
5478 *
5479 * Since the software queue also may have some frames:
5480 *
5481 * + if the node software queue has frames and the TID state
5482 *   is 0, we set the TIM;
5483 * + if the node and the stack are both empty, we clear the TIM bit.
5484 * + If the stack tries to set the bit, always set it.
5485 * + If the stack tries to clear the bit, only clear it if the
5486 *   software queue in question is also cleared.
5487 *
5488 * TODO: this is called during node teardown; so let's ensure this
5489 * is all correctly handled and that the TIM bit is cleared.
5490 * It may be that the node flush is called _AFTER_ the net80211
5491 * stack clears the TIM.
5492 *
5493 * Here is the racy part.  Since it's possible >1 concurrent,
5494 * overlapping TXes will appear complete with a TX completion in
5495 * another thread, it's possible that the concurrent TIM calls will
5496 * clash.  We can't hold the node lock here because setting the
5497 * TIM grabs the net80211 comlock and this may cause a LOR.
5498 * The solution is either to totally serialise _everything_ at
5499 * this point (ie, all TX, completion and any reset/flush go into
5500 * one taskqueue) or a new "ath TIM lock" needs to be created that
5501 * just wraps the driver state change and this call to avp->av_set_tim().
5502 *
5503 * The same race exists in the net80211 power save queue handling
5504 * as well.  Since multiple transmitting threads may queue frames
5505 * into the driver, as well as ps-poll and the driver transmitting
5506 * frames (and thus clearing the psq), it's quite possible that
5507 * a packet entering the PSQ and a ps-poll being handled will
5508 * race, causing the TIM to be cleared and not re-set.
5509 */
5510static int
5511ath_node_set_tim(struct ieee80211_node *ni, int enable)
5512{
5513#ifdef	ATH_SW_PSQ
5514	struct ieee80211com *ic = ni->ni_ic;
5515	struct ath_softc *sc = ic->ic_ifp->if_softc;
5516	struct ath_node *an = ATH_NODE(ni);
5517	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
5518	int changed = 0;
5519
5520	ATH_NODE_UNLOCK_ASSERT(an);
5521
5522	/*
5523	 * For now, just track and then update the TIM.
5524	 */
5525	ATH_NODE_LOCK(an);
5526	an->an_stack_psq = enable;
5527
5528	/*
5529	 * This will get called for all operating modes,
5530	 * even if avp->av_set_tim is unset.
5531	 * It's currently set for hostap/ibss modes; but
5532	 * the same infrastructure is used for both STA
5533	 * and AP/IBSS node power save.
5534	 */
5535	if (avp->av_set_tim == NULL) {
5536		ATH_NODE_UNLOCK(an);
5537		return (0);
5538	}
5539
5540	/*
5541	 * If setting the bit, always set it here.
5542	 * If clearing the bit, only clear it if the
5543	 * software queue is also empty.
5544	 *
5545	 * If the node has left power save, just clear the TIM
5546	 * bit regardless of the state of the power save queue.
5547	 *
5548	 * XXX TODO: although atomics are used, it's quite possible
5549	 * that a race will occur between this and setting/clearing
5550	 * in another thread.  TX completion will occur always in
5551	 * one thread, however setting/clearing the TIM bit can come
5552	 * from a variety of different process contexts!
5553	 */
5554	if (enable && an->an_tim_set == 1) {
5555		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
5556		    "%s: an=%p, enable=%d, tim_set=1, ignoring\n",
5557		    __func__, an, enable);
5558		ATH_NODE_UNLOCK(an);
5559	} else if (enable) {
5560		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
5561		    "%s: an=%p, enable=%d, enabling TIM\n",
5562		    __func__, an, enable);
5563		an->an_tim_set = 1;
5564		ATH_NODE_UNLOCK(an);
5565		changed = avp->av_set_tim(ni, enable);
5566	} else if (atomic_load_acq_int(&an->an_swq_depth) == 0) {
5567		/* disable */
5568		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
5569		    "%s: an=%p, enable=%d, an_swq_depth == 0, disabling\n",
5570		    __func__, an, enable);
5571		an->an_tim_set = 0;
5572		ATH_NODE_UNLOCK(an);
5573		changed = avp->av_set_tim(ni, enable);
5574	} else if (! an->an_is_powersave) {
5575		/*
5576		 * disable regardless; the node isn't in powersave now
5577		 */
5578		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
5579		    "%s: an=%p, enable=%d, an_pwrsave=0, disabling\n",
5580		    __func__, an, enable);
5581		an->an_tim_set = 0;
5582		ATH_NODE_UNLOCK(an);
5583		changed = avp->av_set_tim(ni, enable);
5584	} else {
5585		/*
5586		 * psq disable, node is currently in powersave, node
5587		 * software queue isn't empty, so don't clear the TIM bit
5588		 * for now.
5589		 */
5590		ATH_NODE_UNLOCK(an);
5591		DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
5592		    "%s: enable=%d, an_swq_depth > 0, ignoring\n",
5593		    __func__, enable);
5594		changed = 0;
5595	}
5596
5597	return (changed);
5598#else
5599	struct ath_vap *avp = ATH_VAP(ni->ni_vap);
5600
5601	/*
5602	 * Some operating omdes don't set av_set_tim(), so don't
5603	 * update it here.
5604	 */
5605	if (avp->av_set_tim == NULL)
5606		return (0);
5607
5608	return (avp->av_set_tim(ni, enable));
5609#endif /* ATH_SW_PSQ */
5610}
5611
5612/*
5613 * Set or update the TIM from the software queue.
5614 *
5615 * Check the software queue depth before attempting to do lock
5616 * anything; that avoids trying to obtain the lock.  Then,
5617 * re-check afterwards to ensure nothing has changed in the
5618 * meantime.
5619 *
5620 * set:   This is designed to be called from the TX path, after
5621 *        a frame has been queued; to see if the swq > 0.
5622 *
5623 * clear: This is designed to be called from the buffer completion point
5624 *        (right now it's ath_tx_default_comp()) where the state of
5625 *        a software queue has changed.
5626 *
5627 * It makes sense to place it at buffer free / completion rather
5628 * than after each software queue operation, as there's no real
5629 * point in churning the TIM bit as the last frames in the software
5630 * queue are transmitted.  If they fail and we retry them, we'd
5631 * just be setting the TIM bit again anyway.
5632 */
5633void
5634ath_tx_update_tim(struct ath_softc *sc, struct ieee80211_node *ni,
5635     int enable)
5636{
5637#ifdef	ATH_SW_PSQ
5638	struct ath_node *an;
5639	struct ath_vap *avp;
5640
5641	/* Don't do this for broadcast/etc frames */
5642	if (ni == NULL)
5643		return;
5644
5645	an = ATH_NODE(ni);
5646	avp = ATH_VAP(ni->ni_vap);
5647
5648	/*
5649	 * And for operating modes without the TIM handler set, let's
5650	 * just skip those.
5651	 */
5652	if (avp->av_set_tim == NULL)
5653		return;
5654
5655	ATH_NODE_UNLOCK_ASSERT(an);
5656
5657	if (enable) {
5658		/*
5659		 * Don't bother grabbing the lock unless the queue is not
5660		 * empty.
5661		 */
5662		if (atomic_load_acq_int(&an->an_swq_depth) == 0)
5663			return;
5664
5665		ATH_NODE_LOCK(an);
5666		if (an->an_is_powersave &&
5667		    an->an_tim_set == 0 &&
5668		    atomic_load_acq_int(&an->an_swq_depth) != 0) {
5669			DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
5670			    "%s: an=%p, swq_depth>0, tim_set=0, set!\n",
5671			    __func__, an);
5672			an->an_tim_set = 1;
5673			ATH_NODE_UNLOCK(an);
5674			(void) avp->av_set_tim(ni, 1);
5675		} else {
5676			ATH_NODE_UNLOCK(an);
5677		}
5678	} else {
5679		/*
5680		 * Don't bother grabbing the lock unless the queue is empty.
5681		 */
5682		if (atomic_load_acq_int(&an->an_swq_depth) != 0)
5683			return;
5684
5685		ATH_NODE_LOCK(an);
5686		if (an->an_is_powersave &&
5687		    an->an_stack_psq == 0 &&
5688		    an->an_tim_set == 1 &&
5689		    atomic_load_acq_int(&an->an_swq_depth) == 0) {
5690			DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
5691			    "%s: an=%p, swq_depth=0, tim_set=1, psq_set=0,"
5692			    " clear!\n",
5693			    __func__, an);
5694			an->an_tim_set = 0;
5695			ATH_NODE_UNLOCK(an);
5696			(void) avp->av_set_tim(ni, 0);
5697		} else {
5698			ATH_NODE_UNLOCK(an);
5699		}
5700	}
5701#else
5702	return;
5703#endif	/* ATH_SW_PSQ */
5704}
5705
5706MODULE_VERSION(if_ath, 1);
5707MODULE_DEPEND(if_ath, wlan, 1, 1, 1);          /* 802.11 media layer */
5708#if	defined(IEEE80211_ALQ) || defined(AH_DEBUG_ALQ)
5709MODULE_DEPEND(if_ath, alq, 1, 1, 1);
5710#endif
5711