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