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