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