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