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