ath - wlan_assert_serialized in ath_init/_start/_ioctl
[dragonfly.git] / sys / dev / netif / ath / ath / if_ath.c
1 /*-
2  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification.
11  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13  *    redistribution must be conditioned upon including a substantially
14  *    similar Disclaimer requirement for further binary redistribution.
15  *
16  * NO WARRANTY
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
22  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27  * THE POSSIBILITY OF SUCH DAMAGES.
28  *
29  * $FreeBSD: head/sys/dev/ath/if_ath.c 203751 2010-02-10 11:12:39Z rpaulo $");
30  */
31
32 /*
33  * Driver for the Atheros Wireless LAN controller.
34  *
35  * This software is derived from work of Atsushi Onoe; his contribution
36  * is greatly appreciated.
37  */
38
39 #include "opt_inet.h"
40 #include "opt_ath.h"
41 #include "opt_wlan.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h> 
45 #include <sys/sysctl.h>
46 #include <sys/mbuf.h>   
47 #include <sys/malloc.h>
48 #include <sys/lock.h>
49 #include <sys/mutex.h>
50 #include <sys/kernel.h>
51 #include <sys/socket.h>
52 #include <sys/sockio.h>
53 #include <sys/errno.h>
54 #include <sys/callout.h>
55 #include <sys/bus.h>
56 #include <sys/endian.h>
57 #include <sys/kthread.h>
58 #include <sys/taskqueue.h>
59 #include <sys/priv.h>
60
61 #include <net/if.h>
62 #include <net/if_dl.h>
63 #include <net/if_media.h>
64 #include <net/if_types.h>
65 #include <net/if_arp.h>
66 #include <net/if_llc.h>
67 #include <net/ifq_var.h>
68
69 #include <netproto/802_11/ieee80211_var.h>
70 #include <netproto/802_11/ieee80211_regdomain.h>
71 #ifdef IEEE80211_SUPPORT_SUPERG
72 #include <netproto/802_11/ieee80211_superg.h>
73 #endif
74 #ifdef IEEE80211_SUPPORT_TDMA
75 #include <netproto/802_11/ieee80211_tdma.h>
76 #endif
77
78 #include <net/bpf.h>
79
80 #ifdef INET
81 #include <netinet/in.h> 
82 #include <netinet/if_ether.h>
83 #endif
84
85 #include <dev/netif/ath/ath/if_athvar.h>
86 #include <dev/netif/ath/hal/ath_hal/ah_devid.h>         /* XXX for softled */
87
88 #ifdef ATH_TX99_DIAG
89 #include <dev/netif/ath_tx99/ath_tx99.h>
90 #endif
91
92 /*
93  * ATH_BCBUF determines the number of vap's that can transmit
94  * beacons and also (currently) the number of vap's that can
95  * have unique mac addresses/bssid.  When staggering beacons
96  * 4 is probably a good max as otherwise the beacons become
97  * very closely spaced and there is limited time for cab q traffic
98  * to go out.  You can burst beacons instead but that is not good
99  * for stations in power save and at some point you really want
100  * another radio (and channel).
101  *
102  * The limit on the number of mac addresses is tied to our use of
103  * the U/L bit and tracking addresses in a byte; it would be
104  * worthwhile to allow more for applications like proxy sta.
105  */
106 CTASSERT(ATH_BCBUF <= 8);
107
108 /* unaligned little endian access */
109 #define LE_READ_2(p)                                                    \
110         ((u_int16_t)                                                    \
111          ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
112 #define LE_READ_4(p)                                                    \
113         ((u_int32_t)                                                    \
114          ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) | \
115           (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
116
117 static struct ieee80211vap *ath_vap_create(struct ieee80211com *,
118                     const char name[IFNAMSIZ], int unit, int opmode,
119                     int flags, const uint8_t bssid[IEEE80211_ADDR_LEN],
120                     const uint8_t mac[IEEE80211_ADDR_LEN]);
121 static void     ath_vap_delete(struct ieee80211vap *);
122 static void     ath_init(void *);
123 static void     ath_stop_locked(struct ifnet *);
124 static void     ath_stop(struct ifnet *);
125 static void     ath_start(struct ifnet *);
126 static int      ath_reset(struct ifnet *);
127 static int      ath_reset_vap(struct ieee80211vap *, u_long);
128 static int      ath_media_change(struct ifnet *);
129 static void     ath_watchdog_callout(void *);
130 static int      ath_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
131 static void     ath_fatal_proc(void *, int);
132 static void     ath_bmiss_vap(struct ieee80211vap *);
133 static void     ath_bmiss_task(void *, int);
134 static int      ath_keyset(struct ath_softc *, const struct ieee80211_key *,
135                         struct ieee80211_node *);
136 static int      ath_key_alloc(struct ieee80211vap *,
137                         struct ieee80211_key *,
138                         ieee80211_keyix *, ieee80211_keyix *);
139 static int      ath_key_delete(struct ieee80211vap *,
140                         const struct ieee80211_key *);
141 static int      ath_key_set(struct ieee80211vap *, const struct ieee80211_key *,
142                         const u_int8_t mac[IEEE80211_ADDR_LEN]);
143 static void     ath_key_update_begin(struct ieee80211vap *);
144 static void     ath_key_update_end(struct ieee80211vap *);
145 static void     ath_update_mcast(struct ifnet *);
146 static void     ath_update_promisc(struct ifnet *);
147 static void     ath_mode_init(struct ath_softc *);
148 static void     ath_setslottime(struct ath_softc *);
149 static void     ath_updateslot(struct ifnet *);
150 static int      ath_beaconq_setup(struct ath_hal *);
151 static int      ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
152 static void     ath_beacon_update(struct ieee80211vap *, int item);
153 static void     ath_beacon_setup(struct ath_softc *, struct ath_buf *);
154 static void     ath_beacon_proc(void *, int);
155 static struct ath_buf *ath_beacon_generate(struct ath_softc *,
156                         struct ieee80211vap *);
157 static void     ath_bstuck_task(void *, int);
158 static void     ath_beacon_return(struct ath_softc *, struct ath_buf *);
159 static void     ath_beacon_free(struct ath_softc *);
160 static void     ath_beacon_config(struct ath_softc *, struct ieee80211vap *);
161 static void     ath_descdma_cleanup(struct ath_softc *sc,
162                         struct ath_descdma *, ath_bufhead *);
163 static int      ath_desc_alloc(struct ath_softc *);
164 static void     ath_desc_free(struct ath_softc *);
165 static struct ieee80211_node *ath_node_alloc(struct ieee80211vap *,
166                         const uint8_t [IEEE80211_ADDR_LEN]);
167 static void     ath_node_free(struct ieee80211_node *);
168 static void     ath_node_getsignal(const struct ieee80211_node *,
169                         int8_t *, int8_t *);
170 static int      ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
171 static void     ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
172                         int subtype, int rssi, int nf);
173 static void     ath_setdefantenna(struct ath_softc *, u_int);
174 static void     ath_rx_task(void *, int);
175 static void     ath_txq_init(struct ath_softc *sc, struct ath_txq *, int);
176 static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
177 static int      ath_tx_setup(struct ath_softc *, int, int);
178 static int      ath_wme_update(struct ieee80211com *);
179 static void     ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
180 static void     ath_tx_cleanup(struct ath_softc *);
181 static void     ath_freetx(struct mbuf *);
182 static int      ath_tx_start(struct ath_softc *, struct ieee80211_node *,
183                              struct ath_buf *, struct mbuf *);
184 static void     ath_tx_task_q0(void *, int);
185 static void     ath_tx_task_q0123(void *, int);
186 static void     ath_tx_task(void *, int);
187 static void     ath_tx_draintxq(struct ath_softc *, struct ath_txq *);
188 static int      ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
189 static void     ath_draintxq(struct ath_softc *);
190 static void     ath_stoprecv(struct ath_softc *);
191 static int      ath_startrecv(struct ath_softc *);
192 static void     ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
193 static void     ath_scan_start(struct ieee80211com *);
194 static void     ath_scan_end(struct ieee80211com *);
195 static void     ath_set_channel(struct ieee80211com *);
196 static void     ath_calibrate_callout(void *);
197 static int      ath_newstate(struct ieee80211vap *, enum ieee80211_state, int);
198 static void     ath_setup_stationkey(struct ieee80211_node *);
199 static void     ath_newassoc(struct ieee80211_node *, int);
200 static int      ath_setregdomain(struct ieee80211com *,
201                     struct ieee80211_regdomain *, int,
202                     struct ieee80211_channel []);
203 static void     ath_getradiocaps(struct ieee80211com *, int, int *,
204                     struct ieee80211_channel []);
205 static int      ath_getchannels(struct ath_softc *);
206 static void     ath_led_event(struct ath_softc *, int);
207
208 static int      ath_rate_setup(struct ath_softc *, u_int mode);
209 static void     ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
210
211 static void     ath_sysctlattach(struct ath_softc *);
212 static int      ath_raw_xmit(struct ieee80211_node *,
213                         struct mbuf *, const struct ieee80211_bpf_params *);
214 static void     ath_announce(struct ath_softc *);
215 static void     ath_sysctl_stats_attach(struct ath_softc *sc);
216
217 #ifdef IEEE80211_SUPPORT_TDMA
218 static void     ath_tdma_settimers(struct ath_softc *sc, u_int32_t nexttbtt,
219                     u_int32_t bintval);
220 static void     ath_tdma_bintvalsetup(struct ath_softc *sc,
221                     const struct ieee80211_tdma_state *tdma);
222 static void     ath_tdma_config(struct ath_softc *sc, struct ieee80211vap *vap);
223 static void     ath_tdma_update(struct ieee80211_node *ni,
224                     const struct ieee80211_tdma_param *tdma, int);
225 static void     ath_tdma_beacon_send(struct ath_softc *sc,
226                     struct ieee80211vap *vap);
227
228 static __inline void
229 ath_hal_setcca(struct ath_hal *ah, int ena)
230 {
231         /*
232          * NB: fill me in; this is not provided by default because disabling
233          *     CCA in most locales violates regulatory.
234          */
235 }
236
237 static __inline int
238 ath_hal_getcca(struct ath_hal *ah)
239 {
240         u_int32_t diag;
241         if (ath_hal_getcapability(ah, HAL_CAP_DIAG, 0, &diag) != HAL_OK)
242                 return 1;
243         return ((diag & 0x500000) == 0);
244 }
245
246 #define TDMA_EP_MULTIPLIER      (1<<10) /* pow2 to optimize out * and / */
247 #define TDMA_LPF_LEN            6
248 #define TDMA_DUMMY_MARKER       0x127
249 #define TDMA_EP_MUL(x, mul)     ((x) * (mul))
250 #define TDMA_IN(x)              (TDMA_EP_MUL((x), TDMA_EP_MULTIPLIER))
251 #define TDMA_LPF(x, y, len) \
252     ((x != TDMA_DUMMY_MARKER) ? (((x) * ((len)-1) + (y)) / (len)) : (y))
253 #define TDMA_SAMPLE(x, y) do {                                  \
254         x = TDMA_LPF((x), TDMA_IN(y), TDMA_LPF_LEN);            \
255 } while (0)
256 #define TDMA_EP_RND(x,mul) \
257         ((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
258 #define TDMA_AVG(x)             TDMA_EP_RND(x, TDMA_EP_MULTIPLIER)
259 #endif /* IEEE80211_SUPPORT_TDMA */
260
261 SYSCTL_DECL(_hw_ath);
262
263 /* XXX validate sysctl values */
264 static  int ath_longcalinterval = 30;           /* long cals every 30 secs */
265 SYSCTL_INT(_hw_ath, OID_AUTO, longcal, CTLFLAG_RW, &ath_longcalinterval,
266             0, "long chip calibration interval (secs)");
267 static  int ath_shortcalinterval = 100;         /* short cals every 100 ms */
268 SYSCTL_INT(_hw_ath, OID_AUTO, shortcal, CTLFLAG_RW, &ath_shortcalinterval,
269             0, "short chip calibration interval (msecs)");
270 static  int ath_resetcalinterval = 20*60;       /* reset cal state 20 mins */
271 SYSCTL_INT(_hw_ath, OID_AUTO, resetcal, CTLFLAG_RW, &ath_resetcalinterval,
272             0, "reset chip calibration results (secs)");
273
274 static  int ath_rxbuf = ATH_RXBUF;              /* # rx buffers to allocate */
275 SYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RW, &ath_rxbuf,
276             0, "rx buffers allocated");
277 TUNABLE_INT("hw.ath.rxbuf", &ath_rxbuf);
278 static  int ath_txbuf = ATH_TXBUF;              /* # tx buffers to allocate */
279 SYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RW, &ath_txbuf,
280             0, "tx buffers allocated");
281 TUNABLE_INT("hw.ath.txbuf", &ath_txbuf);
282
283 static  int ath_bstuck_threshold = 4;           /* max missed beacons */
284 SYSCTL_INT(_hw_ath, OID_AUTO, bstuck, CTLFLAG_RW, &ath_bstuck_threshold,
285             0, "max missed beacon xmits before chip reset");
286
287 #ifdef ATH_DEBUG
288 enum {
289         ATH_DEBUG_XMIT          = 0x00000001,   /* basic xmit operation */
290         ATH_DEBUG_XMIT_DESC     = 0x00000002,   /* xmit descriptors */
291         ATH_DEBUG_RECV          = 0x00000004,   /* basic recv operation */
292         ATH_DEBUG_RECV_DESC     = 0x00000008,   /* recv descriptors */
293         ATH_DEBUG_RATE          = 0x00000010,   /* rate control */
294         ATH_DEBUG_RESET         = 0x00000020,   /* reset processing */
295         ATH_DEBUG_MODE          = 0x00000040,   /* mode init/setup */
296         ATH_DEBUG_BEACON        = 0x00000080,   /* beacon handling */
297         ATH_DEBUG_WATCHDOG      = 0x00000100,   /* watchdog timeout */
298         ATH_DEBUG_INTR          = 0x00001000,   /* ISR */
299         ATH_DEBUG_TX_PROC       = 0x00002000,   /* tx ISR proc */
300         ATH_DEBUG_RX_PROC       = 0x00004000,   /* rx ISR proc */
301         ATH_DEBUG_BEACON_PROC   = 0x00008000,   /* beacon ISR proc */
302         ATH_DEBUG_CALIBRATE     = 0x00010000,   /* periodic calibration */
303         ATH_DEBUG_KEYCACHE      = 0x00020000,   /* key cache management */
304         ATH_DEBUG_STATE         = 0x00040000,   /* 802.11 state transitions */
305         ATH_DEBUG_NODE          = 0x00080000,   /* node management */
306         ATH_DEBUG_LED           = 0x00100000,   /* led management */
307         ATH_DEBUG_FF            = 0x00200000,   /* fast frames */
308         ATH_DEBUG_DFS           = 0x00400000,   /* DFS processing */
309         ATH_DEBUG_TDMA          = 0x00800000,   /* TDMA processing */
310         ATH_DEBUG_TDMA_TIMER    = 0x01000000,   /* TDMA timer processing */
311         ATH_DEBUG_REGDOMAIN     = 0x02000000,   /* regulatory processing */
312         ATH_DEBUG_FATAL         = 0x80000000,   /* fatal errors */
313         ATH_DEBUG_ANY           = 0xffffffff
314 };
315 static  int ath_debug = 0;
316 SYSCTL_INT(_hw_ath, OID_AUTO, debug, CTLFLAG_RW, &ath_debug,
317             0, "control debugging printfs");
318 TUNABLE_INT("hw.ath.debug", &ath_debug);
319
320 #define IFF_DUMPPKTS(sc, m) \
321         ((sc->sc_debug & (m)) || \
322             (sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
323 #define DPRINTF(sc, m, fmt, ...) do {                           \
324         if (sc->sc_debug & (m))                                 \
325                 kprintf(fmt, __VA_ARGS__);                      \
326 } while (0)
327 #define KEYPRINTF(sc, ix, hk, mac) do {                         \
328         if (sc->sc_debug & ATH_DEBUG_KEYCACHE)                  \
329                 ath_keyprint(sc, __func__, ix, hk, mac);        \
330 } while (0)
331 static  void ath_printrxbuf(struct ath_softc *, const struct ath_buf *bf,
332         u_int ix, int);
333 static  void ath_printtxbuf(struct ath_softc *, const struct ath_buf *bf,
334         u_int qnum, u_int ix, int done);
335 #else
336 #define IFF_DUMPPKTS(sc, m) \
337         ((sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
338 #define DPRINTF(sc, m, fmt, ...) do {                           \
339         (void) sc;                                              \
340 } while (0)
341 #define KEYPRINTF(sc, k, ix, mac) do {                          \
342         (void) sc;                                              \
343 } while (0)
344 #endif
345
346 MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
347
348 int
349 ath_attach(u_int16_t devid, struct ath_softc *sc)
350 {
351         struct ifnet *ifp;
352         struct ieee80211com *ic;
353         struct ath_hal *ah = NULL;
354         HAL_STATUS status;
355         int error = 0, i;
356         u_int wmodes;
357         uint8_t macaddr[IEEE80211_ADDR_LEN];
358
359         DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
360
361         ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
362         if (ifp == NULL) {
363                 device_printf(sc->sc_dev, "can not if_alloc()\n");
364                 error = ENOSPC;
365                 goto bad;
366         }
367         ic = ifp->if_l2com;
368
369         /* set these up early for if_printf use */
370         if_initname(ifp, device_get_name(sc->sc_dev),
371                 device_get_unit(sc->sc_dev));
372
373         /* prepare sysctl tree for use in sub modules */
374         sysctl_ctx_init(&sc->sc_sysctl_ctx);
375         sc->sc_sysctl_tree = SYSCTL_ADD_NODE(&sc->sc_sysctl_ctx,
376                 SYSCTL_STATIC_CHILDREN(_hw),
377                 OID_AUTO,
378                 device_get_nameunit(sc->sc_dev),
379                 CTLFLAG_RD, 0, "");
380
381         ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, &status);
382         if (ah == NULL) {
383                 if_printf(ifp, "unable to attach hardware; HAL status %u\n",
384                         status);
385                 error = ENXIO;
386                 goto bad;
387         }
388         sc->sc_ah = ah;
389         sc->sc_invalid = 0;     /* ready to go, enable interrupt handling */
390 #ifdef  ATH_DEBUG
391         sc->sc_debug = ath_debug;
392 #endif
393
394         /*
395          * Check if the MAC has multi-rate retry support.
396          * We do this by trying to setup a fake extended
397          * descriptor.  MAC's that don't have support will
398          * return false w/o doing anything.  MAC's that do
399          * support it will return true w/o doing anything.
400          */
401         sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
402
403         /*
404          * Check if the device has hardware counters for PHY
405          * errors.  If so we need to enable the MIB interrupt
406          * so we can act on stat triggers.
407          */
408         if (ath_hal_hwphycounters(ah))
409                 sc->sc_needmib = 1;
410
411         /*
412          * Get the hardware key cache size.
413          */
414         sc->sc_keymax = ath_hal_keycachesize(ah);
415         if (sc->sc_keymax > ATH_KEYMAX) {
416                 if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
417                         ATH_KEYMAX, sc->sc_keymax);
418                 sc->sc_keymax = ATH_KEYMAX;
419         }
420         /*
421          * Reset the key cache since some parts do not
422          * reset the contents on initial power up.
423          */
424         for (i = 0; i < sc->sc_keymax; i++)
425                 ath_hal_keyreset(ah, i);
426
427         /*
428          * Collect the default channel list.
429          */
430         error = ath_getchannels(sc);
431         if (error != 0)
432                 goto bad;
433
434         /*
435          * Setup rate tables for all potential media types.
436          */
437         ath_rate_setup(sc, IEEE80211_MODE_11A);
438         ath_rate_setup(sc, IEEE80211_MODE_11B);
439         ath_rate_setup(sc, IEEE80211_MODE_11G);
440         ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
441         ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
442         ath_rate_setup(sc, IEEE80211_MODE_STURBO_A);
443         ath_rate_setup(sc, IEEE80211_MODE_11NA);
444         ath_rate_setup(sc, IEEE80211_MODE_11NG);
445         ath_rate_setup(sc, IEEE80211_MODE_HALF);
446         ath_rate_setup(sc, IEEE80211_MODE_QUARTER);
447
448         /* NB: setup here so ath_rate_update is happy */
449         ath_setcurmode(sc, IEEE80211_MODE_11A);
450
451         /*
452          * Allocate tx+rx descriptors and populate the lists.
453          */
454         wlan_assert_serialized();
455         wlan_serialize_exit();
456         error = ath_desc_alloc(sc);
457         wlan_serialize_enter();
458         if (error != 0) {
459                 if_printf(ifp, "failed to allocate descriptors: %d\n", error);
460                 goto bad;
461         }
462         callout_init(&sc->sc_cal_ch);
463         callout_init(&sc->sc_wd_ch);
464
465         sc->sc_tq = taskqueue_create("ath_taskq", M_INTWAIT,
466                 taskqueue_thread_enqueue, &sc->sc_tq);
467         taskqueue_start_threads(&sc->sc_tq, 1, TDPRI_KERN_DAEMON, -1,
468                 "%s taskq", ifp->if_xname);
469
470         TASK_INIT(&sc->sc_rxtask, 0, ath_rx_task, sc);
471         TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_task, sc);
472         TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_task, sc);
473
474         /*
475          * Allocate hardware transmit queues: one queue for
476          * beacon frames and one data queue for each QoS
477          * priority.  Note that the hal handles reseting
478          * these queues at the needed time.
479          *
480          * XXX PS-Poll
481          */
482         sc->sc_bhalq = ath_beaconq_setup(ah);
483         if (sc->sc_bhalq == (u_int) -1) {
484                 if_printf(ifp, "unable to setup a beacon xmit queue!\n");
485                 error = EIO;
486                 goto bad2;
487         }
488         sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
489         if (sc->sc_cabq == NULL) {
490                 if_printf(ifp, "unable to setup CAB xmit queue!\n");
491                 error = EIO;
492                 goto bad2;
493         }
494         /* NB: insure BK queue is the lowest priority h/w queue */
495         if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
496                 if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
497                         ieee80211_wme_acnames[WME_AC_BK]);
498                 error = EIO;
499                 goto bad2;
500         }
501         if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
502             !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
503             !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
504                 /*
505                  * Not enough hardware tx queues to properly do WME;
506                  * just punt and assign them all to the same h/w queue.
507                  * We could do a better job of this if, for example,
508                  * we allocate queues when we switch from station to
509                  * AP mode.
510                  */
511                 if (sc->sc_ac2q[WME_AC_VI] != NULL)
512                         ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
513                 if (sc->sc_ac2q[WME_AC_BE] != NULL)
514                         ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
515                 sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
516                 sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
517                 sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
518         }
519
520         /*
521          * Special case certain configurations.  Note the
522          * CAB queue is handled by these specially so don't
523          * include them when checking the txq setup mask.
524          */
525         switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
526         case 0x01:
527                 TASK_INIT(&sc->sc_txtask, 0, ath_tx_task_q0, sc);
528                 break;
529         case 0x0f:
530                 TASK_INIT(&sc->sc_txtask, 0, ath_tx_task_q0123, sc);
531                 break;
532         default:
533                 TASK_INIT(&sc->sc_txtask, 0, ath_tx_task, sc);
534                 break;
535         }
536
537         /*
538          * Setup rate control.  Some rate control modules
539          * call back to change the anntena state so expose
540          * the necessary entry points.
541          * XXX maybe belongs in struct ath_ratectrl?
542          */
543         sc->sc_setdefantenna = ath_setdefantenna;
544         sc->sc_rc = ath_rate_attach(sc);
545         if (sc->sc_rc == NULL) {
546                 error = EIO;
547                 goto bad2;
548         }
549
550         sc->sc_blinking = 0;
551         sc->sc_ledstate = 1;
552         sc->sc_ledon = 0;                       /* low true */
553         sc->sc_ledidle = (2700*hz)/1000;        /* 2.7sec */
554         callout_init_mp(&sc->sc_ledtimer);
555         /*
556          * Auto-enable soft led processing for IBM cards and for
557          * 5211 minipci cards.  Users can also manually enable/disable
558          * support with a sysctl.
559          */
560         sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
561         if (sc->sc_softled) {
562                 ath_hal_gpioCfgOutput(ah, sc->sc_ledpin,
563                     HAL_GPIO_MUX_MAC_NETWORK_LED);
564                 ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
565         }
566
567         ifp->if_softc = sc;
568         ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
569         ifp->if_start = ath_start;
570         ifp->if_ioctl = ath_ioctl;
571         ifp->if_init = ath_init;
572         ifq_set_maxlen(&ifp->if_snd, IFQ_MAXLEN);
573         ifq_set_ready(&ifp->if_snd);
574
575         ic->ic_ifp = ifp;
576         /* XXX not right but it's not used anywhere important */
577         ic->ic_phytype = IEEE80211_T_OFDM;
578         ic->ic_opmode = IEEE80211_M_STA;
579         ic->ic_caps =
580                   IEEE80211_C_STA               /* station mode */
581                 | IEEE80211_C_IBSS              /* ibss, nee adhoc, mode */
582                 | IEEE80211_C_HOSTAP            /* hostap mode */
583                 | IEEE80211_C_MONITOR           /* monitor mode */
584                 | IEEE80211_C_AHDEMO            /* adhoc demo mode */
585                 | IEEE80211_C_WDS               /* 4-address traffic works */
586                 | IEEE80211_C_MBSS              /* mesh point link mode */
587                 | IEEE80211_C_SHPREAMBLE        /* short preamble supported */
588                 | IEEE80211_C_SHSLOT            /* short slot time supported */
589                 | IEEE80211_C_WPA               /* capable of WPA1+WPA2 */
590                 | IEEE80211_C_BGSCAN            /* capable of bg scanning */
591                 | IEEE80211_C_TXFRAG            /* handle tx frags */
592                 ;
593         /*
594          * Query the hal to figure out h/w crypto support.
595          */
596         if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
597                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP;
598         if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
599                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_OCB;
600         if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
601                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_CCM;
602         if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
603                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_CKIP;
604         if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
605                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIP;
606                 /*
607                  * Check if h/w does the MIC and/or whether the
608                  * separate key cache entries are required to
609                  * handle both tx+rx MIC keys.
610                  */
611                 if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
612                         ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
613                 /*
614                  * If the h/w supports storing tx+rx MIC keys
615                  * in one cache slot automatically enable use.
616                  */
617                 if (ath_hal_hastkipsplit(ah) ||
618                     !ath_hal_settkipsplit(ah, AH_FALSE))
619                         sc->sc_splitmic = 1;
620                 /*
621                  * If the h/w can do TKIP MIC together with WME then
622                  * we use it; otherwise we force the MIC to be done
623                  * in software by the net80211 layer.
624                  */
625                 if (ath_hal_haswmetkipmic(ah))
626                         sc->sc_wmetkipmic = 1;
627         }
628         sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
629         /*
630          * Check for multicast key search support.
631          */
632         if (ath_hal_hasmcastkeysearch(sc->sc_ah) &&
633             !ath_hal_getmcastkeysearch(sc->sc_ah)) {
634                 ath_hal_setmcastkeysearch(sc->sc_ah, 1);
635         }
636         sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
637         /*
638          * Mark key cache slots associated with global keys
639          * as in use.  If we knew TKIP was not to be used we
640          * could leave the +32, +64, and +32+64 slots free.
641          */
642         for (i = 0; i < IEEE80211_WEP_NKID; i++) {
643                 setbit(sc->sc_keymap, i);
644                 setbit(sc->sc_keymap, i+64);
645                 if (sc->sc_splitmic) {
646                         setbit(sc->sc_keymap, i+32);
647                         setbit(sc->sc_keymap, i+32+64);
648                 }
649         }
650         /*
651          * TPC support can be done either with a global cap or
652          * per-packet support.  The latter is not available on
653          * all parts.  We're a bit pedantic here as all parts
654          * support a global cap.
655          */
656         if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
657                 ic->ic_caps |= IEEE80211_C_TXPMGT;
658
659         /*
660          * Mark WME capability only if we have sufficient
661          * hardware queues to do proper priority scheduling.
662          */
663         if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
664                 ic->ic_caps |= IEEE80211_C_WME;
665         /*
666          * Check for misc other capabilities.
667          */
668         if (ath_hal_hasbursting(ah))
669                 ic->ic_caps |= IEEE80211_C_BURST;
670         sc->sc_hasbmask = ath_hal_hasbssidmask(ah);
671         sc->sc_hasbmatch = ath_hal_hasbssidmatch(ah);
672         sc->sc_hastsfadd = ath_hal_hastsfadjust(ah);
673         if (ath_hal_hasfastframes(ah))
674                 ic->ic_caps |= IEEE80211_C_FF;
675         wmodes = ath_hal_getwirelessmodes(ah);
676         if (wmodes & (HAL_MODE_108G|HAL_MODE_TURBO))
677                 ic->ic_caps |= IEEE80211_C_TURBOP;
678 #ifdef IEEE80211_SUPPORT_TDMA
679         if (ath_hal_macversion(ah) > 0x78) {
680                 ic->ic_caps |= IEEE80211_C_TDMA; /* capable of TDMA */
681                 ic->ic_tdma_update = ath_tdma_update;
682         }
683 #endif
684         /*
685          * Indicate we need the 802.11 header padded to a
686          * 32-bit boundary for 4-address and QoS frames.
687          */
688         ic->ic_flags |= IEEE80211_F_DATAPAD;
689
690         /*
691          * Query the hal about antenna support.
692          */
693         sc->sc_defant = ath_hal_getdefantenna(ah);
694
695         /*
696          * Not all chips have the VEOL support we want to
697          * use with IBSS beacons; check here for it.
698          */
699         sc->sc_hasveol = ath_hal_hasveol(ah);
700
701         /* get mac address from hardware */
702         ath_hal_getmac(ah, macaddr);
703         if (sc->sc_hasbmask)
704                 ath_hal_getbssidmask(ah, sc->sc_hwbssidmask);
705
706         /* NB: used to size node table key mapping array */
707         ic->ic_max_keyix = sc->sc_keymax;
708         /* call MI attach routine. */
709         ieee80211_ifattach(ic, macaddr);
710         ic->ic_setregdomain = ath_setregdomain;
711         ic->ic_getradiocaps = ath_getradiocaps;
712         sc->sc_opmode = HAL_M_STA;
713
714         /* override default methods */
715         ic->ic_newassoc = ath_newassoc;
716         ic->ic_updateslot = ath_updateslot;
717         ic->ic_wme.wme_update = ath_wme_update;
718         ic->ic_vap_create = ath_vap_create;
719         ic->ic_vap_delete = ath_vap_delete;
720         ic->ic_raw_xmit = ath_raw_xmit;
721         ic->ic_update_mcast = ath_update_mcast;
722         ic->ic_update_promisc = ath_update_promisc;
723         ic->ic_node_alloc = ath_node_alloc;
724         sc->sc_node_free = ic->ic_node_free;
725         ic->ic_node_free = ath_node_free;
726         ic->ic_node_getsignal = ath_node_getsignal;
727         ic->ic_scan_start = ath_scan_start;
728         ic->ic_scan_end = ath_scan_end;
729         ic->ic_set_channel = ath_set_channel;
730
731         ieee80211_radiotap_attach(ic,
732             &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
733                 ATH_TX_RADIOTAP_PRESENT,
734             &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th),
735                 ATH_RX_RADIOTAP_PRESENT);
736
737         /*
738          * Setup dynamic sysctl's now that country code and
739          * regdomain are available from the hal.
740          */
741         ath_sysctlattach(sc);
742         ath_sysctl_stats_attach(sc);
743
744         if (bootverbose)
745                 ieee80211_announce(ic);
746         ath_announce(sc);
747         return 0;
748 bad2:
749         ath_tx_cleanup(sc);
750         ath_desc_free(sc);
751 bad:
752         if (ah)
753                 ath_hal_detach(ah);
754         if (ifp != NULL)
755                 if_free(ifp);
756         sc->sc_invalid = 1;
757         return error;
758 }
759
760 int
761 ath_detach(struct ath_softc *sc)
762 {
763         struct ifnet *ifp = sc->sc_ifp;
764
765         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
766                 __func__, ifp->if_flags);
767
768         /* 
769          * NB: the order of these is important:
770          * o stop the chip so no more interrupts will fire
771          * o call the 802.11 layer before detaching the hal to
772          *   insure callbacks into the driver to delete global
773          *   key cache entries can be handled
774          * o free the taskqueue which drains any pending tasks
775          * o reclaim the tx queue data structures after calling
776          *   the 802.11 layer as we'll get called back to reclaim
777          *   node state and potentially want to use them
778          * o to cleanup the tx queues the hal is called, so detach
779          *   it last
780          * Other than that, it's straightforward...
781          */
782         ath_stop(ifp);
783         ieee80211_ifdetach(ifp->if_l2com);
784         taskqueue_free(sc->sc_tq);
785 #ifdef ATH_TX99_DIAG
786         if (sc->sc_tx99 != NULL)
787                 sc->sc_tx99->detach(sc->sc_tx99);
788 #endif
789         ath_rate_detach(sc->sc_rc);
790         ath_desc_free(sc);
791         ath_tx_cleanup(sc);
792         ath_hal_detach(sc->sc_ah);      /* NB: sets chip in full sleep */
793         if (sc->sc_sysctl_tree) {
794                 sysctl_ctx_free(&sc->sc_sysctl_ctx);
795                 sc->sc_sysctl_tree = NULL;
796         }
797         if_free(ifp);
798
799         return 0;
800 }
801
802 /*
803  * MAC address handling for multiple BSS on the same radio.
804  * The first vap uses the MAC address from the EEPROM.  For
805  * subsequent vap's we set the U/L bit (bit 1) in the MAC
806  * address and use the next six bits as an index.
807  */
808 static void
809 assign_address(struct ath_softc *sc, uint8_t mac[IEEE80211_ADDR_LEN], int clone)
810 {
811         int i;
812
813         if (clone && sc->sc_hasbmask) {
814                 /* NB: we only do this if h/w supports multiple bssid */
815                 for (i = 0; i < 8; i++)
816                         if ((sc->sc_bssidmask & (1<<i)) == 0)
817                                 break;
818                 if (i != 0)
819                         mac[0] |= (i << 2)|0x2;
820         } else
821                 i = 0;
822         sc->sc_bssidmask |= 1<<i;
823         sc->sc_hwbssidmask[0] &= ~mac[0];
824         if (i == 0)
825                 sc->sc_nbssid0++;
826 }
827
828 static void
829 reclaim_address(struct ath_softc *sc, const uint8_t mac[IEEE80211_ADDR_LEN])
830 {
831         int i = mac[0] >> 2;
832         uint8_t mask;
833
834         if (i != 0 || --sc->sc_nbssid0 == 0) {
835                 sc->sc_bssidmask &= ~(1<<i);
836                 /* recalculate bssid mask from remaining addresses */
837                 mask = 0xff;
838                 for (i = 1; i < 8; i++)
839                         if (sc->sc_bssidmask & (1<<i))
840                                 mask &= ~((i<<2)|0x2);
841                 sc->sc_hwbssidmask[0] |= mask;
842         }
843 }
844
845 /*
846  * Assign a beacon xmit slot.  We try to space out
847  * assignments so when beacons are staggered the
848  * traffic coming out of the cab q has maximal time
849  * to go out before the next beacon is scheduled.
850  */
851 static int
852 assign_bslot(struct ath_softc *sc)
853 {
854         u_int slot, free;
855
856         free = 0;
857         for (slot = 0; slot < ATH_BCBUF; slot++)
858                 if (sc->sc_bslot[slot] == NULL) {
859                         if (sc->sc_bslot[(slot+1)%ATH_BCBUF] == NULL &&
860                             sc->sc_bslot[(slot-1)%ATH_BCBUF] == NULL)
861                                 return slot;
862                         free = slot;
863                         /* NB: keep looking for a double slot */
864                 }
865         return free;
866 }
867
868 static struct ieee80211vap *
869 ath_vap_create(struct ieee80211com *ic,
870         const char name[IFNAMSIZ], int unit, int opmode, int flags,
871         const uint8_t bssid[IEEE80211_ADDR_LEN],
872         const uint8_t mac0[IEEE80211_ADDR_LEN])
873 {
874         struct ath_softc *sc = ic->ic_ifp->if_softc;
875         struct ath_vap *avp;
876         struct ieee80211vap *vap;
877         uint8_t mac[IEEE80211_ADDR_LEN];
878         int ic_opmode, needbeacon, error;
879
880         avp = (struct ath_vap *) kmalloc(sizeof(struct ath_vap),
881             M_80211_VAP, M_WAITOK | M_ZERO);
882         needbeacon = 0;
883         IEEE80211_ADDR_COPY(mac, mac0);
884
885         ic_opmode = opmode;             /* default to opmode of new vap */
886         switch (opmode) {
887         case IEEE80211_M_STA:
888                 if (sc->sc_nstavaps != 0) {     /* XXX only 1 for now */
889                         device_printf(sc->sc_dev, "only 1 sta vap supported\n");
890                         goto bad;
891                 }
892                 if (sc->sc_nvaps) {
893                         /*
894                          * With multiple vaps we must fall back
895                          * to s/w beacon miss handling.
896                          */
897                         flags |= IEEE80211_CLONE_NOBEACONS;
898                 }
899                 if (flags & IEEE80211_CLONE_NOBEACONS) {
900                         /*
901                          * Station mode w/o beacons are implemented w/ AP mode.
902                          */
903                         ic_opmode = IEEE80211_M_HOSTAP;
904                 }
905                 break;
906         case IEEE80211_M_IBSS:
907                 if (sc->sc_nvaps != 0) {        /* XXX only 1 for now */
908                         device_printf(sc->sc_dev,
909                             "only 1 ibss vap supported\n");
910                         goto bad;
911                 }
912                 needbeacon = 1;
913                 break;
914         case IEEE80211_M_AHDEMO:
915 #ifdef IEEE80211_SUPPORT_TDMA
916                 if (flags & IEEE80211_CLONE_TDMA) {
917                         if (sc->sc_nvaps != 0) {
918                                 device_printf(sc->sc_dev,
919                                     "only 1 tdma vap supported\n");
920                                 goto bad;
921                         }
922                         needbeacon = 1;
923                         flags |= IEEE80211_CLONE_NOBEACONS;
924                 }
925                 /* fall thru... */
926 #endif
927         case IEEE80211_M_MONITOR:
928                 if (sc->sc_nvaps != 0 && ic->ic_opmode != opmode) {
929                         /*
930                          * Adopt existing mode.  Adding a monitor or ahdemo
931                          * vap to an existing configuration is of dubious
932                          * value but should be ok.
933                          */
934                         /* XXX not right for monitor mode */
935                         ic_opmode = ic->ic_opmode;
936                 }
937                 break;
938         case IEEE80211_M_HOSTAP:
939         case IEEE80211_M_MBSS:
940                 needbeacon = 1;
941                 break;
942         case IEEE80211_M_WDS:
943                 if (sc->sc_nvaps != 0 && ic->ic_opmode == IEEE80211_M_STA) {
944                         device_printf(sc->sc_dev,
945                             "wds not supported in sta mode\n");
946                         goto bad;
947                 }
948                 /*
949                  * Silently remove any request for a unique
950                  * bssid; WDS vap's always share the local
951                  * mac address.
952                  */
953                 flags &= ~IEEE80211_CLONE_BSSID;
954                 if (sc->sc_nvaps == 0)
955                         ic_opmode = IEEE80211_M_HOSTAP;
956                 else
957                         ic_opmode = ic->ic_opmode;
958                 break;
959         default:
960                 device_printf(sc->sc_dev, "unknown opmode %d\n", opmode);
961                 goto bad;
962         }
963         /*
964          * Check that a beacon buffer is available; the code below assumes it.
965          */
966         if (needbeacon & STAILQ_EMPTY(&sc->sc_bbuf)) {
967                 device_printf(sc->sc_dev, "no beacon buffer available\n");
968                 goto bad;
969         }
970
971         /* STA, AHDEMO? */
972         if (opmode == IEEE80211_M_HOSTAP || opmode == IEEE80211_M_MBSS) {
973                 assign_address(sc, mac, flags & IEEE80211_CLONE_BSSID);
974                 ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
975         }
976
977         vap = &avp->av_vap;
978         /* XXX can't hold mutex across if_alloc */
979         error = ieee80211_vap_setup(ic, vap, name, unit, opmode, flags,
980             bssid, mac);
981         if (error != 0) {
982                 device_printf(sc->sc_dev, "%s: error %d creating vap\n",
983                     __func__, error);
984                 goto bad2;
985         }
986
987         /* h/w crypto support */
988         vap->iv_key_alloc = ath_key_alloc;
989         vap->iv_key_delete = ath_key_delete;
990         vap->iv_key_set = ath_key_set;
991         vap->iv_key_update_begin = ath_key_update_begin;
992         vap->iv_key_update_end = ath_key_update_end;
993
994         /* override various methods */
995         avp->av_recv_mgmt = vap->iv_recv_mgmt;
996         vap->iv_recv_mgmt = ath_recv_mgmt;
997         vap->iv_reset = ath_reset_vap;
998         vap->iv_update_beacon = ath_beacon_update;
999         avp->av_newstate = vap->iv_newstate;
1000         vap->iv_newstate = ath_newstate;
1001         avp->av_bmiss = vap->iv_bmiss;
1002         vap->iv_bmiss = ath_bmiss_vap;
1003
1004         avp->av_bslot = -1;
1005         if (needbeacon) {
1006                 /*
1007                  * Allocate beacon state and setup the q for buffered
1008                  * multicast frames.  We know a beacon buffer is
1009                  * available because we checked above.
1010                  */
1011                 avp->av_bcbuf = STAILQ_FIRST(&sc->sc_bbuf);
1012                 STAILQ_REMOVE_HEAD(&sc->sc_bbuf, bf_list);
1013                 if (opmode != IEEE80211_M_IBSS || !sc->sc_hasveol) {
1014                         /*
1015                          * Assign the vap to a beacon xmit slot.  As above
1016                          * this cannot fail to find a free one.
1017                          */
1018                         avp->av_bslot = assign_bslot(sc);
1019                         KASSERT(sc->sc_bslot[avp->av_bslot] == NULL,
1020                             ("beacon slot %u not empty", avp->av_bslot));
1021                         sc->sc_bslot[avp->av_bslot] = vap;
1022                         sc->sc_nbcnvaps++;
1023                 }
1024                 if (sc->sc_hastsfadd && sc->sc_nbcnvaps > 0) {
1025                         /*
1026                          * Multple vaps are to transmit beacons and we
1027                          * have h/w support for TSF adjusting; enable
1028                          * use of staggered beacons.
1029                          */
1030                         sc->sc_stagbeacons = 1;
1031                 }
1032                 ath_txq_init(sc, &avp->av_mcastq, ATH_TXQ_SWQ);
1033         }
1034
1035         ic->ic_opmode = ic_opmode;
1036         if (opmode != IEEE80211_M_WDS) {
1037                 sc->sc_nvaps++;
1038                 if (opmode == IEEE80211_M_STA)
1039                         sc->sc_nstavaps++;
1040                 if (opmode == IEEE80211_M_MBSS)
1041                         sc->sc_nmeshvaps++;
1042         }
1043         switch (ic_opmode) {
1044         case IEEE80211_M_IBSS:
1045                 sc->sc_opmode = HAL_M_IBSS;
1046                 break;
1047         case IEEE80211_M_STA:
1048                 sc->sc_opmode = HAL_M_STA;
1049                 break;
1050         case IEEE80211_M_AHDEMO:
1051 #ifdef IEEE80211_SUPPORT_TDMA
1052                 if (vap->iv_caps & IEEE80211_C_TDMA) {
1053                         sc->sc_tdma = 1;
1054                         /* NB: disable tsf adjust */
1055                         sc->sc_stagbeacons = 0;
1056                 }
1057                 /*
1058                  * NB: adhoc demo mode is a pseudo mode; to the hal it's
1059                  * just ap mode.
1060                  */
1061                 /* fall thru... */
1062 #endif
1063         case IEEE80211_M_HOSTAP:
1064         case IEEE80211_M_MBSS:
1065                 sc->sc_opmode = HAL_M_HOSTAP;
1066                 break;
1067         case IEEE80211_M_MONITOR:
1068                 sc->sc_opmode = HAL_M_MONITOR;
1069                 break;
1070         default:
1071                 /* XXX should not happen */
1072                 break;
1073         }
1074         if (sc->sc_hastsfadd) {
1075                 /*
1076                  * Configure whether or not TSF adjust should be done.
1077                  */
1078                 ath_hal_settsfadjust(sc->sc_ah, sc->sc_stagbeacons);
1079         }
1080         if (flags & IEEE80211_CLONE_NOBEACONS) {
1081                 /*
1082                  * Enable s/w beacon miss handling.
1083                  */
1084                 sc->sc_swbmiss = 1;
1085         }
1086
1087         /* complete setup */
1088         ieee80211_vap_attach(vap, ath_media_change, ieee80211_media_status);
1089         return vap;
1090 bad2:
1091         reclaim_address(sc, mac);
1092         ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
1093 bad:
1094         kfree(avp, M_80211_VAP);
1095         return NULL;
1096 }
1097
1098 static void
1099 ath_vap_delete(struct ieee80211vap *vap)
1100 {
1101         struct ieee80211com *ic = vap->iv_ic;
1102         struct ifnet *ifp = ic->ic_ifp;
1103         struct ath_softc *sc = ifp->if_softc;
1104         struct ath_hal *ah = sc->sc_ah;
1105         struct ath_vap *avp = ATH_VAP(vap);
1106
1107         if (ifp->if_flags & IFF_RUNNING) {
1108                 /*
1109                  * Quiesce the hardware while we remove the vap.  In
1110                  * particular we need to reclaim all references to
1111                  * the vap state by any frames pending on the tx queues.
1112                  */
1113                 ath_hal_intrset(ah, 0);         /* disable interrupts */
1114                 ath_draintxq(sc);               /* stop xmit side */
1115                 ath_stoprecv(sc);               /* stop recv side */
1116         }
1117
1118         ieee80211_vap_detach(vap);
1119         /*
1120          * Reclaim beacon state.  Note this must be done before
1121          * the vap instance is reclaimed as we may have a reference
1122          * to it in the buffer for the beacon frame.
1123          */
1124         if (avp->av_bcbuf != NULL) {
1125                 if (avp->av_bslot != -1) {
1126                         sc->sc_bslot[avp->av_bslot] = NULL;
1127                         sc->sc_nbcnvaps--;
1128                 }
1129                 ath_beacon_return(sc, avp->av_bcbuf);
1130                 avp->av_bcbuf = NULL;
1131                 if (sc->sc_nbcnvaps == 0) {
1132                         sc->sc_stagbeacons = 0;
1133                         if (sc->sc_hastsfadd)
1134                                 ath_hal_settsfadjust(sc->sc_ah, 0);
1135                 }
1136                 /*
1137                  * Reclaim any pending mcast frames for the vap.
1138                  */
1139                 ath_tx_draintxq(sc, &avp->av_mcastq);
1140         }
1141         /*
1142          * Update bookkeeping.
1143          */
1144         if (vap->iv_opmode == IEEE80211_M_STA) {
1145                 sc->sc_nstavaps--;
1146                 if (sc->sc_nstavaps == 0 && sc->sc_swbmiss)
1147                         sc->sc_swbmiss = 0;
1148         } else if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1149             vap->iv_opmode == IEEE80211_M_MBSS) {
1150                 reclaim_address(sc, vap->iv_myaddr);
1151                 ath_hal_setbssidmask(ah, sc->sc_hwbssidmask);
1152                 if (vap->iv_opmode == IEEE80211_M_MBSS)
1153                         sc->sc_nmeshvaps--;
1154         }
1155         if (vap->iv_opmode != IEEE80211_M_WDS)
1156                 sc->sc_nvaps--;
1157 #ifdef IEEE80211_SUPPORT_TDMA
1158         /* TDMA operation ceases when the last vap is destroyed */
1159         if (sc->sc_tdma && sc->sc_nvaps == 0) {
1160                 sc->sc_tdma = 0;
1161                 sc->sc_swbmiss = 0;
1162         }
1163 #endif
1164         kfree(avp, M_80211_VAP);
1165
1166         if (ifp->if_flags & IFF_RUNNING) {
1167                 /*
1168                  * Restart rx+tx machines if still running (RUNNING will
1169                  * be reset if we just destroyed the last vap).
1170                  */
1171                 if (ath_startrecv(sc) != 0)
1172                         if_printf(ifp, "%s: unable to restart recv logic\n",
1173                             __func__);
1174                 if (sc->sc_beacons) {           /* restart beacons */
1175 #ifdef IEEE80211_SUPPORT_TDMA
1176                         if (sc->sc_tdma)
1177                                 ath_tdma_config(sc, NULL);
1178                         else
1179 #endif
1180                                 ath_beacon_config(sc, NULL);
1181                 }
1182                 ath_hal_intrset(ah, sc->sc_imask);
1183         }
1184 }
1185
1186 void
1187 ath_suspend(struct ath_softc *sc)
1188 {
1189         struct ifnet *ifp = sc->sc_ifp;
1190         struct ieee80211com *ic = ifp->if_l2com;
1191
1192         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1193                 __func__, ifp->if_flags);
1194
1195         sc->sc_resume_up = (ifp->if_flags & IFF_UP) != 0;
1196         if (ic->ic_opmode == IEEE80211_M_STA)
1197                 ath_stop(ifp);
1198         else
1199                 ieee80211_suspend_all(ic);
1200         /*
1201          * NB: don't worry about putting the chip in low power
1202          * mode; pci will power off our socket on suspend and
1203          * CardBus detaches the device.
1204          */
1205 }
1206
1207 /*
1208  * Reset the key cache since some parts do not reset the
1209  * contents on resume.  First we clear all entries, then
1210  * re-load keys that the 802.11 layer assumes are setup
1211  * in h/w.
1212  */
1213 static void
1214 ath_reset_keycache(struct ath_softc *sc)
1215 {
1216         struct ifnet *ifp = sc->sc_ifp;
1217         struct ieee80211com *ic = ifp->if_l2com;
1218         struct ath_hal *ah = sc->sc_ah;
1219         int i;
1220
1221         for (i = 0; i < sc->sc_keymax; i++)
1222                 ath_hal_keyreset(ah, i);
1223         ieee80211_crypto_reload_keys(ic);
1224 }
1225
1226 void
1227 ath_resume(struct ath_softc *sc)
1228 {
1229         struct ifnet *ifp = sc->sc_ifp;
1230         struct ieee80211com *ic = ifp->if_l2com;
1231         struct ath_hal *ah = sc->sc_ah;
1232         HAL_STATUS status;
1233
1234         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1235                 __func__, ifp->if_flags);
1236
1237         /*
1238          * Must reset the chip before we reload the
1239          * keycache as we were powered down on suspend.
1240          */
1241         ath_hal_reset(ah, sc->sc_opmode,
1242             sc->sc_curchan != NULL ? sc->sc_curchan : ic->ic_curchan,
1243             AH_FALSE, &status);
1244         ath_reset_keycache(sc);
1245         if (sc->sc_resume_up) {
1246                 if (ic->ic_opmode == IEEE80211_M_STA) {
1247                         ath_init(sc);
1248                         /*
1249                          * Program the beacon registers using the last rx'd
1250                          * beacon frame and enable sync on the next beacon
1251                          * we see.  This should handle the case where we
1252                          * wakeup and find the same AP and also the case where
1253                          * we wakeup and need to roam.  For the latter we
1254                          * should get bmiss events that trigger a roam.
1255                          */
1256                         ath_beacon_config(sc, NULL);
1257                         sc->sc_syncbeacon = 1;
1258                 } else
1259                         ieee80211_resume_all(ic);
1260         }
1261         if (sc->sc_softled) {
1262                 ath_hal_gpioCfgOutput(ah, sc->sc_ledpin,
1263                     HAL_GPIO_MUX_MAC_NETWORK_LED);
1264                 ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
1265         }
1266 }
1267
1268 void
1269 ath_shutdown(struct ath_softc *sc)
1270 {
1271         struct ifnet *ifp = sc->sc_ifp;
1272
1273         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1274                 __func__, ifp->if_flags);
1275
1276         ath_stop(ifp);
1277         /* NB: no point powering down chip as we're about to reboot */
1278 }
1279
1280 /*
1281  * Interrupt handler.  Most of the actual processing is deferred.
1282  */
1283 void
1284 ath_intr(void *arg)
1285 {
1286         struct ath_softc *sc = arg;
1287         struct ifnet *ifp = sc->sc_ifp;
1288         struct ath_hal *ah = sc->sc_ah;
1289         HAL_INT status;
1290         HAL_INT ostatus;
1291
1292         if (sc->sc_invalid) {
1293                 /*
1294                  * The hardware is not ready/present, don't touch anything.
1295                  * Note this can happen early on if the IRQ is shared.
1296                  */
1297                 DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
1298                 return;
1299         }
1300
1301         if (!ath_hal_intrpend(ah))              /* shared irq, not for us */
1302                 return;
1303         if ((ifp->if_flags & IFF_UP) == 0 ||
1304             (ifp->if_flags & IFF_RUNNING) == 0) {
1305                 HAL_INT status;
1306
1307                 DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1308                         __func__, ifp->if_flags);
1309                 ath_hal_getisr(ah, &status);    /* clear ISR */
1310                 ath_hal_intrset(ah, 0);         /* disable further intr's */
1311                 return;
1312         }
1313         /*
1314          * Figure out the reason(s) for the interrupt.  Note
1315          * that the hal returns a pseudo-ISR that may include
1316          * bits we haven't explicitly enabled so we mask the
1317          * value to insure we only process bits we requested.
1318          */
1319         ath_hal_getisr(ah, &ostatus);           /* NB: clears ISR too */
1320         DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, ostatus);
1321         status = ostatus & sc->sc_imask;        /* discard unasked for bits */
1322         if (status & HAL_INT_FATAL) {
1323                 sc->sc_stats.ast_hardware++;
1324                 ath_hal_intrset(ah, 0);         /* disable intr's until reset */
1325                 ath_fatal_proc(sc, 0);
1326         } else {
1327                 if (status & HAL_INT_SWBA) {
1328                         /*
1329                          * Software beacon alert--time to send a beacon.
1330                          * Handle beacon transmission directly; deferring
1331                          * this is too slow to meet timing constraints
1332                          * under load.
1333                          */
1334 #ifdef IEEE80211_SUPPORT_TDMA
1335                         if (sc->sc_tdma) {
1336                                 if (sc->sc_tdmaswba == 0) {
1337                                         struct ieee80211com *ic = ifp->if_l2com;
1338                                         struct ieee80211vap *vap =
1339                                             TAILQ_FIRST(&ic->ic_vaps);
1340                                         ath_tdma_beacon_send(sc, vap);
1341                                         sc->sc_tdmaswba =
1342                                             vap->iv_tdma->tdma_bintval;
1343                                 } else
1344                                         sc->sc_tdmaswba--;
1345                         } else
1346 #endif
1347                         {
1348                                 ath_beacon_proc(sc, 0);
1349 #ifdef IEEE80211_SUPPORT_SUPERG
1350                                 /*
1351                                  * Schedule the rx taskq in case there's no
1352                                  * traffic so any frames held on the staging
1353                                  * queue are aged and potentially flushed.
1354                                  */
1355                                 taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1356 #endif
1357                         }
1358                 }
1359
1360                 /*
1361                  * NB: The hardware should re-read the link when the RXE
1362                  *     bit is written, but it doesn't work at least on
1363                  *     older chipsets.
1364                  */
1365                 if (status & HAL_INT_RXEOL) {
1366                         sc->sc_stats.ast_rxeol++;
1367                         sc->sc_rxlink = NULL;
1368                 }
1369
1370                 if (status & HAL_INT_TXURN) {
1371                         sc->sc_stats.ast_txurn++;
1372                         /* bump tx trigger level */
1373                         ath_hal_updatetxtriglevel(ah, AH_TRUE);
1374                 }
1375
1376                 if (status & HAL_INT_RX)
1377                         taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1378
1379                 if (status & HAL_INT_TX)
1380                         taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
1381
1382                 if (status & HAL_INT_BMISS) {
1383                         sc->sc_stats.ast_bmiss++;
1384                         taskqueue_enqueue(sc->sc_tq, &sc->sc_bmisstask);
1385                 }
1386
1387                 if (status & HAL_INT_MIB) {
1388                         sc->sc_stats.ast_mib++;
1389                         /*
1390                          * Disable interrupts until we service the MIB
1391                          * interrupt; otherwise it will continue to fire.
1392                          */
1393                         ath_hal_intrset(ah, 0);
1394                         /*
1395                          * Let the hal handle the event.  We assume it will
1396                          * clear whatever condition caused the interrupt.
1397                          */
1398                         ath_hal_mibevent(ah, &sc->sc_halstats);
1399                         ath_hal_intrset(ah, sc->sc_imask);
1400                 }
1401
1402                 if (status & HAL_INT_RXORN) {
1403                         /* NB: hal marks HAL_INT_FATAL when RXORN is fatal */
1404                         sc->sc_stats.ast_rxorn++;
1405                 }
1406         }
1407 }
1408
1409 static void
1410 ath_fatal_proc(void *arg, int pending)
1411 {
1412         struct ath_softc *sc = arg;
1413         struct ifnet *ifp = sc->sc_ifp;
1414         u_int32_t *state;
1415         u_int32_t len;
1416         void *sp;
1417
1418         if_printf(ifp, "hardware error; resetting\n");
1419         /*
1420          * Fatal errors are unrecoverable.  Typically these
1421          * are caused by DMA errors.  Collect h/w state from
1422          * the hal so we can diagnose what's going on.
1423          */
1424         if (ath_hal_getfatalstate(sc->sc_ah, &sp, &len)) {
1425                 KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
1426                 state = sp;
1427                 if_printf(ifp, "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n",
1428                     state[0], state[1] , state[2], state[3],
1429                     state[4], state[5]);
1430         }
1431         ath_reset(ifp);
1432 }
1433
1434 static void
1435 ath_bmiss_vap(struct ieee80211vap *vap)
1436 {
1437         /*
1438          * Workaround phantom bmiss interrupts by sanity-checking
1439          * the time of our last rx'd frame.  If it is within the
1440          * beacon miss interval then ignore the interrupt.  If it's
1441          * truly a bmiss we'll get another interrupt soon and that'll
1442          * be dispatched up for processing.  Note this applies only
1443          * for h/w beacon miss events.
1444          */
1445         if ((vap->iv_flags_ext & IEEE80211_FEXT_SWBMISS) == 0) {
1446                 struct ifnet *ifp = vap->iv_ic->ic_ifp;
1447                 struct ath_softc *sc = ifp->if_softc;
1448                 u_int64_t lastrx = sc->sc_lastrx;
1449                 u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
1450                 u_int bmisstimeout =
1451                         vap->iv_bmissthreshold * vap->iv_bss->ni_intval * 1024;
1452
1453                 DPRINTF(sc, ATH_DEBUG_BEACON,
1454                     "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
1455                     __func__, (unsigned long long) tsf,
1456                     (unsigned long long)(tsf - lastrx),
1457                     (unsigned long long) lastrx, bmisstimeout);
1458
1459                 if (tsf - lastrx <= bmisstimeout) {
1460                         sc->sc_stats.ast_bmiss_phantom++;
1461                         return;
1462                 }
1463         }
1464         ATH_VAP(vap)->av_bmiss(vap);
1465 }
1466
1467 static int
1468 ath_hal_gethangstate(struct ath_hal *ah, uint32_t mask, uint32_t *hangs)
1469 {
1470         uint32_t rsize;
1471         void *sp;
1472
1473         if (!ath_hal_getdiagstate(ah, 32, &mask, sizeof(mask), &sp, &rsize))
1474                 return 0;
1475         KASSERT(rsize == sizeof(uint32_t), ("resultsize %u", rsize));
1476         *hangs = *(uint32_t *)sp;
1477         return 1;
1478 }
1479
1480 static void
1481 ath_bmiss_task(void *arg, int pending)
1482 {
1483         struct ath_softc *sc = arg;
1484         struct ifnet *ifp = sc->sc_ifp;
1485         uint32_t hangs;
1486
1487         wlan_serialize_enter();
1488         DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
1489
1490         if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0) {
1491                 if_printf(ifp, "bb hang detected (0x%x), reseting\n", hangs); 
1492                 ath_reset(ifp);
1493         } else {
1494                 ieee80211_beacon_miss(ifp->if_l2com);
1495         }
1496         wlan_serialize_exit();
1497 }
1498
1499 /*
1500  * Handle TKIP MIC setup to deal hardware that doesn't do MIC
1501  * calcs together with WME.  If necessary disable the crypto
1502  * hardware and mark the 802.11 state so keys will be setup
1503  * with the MIC work done in software.
1504  */
1505 static void
1506 ath_settkipmic(struct ath_softc *sc)
1507 {
1508         struct ifnet *ifp = sc->sc_ifp;
1509         struct ieee80211com *ic = ifp->if_l2com;
1510
1511         if ((ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIP) && !sc->sc_wmetkipmic) {
1512                 if (ic->ic_flags & IEEE80211_F_WME) {
1513                         ath_hal_settkipmic(sc->sc_ah, AH_FALSE);
1514                         ic->ic_cryptocaps &= ~IEEE80211_CRYPTO_TKIPMIC;
1515                 } else {
1516                         ath_hal_settkipmic(sc->sc_ah, AH_TRUE);
1517                         ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
1518                 }
1519         }
1520 }
1521
1522 static void
1523 ath_init(void *arg)
1524 {
1525         struct ath_softc *sc = (struct ath_softc *) arg;
1526         struct ifnet *ifp = sc->sc_ifp;
1527         struct ieee80211com *ic = ifp->if_l2com;
1528         struct ath_hal *ah = sc->sc_ah;
1529         HAL_STATUS status;
1530
1531         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1532                 __func__, ifp->if_flags);
1533
1534         wlan_assert_serialized();
1535
1536         /*
1537          * Stop anything previously setup.  This is safe
1538          * whether this is the first time through or not.
1539          */
1540         ath_stop_locked(ifp);
1541
1542         /*
1543          * The basic interface to setting the hardware in a good
1544          * state is ``reset''.  On return the hardware is known to
1545          * be powered up and with interrupts disabled.  This must
1546          * be followed by initialization of the appropriate bits
1547          * and then setup of the interrupt mask.
1548          */
1549         ath_settkipmic(sc);
1550         if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_FALSE, &status)) {
1551                 if_printf(ifp, "unable to reset hardware; hal status %u\n",
1552                         status);
1553                 return;
1554         }
1555         ath_chan_change(sc, ic->ic_curchan);
1556
1557         /*
1558          * Likewise this is set during reset so update
1559          * state cached in the driver.
1560          */
1561         sc->sc_diversity = ath_hal_getdiversity(ah);
1562         sc->sc_lastlongcal = 0;
1563         sc->sc_resetcal = 1;
1564         sc->sc_lastcalreset = 0;
1565
1566         /*
1567          * Setup the hardware after reset: the key cache
1568          * is filled as needed and the receive engine is
1569          * set going.  Frame transmit is handled entirely
1570          * in the frame output path; there's nothing to do
1571          * here except setup the interrupt mask.
1572          */
1573         if (ath_startrecv(sc) != 0) {
1574                 if_printf(ifp, "unable to start recv logic\n");
1575                 return;
1576         }
1577
1578         /*
1579          * Enable interrupts.
1580          */
1581         sc->sc_imask = HAL_INT_RX | HAL_INT_TX
1582                   | HAL_INT_RXEOL | HAL_INT_RXORN
1583                   | HAL_INT_FATAL | HAL_INT_GLOBAL;
1584         /*
1585          * Enable MIB interrupts when there are hardware phy counters.
1586          * Note we only do this (at the moment) for station mode.
1587          */
1588         if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
1589                 sc->sc_imask |= HAL_INT_MIB;
1590
1591         ifp->if_flags |= IFF_RUNNING;
1592         callout_reset(&sc->sc_wd_ch, hz, ath_watchdog_callout, sc);
1593         ath_hal_intrset(ah, sc->sc_imask);
1594
1595
1596 #ifdef ATH_TX99_DIAG
1597         if (sc->sc_tx99 != NULL)
1598                 sc->sc_tx99->start(sc->sc_tx99);
1599         else
1600 #endif
1601         ieee80211_start_all(ic);                /* start all vap's */
1602 }
1603
1604 static void
1605 ath_stop_locked(struct ifnet *ifp)
1606 {
1607         struct ath_softc *sc = ifp->if_softc;
1608         struct ath_hal *ah = sc->sc_ah;
1609
1610         DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1611                 __func__, sc->sc_invalid, ifp->if_flags);
1612
1613         if (ifp->if_flags & IFF_RUNNING) {
1614                 /*
1615                  * Shutdown the hardware and driver:
1616                  *    reset 802.11 state machine
1617                  *    turn off timers
1618                  *    disable interrupts
1619                  *    turn off the radio
1620                  *    clear transmit machinery
1621                  *    clear receive machinery
1622                  *    drain and release tx queues
1623                  *    reclaim beacon resources
1624                  *    power down hardware
1625                  *
1626                  * Note that some of this work is not possible if the
1627                  * hardware is gone (invalid).
1628                  */
1629 #ifdef ATH_TX99_DIAG
1630                 if (sc->sc_tx99 != NULL)
1631                         sc->sc_tx99->stop(sc->sc_tx99);
1632 #endif
1633                 callout_stop(&sc->sc_wd_ch);
1634                 sc->sc_wd_timer = 0;
1635                 ifp->if_flags &= ~IFF_RUNNING;
1636                 if (!sc->sc_invalid) {
1637                         if (sc->sc_softled) {
1638                                 callout_stop(&sc->sc_ledtimer);
1639                                 ath_hal_gpioset(ah, sc->sc_ledpin,
1640                                         !sc->sc_ledon);
1641                                 sc->sc_blinking = 0;
1642                         }
1643                         ath_hal_intrset(ah, 0);
1644                 }
1645                 ath_draintxq(sc);
1646                 if (!sc->sc_invalid) {
1647                         ath_stoprecv(sc);
1648                         ath_hal_phydisable(ah);
1649                 } else
1650                         sc->sc_rxlink = NULL;
1651                 ath_beacon_free(sc);    /* XXX not needed */
1652         }
1653 }
1654
1655 static void
1656 ath_stop(struct ifnet *ifp)
1657 {
1658         struct ath_softc *sc __unused = ifp->if_softc;
1659
1660         ath_stop_locked(ifp);
1661 }
1662
1663 /*
1664  * Reset the hardware w/o losing operational state.  This is
1665  * basically a more efficient way of doing ath_stop, ath_init,
1666  * followed by state transitions to the current 802.11
1667  * operational state.  Used to recover from various errors and
1668  * to reset or reload hardware state.
1669  */
1670 static int
1671 ath_reset(struct ifnet *ifp)
1672 {
1673         struct ath_softc *sc = ifp->if_softc;
1674         struct ieee80211com *ic = ifp->if_l2com;
1675         struct ath_hal *ah = sc->sc_ah;
1676         HAL_STATUS status;
1677
1678         ath_hal_intrset(ah, 0);         /* disable interrupts */
1679         ath_draintxq(sc);               /* stop xmit side */
1680         ath_stoprecv(sc);               /* stop recv side */
1681         ath_settkipmic(sc);             /* configure TKIP MIC handling */
1682         /* NB: indicate channel change so we do a full reset */
1683         if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_TRUE, &status))
1684                 if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
1685                         __func__, status);
1686         sc->sc_diversity = ath_hal_getdiversity(ah);
1687         if (ath_startrecv(sc) != 0)     /* restart recv */
1688                 if_printf(ifp, "%s: unable to start recv logic\n", __func__);
1689         /*
1690          * We may be doing a reset in response to an ioctl
1691          * that changes the channel so update any state that
1692          * might change as a result.
1693          */
1694         ath_chan_change(sc, ic->ic_curchan);
1695         if (sc->sc_beacons) {           /* restart beacons */
1696 #ifdef IEEE80211_SUPPORT_TDMA
1697                 if (sc->sc_tdma)
1698                         ath_tdma_config(sc, NULL);
1699                 else
1700 #endif
1701                         ath_beacon_config(sc, NULL);
1702         }
1703         ath_hal_intrset(ah, sc->sc_imask);
1704
1705         ath_start(ifp);                 /* restart xmit */
1706         return 0;
1707 }
1708
1709 static int
1710 ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
1711 {
1712         struct ieee80211com *ic = vap->iv_ic;
1713         struct ifnet *ifp = ic->ic_ifp;
1714         struct ath_softc *sc = ifp->if_softc;
1715         struct ath_hal *ah = sc->sc_ah;
1716
1717         switch (cmd) {
1718         case IEEE80211_IOC_TXPOWER:
1719                 /*
1720                  * If per-packet TPC is enabled, then we have nothing
1721                  * to do; otherwise we need to force the global limit.
1722                  * All this can happen directly; no need to reset.
1723                  */
1724                 if (!ath_hal_gettpc(ah))
1725                         ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
1726                 return 0;
1727         }
1728         return ath_reset(ifp);
1729 }
1730
1731 static struct ath_buf *
1732 _ath_getbuf_locked(struct ath_softc *sc)
1733 {
1734         struct ath_buf *bf;
1735
1736         bf = STAILQ_FIRST(&sc->sc_txbuf);
1737         if (bf != NULL && (bf->bf_flags & ATH_BUF_BUSY) == 0)
1738                 STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
1739         else
1740                 bf = NULL;
1741         if (bf == NULL) {
1742                 kprintf("ath: ran out of descriptors\n");
1743                 DPRINTF(sc, ATH_DEBUG_XMIT, "%s: %s\n", __func__,
1744                     STAILQ_FIRST(&sc->sc_txbuf) == NULL ?
1745                         "out of xmit buffers" : "xmit buffer busy");
1746         }
1747         return bf;
1748 }
1749
1750 static struct ath_buf *
1751 ath_getbuf(struct ath_softc *sc)
1752 {
1753         struct ath_buf *bf;
1754
1755         bf = _ath_getbuf_locked(sc);
1756         if (bf == NULL) {
1757                 struct ifnet *ifp = sc->sc_ifp;
1758
1759                 DPRINTF(sc, ATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
1760                 sc->sc_stats.ast_tx_qstop++;
1761                 ifp->if_flags |= IFF_OACTIVE;
1762         }
1763         return bf;
1764 }
1765
1766 /*
1767  * Cleanup driver resources when we run out of buffers
1768  * while processing fragments; return the tx buffers
1769  * allocated and drop node references.
1770  */
1771 static void
1772 ath_txfrag_cleanup(struct ath_softc *sc,
1773         ath_bufhead *frags, struct ieee80211_node *ni)
1774 {
1775         struct ath_buf *bf, *next;
1776
1777         STAILQ_FOREACH_MUTABLE(bf, frags, bf_list, next) {
1778                 /* NB: bf assumed clean */
1779                 STAILQ_REMOVE_HEAD(frags, bf_list);
1780                 STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1781                 ieee80211_node_decref(ni);
1782         }
1783 }
1784
1785 /*
1786  * Setup xmit of a fragmented frame.  Allocate a buffer
1787  * for each frag and bump the node reference count to
1788  * reflect the held reference to be setup by ath_tx_start.
1789  */
1790 static int
1791 ath_txfrag_setup(struct ath_softc *sc, ath_bufhead *frags,
1792         struct mbuf *m0, struct ieee80211_node *ni)
1793 {
1794         struct mbuf *m;
1795         struct ath_buf *bf;
1796
1797         for (m = m0->m_nextpkt; m != NULL; m = m->m_nextpkt) {
1798                 bf = _ath_getbuf_locked(sc);
1799                 if (bf == NULL) {       /* out of buffers, cleanup */
1800                         ath_txfrag_cleanup(sc, frags, ni);
1801                         break;
1802                 }
1803                 ieee80211_node_incref(ni);
1804                 STAILQ_INSERT_TAIL(frags, bf, bf_list);
1805         }
1806
1807         return !STAILQ_EMPTY(frags);
1808 }
1809
1810 static void
1811 ath_start(struct ifnet *ifp)
1812 {
1813         struct ath_softc *sc = ifp->if_softc;
1814         struct ieee80211_node *ni;
1815         struct ath_buf *bf;
1816         struct mbuf *m, *next;
1817         ath_bufhead frags;
1818
1819         wlan_assert_serialized();
1820
1821         if ((ifp->if_flags & IFF_RUNNING) == 0 || sc->sc_invalid) {
1822                 ifq_purge(&ifp->if_snd);
1823                 return;
1824         }
1825         for (;;) {
1826                 /*
1827                  * Grab a TX buffer and associated resources.
1828                  */
1829                 bf = ath_getbuf(sc);
1830                 if (bf == NULL)
1831                         break;
1832
1833                 IF_DEQUEUE(&ifp->if_snd, m);
1834                 if (m == NULL) {
1835                         STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1836                         break;
1837                 }
1838                 ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1839                 /*
1840                  * Check for fragmentation.  If this frame
1841                  * has been broken up verify we have enough
1842                  * buffers to send all the fragments so all
1843                  * go out or none...
1844                  */
1845                 STAILQ_INIT(&frags);
1846                 if ((m->m_flags & M_FRAG) && 
1847                     !ath_txfrag_setup(sc, &frags, m, ni)) {
1848                         DPRINTF(sc, ATH_DEBUG_XMIT,
1849                             "%s: out of txfrag buffers\n", __func__);
1850                         sc->sc_stats.ast_tx_nofrag++;
1851                         ifp->if_oerrors++;
1852                         ath_freetx(m);
1853                         goto bad;
1854                 }
1855                 ifp->if_opackets++;
1856         nextfrag:
1857                 /*
1858                  * Pass the frame to the h/w for transmission.
1859                  * Fragmented frames have each frag chained together
1860                  * with m_nextpkt.  We know there are sufficient ath_buf's
1861                  * to send all the frags because of work done by
1862                  * ath_txfrag_setup.  We leave m_nextpkt set while
1863                  * calling ath_tx_start so it can use it to extend the
1864                  * the tx duration to cover the subsequent frag and
1865                  * so it can reclaim all the mbufs in case of an error;
1866                  * ath_tx_start clears m_nextpkt once it commits to
1867                  * handing the frame to the hardware.
1868                  */
1869                 next = m->m_nextpkt;
1870                 if (ath_tx_start(sc, ni, bf, m)) {
1871         bad:
1872                         ifp->if_oerrors++;
1873         reclaim:
1874                         bf->bf_m = NULL;
1875                         bf->bf_node = NULL;
1876                         STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1877                         ath_txfrag_cleanup(sc, &frags, ni);
1878                         if (ni != NULL)
1879                                 ieee80211_free_node(ni);
1880                         continue;
1881                 }
1882                 if (next != NULL) {
1883                         /*
1884                          * Beware of state changing between frags.
1885                          * XXX check sta power-save state?
1886                          */
1887                         if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
1888                                 DPRINTF(sc, ATH_DEBUG_XMIT,
1889                                     "%s: flush fragmented packet, state %s\n",
1890                                     __func__,
1891                                     ieee80211_state_name[ni->ni_vap->iv_state]);
1892                                 ath_freetx(next);
1893                                 goto reclaim;
1894                         }
1895                         m = next;
1896                         bf = STAILQ_FIRST(&frags);
1897                         KASSERT(bf != NULL, ("no buf for txfrag"));
1898                         STAILQ_REMOVE_HEAD(&frags, bf_list);
1899                         goto nextfrag;
1900                 }
1901
1902                 sc->sc_wd_timer = 5;
1903         }
1904 }
1905
1906 static int
1907 ath_media_change(struct ifnet *ifp)
1908 {
1909         int error = ieee80211_media_change(ifp);
1910         /* NB: only the fixed rate can change and that doesn't need a reset */
1911         return (error == ENETRESET ? 0 : error);
1912 }
1913
1914 #ifdef ATH_DEBUG
1915 static void
1916 ath_keyprint(struct ath_softc *sc, const char *tag, u_int ix,
1917         const HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1918 {
1919         static const char *ciphers[] = {
1920                 "WEP",
1921                 "AES-OCB",
1922                 "AES-CCM",
1923                 "CKIP",
1924                 "TKIP",
1925                 "CLR",
1926         };
1927         int i, n;
1928
1929         kprintf("%s: [%02u] %-7s ", tag, ix, ciphers[hk->kv_type]);
1930         for (i = 0, n = hk->kv_len; i < n; i++)
1931                 kprintf("%02x", hk->kv_val[i]);
1932         kprintf(" mac %6D", mac, ":");
1933         if (hk->kv_type == HAL_CIPHER_TKIP) {
1934                 kprintf(" %s ", sc->sc_splitmic ? "mic" : "rxmic");
1935                 for (i = 0; i < sizeof(hk->kv_mic); i++)
1936                         kprintf("%02x", hk->kv_mic[i]);
1937                 if (!sc->sc_splitmic) {
1938                         kprintf(" txmic ");
1939                         for (i = 0; i < sizeof(hk->kv_txmic); i++)
1940                                 kprintf("%02x", hk->kv_txmic[i]);
1941                 }
1942         }
1943         kprintf("\n");
1944 }
1945 #endif
1946
1947 /*
1948  * Set a TKIP key into the hardware.  This handles the
1949  * potential distribution of key state to multiple key
1950  * cache slots for TKIP.
1951  */
1952 static int
1953 ath_keyset_tkip(struct ath_softc *sc, const struct ieee80211_key *k,
1954         HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1955 {
1956 #define IEEE80211_KEY_XR        (IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV)
1957         static const u_int8_t zerobssid[IEEE80211_ADDR_LEN];
1958         struct ath_hal *ah = sc->sc_ah;
1959
1960         KASSERT(k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP,
1961                 ("got a non-TKIP key, cipher %u", k->wk_cipher->ic_cipher));
1962         if ((k->wk_flags & IEEE80211_KEY_XR) == IEEE80211_KEY_XR) {
1963                 if (sc->sc_splitmic) {
1964                         /*
1965                          * TX key goes at first index, RX key at the rx index.
1966                          * The hal handles the MIC keys at index+64.
1967                          */
1968                         memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_mic));
1969                         KEYPRINTF(sc, k->wk_keyix, hk, zerobssid);
1970                         if (!ath_hal_keyset(ah, k->wk_keyix, hk, zerobssid))
1971                                 return 0;
1972
1973                         memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1974                         KEYPRINTF(sc, k->wk_keyix+32, hk, mac);
1975                         /* XXX delete tx key on failure? */
1976                         return ath_hal_keyset(ah, k->wk_keyix+32, hk, mac);
1977                 } else {
1978                         /*
1979                          * Room for both TX+RX MIC keys in one key cache
1980                          * slot, just set key at the first index; the hal
1981                          * will handle the rest.
1982                          */
1983                         memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1984                         memcpy(hk->kv_txmic, k->wk_txmic, sizeof(hk->kv_txmic));
1985                         KEYPRINTF(sc, k->wk_keyix, hk, mac);
1986                         return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1987                 }
1988         } else if (k->wk_flags & IEEE80211_KEY_XMIT) {
1989                 if (sc->sc_splitmic) {
1990                         /*
1991                          * NB: must pass MIC key in expected location when
1992                          * the keycache only holds one MIC key per entry.
1993                          */
1994                         memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_txmic));
1995                 } else
1996                         memcpy(hk->kv_txmic, k->wk_txmic, sizeof(hk->kv_txmic));
1997                 KEYPRINTF(sc, k->wk_keyix, hk, mac);
1998                 return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1999         } else if (k->wk_flags & IEEE80211_KEY_RECV) {
2000                 memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
2001                 KEYPRINTF(sc, k->wk_keyix, hk, mac);
2002                 return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
2003         }
2004         return 0;
2005 #undef IEEE80211_KEY_XR
2006 }
2007
2008 /*
2009  * Set a net80211 key into the hardware.  This handles the
2010  * potential distribution of key state to multiple key
2011  * cache slots for TKIP with hardware MIC support.
2012  */
2013 static int
2014 ath_keyset(struct ath_softc *sc, const struct ieee80211_key *k,
2015         struct ieee80211_node *bss)
2016 {
2017         static const u_int8_t ciphermap[] = {
2018                 HAL_CIPHER_WEP,         /* IEEE80211_CIPHER_WEP */
2019                 HAL_CIPHER_TKIP,        /* IEEE80211_CIPHER_TKIP */
2020                 HAL_CIPHER_AES_OCB,     /* IEEE80211_CIPHER_AES_OCB */
2021                 HAL_CIPHER_AES_CCM,     /* IEEE80211_CIPHER_AES_CCM */
2022                 (u_int8_t) -1,          /* 4 is not allocated */
2023                 HAL_CIPHER_CKIP,        /* IEEE80211_CIPHER_CKIP */
2024                 HAL_CIPHER_CLR,         /* IEEE80211_CIPHER_NONE */
2025         };
2026         struct ath_hal *ah = sc->sc_ah;
2027         const struct ieee80211_cipher *cip = k->wk_cipher;
2028         u_int8_t gmac[IEEE80211_ADDR_LEN];
2029         const u_int8_t *mac;
2030         HAL_KEYVAL hk;
2031
2032         memset(&hk, 0, sizeof(hk));
2033         /*
2034          * Software crypto uses a "clear key" so non-crypto
2035          * state kept in the key cache are maintained and
2036          * so that rx frames have an entry to match.
2037          */
2038         if ((k->wk_flags & IEEE80211_KEY_SWCRYPT) == 0) {
2039                 KASSERT(cip->ic_cipher < NELEM(ciphermap),
2040                         ("invalid cipher type %u", cip->ic_cipher));
2041                 hk.kv_type = ciphermap[cip->ic_cipher];
2042                 hk.kv_len = k->wk_keylen;
2043                 memcpy(hk.kv_val, k->wk_key, k->wk_keylen);
2044         } else
2045                 hk.kv_type = HAL_CIPHER_CLR;
2046
2047         if ((k->wk_flags & IEEE80211_KEY_GROUP) && sc->sc_mcastkey) {
2048                 /*
2049                  * Group keys on hardware that supports multicast frame
2050                  * key search use a MAC that is the sender's address with
2051                  * the high bit set instead of the app-specified address.
2052                  */
2053                 IEEE80211_ADDR_COPY(gmac, bss->ni_macaddr);
2054                 gmac[0] |= 0x80;
2055                 mac = gmac;
2056         } else
2057                 mac = k->wk_macaddr;
2058
2059         if (hk.kv_type == HAL_CIPHER_TKIP &&
2060             (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2061                 return ath_keyset_tkip(sc, k, &hk, mac);
2062         } else {
2063                 KEYPRINTF(sc, k->wk_keyix, &hk, mac);
2064                 return ath_hal_keyset(ah, k->wk_keyix, &hk, mac);
2065         }
2066 }
2067
2068 /*
2069  * Allocate tx/rx key slots for TKIP.  We allocate two slots for
2070  * each key, one for decrypt/encrypt and the other for the MIC.
2071  */
2072 static u_int16_t
2073 key_alloc_2pair(struct ath_softc *sc,
2074         ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2075 {
2076         u_int i, keyix;
2077
2078         KASSERT(sc->sc_splitmic, ("key cache !split"));
2079         /* XXX could optimize */
2080         for (i = 0; i < NELEM(sc->sc_keymap)/4; i++) {
2081                 u_int8_t b = sc->sc_keymap[i];
2082                 if (b != 0xff) {
2083                         /*
2084                          * One or more slots in this byte are free.
2085                          */
2086                         keyix = i*NBBY;
2087                         while (b & 1) {
2088                 again:
2089                                 keyix++;
2090                                 b >>= 1;
2091                         }
2092                         /* XXX IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV */
2093                         if (isset(sc->sc_keymap, keyix+32) ||
2094                             isset(sc->sc_keymap, keyix+64) ||
2095                             isset(sc->sc_keymap, keyix+32+64)) {
2096                                 /* full pair unavailable */
2097                                 /* XXX statistic */
2098                                 if (keyix == (i+1)*NBBY) {
2099                                         /* no slots were appropriate, advance */
2100                                         continue;
2101                                 }
2102                                 goto again;
2103                         }
2104                         setbit(sc->sc_keymap, keyix);
2105                         setbit(sc->sc_keymap, keyix+64);
2106                         setbit(sc->sc_keymap, keyix+32);
2107                         setbit(sc->sc_keymap, keyix+32+64);
2108                         DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2109                                 "%s: key pair %u,%u %u,%u\n",
2110                                 __func__, keyix, keyix+64,
2111                                 keyix+32, keyix+32+64);
2112                         *txkeyix = keyix;
2113                         *rxkeyix = keyix+32;
2114                         return 1;
2115                 }
2116         }
2117         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
2118         return 0;
2119 }
2120
2121 /*
2122  * Allocate tx/rx key slots for TKIP.  We allocate two slots for
2123  * each key, one for decrypt/encrypt and the other for the MIC.
2124  */
2125 static u_int16_t
2126 key_alloc_pair(struct ath_softc *sc,
2127         ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2128 {
2129         u_int i, keyix;
2130
2131         KASSERT(!sc->sc_splitmic, ("key cache split"));
2132         /* XXX could optimize */
2133         for (i = 0; i < NELEM(sc->sc_keymap)/4; i++) {
2134                 u_int8_t b = sc->sc_keymap[i];
2135                 if (b != 0xff) {
2136                         /*
2137                          * One or more slots in this byte are free.
2138                          */
2139                         keyix = i*NBBY;
2140                         while (b & 1) {
2141                 again:
2142                                 keyix++;
2143                                 b >>= 1;
2144                         }
2145                         if (isset(sc->sc_keymap, keyix+64)) {
2146                                 /* full pair unavailable */
2147                                 /* XXX statistic */
2148                                 if (keyix == (i+1)*NBBY) {
2149                                         /* no slots were appropriate, advance */
2150                                         continue;
2151                                 }
2152                                 goto again;
2153                         }
2154                         setbit(sc->sc_keymap, keyix);
2155                         setbit(sc->sc_keymap, keyix+64);
2156                         DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2157                                 "%s: key pair %u,%u\n",
2158                                 __func__, keyix, keyix+64);
2159                         *txkeyix = *rxkeyix = keyix;
2160                         return 1;
2161                 }
2162         }
2163         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
2164         return 0;
2165 }
2166
2167 /*
2168  * Allocate a single key cache slot.
2169  */
2170 static int
2171 key_alloc_single(struct ath_softc *sc,
2172         ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2173 {
2174         u_int i, keyix;
2175
2176         /* XXX try i,i+32,i+64,i+32+64 to minimize key pair conflicts */
2177         for (i = 0; i < NELEM(sc->sc_keymap); i++) {
2178                 u_int8_t b = sc->sc_keymap[i];
2179                 if (b != 0xff) {
2180                         /*
2181                          * One or more slots are free.
2182                          */
2183                         keyix = i*NBBY;
2184                         while (b & 1)
2185                                 keyix++, b >>= 1;
2186                         setbit(sc->sc_keymap, keyix);
2187                         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: key %u\n",
2188                                 __func__, keyix);
2189                         *txkeyix = *rxkeyix = keyix;
2190                         return 1;
2191                 }
2192         }
2193         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of space\n", __func__);
2194         return 0;
2195 }
2196
2197 /*
2198  * Allocate one or more key cache slots for a uniacst key.  The
2199  * key itself is needed only to identify the cipher.  For hardware
2200  * TKIP with split cipher+MIC keys we allocate two key cache slot
2201  * pairs so that we can setup separate TX and RX MIC keys.  Note
2202  * that the MIC key for a TKIP key at slot i is assumed by the
2203  * hardware to be at slot i+64.  This limits TKIP keys to the first
2204  * 64 entries.
2205  */
2206 static int
2207 ath_key_alloc(struct ieee80211vap *vap, struct ieee80211_key *k,
2208         ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
2209 {
2210         struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2211
2212         /*
2213          * Group key allocation must be handled specially for
2214          * parts that do not support multicast key cache search
2215          * functionality.  For those parts the key id must match
2216          * the h/w key index so lookups find the right key.  On
2217          * parts w/ the key search facility we install the sender's
2218          * mac address (with the high bit set) and let the hardware
2219          * find the key w/o using the key id.  This is preferred as
2220          * it permits us to support multiple users for adhoc and/or
2221          * multi-station operation.
2222          */
2223         if (k->wk_keyix != IEEE80211_KEYIX_NONE) {
2224                 /*
2225                  * Only global keys should have key index assigned.
2226                  */
2227                 if (!(&vap->iv_nw_keys[0] <= k &&
2228                       k < &vap->iv_nw_keys[IEEE80211_WEP_NKID])) {
2229                         /* should not happen */
2230                         DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2231                                 "%s: bogus group key\n", __func__);
2232                         return 0;
2233                 }
2234                 if (vap->iv_opmode != IEEE80211_M_HOSTAP ||
2235                     !(k->wk_flags & IEEE80211_KEY_GROUP) ||
2236                     !sc->sc_mcastkey) {
2237                         /*
2238                          * XXX we pre-allocate the global keys so
2239                          * have no way to check if they've already
2240                          * been allocated.
2241                          */
2242                         *keyix = *rxkeyix = k - vap->iv_nw_keys;
2243                         return 1;
2244                 }
2245                 /*
2246                  * Group key and device supports multicast key search.
2247                  */
2248                 k->wk_keyix = IEEE80211_KEYIX_NONE;
2249         }
2250
2251         /*
2252          * We allocate two pair for TKIP when using the h/w to do
2253          * the MIC.  For everything else, including software crypto,
2254          * we allocate a single entry.  Note that s/w crypto requires
2255          * a pass-through slot on the 5211 and 5212.  The 5210 does
2256          * not support pass-through cache entries and we map all
2257          * those requests to slot 0.
2258          */
2259         if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
2260                 return key_alloc_single(sc, keyix, rxkeyix);
2261         } else if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP &&
2262             (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2263                 if (sc->sc_splitmic)
2264                         return key_alloc_2pair(sc, keyix, rxkeyix);
2265                 else
2266                         return key_alloc_pair(sc, keyix, rxkeyix);
2267         } else {
2268                 return key_alloc_single(sc, keyix, rxkeyix);
2269         }
2270 }
2271
2272 /*
2273  * Delete an entry in the key cache allocated by ath_key_alloc.
2274  */
2275 static int
2276 ath_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
2277 {
2278         struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2279         struct ath_hal *ah = sc->sc_ah;
2280         const struct ieee80211_cipher *cip = k->wk_cipher;
2281         u_int keyix = k->wk_keyix;
2282
2283         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: delete key %u\n", __func__, keyix);
2284
2285         ath_hal_keyreset(ah, keyix);
2286         /*
2287          * Handle split tx/rx keying required for TKIP with h/w MIC.
2288          */
2289         if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
2290             (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic)
2291                 ath_hal_keyreset(ah, keyix+32);         /* RX key */
2292         if (keyix >= IEEE80211_WEP_NKID) {
2293                 /*
2294                  * Don't touch keymap entries for global keys so
2295                  * they are never considered for dynamic allocation.
2296                  */
2297                 clrbit(sc->sc_keymap, keyix);
2298                 if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
2299                     (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2300                         clrbit(sc->sc_keymap, keyix+64);        /* TX key MIC */
2301                         if (sc->sc_splitmic) {
2302                                 /* +32 for RX key, +32+64 for RX key MIC */
2303                                 clrbit(sc->sc_keymap, keyix+32);
2304                                 clrbit(sc->sc_keymap, keyix+32+64);
2305                         }
2306                 }
2307         }
2308         return 1;
2309 }
2310
2311 /*
2312  * Set the key cache contents for the specified key.  Key cache
2313  * slot(s) must already have been allocated by ath_key_alloc.
2314  */
2315 static int
2316 ath_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k,
2317         const u_int8_t mac[IEEE80211_ADDR_LEN])
2318 {
2319         struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2320
2321         return ath_keyset(sc, k, vap->iv_bss);
2322 }
2323
2324 /*
2325  * Block/unblock tx+rx processing while a key change is done.
2326  * We assume the caller serializes key management operations
2327  * so we only need to worry about synchronization with other
2328  * uses that originate in the driver.
2329  */
2330 static void
2331 ath_key_update_begin(struct ieee80211vap *vap)
2332 {
2333         struct ifnet *ifp = vap->iv_ic->ic_ifp;
2334         struct ath_softc *sc = ifp->if_softc;
2335
2336         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2337         taskqueue_block(sc->sc_tq);
2338 }
2339
2340 static void
2341 ath_key_update_end(struct ieee80211vap *vap)
2342 {
2343         struct ifnet *ifp = vap->iv_ic->ic_ifp;
2344         struct ath_softc *sc = ifp->if_softc;
2345
2346         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2347         taskqueue_unblock(sc->sc_tq);
2348 }
2349
2350 /*
2351  * Calculate the receive filter according to the
2352  * operating mode and state:
2353  *
2354  * o always accept unicast, broadcast, and multicast traffic
2355  * o accept PHY error frames when hardware doesn't have MIB support
2356  *   to count and we need them for ANI (sta mode only until recently)
2357  *   and we are not scanning (ANI is disabled)
2358  *   NB: older hal's add rx filter bits out of sight and we need to
2359  *       blindly preserve them
2360  * o probe request frames are accepted only when operating in
2361  *   hostap, adhoc, mesh, or monitor modes
2362  * o enable promiscuous mode
2363  *   - when in monitor mode
2364  *   - if interface marked PROMISC (assumes bridge setting is filtered)
2365  * o accept beacons:
2366  *   - when operating in station mode for collecting rssi data when
2367  *     the station is otherwise quiet, or
2368  *   - when operating in adhoc mode so the 802.11 layer creates
2369  *     node table entries for peers,
2370  *   - when scanning
2371  *   - when doing s/w beacon miss (e.g. for ap+sta)
2372  *   - when operating in ap mode in 11g to detect overlapping bss that
2373  *     require protection
2374  *   - when operating in mesh mode to detect neighbors
2375  * o accept control frames:
2376  *   - when in monitor mode
2377  * XXX BAR frames for 11n
2378  * XXX HT protection for 11n
2379  */
2380 static u_int32_t
2381 ath_calcrxfilter(struct ath_softc *sc)
2382 {
2383         struct ifnet *ifp = sc->sc_ifp;
2384         struct ieee80211com *ic = ifp->if_l2com;
2385         u_int32_t rfilt;
2386
2387         rfilt = HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
2388         if (!sc->sc_needmib && !sc->sc_scanning)
2389                 rfilt |= HAL_RX_FILTER_PHYERR;
2390         if (ic->ic_opmode != IEEE80211_M_STA)
2391                 rfilt |= HAL_RX_FILTER_PROBEREQ;
2392         /* XXX ic->ic_monvaps != 0? */
2393         if (ic->ic_opmode == IEEE80211_M_MONITOR || (ifp->if_flags & IFF_PROMISC))
2394                 rfilt |= HAL_RX_FILTER_PROM;
2395         if (ic->ic_opmode == IEEE80211_M_STA ||
2396             ic->ic_opmode == IEEE80211_M_IBSS ||
2397             sc->sc_swbmiss || sc->sc_scanning)
2398                 rfilt |= HAL_RX_FILTER_BEACON;
2399         /*
2400          * NB: We don't recalculate the rx filter when
2401          * ic_protmode changes; otherwise we could do
2402          * this only when ic_protmode != NONE.
2403          */
2404         if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
2405             IEEE80211_IS_CHAN_ANYG(ic->ic_curchan))
2406                 rfilt |= HAL_RX_FILTER_BEACON;
2407         if (sc->sc_nmeshvaps) {
2408                 rfilt |= HAL_RX_FILTER_BEACON;
2409                 if (sc->sc_hasbmatch)
2410                         rfilt |= HAL_RX_FILTER_BSSID;
2411                 else
2412                         rfilt |= HAL_RX_FILTER_PROM;
2413         }
2414         if (ic->ic_opmode == IEEE80211_M_MONITOR)
2415                 rfilt |= HAL_RX_FILTER_CONTROL;
2416         DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, %s if_flags 0x%x\n",
2417             __func__, rfilt, ieee80211_opmode_name[ic->ic_opmode], ifp->if_flags);
2418         return rfilt;
2419 }
2420
2421 static void
2422 ath_update_promisc(struct ifnet *ifp)
2423 {
2424         struct ath_softc *sc = ifp->if_softc;
2425         u_int32_t rfilt;
2426
2427         /* configure rx filter */
2428         rfilt = ath_calcrxfilter(sc);
2429         ath_hal_setrxfilter(sc->sc_ah, rfilt);
2430
2431         DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
2432 }
2433
2434 static void
2435 ath_update_mcast(struct ifnet *ifp)
2436 {
2437         struct ath_softc *sc = ifp->if_softc;
2438         u_int32_t mfilt[2];
2439
2440         /* calculate and install multicast filter */
2441         if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
2442                 struct ifmultiaddr *ifma;
2443                 /*
2444                  * Merge multicast addresses to form the hardware filter.
2445                  */
2446                 mfilt[0] = mfilt[1] = 0;
2447 #ifdef __FreeBSD__
2448                 if_maddr_rlock(ifp);    /* XXX need some fiddling to remove? */
2449 #endif
2450                 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2451                         caddr_t dl;
2452                         u_int32_t val;
2453                         u_int8_t pos;
2454
2455                         /* calculate XOR of eight 6bit values */
2456                         dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
2457                         val = LE_READ_4(dl + 0);
2458                         pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2459                         val = LE_READ_4(dl + 3);
2460                         pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2461                         pos &= 0x3f;
2462                         mfilt[pos / 32] |= (1 << (pos % 32));
2463                 }
2464 #ifdef __FreeBSD__
2465                 if_maddr_runlock(ifp);
2466 #endif
2467         } else
2468                 mfilt[0] = mfilt[1] = ~0;
2469         ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
2470         DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
2471                 __func__, mfilt[0], mfilt[1]);
2472 }
2473
2474 static void
2475 ath_mode_init(struct ath_softc *sc)
2476 {
2477         struct ifnet *ifp = sc->sc_ifp;
2478         struct ath_hal *ah = sc->sc_ah;
2479         u_int32_t rfilt;
2480
2481         /* configure rx filter */
2482         rfilt = ath_calcrxfilter(sc);
2483         ath_hal_setrxfilter(ah, rfilt);
2484
2485         /* configure operational mode */
2486         ath_hal_setopmode(ah);
2487
2488         /* handle any link-level address change */
2489         ath_hal_setmac(ah, IF_LLADDR(ifp));
2490
2491         /* calculate and install multicast filter */
2492         ath_update_mcast(ifp);
2493 }
2494
2495 /*
2496  * Set the slot time based on the current setting.
2497  */
2498 static void
2499 ath_setslottime(struct ath_softc *sc)
2500 {
2501         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2502         struct ath_hal *ah = sc->sc_ah;
2503         u_int usec;
2504
2505         if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
2506                 usec = 13;
2507         else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
2508                 usec = 21;
2509         else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
2510                 /* honor short/long slot time only in 11g */
2511                 /* XXX shouldn't honor on pure g or turbo g channel */
2512                 if (ic->ic_flags & IEEE80211_F_SHSLOT)
2513                         usec = HAL_SLOT_TIME_9;
2514                 else
2515                         usec = HAL_SLOT_TIME_20;
2516         } else
2517                 usec = HAL_SLOT_TIME_9;
2518
2519         DPRINTF(sc, ATH_DEBUG_RESET,
2520             "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
2521             __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
2522             ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
2523
2524         ath_hal_setslottime(ah, usec);
2525         sc->sc_updateslot = OK;
2526 }
2527
2528 /*
2529  * Callback from the 802.11 layer to update the
2530  * slot time based on the current setting.
2531  */
2532 static void
2533 ath_updateslot(struct ifnet *ifp)
2534 {
2535         struct ath_softc *sc = ifp->if_softc;
2536         struct ieee80211com *ic = ifp->if_l2com;
2537
2538         /*
2539          * When not coordinating the BSS, change the hardware
2540          * immediately.  For other operation we defer the change
2541          * until beacon updates have propagated to the stations.
2542          */
2543         if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2544             ic->ic_opmode == IEEE80211_M_MBSS)
2545                 sc->sc_updateslot = UPDATE;
2546         else
2547                 ath_setslottime(sc);
2548 }
2549
2550 /*
2551  * Setup a h/w transmit queue for beacons.
2552  */
2553 static int
2554 ath_beaconq_setup(struct ath_hal *ah)
2555 {
2556         HAL_TXQ_INFO qi;
2557
2558         memset(&qi, 0, sizeof(qi));
2559         qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
2560         qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
2561         qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
2562         /* NB: for dynamic turbo, don't enable any other interrupts */
2563         qi.tqi_qflags = HAL_TXQ_TXDESCINT_ENABLE;
2564         return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
2565 }
2566
2567 /*
2568  * Setup the transmit queue parameters for the beacon queue.
2569  */
2570 static int
2571 ath_beaconq_config(struct ath_softc *sc)
2572 {
2573 #define ATH_EXPONENT_TO_VALUE(v)        ((1<<(v))-1)
2574         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2575         struct ath_hal *ah = sc->sc_ah;
2576         HAL_TXQ_INFO qi;
2577
2578         ath_hal_gettxqueueprops(ah, sc->sc_bhalq, &qi);
2579         if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2580             ic->ic_opmode == IEEE80211_M_MBSS) {
2581                 /*
2582                  * Always burst out beacon and CAB traffic.
2583                  */
2584                 qi.tqi_aifs = ATH_BEACON_AIFS_DEFAULT;
2585                 qi.tqi_cwmin = ATH_BEACON_CWMIN_DEFAULT;
2586                 qi.tqi_cwmax = ATH_BEACON_CWMAX_DEFAULT;
2587         } else {
2588                 struct wmeParams *wmep =
2589                         &ic->ic_wme.wme_chanParams.cap_wmeParams[WME_AC_BE];
2590                 /*
2591                  * Adhoc mode; important thing is to use 2x cwmin.
2592                  */
2593                 qi.tqi_aifs = wmep->wmep_aifsn;
2594                 qi.tqi_cwmin = 2*ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
2595                 qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
2596         }
2597
2598         if (!ath_hal_settxqueueprops(ah, sc->sc_bhalq, &qi)) {
2599                 device_printf(sc->sc_dev, "unable to update parameters for "
2600                         "beacon hardware queue!\n");
2601                 return 0;
2602         } else {
2603                 ath_hal_resettxqueue(ah, sc->sc_bhalq); /* push to h/w */
2604                 return 1;
2605         }
2606 #undef ATH_EXPONENT_TO_VALUE
2607 }
2608
2609 /*
2610  * Allocate and setup an initial beacon frame.
2611  */
2612 static int
2613 ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
2614 {
2615         struct ieee80211vap *vap = ni->ni_vap;
2616         struct ath_vap *avp = ATH_VAP(vap);
2617         struct ath_buf *bf;
2618         struct mbuf *m;
2619         int error;
2620
2621         bf = avp->av_bcbuf;
2622         if (bf->bf_m != NULL) {
2623                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2624                 m_freem(bf->bf_m);
2625                 bf->bf_m = NULL;
2626         }
2627         if (bf->bf_node != NULL) {
2628                 ieee80211_free_node(bf->bf_node);
2629                 bf->bf_node = NULL;
2630         }
2631
2632         /*
2633          * NB: the beacon data buffer must be 32-bit aligned;
2634          * we assume the mbuf routines will return us something
2635          * with this alignment (perhaps should assert).
2636          */
2637         m = ieee80211_beacon_alloc(ni, &avp->av_boff);
2638         if (m == NULL) {
2639                 device_printf(sc->sc_dev, "%s: cannot get mbuf\n", __func__);
2640                 sc->sc_stats.ast_be_nombuf++;
2641                 return ENOMEM;
2642         }
2643         error = bus_dmamap_load_mbuf_segment(sc->sc_dmat, bf->bf_dmamap, m,
2644                                      bf->bf_segs, 1, &bf->bf_nseg,
2645                                      BUS_DMA_NOWAIT);
2646         if (error != 0) {
2647                 device_printf(sc->sc_dev,
2648                     "%s: cannot map mbuf, bus_dmamap_load_mbuf_segment returns %d\n",
2649                     __func__, error);
2650                 m_freem(m);
2651                 return error;
2652         }
2653
2654         /*
2655          * Calculate a TSF adjustment factor required for staggered
2656          * beacons.  Note that we assume the format of the beacon
2657          * frame leaves the tstamp field immediately following the
2658          * header.
2659          */
2660         if (sc->sc_stagbeacons && avp->av_bslot > 0) {
2661                 uint64_t tsfadjust;
2662                 struct ieee80211_frame *wh;
2663
2664                 /*
2665                  * The beacon interval is in TU's; the TSF is in usecs.
2666                  * We figure out how many TU's to add to align the timestamp
2667                  * then convert to TSF units and handle byte swapping before
2668                  * inserting it in the frame.  The hardware will then add this
2669                  * each time a beacon frame is sent.  Note that we align vap's
2670                  * 1..N and leave vap 0 untouched.  This means vap 0 has a
2671                  * timestamp in one beacon interval while the others get a
2672                  * timstamp aligned to the next interval.
2673                  */
2674                 tsfadjust = ni->ni_intval *
2675                     (ATH_BCBUF - avp->av_bslot) / ATH_BCBUF;
2676                 tsfadjust = htole64(tsfadjust << 10);   /* TU -> TSF */
2677
2678                 DPRINTF(sc, ATH_DEBUG_BEACON,
2679                     "%s: %s beacons bslot %d intval %u tsfadjust %llu\n",
2680                     __func__, sc->sc_stagbeacons ? "stagger" : "burst",
2681                     avp->av_bslot, ni->ni_intval,
2682                     (long long unsigned) le64toh(tsfadjust));
2683
2684                 wh = mtod(m, struct ieee80211_frame *);
2685                 memcpy(&wh[1], &tsfadjust, sizeof(tsfadjust));
2686         }
2687         bf->bf_m = m;
2688         bf->bf_node = ieee80211_ref_node(ni);
2689
2690         return 0;
2691 }
2692
2693 /*
2694  * Setup the beacon frame for transmit.
2695  */
2696 static void
2697 ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
2698 {
2699 #define USE_SHPREAMBLE(_ic) \
2700         (((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
2701                 == IEEE80211_F_SHPREAMBLE)
2702         struct ieee80211_node *ni = bf->bf_node;
2703         struct ieee80211com *ic = ni->ni_ic;
2704         struct mbuf *m = bf->bf_m;
2705         struct ath_hal *ah = sc->sc_ah;
2706         struct ath_desc *ds;
2707         int flags, antenna;
2708         const HAL_RATE_TABLE *rt;
2709         u_int8_t rix, rate;
2710
2711         DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: m %p len %u\n",
2712                 __func__, m, m->m_len);
2713
2714         /* setup descriptors */
2715         ds = bf->bf_desc;
2716
2717         flags = HAL_TXDESC_NOACK;
2718         if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
2719                 ds->ds_link = bf->bf_daddr;     /* self-linked */
2720                 flags |= HAL_TXDESC_VEOL;
2721                 /*
2722                  * Let hardware handle antenna switching.
2723                  */
2724                 antenna = sc->sc_txantenna;
2725         } else {
2726                 ds->ds_link = 0;
2727                 /*
2728                  * Switch antenna every 4 beacons.
2729                  * XXX assumes two antenna
2730                  */
2731                 if (sc->sc_txantenna != 0)
2732                         antenna = sc->sc_txantenna;
2733                 else if (sc->sc_stagbeacons && sc->sc_nbcnvaps != 0)
2734                         antenna = ((sc->sc_stats.ast_be_xmit / sc->sc_nbcnvaps) & 4 ? 2 : 1);
2735                 else
2736                         antenna = (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
2737         }
2738
2739         KASSERT(bf->bf_nseg == 1,
2740                 ("multi-segment beacon frame; nseg %u", bf->bf_nseg));
2741         ds->ds_data = bf->bf_segs[0].ds_addr;
2742         /*
2743          * Calculate rate code.
2744          * XXX everything at min xmit rate
2745          */
2746         rix = 0;
2747         rt = sc->sc_currates;
2748         rate = rt->info[rix].rateCode;
2749         if (USE_SHPREAMBLE(ic))
2750                 rate |= rt->info[rix].shortPreamble;
2751         ath_hal_setuptxdesc(ah, ds
2752                 , m->m_len + IEEE80211_CRC_LEN  /* frame length */
2753                 , sizeof(struct ieee80211_frame)/* header length */
2754                 , HAL_PKT_TYPE_BEACON           /* Atheros packet type */
2755                 , ni->ni_txpower                /* txpower XXX */
2756                 , rate, 1                       /* series 0 rate/tries */
2757                 , HAL_TXKEYIX_INVALID           /* no encryption */
2758                 , antenna                       /* antenna mode */
2759                 , flags                         /* no ack, veol for beacons */
2760                 , 0                             /* rts/cts rate */
2761                 , 0                             /* rts/cts duration */
2762         );
2763         /* NB: beacon's BufLen must be a multiple of 4 bytes */
2764         ath_hal_filltxdesc(ah, ds
2765                 , roundup(m->m_len, 4)          /* buffer length */
2766                 , AH_TRUE                       /* first segment */
2767                 , AH_TRUE                       /* last segment */
2768                 , ds                            /* first descriptor */
2769         );
2770 #if 0
2771         ath_desc_swap(ds);
2772 #endif
2773 #undef USE_SHPREAMBLE
2774 }
2775
2776 static void
2777 ath_beacon_update(struct ieee80211vap *vap, int item)
2778 {
2779         struct ieee80211_beacon_offsets *bo = &ATH_VAP(vap)->av_boff;
2780
2781         setbit(bo->bo_flags, item);
2782 }
2783
2784 /*
2785  * Append the contents of src to dst; both queues
2786  * are assumed to be locked.
2787  */
2788 static void
2789 ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
2790 {
2791         STAILQ_CONCAT(&dst->axq_q, &src->axq_q);
2792         if (src->axq_depth)
2793                 dst->axq_link = src->axq_link;
2794         src->axq_link = NULL;
2795         dst->axq_depth += src->axq_depth;
2796         src->axq_depth = 0;
2797 }
2798
2799 /*
2800  * Transmit a beacon frame at SWBA.  Dynamic updates to the
2801  * frame contents are done as needed and the slot time is
2802  * also adjusted based on current state.
2803  */
2804 static void
2805 ath_beacon_proc(void *arg, int pending)
2806 {
2807         struct ath_softc *sc = arg;
2808         struct ath_hal *ah = sc->sc_ah;
2809         struct ieee80211vap *vap;
2810         struct ath_buf *bf;
2811         int slot, otherant;
2812         uint32_t bfaddr;
2813
2814         DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
2815                 __func__, pending);
2816         /*
2817          * Check if the previous beacon has gone out.  If
2818          * not don't try to post another, skip this period
2819          * and wait for the next.  Missed beacons indicate
2820          * a problem and should not occur.  If we miss too
2821          * many consecutive beacons reset the device.
2822          */
2823         if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
2824                 sc->sc_bmisscount++;
2825                 DPRINTF(sc, ATH_DEBUG_BEACON,
2826                         "%s: missed %u consecutive beacons\n",
2827                         __func__, sc->sc_bmisscount);
2828                 if (sc->sc_bmisscount >= ath_bstuck_threshold)
2829                         taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
2830                 return;
2831         }
2832         if (sc->sc_bmisscount != 0) {
2833                 DPRINTF(sc, ATH_DEBUG_BEACON,
2834                         "%s: resume beacon xmit after %u misses\n",
2835                         __func__, sc->sc_bmisscount);
2836                 sc->sc_bmisscount = 0;
2837         }
2838
2839         /*
2840          * Stop any current dma before messing with the beacon linkages.
2841          */
2842         if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
2843                 DPRINTF(sc, ATH_DEBUG_ANY,
2844                         "%s: beacon queue %u did not stop?\n",
2845                         __func__, sc->sc_bhalq);
2846         }
2847
2848         if (sc->sc_stagbeacons) {                       /* staggered beacons */
2849                 struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2850                 uint32_t tsftu;
2851
2852                 tsftu = ath_hal_gettsf32(ah) >> 10;
2853                 /* XXX lintval */
2854                 slot = ((tsftu % ic->ic_lintval) * ATH_BCBUF) / ic->ic_lintval;
2855                 vap = sc->sc_bslot[(slot+1) % ATH_BCBUF];
2856                 bfaddr = 0;
2857                 if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2858                         bf = ath_beacon_generate(sc, vap);
2859                         if (bf != NULL)
2860                                 bfaddr = bf->bf_daddr;
2861                 }
2862         } else {                                        /* burst'd beacons */
2863                 uint32_t *bflink = &bfaddr;
2864
2865                 for (slot = 0; slot < ATH_BCBUF; slot++) {
2866                         vap = sc->sc_bslot[slot];
2867                         if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2868                                 bf = ath_beacon_generate(sc, vap);
2869                                 if (bf != NULL) {
2870                                         *bflink = bf->bf_daddr;
2871                                         bflink = &bf->bf_desc->ds_link;
2872                                 }
2873                         }
2874                 }
2875                 *bflink = 0;                            /* terminate list */
2876         }
2877
2878         /*
2879          * Handle slot time change when a non-ERP station joins/leaves
2880          * an 11g network.  The 802.11 layer notifies us via callback,
2881          * we mark updateslot, then wait one beacon before effecting
2882          * the change.  This gives associated stations at least one
2883          * beacon interval to note the state change.
2884          */
2885         /* XXX locking */
2886         if (sc->sc_updateslot == UPDATE) {
2887                 sc->sc_updateslot = COMMIT;     /* commit next beacon */
2888                 sc->sc_slotupdate = slot;
2889         } else if (sc->sc_updateslot == COMMIT && sc->sc_slotupdate == slot)
2890                 ath_setslottime(sc);            /* commit change to h/w */
2891
2892         /*
2893          * Check recent per-antenna transmit statistics and flip
2894          * the default antenna if noticeably more frames went out
2895          * on the non-default antenna.
2896          * XXX assumes 2 anntenae
2897          */
2898         if (!sc->sc_diversity && (!sc->sc_stagbeacons || slot == 0)) {
2899                 otherant = sc->sc_defant & 1 ? 2 : 1;
2900                 if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
2901                         ath_setdefantenna(sc, otherant);
2902                 sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
2903         }
2904
2905         if (bfaddr != 0) {
2906                 /* NB: cabq traffic should already be queued and primed */
2907                 ath_hal_puttxbuf(ah, sc->sc_bhalq, bfaddr);
2908                 sc->sc_stats.ast_be_xmit++;
2909                 ath_hal_txstart(ah, sc->sc_bhalq);
2910         }
2911         /* else no beacon will be generated */
2912 }
2913
2914 static struct ath_buf *
2915 ath_beacon_generate(struct ath_softc *sc, struct ieee80211vap *vap)
2916 {
2917         struct ath_vap *avp = ATH_VAP(vap);
2918         struct ath_txq *cabq = sc->sc_cabq;
2919         struct ath_buf *bf;
2920         struct mbuf *m;
2921         int nmcastq, error;
2922
2923         KASSERT(vap->iv_state >= IEEE80211_S_RUN,
2924             ("not running, state %d", vap->iv_state));
2925         KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
2926
2927         /*
2928          * Update dynamic beacon contents.  If this returns
2929          * non-zero then we need to remap the memory because
2930          * the beacon frame changed size (probably because
2931          * of the TIM bitmap).
2932          */
2933         bf = avp->av_bcbuf;
2934         m = bf->bf_m;
2935         nmcastq = avp->av_mcastq.axq_depth;
2936         if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, nmcastq)) {
2937                 /* XXX too conservative? */
2938                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2939                 error = bus_dmamap_load_mbuf_segment(sc->sc_dmat, bf->bf_dmamap, m,
2940                                              bf->bf_segs, 1, &bf->bf_nseg,
2941                                              BUS_DMA_NOWAIT);
2942                 if (error != 0) {
2943                         if_printf(vap->iv_ifp,
2944                             "%s: bus_dmamap_load_mbuf_segment failed, error %u\n",
2945                             __func__, error);
2946                         return NULL;
2947                 }
2948         }
2949         if ((avp->av_boff.bo_tim[4] & 1) && cabq->axq_depth) {
2950                 DPRINTF(sc, ATH_DEBUG_BEACON,
2951                     "%s: cabq did not drain, mcastq %u cabq %u\n",
2952                     __func__, nmcastq, cabq->axq_depth);
2953                 sc->sc_stats.ast_cabq_busy++;
2954                 if (sc->sc_nvaps > 1 && sc->sc_stagbeacons) {
2955                         /*
2956                          * CABQ traffic from a previous vap is still pending.
2957                          * We must drain the q before this beacon frame goes
2958                          * out as otherwise this vap's stations will get cab
2959                          * frames from a different vap.
2960                          * XXX could be slow causing us to miss DBA
2961                          */
2962                         ath_tx_draintxq(sc, cabq);
2963                 }
2964         }
2965         ath_beacon_setup(sc, bf);
2966         bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
2967
2968         /*
2969          * Enable the CAB queue before the beacon queue to
2970          * insure cab frames are triggered by this beacon.
2971          */
2972         if (avp->av_boff.bo_tim[4] & 1) {
2973                 struct ath_hal *ah = sc->sc_ah;
2974
2975                 /* NB: only at DTIM */
2976                 if (nmcastq) {
2977                         struct ath_buf *bfm;
2978                         int qbusy;
2979
2980                         /*
2981                          * Move frames from the s/w mcast q to the h/w cab q.
2982                          * XXX MORE_DATA bit
2983                          */
2984                         bfm = STAILQ_FIRST(&avp->av_mcastq.axq_q);
2985                         qbusy = ath_hal_txqenabled(ah, cabq->axq_qnum);
2986                         if (qbusy == 0) {
2987                                 if (cabq->axq_link != NULL) {
2988                                         cpu_sfence();
2989                                         *cabq->axq_link = bfm->bf_daddr;
2990                                         cabq->axq_flags |= ATH_TXQ_PUTPENDING;
2991                                 } else {
2992                                         cpu_sfence();
2993                                         ath_hal_puttxbuf(ah, cabq->axq_qnum,
2994                                                 bfm->bf_daddr);
2995                                 }
2996                         } else {
2997                                 if (cabq->axq_link != NULL) {
2998                                         cpu_sfence();
2999                                         *cabq->axq_link = bfm->bf_daddr;
3000                                 }
3001                                 cabq->axq_flags |= ATH_TXQ_PUTPENDING;
3002                         }
3003                         ath_txqmove(cabq, &avp->av_mcastq);
3004
3005                         sc->sc_stats.ast_cabq_xmit += nmcastq;
3006                 }
3007                 /* NB: gated by beacon so safe to start here */
3008                 ath_hal_txstart(ah, cabq->axq_qnum);
3009         }
3010         return bf;
3011 }
3012
3013 static void
3014 ath_beacon_start_adhoc(struct ath_softc *sc, struct ieee80211vap *vap)
3015 {
3016         struct ath_vap *avp = ATH_VAP(vap);
3017         struct ath_hal *ah = sc->sc_ah;
3018         struct ath_buf *bf;
3019         struct mbuf *m;
3020         int error;
3021
3022         KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
3023
3024         /*
3025          * Update dynamic beacon contents.  If this returns
3026          * non-zero then we need to remap the memory because
3027          * the beacon frame changed size (probably because
3028          * of the TIM bitmap).
3029          */
3030         bf = avp->av_bcbuf;
3031         m = bf->bf_m;
3032         if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, 0)) {
3033                 /* XXX too conservative? */
3034                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3035                 error = bus_dmamap_load_mbuf_segment(sc->sc_dmat, bf->bf_dmamap, m,
3036                                              bf->bf_segs, 1, &bf->bf_nseg,
3037                                              BUS_DMA_NOWAIT);
3038                 if (error != 0) {
3039                         if_printf(vap->iv_ifp,
3040                             "%s: bus_dmamap_load_mbuf_segment failed, error %u\n",
3041                             __func__, error);
3042                         return;
3043                 }
3044         }
3045         ath_beacon_setup(sc, bf);
3046         bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3047
3048         /* NB: caller is known to have already stopped tx dma */
3049         ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
3050         ath_hal_txstart(ah, sc->sc_bhalq);
3051 }
3052
3053 /*
3054  * Reset the hardware after detecting beacons have stopped.
3055  */
3056 static void
3057 ath_bstuck_task(void *arg, int pending)
3058 {
3059         struct ath_softc *sc = arg;
3060         struct ifnet *ifp = sc->sc_ifp;
3061
3062         wlan_serialize_enter();
3063         if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
3064                   sc->sc_bmisscount);
3065         sc->sc_stats.ast_bstuck++;
3066         ath_reset(ifp);
3067         wlan_serialize_exit();
3068 }
3069
3070 /*
3071  * Reclaim beacon resources and return buffer to the pool.
3072  */
3073 static void
3074 ath_beacon_return(struct ath_softc *sc, struct ath_buf *bf)
3075 {
3076
3077         if (bf->bf_m != NULL) {
3078                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3079                 m_freem(bf->bf_m);
3080                 bf->bf_m = NULL;
3081         }
3082         if (bf->bf_node != NULL) {
3083                 ieee80211_free_node(bf->bf_node);
3084                 bf->bf_node = NULL;
3085         }
3086         STAILQ_INSERT_TAIL(&sc->sc_bbuf, bf, bf_list);
3087 }
3088
3089 /*
3090  * Reclaim beacon resources.
3091  */
3092 static void
3093 ath_beacon_free(struct ath_softc *sc)
3094 {
3095         struct ath_buf *bf;
3096
3097         STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
3098                 if (bf->bf_m != NULL) {
3099                         bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3100                         m_freem(bf->bf_m);
3101                         bf->bf_m = NULL;
3102                 }
3103                 if (bf->bf_node != NULL) {
3104                         ieee80211_free_node(bf->bf_node);
3105                         bf->bf_node = NULL;
3106                 }
3107         }
3108 }
3109
3110 /*
3111  * Configure the beacon and sleep timers.
3112  *
3113  * When operating as an AP this resets the TSF and sets
3114  * up the hardware to notify us when we need to issue beacons.
3115  *
3116  * When operating in station mode this sets up the beacon
3117  * timers according to the timestamp of the last received
3118  * beacon and the current TSF, configures PCF and DTIM
3119  * handling, programs the sleep registers so the hardware
3120  * will wakeup in time to receive beacons, and configures
3121  * the beacon miss handling so we'll receive a BMISS
3122  * interrupt when we stop seeing beacons from the AP
3123  * we've associated with.
3124  */
3125 static void
3126 ath_beacon_config(struct ath_softc *sc, struct ieee80211vap *vap)
3127 {
3128 #define TSF_TO_TU(_h,_l) \
3129         ((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
3130 #define FUDGE   2
3131         struct ath_hal *ah = sc->sc_ah;
3132         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3133         struct ieee80211_node *ni;
3134         u_int32_t nexttbtt, intval, tsftu;
3135         u_int64_t tsf;
3136
3137         if (vap == NULL)
3138                 vap = TAILQ_FIRST(&ic->ic_vaps);        /* XXX */
3139         ni = vap->iv_bss;
3140
3141         /* extract tstamp from last beacon and convert to TU */
3142         nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
3143                              LE_READ_4(ni->ni_tstamp.data));
3144         if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3145             ic->ic_opmode == IEEE80211_M_MBSS) {
3146                 /*
3147                  * For multi-bss ap/mesh support beacons are either staggered
3148                  * evenly over N slots or burst together.  For the former
3149                  * arrange for the SWBA to be delivered for each slot.
3150                  * Slots that are not occupied will generate nothing.
3151                  */
3152                 /* NB: the beacon interval is kept internally in TU's */
3153                 intval = ni->ni_intval & HAL_BEACON_PERIOD;
3154                 if (sc->sc_stagbeacons)
3155                         intval /= ATH_BCBUF;
3156         } else {
3157                 /* NB: the beacon interval is kept internally in TU's */
3158                 intval = ni->ni_intval & HAL_BEACON_PERIOD;
3159         }
3160         if (nexttbtt == 0)              /* e.g. for ap mode */
3161                 nexttbtt = intval;
3162         else if (intval)                /* NB: can be 0 for monitor mode */
3163                 nexttbtt = roundup(nexttbtt, intval);
3164         DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
3165                 __func__, nexttbtt, intval, ni->ni_intval);
3166         if (ic->ic_opmode == IEEE80211_M_STA && !sc->sc_swbmiss) {
3167                 HAL_BEACON_STATE bs;
3168                 int dtimperiod, dtimcount;
3169                 int cfpperiod, cfpcount;
3170
3171                 /*
3172                  * Setup dtim and cfp parameters according to
3173                  * last beacon we received (which may be none).
3174                  */
3175                 dtimperiod = ni->ni_dtim_period;
3176                 if (dtimperiod <= 0)            /* NB: 0 if not known */
3177                         dtimperiod = 1;
3178                 dtimcount = ni->ni_dtim_count;
3179                 if (dtimcount >= dtimperiod)    /* NB: sanity check */
3180                         dtimcount = 0;          /* XXX? */
3181                 cfpperiod = 1;                  /* NB: no PCF support yet */
3182                 cfpcount = 0;
3183                 /*
3184                  * Pull nexttbtt forward to reflect the current
3185                  * TSF and calculate dtim+cfp state for the result.
3186                  */
3187                 tsf = ath_hal_gettsf64(ah);
3188                 tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3189                 do {
3190                         nexttbtt += intval;
3191                         if (--dtimcount < 0) {
3192                                 dtimcount = dtimperiod - 1;
3193                                 if (--cfpcount < 0)
3194                                         cfpcount = cfpperiod - 1;
3195                         }
3196                 } while (nexttbtt < tsftu);
3197                 memset(&bs, 0, sizeof(bs));
3198                 bs.bs_intval = intval;
3199                 bs.bs_nexttbtt = nexttbtt;
3200                 bs.bs_dtimperiod = dtimperiod*intval;
3201                 bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
3202                 bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
3203                 bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
3204                 bs.bs_cfpmaxduration = 0;
3205 #if 0
3206                 /*
3207                  * The 802.11 layer records the offset to the DTIM
3208                  * bitmap while receiving beacons; use it here to
3209                  * enable h/w detection of our AID being marked in
3210                  * the bitmap vector (to indicate frames for us are
3211                  * pending at the AP).
3212                  * XXX do DTIM handling in s/w to WAR old h/w bugs
3213                  * XXX enable based on h/w rev for newer chips
3214                  */
3215                 bs.bs_timoffset = ni->ni_timoff;
3216 #endif
3217                 /*
3218                  * Calculate the number of consecutive beacons to miss
3219                  * before taking a BMISS interrupt.
3220                  * Note that we clamp the result to at most 10 beacons.
3221                  */
3222                 bs.bs_bmissthreshold = vap->iv_bmissthreshold;
3223                 if (bs.bs_bmissthreshold > 10)
3224                         bs.bs_bmissthreshold = 10;
3225                 else if (bs.bs_bmissthreshold <= 0)
3226                         bs.bs_bmissthreshold = 1;
3227
3228                 /*
3229                  * Calculate sleep duration.  The configuration is
3230                  * given in ms.  We insure a multiple of the beacon
3231                  * period is used.  Also, if the sleep duration is
3232                  * greater than the DTIM period then it makes senses
3233                  * to make it a multiple of that.
3234                  *
3235                  * XXX fixed at 100ms
3236                  */
3237                 bs.bs_sleepduration =
3238                         roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
3239                 if (bs.bs_sleepduration > bs.bs_dtimperiod)
3240                         bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
3241
3242                 DPRINTF(sc, ATH_DEBUG_BEACON,
3243                         "%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"
3244                         , __func__
3245                         , tsf, tsftu
3246                         , bs.bs_intval
3247                         , bs.bs_nexttbtt
3248                         , bs.bs_dtimperiod
3249                         , bs.bs_nextdtim
3250                         , bs.bs_bmissthreshold
3251                         , bs.bs_sleepduration
3252                         , bs.bs_cfpperiod
3253                         , bs.bs_cfpmaxduration
3254                         , bs.bs_cfpnext
3255                         , bs.bs_timoffset
3256                 );
3257                 ath_hal_intrset(ah, 0);
3258                 ath_hal_beacontimers(ah, &bs);
3259                 sc->sc_imask |= HAL_INT_BMISS;
3260                 ath_hal_intrset(ah, sc->sc_imask);
3261         } else {
3262                 ath_hal_intrset(ah, 0);
3263                 if (nexttbtt == intval)
3264                         intval |= HAL_BEACON_RESET_TSF;
3265                 if (ic->ic_opmode == IEEE80211_M_IBSS) {
3266                         /*
3267                          * In IBSS mode enable the beacon timers but only
3268                          * enable SWBA interrupts if we need to manually
3269                          * prepare beacon frames.  Otherwise we use a
3270                          * self-linked tx descriptor and let the hardware
3271                          * deal with things.
3272                          */
3273                         intval |= HAL_BEACON_ENA;
3274                         if (!sc->sc_hasveol)
3275                                 sc->sc_imask |= HAL_INT_SWBA;
3276                         if ((intval & HAL_BEACON_RESET_TSF) == 0) {
3277                                 /*
3278                                  * Pull nexttbtt forward to reflect
3279                                  * the current TSF.
3280                                  */
3281                                 tsf = ath_hal_gettsf64(ah);
3282                                 tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3283                                 do {
3284                                         nexttbtt += intval;
3285                                 } while (nexttbtt < tsftu);
3286                         }
3287                         ath_beaconq_config(sc);
3288                 } else if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3289                     ic->ic_opmode == IEEE80211_M_MBSS) {
3290                         /*
3291                          * In AP/mesh mode we enable the beacon timers
3292                          * and SWBA interrupts to prepare beacon frames.
3293                          */
3294                         intval |= HAL_BEACON_ENA;
3295                         sc->sc_imask |= HAL_INT_SWBA;   /* beacon prepare */
3296                         ath_beaconq_config(sc);
3297                 }
3298                 ath_hal_beaconinit(ah, nexttbtt, intval);
3299                 sc->sc_bmisscount = 0;
3300                 ath_hal_intrset(ah, sc->sc_imask);
3301                 /*
3302                  * When using a self-linked beacon descriptor in
3303                  * ibss mode load it once here.
3304                  */
3305                 if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
3306                         ath_beacon_start_adhoc(sc, vap);
3307         }
3308         sc->sc_syncbeacon = 0;
3309 #undef FUDGE
3310 #undef TSF_TO_TU
3311 }
3312
3313 static void
3314 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3315 {
3316         bus_addr_t *paddr = (bus_addr_t*) arg;
3317         KASSERT(error == 0, ("error %u on bus_dma callback", error));
3318         *paddr = segs->ds_addr;
3319 }
3320
3321 static int
3322 ath_descdma_setup(struct ath_softc *sc,
3323         struct ath_descdma *dd, ath_bufhead *head,
3324         const char *name, int nbuf, int ndesc)
3325 {
3326 #define DS2PHYS(_dd, _ds) \
3327         ((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3328         struct ifnet *ifp = sc->sc_ifp;
3329         struct ath_desc *ds;
3330         struct ath_buf *bf;
3331         int i, bsize, error;
3332
3333         DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
3334             __func__, name, nbuf, ndesc);
3335
3336         dd->dd_name = name;
3337         dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
3338
3339         /*
3340          * Setup DMA descriptor area.
3341          */
3342         error = bus_dma_tag_create(dd->dd_dmat, /* parent */
3343                        PAGE_SIZE, 0,            /* alignment, bounds */
3344                        BUS_SPACE_MAXADDR_32BIT, /* lowaddr */
3345                        BUS_SPACE_MAXADDR,       /* highaddr */
3346                        NULL, NULL,              /* filter, filterarg */
3347                        dd->dd_desc_len,         /* maxsize */
3348                        1,                       /* nsegments */
3349                        dd->dd_desc_len,         /* maxsegsize */
3350                        BUS_DMA_ALLOCNOW,        /* flags */
3351                        &dd->dd_dmat);
3352         if (error != 0) {
3353                 if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
3354                 return error;
3355         }
3356
3357         /* allocate descriptors */
3358         error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
3359         if (error != 0) {
3360                 if_printf(ifp, "unable to create dmamap for %s descriptors, "
3361                         "error %u\n", dd->dd_name, error);
3362                 goto fail0;
3363         }
3364
3365         error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
3366                                  BUS_DMA_NOWAIT | BUS_DMA_COHERENT, 
3367                                  &dd->dd_dmamap);
3368         if (error != 0) {
3369                 if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
3370                         "error %u\n", nbuf * ndesc, dd->dd_name, error);
3371                 goto fail1;
3372         }
3373
3374         error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
3375                                 dd->dd_desc, dd->dd_desc_len,
3376                                 ath_load_cb, &dd->dd_desc_paddr,
3377                                 BUS_DMA_NOWAIT);
3378         if (error != 0) {
3379                 if_printf(ifp, "unable to map %s descriptors, error %u\n",
3380                         dd->dd_name, error);
3381                 goto fail2;
3382         }
3383
3384         ds = dd->dd_desc;
3385         DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
3386             __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
3387             (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
3388
3389         /* allocate rx buffers */
3390         bsize = sizeof(struct ath_buf) * nbuf;
3391         bf = kmalloc(bsize, M_ATHDEV, M_INTWAIT | M_ZERO);
3392         if (bf == NULL) {
3393                 if_printf(ifp, "malloc of %s buffers failed, size %u\n",
3394                         dd->dd_name, bsize);
3395                 goto fail3;
3396         }
3397         dd->dd_bufptr = bf;
3398
3399         STAILQ_INIT(head);
3400         for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
3401                 bf->bf_desc = ds;
3402                 bf->bf_daddr = DS2PHYS(dd, ds);
3403                 error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3404                                 &bf->bf_dmamap);
3405                 if (error != 0) {
3406                         if_printf(ifp, "unable to create dmamap for %s "
3407                                 "buffer %u, error %u\n", dd->dd_name, i, error);
3408                         ath_descdma_cleanup(sc, dd, head);
3409                         return error;
3410                 }
3411                 STAILQ_INSERT_TAIL(head, bf, bf_list);
3412         }
3413         return 0;
3414 fail3:
3415         bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3416 fail2:
3417         bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3418 fail1:
3419         bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3420 fail0:
3421         bus_dma_tag_destroy(dd->dd_dmat);
3422         memset(dd, 0, sizeof(*dd));
3423         return error;
3424 #undef DS2PHYS
3425 }
3426
3427 static void
3428 ath_descdma_cleanup(struct ath_softc *sc,
3429         struct ath_descdma *dd, ath_bufhead *head)
3430 {
3431         struct ath_buf *bf;
3432         struct ieee80211_node *ni;
3433
3434         bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3435         bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3436         bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3437         bus_dma_tag_destroy(dd->dd_dmat);
3438
3439         STAILQ_FOREACH(bf, head, bf_list) {
3440                 if (bf->bf_m) {
3441                         m_freem(bf->bf_m);
3442                         bf->bf_m = NULL;
3443                 }
3444                 if (bf->bf_dmamap != NULL) {
3445                         bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
3446                         bf->bf_dmamap = NULL;
3447                 }
3448                 ni = bf->bf_node;
3449                 bf->bf_node = NULL;
3450                 if (ni != NULL) {
3451                         /*
3452                          * Reclaim node reference.
3453                          */
3454                         ieee80211_free_node(ni);
3455                 }
3456         }
3457
3458         STAILQ_INIT(head);
3459         kfree(dd->dd_bufptr, M_ATHDEV);
3460         memset(dd, 0, sizeof(*dd));
3461 }
3462
3463 static int
3464 ath_desc_alloc(struct ath_softc *sc)
3465 {
3466         int error;
3467
3468         error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
3469                         "rx", ath_rxbuf, 1);
3470         if (error != 0)
3471                 return error;
3472
3473         error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
3474                         "tx", ath_txbuf, ATH_TXDESC);
3475         if (error != 0) {
3476                 ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3477                 return error;
3478         }
3479
3480         error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
3481                         "beacon", ATH_BCBUF, 1);
3482         if (error != 0) {
3483                 ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3484                 ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3485                 return error;
3486         }
3487         return 0;
3488 }
3489
3490 static void
3491 ath_desc_free(struct ath_softc *sc)
3492 {
3493
3494         if (sc->sc_bdma.dd_desc_len != 0)
3495                 ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
3496         if (sc->sc_txdma.dd_desc_len != 0)
3497                 ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3498         if (sc->sc_rxdma.dd_desc_len != 0)
3499                 ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3500 }
3501
3502 static struct ieee80211_node *
3503 ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
3504 {
3505         struct ieee80211com *ic = vap->iv_ic;
3506         struct ath_softc *sc = ic->ic_ifp->if_softc;
3507         const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
3508         struct ath_node *an;
3509
3510         an = kmalloc(space, M_80211_NODE, M_INTWAIT|M_ZERO);
3511         if (an == NULL) {
3512                 /* XXX stat+msg */
3513                 return NULL;
3514         }
3515         ath_rate_node_init(sc, an);
3516
3517         DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
3518         return &an->an_node;
3519 }
3520
3521 static void
3522 ath_node_free(struct ieee80211_node *ni)
3523 {
3524         struct ieee80211com *ic = ni->ni_ic;
3525         struct ath_softc *sc = ic->ic_ifp->if_softc;
3526
3527         DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
3528
3529         ath_rate_node_cleanup(sc, ATH_NODE(ni));
3530         sc->sc_node_free(ni);
3531 }
3532
3533 static void
3534 ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
3535 {
3536         struct ieee80211com *ic = ni->ni_ic;
3537         struct ath_softc *sc = ic->ic_ifp->if_softc;
3538         struct ath_hal *ah = sc->sc_ah;
3539
3540         *rssi = ic->ic_node_getrssi(ni);
3541         if (ni->ni_chan != IEEE80211_CHAN_ANYC)
3542                 *noise = ath_hal_getchannoise(ah, ni->ni_chan);
3543         else
3544                 *noise = -95;           /* nominally correct */
3545 }
3546
3547 static int
3548 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
3549 {
3550         struct ath_hal *ah = sc->sc_ah;
3551         int error;
3552         struct mbuf *m;
3553         struct ath_desc *ds;
3554
3555         m = bf->bf_m;
3556         if (m == NULL) {
3557                 /*
3558                  * NB: by assigning a page to the rx dma buffer we
3559                  * implicitly satisfy the Atheros requirement that
3560                  * this buffer be cache-line-aligned and sized to be
3561                  * multiple of the cache line size.  Not doing this
3562                  * causes weird stuff to happen (for the 5210 at least).
3563                  */
3564                 m = m_getcl(MB_WAIT, MT_DATA, M_PKTHDR);
3565                 if (m == NULL) {
3566                         kprintf("ath_rxbuf_init: no mbuf\n");
3567                         DPRINTF(sc, ATH_DEBUG_ANY,
3568                                 "%s: no mbuf/cluster\n", __func__);
3569                         sc->sc_stats.ast_rx_nombuf++;
3570                         return ENOMEM;
3571                 }
3572                 m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
3573
3574                 error = bus_dmamap_load_mbuf_segment(sc->sc_dmat,
3575                                              bf->bf_dmamap, m,
3576                                              bf->bf_segs, 1, &bf->bf_nseg,
3577                                              BUS_DMA_NOWAIT);
3578                 if (error != 0) {
3579                         DPRINTF(sc, ATH_DEBUG_ANY,
3580                             "%s: bus_dmamap_load_mbuf_segment failed; error %d\n",
3581                             __func__, error);
3582                         sc->sc_stats.ast_rx_busdma++;
3583                         m_freem(m);
3584                         return error;
3585                 }
3586                 KASSERT(bf->bf_nseg == 1,
3587                         ("multi-segment packet; nseg %u", bf->bf_nseg));
3588                 bf->bf_m = m;
3589         }
3590         bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
3591
3592         /*
3593          * Setup descriptors.  For receive we always terminate
3594          * the descriptor list with a self-linked entry so we'll
3595          * not get overrun under high load (as can happen with a
3596          * 5212 when ANI processing enables PHY error frames).
3597          *
3598          * To insure the last descriptor is self-linked we create
3599          * each descriptor as self-linked and add it to the end.  As
3600          * each additional descriptor is added the previous self-linked
3601          * entry is ``fixed'' naturally.  This should be safe even
3602          * if DMA is happening.  When processing RX interrupts we
3603          * never remove/process the last, self-linked, entry on the
3604          * descriptor list.  This insures the hardware always has
3605          * someplace to write a new frame.
3606          */
3607         ds = bf->bf_desc;
3608         ds->ds_link = bf->bf_daddr;     /* link to self */
3609         ds->ds_data = bf->bf_segs[0].ds_addr;
3610         ath_hal_setuprxdesc(ah, ds
3611                 , m->m_len              /* buffer size */
3612                 , 0
3613         );
3614
3615         if (sc->sc_rxlink != NULL)
3616                 *sc->sc_rxlink = bf->bf_daddr;
3617         sc->sc_rxlink = &ds->ds_link;
3618         return 0;
3619 }
3620
3621 /*
3622  * Extend 15-bit time stamp from rx descriptor to
3623  * a full 64-bit TSF using the specified TSF.
3624  */
3625 static __inline u_int64_t
3626 ath_extend_tsf(u_int32_t rstamp, u_int64_t tsf)
3627 {
3628         if ((tsf & 0x7fff) < rstamp)
3629                 tsf -= 0x8000;
3630         return ((tsf &~ 0x7fff) | rstamp);
3631 }
3632
3633 /*
3634  * Intercept management frames to collect beacon rssi data
3635  * and to do ibss merges.
3636  */
3637 static void
3638 ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
3639         int subtype, int rssi, int nf)
3640 {
3641         struct ieee80211vap *vap = ni->ni_vap;
3642         struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
3643
3644         /*
3645          * Call up first so subsequent work can use information
3646          * potentially stored in the node (e.g. for ibss merge).
3647          */
3648         ATH_VAP(vap)->av_recv_mgmt(ni, m, subtype, rssi, nf);
3649         switch (subtype) {
3650         case IEEE80211_FC0_SUBTYPE_BEACON:
3651                 /* update rssi statistics for use by the hal */
3652                 ATH_RSSI_LPF(sc->sc_halstats.ns_avgbrssi, rssi);
3653                 if (sc->sc_syncbeacon &&
3654                     ni == vap->iv_bss && vap->iv_state == IEEE80211_S_RUN) {
3655                         /*
3656                          * Resync beacon timers using the tsf of the beacon
3657                          * frame we just received.
3658                          */
3659                         ath_beacon_config(sc, vap);
3660                 }
3661                 /* fall thru... */
3662         case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
3663                 if (vap->iv_opmode == IEEE80211_M_IBSS &&
3664                     vap->iv_state == IEEE80211_S_RUN) {
3665                         uint32_t rstamp = sc->sc_lastrs->rs_tstamp;
3666                         u_int64_t tsf = ath_extend_tsf(rstamp,
3667                                 ath_hal_gettsf64(sc->sc_ah));
3668                         /*
3669                          * Handle ibss merge as needed; check the tsf on the
3670                          * frame before attempting the merge.  The 802.11 spec
3671                          * says the station should change it's bssid to match
3672                          * the oldest station with the same ssid, where oldest
3673                          * is determined by the tsf.  Note that hardware
3674                          * reconfiguration happens through callback to
3675                          * ath_newstate as the state machine will go from
3676                          * RUN -> RUN when this happens.
3677                          */
3678                         if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
3679                                 DPRINTF(sc, ATH_DEBUG_STATE,
3680                                     "ibss merge, rstamp %u tsf %ju "
3681                                     "tstamp %ju\n", rstamp, (uintmax_t)tsf,
3682                                     (uintmax_t)ni->ni_tstamp.tsf);
3683                                 (void) ieee80211_ibss_merge(ni);
3684                         }
3685                 }
3686                 break;
3687         }
3688 }
3689
3690 /*
3691  * Set the default antenna.
3692  */
3693 static void
3694 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
3695 {
3696         struct ath_hal *ah = sc->sc_ah;
3697
3698         /* XXX block beacon interrupts */
3699         ath_hal_setdefantenna(ah, antenna);
3700         if (sc->sc_defant != antenna)
3701                 sc->sc_stats.ast_ant_defswitch++;
3702         sc->sc_defant = antenna;
3703         sc->sc_rxotherant = 0;
3704 }
3705
3706 static void
3707 ath_rx_tap(struct ifnet *ifp, struct mbuf *m,
3708         const struct ath_rx_status *rs, u_int64_t tsf, int16_t nf)
3709 {
3710 #define CHAN_HT20       htole32(IEEE80211_CHAN_HT20)
3711 #define CHAN_HT40U      htole32(IEEE80211_CHAN_HT40U)
3712 #define CHAN_HT40D      htole32(IEEE80211_CHAN_HT40D)
3713 #define CHAN_HT         (CHAN_HT20|CHAN_HT40U|CHAN_HT40D)
3714         struct ath_softc *sc = ifp->if_softc;
3715         const HAL_RATE_TABLE *rt;
3716         uint8_t rix;
3717
3718         rt = sc->sc_currates;
3719         KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
3720         rix = rt->rateCodeToIndex[rs->rs_rate];
3721         sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
3722         sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
3723 #ifdef AH_SUPPORT_AR5416
3724         sc->sc_rx_th.wr_chan_flags &= ~CHAN_HT;
3725         if (sc->sc_rx_th.wr_rate & IEEE80211_RATE_MCS) {        /* HT rate */
3726                 struct ieee80211com *ic = ifp->if_l2com;
3727
3728                 if ((rs->rs_flags & HAL_RX_2040) == 0)
3729                         sc->sc_rx_th.wr_chan_flags |= CHAN_HT20;
3730                 else if (IEEE80211_IS_CHAN_HT40U(ic->ic_curchan))
3731                         sc->sc_rx_th.wr_chan_flags |= CHAN_HT40U;
3732                 else
3733                         sc->sc_rx_th.wr_chan_flags |= CHAN_HT40D;
3734                 if ((rs->rs_flags & HAL_RX_GI) == 0)
3735                         sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_SHORTGI;
3736         }
3737 #endif
3738         sc->sc_rx_th.wr_tsf = htole64(ath_extend_tsf(rs->rs_tstamp, tsf));
3739         if (rs->rs_status & HAL_RXERR_CRC)
3740                 sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
3741         /* XXX propagate other error flags from descriptor */
3742         sc->sc_rx_th.wr_antnoise = nf;
3743         sc->sc_rx_th.wr_antsignal = nf + rs->rs_rssi;
3744         sc->sc_rx_th.wr_antenna = rs->rs_antenna;
3745 #undef CHAN_HT
3746 #undef CHAN_HT20
3747 #undef CHAN_HT40U
3748 #undef CHAN_HT40D
3749 }
3750
3751 static void
3752 ath_handle_micerror(struct ieee80211com *ic,
3753         struct ieee80211_frame *wh, int keyix)
3754 {
3755         struct ieee80211_node *ni;
3756
3757         /* XXX recheck MIC to deal w/ chips that lie */
3758         /* XXX discard MIC errors on !data frames */
3759         ni = ieee80211_find_rxnode(ic, (const struct ieee80211_frame_min *) wh);
3760         if (ni != NULL) {
3761                 ieee80211_notify_michael_failure(ni->ni_vap, wh, keyix);
3762                 ieee80211_free_node(ni);
3763         }
3764 }
3765
3766 static void
3767 ath_rx_task(void *arg, int npending)
3768 {
3769 #define PA2DESC(_sc, _pa) \
3770         ((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
3771                 ((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
3772         struct ath_softc *sc = arg;
3773         struct ath_buf *bf;
3774         struct ifnet *ifp;
3775         struct ieee80211com *ic;
3776         struct ath_hal *ah;
3777         struct ath_desc *ds;
3778         struct ath_rx_status *rs;
3779         struct mbuf *m;
3780         struct ieee80211_node *ni;
3781         int len, type, ngood;
3782         u_int phyerr;
3783         HAL_STATUS status;
3784         int16_t nf;
3785         u_int64_t tsf;
3786
3787         wlan_serialize_enter();
3788         ifp = sc->sc_ifp;
3789         ic = ifp->if_l2com;
3790         ah = sc->sc_ah;
3791
3792         DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
3793         ngood = 0;
3794         nf = ath_hal_getchannoise(ah, sc->sc_curchan);
3795         sc->sc_stats.ast_rx_noise = nf;
3796         tsf = ath_hal_gettsf64(ah);
3797         do {
3798                 bf = STAILQ_FIRST(&sc->sc_rxbuf);
3799                 if (bf == NULL) {               /* NB: shouldn't happen */
3800                         if_printf(ifp, "%s: no buffer!\n", __func__);
3801                         break;
3802                 }
3803                 m = bf->bf_m;
3804                 if (m == NULL) {                /* NB: shouldn't happen */
3805                         /*
3806                          * If mbuf allocation failed previously there
3807                          * will be no mbuf; try again to re-populate it.
3808                          */ 
3809                         /* XXX make debug msg */
3810                         if_printf(ifp, "%s: no mbuf!\n", __func__);
3811                         STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
3812                         goto rx_next;
3813                 }
3814                 ds = bf->bf_desc;
3815                 if (ds->ds_link == bf->bf_daddr) {
3816                         /* NB: never process the self-linked entry at the end */
3817                         break;
3818                 }
3819                 /* XXX sync descriptor memory */
3820                 /*
3821                  * Must provide the virtual address of the current
3822                  * descriptor, the physical address, and the virtual
3823                  * address of the next descriptor in the h/w chain.
3824                  * This allows the HAL to look ahead to see if the
3825                  * hardware is done with a descriptor by checking the
3826                  * done bit in the following descriptor and the address
3827                  * of the current descriptor the DMA engine is working
3828                  * on.  All this is necessary because of our use of
3829                  * a self-linked list to avoid rx overruns.
3830                  */
3831                 rs = &bf->bf_status.ds_rxstat;
3832                 status = ath_hal_rxprocdesc(ah, ds,
3833                                 bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
3834 #ifdef ATH_DEBUG
3835                 if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
3836                         ath_printrxbuf(sc, bf, 0, status == HAL_OK);
3837 #endif
3838                 if (status == HAL_EINPROGRESS)
3839                         break;
3840                 STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
3841                 if (rs->rs_status != 0) {
3842                         if (rs->rs_status & HAL_RXERR_CRC)
3843                                 sc->sc_stats.ast_rx_crcerr++;
3844                         if (rs->rs_status & HAL_RXERR_FIFO)
3845                                 sc->sc_stats.ast_rx_fifoerr++;
3846                         if (rs->rs_status & HAL_RXERR_PHY) {
3847                                 sc->sc_stats.ast_rx_phyerr++;
3848                                 phyerr = rs->rs_phyerr & 0x1f;
3849                                 sc->sc_stats.ast_rx_phy[phyerr]++;
3850                                 goto rx_error;  /* NB: don't count in ierrors */
3851                         }
3852                         if (rs->rs_status & HAL_RXERR_DECRYPT) {
3853                                 /*
3854                                  * Decrypt error.  If the error occurred
3855                                  * because there was no hardware key, then
3856                                  * let the frame through so the upper layers
3857                                  * can process it.  This is necessary for 5210
3858                                  * parts which have no way to setup a ``clear''
3859                                  * key cache entry.
3860                                  *
3861                                  * XXX do key cache faulting
3862                                  */
3863                                 if (rs->rs_keyix == HAL_RXKEYIX_INVALID)
3864                                         goto rx_accept;
3865                                 sc->sc_stats.ast_rx_badcrypt++;
3866                         }
3867                         if (rs->rs_status & HAL_RXERR_MIC) {
3868                                 sc->sc_stats.ast_rx_badmic++;
3869                                 /*
3870                                  * Do minimal work required to hand off
3871                                  * the 802.11 header for notification.
3872                                  */
3873                                 /* XXX frag's and qos frames */
3874                                 len = rs->rs_datalen;
3875                                 if (len >= sizeof (struct ieee80211_frame)) {
3876                                         bus_dmamap_sync(sc->sc_dmat,
3877                                             bf->bf_dmamap,
3878                                             BUS_DMASYNC_POSTREAD);
3879                                         ath_handle_micerror(ic, 
3880                                             mtod(m, struct ieee80211_frame *),
3881                                             sc->sc_splitmic ?
3882                                                 rs->rs_keyix-32 : rs->rs_keyix);
3883                                 }
3884                         }
3885                         ifp->if_ierrors++;
3886 rx_error:
3887                         /*
3888                          * Cleanup any pending partial frame.
3889                          */
3890                         if (sc->sc_rxpending != NULL) {
3891                                 m_freem(sc->sc_rxpending);
3892                                 sc->sc_rxpending = NULL;
3893                         }
3894                         /*
3895                          * When a tap is present pass error frames
3896                          * that have been requested.  By default we
3897                          * pass decrypt+mic errors but others may be
3898                          * interesting (e.g. crc).
3899                          */
3900                         if (ieee80211_radiotap_active(ic) &&
3901                             (rs->rs_status & sc->sc_monpass)) {
3902                                 bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3903                                     BUS_DMASYNC_POSTREAD);
3904                                 /* NB: bpf needs the mbuf length setup */
3905                                 len = rs->rs_datalen;
3906                                 m->m_pkthdr.len = m->m_len = len;
3907                                 ath_rx_tap(ifp, m, rs, tsf, nf);
3908                                 ieee80211_radiotap_rx_all(ic, m);
3909                         }
3910                         /* XXX pass MIC errors up for s/w reclaculation */
3911                         goto rx_next;
3912                 }
3913 rx_accept:
3914                 /*
3915                  * Sync and unmap the frame.  At this point we're
3916                  * committed to passing the mbuf somewhere so clear
3917                  * bf_m; this means a new mbuf must be allocated
3918                  * when the rx descriptor is setup again to receive
3919                  * another frame.
3920                  */
3921                 bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3922                     BUS_DMASYNC_POSTREAD);
3923                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3924                 bf->bf_m = NULL;
3925
3926                 len = rs->rs_datalen;
3927                 m->m_len = len;
3928
3929                 if (rs->rs_more) {
3930                         /*
3931                          * Frame spans multiple descriptors; save
3932                          * it for the next completed descriptor, it
3933                          * will be used to construct a jumbogram.
3934                          */
3935                         if (sc->sc_rxpending != NULL) {
3936                                 /* NB: max frame size is currently 2 clusters */
3937                                 sc->sc_stats.ast_rx_toobig++;
3938                                 m_freem(sc->sc_rxpending);
3939                         }
3940                         m->m_pkthdr.rcvif = ifp;
3941                         m->m_pkthdr.len = len;
3942                         sc->sc_rxpending = m;
3943                         goto rx_next;
3944                 } else if (sc->sc_rxpending != NULL) {
3945                         /*
3946                          * This is the second part of a jumbogram,
3947                          * chain it to the first mbuf, adjust the
3948                          * frame length, and clear the rxpending state.
3949                          */
3950                         sc->sc_rxpending->m_next = m;
3951                         sc->sc_rxpending->m_pkthdr.len += len;
3952                         m = sc->sc_rxpending;
3953                         sc->sc_rxpending = NULL;
3954                 } else {
3955                         /*
3956                          * Normal single-descriptor receive; setup
3957                          * the rcvif and packet length.
3958                          */
3959                         m->m_pkthdr.rcvif = ifp;
3960                         m->m_pkthdr.len = len;
3961                 }
3962
3963                 ifp->if_ipackets++;
3964                 sc->sc_stats.ast_ant_rx[rs->rs_antenna]++;
3965
3966                 /*
3967                  * Populate the rx status block.  When there are bpf
3968                  * listeners we do the additional work to provide
3969                  * complete status.  Otherwise we fill in only the
3970                  * material required by ieee80211_input.  Note that
3971                  * noise setting is filled in above.
3972                  */
3973                 if (ieee80211_radiotap_active(ic))
3974                         ath_rx_tap(ifp, m, rs, tsf, nf);
3975
3976                 /*
3977                  * From this point on we assume the frame is at least
3978                  * as large as ieee80211_frame_min; verify that.
3979                  */
3980                 if (len < IEEE80211_MIN_LEN) {
3981                         if (!ieee80211_radiotap_active(ic)) {
3982                                 DPRINTF(sc, ATH_DEBUG_RECV,
3983                                     "%s: short packet %d\n", __func__, len);
3984                                 sc->sc_stats.ast_rx_tooshort++;
3985                         } else {
3986                                 /* NB: in particular this captures ack's */
3987                                 ieee80211_radiotap_rx_all(ic, m);
3988                         }
3989                         m_freem(m);
3990                         goto rx_next;
3991                 }
3992
3993                 if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
3994                         const HAL_RATE_TABLE *rt = sc->sc_currates;
3995                         uint8_t rix = rt->rateCodeToIndex[rs->rs_rate];
3996
3997                         ieee80211_dump_pkt(ic, mtod(m, caddr_t), len,
3998                             sc->sc_hwmap[rix].ieeerate, rs->rs_rssi);
3999                 }
4000
4001                 m_adj(m, -IEEE80211_CRC_LEN);
4002
4003                 /*
4004                  * Locate the node for sender, track state, and then
4005                  * pass the (referenced) node up to the 802.11 layer
4006                  * for its use.
4007                  */
4008                 ni = ieee80211_find_rxnode_withkey(ic,
4009                         mtod(m, const struct ieee80211_frame_min *),
4010                         rs->rs_keyix == HAL_RXKEYIX_INVALID ?
4011                                 IEEE80211_KEYIX_NONE : rs->rs_keyix);
4012                 if (ni != NULL) {
4013                         /*
4014                          * Sending station is known, dispatch directly.
4015                          */
4016                         sc->sc_lastrs = rs;
4017                         type = ieee80211_input(ni, m, rs->rs_rssi, nf);
4018                         ieee80211_free_node(ni);
4019                         /*
4020                          * Arrange to update the last rx timestamp only for
4021                          * frames from our ap when operating in station mode.
4022                          * This assumes the rx key is always setup when
4023                          * associated.
4024                          */
4025                         if (ic->ic_opmode == IEEE80211_M_STA &&
4026                             rs->rs_keyix != HAL_RXKEYIX_INVALID)
4027                                 ngood++;
4028                 } else {
4029                         type = ieee80211_input_all(ic, m, rs->rs_rssi, nf);
4030                 }
4031                 /*
4032                  * Track rx rssi and do any rx antenna management.
4033                  */
4034                 ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, rs->rs_rssi);
4035                 if (sc->sc_diversity) {
4036                         /*
4037                          * When using fast diversity, change the default rx
4038                          * antenna if diversity chooses the other antenna 3
4039                          * times in a row.
4040                          */
4041                         if (sc->sc_defant != rs->rs_antenna) {
4042                                 if (++sc->sc_rxotherant >= 3)
4043                                         ath_setdefantenna(sc, rs->rs_antenna);
4044                         } else
4045                                 sc->sc_rxotherant = 0;
4046                 }
4047                 if (sc->sc_softled) {
4048                         /*
4049                          * Blink for any data frame.  Otherwise do a
4050                          * heartbeat-style blink when idle.  The latter
4051                          * is mainly for station mode where we depend on
4052                          * periodic beacon frames to trigger the poll event.
4053                          */
4054                         if (type == IEEE80211_FC0_TYPE_DATA) {
4055                                 const HAL_RATE_TABLE *rt = sc->sc_currates;
4056                                 ath_led_event(sc, 
4057                                     rt->rateCodeToIndex[rs->rs_rate]);
4058                         } else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
4059                                 ath_led_event(sc, 0);
4060                 }
4061 rx_next:
4062                 STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
4063         } while (ath_rxbuf_init(sc, bf) == 0);
4064
4065         /* rx signal state monitoring */
4066         ath_hal_rxmonitor(ah, &sc->sc_halstats, sc->sc_curchan);
4067         if (ngood)
4068                 sc->sc_lastrx = tsf;
4069
4070         if ((ifp->if_flags & IFF_OACTIVE) == 0) {
4071 #ifdef IEEE80211_SUPPORT_SUPERG
4072                 ieee80211_ff_age_all(ic, 100);
4073 #endif
4074                 if (!ifq_is_empty(&ifp->if_snd))
4075                         ath_start(ifp);
4076         }
4077         wlan_serialize_exit();
4078 #undef PA2DESC
4079 }
4080
4081 static void
4082 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
4083 {
4084         txq->axq_qnum = qnum;
4085         txq->axq_ac = 0;
4086         txq->axq_depth = 0;
4087         txq->axq_intrcnt = 0;
4088         txq->axq_link = NULL;
4089         STAILQ_INIT(&txq->axq_q);
4090 }
4091
4092 /*
4093  * Setup a h/w transmit queue.
4094  */
4095 static struct ath_txq *
4096 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
4097 {
4098         struct ath_hal *ah = sc->sc_ah;
4099         HAL_TXQ_INFO qi;
4100         int qnum;
4101
4102         memset(&qi, 0, sizeof(qi));
4103         qi.tqi_subtype = subtype;
4104         qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
4105         qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
4106         qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
4107         /*
4108          * Enable interrupts only for EOL and DESC conditions.
4109          * We mark tx descriptors to receive a DESC interrupt
4110          * when a tx queue gets deep; otherwise waiting for the
4111          * EOL to reap descriptors.  Note that this is done to
4112          * reduce interrupt load and this only defers reaping
4113          * descriptors, never transmitting frames.  Aside from
4114          * reducing interrupts this also permits more concurrency.
4115          * The only potential downside is if the tx queue backs
4116          * up in which case the top half of the kernel may backup
4117          * due to a lack of tx descriptors.
4118          */
4119         qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
4120         qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
4121         if (qnum == -1) {
4122                 /*
4123                  * NB: don't print a message, this happens
4124                  * normally on parts with too few tx queues
4125                  */
4126                 return NULL;
4127         }
4128         if (qnum >= NELEM(sc->sc_txq)) {
4129                 device_printf(sc->sc_dev,
4130                         "hal qnum %u out of range, max %zu!\n",
4131                         qnum, NELEM(sc->sc_txq));
4132                 ath_hal_releasetxqueue(ah, qnum);
4133                 return NULL;
4134         }
4135         if (!ATH_TXQ_SETUP(sc, qnum)) {
4136                 ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
4137                 sc->sc_txqsetup |= 1<<qnum;
4138         }
4139         return &sc->sc_txq[qnum];
4140 }
4141
4142 /*
4143  * Setup a hardware data transmit queue for the specified
4144  * access control.  The hal may not support all requested
4145  * queues in which case it will return a reference to a
4146  * previously setup queue.  We record the mapping from ac's
4147  * to h/w queues for use by ath_tx_start and also track
4148  * the set of h/w queues being used to optimize work in the
4149  * transmit interrupt handler and related routines.
4150  */
4151 static int
4152 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
4153 {
4154         struct ath_txq *txq;
4155
4156         if (ac >= NELEM(sc->sc_ac2q)) {
4157                 device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
4158                         ac, NELEM(sc->sc_ac2q));
4159                 return 0;
4160         }
4161         txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
4162         if (txq != NULL) {
4163                 txq->axq_ac = ac;
4164                 sc->sc_ac2q[ac] = txq;
4165                 return 1;
4166         } else
4167                 return 0;
4168 }
4169
4170 /*
4171  * Update WME parameters for a transmit queue.
4172  */
4173 static int
4174 ath_txq_update(struct ath_softc *sc, int ac)
4175 {
4176 #define ATH_EXPONENT_TO_VALUE(v)        ((1<<v)-1)
4177 #define ATH_TXOP_TO_US(v)               (v<<5)
4178         struct ifnet *ifp = sc->sc_ifp;
4179         struct ieee80211com *ic = ifp->if_l2com;
4180         struct ath_txq *txq = sc->sc_ac2q[ac];
4181         struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
4182         struct ath_hal *ah = sc->sc_ah;
4183         HAL_TXQ_INFO qi;
4184
4185         ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
4186 #ifdef IEEE80211_SUPPORT_TDMA
4187         if (sc->sc_tdma) {
4188                 /*
4189                  * AIFS is zero so there's no pre-transmit wait.  The
4190                  * burst time defines the slot duration and is configured
4191                  * through net80211.  The QCU is setup to not do post-xmit
4192                  * back off, lockout all lower-priority QCU's, and fire
4193                  * off the DMA beacon alert timer which is setup based
4194                  * on the slot configuration.
4195                  */
4196                 qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4197                               | HAL_TXQ_TXERRINT_ENABLE
4198                               | HAL_TXQ_TXURNINT_ENABLE
4199                               | HAL_TXQ_TXEOLINT_ENABLE
4200                               | HAL_TXQ_DBA_GATED
4201                               | HAL_TXQ_BACKOFF_DISABLE
4202                               | HAL_TXQ_ARB_LOCKOUT_GLOBAL
4203                               ;
4204                 qi.tqi_aifs = 0;
4205                 /* XXX +dbaprep? */
4206                 qi.tqi_readyTime = sc->sc_tdmaslotlen;
4207                 qi.tqi_burstTime = qi.tqi_readyTime;
4208         } else {
4209 #endif
4210                 qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4211                               | HAL_TXQ_TXERRINT_ENABLE
4212                               | HAL_TXQ_TXDESCINT_ENABLE
4213                               | HAL_TXQ_TXURNINT_ENABLE
4214                               ;
4215                 qi.tqi_aifs = wmep->wmep_aifsn;
4216                 qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
4217                 qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
4218                 qi.tqi_readyTime = 0;
4219                 qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
4220 #ifdef IEEE80211_SUPPORT_TDMA
4221         }
4222 #endif
4223
4224         DPRINTF(sc, ATH_DEBUG_RESET,
4225             "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
4226             __func__, txq->axq_qnum, qi.tqi_qflags,
4227             qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
4228
4229         if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
4230                 if_printf(ifp, "unable to update hardware queue "
4231                         "parameters for %s traffic!\n",
4232                         ieee80211_wme_acnames[ac]);
4233                 return 0;
4234         } else {
4235                 ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
4236                 return 1;
4237         }
4238 #undef ATH_TXOP_TO_US
4239 #undef ATH_EXPONENT_TO_VALUE
4240 }
4241
4242 /*
4243  * Callback from the 802.11 layer to update WME parameters.
4244  */
4245 static int
4246 ath_wme_update(struct ieee80211com *ic)
4247 {
4248         struct ath_softc *sc = ic->ic_ifp->if_softc;
4249
4250         return !ath_txq_update(sc, WME_AC_BE) ||
4251             !ath_txq_update(sc, WME_AC_BK) ||
4252             !ath_txq_update(sc, WME_AC_VI) ||
4253             !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
4254 }
4255
4256 /*
4257  * Reclaim resources for a setup queue.
4258  */
4259 static void
4260 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
4261 {
4262
4263         ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
4264         sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
4265 }
4266
4267 /*
4268  * Reclaim all tx queue resources.
4269  */
4270 static void
4271 ath_tx_cleanup(struct ath_softc *sc)
4272 {
4273         int i;
4274
4275         for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4276                 if (ATH_TXQ_SETUP(sc, i))
4277                         ath_tx_cleanupq(sc, &sc->sc_txq[i]);
4278 }
4279
4280 /*
4281  * Return h/w rate index for an IEEE rate (w/o basic rate bit)
4282  * using the current rates in sc_rixmap.
4283  */
4284 static __inline int
4285 ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
4286 {
4287         int rix = sc->sc_rixmap[rate];
4288         /* NB: return lowest rix for invalid rate */
4289         return (rix == 0xff ? 0 : rix);
4290 }
4291
4292 /*
4293  * Reclaim mbuf resources.  For fragmented frames we
4294  * need to claim each frag chained with m_nextpkt.
4295  */
4296 static void
4297 ath_freetx(struct mbuf *m)
4298 {
4299         struct mbuf *next;
4300
4301         do {
4302                 next = m->m_nextpkt;
4303                 m->m_nextpkt = NULL;
4304                 m_freem(m);
4305         } while ((m = next) != NULL);
4306 }
4307
4308 static int
4309 ath_tx_dmasetup(struct ath_softc *sc, struct ath_buf *bf, struct mbuf *m0)
4310 {
4311         int error;
4312
4313         /*
4314          * 
4315          * Load the DMA map so any coalescing is done.  This
4316          * also calculates the number of descriptors we need.
4317          */
4318         error = bus_dmamap_load_mbuf_defrag(sc->sc_dmat, bf->bf_dmamap, &m0,
4319                                      bf->bf_segs, ATH_TXDESC,
4320                                      &bf->bf_nseg, BUS_DMA_NOWAIT);
4321         if (error != 0) {
4322                 sc->sc_stats.ast_tx_busdma++;
4323                 ath_freetx(m0);
4324                 return error;
4325         }
4326
4327         /*
4328          * Discard null packets.
4329          */
4330         if (bf->bf_nseg == 0) {         /* null packet, discard */
4331                 sc->sc_stats.ast_tx_nodata++;
4332                 ath_freetx(m0);
4333                 return EIO;
4334         }
4335         DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n",
4336                 __func__, m0, m0->m_pkthdr.len);
4337         bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
4338         bf->bf_m = m0;
4339
4340         return 0;
4341 }
4342
4343 static void
4344 ath_tx_handoff(struct ath_softc *sc, struct ath_txq *txq, struct ath_buf *bf)
4345 {
4346         struct ath_hal *ah = sc->sc_ah;
4347         struct ath_desc *ds, *ds0;
4348         int i;
4349
4350         /*
4351          * Fillin the remainder of the descriptor info.
4352          */
4353         ds0 = ds = bf->bf_desc;
4354         for (i = 0; i < bf->bf_nseg; i++, ds++) {
4355                 ds->ds_data = bf->bf_segs[i].ds_addr;
4356                 if (i == bf->bf_nseg - 1)
4357                         ds->ds_link = 0;
4358                 else
4359                         ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
4360                 ath_hal_filltxdesc(ah, ds
4361                         , bf->bf_segs[i].ds_len /* segment length */
4362                         , i == 0                /* first segment */
4363                         , i == bf->bf_nseg - 1  /* last segment */
4364                         , ds0                   /* first descriptor */
4365                 );
4366                 DPRINTF(sc, ATH_DEBUG_XMIT,
4367                         "%s: %d: %08x %08x %08x %08x %08x %08x\n",
4368                         __func__, i, ds->ds_link, ds->ds_data,
4369                         ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
4370         }
4371         /*
4372          * Insert the frame on the outbound list and pass it on
4373          * to the hardware.  Multicast frames buffered for power
4374          * save stations and transmit from the CAB queue are stored
4375          * on a s/w only queue and loaded on to the CAB queue in
4376          * the SWBA handler since frames only go out on DTIM and
4377          * to avoid possible races.
4378          */
4379         KASSERT((bf->bf_flags & ATH_BUF_BUSY) == 0,
4380              ("busy status 0x%x", bf->bf_flags));
4381         if (txq->axq_qnum != ATH_TXQ_SWQ) {
4382 #ifdef IEEE80211_SUPPORT_TDMA
4383                 /*
4384                  * Supporting transmit dma.  If the queue is busy it is
4385                  * impossible to determine if we've won the race against
4386                  * the chipset checking the link field or not, so we don't
4387                  * try.  Instead we let the TX interrupt detect the case
4388                  * and restart the transmitter.
4389                  *
4390                  * If the queue is not busy we can start things rolling
4391                  * right here.
4392                  */
4393                 int qbusy;
4394
4395                 ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4396                 qbusy = ath_hal_txqenabled(ah, txq->axq_qnum);
4397
4398                 if (qbusy == 0) {
4399                         if (txq->axq_link != NULL) {
4400                                 /*
4401                                  * We had already started one previously but
4402                                  * not yet processed the TX interrupt.  Don't
4403                                  * try to race a restart because we do not
4404                                  * know where it stopped, let the TX interrupt
4405                                  * restart us when it figures out where we
4406                                  * stopped.
4407                                  */
4408                                 cpu_sfence();
4409                                 *txq->axq_link = bf->bf_daddr;
4410                                 txq->axq_flags |= ATH_TXQ_PUTPENDING;
4411                         } else {
4412                                 /*
4413                                  * We are first in line, we can safely start
4414                                  * at this address.
4415                                  */
4416                                 cpu_sfence();
4417                                 ath_hal_puttxbuf(ah, txq->axq_qnum,
4418                                                  bf->bf_daddr);
4419                         }
4420                 } else {
4421                         /*
4422                          * The queue is busy, go ahead and link us in but
4423                          * do not try to start/restart the tx.  We just
4424                          * don't know whether it will pick up our link
4425                          * or not and we don't want to double-xmit.
4426                          */
4427                         if (txq->axq_link != NULL) {
4428                                 cpu_sfence();
4429                                 *txq->axq_link = bf->bf_daddr;
4430                         }
4431                         txq->axq_flags |= ATH_TXQ_PUTPENDING;
4432                 }
4433 #if 0
4434                                 ath_hal_puttxbuf(ah, txq->axq_qnum,
4435                                         STAILQ_FIRST(&txq->axq_q)->bf_daddr);
4436 #endif
4437 #else
4438                 ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4439                 if (txq->axq_link == NULL) {
4440                         ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
4441                         DPRINTF(sc, ATH_DEBUG_XMIT,
4442                             "%s: TXDP[%u] = %p (%p) depth %d\n",
4443                             __func__, txq->axq_qnum,
4444                             (caddr_t)bf->bf_daddr, bf->bf_desc,
4445                             txq->axq_depth);
4446                 } else {
4447                         *txq->axq_link = bf->bf_daddr;
4448                         DPRINTF(sc, ATH_DEBUG_XMIT,
4449                             "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
4450                             txq->axq_qnum, txq->axq_link,
4451                             (caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
4452                 }
4453 #endif /* IEEE80211_SUPPORT_TDMA */
4454                 txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
4455                 ath_hal_txstart(ah, txq->axq_qnum);
4456         } else {
4457                 if (txq->axq_link != NULL) {
4458                         struct ath_buf *last = ATH_TXQ_LAST(txq);
4459                         struct ieee80211_frame *wh;
4460
4461                         /* mark previous frame */
4462                         wh = mtod(last->bf_m, struct ieee80211_frame *);
4463                         wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
4464                         bus_dmamap_sync(sc->sc_dmat, last->bf_dmamap,
4465                             BUS_DMASYNC_PREWRITE);
4466
4467                         /* link descriptor */
4468                         *txq->axq_link = bf->bf_daddr;
4469                 }
4470                 ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4471                 txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
4472         }
4473 }
4474
4475 static int
4476 ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
4477     struct mbuf *m0)
4478 {
4479         struct ieee80211vap *vap = ni->ni_vap;
4480         struct ath_vap *avp = ATH_VAP(vap);
4481         struct ath_hal *ah = sc->sc_ah;
4482         struct ifnet *ifp = sc->sc_ifp;
4483         struct ieee80211com *ic = ifp->if_l2com;
4484         const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
4485         int error, iswep, ismcast, isfrag, ismrr;
4486         int keyix, hdrlen, pktlen, try0;
4487         u_int8_t rix, txrate, ctsrate;
4488         u_int8_t cix = 0xff;            /* NB: silence compiler */
4489         struct ath_desc *ds;
4490         struct ath_txq *txq;
4491         struct ieee80211_frame *wh;
4492         u_int subtype, flags, ctsduration;
4493         HAL_PKT_TYPE atype;
4494         const HAL_RATE_TABLE *rt;
4495         HAL_BOOL shortPreamble;
4496         struct ath_node *an;
4497         u_int pri;
4498
4499         wh = mtod(m0, struct ieee80211_frame *);
4500         iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
4501         ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
4502         isfrag = m0->m_flags & M_FRAG;
4503         hdrlen = ieee80211_anyhdrsize(wh);
4504         /*
4505          * Packet length must not include any
4506          * pad bytes; deduct them here.
4507          */
4508         pktlen = m0->m_pkthdr.len - (hdrlen & 3);
4509
4510         if (iswep) {
4511                 const struct ieee80211_cipher *cip;
4512                 struct ieee80211_key *k;
4513
4514                 /*
4515                  * Construct the 802.11 header+trailer for an encrypted
4516                  * frame. The only reason this can fail is because of an
4517                  * unknown or unsupported cipher/key type.
4518                  */
4519                 k = ieee80211_crypto_encap(ni, m0);
4520                 if (k == NULL) {
4521                         /*
4522                          * This can happen when the key is yanked after the
4523                          * frame was queued.  Just discard the frame; the
4524                          * 802.11 layer counts failures and provides
4525                          * debugging/diagnostics.
4526                          */
4527                         ath_freetx(m0);
4528                         return EIO;
4529                 }
4530                 /*
4531                  * Adjust the packet + header lengths for the crypto
4532                  * additions and calculate the h/w key index.  When
4533                  * a s/w mic is done the frame will have had any mic
4534                  * added to it prior to entry so m0->m_pkthdr.len will
4535                  * account for it. Otherwise we need to add it to the
4536                  * packet length.
4537                  */
4538                 cip = k->wk_cipher;
4539                 hdrlen += cip->ic_header;
4540                 pktlen += cip->ic_header + cip->ic_trailer;
4541                 /* NB: frags always have any TKIP MIC done in s/w */
4542                 if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && !isfrag)
4543                         pktlen += cip->ic_miclen;
4544                 keyix = k->wk_keyix;
4545
4546                 /* packet header may have moved, reset our local pointer */
4547                 wh = mtod(m0, struct ieee80211_frame *);
4548         } else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
4549                 /*
4550                  * Use station key cache slot, if assigned.
4551                  */
4552                 keyix = ni->ni_ucastkey.wk_keyix;
4553                 if (keyix == IEEE80211_KEYIX_NONE)
4554                         keyix = HAL_TXKEYIX_INVALID;
4555         } else
4556                 keyix = HAL_TXKEYIX_INVALID;
4557
4558         pktlen += IEEE80211_CRC_LEN;
4559
4560         /*
4561          * Load the DMA map so any coalescing is done.  This
4562          * also calculates the number of descriptors we need.
4563          */
4564         error = ath_tx_dmasetup(sc, bf, m0);
4565         if (error != 0) {
4566                 return error;
4567         }
4568         bf->bf_node = ni;                       /* NB: held reference */
4569         m0 = bf->bf_m;                          /* NB: may have changed */
4570         wh = mtod(m0, struct ieee80211_frame *);
4571
4572         /* setup descriptors */
4573         ds = bf->bf_desc;
4574         rt = sc->sc_currates;
4575         KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
4576
4577         /*
4578          * NB: the 802.11 layer marks whether or not we should
4579          * use short preamble based on the current mode and
4580          * negotiated parameters.
4581          */
4582         if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
4583             (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
4584                 shortPreamble = AH_TRUE;
4585                 sc->sc_stats.ast_tx_shortpre++;
4586         } else {
4587                 shortPreamble = AH_FALSE;
4588         }
4589
4590         an = ATH_NODE(ni);
4591         flags = HAL_TXDESC_CLRDMASK;            /* XXX needed for crypto errs */
4592         ismrr = 0;                              /* default no multi-rate retry*/
4593         pri = M_WME_GETAC(m0);                  /* honor classification */
4594         /* XXX use txparams instead of fixed values */
4595         /*
4596          * Calculate Atheros packet type from IEEE80211 packet header,
4597          * setup for rate calculations, and select h/w transmit queue.
4598          */
4599         switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
4600         case IEEE80211_FC0_TYPE_MGT:
4601                 subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
4602                 if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
4603                         atype = HAL_PKT_TYPE_BEACON;
4604                 else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
4605                         atype = HAL_PKT_TYPE_PROBE_RESP;
4606                 else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
4607                         atype = HAL_PKT_TYPE_ATIM;
4608                 else
4609                         atype = HAL_PKT_TYPE_NORMAL;    /* XXX */
4610                 rix = an->an_mgmtrix;
4611                 txrate = rt->info[rix].rateCode;
4612                 if (shortPreamble)
4613                         txrate |= rt->info[rix].shortPreamble;
4614                 try0 = ATH_TXMGTTRY;
4615                 flags |= HAL_TXDESC_INTREQ;     /* force interrupt */
4616                 break;
4617         case IEEE80211_FC0_TYPE_CTL:
4618                 atype = HAL_PKT_TYPE_PSPOLL;    /* stop setting of duration */
4619                 rix = an->an_mgmtrix;
4620                 txrate = rt->info[rix].rateCode;
4621                 if (shortPreamble)
4622                         txrate |= rt->info[rix].shortPreamble;
4623                 try0 = ATH_TXMGTTRY;
4624                 flags |= HAL_TXDESC_INTREQ;     /* force interrupt */
4625                 break;
4626         case IEEE80211_FC0_TYPE_DATA:
4627                 atype = HAL_PKT_TYPE_NORMAL;            /* default */
4628                 /*
4629                  * Data frames: multicast frames go out at a fixed rate,
4630                  * EAPOL frames use the mgmt frame rate; otherwise consult
4631                  * the rate control module for the rate to use.
4632                  */
4633                 if (ismcast) {
4634                         rix = an->an_mcastrix;
4635                         txrate = rt->info[rix].rateCode;
4636                         if (shortPreamble)
4637                                 txrate |= rt->info[rix].shortPreamble;
4638                         try0 = 1;
4639                 } else if (m0->m_flags & M_EAPOL) {
4640                         /* XXX? maybe always use long preamble? */
4641                         rix = an->an_mgmtrix;
4642                         txrate = rt->info[rix].rateCode;
4643                         if (shortPreamble)
4644                                 txrate |= rt->info[rix].shortPreamble;
4645                         try0 = ATH_TXMAXTRY;    /* XXX?too many? */
4646                 } else {
4647                         ath_rate_findrate(sc, an, shortPreamble, pktlen,
4648                                 &rix, &try0, &txrate);
4649                         sc->sc_txrix = rix;             /* for LED blinking */
4650                         sc->sc_lastdatarix = rix;       /* for fast frames */
4651                         if (try0 != ATH_TXMAXTRY)
4652                                 ismrr = 1;
4653                 }
4654                 if (cap->cap_wmeParams[pri].wmep_noackPolicy)
4655                         flags |= HAL_TXDESC_NOACK;
4656                 break;
4657         default:
4658                 if_printf(ifp, "bogus frame type 0x%x (%s)\n",
4659                         wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
4660                 /* XXX statistic */
4661                 ath_freetx(m0);
4662                 return EIO;
4663         }
4664         txq = sc->sc_ac2q[pri];
4665
4666         /*
4667          * When servicing one or more stations in power-save mode
4668          * (or) if there is some mcast data waiting on the mcast
4669          * queue (to prevent out of order delivery) multicast
4670          * frames must be buffered until after the beacon.
4671          */
4672         if (ismcast && (vap->iv_ps_sta || avp->av_mcastq.axq_depth))
4673                 txq = &avp->av_mcastq;
4674
4675         /*
4676          * Calculate miscellaneous flags.
4677          */
4678         if (ismcast) {
4679                 flags |= HAL_TXDESC_NOACK;      /* no ack on broad/multicast */
4680         } else if (pktlen > vap->iv_rtsthreshold &&
4681             (ni->ni_ath_flags & IEEE80211_NODE_FF) == 0) {
4682                 flags |= HAL_TXDESC_RTSENA;     /* RTS based on frame length */
4683                 cix = rt->info[rix].controlRate;
4684                 sc->sc_stats.ast_tx_rts++;
4685         }
4686         if (flags & HAL_TXDESC_NOACK)           /* NB: avoid double counting */
4687                 sc->sc_stats.ast_tx_noack++;
4688 #ifdef IEEE80211_SUPPORT_TDMA
4689         if (sc->sc_tdma && (flags & HAL_TXDESC_NOACK) == 0) {
4690                 DPRINTF(sc, ATH_DEBUG_TDMA,
4691                     "%s: discard frame, ACK required w/ TDMA\n", __func__);
4692                 sc->sc_stats.ast_tdma_ack++;
4693                 ath_freetx(m0);
4694                 return EIO;
4695         }
4696 #endif
4697
4698         /*
4699          * If 802.11g protection is enabled, determine whether
4700          * to use RTS/CTS or just CTS.  Note that this is only
4701          * done for OFDM unicast frames.
4702          */
4703         if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
4704             rt->info[rix].phy == IEEE80211_T_OFDM &&
4705             (flags & HAL_TXDESC_NOACK) == 0) {
4706                 /* XXX fragments must use CCK rates w/ protection */
4707                 if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
4708                         flags |= HAL_TXDESC_RTSENA;
4709                 else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
4710                         flags |= HAL_TXDESC_CTSENA;
4711                 if (isfrag) {
4712                         /*
4713                          * For frags it would be desirable to use the
4714                          * highest CCK rate for RTS/CTS.  But stations
4715                          * farther away may detect it at a lower CCK rate
4716                          * so use the configured protection rate instead
4717                          * (for now).
4718                          */
4719                         cix = rt->info[sc->sc_protrix].controlRate;
4720                 } else
4721                         cix = rt->info[sc->sc_protrix].controlRate;
4722                 sc->sc_stats.ast_tx_protect++;
4723         }
4724
4725         /*
4726          * Calculate duration.  This logically belongs in the 802.11
4727          * layer but it lacks sufficient information to calculate it.
4728          */
4729         if ((flags & HAL_TXDESC_NOACK) == 0 &&
4730             (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
4731                 u_int16_t dur;
4732                 if (shortPreamble)
4733                         dur = rt->info[rix].spAckDuration;
4734                 else
4735                         dur = rt->info[rix].lpAckDuration;
4736                 if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG) {
4737                         dur += dur;             /* additional SIFS+ACK */
4738                         KASSERT(m0->m_nextpkt != NULL, ("no fragment"));
4739                         /*
4740                          * Include the size of next fragment so NAV is
4741                          * updated properly.  The last fragment uses only
4742                          * the ACK duration
4743                          */
4744                         dur += ath_hal_computetxtime(ah, rt,
4745                                         m0->m_nextpkt->m_pkthdr.len,
4746                                         rix, shortPreamble);
4747                 }
4748                 if (isfrag) {
4749                         /*
4750                          * Force hardware to use computed duration for next
4751                          * fragment by disabling multi-rate retry which updates
4752                          * duration based on the multi-rate duration table.
4753                          */
4754                         ismrr = 0;
4755                         try0 = ATH_TXMGTTRY;    /* XXX? */
4756                 }
4757                 *(u_int16_t *)wh->i_dur = htole16(dur);
4758         }
4759
4760         /*
4761          * Calculate RTS/CTS rate and duration if needed.
4762          */
4763         ctsduration = 0;
4764         if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
4765                 /*
4766                  * CTS transmit rate is derived from the transmit rate
4767                  * by looking in the h/w rate table.  We must also factor
4768                  * in whether or not a short preamble is to be used.
4769                  */
4770                 /* NB: cix is set above where RTS/CTS is enabled */
4771                 KASSERT(cix != 0xff, ("cix not setup"));
4772                 ctsrate = rt->info[cix].rateCode;
4773                 /*
4774                  * Compute the transmit duration based on the frame
4775                  * size and the size of an ACK frame.  We call into the
4776                  * HAL to do the computation since it depends on the
4777                  * characteristics of the actual PHY being used.
4778                  *
4779                  * NB: CTS is assumed the same size as an ACK so we can
4780                  *     use the precalculated ACK durations.
4781                  */
4782                 if (shortPreamble) {
4783                         ctsrate |= rt->info[cix].shortPreamble;
4784                         if (flags & HAL_TXDESC_RTSENA)          /* SIFS + CTS */
4785                                 ctsduration += rt->info[cix].spAckDuration;
4786                         ctsduration += ath_hal_computetxtime(ah,
4787                                 rt, pktlen, rix, AH_TRUE);
4788                         if ((flags & HAL_TXDESC_NOACK) == 0)    /* SIFS + ACK */
4789                                 ctsduration += rt->info[rix].spAckDuration;
4790                 } else {
4791                         if (flags & HAL_TXDESC_RTSENA)          /* SIFS + CTS */
4792                                 ctsduration += rt->info[cix].lpAckDuration;
4793                         ctsduration += ath_hal_computetxtime(ah,
4794                                 rt, pktlen, rix, AH_FALSE);
4795                         if ((flags & HAL_TXDESC_NOACK) == 0)    /* SIFS + ACK */
4796                                 ctsduration += rt->info[rix].lpAckDuration;
4797                 }
4798                 /*
4799                  * Must disable multi-rate retry when using RTS/CTS.
4800                  */
4801                 ismrr = 0;
4802                 try0 = ATH_TXMGTTRY;            /* XXX */
4803         } else
4804                 ctsrate = 0;
4805
4806         /*
4807          * At this point we are committed to sending the frame
4808          * and we don't need to look at m_nextpkt; clear it in
4809          * case this frame is part of frag chain.
4810          */
4811         m0->m_nextpkt = NULL;
4812
4813         if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
4814                 ieee80211_dump_pkt(ic, mtod(m0, const uint8_t *), m0->m_len,
4815                     sc->sc_hwmap[rix].ieeerate, -1);
4816
4817         if (ieee80211_radiotap_active_vap(vap)) {
4818                 u_int64_t tsf = ath_hal_gettsf64(ah);
4819
4820                 sc->sc_tx_th.wt_tsf = htole64(tsf);
4821                 sc->sc_tx_th.wt_flags = sc->sc_hwmap[rix].txflags;
4822                 if (iswep)
4823                         sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
4824                 if (isfrag)
4825                         sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
4826                 sc->sc_tx_th.wt_rate = sc->sc_hwmap[rix].ieeerate;
4827                 sc->sc_tx_th.wt_txpower = ni->ni_txpower;
4828                 sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
4829
4830                 ieee80211_radiotap_tx(vap, m0);
4831         }
4832
4833         /*
4834          * Determine if a tx interrupt should be generated for
4835          * this descriptor.  We take a tx interrupt to reap
4836          * descriptors when the h/w hits an EOL condition or
4837          * when the descriptor is specifically marked to generate
4838          * an interrupt.  We periodically mark descriptors in this
4839          * way to insure timely replenishing of the supply needed
4840          * for sending frames.  Defering interrupts reduces system
4841          * load and potentially allows more concurrent work to be
4842          * done but if done to aggressively can cause senders to
4843          * backup.
4844          *
4845          * NB: use >= to deal with sc_txintrperiod changing
4846          *     dynamically through sysctl.
4847          */
4848         if (flags & HAL_TXDESC_INTREQ) {
4849                 txq->axq_intrcnt = 0;
4850         } else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
4851                 flags |= HAL_TXDESC_INTREQ;
4852                 txq->axq_intrcnt = 0;
4853         }
4854
4855         /*
4856          * Formulate first tx descriptor with tx controls.
4857          */
4858         /* XXX check return value? */
4859         ath_hal_setuptxdesc(ah, ds
4860                 , pktlen                /* packet length */
4861                 , hdrlen                /* header length */
4862                 , atype                 /* Atheros packet type */
4863                 , ni->ni_txpower        /* txpower */
4864                 , txrate, try0          /* series 0 rate/tries */
4865                 , keyix                 /* key cache index */
4866                 , sc->sc_txantenna      /* antenna mode */
4867                 , flags                 /* flags */
4868                 , ctsrate               /* rts/cts rate */
4869                 , ctsduration           /* rts/cts duration */
4870         );
4871         bf->bf_txflags = flags;
4872         /*
4873          * Setup the multi-rate retry state only when we're
4874          * going to use it.  This assumes ath_hal_setuptxdesc
4875          * initializes the descriptors (so we don't have to)
4876          * when the hardware supports multi-rate retry and
4877          * we don't use it.
4878          */
4879         if (ismrr)
4880                 ath_rate_setupxtxdesc(sc, an, ds, shortPreamble, rix);
4881
4882         ath_tx_handoff(sc, txq, bf);
4883         return 0;
4884 }
4885
4886 /*
4887  * Process completed xmit descriptors from the specified queue.
4888  */
4889 static int
4890 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
4891 {
4892         struct ath_hal *ah = sc->sc_ah;
4893         struct ifnet *ifp = sc->sc_ifp;
4894         struct ieee80211com *ic = ifp->if_l2com;
4895         struct ath_buf *bf, *last;
4896         struct ath_desc *ds, *ds0;
4897         struct ath_tx_status *ts;
4898         struct ieee80211_node *ni;
4899         struct ath_node *an;
4900         int sr, lr, pri, nacked;
4901         HAL_STATUS status;
4902
4903         DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
4904                 __func__, txq->axq_qnum,
4905                 (caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4906                 txq->axq_link);
4907         nacked = 0;
4908         for (;;) {
4909                 int qbusy;
4910
4911                 txq->axq_intrcnt = 0;   /* reset periodic desc intr count */
4912                 bf = STAILQ_FIRST(&txq->axq_q);
4913                 if (bf == NULL)
4914                         break;
4915                 ds0 = &bf->bf_desc[0];
4916                 ds = &bf->bf_desc[bf->bf_nseg - 1];
4917                 ts = &bf->bf_status.ds_txstat;
4918                 qbusy = ath_hal_txqenabled(ah, txq->axq_qnum);
4919                 status = ath_hal_txprocdesc(ah, ds, ts);
4920 #ifdef ATH_DEBUG
4921                 if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
4922                         ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4923                             status == HAL_OK);
4924 #endif
4925                 if (status == HAL_EINPROGRESS) {
4926 #ifdef IEEE80211_SUPPORT_TDMA
4927                         /*
4928                          * If not done and the queue is not busy then the
4929                          * transmitter raced the hardware on the link field
4930                          * and we have to restart it.
4931                          */
4932                         if (!qbusy) {
4933                                 cpu_sfence();
4934                                 ath_hal_puttxbuf(ah, txq->axq_qnum,
4935                                                  bf->bf_daddr);
4936                                 ath_hal_txstart(ah, txq->axq_qnum);
4937                         }
4938 #endif
4939                         break;
4940                 }
4941                 ATH_TXQ_REMOVE_HEAD(txq, bf_list);
4942 #ifdef IEEE80211_SUPPORT_TDMA
4943                 if (txq->axq_depth > 0) {
4944                         /*
4945                          * More frames follow.  Mark the buffer busy
4946                          * so it's not re-used while the hardware may
4947                          * still re-read the link field in the descriptor.
4948                          */
4949                         bf->bf_flags |= ATH_BUF_BUSY;
4950                 } else
4951 #else
4952                 if (txq->axq_depth == 0)
4953 #endif
4954                         txq->axq_link = NULL;
4955
4956                 ni = bf->bf_node;
4957                 if (ni != NULL) {
4958                         an = ATH_NODE(ni);
4959                         if (ts->ts_status == 0) {
4960                                 u_int8_t txant = ts->ts_antenna;
4961                                 sc->sc_stats.ast_ant_tx[txant]++;
4962                                 sc->sc_ant_tx[txant]++;
4963                                 if (ts->ts_finaltsi != 0)
4964                                         sc->sc_stats.ast_tx_altrate++;
4965                                 pri = M_WME_GETAC(bf->bf_m);
4966                                 if (pri >= WME_AC_VO)
4967                                         ic->ic_wme.wme_hipri_traffic++;
4968                                 if ((bf->bf_txflags & HAL_TXDESC_NOACK) == 0)
4969                                         ni->ni_inact = ni->ni_inact_reload;
4970                         } else {
4971                                 if (ts->ts_status & HAL_TXERR_XRETRY)
4972                                         sc->sc_stats.ast_tx_xretries++;
4973                                 if (ts->ts_status & HAL_TXERR_FIFO)
4974                                         sc->sc_stats.ast_tx_fifoerr++;
4975                                 if (ts->ts_status & HAL_TXERR_FILT)
4976                                         sc->sc_stats.ast_tx_filtered++;
4977                                 if (bf->bf_m->m_flags & M_FF)
4978                                         sc->sc_stats.ast_ff_txerr++;
4979                         }
4980                         sr = ts->ts_shortretry;
4981                         lr = ts->ts_longretry;
4982                         sc->sc_stats.ast_tx_shortretry += sr;
4983                         sc->sc_stats.ast_tx_longretry += lr;
4984                         /*
4985                          * Hand the descriptor to the rate control algorithm.
4986                          */
4987                         if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
4988                             (bf->bf_txflags & HAL_TXDESC_NOACK) == 0) {
4989                                 /*
4990                                  * If frame was ack'd update statistics,
4991                                  * including the last rx time used to
4992                                  * workaround phantom bmiss interrupts.
4993                                  */
4994                                 if (ts->ts_status == 0) {
4995                                         nacked++;
4996                                         sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
4997                                         ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
4998                                                 ts->ts_rssi);
4999                                 }
5000                                 ath_rate_tx_complete(sc, an, bf);
5001                         }
5002                         /*
5003                          * Do any tx complete callback.  Note this must
5004                          * be done before releasing the node reference.
5005                          */
5006                         if (bf->bf_m->m_flags & M_TXCB)
5007                                 ieee80211_process_callback(ni, bf->bf_m,
5008                                     (bf->bf_txflags & HAL_TXDESC_NOACK) == 0 ?
5009                                         ts->ts_status : HAL_TXERR_XRETRY);
5010                         ieee80211_free_node(ni);
5011                 }
5012                 bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
5013                     BUS_DMASYNC_POSTWRITE);
5014                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
5015
5016                 m_freem(bf->bf_m);
5017                 bf->bf_m = NULL;
5018                 bf->bf_node = NULL;
5019
5020                 last = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
5021                 if (last != NULL)
5022                         last->bf_flags &= ~ATH_BUF_BUSY;
5023                 STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5024         }
5025 #ifdef IEEE80211_SUPPORT_SUPERG
5026         /*
5027          * Flush fast-frame staging queue when traffic slows.
5028          */
5029         if (txq->axq_depth <= 1)
5030                 ieee80211_ff_flush(ic, txq->axq_ac);
5031 #endif
5032         return nacked;
5033 }
5034
5035 static __inline int
5036 txqactive(struct ath_hal *ah, int qnum)
5037 {
5038         u_int32_t txqs = 1<<qnum;
5039         ath_hal_gettxintrtxqs(ah, &txqs);
5040         return (txqs & (1<<qnum));
5041 }
5042
5043 /*
5044  * Deferred processing of transmit interrupt; special-cased
5045  * for a single hardware transmit queue (e.g. 5210 and 5211).
5046  */
5047 static void
5048 ath_tx_task_q0(void *arg, int npending)
5049 {
5050         struct ath_softc *sc = arg;
5051         struct ifnet *ifp = sc->sc_ifp;
5052
5053         wlan_serialize_enter();
5054         if (txqactive(sc->sc_ah, 0) && ath_tx_processq(sc, &sc->sc_txq[0]))
5055                 sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5056         if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
5057                 ath_tx_processq(sc, sc->sc_cabq);
5058         ifp->if_flags &= ~IFF_OACTIVE;
5059         sc->sc_wd_timer = 0;
5060
5061         if (sc->sc_softled)
5062                 ath_led_event(sc, sc->sc_txrix);
5063
5064         ath_start(ifp);
5065         wlan_serialize_exit();
5066 }
5067
5068 /*
5069  * Deferred processing of transmit interrupt; special-cased
5070  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
5071  */
5072 static void
5073 ath_tx_task_q0123(void *arg, int npending)
5074 {
5075         struct ath_softc *sc = arg;
5076         struct ifnet *ifp = sc->sc_ifp;
5077         int nacked;
5078
5079         wlan_serialize_enter();
5080         /*
5081          * Process each active queue.
5082          */
5083         nacked = 0;
5084         if (txqactive(sc->sc_ah, 0))
5085                 nacked += ath_tx_processq(sc, &sc->sc_txq[0]);
5086         if (txqactive(sc->sc_ah, 1))
5087                 nacked += ath_tx_processq(sc, &sc->sc_txq[1]);
5088         if (txqactive(sc->sc_ah, 2))
5089                 nacked += ath_tx_processq(sc, &sc->sc_txq[2]);
5090         if (txqactive(sc->sc_ah, 3))
5091                 nacked += ath_tx_processq(sc, &sc->sc_txq[3]);
5092         if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
5093                 ath_tx_processq(sc, sc->sc_cabq);
5094         if (nacked)
5095                 sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5096
5097         ifp->if_flags &= ~IFF_OACTIVE;
5098         sc->sc_wd_timer = 0;
5099
5100         if (sc->sc_softled)
5101                 ath_led_event(sc, sc->sc_txrix);
5102
5103         ath_start(ifp);
5104         wlan_serialize_exit();
5105 }
5106
5107 /*
5108  * Deferred processing of transmit interrupt.
5109  */
5110 static void
5111 ath_tx_task(void *arg, int npending)
5112 {
5113         struct ath_softc *sc = arg;
5114         struct ifnet *ifp = sc->sc_ifp;
5115         int i, nacked;
5116
5117         wlan_serialize_enter();
5118
5119         /*
5120          * Process each active queue.
5121          */
5122         nacked = 0;
5123         for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
5124                 if (ATH_TXQ_SETUP(sc, i) && txqactive(sc->sc_ah, i))
5125                         nacked += ath_tx_processq(sc, &sc->sc_txq[i]);
5126         }
5127         if (nacked)
5128                 sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5129
5130         ifp->if_flags &= ~IFF_OACTIVE;
5131         sc->sc_wd_timer = 0;
5132
5133         if (sc->sc_softled)
5134                 ath_led_event(sc, sc->sc_txrix);
5135
5136         ath_start(ifp);
5137         wlan_serialize_exit();
5138 }
5139
5140 static void
5141 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
5142 {
5143 #ifdef ATH_DEBUG
5144         struct ath_hal *ah = sc->sc_ah;
5145 #endif
5146         struct ieee80211_node *ni;
5147         struct ath_buf *bf;
5148         u_int ix;
5149
5150         /*
5151          * NB: this assumes output has been stopped and
5152          *     we do not need to block ath_tx_proc
5153          */
5154         bf = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
5155         if (bf != NULL)
5156                 bf->bf_flags &= ~ATH_BUF_BUSY;
5157         for (ix = 0;; ix++) {
5158                 bf = STAILQ_FIRST(&txq->axq_q);
5159                 if (bf == NULL) {
5160                         txq->axq_link = NULL;
5161                         break;
5162                 }
5163                 ATH_TXQ_REMOVE_HEAD(txq, bf_list);
5164 #ifdef ATH_DEBUG
5165                 if (sc->sc_debug & ATH_DEBUG_RESET) {
5166                         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
5167
5168                         ath_printtxbuf(sc, bf, txq->axq_qnum, ix,
5169                                 ath_hal_txprocdesc(ah, bf->bf_desc,
5170                                     &bf->bf_status.ds_txstat) == HAL_OK);
5171                         ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
5172                             bf->bf_m->m_len, 0, -1);
5173                 }
5174 #endif /* ATH_DEBUG */
5175                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
5176                 ni = bf->bf_node;
5177                 bf->bf_node = NULL;
5178                 if (ni != NULL) {
5179                         /*
5180                          * Do any callback and reclaim the node reference.
5181                          */
5182                         if (bf->bf_m->m_flags & M_TXCB)
5183                                 ieee80211_process_callback(ni, bf->bf_m, -1);
5184                         ieee80211_free_node(ni);
5185                 }
5186                 m_freem(bf->bf_m);
5187                 bf->bf_m = NULL;
5188                 bf->bf_flags &= ~ATH_BUF_BUSY;
5189
5190                 STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5191         }
5192 }
5193
5194 static void
5195 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
5196 {
5197         struct ath_hal *ah = sc->sc_ah;
5198
5199         DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5200             __func__, txq->axq_qnum,
5201             (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
5202             txq->axq_link);
5203         (void) ath_hal_stoptxdma(ah, txq->axq_qnum);
5204 }
5205
5206 /*
5207  * Drain the transmit queues and reclaim resources.
5208  */
5209 static void
5210 ath_draintxq(struct ath_softc *sc)
5211 {
5212         struct ath_hal *ah = sc->sc_ah;
5213         struct ifnet *ifp = sc->sc_ifp;
5214         int i;
5215
5216         /* XXX return value */
5217         if (!sc->sc_invalid) {
5218                 /* don't touch the hardware if marked invalid */
5219                 DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5220                     __func__, sc->sc_bhalq,
5221                     (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
5222                     NULL);
5223                 (void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
5224                 for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5225                         if (ATH_TXQ_SETUP(sc, i))
5226                                 ath_tx_stopdma(sc, &sc->sc_txq[i]);
5227         }
5228         for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5229                 if (ATH_TXQ_SETUP(sc, i))
5230                         ath_tx_draintxq(sc, &sc->sc_txq[i]);
5231 #ifdef ATH_DEBUG
5232         if (sc->sc_debug & ATH_DEBUG_RESET) {
5233                 struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
5234                 if (bf != NULL && bf->bf_m != NULL) {
5235                         ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
5236                                 ath_hal_txprocdesc(ah, bf->bf_desc,
5237                                     &bf->bf_status.ds_txstat) == HAL_OK);
5238                         ieee80211_dump_pkt(ifp->if_l2com,
5239                             mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
5240                             0, -1);
5241                 }
5242         }
5243 #endif /* ATH_DEBUG */
5244         ifp->if_flags &= ~IFF_OACTIVE;
5245         sc->sc_wd_timer = 0;
5246 }
5247
5248 /*
5249  * Disable the receive h/w in preparation for a reset.
5250  */
5251 static void
5252 ath_stoprecv(struct ath_softc *sc)
5253 {
5254 #define PA2DESC(_sc, _pa) \
5255         ((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
5256                 ((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
5257         struct ath_hal *ah = sc->sc_ah;
5258
5259         ath_hal_stoppcurecv(ah);        /* disable PCU */
5260         ath_hal_setrxfilter(ah, 0);     /* clear recv filter */
5261         ath_hal_stopdmarecv(ah);        /* disable DMA engine */
5262         DELAY(3000);                    /* 3ms is long enough for 1 frame */
5263 #ifdef ATH_DEBUG
5264         if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
5265                 struct ath_buf *bf;
5266                 u_int ix;
5267
5268                 kprintf("%s: rx queue %p, link %p\n", __func__,
5269                         (caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
5270                 ix = 0;
5271                 STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
5272                         struct ath_desc *ds = bf->bf_desc;
5273                         struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
5274                         HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
5275                                 bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
5276                         if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
5277                                 ath_printrxbuf(sc, bf, ix, status == HAL_OK);
5278                         ix++;
5279                 }
5280         }
5281 #endif
5282         if (sc->sc_rxpending != NULL) {
5283                 m_freem(sc->sc_rxpending);
5284                 sc->sc_rxpending = NULL;
5285         }
5286         sc->sc_rxlink = NULL;           /* just in case */
5287 #undef PA2DESC
5288 }
5289
5290 /*
5291  * Enable the receive h/w following a reset.
5292  */
5293 static int
5294 ath_startrecv(struct ath_softc *sc)
5295 {
5296         struct ath_hal *ah = sc->sc_ah;
5297         struct ath_buf *bf;
5298
5299         sc->sc_rxlink = NULL;
5300         sc->sc_rxpending = NULL;
5301         STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
5302                 int error = ath_rxbuf_init(sc, bf);
5303                 if (error != 0) {
5304                         DPRINTF(sc, ATH_DEBUG_RECV,
5305                                 "%s: ath_rxbuf_init failed %d\n",
5306                                 __func__, error);
5307                         return error;
5308                 }
5309         }
5310
5311         bf = STAILQ_FIRST(&sc->sc_rxbuf);
5312         ath_hal_putrxbuf(ah, bf->bf_daddr);
5313         ath_hal_rxena(ah);              /* enable recv descriptors */
5314         ath_mode_init(sc);              /* set filters, etc. */
5315         ath_hal_startpcurecv(ah);       /* re-enable PCU/DMA engine */
5316         return 0;
5317 }
5318
5319 /* 
5320  * Update internal state after a channel change.
5321  */
5322 static void
5323 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
5324 {
5325         enum ieee80211_phymode mode;
5326
5327         /*
5328          * Change channels and update the h/w rate map
5329          * if we're switching; e.g. 11a to 11b/g.
5330          */
5331         mode = ieee80211_chan2mode(chan);
5332         if (mode != sc->sc_curmode)
5333                 ath_setcurmode(sc, mode);
5334         sc->sc_curchan = chan;
5335 }
5336
5337 /*
5338  * Set/change channels.  If the channel is really being changed,
5339  * it's done by reseting the chip.  To accomplish this we must
5340  * first cleanup any pending DMA, then restart stuff after a la
5341  * ath_init.
5342  */
5343 static int
5344 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
5345 {
5346         struct ifnet *ifp = sc->sc_ifp;
5347         struct ieee80211com *ic = ifp->if_l2com;
5348         struct ath_hal *ah = sc->sc_ah;
5349
5350         DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
5351             __func__, ieee80211_chan2ieee(ic, chan),
5352             chan->ic_freq, chan->ic_flags);
5353         if (chan != sc->sc_curchan) {
5354                 HAL_STATUS status;
5355                 /*
5356                  * To switch channels clear any pending DMA operations;
5357                  * wait long enough for the RX fifo to drain, reset the
5358                  * hardware at the new frequency, and then re-enable
5359                  * the relevant bits of the h/w.
5360                  */
5361                 ath_hal_intrset(ah, 0);         /* disable interrupts */
5362                 ath_draintxq(sc);               /* clear pending tx frames */
5363                 ath_stoprecv(sc);               /* turn off frame recv */
5364                 if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
5365                         if_printf(ifp, "%s: unable to reset "
5366                             "channel %u (%u MHz, flags 0x%x), hal status %u\n",
5367                             __func__, ieee80211_chan2ieee(ic, chan),
5368                             chan->ic_freq, chan->ic_flags, status);
5369                         return EIO;
5370                 }
5371                 sc->sc_diversity = ath_hal_getdiversity(ah);
5372
5373                 /*
5374                  * Re-enable rx framework.
5375                  */
5376                 if (ath_startrecv(sc) != 0) {
5377                         if_printf(ifp, "%s: unable to restart recv logic\n",
5378                             __func__);
5379                         return EIO;
5380                 }
5381
5382                 /*
5383                  * Change channels and update the h/w rate map
5384                  * if we're switching; e.g. 11a to 11b/g.
5385                  */
5386                 ath_chan_change(sc, chan);
5387
5388                 /*
5389                  * Re-enable interrupts.
5390                  */
5391                 ath_hal_intrset(ah, sc->sc_imask);
5392         }
5393         return 0;
5394 }
5395
5396 /*
5397  * Periodically recalibrate the PHY to account
5398  * for temperature/environment changes.
5399  */
5400 static void
5401 ath_calibrate_callout(void *arg)
5402 {
5403         struct ath_softc *sc = arg;
5404         struct ath_hal *ah = sc->sc_ah;
5405         struct ifnet *ifp = sc->sc_ifp;
5406         struct ieee80211com *ic = ifp->if_l2com;
5407         HAL_BOOL longCal, isCalDone;
5408         int nextcal;
5409
5410         wlan_serialize_enter();
5411
5412         if (ic->ic_flags & IEEE80211_F_SCAN)    /* defer, off channel */
5413                 goto restart;
5414         longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
5415         if (longCal) {
5416                 sc->sc_stats.ast_per_cal++;
5417                 sc->sc_lastlongcal = ticks;
5418                 if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
5419                         /*
5420                          * Rfgain is out of bounds, reset the chip
5421                          * to load new gain values.
5422                          */
5423                         DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5424                                 "%s: rfgain change\n", __func__);
5425                         sc->sc_stats.ast_per_rfgain++;
5426                         ath_reset(ifp);
5427                 }
5428                 /*
5429                  * If this long cal is after an idle period, then
5430                  * reset the data collection state so we start fresh.
5431                  */
5432                 if (sc->sc_resetcal) {
5433                         (void) ath_hal_calreset(ah, sc->sc_curchan);
5434                         sc->sc_lastcalreset = ticks;
5435                         sc->sc_resetcal = 0;
5436                 }
5437         }
5438         if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
5439                 if (longCal) {
5440                         /*
5441                          * Calibrate noise floor data again in case of change.
5442                          */
5443                         ath_hal_process_noisefloor(ah);
5444                 }
5445         } else {
5446                 DPRINTF(sc, ATH_DEBUG_ANY,
5447                         "%s: calibration of channel %u failed\n",
5448                         __func__, sc->sc_curchan->ic_freq);
5449                 sc->sc_stats.ast_per_calfail++;
5450         }
5451         if (!isCalDone) {
5452 restart:
5453                 /*
5454                  * Use a shorter interval to potentially collect multiple
5455                  * data samples required to complete calibration.  Once
5456                  * we're told the work is done we drop back to a longer
5457                  * interval between requests.  We're more aggressive doing
5458                  * work when operating as an AP to improve operation right
5459                  * after startup.
5460                  */
5461                 nextcal = (1000*ath_shortcalinterval)/hz;
5462                 if (sc->sc_opmode != HAL_M_HOSTAP)
5463                         nextcal *= 10;
5464         } else {
5465                 nextcal = ath_longcalinterval*hz;
5466                 if (sc->sc_lastcalreset == 0)
5467                         sc->sc_lastcalreset = sc->sc_lastlongcal;
5468                 else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
5469                         sc->sc_resetcal = 1;    /* setup reset next trip */
5470         }
5471
5472         if (nextcal != 0) {
5473                 DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
5474                     __func__, nextcal, isCalDone ? "" : "!");
5475                 callout_reset(&sc->sc_cal_ch, nextcal,
5476                               ath_calibrate_callout, sc);
5477         } else {
5478                 DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
5479                     __func__);
5480                 /* NB: don't rearm timer */
5481         }
5482         wlan_serialize_exit();
5483 }
5484
5485 static void
5486 ath_scan_start(struct ieee80211com *ic)
5487 {
5488         struct ifnet *ifp = ic->ic_ifp;
5489         struct ath_softc *sc = ifp->if_softc;
5490         struct ath_hal *ah = sc->sc_ah;
5491         u_int32_t rfilt;
5492
5493         /* XXX calibration timer? */
5494
5495         sc->sc_scanning = 1;
5496         sc->sc_syncbeacon = 0;
5497         rfilt = ath_calcrxfilter(sc);
5498         ath_hal_setrxfilter(ah, rfilt);
5499         ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
5500
5501         DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %6D aid 0\n",
5502                  __func__, rfilt, ifp->if_broadcastaddr, ":");
5503 }
5504
5505 static void
5506 ath_scan_end(struct ieee80211com *ic)
5507 {
5508         struct ifnet *ifp = ic->ic_ifp;
5509         struct ath_softc *sc = ifp->if_softc;
5510         struct ath_hal *ah = sc->sc_ah;
5511         u_int32_t rfilt;
5512
5513         sc->sc_scanning = 0;
5514         rfilt = ath_calcrxfilter(sc);
5515         ath_hal_setrxfilter(ah, rfilt);
5516         ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5517
5518         ath_hal_process_noisefloor(ah);
5519
5520         DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %6D aid 0x%x\n",
5521                  __func__, rfilt, sc->sc_curbssid, ":",
5522                  sc->sc_curaid);
5523 }
5524
5525 static void
5526 ath_set_channel(struct ieee80211com *ic)
5527 {
5528         struct ifnet *ifp = ic->ic_ifp;
5529         struct ath_softc *sc = ifp->if_softc;
5530
5531         (void) ath_chan_set(sc, ic->ic_curchan);
5532         /*
5533          * If we are returning to our bss channel then mark state
5534          * so the next recv'd beacon's tsf will be used to sync the
5535          * beacon timers.  Note that since we only hear beacons in
5536          * sta/ibss mode this has no effect in other operating modes.
5537          */
5538         if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
5539                 sc->sc_syncbeacon = 1;
5540 }
5541
5542 /* 
5543  * Walk the vap list and check if there any vap's in RUN state.
5544  */
5545 static int
5546 ath_isanyrunningvaps(struct ieee80211vap *this)
5547 {
5548         struct ieee80211com *ic = this->iv_ic;
5549         struct ieee80211vap *vap;
5550
5551         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
5552                 if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
5553                         return 1;
5554         }
5555         return 0;
5556 }
5557
5558 static int
5559 ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
5560 {
5561         struct ieee80211com *ic = vap->iv_ic;
5562         struct ath_softc *sc = ic->ic_ifp->if_softc;
5563         struct ath_vap *avp = ATH_VAP(vap);
5564         struct ath_hal *ah = sc->sc_ah;
5565         struct ieee80211_node *ni = NULL;
5566         int i, error, stamode;
5567         u_int32_t rfilt;
5568         static const HAL_LED_STATE leds[] = {
5569             HAL_LED_INIT,       /* IEEE80211_S_INIT */
5570             HAL_LED_SCAN,       /* IEEE80211_S_SCAN */
5571             HAL_LED_AUTH,       /* IEEE80211_S_AUTH */
5572             HAL_LED_ASSOC,      /* IEEE80211_S_ASSOC */
5573             HAL_LED_RUN,        /* IEEE80211_S_CAC */
5574             HAL_LED_RUN,        /* IEEE80211_S_RUN */
5575             HAL_LED_RUN,        /* IEEE80211_S_CSA */
5576             HAL_LED_RUN,        /* IEEE80211_S_SLEEP */
5577         };
5578
5579         DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
5580                 ieee80211_state_name[vap->iv_state],
5581                 ieee80211_state_name[nstate]);
5582
5583         callout_stop(&sc->sc_cal_ch);
5584         ath_hal_setledstate(ah, leds[nstate]);  /* set LED */
5585
5586         if (nstate == IEEE80211_S_SCAN) {
5587                 /*
5588                  * Scanning: turn off beacon miss and don't beacon.
5589                  * Mark beacon state so when we reach RUN state we'll
5590                  * [re]setup beacons.  Unblock the task q thread so
5591                  * deferred interrupt processing is done.
5592                  */
5593                 ath_hal_intrset(ah,
5594                     sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
5595                 sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5596                 sc->sc_beacons = 0;
5597                 taskqueue_unblock(sc->sc_tq);
5598         }
5599
5600         ni = vap->iv_bss;
5601         rfilt = ath_calcrxfilter(sc);
5602         stamode = (vap->iv_opmode == IEEE80211_M_STA ||
5603                    vap->iv_opmode == IEEE80211_M_AHDEMO ||
5604                    vap->iv_opmode == IEEE80211_M_IBSS);
5605         if (stamode && nstate == IEEE80211_S_RUN) {
5606                 sc->sc_curaid = ni->ni_associd;
5607                 IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
5608                 ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5609         }
5610         DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %6D aid 0x%x\n",
5611            __func__, rfilt, sc->sc_curbssid, ":", sc->sc_curaid);
5612         ath_hal_setrxfilter(ah, rfilt);
5613
5614         /* XXX is this to restore keycache on resume? */
5615         if (vap->iv_opmode != IEEE80211_M_STA &&
5616             (vap->iv_flags & IEEE80211_F_PRIVACY)) {
5617                 for (i = 0; i < IEEE80211_WEP_NKID; i++)
5618                         if (ath_hal_keyisvalid(ah, i))
5619                                 ath_hal_keysetmac(ah, i, ni->ni_bssid);
5620         }
5621
5622         /*
5623          * Invoke the parent method to do net80211 work.
5624          */
5625         error = avp->av_newstate(vap, nstate, arg);
5626         if (error != 0)
5627                 goto bad;
5628
5629         if (nstate == IEEE80211_S_RUN) {
5630                 /* NB: collect bss node again, it may have changed */
5631                 ni = vap->iv_bss;
5632
5633                 DPRINTF(sc, ATH_DEBUG_STATE,
5634                     "%s(RUN): iv_flags 0x%08x bintvl %d bssid %6D "
5635                     "capinfo 0x%04x chan %d\n", __func__,
5636                     vap->iv_flags, ni->ni_intval, ni->ni_bssid, ":",
5637                     ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
5638
5639                 switch (vap->iv_opmode) {
5640 #ifdef IEEE80211_SUPPORT_TDMA
5641                 case IEEE80211_M_AHDEMO:
5642                         if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
5643                                 break;
5644                         /* fall thru... */
5645 #endif
5646                 case IEEE80211_M_HOSTAP:
5647                 case IEEE80211_M_IBSS:
5648                 case IEEE80211_M_MBSS:
5649                         /*
5650                          * Allocate and setup the beacon frame.
5651                          *
5652                          * Stop any previous beacon DMA.  This may be
5653                          * necessary, for example, when an ibss merge
5654                          * causes reconfiguration; there will be a state
5655                          * transition from RUN->RUN that means we may
5656                          * be called with beacon transmission active.
5657                          */
5658                         ath_hal_stoptxdma(ah, sc->sc_bhalq);
5659
5660                         error = ath_beacon_alloc(sc, ni);
5661                         if (error != 0)
5662                                 goto bad;
5663                         /*
5664                          * If joining an adhoc network defer beacon timer
5665                          * configuration to the next beacon frame so we
5666                          * have a current TSF to use.  Otherwise we're
5667                          * starting an ibss/bss so there's no need to delay;
5668                          * if this is the first vap moving to RUN state, then
5669                          * beacon state needs to be [re]configured.
5670                          */
5671                         if (vap->iv_opmode == IEEE80211_M_IBSS &&
5672                             ni->ni_tstamp.tsf != 0) {
5673                                 sc->sc_syncbeacon = 1;
5674                         } else if (!sc->sc_beacons) {
5675 #ifdef IEEE80211_SUPPORT_TDMA
5676                                 if (vap->iv_caps & IEEE80211_C_TDMA)
5677                                         ath_tdma_config(sc, vap);
5678                                 else
5679 #endif
5680                                         ath_beacon_config(sc, vap);
5681                                 sc->sc_beacons = 1;
5682                         }
5683                         break;
5684                 case IEEE80211_M_STA:
5685                         /*
5686                          * Defer beacon timer configuration to the next
5687                          * beacon frame so we have a current TSF to use
5688                          * (any TSF collected when scanning is likely old).
5689                          */
5690                         sc->sc_syncbeacon = 1;
5691                         break;
5692                 case IEEE80211_M_MONITOR:
5693                         /*
5694                          * Monitor mode vaps have only INIT->RUN and RUN->RUN
5695                          * transitions so we must re-enable interrupts here to
5696                          * handle the case of a single monitor mode vap.
5697                          */
5698                         ath_hal_intrset(ah, sc->sc_imask);
5699                         break;
5700                 case IEEE80211_M_WDS:
5701                         break;
5702                 default:
5703                         break;
5704                 }
5705                 /*
5706                  * Let the hal process statistics collected during a
5707                  * scan so it can provide calibrated noise floor data.
5708                  */
5709                 ath_hal_process_noisefloor(ah);
5710                 /*
5711                  * Reset rssi stats; maybe not the best place...
5712                  */
5713                 sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
5714                 sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
5715                 sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
5716                 /*
5717                  * Finally, start any timers and the task q thread
5718                  * (in case we didn't go through SCAN state).
5719                  */
5720                 if (ath_longcalinterval != 0) {
5721                         /* start periodic recalibration timer */
5722                         callout_reset(&sc->sc_cal_ch, 1,
5723                                       ath_calibrate_callout, sc);
5724                 } else {
5725                         DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5726                             "%s: calibration disabled\n", __func__);
5727                 }
5728                 taskqueue_unblock(sc->sc_tq);
5729         } else if (nstate == IEEE80211_S_INIT) {
5730                 /*
5731                  * If there are no vaps left in RUN state then
5732                  * shutdown host/driver operation:
5733                  * o disable interrupts
5734                  * o disable the task queue thread
5735                  * o mark beacon processing as stopped
5736                  */
5737                 if (!ath_isanyrunningvaps(vap)) {
5738                         sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
5739                         /* disable interrupts  */
5740                         ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
5741                         taskqueue_block(sc->sc_tq);
5742                         sc->sc_beacons = 0;
5743                 }
5744 #ifdef IEEE80211_SUPPORT_TDMA
5745                 ath_hal_setcca(ah, AH_TRUE);
5746 #endif
5747         }
5748 bad:
5749         return error;
5750 }
5751
5752 /*
5753  * Allocate a key cache slot to the station so we can
5754  * setup a mapping from key index to node. The key cache
5755  * slot is needed for managing antenna state and for
5756  * compression when stations do not use crypto.  We do
5757  * it uniliaterally here; if crypto is employed this slot
5758  * will be reassigned.
5759  */
5760 static void
5761 ath_setup_stationkey(struct ieee80211_node *ni)
5762 {
5763         struct ieee80211vap *vap = ni->ni_vap;
5764         struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
5765         ieee80211_keyix keyix, rxkeyix;
5766
5767         if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
5768                 /*
5769                  * Key cache is full; we'll fall back to doing
5770                  * the more expensive lookup in software.  Note
5771                  * this also means no h/w compression.
5772                  */
5773                 /* XXX msg+statistic */
5774         } else {
5775                 /* XXX locking? */
5776                 ni->ni_ucastkey.wk_keyix = keyix;
5777                 ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
5778                 /* NB: must mark device key to get called back on delete */
5779                 ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
5780                 IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
5781                 /* NB: this will create a pass-thru key entry */
5782                 ath_keyset(sc, &ni->ni_ucastkey, vap->iv_bss);
5783         }
5784 }
5785
5786 /*
5787  * Setup driver-specific state for a newly associated node.
5788  * Note that we're called also on a re-associate, the isnew
5789  * param tells us if this is the first time or not.
5790  */
5791 static void
5792 ath_newassoc(struct ieee80211_node *ni, int isnew)
5793 {
5794         struct ath_node *an = ATH_NODE(ni);
5795         struct ieee80211vap *vap = ni->ni_vap;
5796         struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
5797         const struct ieee80211_txparam *tp = ni->ni_txparms;
5798
5799         an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
5800         an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
5801
5802         ath_rate_newassoc(sc, an, isnew);
5803         if (isnew && 
5804             (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
5805             ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
5806                 ath_setup_stationkey(ni);
5807 }
5808
5809 static int
5810 ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
5811         int nchans, struct ieee80211_channel chans[])
5812 {
5813         struct ath_softc *sc = ic->ic_ifp->if_softc;
5814         struct ath_hal *ah = sc->sc_ah;
5815         HAL_STATUS status;
5816
5817         DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
5818             "%s: rd %u cc %u location %c%s\n",
5819             __func__, reg->regdomain, reg->country, reg->location,
5820             reg->ecm ? " ecm" : "");
5821
5822         status = ath_hal_set_channels(ah, chans, nchans,
5823             reg->country, reg->regdomain);
5824         if (status != HAL_OK) {
5825                 DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
5826                     __func__, status);
5827                 return EINVAL;          /* XXX */
5828         }
5829         return 0;
5830 }
5831
5832 static void
5833 ath_getradiocaps(struct ieee80211com *ic,
5834         int maxchans, int *nchans, struct ieee80211_channel chans[])
5835 {
5836         struct ath_softc *sc = ic->ic_ifp->if_softc;
5837         struct ath_hal *ah = sc->sc_ah;
5838
5839         DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
5840             __func__, SKU_DEBUG, CTRY_DEFAULT);
5841
5842         /* XXX check return */
5843         (void) ath_hal_getchannels(ah, chans, maxchans, nchans,
5844             HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
5845
5846 }
5847
5848 static int
5849 ath_getchannels(struct ath_softc *sc)
5850 {
5851         struct ifnet *ifp = sc->sc_ifp;
5852         struct ieee80211com *ic = ifp->if_l2com;
5853         struct ath_hal *ah = sc->sc_ah;
5854         HAL_STATUS status;
5855
5856         /*
5857          * Collect channel set based on EEPROM contents.
5858          */
5859         status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
5860             &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
5861         if (status != HAL_OK) {
5862                 if_printf(ifp, "%s: unable to collect channel list from hal, "
5863                     "status %d\n", __func__, status);
5864                 return EINVAL;
5865         }
5866         (void) ath_hal_getregdomain(ah, &sc->sc_eerd);
5867         ath_hal_getcountrycode(ah, &sc->sc_eecc);       /* NB: cannot fail */
5868         /* XXX map Atheros sku's to net80211 SKU's */
5869         /* XXX net80211 types too small */
5870         ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
5871         ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
5872         ic->ic_regdomain.isocc[0] = ' ';        /* XXX don't know */
5873         ic->ic_regdomain.isocc[1] = ' ';
5874
5875         ic->ic_regdomain.ecm = 1;
5876         ic->ic_regdomain.location = 'I';
5877
5878         DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
5879             "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
5880             __func__, sc->sc_eerd, sc->sc_eecc,
5881             ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
5882             ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
5883         return 0;
5884 }
5885
5886 static void
5887 ath_led_done_callout(void *arg)
5888 {
5889         struct ath_softc *sc = arg;
5890
5891         wlan_serialize_enter();
5892         sc->sc_blinking = 0;
5893         wlan_serialize_exit();
5894 }
5895
5896 /*
5897  * Turn the LED off: flip the pin and then set a timer so no
5898  * update will happen for the specified duration.
5899  */
5900 static void
5901 ath_led_off_callout(void *arg)
5902 {
5903         struct ath_softc *sc = arg;
5904
5905         wlan_serialize_enter();
5906         ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
5907         callout_reset(&sc->sc_ledtimer, sc->sc_ledoff,
5908                         ath_led_done_callout, sc);
5909         wlan_serialize_exit();
5910 }
5911
5912 /*
5913  * Blink the LED according to the specified on/off times.
5914  */
5915 static void
5916 ath_led_blink(struct ath_softc *sc, int on, int off)
5917 {
5918         DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
5919         ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
5920         sc->sc_blinking = 1;
5921         sc->sc_ledoff = off;
5922         callout_reset(&sc->sc_ledtimer, on, ath_led_off_callout, sc);
5923 }
5924
5925 static void
5926 ath_led_event(struct ath_softc *sc, int rix)
5927 {
5928         sc->sc_ledevent = ticks;        /* time of last event */
5929         if (sc->sc_blinking)            /* don't interrupt active blink */
5930                 return;
5931         ath_led_blink(sc, sc->sc_hwmap[rix].ledon, sc->sc_hwmap[rix].ledoff);
5932 }
5933
5934 static int
5935 ath_rate_setup(struct ath_softc *sc, u_int mode)
5936 {
5937         struct ath_hal *ah = sc->sc_ah;
5938         const HAL_RATE_TABLE *rt;
5939
5940         switch (mode) {
5941         case IEEE80211_MODE_11A:
5942                 rt = ath_hal_getratetable(ah, HAL_MODE_11A);
5943                 break;
5944         case IEEE80211_MODE_HALF:
5945                 rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
5946                 break;
5947         case IEEE80211_MODE_QUARTER:
5948                 rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
5949                 break;
5950         case IEEE80211_MODE_11B:
5951                 rt = ath_hal_getratetable(ah, HAL_MODE_11B);
5952                 break;
5953         case IEEE80211_MODE_11G:
5954                 rt = ath_hal_getratetable(ah, HAL_MODE_11G);
5955                 break;
5956         case IEEE80211_MODE_TURBO_A:
5957                 rt = ath_hal_getratetable(ah, HAL_MODE_108A);
5958                 break;
5959         case IEEE80211_MODE_TURBO_G:
5960                 rt = ath_hal_getratetable(ah, HAL_MODE_108G);
5961                 break;
5962         case IEEE80211_MODE_STURBO_A:
5963                 rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
5964                 break;
5965         case IEEE80211_MODE_11NA:
5966                 rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
5967                 break;
5968         case IEEE80211_MODE_11NG:
5969                 rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
5970                 break;
5971         default:
5972                 DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
5973                         __func__, mode);
5974                 return 0;
5975         }
5976         sc->sc_rates[mode] = rt;
5977         return (rt != NULL);
5978 }
5979
5980 static void
5981 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
5982 {
5983         /* NB: on/off times from the Atheros NDIS driver, w/ permission */
5984         static const struct {
5985                 u_int           rate;           /* tx/rx 802.11 rate */
5986                 u_int16_t       timeOn;         /* LED on time (ms) */
5987                 u_int16_t       timeOff;        /* LED off time (ms) */
5988         } blinkrates[] = {
5989                 { 108,  40,  10 },
5990                 {  96,  44,  11 },
5991                 {  72,  50,  13 },
5992                 {  48,  57,  14 },
5993                 {  36,  67,  16 },
5994                 {  24,  80,  20 },
5995                 {  22, 100,  25 },
5996                 {  18, 133,  34 },
5997                 {  12, 160,  40 },
5998                 {  10, 200,  50 },
5999                 {   6, 240,  58 },
6000                 {   4, 267,  66 },
6001                 {   2, 400, 100 },
6002                 {   0, 500, 130 },
6003                 /* XXX half/quarter rates */
6004         };
6005         const HAL_RATE_TABLE *rt;
6006         int i, j;
6007
6008         memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
6009         rt = sc->sc_rates[mode];
6010         KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
6011         for (i = 0; i < rt->rateCount; i++) {
6012                 uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6013                 if (rt->info[i].phy != IEEE80211_T_HT)
6014                         sc->sc_rixmap[ieeerate] = i;
6015                 else
6016                         sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
6017         }
6018         memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
6019         for (i = 0; i < NELEM(sc->sc_hwmap); i++) {
6020                 if (i >= rt->rateCount) {
6021                         sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
6022                         sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
6023                         continue;
6024                 }
6025                 sc->sc_hwmap[i].ieeerate =
6026                         rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6027                 if (rt->info[i].phy == IEEE80211_T_HT)
6028                         sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
6029                 sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
6030                 if (rt->info[i].shortPreamble ||
6031                     rt->info[i].phy == IEEE80211_T_OFDM)
6032                         sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
6033                 sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
6034                 for (j = 0; j < NELEM(blinkrates)-1; j++)
6035                         if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
6036                                 break;
6037                 /* NB: this uses the last entry if the rate isn't found */
6038                 /* XXX beware of overlow */
6039                 sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
6040                 sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
6041         }
6042         sc->sc_currates = rt;
6043         sc->sc_curmode = mode;
6044         /*
6045          * All protection frames are transmited at 2Mb/s for
6046          * 11g, otherwise at 1Mb/s.
6047          */
6048         if (mode == IEEE80211_MODE_11G)
6049                 sc->sc_protrix = ath_tx_findrix(sc, 2*2);
6050         else
6051                 sc->sc_protrix = ath_tx_findrix(sc, 2*1);
6052         /* NB: caller is responsible for reseting rate control state */
6053 }
6054
6055 #ifdef ATH_DEBUG
6056 static void
6057 ath_printrxbuf(struct ath_softc *sc, const struct ath_buf *bf,
6058         u_int ix, int done)
6059 {
6060         const struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
6061         struct ath_hal *ah = sc->sc_ah;
6062         const struct ath_desc *ds;
6063         int i;
6064
6065         for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
6066                 kprintf("R[%2u] (DS.V:%p DS.P:%p) L:%08x D:%08x%s\n"
6067                        "      %08x %08x %08x %08x\n",
6068                     ix, ds, (const struct ath_desc *)bf->bf_daddr + i,
6069                     ds->ds_link, ds->ds_data,
6070                     !done ? "" : (rs->rs_status == 0) ? " *" : " !",
6071                     ds->ds_ctl0, ds->ds_ctl1,
6072                     ds->ds_hw[0], ds->ds_hw[1]);
6073                 if (ah->ah_magic == 0x20065416) {
6074                         kprintf("        %08x %08x %08x %08x %08x %08x %08x\n",
6075                             ds->ds_hw[2], ds->ds_hw[3], ds->ds_hw[4],
6076                             ds->ds_hw[5], ds->ds_hw[6], ds->ds_hw[7],
6077                             ds->ds_hw[8]);
6078                 }
6079         }
6080 }
6081
6082 static void
6083 ath_printtxbuf(struct ath_softc *sc, const struct ath_buf *bf,
6084         u_int qnum, u_int ix, int done)
6085 {
6086         const struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
6087         struct ath_hal *ah = sc->sc_ah;
6088         const struct ath_desc *ds;
6089         int i;
6090
6091         kprintf("Q%u[%3u]", qnum, ix);
6092         for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
6093                 kprintf(" (DS.V:%p DS.P:%p) L:%08x D:%08x F:04%x%s\n"
6094                        "        %08x %08x %08x %08x %08x %08x\n",
6095                     ds, (const struct ath_desc *)bf->bf_daddr + i,
6096                     ds->ds_link, ds->ds_data, bf->bf_txflags,
6097                     !done ? "" : (ts->ts_status == 0) ? " *" : " !",
6098                     ds->ds_ctl0, ds->ds_ctl1,
6099                     ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3]);
6100                 if (ah->ah_magic == 0x20065416) {
6101                         kprintf("        %08x %08x %08x %08x %08x %08x %08x %08x\n",
6102                             ds->ds_hw[4], ds->ds_hw[5], ds->ds_hw[6],
6103                             ds->ds_hw[7], ds->ds_hw[8], ds->ds_hw[9],
6104                             ds->ds_hw[10],ds->ds_hw[11]);
6105                         kprintf("        %08x %08x %08x %08x %08x %08x %08x %08x\n",
6106                             ds->ds_hw[12],ds->ds_hw[13],ds->ds_hw[14],
6107                             ds->ds_hw[15],ds->ds_hw[16],ds->ds_hw[17],
6108                             ds->ds_hw[18], ds->ds_hw[19]);
6109                 }
6110         }
6111 }
6112 #endif /* ATH_DEBUG */
6113
6114 static void
6115 ath_watchdog_callout(void *arg)
6116 {
6117         struct ath_softc *sc = arg;
6118
6119         wlan_serialize_enter();
6120         if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
6121                 struct ifnet *ifp = sc->sc_ifp;
6122                 uint32_t hangs;
6123
6124                 if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
6125                     hangs != 0) {
6126                         if_printf(ifp, "%s hang detected (0x%x)\n",
6127                             hangs & 0xff ? "bb" : "mac", hangs); 
6128                 } else
6129                         if_printf(ifp, "device timeout\n");
6130                 ath_reset(ifp);
6131                 ifp->if_oerrors++;
6132                 sc->sc_stats.ast_watchdog++;
6133         }
6134         callout_reset(&sc->sc_wd_ch, hz, ath_watchdog_callout, sc);
6135         wlan_serialize_exit();
6136 }
6137
6138 #ifdef ATH_DIAGAPI
6139 /*
6140  * Diagnostic interface to the HAL.  This is used by various
6141  * tools to do things like retrieve register contents for
6142  * debugging.  The mechanism is intentionally opaque so that
6143  * it can change frequently w/o concern for compatiblity.
6144  */
6145 static int
6146 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
6147 {
6148         struct ath_hal *ah = sc->sc_ah;
6149         u_int id = ad->ad_id & ATH_DIAG_ID;
6150         void *indata = NULL;
6151         void *outdata = NULL;
6152         u_int32_t insize = ad->ad_in_size;
6153         u_int32_t outsize = ad->ad_out_size;
6154         int error = 0;
6155
6156         if (ad->ad_id & ATH_DIAG_IN) {
6157                 /*
6158                  * Copy in data.
6159                  */
6160                 indata = kmalloc(insize, M_TEMP, M_INTWAIT);
6161                 if (indata == NULL) {
6162                         error = ENOMEM;
6163                         goto bad;
6164                 }
6165                 error = copyin(ad->ad_in_data, indata, insize);
6166                 if (error)
6167                         goto bad;
6168         }
6169         if (ad->ad_id & ATH_DIAG_DYN) {
6170                 /*
6171                  * Allocate a buffer for the results (otherwise the HAL
6172                  * returns a pointer to a buffer where we can read the
6173                  * results).  Note that we depend on the HAL leaving this
6174                  * pointer for us to use below in reclaiming the buffer;
6175                  * may want to be more defensive.
6176                  */
6177                 outdata = kmalloc(outsize, M_TEMP, M_INTWAIT);
6178                 if (outdata == NULL) {
6179                         error = ENOMEM;
6180                         goto bad;
6181                 }
6182         }
6183         if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
6184                 if (outsize < ad->ad_out_size)
6185                         ad->ad_out_size = outsize;
6186                 if (outdata != NULL)
6187                         error = copyout(outdata, ad->ad_out_data,
6188                                         ad->ad_out_size);
6189         } else {
6190                 error = EINVAL;
6191         }
6192 bad:
6193         if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
6194                 kfree(indata, M_TEMP);
6195         if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
6196                 kfree(outdata, M_TEMP);
6197         return error;
6198 }
6199 #endif /* ATH_DIAGAPI */
6200
6201 static int
6202 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *ucred)
6203 {
6204 #define IS_RUNNING(ifp) \
6205         ((ifp->if_flags & IFF_UP) && (ifp->if_flags & IFF_RUNNING))
6206         struct ath_softc *sc = ifp->if_softc;
6207         struct ieee80211com *ic = ifp->if_l2com;
6208         struct ifreq *ifr = (struct ifreq *)data;
6209         const HAL_RATE_TABLE *rt;
6210         int error = 0;
6211
6212         wlan_assert_serialized();
6213
6214         switch (cmd) {
6215         case SIOCSIFFLAGS:
6216                 if (IS_RUNNING(ifp)) {
6217                         /*
6218                          * To avoid rescanning another access point,
6219                          * do not call ath_init() here.  Instead,
6220                          * only reflect promisc mode settings.
6221                          */
6222                         ath_mode_init(sc);
6223                 } else if (ifp->if_flags & IFF_UP) {
6224                         /*
6225                          * Beware of being called during attach/detach
6226                          * to reset promiscuous mode.  In that case we
6227                          * will still be marked UP but not RUNNING.
6228                          * However trying to re-init the interface
6229                          * is the wrong thing to do as we've already
6230                          * torn down much of our state.  There's
6231                          * probably a better way to deal with this.
6232                          */
6233                         if (!sc->sc_invalid)
6234                                 ath_init(sc);   /* XXX lose error */
6235                 } else {
6236                         ath_stop_locked(ifp);
6237 #ifdef notyet
6238                         /* XXX must wakeup in places like ath_vap_delete */
6239                         if (!sc->sc_invalid)
6240                                 ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP);
6241 #endif
6242                 }
6243                 break;
6244         case SIOCGIFMEDIA:
6245         case SIOCSIFMEDIA:
6246                 error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
6247                 break;
6248         case SIOCGATHSTATS:
6249                 /* NB: embed these numbers to get a consistent view */
6250                 sc->sc_stats.ast_tx_packets = ifp->if_opackets;
6251                 sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
6252                 sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
6253                 sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
6254 #ifdef IEEE80211_SUPPORT_TDMA
6255                 sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
6256                 sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
6257 #endif
6258                 rt = sc->sc_currates;
6259                 /* XXX HT rates */
6260                 sc->sc_stats.ast_tx_rate =
6261                     rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
6262                 return copyout(&sc->sc_stats,
6263                     ifr->ifr_data, sizeof (sc->sc_stats));
6264         case SIOCZATHSTATS:
6265                 error = priv_check(curthread, PRIV_DRIVER);
6266                 if (error == 0)
6267                         memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
6268                 break;
6269 #ifdef ATH_DIAGAPI
6270         case SIOCGATHDIAG:
6271                 error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
6272                 break;
6273 #endif
6274         case SIOCGIFADDR:
6275                 error = ether_ioctl(ifp, cmd, data);
6276                 break;
6277         default:
6278                 error = EINVAL;
6279                 break;
6280         }
6281         return error;
6282 #undef IS_RUNNING
6283 }
6284
6285 static int
6286 ath_sysctl_slottime(SYSCTL_HANDLER_ARGS)
6287 {
6288         struct ath_softc *sc = arg1;
6289         u_int slottime;
6290         int error;
6291
6292         wlan_serialize_enter();
6293         slottime = ath_hal_getslottime(sc->sc_ah);
6294         error = sysctl_handle_int(oidp, &slottime, 0, req);
6295         if (error == 0 && req->newptr) {
6296                 if (!ath_hal_setslottime(sc->sc_ah, slottime))
6297                         error = EINVAL;
6298         }
6299         wlan_serialize_exit();
6300         return error;
6301 }
6302
6303 static int
6304 ath_sysctl_acktimeout(SYSCTL_HANDLER_ARGS)
6305 {
6306         struct ath_softc *sc = arg1;
6307         u_int acktimeout;
6308         int error;
6309
6310         wlan_serialize_enter();
6311         acktimeout = ath_hal_getacktimeout(sc->sc_ah);
6312         error = sysctl_handle_int(oidp, &acktimeout, 0, req);
6313         if (error == 0 && req->newptr) {
6314                 if (!ath_hal_setacktimeout(sc->sc_ah, acktimeout))
6315                         error = EINVAL;
6316         }
6317         wlan_serialize_exit();
6318         return error;
6319 }
6320
6321 static int
6322 ath_sysctl_ctstimeout(SYSCTL_HANDLER_ARGS)
6323 {
6324         struct ath_softc *sc = arg1;
6325         u_int ctstimeout;
6326         int error;
6327
6328         wlan_serialize_enter();
6329         ctstimeout = ath_hal_getctstimeout(sc->sc_ah);
6330         error = sysctl_handle_int(oidp, &ctstimeout, 0, req);
6331         if (error == 0 && req->newptr) {
6332                 if (!ath_hal_setctstimeout(sc->sc_ah, ctstimeout))
6333                         error = EINVAL;
6334         }
6335         wlan_serialize_exit();
6336         return error;
6337 }
6338
6339 static int
6340 ath_sysctl_softled(SYSCTL_HANDLER_ARGS)
6341 {
6342         struct ath_softc *sc = arg1;
6343         int softled = sc->sc_softled;
6344         int error;
6345
6346         error = sysctl_handle_int(oidp, &softled, 0, req);
6347         if (error || !req->newptr)
6348                 return error;
6349         wlan_serialize_enter();
6350         softled = (softled != 0);
6351         if (softled != sc->sc_softled) {
6352                 if (softled) {
6353                         /* NB: handle any sc_ledpin change */
6354                         ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin,
6355                             HAL_GPIO_MUX_MAC_NETWORK_LED);
6356                         ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
6357                                 !sc->sc_ledon);
6358                 }
6359                 sc->sc_softled = softled;
6360         }
6361         wlan_serialize_exit();
6362         return 0;
6363 }
6364
6365 static int
6366 ath_sysctl_ledpin(SYSCTL_HANDLER_ARGS)
6367 {
6368         struct ath_softc *sc = arg1;
6369         int ledpin = sc->sc_ledpin;
6370         int error;
6371
6372         error = sysctl_handle_int(oidp, &ledpin, 0, req);
6373         if (error || !req->newptr)
6374                 return error;
6375         wlan_serialize_enter();
6376         if (ledpin != sc->sc_ledpin) {
6377                 sc->sc_ledpin = ledpin;
6378                 if (sc->sc_softled) {
6379                         ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin,
6380                             HAL_GPIO_MUX_MAC_NETWORK_LED);
6381                         ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
6382                                 !sc->sc_ledon);
6383                 }
6384         }
6385         wlan_serialize_exit();
6386         return 0;
6387 }
6388
6389 static int
6390 ath_sysctl_txantenna(SYSCTL_HANDLER_ARGS)
6391 {
6392         struct ath_softc *sc = arg1;
6393         u_int txantenna;
6394         int error;
6395
6396         wlan_serialize_enter();
6397         txantenna = ath_hal_getantennaswitch(sc->sc_ah);
6398         error = sysctl_handle_int(oidp, &txantenna, 0, req);
6399
6400         if (!error && req->newptr) {
6401                 /* XXX assumes 2 antenna ports */
6402                 if (txantenna < HAL_ANT_VARIABLE ||
6403                     txantenna > HAL_ANT_FIXED_B) {
6404                         error = EINVAL;
6405                 } else {
6406                         ath_hal_setantennaswitch(sc->sc_ah, txantenna);
6407                         /*
6408                          * NB: with the switch locked this isn't meaningful,
6409                          *     but set it anyway so things like radiotap get
6410                          *     consistent info in their data.
6411                          */
6412                         sc->sc_txantenna = txantenna;
6413                 }
6414         }
6415         wlan_serialize_exit();
6416         return error;
6417 }
6418
6419 static int
6420 ath_sysctl_rxantenna(SYSCTL_HANDLER_ARGS)
6421 {
6422         struct ath_softc *sc = arg1;
6423         u_int defantenna;
6424         int error;
6425
6426         wlan_serialize_enter();
6427         defantenna = ath_hal_getdefantenna(sc->sc_ah);
6428         error = sysctl_handle_int(oidp, &defantenna, 0, req);
6429         if (error == 0 && req->newptr)
6430                 ath_hal_setdefantenna(sc->sc_ah, defantenna);
6431         wlan_serialize_exit();
6432         return error;
6433 }
6434
6435 static int
6436 ath_sysctl_diversity(SYSCTL_HANDLER_ARGS)
6437 {
6438         struct ath_softc *sc = arg1;
6439         u_int diversity;
6440         int error;
6441
6442         wlan_serialize_enter();
6443         diversity = ath_hal_getdiversity(sc->sc_ah);
6444         error = sysctl_handle_int(oidp, &diversity, 0, req);
6445         if (error == 0 && req->newptr) {
6446                 if (!ath_hal_setdiversity(sc->sc_ah, diversity))
6447                         error = EINVAL;
6448                 else
6449                         sc->sc_diversity = diversity;
6450         }
6451         wlan_serialize_exit();
6452         return error;
6453 }
6454
6455 static int
6456 ath_sysctl_diag(SYSCTL_HANDLER_ARGS)
6457 {
6458         struct ath_softc *sc = arg1;
6459         u_int32_t diag;
6460         int error;
6461
6462         wlan_serialize_enter();
6463         if (!ath_hal_getdiag(sc->sc_ah, &diag)) {
6464                 error = EINVAL;
6465         } else {
6466                 error = sysctl_handle_int(oidp, &diag, 0, req);
6467                 if (error == 0 && req->newptr) {
6468                         if (!ath_hal_setdiag(sc->sc_ah, diag))
6469                                 error = EINVAL;
6470                 }
6471         }
6472         wlan_serialize_exit();
6473         return error;
6474 }
6475
6476 static int
6477 ath_sysctl_tpscale(SYSCTL_HANDLER_ARGS)
6478 {
6479         struct ath_softc *sc = arg1;
6480         struct ifnet *ifp = sc->sc_ifp;
6481         u_int32_t scale;
6482         int error;
6483
6484         wlan_serialize_enter();
6485         (void)ath_hal_gettpscale(sc->sc_ah, &scale);
6486         error = sysctl_handle_int(oidp, &scale, 0, req);
6487         if (error == 0 && req->newptr) {
6488                 if (!ath_hal_settpscale(sc->sc_ah, scale))
6489                         error = EINVAL;
6490                 else if (ifp->if_flags & IFF_RUNNING)
6491                         error = ath_reset(ifp);
6492         }
6493         wlan_serialize_exit();
6494         return error;
6495 }
6496
6497 static int
6498 ath_sysctl_tpc(SYSCTL_HANDLER_ARGS)
6499 {
6500         struct ath_softc *sc = arg1;
6501         u_int tpc;
6502         int error;
6503
6504         wlan_serialize_enter();
6505         tpc = ath_hal_gettpc(sc->sc_ah);
6506         error = sysctl_handle_int(oidp, &tpc, 0, req);
6507         if (error == 0 && req->newptr) {
6508                 if (!ath_hal_settpc(sc->sc_ah, tpc))
6509                         error = EINVAL;
6510         }
6511         wlan_serialize_exit();
6512         return error;
6513 }
6514
6515 static int
6516 ath_sysctl_rfkill(SYSCTL_HANDLER_ARGS)
6517 {
6518         struct ath_softc *sc = arg1;
6519         struct ifnet *ifp;
6520         struct ath_hal *ah;
6521         u_int rfkill;
6522         int error;
6523
6524         wlan_serialize_enter();
6525         ifp = sc->sc_ifp;
6526         ah = sc->sc_ah;
6527         rfkill = ath_hal_getrfkill(ah);
6528
6529         error = sysctl_handle_int(oidp, &rfkill, 0, req);
6530         if (error == 0 && req->newptr) {
6531                 if (rfkill != ath_hal_getrfkill(ah)) {
6532                         if (!ath_hal_setrfkill(ah, rfkill))
6533                                 error = EINVAL;
6534                         else if (ifp->if_flags & IFF_RUNNING)
6535                                 error = ath_reset(ifp);
6536                 }
6537         }
6538         wlan_serialize_exit();
6539         return error;
6540 }
6541
6542 static int
6543 ath_sysctl_rfsilent(SYSCTL_HANDLER_ARGS)
6544 {
6545         struct ath_softc *sc = arg1;
6546         u_int rfsilent;
6547         int error;
6548
6549         wlan_serialize_enter();
6550         (void)ath_hal_getrfsilent(sc->sc_ah, &rfsilent);
6551         error = sysctl_handle_int(oidp, &rfsilent, 0, req);
6552         if (error == 0 && req->newptr) {
6553                 if (!ath_hal_setrfsilent(sc->sc_ah, rfsilent)) {
6554                         error = EINVAL;
6555                 } else {
6556                         sc->sc_rfsilentpin = rfsilent & 0x1c;
6557                         sc->sc_rfsilentpol = (rfsilent & 0x2) != 0;
6558                 }
6559         }
6560         wlan_serialize_exit();
6561         return error;
6562 }
6563
6564 static int
6565 ath_sysctl_tpack(SYSCTL_HANDLER_ARGS)
6566 {
6567         struct ath_softc *sc = arg1;
6568         u_int32_t tpack;
6569         int error;
6570
6571         wlan_serialize_enter();
6572         (void)ath_hal_gettpack(sc->sc_ah, &tpack);
6573         error = sysctl_handle_int(oidp, &tpack, 0, req);
6574         if (error == 0 && req->newptr) {
6575                 if (!ath_hal_settpack(sc->sc_ah, tpack))
6576                         error = EINVAL;
6577         }
6578         wlan_serialize_exit();
6579         return error;
6580 }
6581
6582 static int
6583 ath_sysctl_tpcts(SYSCTL_HANDLER_ARGS)
6584 {
6585         struct ath_softc *sc = arg1;
6586         u_int32_t tpcts;
6587         int error;
6588
6589         wlan_serialize_enter();
6590         (void)ath_hal_gettpcts(sc->sc_ah, &tpcts);
6591         error = sysctl_handle_int(oidp, &tpcts, 0, req);
6592         if (error == 0 && req->newptr) {
6593                 if (!ath_hal_settpcts(sc->sc_ah, tpcts))
6594                         error = EINVAL;
6595         }
6596         wlan_serialize_exit();
6597         return error;
6598 }
6599
6600 static int
6601 ath_sysctl_intmit(SYSCTL_HANDLER_ARGS)
6602 {
6603         struct ath_softc *sc = arg1;
6604         int intmit, error;
6605
6606         wlan_serialize_enter();
6607         intmit = ath_hal_getintmit(sc->sc_ah);
6608         error = sysctl_handle_int(oidp, &intmit, 0, req);
6609         if (error == 0 && req->newptr) {
6610                 if (!ath_hal_setintmit(sc->sc_ah, intmit))
6611                         error = EINVAL;
6612         }
6613         wlan_serialize_exit();
6614         return error;
6615 }
6616
6617 #ifdef IEEE80211_SUPPORT_TDMA
6618 static int
6619 ath_sysctl_setcca(SYSCTL_HANDLER_ARGS)
6620 {
6621         struct ath_softc *sc = arg1;
6622         int setcca, error;
6623
6624         wlan_serialize_enter();
6625         setcca = sc->sc_setcca;
6626         error = sysctl_handle_int(oidp, &setcca, 0, req);
6627         if (error == 0 && req->newptr)
6628                 sc->sc_setcca = (setcca != 0);
6629         wlan_serialize_exit();
6630         return error;
6631 }
6632 #endif /* IEEE80211_SUPPORT_TDMA */
6633
6634 static void
6635 ath_sysctlattach(struct ath_softc *sc)
6636 {
6637         struct sysctl_ctx_list *ctx;
6638         struct sysctl_oid *tree;
6639         struct ath_hal *ah = sc->sc_ah;
6640
6641         ctx = &sc->sc_sysctl_ctx;
6642         tree = sc->sc_sysctl_tree;
6643         if (tree == NULL) {
6644                 device_printf(sc->sc_dev, "can't add sysctl node\n");
6645                 return;
6646         }
6647
6648         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6649                 "countrycode", CTLFLAG_RD, &sc->sc_eecc, 0,
6650                 "EEPROM country code");
6651         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6652                 "regdomain", CTLFLAG_RD, &sc->sc_eerd, 0,
6653                 "EEPROM regdomain code");
6654 #ifdef  ATH_DEBUG
6655         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6656                 "debug", CTLFLAG_RW, &sc->sc_debug, 0,
6657                 "control debugging printfs");
6658 #endif
6659         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6660                 "slottime", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6661                 ath_sysctl_slottime, "I", "802.11 slot time (us)");
6662         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6663                 "acktimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6664                 ath_sysctl_acktimeout, "I", "802.11 ACK timeout (us)");
6665         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6666                 "ctstimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6667                 ath_sysctl_ctstimeout, "I", "802.11 CTS timeout (us)");
6668         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6669                 "softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6670                 ath_sysctl_softled, "I", "enable/disable software LED support");
6671         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6672                 "ledpin", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6673                 ath_sysctl_ledpin, "I", "GPIO pin connected to LED");
6674         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6675                 "ledon", CTLFLAG_RW, &sc->sc_ledon, 0,
6676                 "setting to turn LED on");
6677         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6678                 "ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
6679                 "idle time for inactivity LED (ticks)");
6680         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6681                 "txantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6682                 ath_sysctl_txantenna, "I", "antenna switch");
6683         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6684                 "rxantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6685                 ath_sysctl_rxantenna, "I", "default/rx antenna");
6686         if (ath_hal_hasdiversity(ah))
6687                 SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6688                         "diversity", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6689                         ath_sysctl_diversity, "I", "antenna diversity");
6690         sc->sc_txintrperiod = ATH_TXINTR_PERIOD;
6691         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6692                 "txintrperiod", CTLFLAG_RW, &sc->sc_txintrperiod, 0,
6693                 "tx descriptor batching");
6694         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6695                 "diag", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6696                 ath_sysctl_diag, "I", "h/w diagnostic control");
6697         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6698                 "tpscale", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6699                 ath_sysctl_tpscale, "I", "tx power scaling");
6700         if (ath_hal_hastpc(ah)) {
6701                 SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6702                         "tpc", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6703                         ath_sysctl_tpc, "I", "enable/disable per-packet TPC");
6704                 SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6705                         "tpack", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6706                         ath_sysctl_tpack, "I", "tx power for ack frames");
6707                 SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6708                         "tpcts", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6709                         ath_sysctl_tpcts, "I", "tx power for cts frames");
6710         }
6711         if (ath_hal_hasrfsilent(ah)) {
6712                 SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6713                         "rfsilent", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6714                         ath_sysctl_rfsilent, "I", "h/w RF silent config");
6715                 SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6716                         "rfkill", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6717                         ath_sysctl_rfkill, "I", "enable/disable RF kill switch");
6718         }
6719         if (ath_hal_hasintmit(ah)) {
6720                 SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6721                         "intmit", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6722                         ath_sysctl_intmit, "I", "interference mitigation");
6723         }
6724         sc->sc_monpass = HAL_RXERR_DECRYPT | HAL_RXERR_MIC;
6725         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6726                 "monpass", CTLFLAG_RW, &sc->sc_monpass, 0,
6727                 "mask of error frames to pass when monitoring");
6728 #ifdef IEEE80211_SUPPORT_TDMA
6729         if (ath_hal_macversion(ah) > 0x78) {
6730                 sc->sc_tdmadbaprep = 2;
6731                 SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6732                         "dbaprep", CTLFLAG_RW, &sc->sc_tdmadbaprep, 0,
6733                         "TDMA DBA preparation time");
6734                 sc->sc_tdmaswbaprep = 10;
6735                 SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6736                         "swbaprep", CTLFLAG_RW, &sc->sc_tdmaswbaprep, 0,
6737                         "TDMA SWBA preparation time");
6738                 SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6739                         "guardtime", CTLFLAG_RW, &sc->sc_tdmaguard, 0,
6740                         "TDMA slot guard time");
6741                 SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6742                         "superframe", CTLFLAG_RD, &sc->sc_tdmabintval, 0,
6743                         "TDMA calculated super frame");
6744                 SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
6745                         "setcca", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
6746                         ath_sysctl_setcca, "I", "enable CCA control");
6747         }
6748 #endif
6749 }
6750
6751 static int
6752 ath_tx_raw_start(struct ath_softc *sc, struct ieee80211_node *ni,
6753         struct ath_buf *bf, struct mbuf *m0,
6754         const struct ieee80211_bpf_params *params)
6755 {
6756         struct ifnet *ifp = sc->sc_ifp;
6757         struct ieee80211com *ic = ifp->if_l2com;
6758         struct ath_hal *ah = sc->sc_ah;
6759         struct ieee80211vap *vap = ni->ni_vap;
6760         int error, ismcast, ismrr;
6761         int keyix, hdrlen, pktlen, try0, txantenna;
6762         u_int8_t rix, cix, txrate, ctsrate, rate1, rate2, rate3;
6763         struct ieee80211_frame *wh;
6764         u_int flags, ctsduration;
6765         HAL_PKT_TYPE atype;
6766         const HAL_RATE_TABLE *rt;
6767         struct ath_desc *ds;
6768         u_int pri;
6769
6770         wh = mtod(m0, struct ieee80211_frame *);
6771         ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
6772         hdrlen = ieee80211_anyhdrsize(wh);
6773         /*
6774          * Packet length must not include any
6775          * pad bytes; deduct them here.
6776          */
6777         /* XXX honor IEEE80211_BPF_DATAPAD */
6778         pktlen = m0->m_pkthdr.len - (hdrlen & 3) + IEEE80211_CRC_LEN;
6779
6780         if (params->ibp_flags & IEEE80211_BPF_CRYPTO) {
6781                 const struct ieee80211_cipher *cip;
6782                 struct ieee80211_key *k;
6783
6784                 /*
6785                  * Construct the 802.11 header+trailer for an encrypted
6786                  * frame. The only reason this can fail is because of an
6787                  * unknown or unsupported cipher/key type.
6788                  */
6789                 k = ieee80211_crypto_encap(ni, m0);
6790                 if (k == NULL) {
6791                         /*
6792                          * This can happen when the key is yanked after the
6793                          * frame was queued.  Just discard the frame; the
6794                          * 802.11 layer counts failures and provides
6795                          * debugging/diagnostics.
6796                          */
6797                         ath_freetx(m0);
6798                         return EIO;
6799                 }
6800                 /*
6801                  * Adjust the packet + header lengths for the crypto
6802                  * additions and calculate the h/w key index.  When
6803                  * a s/w mic is done the frame will have had any mic
6804                  * added to it prior to entry so m0->m_pkthdr.len will
6805                  * account for it. Otherwise we need to add it to the
6806                  * packet length.
6807                  */
6808                 cip = k->wk_cipher;
6809                 hdrlen += cip->ic_header;
6810                 pktlen += cip->ic_header + cip->ic_trailer;
6811                 /* NB: frags always have any TKIP MIC done in s/w */
6812                 if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0)
6813                         pktlen += cip->ic_miclen;
6814                 keyix = k->wk_keyix;
6815
6816                 /* packet header may have moved, reset our local pointer */
6817                 wh = mtod(m0, struct ieee80211_frame *);
6818         } else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
6819                 /*
6820                  * Use station key cache slot, if assigned.
6821                  */
6822                 keyix = ni->ni_ucastkey.wk_keyix;
6823                 if (keyix == IEEE80211_KEYIX_NONE)
6824                         keyix = HAL_TXKEYIX_INVALID;
6825         } else
6826                 keyix = HAL_TXKEYIX_INVALID;
6827
6828         error = ath_tx_dmasetup(sc, bf, m0);
6829         if (error != 0)
6830                 return error;
6831         m0 = bf->bf_m;                          /* NB: may have changed */
6832         wh = mtod(m0, struct ieee80211_frame *);
6833         bf->bf_node = ni;                       /* NB: held reference */
6834
6835         flags = HAL_TXDESC_CLRDMASK;            /* XXX needed for crypto errs */
6836         flags |= HAL_TXDESC_INTREQ;             /* force interrupt */
6837         if (params->ibp_flags & IEEE80211_BPF_RTS)
6838                 flags |= HAL_TXDESC_RTSENA;
6839         else if (params->ibp_flags & IEEE80211_BPF_CTS)
6840                 flags |= HAL_TXDESC_CTSENA;
6841         /* XXX leave ismcast to injector? */
6842         if ((params->ibp_flags & IEEE80211_BPF_NOACK) || ismcast)
6843                 flags |= HAL_TXDESC_NOACK;
6844
6845         rt = sc->sc_currates;
6846         KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
6847         rix = ath_tx_findrix(sc, params->ibp_rate0);
6848         txrate = rt->info[rix].rateCode;
6849         if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
6850                 txrate |= rt->info[rix].shortPreamble;
6851         sc->sc_txrix = rix;
6852         try0 = params->ibp_try0;
6853         ismrr = (params->ibp_try1 != 0);
6854         txantenna = params->ibp_pri >> 2;
6855         if (txantenna == 0)                     /* XXX? */
6856                 txantenna = sc->sc_txantenna;
6857         ctsduration = 0;
6858         if (flags & (HAL_TXDESC_CTSENA | HAL_TXDESC_RTSENA)) {
6859                 cix = ath_tx_findrix(sc, params->ibp_ctsrate);
6860                 ctsrate = rt->info[cix].rateCode;
6861                 if (params->ibp_flags & IEEE80211_BPF_SHORTPRE) {
6862                         ctsrate |= rt->info[cix].shortPreamble;
6863                         if (flags & HAL_TXDESC_RTSENA)          /* SIFS + CTS */
6864                                 ctsduration += rt->info[cix].spAckDuration;
6865                         ctsduration += ath_hal_computetxtime(ah,
6866                                 rt, pktlen, rix, AH_TRUE);
6867                         if ((flags & HAL_TXDESC_NOACK) == 0)    /* SIFS + ACK */
6868                                 ctsduration += rt->info[rix].spAckDuration;
6869                 } else {
6870                         if (flags & HAL_TXDESC_RTSENA)          /* SIFS + CTS */
6871                                 ctsduration += rt->info[cix].lpAckDuration;
6872                         ctsduration += ath_hal_computetxtime(ah,
6873                                 rt, pktlen, rix, AH_FALSE);
6874                         if ((flags & HAL_TXDESC_NOACK) == 0)    /* SIFS + ACK */
6875                                 ctsduration += rt->info[rix].lpAckDuration;
6876                 }
6877                 ismrr = 0;                      /* XXX */
6878         } else
6879                 ctsrate = 0;
6880         pri = params->ibp_pri & 3;
6881         /*
6882          * NB: we mark all packets as type PSPOLL so the h/w won't
6883          * set the sequence number, duration, etc.
6884          */
6885         atype = HAL_PKT_TYPE_PSPOLL;
6886
6887         if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
6888                 ieee80211_dump_pkt(ic, mtod(m0, caddr_t), m0->m_len,
6889                     sc->sc_hwmap[rix].ieeerate, -1);
6890         
6891         if (ieee80211_radiotap_active_vap(vap)) {
6892                 u_int64_t tsf = ath_hal_gettsf64(ah);
6893
6894                 sc->sc_tx_th.wt_tsf = htole64(tsf);
6895                 sc->sc_tx_th.wt_flags = sc->sc_hwmap[rix].txflags;
6896                 if (wh->i_fc[1] & IEEE80211_FC1_WEP)
6897                         sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
6898                 if (m0->m_flags & M_FRAG)
6899                         sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
6900                 sc->sc_tx_th.wt_rate = sc->sc_hwmap[rix].ieeerate;
6901                 sc->sc_tx_th.wt_txpower = ni->ni_txpower;
6902                 sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
6903
6904                 ieee80211_radiotap_tx(vap, m0);
6905         }
6906
6907         /*
6908          * Formulate first tx descriptor with tx controls.
6909          */
6910         ds = bf->bf_desc;
6911         /* XXX check return value? */
6912         ath_hal_setuptxdesc(ah, ds
6913                 , pktlen                /* packet length */
6914                 , hdrlen                /* header length */
6915                 , atype                 /* Atheros packet type */
6916                 , params->ibp_power     /* txpower */
6917                 , txrate, try0          /* series 0 rate/tries */
6918                 , keyix                 /* key cache index */
6919                 , txantenna             /* antenna mode */
6920                 , flags                 /* flags */
6921                 , ctsrate               /* rts/cts rate */
6922                 , ctsduration           /* rts/cts duration */
6923         );
6924         bf->bf_txflags = flags;
6925
6926         if (ismrr) {
6927                 rix = ath_tx_findrix(sc, params->ibp_rate1);
6928                 rate1 = rt->info[rix].rateCode;
6929                 if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
6930                         rate1 |= rt->info[rix].shortPreamble;
6931                 if (params->ibp_try2) {
6932                         rix = ath_tx_findrix(sc, params->ibp_rate2);
6933                         rate2 = rt->info[rix].rateCode;
6934                         if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
6935                                 rate2 |= rt->info[rix].shortPreamble;
6936                 } else
6937                         rate2 = 0;
6938                 if (params->ibp_try3) {
6939                         rix = ath_tx_findrix(sc, params->ibp_rate3);
6940                         rate3 = rt->info[rix].rateCode;
6941                         if (params->ibp_flags & IEEE80211_BPF_SHORTPRE)
6942                                 rate3 |= rt->info[rix].shortPreamble;
6943                 } else
6944                         rate3 = 0;
6945                 ath_hal_setupxtxdesc(ah, ds
6946                         , rate1, params->ibp_try1       /* series 1 */
6947                         , rate2, params->ibp_try2       /* series 2 */
6948                         , rate3, params->ibp_try3       /* series 3 */
6949                 );
6950         }
6951
6952         /* NB: no buffered multicast in power save support */
6953         ath_tx_handoff(sc, sc->sc_ac2q[pri], bf);
6954         return 0;
6955 }
6956
6957 static int
6958 ath_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
6959         const struct ieee80211_bpf_params *params)
6960 {
6961         struct ieee80211com *ic = ni->ni_ic;
6962         struct ifnet *ifp = ic->ic_ifp;
6963         struct ath_softc *sc = ifp->if_softc;
6964         struct ath_buf *bf;
6965         int error;
6966
6967         if ((ifp->if_flags & IFF_RUNNING) == 0 || sc->sc_invalid) {
6968                 DPRINTF(sc, ATH_DEBUG_XMIT, "%s: discard frame, %s", __func__,
6969                     (ifp->if_flags & IFF_RUNNING) == 0 ?
6970                         "!running" : "invalid");
6971                 m_freem(m);
6972                 error = ENETDOWN;
6973                 goto bad;
6974         }
6975         /*
6976          * Grab a TX buffer and associated resources.
6977          */
6978         bf = ath_getbuf(sc);
6979         if (bf == NULL) {
6980                 sc->sc_stats.ast_tx_nobuf++;
6981                 m_freem(m);
6982                 error = ENOBUFS;
6983                 goto bad;
6984         }
6985
6986         if (params == NULL) {
6987                 /*
6988                  * Legacy path; interpret frame contents to decide
6989                  * precisely how to send the frame.
6990                  */
6991                 if (ath_tx_start(sc, ni, bf, m)) {
6992                         error = EIO;            /* XXX */
6993                         goto bad2;
6994                 }
6995         } else {
6996                 /*
6997                  * Caller supplied explicit parameters to use in
6998                  * sending the frame.
6999                  */
7000                 if (ath_tx_raw_start(sc, ni, bf, m, params)) {
7001                         error = EIO;            /* XXX */
7002                         goto bad2;
7003                 }
7004         }
7005         sc->sc_wd_timer = 5;
7006         ifp->if_opackets++;
7007         sc->sc_stats.ast_tx_raw++;
7008
7009         return 0;
7010 bad2:
7011         STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
7012 bad:
7013         ifp->if_oerrors++;
7014         sc->sc_stats.ast_tx_raw_fail++;
7015         ieee80211_free_node(ni);
7016         return error;
7017 }
7018
7019 /*
7020  * Announce various information on device/driver attach.
7021  */
7022 static void
7023 ath_announce(struct ath_softc *sc)
7024 {
7025         struct ifnet *ifp = sc->sc_ifp;
7026         struct ath_hal *ah = sc->sc_ah;
7027
7028         if_printf(ifp, "AR%s mac %d.%d RF%s phy %d.%d\n",
7029                 ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
7030                 ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
7031         if (bootverbose) {
7032                 int i;
7033                 for (i = 0; i <= WME_AC_VO; i++) {
7034                         struct ath_txq *txq = sc->sc_ac2q[i];
7035                         if_printf(ifp, "Use hw queue %u for %s traffic\n",
7036                                 txq->axq_qnum, ieee80211_wme_acnames[i]);
7037                 }
7038                 if_printf(ifp, "Use hw queue %u for CAB traffic\n",
7039                         sc->sc_cabq->axq_qnum);
7040                 if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
7041         }
7042         if (ath_rxbuf != ATH_RXBUF)
7043                 if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
7044         if (ath_txbuf != ATH_TXBUF)
7045                 if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
7046         if (sc->sc_mcastkey && bootverbose)
7047                 if_printf(ifp, "using multicast key search\n");
7048 }
7049
7050 #ifdef IEEE80211_SUPPORT_TDMA
7051 static __inline uint32_t
7052 ath_hal_getnexttbtt(struct ath_hal *ah)
7053 {
7054 #define AR_TIMER0       0x8028
7055         return OS_REG_READ(ah, AR_TIMER0);
7056 }
7057
7058 static __inline void
7059 ath_hal_adjusttsf(struct ath_hal *ah, int32_t tsfdelta)
7060 {
7061         /* XXX handle wrap/overflow */
7062         OS_REG_WRITE(ah, AR_TSF_L32, OS_REG_READ(ah, AR_TSF_L32) + tsfdelta);
7063 }
7064
7065 static void
7066 ath_tdma_settimers(struct ath_softc *sc, u_int32_t nexttbtt, u_int32_t bintval)
7067 {
7068         struct ath_hal *ah = sc->sc_ah;
7069         HAL_BEACON_TIMERS bt;
7070
7071         bt.bt_intval = bintval | HAL_BEACON_ENA;
7072         bt.bt_nexttbtt = nexttbtt;
7073         bt.bt_nextdba = (nexttbtt<<3) - sc->sc_tdmadbaprep;
7074         bt.bt_nextswba = (nexttbtt<<3) - sc->sc_tdmaswbaprep;
7075         bt.bt_nextatim = nexttbtt+1;
7076         ath_hal_beaconsettimers(ah, &bt);
7077 }
7078
7079 /*
7080  * Calculate the beacon interval.  This is periodic in the
7081  * superframe for the bss.  We assume each station is configured
7082  * identically wrt transmit rate so the guard time we calculate
7083  * above will be the same on all stations.  Note we need to
7084  * factor in the xmit time because the hardware will schedule
7085  * a frame for transmit if the start of the frame is within
7086  * the burst time.  When we get hardware that properly kills
7087  * frames in the PCU we can reduce/eliminate the guard time.
7088  *
7089  * Roundup to 1024 is so we have 1 TU buffer in the guard time
7090  * to deal with the granularity of the nexttbtt timer.  11n MAC's
7091  * with 1us timer granularity should allow us to reduce/eliminate
7092  * this.
7093  */
7094 static void
7095 ath_tdma_bintvalsetup(struct ath_softc *sc,
7096         const struct ieee80211_tdma_state *tdma)
7097 {
7098         /* copy from vap state (XXX check all vaps have same value?) */
7099         sc->sc_tdmaslotlen = tdma->tdma_slotlen;
7100
7101         sc->sc_tdmabintval = roundup((sc->sc_tdmaslotlen+sc->sc_tdmaguard) *
7102                 tdma->tdma_slotcnt, 1024);
7103         sc->sc_tdmabintval >>= 10;              /* TSF -> TU */
7104         if (sc->sc_tdmabintval & 1)
7105                 sc->sc_tdmabintval++;
7106
7107         if (tdma->tdma_slot == 0) {
7108                 /*
7109                  * Only slot 0 beacons; other slots respond.
7110                  */
7111                 sc->sc_imask |= HAL_INT_SWBA;
7112                 sc->sc_tdmaswba = 0;            /* beacon immediately */
7113         } else {
7114                 /* XXX all vaps must be slot 0 or slot !0 */
7115                 sc->sc_imask &= ~HAL_INT_SWBA;
7116         }
7117 }
7118
7119 /*
7120  * Max 802.11 overhead.  This assumes no 4-address frames and
7121  * the encapsulation done by ieee80211_encap (llc).  We also
7122  * include potential crypto overhead.
7123  */
7124 #define IEEE80211_MAXOVERHEAD \
7125         (sizeof(struct ieee80211_qosframe) \
7126          + sizeof(struct llc) \
7127          + IEEE80211_ADDR_LEN \
7128          + IEEE80211_WEP_IVLEN \
7129          + IEEE80211_WEP_KIDLEN \
7130          + IEEE80211_WEP_CRCLEN \
7131          + IEEE80211_WEP_MICLEN \
7132          + IEEE80211_CRC_LEN)
7133
7134 /*
7135  * Setup initially for tdma operation.  Start the beacon
7136  * timers and enable SWBA if we are slot 0.  Otherwise
7137  * we wait for slot 0 to arrive so we can sync up before
7138  * starting to transmit.
7139  */
7140 static void
7141 ath_tdma_config(struct ath_softc *sc, struct ieee80211vap *vap)
7142 {
7143         struct ath_hal *ah = sc->sc_ah;
7144         struct ifnet *ifp = sc->sc_ifp;
7145         struct ieee80211com *ic = ifp->if_l2com;
7146         const struct ieee80211_txparam *tp;
7147         const struct ieee80211_tdma_state *tdma = NULL;
7148         int rix;
7149
7150         if (vap == NULL) {
7151                 vap = TAILQ_FIRST(&ic->ic_vaps);   /* XXX */
7152                 if (vap == NULL) {
7153                         if_printf(ifp, "%s: no vaps?\n", __func__);
7154                         return;
7155                 }
7156         }
7157         tp = vap->iv_bss->ni_txparms;
7158         /*
7159          * Calculate the guard time for each slot.  This is the
7160          * time to send a maximal-size frame according to the
7161          * fixed/lowest transmit rate.  Note that the interface
7162          * mtu does not include the 802.11 overhead so we must
7163          * tack that on (ath_hal_computetxtime includes the
7164          * preamble and plcp in it's calculation).
7165          */
7166         tdma = vap->iv_tdma;
7167         if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE)
7168                 rix = ath_tx_findrix(sc, tp->ucastrate);
7169         else
7170                 rix = ath_tx_findrix(sc, tp->mcastrate);
7171         /* XXX short preamble assumed */
7172         sc->sc_tdmaguard = ath_hal_computetxtime(ah, sc->sc_currates,
7173                 ifp->if_mtu + IEEE80211_MAXOVERHEAD, rix, AH_TRUE);
7174
7175         ath_hal_intrset(ah, 0);
7176
7177         ath_beaconq_config(sc);                 /* setup h/w beacon q */
7178         if (sc->sc_setcca)
7179                 ath_hal_setcca(ah, AH_FALSE);   /* disable CCA */
7180         ath_tdma_bintvalsetup(sc, tdma);        /* calculate beacon interval */
7181         ath_tdma_settimers(sc, sc->sc_tdmabintval,
7182                 sc->sc_tdmabintval | HAL_BEACON_RESET_TSF);
7183         sc->sc_syncbeacon = 0;
7184
7185         sc->sc_avgtsfdeltap = TDMA_DUMMY_MARKER;
7186         sc->sc_avgtsfdeltam = TDMA_DUMMY_MARKER;
7187
7188         ath_hal_intrset(ah, sc->sc_imask);
7189
7190         DPRINTF(sc, ATH_DEBUG_TDMA, "%s: slot %u len %uus cnt %u "
7191             "bsched %u guard %uus bintval %u TU dba prep %u\n", __func__,
7192             tdma->tdma_slot, tdma->tdma_slotlen, tdma->tdma_slotcnt,
7193             tdma->tdma_bintval, sc->sc_tdmaguard, sc->sc_tdmabintval,
7194             sc->sc_tdmadbaprep);
7195 }
7196
7197 /*
7198  * Update tdma operation.  Called from the 802.11 layer
7199  * when a beacon is received from the TDMA station operating
7200  * in the slot immediately preceding us in the bss.  Use
7201  * the rx timestamp for the beacon frame to update our
7202  * beacon timers so we follow their schedule.  Note that
7203  * by using the rx timestamp we implicitly include the
7204  * propagation delay in our schedule.
7205  */
7206 static void
7207 ath_tdma_update(struct ieee80211_node *ni,
7208         const struct ieee80211_tdma_param *tdma, int changed)
7209 {
7210 #define TSF_TO_TU(_h,_l) \
7211         ((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
7212 #define TU_TO_TSF(_tu)  (((u_int64_t)(_tu)) << 10)
7213         struct ieee80211vap *vap = ni->ni_vap;
7214         struct ieee80211com *ic = ni->ni_ic;
7215         struct ath_softc *sc = ic->ic_ifp->if_softc;
7216         struct ath_hal *ah = sc->sc_ah;
7217         const HAL_RATE_TABLE *rt = sc->sc_currates;
7218         u_int64_t tsf, rstamp, nextslot;
7219         u_int32_t txtime, nextslottu, timer0;
7220         int32_t tudelta, tsfdelta;
7221         const struct ath_rx_status *rs;
7222         int rix;
7223
7224         sc->sc_stats.ast_tdma_update++;
7225
7226         /*
7227          * Check for and adopt configuration changes.
7228          */
7229         if (changed != 0) {
7230                 const struct ieee80211_tdma_state *ts = vap->iv_tdma;
7231
7232                 ath_tdma_bintvalsetup(sc, ts);
7233                 if (changed & TDMA_UPDATE_SLOTLEN)
7234                         ath_wme_update(ic);
7235
7236                 DPRINTF(sc, ATH_DEBUG_TDMA,
7237                     "%s: adopt slot %u slotcnt %u slotlen %u us "
7238                     "bintval %u TU\n", __func__,
7239                     ts->tdma_slot, ts->tdma_slotcnt, ts->tdma_slotlen,
7240                     sc->sc_tdmabintval);
7241
7242                 /* XXX right? */
7243                 ath_hal_intrset(ah, sc->sc_imask);
7244                 /* NB: beacon timers programmed below */
7245         }
7246
7247         /* extend rx timestamp to 64 bits */
7248         rs = sc->sc_lastrs;
7249         tsf = ath_hal_gettsf64(ah);
7250         rstamp = ath_extend_tsf(rs->rs_tstamp, tsf);
7251         /*
7252          * The rx timestamp is set by the hardware on completing
7253          * reception (at the point where the rx descriptor is DMA'd
7254          * to the host).  To find the start of our next slot we
7255          * must adjust this time by the time required to send
7256          * the packet just received.
7257          */
7258         rix = rt->rateCodeToIndex[rs->rs_rate];
7259         txtime = ath_hal_computetxtime(ah, rt, rs->rs_datalen, rix,
7260             rt->info[rix].shortPreamble);
7261         /* NB: << 9 is to cvt to TU and /2 */
7262         nextslot = (rstamp - txtime) + (sc->sc_tdmabintval << 9);
7263         nextslottu = TSF_TO_TU(nextslot>>32, nextslot) & HAL_BEACON_PERIOD;
7264
7265         /*
7266          * TIMER0 is the h/w's idea of NextTBTT (in TU's).  Convert
7267          * to usecs and calculate the difference between what the
7268          * other station thinks and what we have programmed.  This
7269          * lets us figure how to adjust our timers to match.  The
7270          * adjustments are done by pulling the TSF forward and possibly
7271          * rewriting the beacon timers.
7272          */
7273         timer0 = ath_hal_getnexttbtt(ah);
7274         tsfdelta = (int32_t)((nextslot % TU_TO_TSF(HAL_BEACON_PERIOD+1)) - TU_TO_TSF(timer0));
7275
7276         DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
7277             "tsfdelta %d avg +%d/-%d\n", tsfdelta,
7278             TDMA_AVG(sc->sc_avgtsfdeltap), TDMA_AVG(sc->sc_avgtsfdeltam));
7279
7280         if (tsfdelta < 0) {
7281                 TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
7282                 TDMA_SAMPLE(sc->sc_avgtsfdeltam, -tsfdelta);
7283                 tsfdelta = -tsfdelta % 1024;
7284                 nextslottu++;
7285         } else if (tsfdelta > 0) {
7286                 TDMA_SAMPLE(sc->sc_avgtsfdeltap, tsfdelta);
7287                 TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
7288                 tsfdelta = 1024 - (tsfdelta % 1024);
7289                 nextslottu++;
7290         } else {
7291                 TDMA_SAMPLE(sc->sc_avgtsfdeltap, 0);
7292                 TDMA_SAMPLE(sc->sc_avgtsfdeltam, 0);
7293         }
7294         tudelta = nextslottu - timer0;
7295
7296         /*
7297          * Copy sender's timetstamp into tdma ie so they can
7298          * calculate roundtrip time.  We submit a beacon frame
7299          * below after any timer adjustment.  The frame goes out
7300          * at the next TBTT so the sender can calculate the
7301          * roundtrip by inspecting the tdma ie in our beacon frame.
7302          *
7303          * NB: This tstamp is subtlely preserved when
7304          *     IEEE80211_BEACON_TDMA is marked (e.g. when the
7305          *     slot position changes) because ieee80211_add_tdma
7306          *     skips over the data.
7307          */
7308         memcpy(ATH_VAP(vap)->av_boff.bo_tdma +
7309                 __offsetof(struct ieee80211_tdma_param, tdma_tstamp),
7310                 &ni->ni_tstamp.data, 8);
7311 #if 0
7312         DPRINTF(sc, ATH_DEBUG_TDMA_TIMER,
7313             "tsf %llu nextslot %llu (%d, %d) nextslottu %u timer0 %u (%d)\n",
7314             (unsigned long long) tsf, (unsigned long long) nextslot,
7315             (int)(nextslot - tsf), tsfdelta,
7316             nextslottu, timer0, tudelta);
7317 #endif
7318         /*
7319          * Adjust the beacon timers only when pulling them forward
7320          * or when going back by less than the beacon interval.
7321          * Negative jumps larger than the beacon interval seem to
7322          * cause the timers to stop and generally cause instability.
7323          * This basically filters out jumps due to missed beacons.
7324          */
7325         if (tudelta != 0 && (tudelta > 0 || -tudelta < sc->sc_tdmabintval)) {
7326                 ath_tdma_settimers(sc, nextslottu, sc->sc_tdmabintval);
7327                 sc->sc_stats.ast_tdma_timers++;
7328         }
7329         if (tsfdelta > 0) {
7330                 ath_hal_adjusttsf(ah, tsfdelta);
7331                 sc->sc_stats.ast_tdma_tsf++;
7332         }
7333         ath_tdma_beacon_send(sc, vap);          /* prepare response */
7334 #undef TU_TO_TSF
7335 #undef TSF_TO_TU
7336 }
7337
7338 /*
7339  * Transmit a beacon frame at SWBA.  Dynamic updates
7340  * to the frame contents are done as needed.
7341  */
7342 static void
7343 ath_tdma_beacon_send(struct ath_softc *sc, struct ieee80211vap *vap)
7344 {
7345         struct ath_hal *ah = sc->sc_ah;
7346         struct ath_buf *bf;
7347         int otherant;
7348
7349         /*
7350          * Check if the previous beacon has gone out.  If
7351          * not don't try to post another, skip this period
7352          * and wait for the next.  Missed beacons indicate
7353          * a problem and should not occur.  If we miss too
7354          * many consecutive beacons reset the device.
7355          */
7356         if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
7357                 sc->sc_bmisscount++;
7358                 DPRINTF(sc, ATH_DEBUG_BEACON,
7359                         "%s: missed %u consecutive beacons\n",
7360                         __func__, sc->sc_bmisscount);
7361                 if (sc->sc_bmisscount >= ath_bstuck_threshold)
7362                         taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
7363                 return;
7364         }
7365         if (sc->sc_bmisscount != 0) {
7366                 DPRINTF(sc, ATH_DEBUG_BEACON,
7367                         "%s: resume beacon xmit after %u misses\n",
7368                         __func__, sc->sc_bmisscount);
7369                 sc->sc_bmisscount = 0;
7370         }
7371
7372         /*
7373          * Check recent per-antenna transmit statistics and flip
7374          * the default antenna if noticeably more frames went out
7375          * on the non-default antenna.
7376          * XXX assumes 2 anntenae
7377          */
7378         if (!sc->sc_diversity) {
7379                 otherant = sc->sc_defant & 1 ? 2 : 1;
7380                 if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
7381                         ath_setdefantenna(sc, otherant);
7382                 sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
7383         }
7384
7385         /*
7386          * Stop any current dma before messing with the beacon linkages.
7387          *
7388          * This should never fail since we check above that no frames
7389          * are still pending on the queue.
7390          */
7391         if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
7392                 DPRINTF(sc, ATH_DEBUG_ANY,
7393                         "%s: beacon queue %u did not stop?\n",
7394                         __func__, sc->sc_bhalq);
7395                 /* NB: the HAL still stops DMA, so proceed */
7396         }
7397         bf = ath_beacon_generate(sc, vap);
7398         if (bf != NULL) {
7399                 ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
7400                 ath_hal_txstart(ah, sc->sc_bhalq);
7401
7402                 sc->sc_stats.ast_be_xmit++;             /* XXX per-vap? */
7403
7404                 /*
7405                  * Record local TSF for our last send for use
7406                  * in arbitrating slot collisions.
7407                  */
7408                 vap->iv_bss->ni_tstamp.tsf = ath_hal_gettsf64(ah);
7409         } else {
7410                 device_printf(sc->sc_dev, "tdma beacon gen failed!\n");
7411         }
7412 }
7413 #endif /* IEEE80211_SUPPORT_TDMA */
7414
7415 static int
7416 ath_sysctl_clearstats(SYSCTL_HANDLER_ARGS)
7417 {
7418         struct ath_softc *sc = arg1;
7419         int val = 0;
7420         int error;
7421
7422         error = sysctl_handle_int(oidp, &val, 0, req);
7423         if (error || !req->newptr)
7424                 return error;
7425         if (val == 0)
7426                 return 0;       /* Not clearing the stats is still valid */
7427         memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
7428         val = 0;
7429         return 0;
7430 }
7431
7432 static void
7433 ath_sysctl_stats_attach(struct ath_softc *sc)
7434 {
7435         struct sysctl_oid *tree;
7436         struct sysctl_ctx_list *ctx;
7437         struct sysctl_oid_list *child;
7438
7439         ctx = &sc->sc_sysctl_ctx;
7440         tree = sc->sc_sysctl_tree;
7441         child = SYSCTL_CHILDREN(tree);
7442
7443         /* Create "clear" node */
7444         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
7445             "clear_stats", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
7446             ath_sysctl_clearstats, "I", "clear stats");
7447
7448         /* Create stats node */
7449         tree = SYSCTL_ADD_NODE(ctx, child, OID_AUTO, "stats", CTLFLAG_RD,
7450             NULL, "Statistics");
7451         child = SYSCTL_CHILDREN(tree);
7452
7453         /* This was generated from if_athioctl.h */
7454
7455         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_watchdog", CTLFLAG_RD,
7456             &sc->sc_stats.ast_watchdog, 0, "device reset by watchdog");
7457         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_hardware", CTLFLAG_RD,
7458             &sc->sc_stats.ast_hardware, 0, "fatal hardware error interrupts");
7459         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_bmiss", CTLFLAG_RD,
7460             &sc->sc_stats.ast_bmiss, 0, "beacon miss interrupts");
7461         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_bmiss_phantom", CTLFLAG_RD,
7462             &sc->sc_stats.ast_bmiss_phantom, 0, "beacon miss interrupts");
7463         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_bstuck", CTLFLAG_RD,
7464             &sc->sc_stats.ast_bstuck, 0, "beacon stuck interrupts");
7465         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rxorn", CTLFLAG_RD,
7466             &sc->sc_stats.ast_rxorn, 0, "rx overrun interrupts");
7467         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rxeol", CTLFLAG_RD,
7468             &sc->sc_stats.ast_rxeol, 0, "rx eol interrupts");
7469         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_txurn", CTLFLAG_RD,
7470             &sc->sc_stats.ast_txurn, 0, "tx underrun interrupts");
7471         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_mib", CTLFLAG_RD,
7472             &sc->sc_stats.ast_mib, 0, "mib interrupts");
7473         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_intrcoal", CTLFLAG_RD,
7474             &sc->sc_stats.ast_intrcoal, 0, "interrupts coalesced");
7475         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_packets", CTLFLAG_RD,
7476             &sc->sc_stats.ast_tx_packets, 0, "packet sent on the interface");
7477         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_mgmt", CTLFLAG_RD,
7478             &sc->sc_stats.ast_tx_mgmt, 0, "management frames transmitted");
7479         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_discard", CTLFLAG_RD,
7480             &sc->sc_stats.ast_tx_discard, 0, "frames discarded prior to assoc");
7481         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_qstop", CTLFLAG_RD,
7482             &sc->sc_stats.ast_tx_qstop, 0, "output stopped 'cuz no buffer");
7483         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_encap", CTLFLAG_RD,
7484             &sc->sc_stats.ast_tx_encap, 0, "tx encapsulation failed");
7485         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nonode", CTLFLAG_RD,
7486             &sc->sc_stats.ast_tx_nonode, 0, "tx failed 'cuz no node");
7487         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nombuf", CTLFLAG_RD,
7488             &sc->sc_stats.ast_tx_nombuf, 0, "tx failed 'cuz no mbuf");
7489         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nomcl", CTLFLAG_RD,
7490             &sc->sc_stats.ast_tx_nomcl, 0, "tx failed 'cuz no cluster");
7491         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_linear", CTLFLAG_RD,
7492             &sc->sc_stats.ast_tx_linear, 0, "tx linearized to cluster");
7493         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nodata", CTLFLAG_RD,
7494             &sc->sc_stats.ast_tx_nodata, 0, "tx discarded empty frame");
7495         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_busdma", CTLFLAG_RD,
7496             &sc->sc_stats.ast_tx_busdma, 0, "tx failed for dma resrcs");
7497         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_xretries", CTLFLAG_RD,
7498             &sc->sc_stats.ast_tx_xretries, 0, "tx failed 'cuz too many retries");
7499         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_fifoerr", CTLFLAG_RD,
7500             &sc->sc_stats.ast_tx_fifoerr, 0, "tx failed 'cuz FIFO underrun");
7501         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_filtered", CTLFLAG_RD,
7502             &sc->sc_stats.ast_tx_filtered, 0, "tx failed 'cuz xmit filtered");
7503         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_shortretry", CTLFLAG_RD,
7504             &sc->sc_stats.ast_tx_shortretry, 0, "tx on-chip retries (short)");
7505         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_longretry", CTLFLAG_RD,
7506             &sc->sc_stats.ast_tx_longretry, 0, "tx on-chip retries (long)");
7507         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_badrate", CTLFLAG_RD,
7508             &sc->sc_stats.ast_tx_badrate, 0, "tx failed 'cuz bogus xmit rate");
7509         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_noack", CTLFLAG_RD,
7510             &sc->sc_stats.ast_tx_noack, 0, "tx frames with no ack marked");
7511         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_rts", CTLFLAG_RD,
7512             &sc->sc_stats.ast_tx_rts, 0, "tx frames with rts enabled");
7513         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_cts", CTLFLAG_RD,
7514             &sc->sc_stats.ast_tx_cts, 0, "tx frames with cts enabled");
7515         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_shortpre", CTLFLAG_RD,
7516             &sc->sc_stats.ast_tx_shortpre, 0, "tx frames with short preamble");
7517         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_altrate", CTLFLAG_RD,
7518             &sc->sc_stats.ast_tx_altrate, 0, "tx frames with alternate rate");
7519         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_protect", CTLFLAG_RD,
7520             &sc->sc_stats.ast_tx_protect, 0, "tx frames with protection");
7521         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_ctsburst", CTLFLAG_RD,
7522             &sc->sc_stats.ast_tx_ctsburst, 0, "tx frames with cts and bursting");
7523         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_ctsext", CTLFLAG_RD,
7524             &sc->sc_stats.ast_tx_ctsext, 0, "tx frames with cts extension");
7525         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_nombuf", CTLFLAG_RD,
7526             &sc->sc_stats.ast_rx_nombuf, 0, "rx setup failed 'cuz no mbuf");
7527         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_busdma", CTLFLAG_RD,
7528             &sc->sc_stats.ast_rx_busdma, 0, "rx setup failed for dma resrcs");
7529         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_orn", CTLFLAG_RD,
7530             &sc->sc_stats.ast_rx_orn, 0, "rx failed 'cuz of desc overrun");
7531         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_crcerr", CTLFLAG_RD,
7532             &sc->sc_stats.ast_rx_crcerr, 0, "rx failed 'cuz of bad CRC");
7533         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_fifoerr", CTLFLAG_RD,
7534             &sc->sc_stats.ast_rx_fifoerr, 0, "rx failed 'cuz of FIFO overrun");
7535         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_badcrypt", CTLFLAG_RD,
7536             &sc->sc_stats.ast_rx_badcrypt, 0, "rx failed 'cuz decryption");
7537         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_badmic", CTLFLAG_RD,
7538             &sc->sc_stats.ast_rx_badmic, 0, "rx failed 'cuz MIC failure");
7539         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_phyerr", CTLFLAG_RD,
7540             &sc->sc_stats.ast_rx_phyerr, 0, "rx failed 'cuz of PHY err");
7541         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_tooshort", CTLFLAG_RD,
7542             &sc->sc_stats.ast_rx_tooshort, 0, "rx discarded 'cuz frame too short");
7543         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_toobig", CTLFLAG_RD,
7544             &sc->sc_stats.ast_rx_toobig, 0, "rx discarded 'cuz frame too large");
7545         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_packets", CTLFLAG_RD,
7546             &sc->sc_stats.ast_rx_packets, 0, "packet recv on the interface");
7547         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_mgt", CTLFLAG_RD,
7548             &sc->sc_stats.ast_rx_mgt, 0, "management frames received");
7549         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rx_ctl", CTLFLAG_RD,
7550             &sc->sc_stats.ast_rx_ctl, 0, "rx discarded 'cuz ctl frame");
7551         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_be_xmit", CTLFLAG_RD,
7552             &sc->sc_stats.ast_be_xmit, 0, "beacons transmitted");
7553         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_be_nombuf", CTLFLAG_RD,
7554             &sc->sc_stats.ast_be_nombuf, 0, "beacon setup failed 'cuz no mbuf");
7555         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_per_cal", CTLFLAG_RD,
7556             &sc->sc_stats.ast_per_cal, 0, "periodic calibration calls");
7557         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_per_calfail", CTLFLAG_RD,
7558             &sc->sc_stats.ast_per_calfail, 0, "periodic calibration failed");
7559         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_per_rfgain", CTLFLAG_RD,
7560             &sc->sc_stats.ast_per_rfgain, 0, "periodic calibration rfgain reset");
7561         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rate_calls", CTLFLAG_RD,
7562             &sc->sc_stats.ast_rate_calls, 0, "rate control checks");
7563         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rate_raise", CTLFLAG_RD,
7564             &sc->sc_stats.ast_rate_raise, 0, "rate control raised xmit rate");
7565         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_rate_drop", CTLFLAG_RD,
7566             &sc->sc_stats.ast_rate_drop, 0, "rate control dropped xmit rate");
7567         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ant_defswitch", CTLFLAG_RD,
7568             &sc->sc_stats.ast_ant_defswitch, 0, "rx/default antenna switches");
7569         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ant_txswitch", CTLFLAG_RD,
7570             &sc->sc_stats.ast_ant_txswitch, 0, "tx antenna switches");
7571         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_cabq_xmit", CTLFLAG_RD,
7572             &sc->sc_stats.ast_cabq_xmit, 0, "cabq frames transmitted");
7573         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_cabq_busy", CTLFLAG_RD,
7574             &sc->sc_stats.ast_cabq_busy, 0, "cabq found busy");
7575         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_raw", CTLFLAG_RD,
7576             &sc->sc_stats.ast_tx_raw, 0, "tx frames through raw api");
7577         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ff_txok", CTLFLAG_RD,
7578             &sc->sc_stats.ast_ff_txok, 0, "fast frames tx'd successfully");
7579         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ff_txerr", CTLFLAG_RD,
7580             &sc->sc_stats.ast_ff_txerr, 0, "fast frames tx'd w/ error");
7581         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ff_rx", CTLFLAG_RD,
7582             &sc->sc_stats.ast_ff_rx, 0, "fast frames rx'd");
7583         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_ff_flush", CTLFLAG_RD,
7584             &sc->sc_stats.ast_ff_flush, 0, "fast frames flushed from staging q");
7585         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_qfull", CTLFLAG_RD,
7586             &sc->sc_stats.ast_tx_qfull, 0, "tx dropped 'cuz of queue limit");
7587         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nobuf", CTLFLAG_RD,
7588             &sc->sc_stats.ast_tx_nobuf, 0, "tx dropped 'cuz no ath buffer");
7589         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tdma_update", CTLFLAG_RD,
7590             &sc->sc_stats.ast_tdma_update, 0, "TDMA slot timing updates");
7591         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tdma_timers", CTLFLAG_RD,
7592             &sc->sc_stats.ast_tdma_timers, 0, "TDMA slot update set beacon timers");
7593         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tdma_tsf", CTLFLAG_RD,
7594             &sc->sc_stats.ast_tdma_tsf, 0, "TDMA slot update set TSF");
7595         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tdma_ack", CTLFLAG_RD,
7596             &sc->sc_stats.ast_tdma_ack, 0, "TDMA tx failed 'cuz ACK required");
7597         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_raw_fail", CTLFLAG_RD,
7598             &sc->sc_stats.ast_tx_raw_fail, 0, "raw tx failed 'cuz h/w down");
7599         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_tx_nofrag", CTLFLAG_RD,
7600             &sc->sc_stats.ast_tx_nofrag, 0, "tx dropped 'cuz no ath frag buffer");
7601 #if 0
7602         SYSCTL_ADD_UINT(ctx, child, OID_AUTO, "ast_be_missed", CTLFLAG_RD,
7603             &sc->sc_stats.ast_be_missed, 0, "number of -missed- beacons");
7604 #endif
7605 }