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