wlan - Update ath, sync rev 1.276@FreeBSD
[dragonfly.git] / sys / dev / netif / ath / ath / if_ath.c
1 /*-
2  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification.
11  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13  *    redistribution must be conditioned upon including a substantially
14  *    similar Disclaimer requirement for further binary redistribution.
15  *
16  * NO WARRANTY
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
22  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27  * THE POSSIBILITY OF SUCH DAMAGES.
28  *
29  * $FreeBSD: head/sys/dev/ath/if_ath.c 203751 2010-02-10 11:12:39Z rpaulo $");
30  */
31
32 /*
33  * Driver for the Atheros Wireless LAN controller.
34  *
35  * This software is derived from work of Atsushi Onoe; his contribution
36  * is greatly appreciated.
37  */
38
39 #include "opt_inet.h"
40 #include "opt_ath.h"
41 #include "opt_wlan.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h> 
45 #include <sys/sysctl.h>
46 #include <sys/mbuf.h>   
47 #include <sys/malloc.h>
48 #include <sys/lock.h>
49 #include <sys/mutex.h>
50 #include <sys/kernel.h>
51 #include <sys/socket.h>
52 #include <sys/sockio.h>
53 #include <sys/errno.h>
54 #include <sys/callout.h>
55 #include <sys/bus.h>
56 #include <sys/endian.h>
57 #include <sys/kthread.h>
58 #include <sys/taskqueue.h>
59 #include <sys/priv.h>
60
61 #include <net/if.h>
62 #include <net/if_dl.h>
63 #include <net/if_media.h>
64 #include <net/if_types.h>
65 #include <net/if_arp.h>
66 #include <net/if_llc.h>
67 #include <net/ifq_var.h>
68
69 #include <netproto/802_11/ieee80211_var.h>
70 #include <netproto/802_11/ieee80211_regdomain.h>
71 #ifdef IEEE80211_SUPPORT_SUPERG
72 #include <netproto/802_11/ieee80211_superg.h>
73 #endif
74 #ifdef IEEE80211_SUPPORT_TDMA
75 #include <netproto/802_11/ieee80211_tdma.h>
76 #endif
77
78 #include <net/bpf.h>
79
80 #ifdef INET
81 #include <netinet/in.h> 
82 #include <netinet/if_ether.h>
83 #endif
84
85 #include <dev/netif/ath/ath/if_athvar.h>
86 #include <dev/netif/ath/hal/ath_hal/ah_devid.h>         /* XXX for softled */
87
88 #ifdef ATH_TX99_DIAG
89 #include <dev/netif/ath_tx99/ath_tx99.h>
90 #endif
91
92 /*
93  * ATH_BCBUF determines the number of vap's that can transmit
94  * beacons and also (currently) the number of vap's that can
95  * have unique mac addresses/bssid.  When staggering beacons
96  * 4 is probably a good max as otherwise the beacons become
97  * very closely spaced and there is limited time for cab q traffic
98  * to go out.  You can burst beacons instead but that is not good
99  * for stations in power save and at some point you really want
100  * another radio (and channel).
101  *
102  * The limit on the number of mac addresses is tied to our use of
103  * the U/L bit and tracking addresses in a byte; it would be
104  * worthwhile to allow more for applications like proxy sta.
105  */
106 CTASSERT(ATH_BCBUF <= 8);
107
108 /* unaligned little endian access */
109 #define LE_READ_2(p)                                                    \
110         ((u_int16_t)                                                    \
111          ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
112 #define LE_READ_4(p)                                                    \
113         ((u_int32_t)                                                    \
114          ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) | \
115           (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
116
117 static struct ieee80211vap *ath_vap_create(struct ieee80211com *,
118                     const char name[IFNAMSIZ], int unit, int opmode,
119                     int flags, const uint8_t bssid[IEEE80211_ADDR_LEN],
120                     const uint8_t mac[IEEE80211_ADDR_LEN]);
121 static void     ath_vap_delete(struct ieee80211vap *);
122 static void     ath_init(void *);
123 static void     ath_stop_locked(struct ifnet *);
124 static void     ath_stop(struct ifnet *);
125 static void     ath_start(struct ifnet *);
126 static int      ath_reset(struct ifnet *);
127 static int      ath_reset_vap(struct ieee80211vap *, u_long);
128 static int      ath_media_change(struct ifnet *);
129 static void     ath_watchdog_callout(void *);
130 static int      ath_ioctl(struct ifnet *, u_long, caddr_t, struct ucred *);
131 static void     ath_fatal_proc(void *, int);
132 static void     ath_bmiss_vap(struct ieee80211vap *);
133 static void     ath_bmiss_task(void *, int);
134 static int      ath_keyset(struct ath_softc *, const struct ieee80211_key *,
135                         struct ieee80211_node *);
136 static int      ath_key_alloc(struct ieee80211vap *,
137                         struct ieee80211_key *,
138                         ieee80211_keyix *, ieee80211_keyix *);
139 static int      ath_key_delete(struct ieee80211vap *,
140                         const struct ieee80211_key *);
141 static int      ath_key_set(struct ieee80211vap *, const struct ieee80211_key *,
142                         const u_int8_t mac[IEEE80211_ADDR_LEN]);
143 static void     ath_key_update_begin(struct ieee80211vap *);
144 static void     ath_key_update_end(struct ieee80211vap *);
145 static void     ath_update_mcast(struct ifnet *);
146 static void     ath_update_promisc(struct ifnet *);
147 static void     ath_mode_init(struct ath_softc *);
148 static void     ath_setslottime(struct ath_softc *);
149 static void     ath_updateslot(struct ifnet *);
150 static int      ath_beaconq_setup(struct ath_hal *);
151 static int      ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
152 static void     ath_beacon_update(struct ieee80211vap *, int item);
153 static void     ath_beacon_setup(struct ath_softc *, struct ath_buf *);
154 static void     ath_beacon_proc(void *, int);
155 static struct ath_buf *ath_beacon_generate(struct ath_softc *,
156                         struct ieee80211vap *);
157 static void     ath_bstuck_task(void *, int);
158 static void     ath_beacon_return(struct ath_softc *, struct ath_buf *);
159 static void     ath_beacon_free(struct ath_softc *);
160 static void     ath_beacon_config(struct ath_softc *, struct ieee80211vap *);
161 static void     ath_descdma_cleanup(struct ath_softc *sc,
162                         struct ath_descdma *, ath_bufhead *);
163 static int      ath_desc_alloc(struct ath_softc *);
164 static void     ath_desc_free(struct ath_softc *);
165 static struct ieee80211_node *ath_node_alloc(struct ieee80211vap *,
166                         const uint8_t [IEEE80211_ADDR_LEN]);
167 static void     ath_node_free(struct ieee80211_node *);
168 static void     ath_node_getsignal(const struct ieee80211_node *,
169                         int8_t *, int8_t *);
170 static int      ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
171 static void     ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
172                         int subtype, int rssi, int nf);
173 static void     ath_setdefantenna(struct ath_softc *, u_int);
174 static void     ath_rx_task(void *, int);
175 static void     ath_txq_init(struct ath_softc *sc, struct ath_txq *, int);
176 static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
177 static int      ath_tx_setup(struct ath_softc *, int, int);
178 static int      ath_wme_update(struct ieee80211com *);
179 static void     ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
180 static void     ath_tx_cleanup(struct ath_softc *);
181 static void     ath_freetx(struct mbuf *);
182 static int      ath_tx_start(struct ath_softc *, struct ieee80211_node *,
183                              struct ath_buf *, struct mbuf *);
184 static void     ath_tx_task_q0(void *, int);
185 static void     ath_tx_task_q0123(void *, int);
186 static void     ath_tx_task(void *, int);
187 static void     ath_tx_draintxq(struct ath_softc *, struct ath_txq *);
188 static int      ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
189 static void     ath_draintxq(struct ath_softc *);
190 static void     ath_stoprecv(struct ath_softc *);
191 static int      ath_startrecv(struct ath_softc *);
192 static void     ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
193 static void     ath_scan_start(struct ieee80211com *);
194 static void     ath_scan_end(struct ieee80211com *);
195 static void     ath_set_channel(struct ieee80211com *);
196 static void     ath_calibrate_callout(void *);
197 static int      ath_newstate(struct ieee80211vap *, enum ieee80211_state, int);
198 static void     ath_setup_stationkey(struct ieee80211_node *);
199 static void     ath_newassoc(struct ieee80211_node *, int);
200 static int      ath_setregdomain(struct ieee80211com *,
201                     struct ieee80211_regdomain *, int,
202                     struct ieee80211_channel []);
203 static void     ath_getradiocaps(struct ieee80211com *, int, int *,
204                     struct ieee80211_channel []);
205 static int      ath_getchannels(struct ath_softc *);
206 static void     ath_led_event(struct ath_softc *, int);
207
208 static int      ath_rate_setup(struct ath_softc *, u_int mode);
209 static void     ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
210
211 static void     ath_sysctlattach(struct ath_softc *);
212 static int      ath_raw_xmit(struct ieee80211_node *,
213                         struct mbuf *, const struct ieee80211_bpf_params *);
214 static void     ath_announce(struct ath_softc *);
215
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         wlan_assert_serialized();
454         wlan_serialize_exit();
455         error = ath_desc_alloc(sc);
456         wlan_serialize_enter();
457         if (error != 0) {
458                 if_printf(ifp, "failed to allocate descriptors: %d\n", error);
459                 goto bad;
460         }
461         callout_init(&sc->sc_cal_ch);
462         callout_init(&sc->sc_wd_ch);
463
464         sc->sc_tq = taskqueue_create("ath_taskq", M_INTWAIT,
465                 taskqueue_thread_enqueue, &sc->sc_tq);
466         taskqueue_start_threads(&sc->sc_tq, 1, TDPRI_KERN_DAEMON, -1,
467                 "%s taskq", ifp->if_xname);
468
469         TASK_INIT(&sc->sc_rxtask, 0, ath_rx_task, sc);
470         TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_task, sc);
471         TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_task, sc);
472
473         /*
474          * Allocate hardware transmit queues: one queue for
475          * beacon frames and one data queue for each QoS
476          * priority.  Note that the hal handles reseting
477          * these queues at the needed time.
478          *
479          * XXX PS-Poll
480          */
481         sc->sc_bhalq = ath_beaconq_setup(ah);
482         if (sc->sc_bhalq == (u_int) -1) {
483                 if_printf(ifp, "unable to setup a beacon xmit queue!\n");
484                 error = EIO;
485                 goto bad2;
486         }
487         sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
488         if (sc->sc_cabq == NULL) {
489                 if_printf(ifp, "unable to setup CAB xmit queue!\n");
490                 error = EIO;
491                 goto bad2;
492         }
493         /* NB: insure BK queue is the lowest priority h/w queue */
494         if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
495                 if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
496                         ieee80211_wme_acnames[WME_AC_BK]);
497                 error = EIO;
498                 goto bad2;
499         }
500         if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
501             !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
502             !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
503                 /*
504                  * Not enough hardware tx queues to properly do WME;
505                  * just punt and assign them all to the same h/w queue.
506                  * We could do a better job of this if, for example,
507                  * we allocate queues when we switch from station to
508                  * AP mode.
509                  */
510                 if (sc->sc_ac2q[WME_AC_VI] != NULL)
511                         ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
512                 if (sc->sc_ac2q[WME_AC_BE] != NULL)
513                         ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
514                 sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
515                 sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
516                 sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
517         }
518
519         /*
520          * Special case certain configurations.  Note the
521          * CAB queue is handled by these specially so don't
522          * include them when checking the txq setup mask.
523          */
524         switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
525         case 0x01:
526                 TASK_INIT(&sc->sc_txtask, 0, ath_tx_task_q0, sc);
527                 break;
528         case 0x0f:
529                 TASK_INIT(&sc->sc_txtask, 0, ath_tx_task_q0123, sc);
530                 break;
531         default:
532                 TASK_INIT(&sc->sc_txtask, 0, ath_tx_task, sc);
533                 break;
534         }
535
536         /*
537          * Setup rate control.  Some rate control modules
538          * call back to change the anntena state so expose
539          * the necessary entry points.
540          * XXX maybe belongs in struct ath_ratectrl?
541          */
542         sc->sc_setdefantenna = ath_setdefantenna;
543         sc->sc_rc = ath_rate_attach(sc);
544         if (sc->sc_rc == NULL) {
545                 error = EIO;
546                 goto bad2;
547         }
548
549         sc->sc_blinking = 0;
550         sc->sc_ledstate = 1;
551         sc->sc_ledon = 0;                       /* low true */
552         sc->sc_ledidle = (2700*hz)/1000;        /* 2.7sec */
553         callout_init_mp(&sc->sc_ledtimer);
554         /*
555          * Auto-enable soft led processing for IBM cards and for
556          * 5211 minipci cards.  Users can also manually enable/disable
557          * support with a sysctl.
558          */
559         sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
560         if (sc->sc_softled) {
561                 ath_hal_gpioCfgOutput(ah, sc->sc_ledpin,
562                     HAL_GPIO_MUX_MAC_NETWORK_LED);
563                 ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
564         }
565
566         ifp->if_softc = sc;
567         ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
568         ifp->if_start = ath_start;
569         ifp->if_ioctl = ath_ioctl;
570         ifp->if_init = ath_init;
571         ifq_set_maxlen(&ifp->if_snd, IFQ_MAXLEN);
572         ifq_set_ready(&ifp->if_snd);
573
574         ic->ic_ifp = ifp;
575         /* XXX not right but it's not used anywhere important */
576         ic->ic_phytype = IEEE80211_T_OFDM;
577         ic->ic_opmode = IEEE80211_M_STA;
578         ic->ic_caps =
579                   IEEE80211_C_STA               /* station mode */
580                 | IEEE80211_C_IBSS              /* ibss, nee adhoc, mode */
581                 | IEEE80211_C_HOSTAP            /* hostap mode */
582                 | IEEE80211_C_MONITOR           /* monitor mode */
583                 | IEEE80211_C_AHDEMO            /* adhoc demo mode */
584                 | IEEE80211_C_WDS               /* 4-address traffic works */
585                 | IEEE80211_C_MBSS              /* mesh point link mode */
586                 | IEEE80211_C_SHPREAMBLE        /* short preamble supported */
587                 | IEEE80211_C_SHSLOT            /* short slot time supported */
588                 | IEEE80211_C_WPA               /* capable of WPA1+WPA2 */
589                 | IEEE80211_C_BGSCAN            /* capable of bg scanning */
590                 | IEEE80211_C_TXFRAG            /* handle tx frags */
591                 ;
592         /*
593          * Query the hal to figure out h/w crypto support.
594          */
595         if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
596                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP;
597         if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
598                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_OCB;
599         if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
600                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_CCM;
601         if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
602                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_CKIP;
603         if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
604                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIP;
605                 /*
606                  * Check if h/w does the MIC and/or whether the
607                  * separate key cache entries are required to
608                  * handle both tx+rx MIC keys.
609                  */
610                 if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
611                         ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
612                 /*
613                  * If the h/w supports storing tx+rx MIC keys
614                  * in one cache slot automatically enable use.
615                  */
616                 if (ath_hal_hastkipsplit(ah) ||
617                     !ath_hal_settkipsplit(ah, AH_FALSE))
618                         sc->sc_splitmic = 1;
619                 /*
620                  * If the h/w can do TKIP MIC together with WME then
621                  * we use it; otherwise we force the MIC to be done
622                  * in software by the net80211 layer.
623                  */
624                 if (ath_hal_haswmetkipmic(ah))
625                         sc->sc_wmetkipmic = 1;
626         }
627         sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
628         /*
629          * Check for multicast key search support.
630          */
631         if (ath_hal_hasmcastkeysearch(sc->sc_ah) &&
632             !ath_hal_getmcastkeysearch(sc->sc_ah)) {
633                 ath_hal_setmcastkeysearch(sc->sc_ah, 1);
634         }
635         sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
636         /*
637          * Mark key cache slots associated with global keys
638          * as in use.  If we knew TKIP was not to be used we
639          * could leave the +32, +64, and +32+64 slots free.
640          */
641         for (i = 0; i < IEEE80211_WEP_NKID; i++) {
642                 setbit(sc->sc_keymap, i);
643                 setbit(sc->sc_keymap, i+64);
644                 if (sc->sc_splitmic) {
645                         setbit(sc->sc_keymap, i+32);
646                         setbit(sc->sc_keymap, i+32+64);
647                 }
648         }
649         /*
650          * TPC support can be done either with a global cap or
651          * per-packet support.  The latter is not available on
652          * all parts.  We're a bit pedantic here as all parts
653          * support a global cap.
654          */
655         if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
656                 ic->ic_caps |= IEEE80211_C_TXPMGT;
657
658         /*
659          * Mark WME capability only if we have sufficient
660          * hardware queues to do proper priority scheduling.
661          */
662         if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
663                 ic->ic_caps |= IEEE80211_C_WME;
664         /*
665          * Check for misc other capabilities.
666          */
667         if (ath_hal_hasbursting(ah))
668                 ic->ic_caps |= IEEE80211_C_BURST;
669         sc->sc_hasbmask = ath_hal_hasbssidmask(ah);
670         sc->sc_hasbmatch = ath_hal_hasbssidmatch(ah);
671         sc->sc_hastsfadd = ath_hal_hastsfadjust(ah);
672         if (ath_hal_hasfastframes(ah))
673                 ic->ic_caps |= IEEE80211_C_FF;
674         wmodes = ath_hal_getwirelessmodes(ah);
675         if (wmodes & (HAL_MODE_108G|HAL_MODE_TURBO))
676                 ic->ic_caps |= IEEE80211_C_TURBOP;
677 #ifdef IEEE80211_SUPPORT_TDMA
678         if (ath_hal_macversion(ah) > 0x78) {
679                 ic->ic_caps |= IEEE80211_C_TDMA; /* capable of TDMA */
680                 ic->ic_tdma_update = ath_tdma_update;
681         }
682 #endif
683         /*
684          * Indicate we need the 802.11 header padded to a
685          * 32-bit boundary for 4-address and QoS frames.
686          */
687         ic->ic_flags |= IEEE80211_F_DATAPAD;
688
689         /*
690          * Query the hal about antenna support.
691          */
692         sc->sc_defant = ath_hal_getdefantenna(ah);
693
694         /*
695          * Not all chips have the VEOL support we want to
696          * use with IBSS beacons; check here for it.
697          */
698         sc->sc_hasveol = ath_hal_hasveol(ah);
699
700         /* get mac address from hardware */
701         ath_hal_getmac(ah, macaddr);
702         if (sc->sc_hasbmask)
703                 ath_hal_getbssidmask(ah, sc->sc_hwbssidmask);
704
705         /* NB: used to size node table key mapping array */
706         ic->ic_max_keyix = sc->sc_keymax;
707         /* call MI attach routine. */
708         ieee80211_ifattach(ic, macaddr);
709         ic->ic_setregdomain = ath_setregdomain;
710         ic->ic_getradiocaps = ath_getradiocaps;
711         sc->sc_opmode = HAL_M_STA;
712
713         /* override default methods */
714         ic->ic_newassoc = ath_newassoc;
715         ic->ic_updateslot = ath_updateslot;
716         ic->ic_wme.wme_update = ath_wme_update;
717         ic->ic_vap_create = ath_vap_create;
718         ic->ic_vap_delete = ath_vap_delete;
719         ic->ic_raw_xmit = ath_raw_xmit;
720         ic->ic_update_mcast = ath_update_mcast;
721         ic->ic_update_promisc = ath_update_promisc;
722         ic->ic_node_alloc = ath_node_alloc;
723         sc->sc_node_free = ic->ic_node_free;
724         ic->ic_node_free = ath_node_free;
725         ic->ic_node_getsignal = ath_node_getsignal;
726         ic->ic_scan_start = ath_scan_start;
727         ic->ic_scan_end = ath_scan_end;
728         ic->ic_set_channel = ath_set_channel;
729
730         ieee80211_radiotap_attach(ic,
731             &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
732                 ATH_TX_RADIOTAP_PRESENT,
733             &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th),
734                 ATH_RX_RADIOTAP_PRESENT);
735
736         /*
737          * Setup dynamic sysctl's now that country code and
738          * regdomain are available from the hal.
739          */
740         ath_sysctlattach(sc);
741
742         if (bootverbose)
743                 ieee80211_announce(ic);
744         ath_announce(sc);
745         return 0;
746 bad2:
747         ath_tx_cleanup(sc);
748         ath_desc_free(sc);
749 bad:
750         if (ah)
751                 ath_hal_detach(ah);
752         if (ifp != NULL)
753                 if_free(ifp);
754         sc->sc_invalid = 1;
755         return error;
756 }
757
758 int
759 ath_detach(struct ath_softc *sc)
760 {
761         struct ifnet *ifp = sc->sc_ifp;
762
763         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
764                 __func__, ifp->if_flags);
765
766         /* 
767          * NB: the order of these is important:
768          * o stop the chip so no more interrupts will fire
769          * o call the 802.11 layer before detaching the hal to
770          *   insure callbacks into the driver to delete global
771          *   key cache entries can be handled
772          * o free the taskqueue which drains any pending tasks
773          * o reclaim the tx queue data structures after calling
774          *   the 802.11 layer as we'll get called back to reclaim
775          *   node state and potentially want to use them
776          * o to cleanup the tx queues the hal is called, so detach
777          *   it last
778          * Other than that, it's straightforward...
779          */
780         ath_stop(ifp);
781         ieee80211_ifdetach(ifp->if_l2com);
782         taskqueue_free(sc->sc_tq);
783 #ifdef ATH_TX99_DIAG
784         if (sc->sc_tx99 != NULL)
785                 sc->sc_tx99->detach(sc->sc_tx99);
786 #endif
787         ath_rate_detach(sc->sc_rc);
788         ath_desc_free(sc);
789         ath_tx_cleanup(sc);
790         ath_hal_detach(sc->sc_ah);      /* NB: sets chip in full sleep */
791         if (sc->sc_sysctl_tree) {
792                 sysctl_ctx_free(&sc->sc_sysctl_ctx);
793                 sc->sc_sysctl_tree = NULL;
794         }
795         if_free(ifp);
796
797         return 0;
798 }
799
800 /*
801  * MAC address handling for multiple BSS on the same radio.
802  * The first vap uses the MAC address from the EEPROM.  For
803  * subsequent vap's we set the U/L bit (bit 1) in the MAC
804  * address and use the next six bits as an index.
805  */
806 static void
807 assign_address(struct ath_softc *sc, uint8_t mac[IEEE80211_ADDR_LEN], int clone)
808 {
809         int i;
810
811         if (clone && sc->sc_hasbmask) {
812                 /* NB: we only do this if h/w supports multiple bssid */
813                 for (i = 0; i < 8; i++)
814                         if ((sc->sc_bssidmask & (1<<i)) == 0)
815                                 break;
816                 if (i != 0)
817                         mac[0] |= (i << 2)|0x2;
818         } else
819                 i = 0;
820         sc->sc_bssidmask |= 1<<i;
821         sc->sc_hwbssidmask[0] &= ~mac[0];
822         if (i == 0)
823                 sc->sc_nbssid0++;
824 }
825
826 static void
827 reclaim_address(struct ath_softc *sc, const uint8_t mac[IEEE80211_ADDR_LEN])
828 {
829         int i = mac[0] >> 2;
830         uint8_t mask;
831
832         if (i != 0 || --sc->sc_nbssid0 == 0) {
833                 sc->sc_bssidmask &= ~(1<<i);
834                 /* recalculate bssid mask from remaining addresses */
835                 mask = 0xff;
836                 for (i = 1; i < 8; i++)
837                         if (sc->sc_bssidmask & (1<<i))
838                                 mask &= ~((i<<2)|0x2);
839                 sc->sc_hwbssidmask[0] |= mask;
840         }
841 }
842
843 /*
844  * Assign a beacon xmit slot.  We try to space out
845  * assignments so when beacons are staggered the
846  * traffic coming out of the cab q has maximal time
847  * to go out before the next beacon is scheduled.
848  */
849 static int
850 assign_bslot(struct ath_softc *sc)
851 {
852         u_int slot, free;
853
854         free = 0;
855         for (slot = 0; slot < ATH_BCBUF; slot++)
856                 if (sc->sc_bslot[slot] == NULL) {
857                         if (sc->sc_bslot[(slot+1)%ATH_BCBUF] == NULL &&
858                             sc->sc_bslot[(slot-1)%ATH_BCBUF] == NULL)
859                                 return slot;
860                         free = slot;
861                         /* NB: keep looking for a double slot */
862                 }
863         return free;
864 }
865
866 static struct ieee80211vap *
867 ath_vap_create(struct ieee80211com *ic,
868         const char name[IFNAMSIZ], int unit, int opmode, int flags,
869         const uint8_t bssid[IEEE80211_ADDR_LEN],
870         const uint8_t mac0[IEEE80211_ADDR_LEN])
871 {
872         struct ath_softc *sc = ic->ic_ifp->if_softc;
873         struct ath_vap *avp;
874         struct ieee80211vap *vap;
875         uint8_t mac[IEEE80211_ADDR_LEN];
876         int ic_opmode, needbeacon, error;
877
878         avp = (struct ath_vap *) kmalloc(sizeof(struct ath_vap),
879             M_80211_VAP, M_WAITOK | M_ZERO);
880         needbeacon = 0;
881         IEEE80211_ADDR_COPY(mac, mac0);
882
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         error = ieee80211_vap_setup(ic, vap, name, unit, opmode, flags,
978             bssid, mac);
979         if (error != 0) {
980                 device_printf(sc->sc_dev, "%s: error %d creating vap\n",
981                     __func__, error);
982                 goto bad2;
983         }
984
985         /* h/w crypto support */
986         vap->iv_key_alloc = ath_key_alloc;
987         vap->iv_key_delete = ath_key_delete;
988         vap->iv_key_set = ath_key_set;
989         vap->iv_key_update_begin = ath_key_update_begin;
990         vap->iv_key_update_end = ath_key_update_end;
991
992         /* override various methods */
993         avp->av_recv_mgmt = vap->iv_recv_mgmt;
994         vap->iv_recv_mgmt = ath_recv_mgmt;
995         vap->iv_reset = ath_reset_vap;
996         vap->iv_update_beacon = ath_beacon_update;
997         avp->av_newstate = vap->iv_newstate;
998         vap->iv_newstate = ath_newstate;
999         avp->av_bmiss = vap->iv_bmiss;
1000         vap->iv_bmiss = ath_bmiss_vap;
1001
1002         avp->av_bslot = -1;
1003         if (needbeacon) {
1004                 /*
1005                  * Allocate beacon state and setup the q for buffered
1006                  * multicast frames.  We know a beacon buffer is
1007                  * available because we checked above.
1008                  */
1009                 avp->av_bcbuf = STAILQ_FIRST(&sc->sc_bbuf);
1010                 STAILQ_REMOVE_HEAD(&sc->sc_bbuf, bf_list);
1011                 if (opmode != IEEE80211_M_IBSS || !sc->sc_hasveol) {
1012                         /*
1013                          * Assign the vap to a beacon xmit slot.  As above
1014                          * this cannot fail to find a free one.
1015                          */
1016                         avp->av_bslot = assign_bslot(sc);
1017                         KASSERT(sc->sc_bslot[avp->av_bslot] == NULL,
1018                             ("beacon slot %u not empty", avp->av_bslot));
1019                         sc->sc_bslot[avp->av_bslot] = vap;
1020                         sc->sc_nbcnvaps++;
1021                 }
1022                 if (sc->sc_hastsfadd && sc->sc_nbcnvaps > 0) {
1023                         /*
1024                          * Multple vaps are to transmit beacons and we
1025                          * have h/w support for TSF adjusting; enable
1026                          * use of staggered beacons.
1027                          */
1028                         sc->sc_stagbeacons = 1;
1029                 }
1030                 ath_txq_init(sc, &avp->av_mcastq, ATH_TXQ_SWQ);
1031         }
1032
1033         ic->ic_opmode = ic_opmode;
1034         if (opmode != IEEE80211_M_WDS) {
1035                 sc->sc_nvaps++;
1036                 if (opmode == IEEE80211_M_STA)
1037                         sc->sc_nstavaps++;
1038                 if (opmode == IEEE80211_M_MBSS)
1039                         sc->sc_nmeshvaps++;
1040         }
1041         switch (ic_opmode) {
1042         case IEEE80211_M_IBSS:
1043                 sc->sc_opmode = HAL_M_IBSS;
1044                 break;
1045         case IEEE80211_M_STA:
1046                 sc->sc_opmode = HAL_M_STA;
1047                 break;
1048         case IEEE80211_M_AHDEMO:
1049 #ifdef IEEE80211_SUPPORT_TDMA
1050                 if (vap->iv_caps & IEEE80211_C_TDMA) {
1051                         sc->sc_tdma = 1;
1052                         /* NB: disable tsf adjust */
1053                         sc->sc_stagbeacons = 0;
1054                 }
1055                 /*
1056                  * NB: adhoc demo mode is a pseudo mode; to the hal it's
1057                  * just ap mode.
1058                  */
1059                 /* fall thru... */
1060 #endif
1061         case IEEE80211_M_HOSTAP:
1062         case IEEE80211_M_MBSS:
1063                 sc->sc_opmode = HAL_M_HOSTAP;
1064                 break;
1065         case IEEE80211_M_MONITOR:
1066                 sc->sc_opmode = HAL_M_MONITOR;
1067                 break;
1068         default:
1069                 /* XXX should not happen */
1070                 break;
1071         }
1072         if (sc->sc_hastsfadd) {
1073                 /*
1074                  * Configure whether or not TSF adjust should be done.
1075                  */
1076                 ath_hal_settsfadjust(sc->sc_ah, sc->sc_stagbeacons);
1077         }
1078         if (flags & IEEE80211_CLONE_NOBEACONS) {
1079                 /*
1080                  * Enable s/w beacon miss handling.
1081                  */
1082                 sc->sc_swbmiss = 1;
1083         }
1084
1085         /* complete setup */
1086         ieee80211_vap_attach(vap, ath_media_change, ieee80211_media_status);
1087         return vap;
1088 bad2:
1089         reclaim_address(sc, mac);
1090         ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
1091 bad:
1092         kfree(avp, M_80211_VAP);
1093         return NULL;
1094 }
1095
1096 static void
1097 ath_vap_delete(struct ieee80211vap *vap)
1098 {
1099         struct ieee80211com *ic = vap->iv_ic;
1100         struct ifnet *ifp = ic->ic_ifp;
1101         struct ath_softc *sc = ifp->if_softc;
1102         struct ath_hal *ah = sc->sc_ah;
1103         struct ath_vap *avp = ATH_VAP(vap);
1104
1105         if (ifp->if_flags & IFF_RUNNING) {
1106                 /*
1107                  * Quiesce the hardware while we remove the vap.  In
1108                  * particular we need to reclaim all references to
1109                  * the vap state by any frames pending on the tx queues.
1110                  */
1111                 ath_hal_intrset(ah, 0);         /* disable interrupts */
1112                 ath_draintxq(sc);               /* stop xmit side */
1113                 ath_stoprecv(sc);               /* stop recv side */
1114         }
1115
1116         ieee80211_vap_detach(vap);
1117         /*
1118          * Reclaim beacon state.  Note this must be done before
1119          * the vap instance is reclaimed as we may have a reference
1120          * to it in the buffer for the beacon frame.
1121          */
1122         if (avp->av_bcbuf != NULL) {
1123                 if (avp->av_bslot != -1) {
1124                         sc->sc_bslot[avp->av_bslot] = NULL;
1125                         sc->sc_nbcnvaps--;
1126                 }
1127                 ath_beacon_return(sc, avp->av_bcbuf);
1128                 avp->av_bcbuf = NULL;
1129                 if (sc->sc_nbcnvaps == 0) {
1130                         sc->sc_stagbeacons = 0;
1131                         if (sc->sc_hastsfadd)
1132                                 ath_hal_settsfadjust(sc->sc_ah, 0);
1133                 }
1134                 /*
1135                  * Reclaim any pending mcast frames for the vap.
1136                  */
1137                 ath_tx_draintxq(sc, &avp->av_mcastq);
1138         }
1139         /*
1140          * Update bookkeeping.
1141          */
1142         if (vap->iv_opmode == IEEE80211_M_STA) {
1143                 sc->sc_nstavaps--;
1144                 if (sc->sc_nstavaps == 0 && sc->sc_swbmiss)
1145                         sc->sc_swbmiss = 0;
1146         } else if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1147             vap->iv_opmode == IEEE80211_M_MBSS) {
1148                 reclaim_address(sc, vap->iv_myaddr);
1149                 ath_hal_setbssidmask(ah, sc->sc_hwbssidmask);
1150                 if (vap->iv_opmode == IEEE80211_M_MBSS)
1151                         sc->sc_nmeshvaps--;
1152         }
1153         if (vap->iv_opmode != IEEE80211_M_WDS)
1154                 sc->sc_nvaps--;
1155 #ifdef IEEE80211_SUPPORT_TDMA
1156         /* TDMA operation ceases when the last vap is destroyed */
1157         if (sc->sc_tdma && sc->sc_nvaps == 0) {
1158                 sc->sc_tdma = 0;
1159                 sc->sc_swbmiss = 0;
1160         }
1161 #endif
1162         kfree(avp, M_80211_VAP);
1163
1164         if (ifp->if_flags & IFF_RUNNING) {
1165                 /*
1166                  * Restart rx+tx machines if still running (RUNNING will
1167                  * be reset if we just destroyed the last vap).
1168                  */
1169                 if (ath_startrecv(sc) != 0)
1170                         if_printf(ifp, "%s: unable to restart recv logic\n",
1171                             __func__);
1172                 if (sc->sc_beacons) {           /* restart beacons */
1173 #ifdef IEEE80211_SUPPORT_TDMA
1174                         if (sc->sc_tdma)
1175                                 ath_tdma_config(sc, NULL);
1176                         else
1177 #endif
1178                                 ath_beacon_config(sc, NULL);
1179                 }
1180                 ath_hal_intrset(ah, sc->sc_imask);
1181         }
1182 }
1183
1184 void
1185 ath_suspend(struct ath_softc *sc)
1186 {
1187         struct ifnet *ifp = sc->sc_ifp;
1188         struct ieee80211com *ic = ifp->if_l2com;
1189
1190         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1191                 __func__, ifp->if_flags);
1192
1193         sc->sc_resume_up = (ifp->if_flags & IFF_UP) != 0;
1194         if (ic->ic_opmode == IEEE80211_M_STA)
1195                 ath_stop(ifp);
1196         else
1197                 ieee80211_suspend_all(ic);
1198         /*
1199          * NB: don't worry about putting the chip in low power
1200          * mode; pci will power off our socket on suspend and
1201          * CardBus detaches the device.
1202          */
1203 }
1204
1205 /*
1206  * Reset the key cache since some parts do not reset the
1207  * contents on resume.  First we clear all entries, then
1208  * re-load keys that the 802.11 layer assumes are setup
1209  * in h/w.
1210  */
1211 static void
1212 ath_reset_keycache(struct ath_softc *sc)
1213 {
1214         struct ifnet *ifp = sc->sc_ifp;
1215         struct ieee80211com *ic = ifp->if_l2com;
1216         struct ath_hal *ah = sc->sc_ah;
1217         int i;
1218
1219         for (i = 0; i < sc->sc_keymax; i++)
1220                 ath_hal_keyreset(ah, i);
1221         ieee80211_crypto_reload_keys(ic);
1222 }
1223
1224 void
1225 ath_resume(struct ath_softc *sc)
1226 {
1227         struct ifnet *ifp = sc->sc_ifp;
1228         struct ieee80211com *ic = ifp->if_l2com;
1229         struct ath_hal *ah = sc->sc_ah;
1230         HAL_STATUS status;
1231
1232         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1233                 __func__, ifp->if_flags);
1234
1235         /*
1236          * Must reset the chip before we reload the
1237          * keycache as we were powered down on suspend.
1238          */
1239         ath_hal_reset(ah, sc->sc_opmode,
1240             sc->sc_curchan != NULL ? sc->sc_curchan : ic->ic_curchan,
1241             AH_FALSE, &status);
1242         ath_reset_keycache(sc);
1243         if (sc->sc_resume_up) {
1244                 if (ic->ic_opmode == IEEE80211_M_STA) {
1245                         ath_init(sc);
1246                         /*
1247                          * Program the beacon registers using the last rx'd
1248                          * beacon frame and enable sync on the next beacon
1249                          * we see.  This should handle the case where we
1250                          * wakeup and find the same AP and also the case where
1251                          * we wakeup and need to roam.  For the latter we
1252                          * should get bmiss events that trigger a roam.
1253                          */
1254                         ath_beacon_config(sc, NULL);
1255                         sc->sc_syncbeacon = 1;
1256                 } else
1257                         ieee80211_resume_all(ic);
1258         }
1259         if (sc->sc_softled) {
1260                 ath_hal_gpioCfgOutput(ah, sc->sc_ledpin,
1261                     HAL_GPIO_MUX_MAC_NETWORK_LED);
1262                 ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
1263         }
1264 }
1265
1266 void
1267 ath_shutdown(struct ath_softc *sc)
1268 {
1269         struct ifnet *ifp = sc->sc_ifp;
1270
1271         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1272                 __func__, ifp->if_flags);
1273
1274         ath_stop(ifp);
1275         /* NB: no point powering down chip as we're about to reboot */
1276 }
1277
1278 /*
1279  * Interrupt handler.  Most of the actual processing is deferred.
1280  */
1281 void
1282 ath_intr(void *arg)
1283 {
1284         struct ath_softc *sc = arg;
1285         struct ifnet *ifp = sc->sc_ifp;
1286         struct ath_hal *ah = sc->sc_ah;
1287         HAL_INT status;
1288         HAL_INT ostatus;
1289
1290         if (sc->sc_invalid) {
1291                 /*
1292                  * The hardware is not ready/present, don't touch anything.
1293                  * Note this can happen early on if the IRQ is shared.
1294                  */
1295                 DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
1296                 return;
1297         }
1298
1299         if (!ath_hal_intrpend(ah))              /* shared irq, not for us */
1300                 return;
1301         if ((ifp->if_flags & IFF_UP) == 0 ||
1302             (ifp->if_flags & IFF_RUNNING) == 0) {
1303                 HAL_INT status;
1304
1305                 DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1306                         __func__, ifp->if_flags);
1307                 ath_hal_getisr(ah, &status);    /* clear ISR */
1308                 ath_hal_intrset(ah, 0);         /* disable further intr's */
1309                 return;
1310         }
1311         /*
1312          * Figure out the reason(s) for the interrupt.  Note
1313          * that the hal returns a pseudo-ISR that may include
1314          * bits we haven't explicitly enabled so we mask the
1315          * value to insure we only process bits we requested.
1316          */
1317         ath_hal_getisr(ah, &ostatus);           /* NB: clears ISR too */
1318         DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, ostatus);
1319         status = ostatus & sc->sc_imask;        /* discard unasked for bits */
1320         if (status & HAL_INT_FATAL) {
1321                 sc->sc_stats.ast_hardware++;
1322                 ath_hal_intrset(ah, 0);         /* disable intr's until reset */
1323                 ath_fatal_proc(sc, 0);
1324         } else {
1325                 if (status & HAL_INT_SWBA) {
1326                         /*
1327                          * Software beacon alert--time to send a beacon.
1328                          * Handle beacon transmission directly; deferring
1329                          * this is too slow to meet timing constraints
1330                          * under load.
1331                          */
1332 #ifdef IEEE80211_SUPPORT_TDMA
1333                         if (sc->sc_tdma) {
1334                                 if (sc->sc_tdmaswba == 0) {
1335                                         struct ieee80211com *ic = ifp->if_l2com;
1336                                         struct ieee80211vap *vap =
1337                                             TAILQ_FIRST(&ic->ic_vaps);
1338                                         ath_tdma_beacon_send(sc, vap);
1339                                         sc->sc_tdmaswba =
1340                                             vap->iv_tdma->tdma_bintval;
1341                                 } else
1342                                         sc->sc_tdmaswba--;
1343                         } else
1344 #endif
1345                         {
1346                                 ath_beacon_proc(sc, 0);
1347 #ifdef IEEE80211_SUPPORT_SUPERG
1348                                 /*
1349                                  * Schedule the rx taskq in case there's no
1350                                  * traffic so any frames held on the staging
1351                                  * queue are aged and potentially flushed.
1352                                  */
1353                                 taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1354 #endif
1355                         }
1356                 }
1357
1358                 /*
1359                  * NB: The hardware should re-read the link when the RXE
1360                  *     bit is written, but it doesn't work at least on
1361                  *     older chipsets.
1362                  */
1363                 if (status & HAL_INT_RXEOL) {
1364                         sc->sc_stats.ast_rxeol++;
1365                         sc->sc_rxlink = NULL;
1366                 }
1367
1368                 if (status & HAL_INT_TXURN) {
1369                         sc->sc_stats.ast_txurn++;
1370                         /* bump tx trigger level */
1371                         ath_hal_updatetxtriglevel(ah, AH_TRUE);
1372                 }
1373
1374                 if (status & HAL_INT_RX)
1375                         taskqueue_enqueue(sc->sc_tq, &sc->sc_rxtask);
1376
1377                 if (status & HAL_INT_TX)
1378                         taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
1379
1380                 if (status & HAL_INT_BMISS) {
1381                         sc->sc_stats.ast_bmiss++;
1382                         taskqueue_enqueue(sc->sc_tq, &sc->sc_bmisstask);
1383                 }
1384
1385                 if (status & HAL_INT_MIB) {
1386                         sc->sc_stats.ast_mib++;
1387                         /*
1388                          * Disable interrupts until we service the MIB
1389                          * interrupt; otherwise it will continue to fire.
1390                          */
1391                         ath_hal_intrset(ah, 0);
1392                         /*
1393                          * Let the hal handle the event.  We assume it will
1394                          * clear whatever condition caused the interrupt.
1395                          */
1396                         ath_hal_mibevent(ah, &sc->sc_halstats);
1397                         ath_hal_intrset(ah, sc->sc_imask);
1398                 }
1399
1400                 if (status & HAL_INT_RXORN) {
1401                         /* NB: hal marks HAL_INT_FATAL when RXORN is fatal */
1402                         sc->sc_stats.ast_rxorn++;
1403                 }
1404         }
1405 }
1406
1407 static void
1408 ath_fatal_proc(void *arg, int pending)
1409 {
1410         struct ath_softc *sc = arg;
1411         struct ifnet *ifp = sc->sc_ifp;
1412         u_int32_t *state;
1413         u_int32_t len;
1414         void *sp;
1415
1416         if_printf(ifp, "hardware error; resetting\n");
1417         /*
1418          * Fatal errors are unrecoverable.  Typically these
1419          * are caused by DMA errors.  Collect h/w state from
1420          * the hal so we can diagnose what's going on.
1421          */
1422         if (ath_hal_getfatalstate(sc->sc_ah, &sp, &len)) {
1423                 KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
1424                 state = sp;
1425                 if_printf(ifp, "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n",
1426                     state[0], state[1] , state[2], state[3],
1427                     state[4], state[5]);
1428         }
1429         ath_reset(ifp);
1430 }
1431
1432 static void
1433 ath_bmiss_vap(struct ieee80211vap *vap)
1434 {
1435         /*
1436          * Workaround phantom bmiss interrupts by sanity-checking
1437          * the time of our last rx'd frame.  If it is within the
1438          * beacon miss interval then ignore the interrupt.  If it's
1439          * truly a bmiss we'll get another interrupt soon and that'll
1440          * be dispatched up for processing.  Note this applies only
1441          * for h/w beacon miss events.
1442          */
1443         if ((vap->iv_flags_ext & IEEE80211_FEXT_SWBMISS) == 0) {
1444                 struct ifnet *ifp = vap->iv_ic->ic_ifp;
1445                 struct ath_softc *sc = ifp->if_softc;
1446                 u_int64_t lastrx = sc->sc_lastrx;
1447                 u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
1448                 u_int bmisstimeout =
1449                         vap->iv_bmissthreshold * vap->iv_bss->ni_intval * 1024;
1450
1451                 DPRINTF(sc, ATH_DEBUG_BEACON,
1452                     "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
1453                     __func__, (unsigned long long) tsf,
1454                     (unsigned long long)(tsf - lastrx),
1455                     (unsigned long long) lastrx, bmisstimeout);
1456
1457                 if (tsf - lastrx <= bmisstimeout) {
1458                         sc->sc_stats.ast_bmiss_phantom++;
1459                         return;
1460                 }
1461         }
1462         ATH_VAP(vap)->av_bmiss(vap);
1463 }
1464
1465 static int
1466 ath_hal_gethangstate(struct ath_hal *ah, uint32_t mask, uint32_t *hangs)
1467 {
1468         uint32_t rsize;
1469         void *sp;
1470
1471         if (!ath_hal_getdiagstate(ah, 32, &mask, sizeof(mask), &sp, &rsize))
1472                 return 0;
1473         KASSERT(rsize == sizeof(uint32_t), ("resultsize %u", rsize));
1474         *hangs = *(uint32_t *)sp;
1475         return 1;
1476 }
1477
1478 static void
1479 ath_bmiss_task(void *arg, int pending)
1480 {
1481         struct ath_softc *sc = arg;
1482         struct ifnet *ifp = sc->sc_ifp;
1483         uint32_t hangs;
1484
1485         wlan_serialize_enter();
1486         DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
1487
1488         if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0) {
1489                 if_printf(ifp, "bb hang detected (0x%x), reseting\n", hangs); 
1490                 ath_reset(ifp);
1491         } else {
1492                 ieee80211_beacon_miss(ifp->if_l2com);
1493         }
1494         wlan_serialize_exit();
1495 }
1496
1497 /*
1498  * Handle TKIP MIC setup to deal hardware that doesn't do MIC
1499  * calcs together with WME.  If necessary disable the crypto
1500  * hardware and mark the 802.11 state so keys will be setup
1501  * with the MIC work done in software.
1502  */
1503 static void
1504 ath_settkipmic(struct ath_softc *sc)
1505 {
1506         struct ifnet *ifp = sc->sc_ifp;
1507         struct ieee80211com *ic = ifp->if_l2com;
1508
1509         if ((ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIP) && !sc->sc_wmetkipmic) {
1510                 if (ic->ic_flags & IEEE80211_F_WME) {
1511                         ath_hal_settkipmic(sc->sc_ah, AH_FALSE);
1512                         ic->ic_cryptocaps &= ~IEEE80211_CRYPTO_TKIPMIC;
1513                 } else {
1514                         ath_hal_settkipmic(sc->sc_ah, AH_TRUE);
1515                         ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
1516                 }
1517         }
1518 }
1519
1520 static void
1521 ath_init(void *arg)
1522 {
1523         struct ath_softc *sc = (struct ath_softc *) arg;
1524         struct ifnet *ifp = sc->sc_ifp;
1525         struct ieee80211com *ic = ifp->if_l2com;
1526         struct ath_hal *ah = sc->sc_ah;
1527         HAL_STATUS status;
1528
1529         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
1530                 __func__, ifp->if_flags);
1531
1532         /*
1533          * Stop anything previously setup.  This is safe
1534          * whether this is the first time through or not.
1535          */
1536         ath_stop_locked(ifp);
1537
1538         /*
1539          * The basic interface to setting the hardware in a good
1540          * state is ``reset''.  On return the hardware is known to
1541          * be powered up and with interrupts disabled.  This must
1542          * be followed by initialization of the appropriate bits
1543          * and then setup of the interrupt mask.
1544          */
1545         ath_settkipmic(sc);
1546         if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_FALSE, &status)) {
1547                 if_printf(ifp, "unable to reset hardware; hal status %u\n",
1548                         status);
1549                 return;
1550         }
1551         ath_chan_change(sc, ic->ic_curchan);
1552
1553         /*
1554          * Likewise this is set during reset so update
1555          * state cached in the driver.
1556          */
1557         sc->sc_diversity = ath_hal_getdiversity(ah);
1558         sc->sc_lastlongcal = 0;
1559         sc->sc_resetcal = 1;
1560         sc->sc_lastcalreset = 0;
1561
1562         /*
1563          * Setup the hardware after reset: the key cache
1564          * is filled as needed and the receive engine is
1565          * set going.  Frame transmit is handled entirely
1566          * in the frame output path; there's nothing to do
1567          * here except setup the interrupt mask.
1568          */
1569         if (ath_startrecv(sc) != 0) {
1570                 if_printf(ifp, "unable to start recv logic\n");
1571                 return;
1572         }
1573
1574         /*
1575          * Enable interrupts.
1576          */
1577         sc->sc_imask = HAL_INT_RX | HAL_INT_TX
1578                   | HAL_INT_RXEOL | HAL_INT_RXORN
1579                   | HAL_INT_FATAL | HAL_INT_GLOBAL;
1580         /*
1581          * Enable MIB interrupts when there are hardware phy counters.
1582          * Note we only do this (at the moment) for station mode.
1583          */
1584         if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
1585                 sc->sc_imask |= HAL_INT_MIB;
1586
1587         ifp->if_flags |= IFF_RUNNING;
1588         callout_reset(&sc->sc_wd_ch, hz, ath_watchdog_callout, sc);
1589         ath_hal_intrset(ah, sc->sc_imask);
1590
1591
1592 #ifdef ATH_TX99_DIAG
1593         if (sc->sc_tx99 != NULL)
1594                 sc->sc_tx99->start(sc->sc_tx99);
1595         else
1596 #endif
1597         ieee80211_start_all(ic);                /* start all vap's */
1598 }
1599
1600 static void
1601 ath_stop_locked(struct ifnet *ifp)
1602 {
1603         struct ath_softc *sc = ifp->if_softc;
1604         struct ath_hal *ah = sc->sc_ah;
1605
1606         DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
1607                 __func__, sc->sc_invalid, ifp->if_flags);
1608
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 __unused = ifp->if_softc;
1655
1656         ath_stop_locked(ifp);
1657 }
1658
1659 /*
1660  * Reset the hardware w/o losing operational state.  This is
1661  * basically a more efficient way of doing ath_stop, ath_init,
1662  * followed by state transitions to the current 802.11
1663  * operational state.  Used to recover from various errors and
1664  * to reset or reload hardware state.
1665  */
1666 static int
1667 ath_reset(struct ifnet *ifp)
1668 {
1669         struct ath_softc *sc = ifp->if_softc;
1670         struct ieee80211com *ic = ifp->if_l2com;
1671         struct ath_hal *ah = sc->sc_ah;
1672         HAL_STATUS status;
1673
1674         kprintf("ath_reset\n");
1675         ath_hal_intrset(ah, 0);         /* disable interrupts */
1676         ath_draintxq(sc);               /* stop xmit side */
1677         ath_stoprecv(sc);               /* stop recv side */
1678         ath_settkipmic(sc);             /* configure TKIP MIC handling */
1679         /* NB: indicate channel change so we do a full reset */
1680         if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_TRUE, &status))
1681                 if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
1682                         __func__, status);
1683         sc->sc_diversity = ath_hal_getdiversity(ah);
1684         if (ath_startrecv(sc) != 0)     /* restart recv */
1685                 if_printf(ifp, "%s: unable to start recv logic\n", __func__);
1686         /*
1687          * We may be doing a reset in response to an ioctl
1688          * that changes the channel so update any state that
1689          * might change as a result.
1690          */
1691         ath_chan_change(sc, ic->ic_curchan);
1692         if (sc->sc_beacons) {           /* restart beacons */
1693 #ifdef IEEE80211_SUPPORT_TDMA
1694                 if (sc->sc_tdma)
1695                         ath_tdma_config(sc, NULL);
1696                 else
1697 #endif
1698                         ath_beacon_config(sc, NULL);
1699         }
1700         ath_hal_intrset(ah, sc->sc_imask);
1701
1702         ath_start(ifp);                 /* restart xmit */
1703         return 0;
1704 }
1705
1706 static int
1707 ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
1708 {
1709         struct ieee80211com *ic = vap->iv_ic;
1710         struct ifnet *ifp = ic->ic_ifp;
1711         struct ath_softc *sc = ifp->if_softc;
1712         struct ath_hal *ah = sc->sc_ah;
1713
1714         switch (cmd) {
1715         case IEEE80211_IOC_TXPOWER:
1716                 /*
1717                  * If per-packet TPC is enabled, then we have nothing
1718                  * to do; otherwise we need to force the global limit.
1719                  * All this can happen directly; no need to reset.
1720                  */
1721                 if (!ath_hal_gettpc(ah))
1722                         ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
1723                 return 0;
1724         }
1725         return ath_reset(ifp);
1726 }
1727
1728 static struct ath_buf *
1729 _ath_getbuf_locked(struct ath_softc *sc)
1730 {
1731         struct ath_buf *bf;
1732
1733         bf = STAILQ_FIRST(&sc->sc_txbuf);
1734         if (bf != NULL && (bf->bf_flags & ATH_BUF_BUSY) == 0)
1735                 STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
1736         else
1737                 bf = NULL;
1738         if (bf == NULL) {
1739                 kprintf("ath: ran out of descriptors\n");
1740                 DPRINTF(sc, ATH_DEBUG_XMIT, "%s: %s\n", __func__,
1741                     STAILQ_FIRST(&sc->sc_txbuf) == NULL ?
1742                         "out of xmit buffers" : "xmit buffer busy");
1743         }
1744         return bf;
1745 }
1746
1747 static struct ath_buf *
1748 ath_getbuf(struct ath_softc *sc)
1749 {
1750         struct ath_buf *bf;
1751
1752         bf = _ath_getbuf_locked(sc);
1753         if (bf == NULL) {
1754                 struct ifnet *ifp = sc->sc_ifp;
1755
1756                 DPRINTF(sc, ATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
1757                 sc->sc_stats.ast_tx_qstop++;
1758                 ifp->if_flags |= IFF_OACTIVE;
1759         }
1760         return bf;
1761 }
1762
1763 /*
1764  * Cleanup driver resources when we run out of buffers
1765  * while processing fragments; return the tx buffers
1766  * allocated and drop node references.
1767  */
1768 static void
1769 ath_txfrag_cleanup(struct ath_softc *sc,
1770         ath_bufhead *frags, struct ieee80211_node *ni)
1771 {
1772         struct ath_buf *bf, *next;
1773
1774         STAILQ_FOREACH_MUTABLE(bf, frags, bf_list, next) {
1775                 /* NB: bf assumed clean */
1776                 STAILQ_REMOVE_HEAD(frags, bf_list);
1777                 STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1778                 ieee80211_node_decref(ni);
1779         }
1780 }
1781
1782 /*
1783  * Setup xmit of a fragmented frame.  Allocate a buffer
1784  * for each frag and bump the node reference count to
1785  * reflect the held reference to be setup by ath_tx_start.
1786  */
1787 static int
1788 ath_txfrag_setup(struct ath_softc *sc, ath_bufhead *frags,
1789         struct mbuf *m0, struct ieee80211_node *ni)
1790 {
1791         struct mbuf *m;
1792         struct ath_buf *bf;
1793
1794         for (m = m0->m_nextpkt; m != NULL; m = m->m_nextpkt) {
1795                 bf = _ath_getbuf_locked(sc);
1796                 if (bf == NULL) {       /* out of buffers, cleanup */
1797                         ath_txfrag_cleanup(sc, frags, ni);
1798                         break;
1799                 }
1800                 ieee80211_node_incref(ni);
1801                 STAILQ_INSERT_TAIL(frags, bf, bf_list);
1802         }
1803
1804         return !STAILQ_EMPTY(frags);
1805 }
1806
1807 static void
1808 ath_start(struct ifnet *ifp)
1809 {
1810         struct ath_softc *sc = ifp->if_softc;
1811         struct ieee80211_node *ni;
1812         struct ath_buf *bf;
1813         struct mbuf *m, *next;
1814         ath_bufhead frags;
1815
1816         if ((ifp->if_flags & IFF_RUNNING) == 0 || sc->sc_invalid) {
1817                 ifq_purge(&ifp->if_snd);
1818                 return;
1819         }
1820         for (;;) {
1821                 /*
1822                  * Grab a TX buffer and associated resources.
1823                  */
1824                 bf = ath_getbuf(sc);
1825                 if (bf == NULL)
1826                         break;
1827
1828                 IF_DEQUEUE(&ifp->if_snd, m);
1829                 if (m == NULL) {
1830                         STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1831                         break;
1832                 }
1833                 ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1834                 /*
1835                  * Check for fragmentation.  If this frame
1836                  * has been broken up verify we have enough
1837                  * buffers to send all the fragments so all
1838                  * go out or none...
1839                  */
1840                 STAILQ_INIT(&frags);
1841                 if ((m->m_flags & M_FRAG) && 
1842                     !ath_txfrag_setup(sc, &frags, m, ni)) {
1843                         DPRINTF(sc, ATH_DEBUG_XMIT,
1844                             "%s: out of txfrag buffers\n", __func__);
1845                         sc->sc_stats.ast_tx_nofrag++;
1846                         ifp->if_oerrors++;
1847                         ath_freetx(m);
1848                         goto bad;
1849                 }
1850                 ifp->if_opackets++;
1851         nextfrag:
1852                 /*
1853                  * Pass the frame to the h/w for transmission.
1854                  * Fragmented frames have each frag chained together
1855                  * with m_nextpkt.  We know there are sufficient ath_buf's
1856                  * to send all the frags because of work done by
1857                  * ath_txfrag_setup.  We leave m_nextpkt set while
1858                  * calling ath_tx_start so it can use it to extend the
1859                  * the tx duration to cover the subsequent frag and
1860                  * so it can reclaim all the mbufs in case of an error;
1861                  * ath_tx_start clears m_nextpkt once it commits to
1862                  * handing the frame to the hardware.
1863                  */
1864                 next = m->m_nextpkt;
1865                 if (ath_tx_start(sc, ni, bf, m)) {
1866         bad:
1867                         ifp->if_oerrors++;
1868         reclaim:
1869                         bf->bf_m = NULL;
1870                         bf->bf_node = NULL;
1871                         STAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
1872                         ath_txfrag_cleanup(sc, &frags, ni);
1873                         if (ni != NULL)
1874                                 ieee80211_free_node(ni);
1875                         continue;
1876                 }
1877                 if (next != NULL) {
1878                         /*
1879                          * Beware of state changing between frags.
1880                          * XXX check sta power-save state?
1881                          */
1882                         if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
1883                                 DPRINTF(sc, ATH_DEBUG_XMIT,
1884                                     "%s: flush fragmented packet, state %s\n",
1885                                     __func__,
1886                                     ieee80211_state_name[ni->ni_vap->iv_state]);
1887                                 ath_freetx(next);
1888                                 goto reclaim;
1889                         }
1890                         m = next;
1891                         bf = STAILQ_FIRST(&frags);
1892                         KASSERT(bf != NULL, ("no buf for txfrag"));
1893                         STAILQ_REMOVE_HEAD(&frags, bf_list);
1894                         goto nextfrag;
1895                 }
1896
1897                 sc->sc_wd_timer = 5;
1898         }
1899 }
1900
1901 static int
1902 ath_media_change(struct ifnet *ifp)
1903 {
1904         int error = ieee80211_media_change(ifp);
1905         /* NB: only the fixed rate can change and that doesn't need a reset */
1906         return (error == ENETRESET ? 0 : error);
1907 }
1908
1909 #ifdef ATH_DEBUG
1910 static void
1911 ath_keyprint(struct ath_softc *sc, const char *tag, u_int ix,
1912         const HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1913 {
1914         static const char *ciphers[] = {
1915                 "WEP",
1916                 "AES-OCB",
1917                 "AES-CCM",
1918                 "CKIP",
1919                 "TKIP",
1920                 "CLR",
1921         };
1922         int i, n;
1923
1924         kprintf("%s: [%02u] %-7s ", tag, ix, ciphers[hk->kv_type]);
1925         for (i = 0, n = hk->kv_len; i < n; i++)
1926                 kprintf("%02x", hk->kv_val[i]);
1927         kprintf(" mac %6D", mac, ":");
1928         if (hk->kv_type == HAL_CIPHER_TKIP) {
1929                 kprintf(" %s ", sc->sc_splitmic ? "mic" : "rxmic");
1930                 for (i = 0; i < sizeof(hk->kv_mic); i++)
1931                         kprintf("%02x", hk->kv_mic[i]);
1932                 if (!sc->sc_splitmic) {
1933                         kprintf(" txmic ");
1934                         for (i = 0; i < sizeof(hk->kv_txmic); i++)
1935                                 kprintf("%02x", hk->kv_txmic[i]);
1936                 }
1937         }
1938         kprintf("\n");
1939 }
1940 #endif
1941
1942 /*
1943  * Set a TKIP key into the hardware.  This handles the
1944  * potential distribution of key state to multiple key
1945  * cache slots for TKIP.
1946  */
1947 static int
1948 ath_keyset_tkip(struct ath_softc *sc, const struct ieee80211_key *k,
1949         HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1950 {
1951 #define IEEE80211_KEY_XR        (IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV)
1952         static const u_int8_t zerobssid[IEEE80211_ADDR_LEN];
1953         struct ath_hal *ah = sc->sc_ah;
1954
1955         KASSERT(k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP,
1956                 ("got a non-TKIP key, cipher %u", k->wk_cipher->ic_cipher));
1957         if ((k->wk_flags & IEEE80211_KEY_XR) == IEEE80211_KEY_XR) {
1958                 if (sc->sc_splitmic) {
1959                         /*
1960                          * TX key goes at first index, RX key at the rx index.
1961                          * The hal handles the MIC keys at index+64.
1962                          */
1963                         memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_mic));
1964                         KEYPRINTF(sc, k->wk_keyix, hk, zerobssid);
1965                         if (!ath_hal_keyset(ah, k->wk_keyix, hk, zerobssid))
1966                                 return 0;
1967
1968                         memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1969                         KEYPRINTF(sc, k->wk_keyix+32, hk, mac);
1970                         /* XXX delete tx key on failure? */
1971                         return ath_hal_keyset(ah, k->wk_keyix+32, hk, mac);
1972                 } else {
1973                         /*
1974                          * Room for both TX+RX MIC keys in one key cache
1975                          * slot, just set key at the first index; the hal
1976                          * will handle the rest.
1977                          */
1978                         memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1979                         memcpy(hk->kv_txmic, k->wk_txmic, sizeof(hk->kv_txmic));
1980                         KEYPRINTF(sc, k->wk_keyix, hk, mac);
1981                         return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1982                 }
1983         } else if (k->wk_flags & IEEE80211_KEY_XMIT) {
1984                 if (sc->sc_splitmic) {
1985                         /*
1986                          * NB: must pass MIC key in expected location when
1987                          * the keycache only holds one MIC key per entry.
1988                          */
1989                         memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_txmic));
1990                 } else
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         } else if (k->wk_flags & IEEE80211_KEY_RECV) {
1995                 memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1996                 KEYPRINTF(sc, k->wk_keyix, hk, mac);
1997                 return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1998         }
1999         return 0;
2000 #undef IEEE80211_KEY_XR
2001 }
2002
2003 /*
2004  * Set a net80211 key into the hardware.  This handles the
2005  * potential distribution of key state to multiple key
2006  * cache slots for TKIP with hardware MIC support.
2007  */
2008 static int
2009 ath_keyset(struct ath_softc *sc, const struct ieee80211_key *k,
2010         struct ieee80211_node *bss)
2011 {
2012 #define N(a)    (sizeof(a)/sizeof(a[0]))
2013         static const u_int8_t ciphermap[] = {
2014                 HAL_CIPHER_WEP,         /* IEEE80211_CIPHER_WEP */
2015                 HAL_CIPHER_TKIP,        /* IEEE80211_CIPHER_TKIP */
2016                 HAL_CIPHER_AES_OCB,     /* IEEE80211_CIPHER_AES_OCB */
2017                 HAL_CIPHER_AES_CCM,     /* IEEE80211_CIPHER_AES_CCM */
2018                 (u_int8_t) -1,          /* 4 is not allocated */
2019                 HAL_CIPHER_CKIP,        /* IEEE80211_CIPHER_CKIP */
2020                 HAL_CIPHER_CLR,         /* IEEE80211_CIPHER_NONE */
2021         };
2022         struct ath_hal *ah = sc->sc_ah;
2023         const struct ieee80211_cipher *cip = k->wk_cipher;
2024         u_int8_t gmac[IEEE80211_ADDR_LEN];
2025         const u_int8_t *mac;
2026         HAL_KEYVAL hk;
2027
2028         memset(&hk, 0, sizeof(hk));
2029         /*
2030          * Software crypto uses a "clear key" so non-crypto
2031          * state kept in the key cache are maintained and
2032          * so that rx frames have an entry to match.
2033          */
2034         if ((k->wk_flags & IEEE80211_KEY_SWCRYPT) == 0) {
2035                 KASSERT(cip->ic_cipher < N(ciphermap),
2036                         ("invalid cipher type %u", cip->ic_cipher));
2037                 hk.kv_type = ciphermap[cip->ic_cipher];
2038                 hk.kv_len = k->wk_keylen;
2039                 memcpy(hk.kv_val, k->wk_key, k->wk_keylen);
2040         } else
2041                 hk.kv_type = HAL_CIPHER_CLR;
2042
2043         if ((k->wk_flags & IEEE80211_KEY_GROUP) && sc->sc_mcastkey) {
2044                 /*
2045                  * Group keys on hardware that supports multicast frame
2046                  * key search use a MAC that is the sender's address with
2047                  * the high bit set instead of the app-specified address.
2048                  */
2049                 IEEE80211_ADDR_COPY(gmac, bss->ni_macaddr);
2050                 gmac[0] |= 0x80;
2051                 mac = gmac;
2052         } else
2053                 mac = k->wk_macaddr;
2054
2055         if (hk.kv_type == HAL_CIPHER_TKIP &&
2056             (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2057                 return ath_keyset_tkip(sc, k, &hk, mac);
2058         } else {
2059                 KEYPRINTF(sc, k->wk_keyix, &hk, mac);
2060                 return ath_hal_keyset(ah, k->wk_keyix, &hk, mac);
2061         }
2062 #undef N
2063 }
2064
2065 /*
2066  * Allocate tx/rx key slots for TKIP.  We allocate two slots for
2067  * each key, one for decrypt/encrypt and the other for the MIC.
2068  */
2069 static u_int16_t
2070 key_alloc_2pair(struct ath_softc *sc,
2071         ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2072 {
2073 #define N(a)    (sizeof(a)/sizeof(a[0]))
2074         u_int i, keyix;
2075
2076         KASSERT(sc->sc_splitmic, ("key cache !split"));
2077         /* XXX could optimize */
2078         for (i = 0; i < N(sc->sc_keymap)/4; i++) {
2079                 u_int8_t b = sc->sc_keymap[i];
2080                 if (b != 0xff) {
2081                         /*
2082                          * One or more slots in this byte are free.
2083                          */
2084                         keyix = i*NBBY;
2085                         while (b & 1) {
2086                 again:
2087                                 keyix++;
2088                                 b >>= 1;
2089                         }
2090                         /* XXX IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV */
2091                         if (isset(sc->sc_keymap, keyix+32) ||
2092                             isset(sc->sc_keymap, keyix+64) ||
2093                             isset(sc->sc_keymap, keyix+32+64)) {
2094                                 /* full pair unavailable */
2095                                 /* XXX statistic */
2096                                 if (keyix == (i+1)*NBBY) {
2097                                         /* no slots were appropriate, advance */
2098                                         continue;
2099                                 }
2100                                 goto again;
2101                         }
2102                         setbit(sc->sc_keymap, keyix);
2103                         setbit(sc->sc_keymap, keyix+64);
2104                         setbit(sc->sc_keymap, keyix+32);
2105                         setbit(sc->sc_keymap, keyix+32+64);
2106                         DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2107                                 "%s: key pair %u,%u %u,%u\n",
2108                                 __func__, keyix, keyix+64,
2109                                 keyix+32, keyix+32+64);
2110                         *txkeyix = keyix;
2111                         *rxkeyix = keyix+32;
2112                         return 1;
2113                 }
2114         }
2115         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
2116         return 0;
2117 #undef N
2118 }
2119
2120 /*
2121  * Allocate tx/rx key slots for TKIP.  We allocate two slots for
2122  * each key, one for decrypt/encrypt and the other for the MIC.
2123  */
2124 static u_int16_t
2125 key_alloc_pair(struct ath_softc *sc,
2126         ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2127 {
2128 #define N(a)    (sizeof(a)/sizeof(a[0]))
2129         u_int i, keyix;
2130
2131         KASSERT(!sc->sc_splitmic, ("key cache split"));
2132         /* XXX could optimize */
2133         for (i = 0; i < N(sc->sc_keymap)/4; i++) {
2134                 u_int8_t b = sc->sc_keymap[i];
2135                 if (b != 0xff) {
2136                         /*
2137                          * One or more slots in this byte are free.
2138                          */
2139                         keyix = i*NBBY;
2140                         while (b & 1) {
2141                 again:
2142                                 keyix++;
2143                                 b >>= 1;
2144                         }
2145                         if (isset(sc->sc_keymap, keyix+64)) {
2146                                 /* full pair unavailable */
2147                                 /* XXX statistic */
2148                                 if (keyix == (i+1)*NBBY) {
2149                                         /* no slots were appropriate, advance */
2150                                         continue;
2151                                 }
2152                                 goto again;
2153                         }
2154                         setbit(sc->sc_keymap, keyix);
2155                         setbit(sc->sc_keymap, keyix+64);
2156                         DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2157                                 "%s: key pair %u,%u\n",
2158                                 __func__, keyix, keyix+64);
2159                         *txkeyix = *rxkeyix = keyix;
2160                         return 1;
2161                 }
2162         }
2163         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
2164         return 0;
2165 #undef N
2166 }
2167
2168 /*
2169  * Allocate a single key cache slot.
2170  */
2171 static int
2172 key_alloc_single(struct ath_softc *sc,
2173         ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
2174 {
2175 #define N(a)    (sizeof(a)/sizeof(a[0]))
2176         u_int i, keyix;
2177
2178         /* XXX try i,i+32,i+64,i+32+64 to minimize key pair conflicts */
2179         for (i = 0; i < N(sc->sc_keymap); i++) {
2180                 u_int8_t b = sc->sc_keymap[i];
2181                 if (b != 0xff) {
2182                         /*
2183                          * One or more slots are free.
2184                          */
2185                         keyix = i*NBBY;
2186                         while (b & 1)
2187                                 keyix++, b >>= 1;
2188                         setbit(sc->sc_keymap, keyix);
2189                         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: key %u\n",
2190                                 __func__, keyix);
2191                         *txkeyix = *rxkeyix = keyix;
2192                         return 1;
2193                 }
2194         }
2195         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of space\n", __func__);
2196         return 0;
2197 #undef N
2198 }
2199
2200 /*
2201  * Allocate one or more key cache slots for a uniacst key.  The
2202  * key itself is needed only to identify the cipher.  For hardware
2203  * TKIP with split cipher+MIC keys we allocate two key cache slot
2204  * pairs so that we can setup separate TX and RX MIC keys.  Note
2205  * that the MIC key for a TKIP key at slot i is assumed by the
2206  * hardware to be at slot i+64.  This limits TKIP keys to the first
2207  * 64 entries.
2208  */
2209 static int
2210 ath_key_alloc(struct ieee80211vap *vap, struct ieee80211_key *k,
2211         ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
2212 {
2213         struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2214
2215         /*
2216          * Group key allocation must be handled specially for
2217          * parts that do not support multicast key cache search
2218          * functionality.  For those parts the key id must match
2219          * the h/w key index so lookups find the right key.  On
2220          * parts w/ the key search facility we install the sender's
2221          * mac address (with the high bit set) and let the hardware
2222          * find the key w/o using the key id.  This is preferred as
2223          * it permits us to support multiple users for adhoc and/or
2224          * multi-station operation.
2225          */
2226         if (k->wk_keyix != IEEE80211_KEYIX_NONE) {
2227                 /*
2228                  * Only global keys should have key index assigned.
2229                  */
2230                 if (!(&vap->iv_nw_keys[0] <= k &&
2231                       k < &vap->iv_nw_keys[IEEE80211_WEP_NKID])) {
2232                         /* should not happen */
2233                         DPRINTF(sc, ATH_DEBUG_KEYCACHE,
2234                                 "%s: bogus group key\n", __func__);
2235                         return 0;
2236                 }
2237                 if (vap->iv_opmode != IEEE80211_M_HOSTAP ||
2238                     !(k->wk_flags & IEEE80211_KEY_GROUP) ||
2239                     !sc->sc_mcastkey) {
2240                         /*
2241                          * XXX we pre-allocate the global keys so
2242                          * have no way to check if they've already
2243                          * been allocated.
2244                          */
2245                         *keyix = *rxkeyix = k - vap->iv_nw_keys;
2246                         return 1;
2247                 }
2248                 /*
2249                  * Group key and device supports multicast key search.
2250                  */
2251                 k->wk_keyix = IEEE80211_KEYIX_NONE;
2252         }
2253
2254         /*
2255          * We allocate two pair for TKIP when using the h/w to do
2256          * the MIC.  For everything else, including software crypto,
2257          * we allocate a single entry.  Note that s/w crypto requires
2258          * a pass-through slot on the 5211 and 5212.  The 5210 does
2259          * not support pass-through cache entries and we map all
2260          * those requests to slot 0.
2261          */
2262         if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
2263                 return key_alloc_single(sc, keyix, rxkeyix);
2264         } else if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP &&
2265             (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2266                 if (sc->sc_splitmic)
2267                         return key_alloc_2pair(sc, keyix, rxkeyix);
2268                 else
2269                         return key_alloc_pair(sc, keyix, rxkeyix);
2270         } else {
2271                 return key_alloc_single(sc, keyix, rxkeyix);
2272         }
2273 }
2274
2275 /*
2276  * Delete an entry in the key cache allocated by ath_key_alloc.
2277  */
2278 static int
2279 ath_key_delete(struct ieee80211vap *vap, const struct ieee80211_key *k)
2280 {
2281         struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2282         struct ath_hal *ah = sc->sc_ah;
2283         const struct ieee80211_cipher *cip = k->wk_cipher;
2284         u_int keyix = k->wk_keyix;
2285
2286         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: delete key %u\n", __func__, keyix);
2287
2288         ath_hal_keyreset(ah, keyix);
2289         /*
2290          * Handle split tx/rx keying required for TKIP with h/w MIC.
2291          */
2292         if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
2293             (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic)
2294                 ath_hal_keyreset(ah, keyix+32);         /* RX key */
2295         if (keyix >= IEEE80211_WEP_NKID) {
2296                 /*
2297                  * Don't touch keymap entries for global keys so
2298                  * they are never considered for dynamic allocation.
2299                  */
2300                 clrbit(sc->sc_keymap, keyix);
2301                 if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
2302                     (k->wk_flags & IEEE80211_KEY_SWMIC) == 0) {
2303                         clrbit(sc->sc_keymap, keyix+64);        /* TX key MIC */
2304                         if (sc->sc_splitmic) {
2305                                 /* +32 for RX key, +32+64 for RX key MIC */
2306                                 clrbit(sc->sc_keymap, keyix+32);
2307                                 clrbit(sc->sc_keymap, keyix+32+64);
2308                         }
2309                 }
2310         }
2311         return 1;
2312 }
2313
2314 /*
2315  * Set the key cache contents for the specified key.  Key cache
2316  * slot(s) must already have been allocated by ath_key_alloc.
2317  */
2318 static int
2319 ath_key_set(struct ieee80211vap *vap, const struct ieee80211_key *k,
2320         const u_int8_t mac[IEEE80211_ADDR_LEN])
2321 {
2322         struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2323
2324         return ath_keyset(sc, k, vap->iv_bss);
2325 }
2326
2327 /*
2328  * Block/unblock tx+rx processing while a key change is done.
2329  * We assume the caller serializes key management operations
2330  * so we only need to worry about synchronization with other
2331  * uses that originate in the driver.
2332  */
2333 static void
2334 ath_key_update_begin(struct ieee80211vap *vap)
2335 {
2336         struct ifnet *ifp = vap->iv_ic->ic_ifp;
2337         struct ath_softc *sc = ifp->if_softc;
2338
2339         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2340         taskqueue_block(sc->sc_tq);
2341 }
2342
2343 static void
2344 ath_key_update_end(struct ieee80211vap *vap)
2345 {
2346         struct ifnet *ifp = vap->iv_ic->ic_ifp;
2347         struct ath_softc *sc = ifp->if_softc;
2348
2349         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
2350         taskqueue_unblock(sc->sc_tq);
2351 }
2352
2353 /*
2354  * Calculate the receive filter according to the
2355  * operating mode and state:
2356  *
2357  * o always accept unicast, broadcast, and multicast traffic
2358  * o accept PHY error frames when hardware doesn't have MIB support
2359  *   to count and we need them for ANI (sta mode only until recently)
2360  *   and we are not scanning (ANI is disabled)
2361  *   NB: older hal's add rx filter bits out of sight and we need to
2362  *       blindly preserve them
2363  * o probe request frames are accepted only when operating in
2364  *   hostap, adhoc, mesh, or monitor modes
2365  * o enable promiscuous mode
2366  *   - when in monitor mode
2367  *   - if interface marked PROMISC (assumes bridge setting is filtered)
2368  * o accept beacons:
2369  *   - when operating in station mode for collecting rssi data when
2370  *     the station is otherwise quiet, or
2371  *   - when operating in adhoc mode so the 802.11 layer creates
2372  *     node table entries for peers,
2373  *   - when scanning
2374  *   - when doing s/w beacon miss (e.g. for ap+sta)
2375  *   - when operating in ap mode in 11g to detect overlapping bss that
2376  *     require protection
2377  *   - when operating in mesh mode to detect neighbors
2378  * o accept control frames:
2379  *   - when in monitor mode
2380  * XXX BAR frames for 11n
2381  * XXX HT protection for 11n
2382  */
2383 static u_int32_t
2384 ath_calcrxfilter(struct ath_softc *sc)
2385 {
2386         struct ifnet *ifp = sc->sc_ifp;
2387         struct ieee80211com *ic = ifp->if_l2com;
2388         u_int32_t rfilt;
2389
2390         rfilt = HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
2391         if (!sc->sc_needmib && !sc->sc_scanning)
2392                 rfilt |= HAL_RX_FILTER_PHYERR;
2393         if (ic->ic_opmode != IEEE80211_M_STA)
2394                 rfilt |= HAL_RX_FILTER_PROBEREQ;
2395         /* XXX ic->ic_monvaps != 0? */
2396         if (ic->ic_opmode == IEEE80211_M_MONITOR || (ifp->if_flags & IFF_PROMISC))
2397                 rfilt |= HAL_RX_FILTER_PROM;
2398         if (ic->ic_opmode == IEEE80211_M_STA ||
2399             ic->ic_opmode == IEEE80211_M_IBSS ||
2400             sc->sc_swbmiss || sc->sc_scanning)
2401                 rfilt |= HAL_RX_FILTER_BEACON;
2402         /*
2403          * NB: We don't recalculate the rx filter when
2404          * ic_protmode changes; otherwise we could do
2405          * this only when ic_protmode != NONE.
2406          */
2407         if (ic->ic_opmode == IEEE80211_M_HOSTAP &&
2408             IEEE80211_IS_CHAN_ANYG(ic->ic_curchan))
2409                 rfilt |= HAL_RX_FILTER_BEACON;
2410         if (sc->sc_nmeshvaps) {
2411                 rfilt |= HAL_RX_FILTER_BEACON;
2412                 if (sc->sc_hasbmatch)
2413                         rfilt |= HAL_RX_FILTER_BSSID;
2414                 else
2415                         rfilt |= HAL_RX_FILTER_PROM;
2416         }
2417         if (ic->ic_opmode == IEEE80211_M_MONITOR)
2418                 rfilt |= HAL_RX_FILTER_CONTROL;
2419         DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, %s if_flags 0x%x\n",
2420             __func__, rfilt, ieee80211_opmode_name[ic->ic_opmode], ifp->if_flags);
2421         return rfilt;
2422 }
2423
2424 static void
2425 ath_update_promisc(struct ifnet *ifp)
2426 {
2427         struct ath_softc *sc = ifp->if_softc;
2428         u_int32_t rfilt;
2429
2430         /* configure rx filter */
2431         rfilt = ath_calcrxfilter(sc);
2432         ath_hal_setrxfilter(sc->sc_ah, rfilt);
2433
2434         DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
2435 }
2436
2437 static void
2438 ath_update_mcast(struct ifnet *ifp)
2439 {
2440         struct ath_softc *sc = ifp->if_softc;
2441         u_int32_t mfilt[2];
2442
2443         /* calculate and install multicast filter */
2444         if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
2445                 struct ifmultiaddr *ifma;
2446                 /*
2447                  * Merge multicast addresses to form the hardware filter.
2448                  */
2449                 mfilt[0] = mfilt[1] = 0;
2450 #ifdef __FreeBSD__
2451                 if_maddr_rlock(ifp);    /* XXX need some fiddling to remove? */
2452 #endif
2453                 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
2454                         caddr_t dl;
2455                         u_int32_t val;
2456                         u_int8_t pos;
2457
2458                         /* calculate XOR of eight 6bit values */
2459                         dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
2460                         val = LE_READ_4(dl + 0);
2461                         pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2462                         val = LE_READ_4(dl + 3);
2463                         pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2464                         pos &= 0x3f;
2465                         mfilt[pos / 32] |= (1 << (pos % 32));
2466                 }
2467 #ifdef __FreeBSD__
2468                 if_maddr_runlock(ifp);
2469 #endif
2470         } else
2471                 mfilt[0] = mfilt[1] = ~0;
2472         ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
2473         DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
2474                 __func__, mfilt[0], mfilt[1]);
2475 }
2476
2477 static void
2478 ath_mode_init(struct ath_softc *sc)
2479 {
2480         struct ifnet *ifp = sc->sc_ifp;
2481         struct ath_hal *ah = sc->sc_ah;
2482         u_int32_t rfilt;
2483
2484         /* configure rx filter */
2485         rfilt = ath_calcrxfilter(sc);
2486         ath_hal_setrxfilter(ah, rfilt);
2487
2488         /* configure operational mode */
2489         ath_hal_setopmode(ah);
2490
2491         /* handle any link-level address change */
2492         ath_hal_setmac(ah, IF_LLADDR(ifp));
2493
2494         /* calculate and install multicast filter */
2495         ath_update_mcast(ifp);
2496 }
2497
2498 /*
2499  * Set the slot time based on the current setting.
2500  */
2501 static void
2502 ath_setslottime(struct ath_softc *sc)
2503 {
2504         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2505         struct ath_hal *ah = sc->sc_ah;
2506         u_int usec;
2507
2508         if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
2509                 usec = 13;
2510         else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
2511                 usec = 21;
2512         else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
2513                 /* honor short/long slot time only in 11g */
2514                 /* XXX shouldn't honor on pure g or turbo g channel */
2515                 if (ic->ic_flags & IEEE80211_F_SHSLOT)
2516                         usec = HAL_SLOT_TIME_9;
2517                 else
2518                         usec = HAL_SLOT_TIME_20;
2519         } else
2520                 usec = HAL_SLOT_TIME_9;
2521
2522         DPRINTF(sc, ATH_DEBUG_RESET,
2523             "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
2524             __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
2525             ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
2526
2527         ath_hal_setslottime(ah, usec);
2528         sc->sc_updateslot = OK;
2529 }
2530
2531 /*
2532  * Callback from the 802.11 layer to update the
2533  * slot time based on the current setting.
2534  */
2535 static void
2536 ath_updateslot(struct ifnet *ifp)
2537 {
2538         struct ath_softc *sc = ifp->if_softc;
2539         struct ieee80211com *ic = ifp->if_l2com;
2540
2541         /*
2542          * When not coordinating the BSS, change the hardware
2543          * immediately.  For other operation we defer the change
2544          * until beacon updates have propagated to the stations.
2545          */
2546         if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2547             ic->ic_opmode == IEEE80211_M_MBSS)
2548                 sc->sc_updateslot = UPDATE;
2549         else
2550                 ath_setslottime(sc);
2551 }
2552
2553 /*
2554  * Setup a h/w transmit queue for beacons.
2555  */
2556 static int
2557 ath_beaconq_setup(struct ath_hal *ah)
2558 {
2559         HAL_TXQ_INFO qi;
2560
2561         memset(&qi, 0, sizeof(qi));
2562         qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
2563         qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
2564         qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
2565         /* NB: for dynamic turbo, don't enable any other interrupts */
2566         qi.tqi_qflags = HAL_TXQ_TXDESCINT_ENABLE;
2567         return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
2568 }
2569
2570 /*
2571  * Setup the transmit queue parameters for the beacon queue.
2572  */
2573 static int
2574 ath_beaconq_config(struct ath_softc *sc)
2575 {
2576 #define ATH_EXPONENT_TO_VALUE(v)        ((1<<(v))-1)
2577         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2578         struct ath_hal *ah = sc->sc_ah;
2579         HAL_TXQ_INFO qi;
2580
2581         ath_hal_gettxqueueprops(ah, sc->sc_bhalq, &qi);
2582         if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2583             ic->ic_opmode == IEEE80211_M_MBSS) {
2584                 /*
2585                  * Always burst out beacon and CAB traffic.
2586                  */
2587                 qi.tqi_aifs = ATH_BEACON_AIFS_DEFAULT;
2588                 qi.tqi_cwmin = ATH_BEACON_CWMIN_DEFAULT;
2589                 qi.tqi_cwmax = ATH_BEACON_CWMAX_DEFAULT;
2590         } else {
2591                 struct wmeParams *wmep =
2592                         &ic->ic_wme.wme_chanParams.cap_wmeParams[WME_AC_BE];
2593                 /*
2594                  * Adhoc mode; important thing is to use 2x cwmin.
2595                  */
2596                 qi.tqi_aifs = wmep->wmep_aifsn;
2597                 qi.tqi_cwmin = 2*ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
2598                 qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
2599         }
2600
2601         if (!ath_hal_settxqueueprops(ah, sc->sc_bhalq, &qi)) {
2602                 device_printf(sc->sc_dev, "unable to update parameters for "
2603                         "beacon hardware queue!\n");
2604                 return 0;
2605         } else {
2606                 ath_hal_resettxqueue(ah, sc->sc_bhalq); /* push to h/w */
2607                 return 1;
2608         }
2609 #undef ATH_EXPONENT_TO_VALUE
2610 }
2611
2612 /*
2613  * Allocate and setup an initial beacon frame.
2614  */
2615 static int
2616 ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
2617 {
2618         struct ieee80211vap *vap = ni->ni_vap;
2619         struct ath_vap *avp = ATH_VAP(vap);
2620         struct ath_buf *bf;
2621         struct mbuf *m;
2622         int error;
2623
2624         bf = avp->av_bcbuf;
2625         if (bf->bf_m != NULL) {
2626                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2627                 m_freem(bf->bf_m);
2628                 bf->bf_m = NULL;
2629         }
2630         if (bf->bf_node != NULL) {
2631                 ieee80211_free_node(bf->bf_node);
2632                 bf->bf_node = NULL;
2633         }
2634
2635         /*
2636          * NB: the beacon data buffer must be 32-bit aligned;
2637          * we assume the mbuf routines will return us something
2638          * with this alignment (perhaps should assert).
2639          */
2640         m = ieee80211_beacon_alloc(ni, &avp->av_boff);
2641         if (m == NULL) {
2642                 device_printf(sc->sc_dev, "%s: cannot get mbuf\n", __func__);
2643                 sc->sc_stats.ast_be_nombuf++;
2644                 return ENOMEM;
2645         }
2646         error = bus_dmamap_load_mbuf_segment(sc->sc_dmat, bf->bf_dmamap, m,
2647                                      bf->bf_segs, 1, &bf->bf_nseg,
2648                                      BUS_DMA_NOWAIT);
2649         if (error != 0) {
2650                 device_printf(sc->sc_dev,
2651                     "%s: cannot map mbuf, bus_dmamap_load_mbuf_segment returns %d\n",
2652                     __func__, error);
2653                 m_freem(m);
2654                 return error;
2655         }
2656
2657         /*
2658          * Calculate a TSF adjustment factor required for staggered
2659          * beacons.  Note that we assume the format of the beacon
2660          * frame leaves the tstamp field immediately following the
2661          * header.
2662          */
2663         if (sc->sc_stagbeacons && avp->av_bslot > 0) {
2664                 uint64_t tsfadjust;
2665                 struct ieee80211_frame *wh;
2666
2667                 /*
2668                  * The beacon interval is in TU's; the TSF is in usecs.
2669                  * We figure out how many TU's to add to align the timestamp
2670                  * then convert to TSF units and handle byte swapping before
2671                  * inserting it in the frame.  The hardware will then add this
2672                  * each time a beacon frame is sent.  Note that we align vap's
2673                  * 1..N and leave vap 0 untouched.  This means vap 0 has a
2674                  * timestamp in one beacon interval while the others get a
2675                  * timstamp aligned to the next interval.
2676                  */
2677                 tsfadjust = ni->ni_intval *
2678                     (ATH_BCBUF - avp->av_bslot) / ATH_BCBUF;
2679                 tsfadjust = htole64(tsfadjust << 10);   /* TU -> TSF */
2680
2681                 DPRINTF(sc, ATH_DEBUG_BEACON,
2682                     "%s: %s beacons bslot %d intval %u tsfadjust %llu\n",
2683                     __func__, sc->sc_stagbeacons ? "stagger" : "burst",
2684                     avp->av_bslot, ni->ni_intval,
2685                     (long long unsigned) le64toh(tsfadjust));
2686
2687                 wh = mtod(m, struct ieee80211_frame *);
2688                 memcpy(&wh[1], &tsfadjust, sizeof(tsfadjust));
2689         }
2690         bf->bf_m = m;
2691         bf->bf_node = ieee80211_ref_node(ni);
2692
2693         return 0;
2694 }
2695
2696 /*
2697  * Setup the beacon frame for transmit.
2698  */
2699 static void
2700 ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
2701 {
2702 #define USE_SHPREAMBLE(_ic) \
2703         (((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
2704                 == IEEE80211_F_SHPREAMBLE)
2705         struct ieee80211_node *ni = bf->bf_node;
2706         struct ieee80211com *ic = ni->ni_ic;
2707         struct mbuf *m = bf->bf_m;
2708         struct ath_hal *ah = sc->sc_ah;
2709         struct ath_desc *ds;
2710         int flags, antenna;
2711         const HAL_RATE_TABLE *rt;
2712         u_int8_t rix, rate;
2713
2714         DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: m %p len %u\n",
2715                 __func__, m, m->m_len);
2716
2717         /* setup descriptors */
2718         ds = bf->bf_desc;
2719
2720         flags = HAL_TXDESC_NOACK;
2721         if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
2722                 ds->ds_link = bf->bf_daddr;     /* self-linked */
2723                 flags |= HAL_TXDESC_VEOL;
2724                 /*
2725                  * Let hardware handle antenna switching.
2726                  */
2727                 antenna = sc->sc_txantenna;
2728         } else {
2729                 ds->ds_link = 0;
2730                 /*
2731                  * Switch antenna every 4 beacons.
2732                  * XXX assumes two antenna
2733                  */
2734                 if (sc->sc_txantenna != 0)
2735                         antenna = sc->sc_txantenna;
2736                 else if (sc->sc_stagbeacons && sc->sc_nbcnvaps != 0)
2737                         antenna = ((sc->sc_stats.ast_be_xmit / sc->sc_nbcnvaps) & 4 ? 2 : 1);
2738                 else
2739                         antenna = (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
2740         }
2741
2742         KASSERT(bf->bf_nseg == 1,
2743                 ("multi-segment beacon frame; nseg %u", bf->bf_nseg));
2744         ds->ds_data = bf->bf_segs[0].ds_addr;
2745         /*
2746          * Calculate rate code.
2747          * XXX everything at min xmit rate
2748          */
2749         rix = 0;
2750         rt = sc->sc_currates;
2751         rate = rt->info[rix].rateCode;
2752         if (USE_SHPREAMBLE(ic))
2753                 rate |= rt->info[rix].shortPreamble;
2754         ath_hal_setuptxdesc(ah, ds
2755                 , m->m_len + IEEE80211_CRC_LEN  /* frame length */
2756                 , sizeof(struct ieee80211_frame)/* header length */
2757                 , HAL_PKT_TYPE_BEACON           /* Atheros packet type */
2758                 , ni->ni_txpower                /* txpower XXX */
2759                 , rate, 1                       /* series 0 rate/tries */
2760                 , HAL_TXKEYIX_INVALID           /* no encryption */
2761                 , antenna                       /* antenna mode */
2762                 , flags                         /* no ack, veol for beacons */
2763                 , 0                             /* rts/cts rate */
2764                 , 0                             /* rts/cts duration */
2765         );
2766         /* NB: beacon's BufLen must be a multiple of 4 bytes */
2767         ath_hal_filltxdesc(ah, ds
2768                 , roundup(m->m_len, 4)          /* buffer length */
2769                 , AH_TRUE                       /* first segment */
2770                 , AH_TRUE                       /* last segment */
2771                 , ds                            /* first descriptor */
2772         );
2773 #if 0
2774         ath_desc_swap(ds);
2775 #endif
2776 #undef USE_SHPREAMBLE
2777 }
2778
2779 static void
2780 ath_beacon_update(struct ieee80211vap *vap, int item)
2781 {
2782         struct ieee80211_beacon_offsets *bo = &ATH_VAP(vap)->av_boff;
2783
2784         setbit(bo->bo_flags, item);
2785 }
2786
2787 /*
2788  * Append the contents of src to dst; both queues
2789  * are assumed to be locked.
2790  */
2791 static void
2792 ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
2793 {
2794         STAILQ_CONCAT(&dst->axq_q, &src->axq_q);
2795         if (src->axq_depth)
2796                 dst->axq_link = src->axq_link;
2797         src->axq_link = NULL;
2798         dst->axq_depth += src->axq_depth;
2799         src->axq_depth = 0;
2800 }
2801
2802 /*
2803  * Transmit a beacon frame at SWBA.  Dynamic updates to the
2804  * frame contents are done as needed and the slot time is
2805  * also adjusted based on current state.
2806  */
2807 static void
2808 ath_beacon_proc(void *arg, int pending)
2809 {
2810         struct ath_softc *sc = arg;
2811         struct ath_hal *ah = sc->sc_ah;
2812         struct ieee80211vap *vap;
2813         struct ath_buf *bf;
2814         int slot, otherant;
2815         uint32_t bfaddr;
2816
2817         DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
2818                 __func__, pending);
2819         /*
2820          * Check if the previous beacon has gone out.  If
2821          * not don't try to post another, skip this period
2822          * and wait for the next.  Missed beacons indicate
2823          * a problem and should not occur.  If we miss too
2824          * many consecutive beacons reset the device.
2825          */
2826         if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
2827                 sc->sc_bmisscount++;
2828                 DPRINTF(sc, ATH_DEBUG_BEACON,
2829                         "%s: missed %u consecutive beacons\n",
2830                         __func__, sc->sc_bmisscount);
2831                 if (sc->sc_bmisscount >= ath_bstuck_threshold)
2832                         taskqueue_enqueue(sc->sc_tq, &sc->sc_bstucktask);
2833                 return;
2834         }
2835         if (sc->sc_bmisscount != 0) {
2836                 DPRINTF(sc, ATH_DEBUG_BEACON,
2837                         "%s: resume beacon xmit after %u misses\n",
2838                         __func__, sc->sc_bmisscount);
2839                 sc->sc_bmisscount = 0;
2840         }
2841
2842         /*
2843          * Stop any current dma before messing with the beacon linkages.
2844          */
2845         if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
2846                 DPRINTF(sc, ATH_DEBUG_ANY,
2847                         "%s: beacon queue %u did not stop?\n",
2848                         __func__, sc->sc_bhalq);
2849         }
2850
2851         if (sc->sc_stagbeacons) {                       /* staggered beacons */
2852                 struct ieee80211com *ic = sc->sc_ifp->if_l2com;
2853                 uint32_t tsftu;
2854
2855                 tsftu = ath_hal_gettsf32(ah) >> 10;
2856                 /* XXX lintval */
2857                 slot = ((tsftu % ic->ic_lintval) * ATH_BCBUF) / ic->ic_lintval;
2858                 vap = sc->sc_bslot[(slot+1) % ATH_BCBUF];
2859                 bfaddr = 0;
2860                 if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2861                         bf = ath_beacon_generate(sc, vap);
2862                         if (bf != NULL)
2863                                 bfaddr = bf->bf_daddr;
2864                 }
2865         } else {                                        /* burst'd beacons */
2866                 uint32_t *bflink = &bfaddr;
2867
2868                 for (slot = 0; slot < ATH_BCBUF; slot++) {
2869                         vap = sc->sc_bslot[slot];
2870                         if (vap != NULL && vap->iv_state >= IEEE80211_S_RUN) {
2871                                 bf = ath_beacon_generate(sc, vap);
2872                                 if (bf != NULL) {
2873                                         *bflink = bf->bf_daddr;
2874                                         bflink = &bf->bf_desc->ds_link;
2875                                 }
2876                         }
2877                 }
2878                 *bflink = 0;                            /* terminate list */
2879         }
2880
2881         /*
2882          * Handle slot time change when a non-ERP station joins/leaves
2883          * an 11g network.  The 802.11 layer notifies us via callback,
2884          * we mark updateslot, then wait one beacon before effecting
2885          * the change.  This gives associated stations at least one
2886          * beacon interval to note the state change.
2887          */
2888         /* XXX locking */
2889         if (sc->sc_updateslot == UPDATE) {
2890                 sc->sc_updateslot = COMMIT;     /* commit next beacon */
2891                 sc->sc_slotupdate = slot;
2892         } else if (sc->sc_updateslot == COMMIT && sc->sc_slotupdate == slot)
2893                 ath_setslottime(sc);            /* commit change to h/w */
2894
2895         /*
2896          * Check recent per-antenna transmit statistics and flip
2897          * the default antenna if noticeably more frames went out
2898          * on the non-default antenna.
2899          * XXX assumes 2 anntenae
2900          */
2901         if (!sc->sc_diversity && (!sc->sc_stagbeacons || slot == 0)) {
2902                 otherant = sc->sc_defant & 1 ? 2 : 1;
2903                 if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
2904                         ath_setdefantenna(sc, otherant);
2905                 sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
2906         }
2907
2908         if (bfaddr != 0) {
2909                 /* NB: cabq traffic should already be queued and primed */
2910                 ath_hal_puttxbuf(ah, sc->sc_bhalq, bfaddr);
2911                 sc->sc_stats.ast_be_xmit++;
2912                 ath_hal_txstart(ah, sc->sc_bhalq);
2913         }
2914         /* else no beacon will be generated */
2915 }
2916
2917 static struct ath_buf *
2918 ath_beacon_generate(struct ath_softc *sc, struct ieee80211vap *vap)
2919 {
2920         struct ath_vap *avp = ATH_VAP(vap);
2921         struct ath_txq *cabq = sc->sc_cabq;
2922         struct ath_buf *bf;
2923         struct mbuf *m;
2924         int nmcastq, error;
2925
2926         KASSERT(vap->iv_state >= IEEE80211_S_RUN,
2927             ("not running, state %d", vap->iv_state));
2928         KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
2929
2930         /*
2931          * Update dynamic beacon contents.  If this returns
2932          * non-zero then we need to remap the memory because
2933          * the beacon frame changed size (probably because
2934          * of the TIM bitmap).
2935          */
2936         bf = avp->av_bcbuf;
2937         m = bf->bf_m;
2938         nmcastq = avp->av_mcastq.axq_depth;
2939         if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, nmcastq)) {
2940                 /* XXX too conservative? */
2941                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2942                 error = bus_dmamap_load_mbuf_segment(sc->sc_dmat, bf->bf_dmamap, m,
2943                                              bf->bf_segs, 1, &bf->bf_nseg,
2944                                              BUS_DMA_NOWAIT);
2945                 if (error != 0) {
2946                         if_printf(vap->iv_ifp,
2947                             "%s: bus_dmamap_load_mbuf_segment failed, error %u\n",
2948                             __func__, error);
2949                         return NULL;
2950                 }
2951         }
2952         if ((avp->av_boff.bo_tim[4] & 1) && cabq->axq_depth) {
2953                 DPRINTF(sc, ATH_DEBUG_BEACON,
2954                     "%s: cabq did not drain, mcastq %u cabq %u\n",
2955                     __func__, nmcastq, cabq->axq_depth);
2956                 sc->sc_stats.ast_cabq_busy++;
2957                 if (sc->sc_nvaps > 1 && sc->sc_stagbeacons) {
2958                         /*
2959                          * CABQ traffic from a previous vap is still pending.
2960                          * We must drain the q before this beacon frame goes
2961                          * out as otherwise this vap's stations will get cab
2962                          * frames from a different vap.
2963                          * XXX could be slow causing us to miss DBA
2964                          */
2965                         ath_tx_draintxq(sc, cabq);
2966                 }
2967         }
2968         ath_beacon_setup(sc, bf);
2969         bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
2970
2971         /*
2972          * Enable the CAB queue before the beacon queue to
2973          * insure cab frames are triggered by this beacon.
2974          */
2975         if (avp->av_boff.bo_tim[4] & 1) {
2976                 struct ath_hal *ah = sc->sc_ah;
2977
2978                 /* NB: only at DTIM */
2979                 if (nmcastq) {
2980                         struct ath_buf *bfm;
2981                         int qbusy;
2982
2983                         /*
2984                          * Move frames from the s/w mcast q to the h/w cab q.
2985                          * XXX MORE_DATA bit
2986                          */
2987                         bfm = STAILQ_FIRST(&avp->av_mcastq.axq_q);
2988                         qbusy = ath_hal_txqenabled(ah, cabq->axq_qnum);
2989                         if (qbusy == 0) {
2990                                 if (cabq->axq_link != NULL) {
2991                                         cpu_sfence();
2992                                         *cabq->axq_link = bfm->bf_daddr;
2993                                         cabq->axq_flags |= ATH_TXQ_PUTPENDING;
2994                                 } else {
2995                                         cpu_sfence();
2996                                         ath_hal_puttxbuf(ah, cabq->axq_qnum,
2997                                                 bfm->bf_daddr);
2998                                 }
2999                         } else {
3000                                 if (cabq->axq_link != NULL) {
3001                                         cpu_sfence();
3002                                         *cabq->axq_link = bfm->bf_daddr;
3003                                 }
3004                                 cabq->axq_flags |= ATH_TXQ_PUTPENDING;
3005                         }
3006                         ath_txqmove(cabq, &avp->av_mcastq);
3007
3008                         sc->sc_stats.ast_cabq_xmit += nmcastq;
3009                 }
3010                 /* NB: gated by beacon so safe to start here */
3011                 ath_hal_txstart(ah, cabq->axq_qnum);
3012         }
3013         return bf;
3014 }
3015
3016 static void
3017 ath_beacon_start_adhoc(struct ath_softc *sc, struct ieee80211vap *vap)
3018 {
3019         struct ath_vap *avp = ATH_VAP(vap);
3020         struct ath_hal *ah = sc->sc_ah;
3021         struct ath_buf *bf;
3022         struct mbuf *m;
3023         int error;
3024
3025         KASSERT(avp->av_bcbuf != NULL, ("no beacon buffer"));
3026
3027         /*
3028          * Update dynamic beacon contents.  If this returns
3029          * non-zero then we need to remap the memory because
3030          * the beacon frame changed size (probably because
3031          * of the TIM bitmap).
3032          */
3033         bf = avp->av_bcbuf;
3034         m = bf->bf_m;
3035         if (ieee80211_beacon_update(bf->bf_node, &avp->av_boff, m, 0)) {
3036                 /* XXX too conservative? */
3037                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3038                 error = bus_dmamap_load_mbuf_segment(sc->sc_dmat, bf->bf_dmamap, m,
3039                                              bf->bf_segs, 1, &bf->bf_nseg,
3040                                              BUS_DMA_NOWAIT);
3041                 if (error != 0) {
3042                         if_printf(vap->iv_ifp,
3043                             "%s: bus_dmamap_load_mbuf_segment failed, error %u\n",
3044                             __func__, error);
3045                         return;
3046                 }
3047         }
3048         ath_beacon_setup(sc, bf);
3049         bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3050
3051         /* NB: caller is known to have already stopped tx dma */
3052         ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
3053         ath_hal_txstart(ah, sc->sc_bhalq);
3054 }
3055
3056 /*
3057  * Reset the hardware after detecting beacons have stopped.
3058  */
3059 static void
3060 ath_bstuck_task(void *arg, int pending)
3061 {
3062         struct ath_softc *sc = arg;
3063         struct ifnet *ifp = sc->sc_ifp;
3064
3065         wlan_serialize_enter();
3066         if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
3067                   sc->sc_bmisscount);
3068         sc->sc_stats.ast_bstuck++;
3069         ath_reset(ifp);
3070         wlan_serialize_exit();
3071 }
3072
3073 /*
3074  * Reclaim beacon resources and return buffer to the pool.
3075  */
3076 static void
3077 ath_beacon_return(struct ath_softc *sc, struct ath_buf *bf)
3078 {
3079
3080         if (bf->bf_m != NULL) {
3081                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3082                 m_freem(bf->bf_m);
3083                 bf->bf_m = NULL;
3084         }
3085         if (bf->bf_node != NULL) {
3086                 ieee80211_free_node(bf->bf_node);
3087                 bf->bf_node = NULL;
3088         }
3089         STAILQ_INSERT_TAIL(&sc->sc_bbuf, bf, bf_list);
3090 }
3091
3092 /*
3093  * Reclaim beacon resources.
3094  */
3095 static void
3096 ath_beacon_free(struct ath_softc *sc)
3097 {
3098         struct ath_buf *bf;
3099
3100         STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
3101                 if (bf->bf_m != NULL) {
3102                         bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3103                         m_freem(bf->bf_m);
3104                         bf->bf_m = NULL;
3105                 }
3106                 if (bf->bf_node != NULL) {
3107                         ieee80211_free_node(bf->bf_node);
3108                         bf->bf_node = NULL;
3109                 }
3110         }
3111 }
3112
3113 /*
3114  * Configure the beacon and sleep timers.
3115  *
3116  * When operating as an AP this resets the TSF and sets
3117  * up the hardware to notify us when we need to issue beacons.
3118  *
3119  * When operating in station mode this sets up the beacon
3120  * timers according to the timestamp of the last received
3121  * beacon and the current TSF, configures PCF and DTIM
3122  * handling, programs the sleep registers so the hardware
3123  * will wakeup in time to receive beacons, and configures
3124  * the beacon miss handling so we'll receive a BMISS
3125  * interrupt when we stop seeing beacons from the AP
3126  * we've associated with.
3127  */
3128 static void
3129 ath_beacon_config(struct ath_softc *sc, struct ieee80211vap *vap)
3130 {
3131 #define TSF_TO_TU(_h,_l) \
3132         ((((u_int32_t)(_h)) << 22) | (((u_int32_t)(_l)) >> 10))
3133 #define FUDGE   2
3134         struct ath_hal *ah = sc->sc_ah;
3135         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3136         struct ieee80211_node *ni;
3137         u_int32_t nexttbtt, intval, tsftu;
3138         u_int64_t tsf;
3139
3140         if (vap == NULL)
3141                 vap = TAILQ_FIRST(&ic->ic_vaps);        /* XXX */
3142         ni = vap->iv_bss;
3143
3144         /* extract tstamp from last beacon and convert to TU */
3145         nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
3146                              LE_READ_4(ni->ni_tstamp.data));
3147         if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3148             ic->ic_opmode == IEEE80211_M_MBSS) {
3149                 /*
3150                  * For multi-bss ap/mesh support beacons are either staggered
3151                  * evenly over N slots or burst together.  For the former
3152                  * arrange for the SWBA to be delivered for each slot.
3153                  * Slots that are not occupied will generate nothing.
3154                  */
3155                 /* NB: the beacon interval is kept internally in TU's */
3156                 intval = ni->ni_intval & HAL_BEACON_PERIOD;
3157                 if (sc->sc_stagbeacons)
3158                         intval /= ATH_BCBUF;
3159         } else {
3160                 /* NB: the beacon interval is kept internally in TU's */
3161                 intval = ni->ni_intval & HAL_BEACON_PERIOD;
3162         }
3163         if (nexttbtt == 0)              /* e.g. for ap mode */
3164                 nexttbtt = intval;
3165         else if (intval)                /* NB: can be 0 for monitor mode */
3166                 nexttbtt = roundup(nexttbtt, intval);
3167         DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
3168                 __func__, nexttbtt, intval, ni->ni_intval);
3169         if (ic->ic_opmode == IEEE80211_M_STA && !sc->sc_swbmiss) {
3170                 HAL_BEACON_STATE bs;
3171                 int dtimperiod, dtimcount;
3172                 int cfpperiod, cfpcount;
3173
3174                 /*
3175                  * Setup dtim and cfp parameters according to
3176                  * last beacon we received (which may be none).
3177                  */
3178                 dtimperiod = ni->ni_dtim_period;
3179                 if (dtimperiod <= 0)            /* NB: 0 if not known */
3180                         dtimperiod = 1;
3181                 dtimcount = ni->ni_dtim_count;
3182                 if (dtimcount >= dtimperiod)    /* NB: sanity check */
3183                         dtimcount = 0;          /* XXX? */
3184                 cfpperiod = 1;                  /* NB: no PCF support yet */
3185                 cfpcount = 0;
3186                 /*
3187                  * Pull nexttbtt forward to reflect the current
3188                  * TSF and calculate dtim+cfp state for the result.
3189                  */
3190                 tsf = ath_hal_gettsf64(ah);
3191                 tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3192                 do {
3193                         nexttbtt += intval;
3194                         if (--dtimcount < 0) {
3195                                 dtimcount = dtimperiod - 1;
3196                                 if (--cfpcount < 0)
3197                                         cfpcount = cfpperiod - 1;
3198                         }
3199                 } while (nexttbtt < tsftu);
3200                 memset(&bs, 0, sizeof(bs));
3201                 bs.bs_intval = intval;
3202                 bs.bs_nexttbtt = nexttbtt;
3203                 bs.bs_dtimperiod = dtimperiod*intval;
3204                 bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
3205                 bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
3206                 bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
3207                 bs.bs_cfpmaxduration = 0;
3208 #if 0
3209                 /*
3210                  * The 802.11 layer records the offset to the DTIM
3211                  * bitmap while receiving beacons; use it here to
3212                  * enable h/w detection of our AID being marked in
3213                  * the bitmap vector (to indicate frames for us are
3214                  * pending at the AP).
3215                  * XXX do DTIM handling in s/w to WAR old h/w bugs
3216                  * XXX enable based on h/w rev for newer chips
3217                  */
3218                 bs.bs_timoffset = ni->ni_timoff;
3219 #endif
3220                 /*
3221                  * Calculate the number of consecutive beacons to miss
3222                  * before taking a BMISS interrupt.
3223                  * Note that we clamp the result to at most 10 beacons.
3224                  */
3225                 bs.bs_bmissthreshold = vap->iv_bmissthreshold;
3226                 if (bs.bs_bmissthreshold > 10)
3227                         bs.bs_bmissthreshold = 10;
3228                 else if (bs.bs_bmissthreshold <= 0)
3229                         bs.bs_bmissthreshold = 1;
3230
3231                 /*
3232                  * Calculate sleep duration.  The configuration is
3233                  * given in ms.  We insure a multiple of the beacon
3234                  * period is used.  Also, if the sleep duration is
3235                  * greater than the DTIM period then it makes senses
3236                  * to make it a multiple of that.
3237                  *
3238                  * XXX fixed at 100ms
3239                  */
3240                 bs.bs_sleepduration =
3241                         roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
3242                 if (bs.bs_sleepduration > bs.bs_dtimperiod)
3243                         bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
3244
3245                 DPRINTF(sc, ATH_DEBUG_BEACON,
3246                         "%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"
3247                         , __func__
3248                         , tsf, tsftu
3249                         , bs.bs_intval
3250                         , bs.bs_nexttbtt
3251                         , bs.bs_dtimperiod
3252                         , bs.bs_nextdtim
3253                         , bs.bs_bmissthreshold
3254                         , bs.bs_sleepduration
3255                         , bs.bs_cfpperiod
3256                         , bs.bs_cfpmaxduration
3257                         , bs.bs_cfpnext
3258                         , bs.bs_timoffset
3259                 );
3260                 ath_hal_intrset(ah, 0);
3261                 ath_hal_beacontimers(ah, &bs);
3262                 sc->sc_imask |= HAL_INT_BMISS;
3263                 ath_hal_intrset(ah, sc->sc_imask);
3264         } else {
3265                 ath_hal_intrset(ah, 0);
3266                 if (nexttbtt == intval)
3267                         intval |= HAL_BEACON_RESET_TSF;
3268                 if (ic->ic_opmode == IEEE80211_M_IBSS) {
3269                         /*
3270                          * In IBSS mode enable the beacon timers but only
3271                          * enable SWBA interrupts if we need to manually
3272                          * prepare beacon frames.  Otherwise we use a
3273                          * self-linked tx descriptor and let the hardware
3274                          * deal with things.
3275                          */
3276                         intval |= HAL_BEACON_ENA;
3277                         if (!sc->sc_hasveol)
3278                                 sc->sc_imask |= HAL_INT_SWBA;
3279                         if ((intval & HAL_BEACON_RESET_TSF) == 0) {
3280                                 /*
3281                                  * Pull nexttbtt forward to reflect
3282                                  * the current TSF.
3283                                  */
3284                                 tsf = ath_hal_gettsf64(ah);
3285                                 tsftu = TSF_TO_TU(tsf>>32, tsf) + FUDGE;
3286                                 do {
3287                                         nexttbtt += intval;
3288                                 } while (nexttbtt < tsftu);
3289                         }
3290                         ath_beaconq_config(sc);
3291                 } else if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3292                     ic->ic_opmode == IEEE80211_M_MBSS) {
3293                         /*
3294                          * In AP/mesh mode we enable the beacon timers
3295                          * and SWBA interrupts to prepare beacon frames.
3296                          */
3297                         intval |= HAL_BEACON_ENA;
3298                         sc->sc_imask |= HAL_INT_SWBA;   /* beacon prepare */
3299                         ath_beaconq_config(sc);
3300                 }
3301                 ath_hal_beaconinit(ah, nexttbtt, intval);
3302                 sc->sc_bmisscount = 0;
3303                 ath_hal_intrset(ah, sc->sc_imask);
3304                 /*
3305                  * When using a self-linked beacon descriptor in
3306                  * ibss mode load it once here.
3307                  */
3308                 if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
3309                         ath_beacon_start_adhoc(sc, vap);
3310         }
3311         sc->sc_syncbeacon = 0;
3312 #undef FUDGE
3313 #undef TSF_TO_TU
3314 }
3315
3316 static void
3317 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3318 {
3319         bus_addr_t *paddr = (bus_addr_t*) arg;
3320         KASSERT(error == 0, ("error %u on bus_dma callback", error));
3321         *paddr = segs->ds_addr;
3322 }
3323
3324 static int
3325 ath_descdma_setup(struct ath_softc *sc,
3326         struct ath_descdma *dd, ath_bufhead *head,
3327         const char *name, int nbuf, int ndesc)
3328 {
3329 #define DS2PHYS(_dd, _ds) \
3330         ((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3331         struct ifnet *ifp = sc->sc_ifp;
3332         struct ath_desc *ds;
3333         struct ath_buf *bf;
3334         int i, bsize, error;
3335
3336         DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
3337             __func__, name, nbuf, ndesc);
3338
3339         dd->dd_name = name;
3340         dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
3341
3342         /*
3343          * Setup DMA descriptor area.
3344          */
3345         error = bus_dma_tag_create(dd->dd_dmat, /* parent */
3346                        PAGE_SIZE, 0,            /* alignment, bounds */
3347                        BUS_SPACE_MAXADDR_32BIT, /* lowaddr */
3348                        BUS_SPACE_MAXADDR,       /* highaddr */
3349                        NULL, NULL,              /* filter, filterarg */
3350                        dd->dd_desc_len,         /* maxsize */
3351                        1,                       /* nsegments */
3352                        dd->dd_desc_len,         /* maxsegsize */
3353                        BUS_DMA_ALLOCNOW,        /* flags */
3354                        &dd->dd_dmat);
3355         if (error != 0) {
3356                 if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
3357                 return error;
3358         }
3359
3360         /* allocate descriptors */
3361         error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
3362         if (error != 0) {
3363                 if_printf(ifp, "unable to create dmamap for %s descriptors, "
3364                         "error %u\n", dd->dd_name, error);
3365                 goto fail0;
3366         }
3367
3368         error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
3369                                  BUS_DMA_NOWAIT | BUS_DMA_COHERENT, 
3370                                  &dd->dd_dmamap);
3371         if (error != 0) {
3372                 if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
3373                         "error %u\n", nbuf * ndesc, dd->dd_name, error);
3374                 goto fail1;
3375         }
3376
3377         error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
3378                                 dd->dd_desc, dd->dd_desc_len,
3379                                 ath_load_cb, &dd->dd_desc_paddr,
3380                                 BUS_DMA_NOWAIT);
3381         if (error != 0) {
3382                 if_printf(ifp, "unable to map %s descriptors, error %u\n",
3383                         dd->dd_name, error);
3384                 goto fail2;
3385         }
3386
3387         ds = dd->dd_desc;
3388         DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
3389             __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
3390             (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
3391
3392         /* allocate rx buffers */
3393         bsize = sizeof(struct ath_buf) * nbuf;
3394         bf = kmalloc(bsize, M_ATHDEV, M_INTWAIT | M_ZERO);
3395         if (bf == NULL) {
3396                 if_printf(ifp, "malloc of %s buffers failed, size %u\n",
3397                         dd->dd_name, bsize);
3398                 goto fail3;
3399         }
3400         dd->dd_bufptr = bf;
3401
3402         STAILQ_INIT(head);
3403         for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
3404                 bf->bf_desc = ds;
3405                 bf->bf_daddr = DS2PHYS(dd, ds);
3406                 error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3407                                 &bf->bf_dmamap);
3408                 if (error != 0) {
3409                         if_printf(ifp, "unable to create dmamap for %s "
3410                                 "buffer %u, error %u\n", dd->dd_name, i, error);
3411                         ath_descdma_cleanup(sc, dd, head);
3412                         return error;
3413                 }
3414                 STAILQ_INSERT_TAIL(head, bf, bf_list);
3415         }
3416         return 0;
3417 fail3:
3418         bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3419 fail2:
3420         bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3421 fail1:
3422         bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3423 fail0:
3424         bus_dma_tag_destroy(dd->dd_dmat);
3425         memset(dd, 0, sizeof(*dd));
3426         return error;
3427 #undef DS2PHYS
3428 }
3429
3430 static void
3431 ath_descdma_cleanup(struct ath_softc *sc,
3432         struct ath_descdma *dd, ath_bufhead *head)
3433 {
3434         struct ath_buf *bf;
3435         struct ieee80211_node *ni;
3436
3437         bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
3438         bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3439         bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
3440         bus_dma_tag_destroy(dd->dd_dmat);
3441
3442         STAILQ_FOREACH(bf, head, bf_list) {
3443                 if (bf->bf_m) {
3444                         m_freem(bf->bf_m);
3445                         bf->bf_m = NULL;
3446                 }
3447                 if (bf->bf_dmamap != NULL) {
3448                         bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
3449                         bf->bf_dmamap = NULL;
3450                 }
3451                 ni = bf->bf_node;
3452                 bf->bf_node = NULL;
3453                 if (ni != NULL) {
3454                         /*
3455                          * Reclaim node reference.
3456                          */
3457                         ieee80211_free_node(ni);
3458                 }
3459         }
3460
3461         STAILQ_INIT(head);
3462         kfree(dd->dd_bufptr, M_ATHDEV);
3463         memset(dd, 0, sizeof(*dd));
3464 }
3465
3466 static int
3467 ath_desc_alloc(struct ath_softc *sc)
3468 {
3469         int error;
3470
3471         error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
3472                         "rx", ath_rxbuf, 1);
3473         if (error != 0)
3474                 return error;
3475
3476         error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
3477                         "tx", ath_txbuf, ATH_TXDESC);
3478         if (error != 0) {
3479                 ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3480                 return error;
3481         }
3482
3483         error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
3484                         "beacon", ATH_BCBUF, 1);
3485         if (error != 0) {
3486                 ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3487                 ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3488                 return error;
3489         }
3490         return 0;
3491 }
3492
3493 static void
3494 ath_desc_free(struct ath_softc *sc)
3495 {
3496
3497         if (sc->sc_bdma.dd_desc_len != 0)
3498                 ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
3499         if (sc->sc_txdma.dd_desc_len != 0)
3500                 ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
3501         if (sc->sc_rxdma.dd_desc_len != 0)
3502                 ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
3503 }
3504
3505 static struct ieee80211_node *
3506 ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
3507 {
3508         struct ieee80211com *ic = vap->iv_ic;
3509         struct ath_softc *sc = ic->ic_ifp->if_softc;
3510         const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
3511         struct ath_node *an;
3512
3513         an = kmalloc(space, M_80211_NODE, M_INTWAIT|M_ZERO);
3514         if (an == NULL) {
3515                 /* XXX stat+msg */
3516                 return NULL;
3517         }
3518         ath_rate_node_init(sc, an);
3519
3520         DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
3521         return &an->an_node;
3522 }
3523
3524 static void
3525 ath_node_free(struct ieee80211_node *ni)
3526 {
3527         struct ieee80211com *ic = ni->ni_ic;
3528         struct ath_softc *sc = ic->ic_ifp->if_softc;
3529
3530         DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
3531
3532         ath_rate_node_cleanup(sc, ATH_NODE(ni));
3533         sc->sc_node_free(ni);
3534 }
3535
3536 static void
3537 ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
3538 {
3539         struct ieee80211com *ic = ni->ni_ic;
3540         struct ath_softc *sc = ic->ic_ifp->if_softc;
3541         struct ath_hal *ah = sc->sc_ah;
3542
3543         *rssi = ic->ic_node_getrssi(ni);
3544         if (ni->ni_chan != IEEE80211_CHAN_ANYC)
3545                 *noise = ath_hal_getchannoise(ah, ni->ni_chan);
3546         else
3547                 *noise = -95;           /* nominally correct */
3548 }
3549
3550 static int
3551 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
3552 {
3553         struct ath_hal *ah = sc->sc_ah;
3554         int error;
3555         struct mbuf *m;
3556         struct ath_desc *ds;
3557
3558         m = bf->bf_m;
3559         if (m == NULL) {
3560                 /*
3561                  * NB: by assigning a page to the rx dma buffer we
3562                  * implicitly satisfy the Atheros requirement that
3563                  * this buffer be cache-line-aligned and sized to be
3564                  * multiple of the cache line size.  Not doing this
3565                  * causes weird stuff to happen (for the 5210 at least).
3566                  */
3567                 m = m_getcl(MB_WAIT, MT_DATA, M_PKTHDR);
3568                 if (m == NULL) {
3569                         kprintf("ath_rxbuf_init: no mbuf\n");
3570                         DPRINTF(sc, ATH_DEBUG_ANY,
3571                                 "%s: no mbuf/cluster\n", __func__);
3572                         sc->sc_stats.ast_rx_nombuf++;
3573                         return ENOMEM;
3574                 }
3575                 m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
3576
3577                 error = bus_dmamap_load_mbuf_segment(sc->sc_dmat,
3578                                              bf->bf_dmamap, m,
3579                                              bf->bf_segs, 1, &bf->bf_nseg,
3580                                              BUS_DMA_NOWAIT);
3581                 if (error != 0) {
3582                         DPRINTF(sc, ATH_DEBUG_ANY,
3583                             "%s: bus_dmamap_load_mbuf_segment failed; error %d\n",
3584                             __func__, error);
3585                         sc->sc_stats.ast_rx_busdma++;
3586                         m_freem(m);
3587                         return error;
3588                 }
3589                 KASSERT(bf->bf_nseg == 1,
3590                         ("multi-segment packet; nseg %u", bf->bf_nseg));
3591                 bf->bf_m = m;
3592         }
3593         bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
3594
3595         /*
3596          * Setup descriptors.  For receive we always terminate
3597          * the descriptor list with a self-linked entry so we'll
3598          * not get overrun under high load (as can happen with a
3599          * 5212 when ANI processing enables PHY error frames).
3600          *
3601          * To insure the last descriptor is self-linked we create
3602          * each descriptor as self-linked and add it to the end.  As
3603          * each additional descriptor is added the previous self-linked
3604          * entry is ``fixed'' naturally.  This should be safe even
3605          * if DMA is happening.  When processing RX interrupts we
3606          * never remove/process the last, self-linked, entry on the
3607          * descriptor list.  This insures the hardware always has
3608          * someplace to write a new frame.
3609          */
3610         ds = bf->bf_desc;
3611         ds->ds_link = bf->bf_daddr;     /* link to self */
3612         ds->ds_data = bf->bf_segs[0].ds_addr;
3613         ath_hal_setuprxdesc(ah, ds
3614                 , m->m_len              /* buffer size */
3615                 , 0
3616         );
3617
3618         if (sc->sc_rxlink != NULL)
3619                 *sc->sc_rxlink = bf->bf_daddr;
3620         sc->sc_rxlink = &ds->ds_link;
3621         return 0;
3622 }
3623
3624 /*
3625  * Extend 15-bit time stamp from rx descriptor to
3626  * a full 64-bit TSF using the specified TSF.
3627  */
3628 static __inline u_int64_t
3629 ath_extend_tsf(u_int32_t rstamp, u_int64_t tsf)
3630 {
3631         if ((tsf & 0x7fff) < rstamp)
3632                 tsf -= 0x8000;
3633         return ((tsf &~ 0x7fff) | rstamp);
3634 }
3635
3636 /*
3637  * Intercept management frames to collect beacon rssi data
3638  * and to do ibss merges.
3639  */
3640 static void
3641 ath_recv_mgmt(struct ieee80211_node *ni, struct mbuf *m,
3642         int subtype, int rssi, int nf)
3643 {
3644         struct ieee80211vap *vap = ni->ni_vap;
3645         struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
3646
3647         /*
3648          * Call up first so subsequent work can use information
3649          * potentially stored in the node (e.g. for ibss merge).
3650          */
3651         ATH_VAP(vap)->av_recv_mgmt(ni, m, subtype, rssi, nf);
3652         switch (subtype) {
3653         case IEEE80211_FC0_SUBTYPE_BEACON:
3654                 /* update rssi statistics for use by the hal */
3655                 ATH_RSSI_LPF(sc->sc_halstats.ns_avgbrssi, rssi);
3656                 if (sc->sc_syncbeacon &&
3657                     ni == vap->iv_bss && vap->iv_state == IEEE80211_S_RUN) {
3658                         /*
3659                          * Resync beacon timers using the tsf of the beacon
3660                          * frame we just received.
3661                          */
3662                         ath_beacon_config(sc, vap);
3663                 }
3664                 /* fall thru... */
3665         case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
3666                 if (vap->iv_opmode == IEEE80211_M_IBSS &&
3667                     vap->iv_state == IEEE80211_S_RUN) {
3668                         uint32_t rstamp = sc->sc_lastrs->rs_tstamp;
3669                         u_int64_t tsf = ath_extend_tsf(rstamp,
3670                                 ath_hal_gettsf64(sc->sc_ah));
3671                         /*
3672                          * Handle ibss merge as needed; check the tsf on the
3673                          * frame before attempting the merge.  The 802.11 spec
3674                          * says the station should change it's bssid to match
3675                          * the oldest station with the same ssid, where oldest
3676                          * is determined by the tsf.  Note that hardware
3677                          * reconfiguration happens through callback to
3678                          * ath_newstate as the state machine will go from
3679                          * RUN -> RUN when this happens.
3680                          */
3681                         if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
3682                                 DPRINTF(sc, ATH_DEBUG_STATE,
3683                                     "ibss merge, rstamp %u tsf %ju "
3684                                     "tstamp %ju\n", rstamp, (uintmax_t)tsf,
3685                                     (uintmax_t)ni->ni_tstamp.tsf);
3686                                 (void) ieee80211_ibss_merge(ni);
3687                         }
3688                 }
3689                 break;
3690         }
3691 }
3692
3693 /*
3694  * Set the default antenna.
3695  */
3696 static void
3697 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
3698 {
3699         struct ath_hal *ah = sc->sc_ah;
3700
3701         /* XXX block beacon interrupts */
3702         ath_hal_setdefantenna(ah, antenna);
3703         if (sc->sc_defant != antenna)
3704                 sc->sc_stats.ast_ant_defswitch++;
3705         sc->sc_defant = antenna;
3706         sc->sc_rxotherant = 0;
3707 }
3708
3709 static void
3710 ath_rx_tap(struct ifnet *ifp, struct mbuf *m,
3711         const struct ath_rx_status *rs, u_int64_t tsf, int16_t nf)
3712 {
3713 #define CHAN_HT20       htole32(IEEE80211_CHAN_HT20)
3714 #define CHAN_HT40U      htole32(IEEE80211_CHAN_HT40U)
3715 #define CHAN_HT40D      htole32(IEEE80211_CHAN_HT40D)
3716 #define CHAN_HT         (CHAN_HT20|CHAN_HT40U|CHAN_HT40D)
3717         struct ath_softc *sc = ifp->if_softc;
3718         const HAL_RATE_TABLE *rt;
3719         uint8_t rix;
3720
3721         rt = sc->sc_currates;
3722         KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
3723         rix = rt->rateCodeToIndex[rs->rs_rate];
3724         sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
3725         sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
3726 #ifdef AH_SUPPORT_AR5416
3727         sc->sc_rx_th.wr_chan_flags &= ~CHAN_HT;
3728         if (sc->sc_rx_th.wr_rate & IEEE80211_RATE_MCS) {        /* HT rate */
3729                 struct ieee80211com *ic = ifp->if_l2com;
3730
3731                 if ((rs->rs_flags & HAL_RX_2040) == 0)
3732                         sc->sc_rx_th.wr_chan_flags |= CHAN_HT20;
3733                 else if (IEEE80211_IS_CHAN_HT40U(ic->ic_curchan))
3734                         sc->sc_rx_th.wr_chan_flags |= CHAN_HT40U;
3735                 else
3736                         sc->sc_rx_th.wr_chan_flags |= CHAN_HT40D;
3737                 if ((rs->rs_flags & HAL_RX_GI) == 0)
3738                         sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_SHORTGI;
3739         }
3740 #endif
3741         sc->sc_rx_th.wr_tsf = htole64(ath_extend_tsf(rs->rs_tstamp, tsf));
3742         if (rs->rs_status & HAL_RXERR_CRC)
3743                 sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
3744         /* XXX propagate other error flags from descriptor */
3745         sc->sc_rx_th.wr_antnoise = nf;
3746         sc->sc_rx_th.wr_antsignal = nf + rs->rs_rssi;
3747         sc->sc_rx_th.wr_antenna = rs->rs_antenna;
3748 #undef CHAN_HT
3749 #undef CHAN_HT20
3750 #undef CHAN_HT40U
3751 #undef CHAN_HT40D
3752 }
3753
3754 static void
3755 ath_handle_micerror(struct ieee80211com *ic,
3756         struct ieee80211_frame *wh, int keyix)
3757 {
3758         struct ieee80211_node *ni;
3759
3760         /* XXX recheck MIC to deal w/ chips that lie */
3761         /* XXX discard MIC errors on !data frames */
3762         ni = ieee80211_find_rxnode(ic, (const struct ieee80211_frame_min *) wh);
3763         if (ni != NULL) {
3764                 ieee80211_notify_michael_failure(ni->ni_vap, wh, keyix);
3765                 ieee80211_free_node(ni);
3766         }
3767 }
3768
3769 static void
3770 ath_rx_task(void *arg, int npending)
3771 {
3772 #define PA2DESC(_sc, _pa) \
3773         ((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
3774                 ((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
3775         struct ath_softc *sc = arg;
3776         struct ath_buf *bf;
3777         struct ifnet *ifp;
3778         struct ieee80211com *ic;
3779         struct ath_hal *ah;
3780         struct ath_desc *ds;
3781         struct ath_rx_status *rs;
3782         struct mbuf *m;
3783         struct ieee80211_node *ni;
3784         int len, type, ngood;
3785         u_int phyerr;
3786         HAL_STATUS status;
3787         int16_t nf;
3788         u_int64_t tsf;
3789
3790         wlan_serialize_enter();
3791         ifp = sc->sc_ifp;
3792         ic = ifp->if_l2com;
3793         ah = sc->sc_ah;
3794
3795         DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
3796         ngood = 0;
3797         nf = ath_hal_getchannoise(ah, sc->sc_curchan);
3798         sc->sc_stats.ast_rx_noise = nf;
3799         tsf = ath_hal_gettsf64(ah);
3800         do {
3801                 bf = STAILQ_FIRST(&sc->sc_rxbuf);
3802                 if (bf == NULL) {               /* NB: shouldn't happen */
3803                         if_printf(ifp, "%s: no buffer!\n", __func__);
3804                         break;
3805                 }
3806                 m = bf->bf_m;
3807                 if (m == NULL) {                /* NB: shouldn't happen */
3808                         /*
3809                          * If mbuf allocation failed previously there
3810                          * will be no mbuf; try again to re-populate it.
3811                          */ 
3812                         /* XXX make debug msg */
3813                         if_printf(ifp, "%s: no mbuf!\n", __func__);
3814                         STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
3815                         goto rx_next;
3816                 }
3817                 ds = bf->bf_desc;
3818                 if (ds->ds_link == bf->bf_daddr) {
3819                         /* NB: never process the self-linked entry at the end */
3820                         break;
3821                 }
3822                 /* XXX sync descriptor memory */
3823                 /*
3824                  * Must provide the virtual address of the current
3825                  * descriptor, the physical address, and the virtual
3826                  * address of the next descriptor in the h/w chain.
3827                  * This allows the HAL to look ahead to see if the
3828                  * hardware is done with a descriptor by checking the
3829                  * done bit in the following descriptor and the address
3830                  * of the current descriptor the DMA engine is working
3831                  * on.  All this is necessary because of our use of
3832                  * a self-linked list to avoid rx overruns.
3833                  */
3834                 rs = &bf->bf_status.ds_rxstat;
3835                 status = ath_hal_rxprocdesc(ah, ds,
3836                                 bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
3837 #ifdef ATH_DEBUG
3838                 if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
3839                         ath_printrxbuf(sc, bf, 0, status == HAL_OK);
3840 #endif
3841                 if (status == HAL_EINPROGRESS)
3842                         break;
3843                 STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
3844                 if (rs->rs_status != 0) {
3845                         if (rs->rs_status & HAL_RXERR_CRC)
3846                                 sc->sc_stats.ast_rx_crcerr++;
3847                         if (rs->rs_status & HAL_RXERR_FIFO)
3848                                 sc->sc_stats.ast_rx_fifoerr++;
3849                         if (rs->rs_status & HAL_RXERR_PHY) {
3850                                 sc->sc_stats.ast_rx_phyerr++;
3851                                 phyerr = rs->rs_phyerr & 0x1f;
3852                                 sc->sc_stats.ast_rx_phy[phyerr]++;
3853                                 goto rx_error;  /* NB: don't count in ierrors */
3854                         }
3855                         if (rs->rs_status & HAL_RXERR_DECRYPT) {
3856                                 /*
3857                                  * Decrypt error.  If the error occurred
3858                                  * because there was no hardware key, then
3859                                  * let the frame through so the upper layers
3860                                  * can process it.  This is necessary for 5210
3861                                  * parts which have no way to setup a ``clear''
3862                                  * key cache entry.
3863                                  *
3864                                  * XXX do key cache faulting
3865                                  */
3866                                 if (rs->rs_keyix == HAL_RXKEYIX_INVALID)
3867                                         goto rx_accept;
3868                                 sc->sc_stats.ast_rx_badcrypt++;
3869                         }
3870                         if (rs->rs_status & HAL_RXERR_MIC) {
3871                                 sc->sc_stats.ast_rx_badmic++;
3872                                 /*
3873                                  * Do minimal work required to hand off
3874                                  * the 802.11 header for notification.
3875                                  */
3876                                 /* XXX frag's and qos frames */
3877                                 len = rs->rs_datalen;
3878                                 if (len >= sizeof (struct ieee80211_frame)) {
3879                                         bus_dmamap_sync(sc->sc_dmat,
3880                                             bf->bf_dmamap,
3881                                             BUS_DMASYNC_POSTREAD);
3882                                         ath_handle_micerror(ic, 
3883                                             mtod(m, struct ieee80211_frame *),
3884                                             sc->sc_splitmic ?
3885                                                 rs->rs_keyix-32 : rs->rs_keyix);
3886                                 }
3887                         }
3888                         ifp->if_ierrors++;
3889 rx_error:
3890                         /*
3891                          * Cleanup any pending partial frame.
3892                          */
3893                         if (sc->sc_rxpending != NULL) {
3894                                 m_freem(sc->sc_rxpending);
3895                                 sc->sc_rxpending = NULL;
3896                         }
3897                         /*
3898                          * When a tap is present pass error frames
3899                          * that have been requested.  By default we
3900                          * pass decrypt+mic errors but others may be
3901                          * interesting (e.g. crc).
3902                          */
3903                         if (ieee80211_radiotap_active(ic) &&
3904                             (rs->rs_status & sc->sc_monpass)) {
3905                                 bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3906                                     BUS_DMASYNC_POSTREAD);
3907                                 /* NB: bpf needs the mbuf length setup */
3908                                 len = rs->rs_datalen;
3909                                 m->m_pkthdr.len = m->m_len = len;
3910                                 ath_rx_tap(ifp, m, rs, tsf, nf);
3911                                 ieee80211_radiotap_rx_all(ic, m);
3912                         }
3913                         /* XXX pass MIC errors up for s/w reclaculation */
3914                         goto rx_next;
3915                 }
3916 rx_accept:
3917                 /*
3918                  * Sync and unmap the frame.  At this point we're
3919                  * committed to passing the mbuf somewhere so clear
3920                  * bf_m; this means a new mbuf must be allocated
3921                  * when the rx descriptor is setup again to receive
3922                  * another frame.
3923                  */
3924                 bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3925                     BUS_DMASYNC_POSTREAD);
3926                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3927                 bf->bf_m = NULL;
3928
3929                 len = rs->rs_datalen;
3930                 m->m_len = len;
3931
3932                 if (rs->rs_more) {
3933                         /*
3934                          * Frame spans multiple descriptors; save
3935                          * it for the next completed descriptor, it
3936                          * will be used to construct a jumbogram.
3937                          */
3938                         if (sc->sc_rxpending != NULL) {
3939                                 /* NB: max frame size is currently 2 clusters */
3940                                 sc->sc_stats.ast_rx_toobig++;
3941                                 m_freem(sc->sc_rxpending);
3942                         }
3943                         m->m_pkthdr.rcvif = ifp;
3944                         m->m_pkthdr.len = len;
3945                         sc->sc_rxpending = m;
3946                         goto rx_next;
3947                 } else if (sc->sc_rxpending != NULL) {
3948                         /*
3949                          * This is the second part of a jumbogram,
3950                          * chain it to the first mbuf, adjust the
3951                          * frame length, and clear the rxpending state.
3952                          */
3953                         sc->sc_rxpending->m_next = m;
3954                         sc->sc_rxpending->m_pkthdr.len += len;
3955                         m = sc->sc_rxpending;
3956                         sc->sc_rxpending = NULL;
3957                 } else {
3958                         /*
3959                          * Normal single-descriptor receive; setup
3960                          * the rcvif and packet length.
3961                          */
3962                         m->m_pkthdr.rcvif = ifp;
3963                         m->m_pkthdr.len = len;
3964                 }
3965
3966                 ifp->if_ipackets++;
3967                 sc->sc_stats.ast_ant_rx[rs->rs_antenna]++;
3968
3969                 /*
3970                  * Populate the rx status block.  When there are bpf
3971                  * listeners we do the additional work to provide
3972                  * complete status.  Otherwise we fill in only the
3973                  * material required by ieee80211_input.  Note that
3974                  * noise setting is filled in above.
3975                  */
3976                 if (ieee80211_radiotap_active(ic))
3977                         ath_rx_tap(ifp, m, rs, tsf, nf);
3978
3979                 /*
3980                  * From this point on we assume the frame is at least
3981                  * as large as ieee80211_frame_min; verify that.
3982                  */
3983                 if (len < IEEE80211_MIN_LEN) {
3984                         if (!ieee80211_radiotap_active(ic)) {
3985                                 DPRINTF(sc, ATH_DEBUG_RECV,
3986                                     "%s: short packet %d\n", __func__, len);
3987                                 sc->sc_stats.ast_rx_tooshort++;
3988                         } else {
3989                                 /* NB: in particular this captures ack's */
3990                                 ieee80211_radiotap_rx_all(ic, m);
3991                         }
3992                         m_freem(m);
3993                         goto rx_next;
3994                 }
3995
3996                 if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
3997                         const HAL_RATE_TABLE *rt = sc->sc_currates;
3998                         uint8_t rix = rt->rateCodeToIndex[rs->rs_rate];
3999
4000                         ieee80211_dump_pkt(ic, mtod(m, caddr_t), len,
4001                             sc->sc_hwmap[rix].ieeerate, rs->rs_rssi);
4002                 }
4003
4004                 m_adj(m, -IEEE80211_CRC_LEN);
4005
4006                 /*
4007                  * Locate the node for sender, track state, and then
4008                  * pass the (referenced) node up to the 802.11 layer
4009                  * for its use.
4010                  */
4011                 ni = ieee80211_find_rxnode_withkey(ic,
4012                         mtod(m, const struct ieee80211_frame_min *),
4013                         rs->rs_keyix == HAL_RXKEYIX_INVALID ?
4014                                 IEEE80211_KEYIX_NONE : rs->rs_keyix);
4015                 if (ni != NULL) {
4016                         /*
4017                          * Sending station is known, dispatch directly.
4018                          */
4019                         sc->sc_lastrs = rs;
4020                         type = ieee80211_input(ni, m, rs->rs_rssi, nf);
4021                         ieee80211_free_node(ni);
4022                         /*
4023                          * Arrange to update the last rx timestamp only for
4024                          * frames from our ap when operating in station mode.
4025                          * This assumes the rx key is always setup when
4026                          * associated.
4027                          */
4028                         if (ic->ic_opmode == IEEE80211_M_STA &&
4029                             rs->rs_keyix != HAL_RXKEYIX_INVALID)
4030                                 ngood++;
4031                 } else {
4032                         type = ieee80211_input_all(ic, m, rs->rs_rssi, nf);
4033                 }
4034                 /*
4035                  * Track rx rssi and do any rx antenna management.
4036                  */
4037                 ATH_RSSI_LPF(sc->sc_halstats.ns_avgrssi, rs->rs_rssi);
4038                 if (sc->sc_diversity) {
4039                         /*
4040                          * When using fast diversity, change the default rx
4041                          * antenna if diversity chooses the other antenna 3
4042                          * times in a row.
4043                          */
4044                         if (sc->sc_defant != rs->rs_antenna) {
4045                                 if (++sc->sc_rxotherant >= 3)
4046                                         ath_setdefantenna(sc, rs->rs_antenna);
4047                         } else
4048                                 sc->sc_rxotherant = 0;
4049                 }
4050                 if (sc->sc_softled) {
4051                         /*
4052                          * Blink for any data frame.  Otherwise do a
4053                          * heartbeat-style blink when idle.  The latter
4054                          * is mainly for station mode where we depend on
4055                          * periodic beacon frames to trigger the poll event.
4056                          */
4057                         if (type == IEEE80211_FC0_TYPE_DATA) {
4058                                 const HAL_RATE_TABLE *rt = sc->sc_currates;
4059                                 ath_led_event(sc, 
4060                                     rt->rateCodeToIndex[rs->rs_rate]);
4061                         } else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
4062                                 ath_led_event(sc, 0);
4063                 }
4064 rx_next:
4065                 STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
4066         } while (ath_rxbuf_init(sc, bf) == 0);
4067
4068         /* rx signal state monitoring */
4069         ath_hal_rxmonitor(ah, &sc->sc_halstats, sc->sc_curchan);
4070         if (ngood)
4071                 sc->sc_lastrx = tsf;
4072
4073         if ((ifp->if_flags & IFF_OACTIVE) == 0) {
4074 #ifdef IEEE80211_SUPPORT_SUPERG
4075                 ieee80211_ff_age_all(ic, 100);
4076 #endif
4077                 if (!ifq_is_empty(&ifp->if_snd))
4078                         ath_start(ifp);
4079         }
4080         wlan_serialize_exit();
4081 #undef PA2DESC
4082 }
4083
4084 static void
4085 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
4086 {
4087         txq->axq_qnum = qnum;
4088         txq->axq_ac = 0;
4089         txq->axq_depth = 0;
4090         txq->axq_intrcnt = 0;
4091         txq->axq_link = NULL;
4092         STAILQ_INIT(&txq->axq_q);
4093 }
4094
4095 /*
4096  * Setup a h/w transmit queue.
4097  */
4098 static struct ath_txq *
4099 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
4100 {
4101 #define N(a)    (sizeof(a)/sizeof(a[0]))
4102         struct ath_hal *ah = sc->sc_ah;
4103         HAL_TXQ_INFO qi;
4104         int qnum;
4105
4106         memset(&qi, 0, sizeof(qi));
4107         qi.tqi_subtype = subtype;
4108         qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
4109         qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
4110         qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
4111         /*
4112          * Enable interrupts only for EOL and DESC conditions.
4113          * We mark tx descriptors to receive a DESC interrupt
4114          * when a tx queue gets deep; otherwise waiting for the
4115          * EOL to reap descriptors.  Note that this is done to
4116          * reduce interrupt load and this only defers reaping
4117          * descriptors, never transmitting frames.  Aside from
4118          * reducing interrupts this also permits more concurrency.
4119          * The only potential downside is if the tx queue backs
4120          * up in which case the top half of the kernel may backup
4121          * due to a lack of tx descriptors.
4122          */
4123         qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE | HAL_TXQ_TXDESCINT_ENABLE;
4124         qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
4125         if (qnum == -1) {
4126                 /*
4127                  * NB: don't print a message, this happens
4128                  * normally on parts with too few tx queues
4129                  */
4130                 return NULL;
4131         }
4132         if (qnum >= N(sc->sc_txq)) {
4133                 device_printf(sc->sc_dev,
4134                         "hal qnum %u out of range, max %zu!\n",
4135                         qnum, N(sc->sc_txq));
4136                 ath_hal_releasetxqueue(ah, qnum);
4137                 return NULL;
4138         }
4139         if (!ATH_TXQ_SETUP(sc, qnum)) {
4140                 ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
4141                 sc->sc_txqsetup |= 1<<qnum;
4142         }
4143         return &sc->sc_txq[qnum];
4144 #undef N
4145 }
4146
4147 /*
4148  * Setup a hardware data transmit queue for the specified
4149  * access control.  The hal may not support all requested
4150  * queues in which case it will return a reference to a
4151  * previously setup queue.  We record the mapping from ac's
4152  * to h/w queues for use by ath_tx_start and also track
4153  * the set of h/w queues being used to optimize work in the
4154  * transmit interrupt handler and related routines.
4155  */
4156 static int
4157 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
4158 {
4159 #define N(a)    (sizeof(a)/sizeof(a[0]))
4160         struct ath_txq *txq;
4161
4162         if (ac >= N(sc->sc_ac2q)) {
4163                 device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
4164                         ac, N(sc->sc_ac2q));
4165                 return 0;
4166         }
4167         txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
4168         if (txq != NULL) {
4169                 txq->axq_ac = ac;
4170                 sc->sc_ac2q[ac] = txq;
4171                 return 1;
4172         } else
4173                 return 0;
4174 #undef N
4175 }
4176
4177 /*
4178  * Update WME parameters for a transmit queue.
4179  */
4180 static int
4181 ath_txq_update(struct ath_softc *sc, int ac)
4182 {
4183 #define ATH_EXPONENT_TO_VALUE(v)        ((1<<v)-1)
4184 #define ATH_TXOP_TO_US(v)               (v<<5)
4185         struct ifnet *ifp = sc->sc_ifp;
4186         struct ieee80211com *ic = ifp->if_l2com;
4187         struct ath_txq *txq = sc->sc_ac2q[ac];
4188         struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
4189         struct ath_hal *ah = sc->sc_ah;
4190         HAL_TXQ_INFO qi;
4191
4192         ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
4193 #ifdef IEEE80211_SUPPORT_TDMA
4194         if (sc->sc_tdma) {
4195                 /*
4196                  * AIFS is zero so there's no pre-transmit wait.  The
4197                  * burst time defines the slot duration and is configured
4198                  * through net80211.  The QCU is setup to not do post-xmit
4199                  * back off, lockout all lower-priority QCU's, and fire
4200                  * off the DMA beacon alert timer which is setup based
4201                  * on the slot configuration.
4202                  */
4203                 qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4204                               | HAL_TXQ_TXERRINT_ENABLE
4205                               | HAL_TXQ_TXURNINT_ENABLE
4206                               | HAL_TXQ_TXEOLINT_ENABLE
4207                               | HAL_TXQ_DBA_GATED
4208                               | HAL_TXQ_BACKOFF_DISABLE
4209                               | HAL_TXQ_ARB_LOCKOUT_GLOBAL
4210                               ;
4211                 qi.tqi_aifs = 0;
4212                 /* XXX +dbaprep? */
4213                 qi.tqi_readyTime = sc->sc_tdmaslotlen;
4214                 qi.tqi_burstTime = qi.tqi_readyTime;
4215         } else {
4216 #endif
4217                 qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4218                               | HAL_TXQ_TXERRINT_ENABLE
4219                               | HAL_TXQ_TXDESCINT_ENABLE
4220                               | HAL_TXQ_TXURNINT_ENABLE
4221                               ;
4222                 qi.tqi_aifs = wmep->wmep_aifsn;
4223                 qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
4224                 qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
4225                 qi.tqi_readyTime = 0;
4226                 qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
4227 #ifdef IEEE80211_SUPPORT_TDMA
4228         }
4229 #endif
4230
4231         DPRINTF(sc, ATH_DEBUG_RESET,
4232             "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
4233             __func__, txq->axq_qnum, qi.tqi_qflags,
4234             qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
4235
4236         if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
4237                 if_printf(ifp, "unable to update hardware queue "
4238                         "parameters for %s traffic!\n",
4239                         ieee80211_wme_acnames[ac]);
4240                 return 0;
4241         } else {
4242                 ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
4243                 return 1;
4244         }
4245 #undef ATH_TXOP_TO_US
4246 #undef ATH_EXPONENT_TO_VALUE
4247 }
4248
4249 /*
4250  * Callback from the 802.11 layer to update WME parameters.
4251  */
4252 static int
4253 ath_wme_update(struct ieee80211com *ic)
4254 {
4255         struct ath_softc *sc = ic->ic_ifp->if_softc;
4256
4257         return !ath_txq_update(sc, WME_AC_BE) ||
4258             !ath_txq_update(sc, WME_AC_BK) ||
4259             !ath_txq_update(sc, WME_AC_VI) ||
4260             !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
4261 }
4262
4263 /*
4264  * Reclaim resources for a setup queue.
4265  */
4266 static void
4267 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
4268 {
4269
4270         ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
4271         sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
4272 }
4273
4274 /*
4275  * Reclaim all tx queue resources.
4276  */
4277 static void
4278 ath_tx_cleanup(struct ath_softc *sc)
4279 {
4280         int i;
4281
4282         for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4283                 if (ATH_TXQ_SETUP(sc, i))
4284                         ath_tx_cleanupq(sc, &sc->sc_txq[i]);
4285 }
4286
4287 /*
4288  * Return h/w rate index for an IEEE rate (w/o basic rate bit)
4289  * using the current rates in sc_rixmap.
4290  */
4291 static __inline int
4292 ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
4293 {
4294         int rix = sc->sc_rixmap[rate];
4295         /* NB: return lowest rix for invalid rate */
4296         return (rix == 0xff ? 0 : rix);
4297 }
4298
4299 /*
4300  * Reclaim mbuf resources.  For fragmented frames we
4301  * need to claim each frag chained with m_nextpkt.
4302  */
4303 static void
4304 ath_freetx(struct mbuf *m)
4305 {
4306         struct mbuf *next;
4307
4308         do {
4309                 next = m->m_nextpkt;
4310                 m->m_nextpkt = NULL;
4311                 m_freem(m);
4312         } while ((m = next) != NULL);
4313 }
4314
4315 static int
4316 ath_tx_dmasetup(struct ath_softc *sc, struct ath_buf *bf, struct mbuf *m0)
4317 {
4318         int error;
4319
4320         /*
4321          * 
4322          * Load the DMA map so any coalescing is done.  This
4323          * also calculates the number of descriptors we need.
4324          */
4325         error = bus_dmamap_load_mbuf_defrag(sc->sc_dmat, bf->bf_dmamap, &m0,
4326                                      bf->bf_segs, ATH_TXDESC,
4327                                      &bf->bf_nseg, BUS_DMA_NOWAIT);
4328         if (error != 0) {
4329                 sc->sc_stats.ast_tx_busdma++;
4330                 ath_freetx(m0);
4331                 return error;
4332         }
4333
4334         /*
4335          * Discard null packets.
4336          */
4337         if (bf->bf_nseg == 0) {         /* null packet, discard */
4338                 sc->sc_stats.ast_tx_nodata++;
4339                 ath_freetx(m0);
4340                 return EIO;
4341         }
4342         DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n",
4343                 __func__, m0, m0->m_pkthdr.len);
4344         bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
4345         bf->bf_m = m0;
4346
4347         return 0;
4348 }
4349
4350 static void
4351 ath_tx_handoff(struct ath_softc *sc, struct ath_txq *txq, struct ath_buf *bf)
4352 {
4353         struct ath_hal *ah = sc->sc_ah;
4354         struct ath_desc *ds, *ds0;
4355         int i;
4356
4357         /*
4358          * Fillin the remainder of the descriptor info.
4359          */
4360         ds0 = ds = bf->bf_desc;
4361         for (i = 0; i < bf->bf_nseg; i++, ds++) {
4362                 ds->ds_data = bf->bf_segs[i].ds_addr;
4363                 if (i == bf->bf_nseg - 1)
4364                         ds->ds_link = 0;
4365                 else
4366                         ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
4367                 ath_hal_filltxdesc(ah, ds
4368                         , bf->bf_segs[i].ds_len /* segment length */
4369                         , i == 0                /* first segment */
4370                         , i == bf->bf_nseg - 1  /* last segment */
4371                         , ds0                   /* first descriptor */
4372                 );
4373                 DPRINTF(sc, ATH_DEBUG_XMIT,
4374                         "%s: %d: %08x %08x %08x %08x %08x %08x\n",
4375                         __func__, i, ds->ds_link, ds->ds_data,
4376                         ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
4377         }
4378         /*
4379          * Insert the frame on the outbound list and pass it on
4380          * to the hardware.  Multicast frames buffered for power
4381          * save stations and transmit from the CAB queue are stored
4382          * on a s/w only queue and loaded on to the CAB queue in
4383          * the SWBA handler since frames only go out on DTIM and
4384          * to avoid possible races.
4385          */
4386         KASSERT((bf->bf_flags & ATH_BUF_BUSY) == 0,
4387              ("busy status 0x%x", bf->bf_flags));
4388         if (txq->axq_qnum != ATH_TXQ_SWQ) {
4389 #ifdef IEEE80211_SUPPORT_TDMA
4390                 /*
4391                  * Supporting transmit dma.  If the queue is busy it is
4392                  * impossible to determine if we've won the race against
4393                  * the chipset checking the link field or not, so we don't
4394                  * try.  Instead we let the TX interrupt detect the case
4395                  * and restart the transmitter.
4396                  *
4397                  * If the queue is not busy we can start things rolling
4398                  * right here.
4399                  */
4400                 int qbusy;
4401
4402                 ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4403                 qbusy = ath_hal_txqenabled(ah, txq->axq_qnum);
4404
4405                 if (qbusy == 0) {
4406                         if (txq->axq_link != NULL) {
4407                                 /*
4408                                  * We had already started one previously but
4409                                  * not yet processed the TX interrupt.  Don't
4410                                  * try to race a restart because we do not
4411                                  * know where it stopped, let the TX interrupt
4412                                  * restart us when it figures out where we
4413                                  * stopped.
4414                                  */
4415                                 cpu_sfence();
4416                                 *txq->axq_link = bf->bf_daddr;
4417                                 txq->axq_flags |= ATH_TXQ_PUTPENDING;
4418                         } else {
4419                                 /*
4420                                  * We are first in line, we can safely start
4421                                  * at this address.
4422                                  */
4423                                 cpu_sfence();
4424                                 ath_hal_puttxbuf(ah, txq->axq_qnum,
4425                                                  bf->bf_daddr);
4426                         }
4427                 } else {
4428                         /*
4429                          * The queue is busy, go ahead and link us in but
4430                          * do not try to start/restart the tx.  We just
4431                          * don't know whether it will pick up our link
4432                          * or not and we don't want to double-xmit.
4433                          */
4434                         if (txq->axq_link != NULL) {
4435                                 cpu_sfence();
4436                                 *txq->axq_link = bf->bf_daddr;
4437                         }
4438                         txq->axq_flags |= ATH_TXQ_PUTPENDING;
4439                 }
4440 #if 0
4441                                 ath_hal_puttxbuf(ah, txq->axq_qnum,
4442                                         STAILQ_FIRST(&txq->axq_q)->bf_daddr);
4443 #endif
4444 #else
4445                 ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4446                 if (txq->axq_link == NULL) {
4447                         ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
4448                         DPRINTF(sc, ATH_DEBUG_XMIT,
4449                             "%s: TXDP[%u] = %p (%p) depth %d\n",
4450                             __func__, txq->axq_qnum,
4451                             (caddr_t)bf->bf_daddr, bf->bf_desc,
4452                             txq->axq_depth);
4453                 } else {
4454                         *txq->axq_link = bf->bf_daddr;
4455                         DPRINTF(sc, ATH_DEBUG_XMIT,
4456                             "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
4457                             txq->axq_qnum, txq->axq_link,
4458                             (caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
4459                 }
4460 #endif /* IEEE80211_SUPPORT_TDMA */
4461                 txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
4462                 ath_hal_txstart(ah, txq->axq_qnum);
4463         } else {
4464                 if (txq->axq_link != NULL) {
4465                         struct ath_buf *last = ATH_TXQ_LAST(txq);
4466                         struct ieee80211_frame *wh;
4467
4468                         /* mark previous frame */
4469                         wh = mtod(last->bf_m, struct ieee80211_frame *);
4470                         wh->i_fc[1] |= IEEE80211_FC1_MORE_DATA;
4471                         bus_dmamap_sync(sc->sc_dmat, last->bf_dmamap,
4472                             BUS_DMASYNC_PREWRITE);
4473
4474                         /* link descriptor */
4475                         *txq->axq_link = bf->bf_daddr;
4476                 }
4477                 ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
4478                 txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
4479         }
4480 }
4481
4482 static int
4483 ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
4484     struct mbuf *m0)
4485 {
4486         struct ieee80211vap *vap = ni->ni_vap;
4487         struct ath_vap *avp = ATH_VAP(vap);
4488         struct ath_hal *ah = sc->sc_ah;
4489         struct ifnet *ifp = sc->sc_ifp;
4490         struct ieee80211com *ic = ifp->if_l2com;
4491         const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
4492         int error, iswep, ismcast, isfrag, ismrr;
4493         int keyix, hdrlen, pktlen, try0;
4494         u_int8_t rix, txrate, ctsrate;
4495         u_int8_t cix = 0xff;            /* NB: silence compiler */
4496         struct ath_desc *ds;
4497         struct ath_txq *txq;
4498         struct ieee80211_frame *wh;
4499         u_int subtype, flags, ctsduration;
4500         HAL_PKT_TYPE atype;
4501         const HAL_RATE_TABLE *rt;
4502         HAL_BOOL shortPreamble;
4503         struct ath_node *an;
4504         u_int pri;
4505
4506         wh = mtod(m0, struct ieee80211_frame *);
4507         iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
4508         ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
4509         isfrag = m0->m_flags & M_FRAG;
4510         hdrlen = ieee80211_anyhdrsize(wh);
4511         /*
4512          * Packet length must not include any
4513          * pad bytes; deduct them here.
4514          */
4515         pktlen = m0->m_pkthdr.len - (hdrlen & 3);
4516
4517         if (iswep) {
4518                 const struct ieee80211_cipher *cip;
4519                 struct ieee80211_key *k;
4520
4521                 /*
4522                  * Construct the 802.11 header+trailer for an encrypted
4523                  * frame. The only reason this can fail is because of an
4524                  * unknown or unsupported cipher/key type.
4525                  */
4526                 k = ieee80211_crypto_encap(ni, m0);
4527                 if (k == NULL) {
4528                         /*
4529                          * This can happen when the key is yanked after the
4530                          * frame was queued.  Just discard the frame; the
4531                          * 802.11 layer counts failures and provides
4532                          * debugging/diagnostics.
4533                          */
4534                         ath_freetx(m0);
4535                         return EIO;
4536                 }
4537                 /*
4538                  * Adjust the packet + header lengths for the crypto
4539                  * additions and calculate the h/w key index.  When
4540                  * a s/w mic is done the frame will have had any mic
4541                  * added to it prior to entry so m0->m_pkthdr.len will
4542                  * account for it. Otherwise we need to add it to the
4543                  * packet length.
4544                  */
4545                 cip = k->wk_cipher;
4546                 hdrlen += cip->ic_header;
4547                 pktlen += cip->ic_header + cip->ic_trailer;
4548                 /* NB: frags always have any TKIP MIC done in s/w */
4549                 if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && !isfrag)
4550                         pktlen += cip->ic_miclen;
4551                 keyix = k->wk_keyix;
4552
4553                 /* packet header may have moved, reset our local pointer */
4554                 wh = mtod(m0, struct ieee80211_frame *);
4555         } else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
4556                 /*
4557                  * Use station key cache slot, if assigned.
4558                  */
4559                 keyix = ni->ni_ucastkey.wk_keyix;
4560                 if (keyix == IEEE80211_KEYIX_NONE)
4561                         keyix = HAL_TXKEYIX_INVALID;
4562         } else
4563                 keyix = HAL_TXKEYIX_INVALID;
4564
4565         pktlen += IEEE80211_CRC_LEN;
4566
4567         /*
4568          * Load the DMA map so any coalescing is done.  This
4569          * also calculates the number of descriptors we need.
4570          */
4571         error = ath_tx_dmasetup(sc, bf, m0);
4572         if (error != 0) {
4573                 return error;
4574         }
4575         bf->bf_node = ni;                       /* NB: held reference */
4576         m0 = bf->bf_m;                          /* NB: may have changed */
4577         wh = mtod(m0, struct ieee80211_frame *);
4578
4579         /* setup descriptors */
4580         ds = bf->bf_desc;
4581         rt = sc->sc_currates;
4582         KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
4583
4584         /*
4585          * NB: the 802.11 layer marks whether or not we should
4586          * use short preamble based on the current mode and
4587          * negotiated parameters.
4588          */
4589         if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
4590             (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
4591                 shortPreamble = AH_TRUE;
4592                 sc->sc_stats.ast_tx_shortpre++;
4593         } else {
4594                 shortPreamble = AH_FALSE;
4595         }
4596
4597         an = ATH_NODE(ni);
4598         flags = HAL_TXDESC_CLRDMASK;            /* XXX needed for crypto errs */
4599         ismrr = 0;                              /* default no multi-rate retry*/
4600         pri = M_WME_GETAC(m0);                  /* honor classification */
4601         /* XXX use txparams instead of fixed values */
4602         /*
4603          * Calculate Atheros packet type from IEEE80211 packet header,
4604          * setup for rate calculations, and select h/w transmit queue.
4605          */
4606         switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
4607         case IEEE80211_FC0_TYPE_MGT:
4608                 subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
4609                 if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
4610                         atype = HAL_PKT_TYPE_BEACON;
4611                 else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
4612                         atype = HAL_PKT_TYPE_PROBE_RESP;
4613                 else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
4614                         atype = HAL_PKT_TYPE_ATIM;
4615                 else
4616                         atype = HAL_PKT_TYPE_NORMAL;    /* XXX */
4617                 rix = an->an_mgmtrix;
4618                 txrate = rt->info[rix].rateCode;
4619                 if (shortPreamble)
4620                         txrate |= rt->info[rix].shortPreamble;
4621                 try0 = ATH_TXMGTTRY;
4622                 flags |= HAL_TXDESC_INTREQ;     /* force interrupt */
4623                 break;
4624         case IEEE80211_FC0_TYPE_CTL:
4625                 atype = HAL_PKT_TYPE_PSPOLL;    /* stop setting of duration */
4626                 rix = an->an_mgmtrix;
4627                 txrate = rt->info[rix].rateCode;
4628                 if (shortPreamble)
4629                         txrate |= rt->info[rix].shortPreamble;
4630                 try0 = ATH_TXMGTTRY;
4631                 flags |= HAL_TXDESC_INTREQ;     /* force interrupt */
4632                 break;
4633         case IEEE80211_FC0_TYPE_DATA:
4634                 atype = HAL_PKT_TYPE_NORMAL;            /* default */
4635                 /*
4636                  * Data frames: multicast frames go out at a fixed rate,
4637                  * EAPOL frames use the mgmt frame rate; otherwise consult
4638                  * the rate control module for the rate to use.
4639                  */
4640                 if (ismcast) {
4641                         rix = an->an_mcastrix;
4642                         txrate = rt->info[rix].rateCode;
4643                         if (shortPreamble)
4644                                 txrate |= rt->info[rix].shortPreamble;
4645                         try0 = 1;
4646                 } else if (m0->m_flags & M_EAPOL) {
4647                         /* XXX? maybe always use long preamble? */
4648                         rix = an->an_mgmtrix;
4649                         txrate = rt->info[rix].rateCode;
4650                         if (shortPreamble)
4651                                 txrate |= rt->info[rix].shortPreamble;
4652                         try0 = ATH_TXMAXTRY;    /* XXX?too many? */
4653                 } else {
4654                         ath_rate_findrate(sc, an, shortPreamble, pktlen,
4655                                 &rix, &try0, &txrate);
4656                         sc->sc_txrix = rix;             /* for LED blinking */
4657                         sc->sc_lastdatarix = rix;       /* for fast frames */
4658                         if (try0 != ATH_TXMAXTRY)
4659                                 ismrr = 1;
4660                 }
4661                 if (cap->cap_wmeParams[pri].wmep_noackPolicy)
4662                         flags |= HAL_TXDESC_NOACK;
4663                 break;
4664         default:
4665                 if_printf(ifp, "bogus frame type 0x%x (%s)\n",
4666                         wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
4667                 /* XXX statistic */
4668                 ath_freetx(m0);
4669                 return EIO;
4670         }
4671         txq = sc->sc_ac2q[pri];
4672
4673         /*
4674          * When servicing one or more stations in power-save mode
4675          * (or) if there is some mcast data waiting on the mcast
4676          * queue (to prevent out of order delivery) multicast
4677          * frames must be buffered until after the beacon.
4678          */
4679         if (ismcast && (vap->iv_ps_sta || avp->av_mcastq.axq_depth))
4680                 txq = &avp->av_mcastq;
4681
4682         /*
4683          * Calculate miscellaneous flags.
4684          */
4685         if (ismcast) {
4686                 flags |= HAL_TXDESC_NOACK;      /* no ack on broad/multicast */
4687         } else if (pktlen > vap->iv_rtsthreshold &&
4688             (ni->ni_ath_flags & IEEE80211_NODE_FF) == 0) {
4689                 flags |= HAL_TXDESC_RTSENA;     /* RTS based on frame length */
4690                 cix = rt->info[rix].controlRate;
4691                 sc->sc_stats.ast_tx_rts++;
4692         }
4693         if (flags & HAL_TXDESC_NOACK)           /* NB: avoid double counting */
4694                 sc->sc_stats.ast_tx_noack++;
4695 #ifdef IEEE80211_SUPPORT_TDMA
4696         if (sc->sc_tdma && (flags & HAL_TXDESC_NOACK) == 0) {
4697                 DPRINTF(sc, ATH_DEBUG_TDMA,
4698                     "%s: discard frame, ACK required w/ TDMA\n", __func__);
4699                 sc->sc_stats.ast_tdma_ack++;
4700                 ath_freetx(m0);
4701                 return EIO;
4702         }
4703 #endif
4704
4705         /*
4706          * If 802.11g protection is enabled, determine whether
4707          * to use RTS/CTS or just CTS.  Note that this is only
4708          * done for OFDM unicast frames.
4709          */
4710         if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
4711             rt->info[rix].phy == IEEE80211_T_OFDM &&
4712             (flags & HAL_TXDESC_NOACK) == 0) {
4713                 /* XXX fragments must use CCK rates w/ protection */
4714                 if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
4715                         flags |= HAL_TXDESC_RTSENA;
4716                 else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
4717                         flags |= HAL_TXDESC_CTSENA;
4718                 if (isfrag) {
4719                         /*
4720                          * For frags it would be desirable to use the
4721                          * highest CCK rate for RTS/CTS.  But stations
4722                          * farther away may detect it at a lower CCK rate
4723                          * so use the configured protection rate instead
4724                          * (for now).
4725                          */
4726                         cix = rt->info[sc->sc_protrix].controlRate;
4727                 } else
4728                         cix = rt->info[sc->sc_protrix].controlRate;
4729                 sc->sc_stats.ast_tx_protect++;
4730         }
4731
4732         /*
4733          * Calculate duration.  This logically belongs in the 802.11
4734          * layer but it lacks sufficient information to calculate it.
4735          */
4736         if ((flags & HAL_TXDESC_NOACK) == 0 &&
4737             (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
4738                 u_int16_t dur;
4739                 if (shortPreamble)
4740                         dur = rt->info[rix].spAckDuration;
4741                 else
4742                         dur = rt->info[rix].lpAckDuration;
4743                 if (wh->i_fc[1] & IEEE80211_FC1_MORE_FRAG) {
4744                         dur += dur;             /* additional SIFS+ACK */
4745                         KASSERT(m0->m_nextpkt != NULL, ("no fragment"));
4746                         /*
4747                          * Include the size of next fragment so NAV is
4748                          * updated properly.  The last fragment uses only
4749                          * the ACK duration
4750                          */
4751                         dur += ath_hal_computetxtime(ah, rt,
4752                                         m0->m_nextpkt->m_pkthdr.len,
4753                                         rix, shortPreamble);
4754                 }
4755                 if (isfrag) {
4756                         /*
4757                          * Force hardware to use computed duration for next
4758                          * fragment by disabling multi-rate retry which updates
4759                          * duration based on the multi-rate duration table.
4760                          */
4761                         ismrr = 0;
4762                         try0 = ATH_TXMGTTRY;    /* XXX? */
4763                 }
4764                 *(u_int16_t *)wh->i_dur = htole16(dur);
4765         }
4766
4767         /*
4768          * Calculate RTS/CTS rate and duration if needed.
4769          */
4770         ctsduration = 0;
4771         if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
4772                 /*
4773                  * CTS transmit rate is derived from the transmit rate
4774                  * by looking in the h/w rate table.  We must also factor
4775                  * in whether or not a short preamble is to be used.
4776                  */
4777                 /* NB: cix is set above where RTS/CTS is enabled */
4778                 KASSERT(cix != 0xff, ("cix not setup"));
4779                 ctsrate = rt->info[cix].rateCode;
4780                 /*
4781                  * Compute the transmit duration based on the frame
4782                  * size and the size of an ACK frame.  We call into the
4783                  * HAL to do the computation since it depends on the
4784                  * characteristics of the actual PHY being used.
4785                  *
4786                  * NB: CTS is assumed the same size as an ACK so we can
4787                  *     use the precalculated ACK durations.
4788                  */
4789                 if (shortPreamble) {
4790                         ctsrate |= rt->info[cix].shortPreamble;
4791                         if (flags & HAL_TXDESC_RTSENA)          /* SIFS + CTS */
4792                                 ctsduration += rt->info[cix].spAckDuration;
4793                         ctsduration += ath_hal_computetxtime(ah,
4794                                 rt, pktlen, rix, AH_TRUE);
4795                         if ((flags & HAL_TXDESC_NOACK) == 0)    /* SIFS + ACK */
4796                                 ctsduration += rt->info[rix].spAckDuration;
4797                 } else {
4798                         if (flags & HAL_TXDESC_RTSENA)          /* SIFS + CTS */
4799                                 ctsduration += rt->info[cix].lpAckDuration;
4800                         ctsduration += ath_hal_computetxtime(ah,
4801                                 rt, pktlen, rix, AH_FALSE);
4802                         if ((flags & HAL_TXDESC_NOACK) == 0)    /* SIFS + ACK */
4803                                 ctsduration += rt->info[rix].lpAckDuration;
4804                 }
4805                 /*
4806                  * Must disable multi-rate retry when using RTS/CTS.
4807                  */
4808                 ismrr = 0;
4809                 try0 = ATH_TXMGTTRY;            /* XXX */
4810         } else
4811                 ctsrate = 0;
4812
4813         /*
4814          * At this point we are committed to sending the frame
4815          * and we don't need to look at m_nextpkt; clear it in
4816          * case this frame is part of frag chain.
4817          */
4818         m0->m_nextpkt = NULL;
4819
4820         if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
4821                 ieee80211_dump_pkt(ic, mtod(m0, const uint8_t *), m0->m_len,
4822                     sc->sc_hwmap[rix].ieeerate, -1);
4823
4824         if (ieee80211_radiotap_active_vap(vap)) {
4825                 u_int64_t tsf = ath_hal_gettsf64(ah);
4826
4827                 sc->sc_tx_th.wt_tsf = htole64(tsf);
4828                 sc->sc_tx_th.wt_flags = sc->sc_hwmap[rix].txflags;
4829                 if (iswep)
4830                         sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
4831                 if (isfrag)
4832                         sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_FRAG;
4833                 sc->sc_tx_th.wt_rate = sc->sc_hwmap[rix].ieeerate;
4834                 sc->sc_tx_th.wt_txpower = ni->ni_txpower;
4835                 sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
4836
4837                 ieee80211_radiotap_tx(vap, m0);
4838         }
4839
4840         /*
4841          * Determine if a tx interrupt should be generated for
4842          * this descriptor.  We take a tx interrupt to reap
4843          * descriptors when the h/w hits an EOL condition or
4844          * when the descriptor is specifically marked to generate
4845          * an interrupt.  We periodically mark descriptors in this
4846          * way to insure timely replenishing of the supply needed
4847          * for sending frames.  Defering interrupts reduces system
4848          * load and potentially allows more concurrent work to be
4849          * done but if done to aggressively can cause senders to
4850          * backup.
4851          *
4852          * NB: use >= to deal with sc_txintrperiod changing
4853          *     dynamically through sysctl.
4854          */
4855         if (flags & HAL_TXDESC_INTREQ) {
4856                 txq->axq_intrcnt = 0;
4857         } else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
4858                 flags |= HAL_TXDESC_INTREQ;
4859                 txq->axq_intrcnt = 0;
4860         }
4861
4862         /*
4863          * Formulate first tx descriptor with tx controls.
4864          */
4865         /* XXX check return value? */
4866         ath_hal_setuptxdesc(ah, ds
4867                 , pktlen                /* packet length */
4868                 , hdrlen                /* header length */
4869                 , atype                 /* Atheros packet type */
4870                 , ni->ni_txpower        /* txpower */
4871                 , txrate, try0          /* series 0 rate/tries */
4872                 , keyix                 /* key cache index */
4873                 , sc->sc_txantenna      /* antenna mode */
4874                 , flags                 /* flags */
4875                 , ctsrate               /* rts/cts rate */
4876                 , ctsduration           /* rts/cts duration */
4877         );
4878         bf->bf_txflags = flags;
4879         /*
4880          * Setup the multi-rate retry state only when we're
4881          * going to use it.  This assumes ath_hal_setuptxdesc
4882          * initializes the descriptors (so we don't have to)
4883          * when the hardware supports multi-rate retry and
4884          * we don't use it.
4885          */
4886         if (ismrr)
4887                 ath_rate_setupxtxdesc(sc, an, ds, shortPreamble, rix);
4888
4889         ath_tx_handoff(sc, txq, bf);
4890         return 0;
4891 }
4892
4893 /*
4894  * Process completed xmit descriptors from the specified queue.
4895  */
4896 static int
4897 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
4898 {
4899         struct ath_hal *ah = sc->sc_ah;
4900         struct ifnet *ifp = sc->sc_ifp;
4901         struct ieee80211com *ic = ifp->if_l2com;
4902         struct ath_buf *bf, *last;
4903         struct ath_desc *ds, *ds0;
4904         struct ath_tx_status *ts;
4905         struct ieee80211_node *ni;
4906         struct ath_node *an;
4907         int sr, lr, pri, nacked;
4908         HAL_STATUS status;
4909
4910         DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
4911                 __func__, txq->axq_qnum,
4912                 (caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4913                 txq->axq_link);
4914         nacked = 0;
4915         for (;;) {
4916                 int qbusy;
4917
4918                 txq->axq_intrcnt = 0;   /* reset periodic desc intr count */
4919                 bf = STAILQ_FIRST(&txq->axq_q);
4920                 if (bf == NULL)
4921                         break;
4922                 ds0 = &bf->bf_desc[0];
4923                 ds = &bf->bf_desc[bf->bf_nseg - 1];
4924                 ts = &bf->bf_status.ds_txstat;
4925                 qbusy = ath_hal_txqenabled(ah, txq->axq_qnum);
4926                 status = ath_hal_txprocdesc(ah, ds, ts);
4927 #ifdef ATH_DEBUG
4928                 if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
4929                         ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4930                             status == HAL_OK);
4931 #endif
4932                 if (status == HAL_EINPROGRESS) {
4933 #ifdef IEEE80211_SUPPORT_TDMA
4934                         /*
4935                          * If not done and the queue is not busy then the
4936                          * transmitter raced the hardware on the link field
4937                          * and we have to restart it.
4938                          */
4939                         if (!qbusy) {
4940                                 cpu_sfence();
4941                                 ath_hal_puttxbuf(ah, txq->axq_qnum,
4942                                                  bf->bf_daddr);
4943                                 ath_hal_txstart(ah, txq->axq_qnum);
4944                         }
4945 #endif
4946                         break;
4947                 }
4948                 ATH_TXQ_REMOVE_HEAD(txq, bf_list);
4949 #ifdef IEEE80211_SUPPORT_TDMA
4950                 if (txq->axq_depth > 0) {
4951                         /*
4952                          * More frames follow.  Mark the buffer busy
4953                          * so it's not re-used while the hardware may
4954                          * still re-read the link field in the descriptor.
4955                          */
4956                         bf->bf_flags |= ATH_BUF_BUSY;
4957                 } else
4958 #else
4959                 if (txq->axq_depth == 0)
4960 #endif
4961                         txq->axq_link = NULL;
4962
4963                 ni = bf->bf_node;
4964                 if (ni != NULL) {
4965                         an = ATH_NODE(ni);
4966                         if (ts->ts_status == 0) {
4967                                 u_int8_t txant = ts->ts_antenna;
4968                                 sc->sc_stats.ast_ant_tx[txant]++;
4969                                 sc->sc_ant_tx[txant]++;
4970                                 if (ts->ts_finaltsi != 0)
4971                                         sc->sc_stats.ast_tx_altrate++;
4972                                 pri = M_WME_GETAC(bf->bf_m);
4973                                 if (pri >= WME_AC_VO)
4974                                         ic->ic_wme.wme_hipri_traffic++;
4975                                 if ((bf->bf_txflags & HAL_TXDESC_NOACK) == 0)
4976                                         ni->ni_inact = ni->ni_inact_reload;
4977                         } else {
4978                                 if (ts->ts_status & HAL_TXERR_XRETRY)
4979                                         sc->sc_stats.ast_tx_xretries++;
4980                                 if (ts->ts_status & HAL_TXERR_FIFO)
4981                                         sc->sc_stats.ast_tx_fifoerr++;
4982                                 if (ts->ts_status & HAL_TXERR_FILT)
4983                                         sc->sc_stats.ast_tx_filtered++;
4984                                 if (bf->bf_m->m_flags & M_FF)
4985                                         sc->sc_stats.ast_ff_txerr++;
4986                         }
4987                         sr = ts->ts_shortretry;
4988                         lr = ts->ts_longretry;
4989                         sc->sc_stats.ast_tx_shortretry += sr;
4990                         sc->sc_stats.ast_tx_longretry += lr;
4991                         /*
4992                          * Hand the descriptor to the rate control algorithm.
4993                          */
4994                         if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
4995                             (bf->bf_txflags & HAL_TXDESC_NOACK) == 0) {
4996                                 /*
4997                                  * If frame was ack'd update statistics,
4998                                  * including the last rx time used to
4999                                  * workaround phantom bmiss interrupts.
5000                                  */
5001                                 if (ts->ts_status == 0) {
5002                                         nacked++;
5003                                         sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
5004                                         ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
5005                                                 ts->ts_rssi);
5006                                 }
5007                                 ath_rate_tx_complete(sc, an, bf);
5008                         }
5009                         /*
5010                          * Do any tx complete callback.  Note this must
5011                          * be done before releasing the node reference.
5012                          */
5013                         if (bf->bf_m->m_flags & M_TXCB)
5014                                 ieee80211_process_callback(ni, bf->bf_m,
5015                                     (bf->bf_txflags & HAL_TXDESC_NOACK) == 0 ?
5016                                         ts->ts_status : HAL_TXERR_XRETRY);
5017                         ieee80211_free_node(ni);
5018                 }
5019                 bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
5020                     BUS_DMASYNC_POSTWRITE);
5021                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
5022
5023                 m_freem(bf->bf_m);
5024                 bf->bf_m = NULL;
5025                 bf->bf_node = NULL;
5026
5027                 last = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
5028                 if (last != NULL)
5029                         last->bf_flags &= ~ATH_BUF_BUSY;
5030                 STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5031         }
5032 #ifdef IEEE80211_SUPPORT_SUPERG
5033         /*
5034          * Flush fast-frame staging queue when traffic slows.
5035          */
5036         if (txq->axq_depth <= 1)
5037                 ieee80211_ff_flush(ic, txq->axq_ac);
5038 #endif
5039         return nacked;
5040 }
5041
5042 static __inline int
5043 txqactive(struct ath_hal *ah, int qnum)
5044 {
5045         u_int32_t txqs = 1<<qnum;
5046         ath_hal_gettxintrtxqs(ah, &txqs);
5047         return (txqs & (1<<qnum));
5048 }
5049
5050 /*
5051  * Deferred processing of transmit interrupt; special-cased
5052  * for a single hardware transmit queue (e.g. 5210 and 5211).
5053  */
5054 static void
5055 ath_tx_task_q0(void *arg, int npending)
5056 {
5057         struct ath_softc *sc = arg;
5058         struct ifnet *ifp = sc->sc_ifp;
5059
5060         wlan_serialize_enter();
5061         if (txqactive(sc->sc_ah, 0) && ath_tx_processq(sc, &sc->sc_txq[0]))
5062                 sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5063         if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
5064                 ath_tx_processq(sc, sc->sc_cabq);
5065         ifp->if_flags &= ~IFF_OACTIVE;
5066         sc->sc_wd_timer = 0;
5067
5068         if (sc->sc_softled)
5069                 ath_led_event(sc, sc->sc_txrix);
5070
5071         ath_start(ifp);
5072         wlan_serialize_exit();
5073 }
5074
5075 /*
5076  * Deferred processing of transmit interrupt; special-cased
5077  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
5078  */
5079 static void
5080 ath_tx_task_q0123(void *arg, int npending)
5081 {
5082         struct ath_softc *sc = arg;
5083         struct ifnet *ifp = sc->sc_ifp;
5084         int nacked;
5085
5086         wlan_serialize_enter();
5087         /*
5088          * Process each active queue.
5089          */
5090         nacked = 0;
5091         if (txqactive(sc->sc_ah, 0))
5092                 nacked += ath_tx_processq(sc, &sc->sc_txq[0]);
5093         if (txqactive(sc->sc_ah, 1))
5094                 nacked += ath_tx_processq(sc, &sc->sc_txq[1]);
5095         if (txqactive(sc->sc_ah, 2))
5096                 nacked += ath_tx_processq(sc, &sc->sc_txq[2]);
5097         if (txqactive(sc->sc_ah, 3))
5098                 nacked += ath_tx_processq(sc, &sc->sc_txq[3]);
5099         if (txqactive(sc->sc_ah, sc->sc_cabq->axq_qnum))
5100                 ath_tx_processq(sc, sc->sc_cabq);
5101         if (nacked)
5102                 sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5103
5104         ifp->if_flags &= ~IFF_OACTIVE;
5105         sc->sc_wd_timer = 0;
5106
5107         if (sc->sc_softled)
5108                 ath_led_event(sc, sc->sc_txrix);
5109
5110         ath_start(ifp);
5111         wlan_serialize_exit();
5112 }
5113
5114 /*
5115  * Deferred processing of transmit interrupt.
5116  */
5117 static void
5118 ath_tx_task(void *arg, int npending)
5119 {
5120         struct ath_softc *sc = arg;
5121         struct ifnet *ifp = sc->sc_ifp;
5122         int i, nacked;
5123
5124         wlan_serialize_enter();
5125
5126         /*
5127          * Process each active queue.
5128          */
5129         nacked = 0;
5130         for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
5131                 if (ATH_TXQ_SETUP(sc, i) && txqactive(sc->sc_ah, i))
5132                         nacked += ath_tx_processq(sc, &sc->sc_txq[i]);
5133         }
5134         if (nacked)
5135                 sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5136
5137         ifp->if_flags &= ~IFF_OACTIVE;
5138         sc->sc_wd_timer = 0;
5139
5140         if (sc->sc_softled)
5141                 ath_led_event(sc, sc->sc_txrix);
5142
5143         ath_start(ifp);
5144         wlan_serialize_exit();
5145 }
5146
5147 static void
5148 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
5149 {
5150 #ifdef ATH_DEBUG
5151         struct ath_hal *ah = sc->sc_ah;
5152 #endif
5153         struct ieee80211_node *ni;
5154         struct ath_buf *bf;
5155         u_int ix;
5156
5157         /*
5158          * NB: this assumes output has been stopped and
5159          *     we do not need to block ath_tx_proc
5160          */
5161         bf = STAILQ_LAST(&sc->sc_txbuf, ath_buf, bf_list);
5162         if (bf != NULL)
5163                 bf->bf_flags &= ~ATH_BUF_BUSY;
5164         for (ix = 0;; ix++) {
5165                 bf = STAILQ_FIRST(&txq->axq_q);
5166                 if (bf == NULL) {
5167                         txq->axq_link = NULL;
5168                         break;
5169                 }
5170                 ATH_TXQ_REMOVE_HEAD(txq, bf_list);
5171 #ifdef ATH_DEBUG
5172                 if (sc->sc_debug & ATH_DEBUG_RESET) {
5173                         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
5174
5175                         ath_printtxbuf(sc, bf, txq->axq_qnum, ix,
5176                                 ath_hal_txprocdesc(ah, bf->bf_desc,
5177                                     &bf->bf_status.ds_txstat) == HAL_OK);
5178                         ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
5179                             bf->bf_m->m_len, 0, -1);
5180                 }
5181 #endif /* ATH_DEBUG */
5182                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
5183                 ni = bf->bf_node;
5184                 bf->bf_node = NULL;
5185                 if (ni != NULL) {
5186                         /*
5187                          * Do any callback and reclaim the node reference.
5188                          */
5189                         if (bf->bf_m->m_flags & M_TXCB)
5190                                 ieee80211_process_callback(ni, bf->bf_m, -1);
5191                         ieee80211_free_node(ni);
5192                 }
5193                 m_freem(bf->bf_m);
5194                 bf->bf_m = NULL;
5195                 bf->bf_flags &= ~ATH_BUF_BUSY;
5196
5197                 STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5198         }
5199 }
5200
5201 static void
5202 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
5203 {
5204         struct ath_hal *ah = sc->sc_ah;
5205
5206         DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5207             __func__, txq->axq_qnum,
5208             (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
5209             txq->axq_link);
5210         (void) ath_hal_stoptxdma(ah, txq->axq_qnum);
5211 }
5212
5213 /*
5214  * Drain the transmit queues and reclaim resources.
5215  */
5216 static void
5217 ath_draintxq(struct ath_softc *sc)
5218 {
5219         struct ath_hal *ah = sc->sc_ah;
5220         struct ifnet *ifp = sc->sc_ifp;
5221         int i;
5222
5223         /* XXX return value */
5224         if (!sc->sc_invalid) {
5225                 /* don't touch the hardware if marked invalid */
5226                 DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5227                     __func__, sc->sc_bhalq,
5228                     (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
5229                     NULL);
5230                 (void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
5231                 for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5232                         if (ATH_TXQ_SETUP(sc, i))
5233                                 ath_tx_stopdma(sc, &sc->sc_txq[i]);
5234         }
5235         for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5236                 if (ATH_TXQ_SETUP(sc, i))
5237                         ath_tx_draintxq(sc, &sc->sc_txq[i]);
5238 #ifdef ATH_DEBUG
5239         if (sc->sc_debug & ATH_DEBUG_RESET) {
5240                 struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
5241                 if (bf != NULL && bf->bf_m != NULL) {
5242                         ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
5243                                 ath_hal_txprocdesc(ah, bf->bf_desc,
5244                                     &bf->bf_status.ds_txstat) == HAL_OK);
5245                         ieee80211_dump_pkt(ifp->if_l2com,
5246                             mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
5247                             0, -1);
5248                 }
5249         }
5250 #endif /* ATH_DEBUG */
5251         ifp->if_flags &= ~IFF_OACTIVE;
5252         sc->sc_wd_timer = 0;
5253 }
5254
5255 /*
5256  * Disable the receive h/w in preparation for a reset.
5257  */
5258 static void
5259 ath_stoprecv(struct ath_softc *sc)
5260 {
5261 #define PA2DESC(_sc, _pa) \
5262         ((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
5263                 ((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
5264         struct ath_hal *ah = sc->sc_ah;
5265
5266         ath_hal_stoppcurecv(ah);        /* disable PCU */
5267         ath_hal_setrxfilter(ah, 0);     /* clear recv filter */
5268         ath_hal_stopdmarecv(ah);        /* disable DMA engine */
5269         DELAY(3000);                    /* 3ms is long enough for 1 frame */
5270 #ifdef ATH_DEBUG
5271         if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
5272                 struct ath_buf *bf;
5273                 u_int ix;
5274
5275                 kprintf("%s: rx queue %p, link %p\n", __func__,
5276                         (caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
5277                 ix = 0;
5278                 STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
5279                         struct ath_desc *ds = bf->bf_desc;
5280                         struct ath_rx_status *rs = &bf->bf_status.ds_rxstat;
5281                         HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
5282                                 bf->bf_daddr, PA2DESC(sc, ds->ds_link), rs);
5283                         if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
5284                                 ath_printrxbuf(sc, bf, ix, status == HAL_OK);
5285                         ix++;
5286                 }
5287         }
5288 #endif
5289         if (sc->sc_rxpending != NULL) {
5290                 m_freem(sc->sc_rxpending);
5291                 sc->sc_rxpending = NULL;
5292         }
5293         sc->sc_rxlink = NULL;           /* just in case */
5294 #undef PA2DESC
5295 }
5296
5297 /*
5298  * Enable the receive h/w following a reset.
5299  */
5300 static int
5301 ath_startrecv(struct ath_softc *sc)
5302 {
5303         struct ath_hal *ah = sc->sc_ah;
5304         struct ath_buf *bf;
5305
5306         sc->sc_rxlink = NULL;
5307         sc->sc_rxpending = NULL;
5308         STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
5309                 int error = ath_rxbuf_init(sc, bf);
5310                 if (error != 0) {
5311                         DPRINTF(sc, ATH_DEBUG_RECV,
5312                                 "%s: ath_rxbuf_init failed %d\n",
5313                                 __func__, error);
5314                         return error;
5315                 }
5316         }
5317
5318         bf = STAILQ_FIRST(&sc->sc_rxbuf);
5319         ath_hal_putrxbuf(ah, bf->bf_daddr);
5320         ath_hal_rxena(ah);              /* enable recv descriptors */
5321         ath_mode_init(sc);              /* set filters, etc. */
5322         ath_hal_startpcurecv(ah);       /* re-enable PCU/DMA engine */
5323         return 0;
5324 }
5325
5326 /* 
5327  * Update internal state after a channel change.
5328  */
5329 static void
5330 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
5331 {
5332         enum ieee80211_phymode mode;
5333
5334         /*
5335          * Change channels and update the h/w rate map
5336          * if we're switching; e.g. 11a to 11b/g.
5337          */
5338         mode = ieee80211_chan2mode(chan);
5339         if (mode != sc->sc_curmode)
5340                 ath_setcurmode(sc, mode);
5341         sc->sc_curchan = chan;
5342 }
5343
5344 /*
5345  * Set/change channels.  If the channel is really being changed,
5346  * it's done by reseting the chip.  To accomplish this we must
5347  * first cleanup any pending DMA, then restart stuff after a la
5348  * ath_init.
5349  */
5350 static int
5351 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
5352 {
5353         struct ifnet *ifp = sc->sc_ifp;
5354         struct ieee80211com *ic = ifp->if_l2com;
5355         struct ath_hal *ah = sc->sc_ah;
5356
5357         DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
5358             __func__, ieee80211_chan2ieee(ic, chan),
5359             chan->ic_freq, chan->ic_flags);
5360         if (chan != sc->sc_curchan) {
5361                 HAL_STATUS status;
5362                 /*
5363                  * To switch channels clear any pending DMA operations;
5364                  * wait long enough for the RX fifo to drain, reset the
5365                  * hardware at the new frequency, and then re-enable
5366                  * the relevant bits of the h/w.
5367                  */
5368                 ath_hal_intrset(ah, 0);         /* disable interrupts */
5369                 ath_draintxq(sc);               /* clear pending tx frames */
5370                 ath_stoprecv(sc);               /* turn off frame recv */
5371                 if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
5372                         if_printf(ifp, "%s: unable to reset "
5373                             "channel %u (%u MHz, flags 0x%x), hal status %u\n",
5374                             __func__, ieee80211_chan2ieee(ic, chan),
5375                             chan->ic_freq, chan->ic_flags, status);
5376                         return EIO;
5377                 }
5378                 sc->sc_diversity = ath_hal_getdiversity(ah);
5379
5380                 /*
5381                  * Re-enable rx framework.
5382                  */
5383                 if (ath_startrecv(sc) != 0) {
5384                         if_printf(ifp, "%s: unable to restart recv logic\n",
5385                             __func__);
5386                         return EIO;
5387                 }
5388
5389                 /*
5390                  * Change channels and update the h/w rate map
5391                  * if we're switching; e.g. 11a to 11b/g.
5392                  */
5393                 ath_chan_change(sc, chan);
5394
5395                 /*
5396                  * Re-enable interrupts.
5397                  */
5398                 ath_hal_intrset(ah, sc->sc_imask);
5399         }
5400         return 0;
5401 }
5402
5403 /*
5404  * Periodically recalibrate the PHY to account
5405  * for temperature/environment changes.
5406  */
5407 static void
5408 ath_calibrate_callout(void *arg)
5409 {
5410         struct ath_softc *sc = arg;
5411         struct ath_hal *ah = sc->sc_ah;
5412         struct ifnet *ifp = sc->sc_ifp;
5413         struct ieee80211com *ic = ifp->if_l2com;
5414         HAL_BOOL longCal, isCalDone;
5415         int nextcal;
5416
5417         wlan_serialize_enter();
5418
5419         if (ic->ic_flags & IEEE80211_F_SCAN)    /* defer, off channel */
5420                 goto restart;
5421         longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
5422         if (longCal) {
5423                 sc->sc_stats.ast_per_cal++;
5424                 sc->sc_lastlongcal = ticks;
5425                 if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
5426                         /*
5427                          * Rfgain is out of bounds, reset the chip
5428                          * to load new gain values.
5429                          */
5430                         DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5431                                 "%s: rfgain change\n", __func__);
5432                         sc->sc_stats.ast_per_rfgain++;
5433                         ath_reset(ifp);
5434                 }
5435                 /*
5436                  * If this long cal is after an idle period, then
5437                  * reset the data collection state so we start fresh.
5438                  */
5439                 if (sc->sc_resetcal) {
5440                         (void) ath_hal_calreset(ah, sc->sc_curchan);
5441                         sc->sc_lastcalreset = ticks;
5442                         sc->sc_resetcal = 0;
5443                 }
5444         }
5445         if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
5446                 if (longCal) {
5447                         /*
5448                          * Calibrate noise floor data again in case of change.
5449                          */
5450                         ath_hal_process_noisefloor(ah);
5451                 }
5452         } else {
5453                 DPRINTF(sc, ATH_DEBUG_ANY,
5454                         "%s: calibration of channel %u failed\n",
5455                         __func__, sc->sc_curchan->ic_freq);
5456                 sc->sc_stats.ast_per_calfail++;
5457         }
5458         if (!isCalDone) {
5459 restart:
5460                 /*
5461                  * Use a shorter interval to potentially collect multiple
5462                  * data samples required to complete calibration.  Once
5463                  * we're told the work is done we drop back to a longer
5464                  * interval between requests.  We're more aggressive doing
5465                  * work when operating as an AP to improve operation right
5466                  * after startup.
5467                  */
5468                 nextcal