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