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