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