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