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