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