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