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