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