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