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