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