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