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