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