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