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