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