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