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