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