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