]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/ath/if_ath.c
lookup the protection tx rate index in the rate tables
[FreeBSD/FreeBSD.git] / sys / dev / ath / if_ath.c
1 /*-
2  * Copyright (c) 2002-2005 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  * 3. Neither the names of the above-listed copyright holders nor the names
16  *    of any contributors may be used to endorse or promote products derived
17  *    from this software without specific prior written permission.
18  *
19  * Alternatively, this software may be distributed under the terms of the
20  * GNU General Public License ("GPL") version 2 as published by the Free
21  * Software Foundation.
22  *
23  * NO WARRANTY
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
27  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
28  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
29  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
32  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
34  * THE POSSIBILITY OF SUCH DAMAGES.
35  */
36
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39
40 /*
41  * Driver for the Atheros Wireless LAN controller.
42  *
43  * This software is derived from work of Atsushi Onoe; his contribution
44  * is greatly appreciated.
45  */
46
47 #include "opt_inet.h"
48
49 #include <sys/param.h>
50 #include <sys/systm.h> 
51 #include <sys/sysctl.h>
52 #include <sys/mbuf.h>   
53 #include <sys/malloc.h>
54 #include <sys/lock.h>
55 #include <sys/mutex.h>
56 #include <sys/kernel.h>
57 #include <sys/socket.h>
58 #include <sys/sockio.h>
59 #include <sys/errno.h>
60 #include <sys/callout.h>
61 #include <sys/bus.h>
62 #include <sys/endian.h>
63
64 #include <machine/bus.h>
65  
66 #include <net/if.h>
67 #include <net/if_dl.h>
68 #include <net/if_media.h>
69 #include <net/if_types.h>
70 #include <net/if_arp.h>
71 #include <net/ethernet.h>
72 #include <net/if_llc.h>
73
74 #include <net80211/ieee80211_var.h>
75
76 #include <net/bpf.h>
77
78 #ifdef INET
79 #include <netinet/in.h> 
80 #include <netinet/if_ether.h>
81 #endif
82
83 #define AR_DEBUG
84 #include <dev/ath/if_athvar.h>
85 #include <contrib/dev/ath/ah_desc.h>
86 #include <contrib/dev/ath/ah_devid.h>           /* XXX for softled */
87
88 /* unaligned little endian access */
89 #define LE_READ_2(p)                                                    \
90         ((u_int16_t)                                                    \
91          ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
92 #define LE_READ_4(p)                                                    \
93         ((u_int32_t)                                                    \
94          ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) | \
95           (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
96
97 enum {
98         ATH_LED_TX,
99         ATH_LED_RX,
100         ATH_LED_POLL,
101 };
102
103 static void     ath_init(void *);
104 static void     ath_stop_locked(struct ifnet *);
105 static void     ath_stop(struct ifnet *);
106 static void     ath_start(struct ifnet *);
107 static int      ath_reset(struct ifnet *);
108 static int      ath_media_change(struct ifnet *);
109 static void     ath_watchdog(struct ifnet *);
110 static int      ath_ioctl(struct ifnet *, u_long, caddr_t);
111 static void     ath_fatal_proc(void *, int);
112 static void     ath_rxorn_proc(void *, int);
113 static void     ath_bmiss_proc(void *, int);
114 static int      ath_key_alloc(struct ieee80211com *,
115                         const struct ieee80211_key *,
116                         ieee80211_keyix *, ieee80211_keyix *);
117 static int      ath_key_delete(struct ieee80211com *,
118                         const struct ieee80211_key *);
119 static int      ath_key_set(struct ieee80211com *, const struct ieee80211_key *,
120                         const u_int8_t mac[IEEE80211_ADDR_LEN]);
121 static void     ath_key_update_begin(struct ieee80211com *);
122 static void     ath_key_update_end(struct ieee80211com *);
123 static void     ath_mode_init(struct ath_softc *);
124 static void     ath_setslottime(struct ath_softc *);
125 static void     ath_updateslot(struct ifnet *);
126 static int      ath_beaconq_setup(struct ath_hal *);
127 static int      ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
128 static void     ath_beacon_setup(struct ath_softc *, struct ath_buf *);
129 static void     ath_beacon_proc(void *, int);
130 static void     ath_bstuck_proc(void *, int);
131 static void     ath_beacon_free(struct ath_softc *);
132 static void     ath_beacon_config(struct ath_softc *);
133 static void     ath_descdma_cleanup(struct ath_softc *sc,
134                         struct ath_descdma *, ath_bufhead *);
135 static int      ath_desc_alloc(struct ath_softc *);
136 static void     ath_desc_free(struct ath_softc *);
137 static struct ieee80211_node *ath_node_alloc(struct ieee80211_node_table *);
138 static void     ath_node_free(struct ieee80211_node *);
139 static u_int8_t ath_node_getrssi(const struct ieee80211_node *);
140 static int      ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
141 static void     ath_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
142                         struct ieee80211_node *ni,
143                         int subtype, int rssi, u_int32_t rstamp);
144 static void     ath_setdefantenna(struct ath_softc *, u_int);
145 static void     ath_rx_proc(void *, int);
146 static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
147 static int      ath_tx_setup(struct ath_softc *, int, int);
148 static int      ath_wme_update(struct ieee80211com *);
149 static void     ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
150 static void     ath_tx_cleanup(struct ath_softc *);
151 static int      ath_tx_start(struct ath_softc *, struct ieee80211_node *,
152                              struct ath_buf *, struct mbuf *);
153 static void     ath_tx_proc_q0(void *, int);
154 static void     ath_tx_proc_q0123(void *, int);
155 static void     ath_tx_proc(void *, int);
156 static int      ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
157 static void     ath_draintxq(struct ath_softc *);
158 static void     ath_stoprecv(struct ath_softc *);
159 static int      ath_startrecv(struct ath_softc *);
160 static void     ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
161 static void     ath_next_scan(void *);
162 static void     ath_calibrate(void *);
163 static int      ath_newstate(struct ieee80211com *, enum ieee80211_state, int);
164 static void     ath_setup_stationkey(struct ieee80211_node *);
165 static void     ath_newassoc(struct ieee80211_node *, int);
166 static int      ath_getchannels(struct ath_softc *, u_int cc,
167                         HAL_BOOL outdoor, HAL_BOOL xchanmode);
168 static void     ath_led_event(struct ath_softc *, int);
169 static void     ath_update_txpow(struct ath_softc *);
170
171 static int      ath_rate_setup(struct ath_softc *, u_int mode);
172 static void     ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
173
174 static void     ath_sysctlattach(struct ath_softc *);
175 static void     ath_bpfattach(struct ath_softc *);
176 static void     ath_announce(struct ath_softc *);
177
178 SYSCTL_DECL(_hw_ath);
179
180 /* XXX validate sysctl values */
181 static  int ath_dwelltime = 200;                /* 5 channels/second */
182 SYSCTL_INT(_hw_ath, OID_AUTO, dwell, CTLFLAG_RW, &ath_dwelltime,
183             0, "channel dwell time (ms) for AP/station scanning");
184 static  int ath_calinterval = 30;               /* calibrate every 30 secs */
185 SYSCTL_INT(_hw_ath, OID_AUTO, calibrate, CTLFLAG_RW, &ath_calinterval,
186             0, "chip calibration interval (secs)");
187 static  int ath_outdoor = AH_TRUE;              /* outdoor operation */
188 SYSCTL_INT(_hw_ath, OID_AUTO, outdoor, CTLFLAG_RD, &ath_outdoor,
189             0, "outdoor operation");
190 TUNABLE_INT("hw.ath.outdoor", &ath_outdoor);
191 static  int ath_xchanmode = AH_TRUE;            /* extended channel use */
192 SYSCTL_INT(_hw_ath, OID_AUTO, xchanmode, CTLFLAG_RD, &ath_xchanmode,
193             0, "extended channel mode");
194 TUNABLE_INT("hw.ath.xchanmode", &ath_xchanmode);
195 static  int ath_countrycode = CTRY_DEFAULT;     /* country code */
196 SYSCTL_INT(_hw_ath, OID_AUTO, countrycode, CTLFLAG_RD, &ath_countrycode,
197             0, "country code");
198 TUNABLE_INT("hw.ath.countrycode", &ath_countrycode);
199 static  int ath_regdomain = 0;                  /* regulatory domain */
200 SYSCTL_INT(_hw_ath, OID_AUTO, regdomain, CTLFLAG_RD, &ath_regdomain,
201             0, "regulatory domain");
202
203 static  int ath_rxbuf = ATH_RXBUF;              /* # rx buffers to allocate */
204 SYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RD, &ath_rxbuf,
205             0, "rx buffers allocated");
206 TUNABLE_INT("hw.ath.rxbuf", &ath_rxbuf);
207 static  int ath_txbuf = ATH_TXBUF;              /* # tx buffers to allocate */
208 SYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RD, &ath_txbuf,
209             0, "tx buffers allocated");
210 TUNABLE_INT("hw.ath.txbuf", &ath_txbuf);
211
212 #ifdef AR_DEBUG
213 static  int ath_debug = 0;
214 SYSCTL_INT(_hw_ath, OID_AUTO, debug, CTLFLAG_RW, &ath_debug,
215             0, "control debugging printfs");
216 TUNABLE_INT("hw.ath.debug", &ath_debug);
217 enum {
218         ATH_DEBUG_XMIT          = 0x00000001,   /* basic xmit operation */
219         ATH_DEBUG_XMIT_DESC     = 0x00000002,   /* xmit descriptors */
220         ATH_DEBUG_RECV          = 0x00000004,   /* basic recv operation */
221         ATH_DEBUG_RECV_DESC     = 0x00000008,   /* recv descriptors */
222         ATH_DEBUG_RATE          = 0x00000010,   /* rate control */
223         ATH_DEBUG_RESET         = 0x00000020,   /* reset processing */
224         ATH_DEBUG_MODE          = 0x00000040,   /* mode init/setup */
225         ATH_DEBUG_BEACON        = 0x00000080,   /* beacon handling */
226         ATH_DEBUG_WATCHDOG      = 0x00000100,   /* watchdog timeout */
227         ATH_DEBUG_INTR          = 0x00001000,   /* ISR */
228         ATH_DEBUG_TX_PROC       = 0x00002000,   /* tx ISR proc */
229         ATH_DEBUG_RX_PROC       = 0x00004000,   /* rx ISR proc */
230         ATH_DEBUG_BEACON_PROC   = 0x00008000,   /* beacon ISR proc */
231         ATH_DEBUG_CALIBRATE     = 0x00010000,   /* periodic calibration */
232         ATH_DEBUG_KEYCACHE      = 0x00020000,   /* key cache management */
233         ATH_DEBUG_STATE         = 0x00040000,   /* 802.11 state transitions */
234         ATH_DEBUG_NODE          = 0x00080000,   /* node management */
235         ATH_DEBUG_LED           = 0x00100000,   /* led management */
236         ATH_DEBUG_FATAL         = 0x80000000,   /* fatal errors */
237         ATH_DEBUG_ANY           = 0xffffffff
238 };
239 #define IFF_DUMPPKTS(sc, m) \
240         ((sc->sc_debug & (m)) || \
241             (sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
242 #define DPRINTF(sc, m, fmt, ...) do {                           \
243         if (sc->sc_debug & (m))                                 \
244                 printf(fmt, __VA_ARGS__);                       \
245 } while (0)
246 #define KEYPRINTF(sc, ix, hk, mac) do {                         \
247         if (sc->sc_debug & ATH_DEBUG_KEYCACHE)                  \
248                 ath_keyprint(__func__, ix, hk, mac);            \
249 } while (0)
250 static  void ath_printrxbuf(struct ath_buf *bf, int);
251 static  void ath_printtxbuf(struct ath_buf *bf, int);
252 #else
253 #define IFF_DUMPPKTS(sc, m) \
254         ((sc->sc_ifp->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
255 #define DPRINTF(m, fmt, ...)
256 #define KEYPRINTF(sc, k, ix, mac)
257 #endif
258
259 MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
260
261 int
262 ath_attach(u_int16_t devid, struct ath_softc *sc)
263 {
264         struct ifnet *ifp;
265         struct ieee80211com *ic = &sc->sc_ic;
266         struct ath_hal *ah = NULL;
267         HAL_STATUS status;
268         int error = 0, i;
269
270         DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
271
272         ifp = sc->sc_ifp = if_alloc(IFT_ETHER);
273         if (ifp == NULL) {
274                 device_printf(sc->sc_dev, "can not if_alloc()\n");
275                 error = ENOSPC;
276                 goto bad;
277         }
278
279         /* set these up early for if_printf use */
280         if_initname(ifp, device_get_name(sc->sc_dev),
281                 device_get_unit(sc->sc_dev));
282
283         ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, &status);
284         if (ah == NULL) {
285                 if_printf(ifp, "unable to attach hardware; HAL status %u\n",
286                         status);
287                 error = ENXIO;
288                 goto bad;
289         }
290         if (ah->ah_abi != HAL_ABI_VERSION) {
291                 if_printf(ifp, "HAL ABI mismatch detected "
292                         "(HAL:0x%x != driver:0x%x)\n",
293                         ah->ah_abi, HAL_ABI_VERSION);
294                 error = ENXIO;
295                 goto bad;
296         }
297         sc->sc_ah = ah;
298         sc->sc_invalid = 0;     /* ready to go, enable interrupt handling */
299
300         /*
301          * Check if the MAC has multi-rate retry support.
302          * We do this by trying to setup a fake extended
303          * descriptor.  MAC's that don't have support will
304          * return false w/o doing anything.  MAC's that do
305          * support it will return true w/o doing anything.
306          */
307         sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
308
309         /*
310          * Check if the device has hardware counters for PHY
311          * errors.  If so we need to enable the MIB interrupt
312          * so we can act on stat triggers.
313          */
314         if (ath_hal_hwphycounters(ah))
315                 sc->sc_needmib = 1;
316
317         /*
318          * Get the hardware key cache size.
319          */
320         sc->sc_keymax = ath_hal_keycachesize(ah);
321         if (sc->sc_keymax > ATH_KEYMAX) {
322                 if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
323                         ATH_KEYMAX, sc->sc_keymax);
324                 sc->sc_keymax = ATH_KEYMAX;
325         }
326         /*
327          * Reset the key cache since some parts do not
328          * reset the contents on initial power up.
329          */
330         for (i = 0; i < sc->sc_keymax; i++)
331                 ath_hal_keyreset(ah, i);
332         /*
333          * Mark key cache slots associated with global keys
334          * as in use.  If we knew TKIP was not to be used we
335          * could leave the +32, +64, and +32+64 slots free.
336          * XXX only for splitmic.
337          */
338         for (i = 0; i < IEEE80211_WEP_NKID; i++) {
339                 setbit(sc->sc_keymap, i);
340                 setbit(sc->sc_keymap, i+32);
341                 setbit(sc->sc_keymap, i+64);
342                 setbit(sc->sc_keymap, i+32+64);
343         }
344
345         /*
346          * Collect the channel list using the default country
347          * code and including outdoor channels.  The 802.11 layer
348          * is resposible for filtering this list based on settings
349          * like the phy mode.
350          */
351         error = ath_getchannels(sc, ath_countrycode,
352                         ath_outdoor, ath_xchanmode);
353         if (error != 0)
354                 goto bad;
355
356         /*
357          * Setup rate tables for all potential media types.
358          */
359         ath_rate_setup(sc, IEEE80211_MODE_11A);
360         ath_rate_setup(sc, IEEE80211_MODE_11B);
361         ath_rate_setup(sc, IEEE80211_MODE_11G);
362         ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
363         ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
364         /* NB: setup here so ath_rate_update is happy */
365         ath_setcurmode(sc, IEEE80211_MODE_11A);
366
367         /*
368          * Allocate tx+rx descriptors and populate the lists.
369          */
370         error = ath_desc_alloc(sc);
371         if (error != 0) {
372                 if_printf(ifp, "failed to allocate descriptors: %d\n", error);
373                 goto bad;
374         }
375         callout_init(&sc->sc_scan_ch, debug_mpsafenet ? CALLOUT_MPSAFE : 0);
376         callout_init(&sc->sc_cal_ch, CALLOUT_MPSAFE);
377
378         ATH_TXBUF_LOCK_INIT(sc);
379
380         TASK_INIT(&sc->sc_rxtask, 0, ath_rx_proc, sc);
381         TASK_INIT(&sc->sc_rxorntask, 0, ath_rxorn_proc, sc);
382         TASK_INIT(&sc->sc_fataltask, 0, ath_fatal_proc, sc);
383         TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
384         TASK_INIT(&sc->sc_bstucktask, 0, ath_bstuck_proc, sc);
385
386         /*
387          * Allocate hardware transmit queues: one queue for
388          * beacon frames and one data queue for each QoS
389          * priority.  Note that the hal handles reseting
390          * these queues at the needed time.
391          *
392          * XXX PS-Poll
393          */
394         sc->sc_bhalq = ath_beaconq_setup(ah);
395         if (sc->sc_bhalq == (u_int) -1) {
396                 if_printf(ifp, "unable to setup a beacon xmit queue!\n");
397                 error = EIO;
398                 goto bad2;
399         }
400         sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
401         if (sc->sc_cabq == NULL) {
402                 if_printf(ifp, "unable to setup CAB xmit queue!\n");
403                 error = EIO;
404                 goto bad2;
405         }
406         /* NB: insure BK queue is the lowest priority h/w queue */
407         if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
408                 if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
409                         ieee80211_wme_acnames[WME_AC_BK]);
410                 error = EIO;
411                 goto bad2;
412         }
413         if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
414             !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
415             !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
416                 /* 
417                  * Not enough hardware tx queues to properly do WME;
418                  * just punt and assign them all to the same h/w queue.
419                  * We could do a better job of this if, for example,
420                  * we allocate queues when we switch from station to
421                  * AP mode.
422                  */
423                 if (sc->sc_ac2q[WME_AC_VI] != NULL)
424                         ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
425                 if (sc->sc_ac2q[WME_AC_BE] != NULL)
426                         ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
427                 sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
428                 sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
429                 sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
430         }
431
432         /* 
433          * Special case certain configurations.  Note the
434          * CAB queue is handled by these specially so don't
435          * include them when checking the txq setup mask.
436          */
437         switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
438         case 0x01:
439                 TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
440                 break;
441         case 0x0f:
442                 TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
443                 break;
444         default:
445                 TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
446                 break;
447         }
448
449         /*
450          * Setup rate control.  Some rate control modules
451          * call back to change the anntena state so expose
452          * the necessary entry points.
453          * XXX maybe belongs in struct ath_ratectrl?
454          */
455         sc->sc_setdefantenna = ath_setdefantenna;
456         sc->sc_rc = ath_rate_attach(sc);
457         if (sc->sc_rc == NULL) {
458                 error = EIO;
459                 goto bad2;
460         }
461
462         sc->sc_blinking = 0;
463         sc->sc_ledstate = 1;
464         sc->sc_ledon = 0;                       /* low true */
465         sc->sc_ledidle = (2700*hz)/1000;        /* 2.7sec */
466         callout_init(&sc->sc_ledtimer, CALLOUT_MPSAFE);
467         /*
468          * Auto-enable soft led processing for IBM cards and for
469          * 5211 minipci cards.  Users can also manually enable/disable
470          * support with a sysctl.
471          */
472         sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
473         if (sc->sc_softled) {
474                 ath_hal_gpioCfgOutput(ah, sc->sc_ledpin);
475                 ath_hal_gpioset(ah, sc->sc_ledpin, !sc->sc_ledon);
476         }
477
478         ifp->if_softc = sc;
479         ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
480         ifp->if_start = ath_start;
481         ifp->if_watchdog = ath_watchdog;
482         ifp->if_ioctl = ath_ioctl;
483         ifp->if_init = ath_init;
484         IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
485         ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
486         IFQ_SET_READY(&ifp->if_snd);
487
488         ic->ic_ifp = ifp;
489         ic->ic_reset = ath_reset;
490         ic->ic_newassoc = ath_newassoc;
491         ic->ic_updateslot = ath_updateslot;
492         ic->ic_wme.wme_update = ath_wme_update;
493         /* XXX not right but it's not used anywhere important */
494         ic->ic_phytype = IEEE80211_T_OFDM;
495         ic->ic_opmode = IEEE80211_M_STA;
496         ic->ic_caps =
497                   IEEE80211_C_IBSS              /* ibss, nee adhoc, mode */
498                 | IEEE80211_C_HOSTAP            /* hostap mode */
499                 | IEEE80211_C_MONITOR           /* monitor mode */
500                 | IEEE80211_C_SHPREAMBLE        /* short preamble supported */
501                 | IEEE80211_C_SHSLOT            /* short slot time supported */
502                 | IEEE80211_C_WPA               /* capable of WPA1+WPA2 */
503                 ;
504         /*
505          * Query the hal to figure out h/w crypto support.
506          */
507         if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
508                 ic->ic_caps |= IEEE80211_C_WEP;
509         if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
510                 ic->ic_caps |= IEEE80211_C_AES;
511         if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
512                 ic->ic_caps |= IEEE80211_C_AES_CCM;
513         if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
514                 ic->ic_caps |= IEEE80211_C_CKIP;
515         if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
516                 ic->ic_caps |= IEEE80211_C_TKIP;
517                 /*
518                  * Check if h/w does the MIC and/or whether the
519                  * separate key cache entries are required to
520                  * handle both tx+rx MIC keys.
521                  */
522                 if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
523                         ic->ic_caps |= IEEE80211_C_TKIPMIC;
524                 if (ath_hal_tkipsplit(ah))
525                         sc->sc_splitmic = 1;
526         }
527         sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
528         sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
529         /*
530          * TPC support can be done either with a global cap or
531          * per-packet support.  The latter is not available on
532          * all parts.  We're a bit pedantic here as all parts
533          * support a global cap.
534          */
535         if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
536                 ic->ic_caps |= IEEE80211_C_TXPMGT;
537
538         /*
539          * Mark WME capability only if we have sufficient
540          * hardware queues to do proper priority scheduling.
541          */
542         if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
543                 ic->ic_caps |= IEEE80211_C_WME;
544         /*
545          * Check for misc other capabilities.
546          */
547         if (ath_hal_hasbursting(ah))
548                 ic->ic_caps |= IEEE80211_C_BURST;
549
550         /*
551          * Indicate we need the 802.11 header padded to a
552          * 32-bit boundary for 4-address and QoS frames.
553          */
554         ic->ic_flags |= IEEE80211_F_DATAPAD;
555
556         /*
557          * Query the hal about antenna support.
558          */
559         sc->sc_defant = ath_hal_getdefantenna(ah);
560
561         /*
562          * Not all chips have the VEOL support we want to
563          * use with IBSS beacons; check here for it.
564          */
565         sc->sc_hasveol = ath_hal_hasveol(ah);
566
567         /* get mac address from hardware */
568         ath_hal_getmac(ah, ic->ic_myaddr);
569
570         /* call MI attach routine. */
571         ieee80211_ifattach(ic);
572         /* override default methods */
573         ic->ic_node_alloc = ath_node_alloc;
574         sc->sc_node_free = ic->ic_node_free;
575         ic->ic_node_free = ath_node_free;
576         ic->ic_node_getrssi = ath_node_getrssi;
577         sc->sc_recv_mgmt = ic->ic_recv_mgmt;
578         ic->ic_recv_mgmt = ath_recv_mgmt;
579         sc->sc_newstate = ic->ic_newstate;
580         ic->ic_newstate = ath_newstate;
581         ic->ic_crypto.cs_max_keyix = sc->sc_keymax;
582         ic->ic_crypto.cs_key_alloc = ath_key_alloc;
583         ic->ic_crypto.cs_key_delete = ath_key_delete;
584         ic->ic_crypto.cs_key_set = ath_key_set;
585         ic->ic_crypto.cs_key_update_begin = ath_key_update_begin;
586         ic->ic_crypto.cs_key_update_end = ath_key_update_end;
587         /* complete initialization */
588         ieee80211_media_init(ic, ath_media_change, ieee80211_media_status);
589
590         ath_bpfattach(sc);
591         /*
592          * Setup dynamic sysctl's now that country code and
593          * regdomain are available from the hal.
594          */
595         ath_sysctlattach(sc);
596
597         if (bootverbose)
598                 ieee80211_announce(ic);
599         ath_announce(sc);
600         return 0;
601 bad2:
602         ath_tx_cleanup(sc);
603         ath_desc_free(sc);
604 bad:
605         if (ah)
606                 ath_hal_detach(ah);
607         if (ifp != NULL)
608                 if_free(ifp);
609         sc->sc_invalid = 1;
610         return error;
611 }
612
613 int
614 ath_detach(struct ath_softc *sc)
615 {
616         struct ifnet *ifp = sc->sc_ifp;
617
618         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
619                 __func__, ifp->if_flags);
620
621         ath_stop(ifp);
622         bpfdetach(ifp);
623         /* 
624          * NB: the order of these is important:
625          * o call the 802.11 layer before detaching the hal to
626          *   insure callbacks into the driver to delete global
627          *   key cache entries can be handled
628          * o reclaim the tx queue data structures after calling
629          *   the 802.11 layer as we'll get called back to reclaim
630          *   node state and potentially want to use them
631          * o to cleanup the tx queues the hal is called, so detach
632          *   it last
633          * Other than that, it's straightforward...
634          */
635         ieee80211_ifdetach(&sc->sc_ic);
636         ath_rate_detach(sc->sc_rc);
637         ath_desc_free(sc);
638         ath_tx_cleanup(sc);
639         ath_hal_detach(sc->sc_ah);
640         if_free(ifp);
641
642         return 0;
643 }
644
645 void
646 ath_suspend(struct ath_softc *sc)
647 {
648         struct ifnet *ifp = sc->sc_ifp;
649
650         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
651                 __func__, ifp->if_flags);
652
653         ath_stop(ifp);
654 }
655
656 void
657 ath_resume(struct ath_softc *sc)
658 {
659         struct ifnet *ifp = sc->sc_ifp;
660
661         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
662                 __func__, ifp->if_flags);
663
664         if (ifp->if_flags & IFF_UP) {
665                 ath_init(sc);
666                 if (ifp->if_drv_flags & IFF_DRV_RUNNING)
667                         ath_start(ifp);
668         }
669         if (sc->sc_softled) {
670                 ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
671                 ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
672         }
673 }
674
675 void
676 ath_shutdown(struct ath_softc *sc)
677 {
678         struct ifnet *ifp = sc->sc_ifp;
679
680         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
681                 __func__, ifp->if_flags);
682
683         ath_stop(ifp);
684 }
685
686 /*
687  * Interrupt handler.  Most of the actual processing is deferred.
688  */
689 void
690 ath_intr(void *arg)
691 {
692         struct ath_softc *sc = arg;
693         struct ifnet *ifp = sc->sc_ifp;
694         struct ath_hal *ah = sc->sc_ah;
695         HAL_INT status;
696
697         if (sc->sc_invalid) {
698                 /*
699                  * The hardware is not ready/present, don't touch anything.
700                  * Note this can happen early on if the IRQ is shared.
701                  */
702                 DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
703                 return;
704         }
705         if (!ath_hal_intrpend(ah))              /* shared irq, not for us */
706                 return;
707         if (!((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags &
708             IFF_DRV_RUNNING))) {
709                 DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
710                         __func__, ifp->if_flags);
711                 ath_hal_getisr(ah, &status);    /* clear ISR */
712                 ath_hal_intrset(ah, 0);         /* disable further intr's */
713                 return;
714         }
715         /*
716          * Figure out the reason(s) for the interrupt.  Note
717          * that the hal returns a pseudo-ISR that may include
718          * bits we haven't explicitly enabled so we mask the
719          * value to insure we only process bits we requested.
720          */
721         ath_hal_getisr(ah, &status);            /* NB: clears ISR too */
722         DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
723         status &= sc->sc_imask;                 /* discard unasked for bits */
724         if (status & HAL_INT_FATAL) {
725                 /*
726                  * Fatal errors are unrecoverable.  Typically
727                  * these are caused by DMA errors.  Unfortunately
728                  * the exact reason is not (presently) returned
729                  * by the hal.
730                  */
731                 sc->sc_stats.ast_hardware++;
732                 ath_hal_intrset(ah, 0);         /* disable intr's until reset */
733                 taskqueue_enqueue(taskqueue_swi, &sc->sc_fataltask);
734         } else if (status & HAL_INT_RXORN) {
735                 sc->sc_stats.ast_rxorn++;
736                 ath_hal_intrset(ah, 0);         /* disable intr's until reset */
737                 taskqueue_enqueue(taskqueue_swi, &sc->sc_rxorntask);
738         } else {
739                 if (status & HAL_INT_SWBA) {
740                         /*
741                          * Software beacon alert--time to send a beacon.
742                          * Handle beacon transmission directly; deferring
743                          * this is too slow to meet timing constraints
744                          * under load.
745                          */
746                         ath_beacon_proc(sc, 0);
747                 }
748                 if (status & HAL_INT_RXEOL) {
749                         /*
750                          * NB: the hardware should re-read the link when
751                          *     RXE bit is written, but it doesn't work at
752                          *     least on older hardware revs.
753                          */
754                         sc->sc_stats.ast_rxeol++;
755                         sc->sc_rxlink = NULL;
756                 }
757                 if (status & HAL_INT_TXURN) {
758                         sc->sc_stats.ast_txurn++;
759                         /* bump tx trigger level */
760                         ath_hal_updatetxtriglevel(ah, AH_TRUE);
761                 }
762                 if (status & HAL_INT_RX)
763                         taskqueue_enqueue(taskqueue_swi, &sc->sc_rxtask);
764                 if (status & HAL_INT_TX)
765                         taskqueue_enqueue(taskqueue_swi, &sc->sc_txtask);
766                 if (status & HAL_INT_BMISS) {
767                         sc->sc_stats.ast_bmiss++;
768                         taskqueue_enqueue(taskqueue_swi, &sc->sc_bmisstask);
769                 }
770                 if (status & HAL_INT_MIB) {
771                         sc->sc_stats.ast_mib++;
772                         /*
773                          * Disable interrupts until we service the MIB
774                          * interrupt; otherwise it will continue to fire.
775                          */
776                         ath_hal_intrset(ah, 0);
777                         /*
778                          * Let the hal handle the event.  We assume it will
779                          * clear whatever condition caused the interrupt.
780                          */
781                         ath_hal_mibevent(ah,
782                                 &ATH_NODE(sc->sc_ic.ic_bss)->an_halstats);
783                         ath_hal_intrset(ah, sc->sc_imask);
784                 }
785         }
786 }
787
788 static void
789 ath_fatal_proc(void *arg, int pending)
790 {
791         struct ath_softc *sc = arg;
792         struct ifnet *ifp = sc->sc_ifp;
793
794         if_printf(ifp, "hardware error; resetting\n");
795         ath_reset(ifp);
796 }
797
798 static void
799 ath_rxorn_proc(void *arg, int pending)
800 {
801         struct ath_softc *sc = arg;
802         struct ifnet *ifp = sc->sc_ifp;
803
804         if_printf(ifp, "rx FIFO overrun; resetting\n");
805         ath_reset(ifp);
806 }
807
808 static void
809 ath_bmiss_proc(void *arg, int pending)
810 {
811         struct ath_softc *sc = arg;
812         struct ieee80211com *ic = &sc->sc_ic;
813
814         DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
815         KASSERT(ic->ic_opmode == IEEE80211_M_STA,
816                 ("unexpect operating mode %u", ic->ic_opmode));
817         if (ic->ic_state == IEEE80211_S_RUN) {
818                 /*
819                  * Rather than go directly to scan state, try to
820                  * reassociate first.  If that fails then the state
821                  * machine will drop us into scanning after timing
822                  * out waiting for a probe response.
823                  */
824                 NET_LOCK_GIANT();
825                 ieee80211_new_state(ic, IEEE80211_S_ASSOC, -1);
826                 NET_UNLOCK_GIANT();
827         }
828 }
829
830 static u_int
831 ath_chan2flags(struct ieee80211com *ic, struct ieee80211_channel *chan)
832 {
833 #define N(a)    (sizeof(a) / sizeof(a[0]))
834         static const u_int modeflags[] = {
835                 0,                      /* IEEE80211_MODE_AUTO */
836                 CHANNEL_A,              /* IEEE80211_MODE_11A */
837                 CHANNEL_B,              /* IEEE80211_MODE_11B */
838                 CHANNEL_PUREG,          /* IEEE80211_MODE_11G */
839                 0,                      /* IEEE80211_MODE_FH */
840                 CHANNEL_T,              /* IEEE80211_MODE_TURBO_A */
841                 CHANNEL_108G            /* IEEE80211_MODE_TURBO_G */
842         };
843         enum ieee80211_phymode mode = ieee80211_chan2mode(ic, chan);
844
845         KASSERT(mode < N(modeflags), ("unexpected phy mode %u", mode));
846         KASSERT(modeflags[mode] != 0, ("mode %u undefined", mode));
847         return modeflags[mode];
848 #undef N
849 }
850
851 static void
852 ath_init(void *arg)
853 {
854         struct ath_softc *sc = (struct ath_softc *) arg;
855         struct ieee80211com *ic = &sc->sc_ic;
856         struct ifnet *ifp = sc->sc_ifp;
857         struct ath_hal *ah = sc->sc_ah;
858         HAL_STATUS status;
859
860         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
861                 __func__, ifp->if_flags);
862
863         ATH_LOCK(sc);
864         /*
865          * Stop anything previously setup.  This is safe
866          * whether this is the first time through or not.
867          */
868         ath_stop_locked(ifp);
869
870         /*
871          * The basic interface to setting the hardware in a good
872          * state is ``reset''.  On return the hardware is known to
873          * be powered up and with interrupts disabled.  This must
874          * be followed by initialization of the appropriate bits
875          * and then setup of the interrupt mask.
876          */
877         sc->sc_curchan.channel = ic->ic_curchan->ic_freq;
878         sc->sc_curchan.channelFlags = ath_chan2flags(ic, ic->ic_curchan);
879         if (!ath_hal_reset(ah, ic->ic_opmode, &sc->sc_curchan, AH_FALSE, &status)) {
880                 if_printf(ifp, "unable to reset hardware; hal status %u\n",
881                         status);
882                 goto done;
883         }
884
885         /*
886          * This is needed only to setup initial state
887          * but it's best done after a reset.
888          */
889         ath_update_txpow(sc);
890         /*
891          * Likewise this is set during reset so update
892          * state cached in the driver.
893          */
894         sc->sc_diversity = ath_hal_getdiversity(ah);
895
896         /*
897          * Setup the hardware after reset: the key cache
898          * is filled as needed and the receive engine is
899          * set going.  Frame transmit is handled entirely
900          * in the frame output path; there's nothing to do
901          * here except setup the interrupt mask.
902          */
903         if (ath_startrecv(sc) != 0) {
904                 if_printf(ifp, "unable to start recv logic\n");
905                 goto done;
906         }
907
908         /*
909          * Enable interrupts.
910          */
911         sc->sc_imask = HAL_INT_RX | HAL_INT_TX
912                   | HAL_INT_RXEOL | HAL_INT_RXORN
913                   | HAL_INT_FATAL | HAL_INT_GLOBAL;
914         /*
915          * Enable MIB interrupts when there are hardware phy counters.
916          * Note we only do this (at the moment) for station mode.
917          */
918         if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
919                 sc->sc_imask |= HAL_INT_MIB;
920         ath_hal_intrset(ah, sc->sc_imask);
921
922         ifp->if_drv_flags |= IFF_DRV_RUNNING;
923         ic->ic_state = IEEE80211_S_INIT;
924
925         /*
926          * The hardware should be ready to go now so it's safe
927          * to kick the 802.11 state machine as it's likely to
928          * immediately call back to us to send mgmt frames.
929          */
930         ath_chan_change(sc, ic->ic_curchan);
931         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
932                 if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
933                         ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
934         } else
935                 ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
936 done:
937         ATH_UNLOCK(sc);
938 }
939
940 static void
941 ath_stop_locked(struct ifnet *ifp)
942 {
943         struct ath_softc *sc = ifp->if_softc;
944         struct ieee80211com *ic = &sc->sc_ic;
945         struct ath_hal *ah = sc->sc_ah;
946
947         DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
948                 __func__, sc->sc_invalid, ifp->if_flags);
949
950         ATH_LOCK_ASSERT(sc);
951         if (ifp->if_drv_flags & IFF_DRV_RUNNING) {
952                 /*
953                  * Shutdown the hardware and driver:
954                  *    reset 802.11 state machine
955                  *    turn off timers
956                  *    disable interrupts
957                  *    turn off the radio
958                  *    clear transmit machinery
959                  *    clear receive machinery
960                  *    drain and release tx queues
961                  *    reclaim beacon resources
962                  *    power down hardware
963                  *
964                  * Note that some of this work is not possible if the
965                  * hardware is gone (invalid).
966                  */
967                 ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
968                 ifp->if_drv_flags &= ~IFF_DRV_RUNNING;
969                 ifp->if_timer = 0;
970                 if (!sc->sc_invalid) {
971                         if (sc->sc_softled) {
972                                 callout_stop(&sc->sc_ledtimer);
973                                 ath_hal_gpioset(ah, sc->sc_ledpin,
974                                         !sc->sc_ledon);
975                                 sc->sc_blinking = 0;
976                         }
977                         ath_hal_intrset(ah, 0);
978                 }
979                 ath_draintxq(sc);
980                 if (!sc->sc_invalid) {
981                         ath_stoprecv(sc);
982                         ath_hal_phydisable(ah);
983                 } else
984                         sc->sc_rxlink = NULL;
985                 IFQ_DRV_PURGE(&ifp->if_snd);
986                 ath_beacon_free(sc);
987         }
988 }
989
990 static void
991 ath_stop(struct ifnet *ifp)
992 {
993         struct ath_softc *sc = ifp->if_softc;
994
995         ATH_LOCK(sc);
996         ath_stop_locked(ifp);
997         if (!sc->sc_invalid) {
998                 /*
999                  * Set the chip in full sleep mode.  Note that we are
1000                  * careful to do this only when bringing the interface
1001                  * completely to a stop.  When the chip is in this state
1002                  * it must be carefully woken up or references to
1003                  * registers in the PCI clock domain may freeze the bus
1004                  * (and system).  This varies by chip and is mostly an
1005                  * issue with newer parts that go to sleep more quickly.
1006                  */
1007                 ath_hal_setpower(sc->sc_ah, HAL_PM_FULL_SLEEP, 0);
1008         }
1009         ATH_UNLOCK(sc);
1010 }
1011
1012 /*
1013  * Reset the hardware w/o losing operational state.  This is
1014  * basically a more efficient way of doing ath_stop, ath_init,
1015  * followed by state transitions to the current 802.11
1016  * operational state.  Used to recover from various errors and
1017  * to reset or reload hardware state.
1018  */
1019 static int
1020 ath_reset(struct ifnet *ifp)
1021 {
1022         struct ath_softc *sc = ifp->if_softc;
1023         struct ieee80211com *ic = &sc->sc_ic;
1024         struct ath_hal *ah = sc->sc_ah;
1025         struct ieee80211_channel *c;
1026         HAL_STATUS status;
1027
1028         /*
1029          * Convert to a HAL channel description with the flags
1030          * constrained to reflect the current operating mode.
1031          */
1032         c = ic->ic_curchan;
1033         sc->sc_curchan.channel = c->ic_freq;
1034         sc->sc_curchan.channelFlags = ath_chan2flags(ic, c);
1035
1036         ath_hal_intrset(ah, 0);         /* disable interrupts */
1037         ath_draintxq(sc);               /* stop xmit side */
1038         ath_stoprecv(sc);               /* stop recv side */
1039         /* NB: indicate channel change so we do a full reset */
1040         if (!ath_hal_reset(ah, ic->ic_opmode, &sc->sc_curchan, AH_TRUE, &status))
1041                 if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
1042                         __func__, status);
1043         ath_update_txpow(sc);           /* update tx power state */
1044         sc->sc_diversity = ath_hal_getdiversity(ah);
1045         if (ath_startrecv(sc) != 0)     /* restart recv */
1046                 if_printf(ifp, "%s: unable to start recv logic\n", __func__);
1047         /*
1048          * We may be doing a reset in response to an ioctl
1049          * that changes the channel so update any state that
1050          * might change as a result.
1051          */
1052         ath_chan_change(sc, c);
1053         if (ic->ic_state == IEEE80211_S_RUN)
1054                 ath_beacon_config(sc);  /* restart beacons */
1055         ath_hal_intrset(ah, sc->sc_imask);
1056
1057         ath_start(ifp);                 /* restart xmit */
1058         return 0;
1059 }
1060
1061 static void
1062 ath_start(struct ifnet *ifp)
1063 {
1064         struct ath_softc *sc = ifp->if_softc;
1065         struct ath_hal *ah = sc->sc_ah;
1066         struct ieee80211com *ic = &sc->sc_ic;
1067         struct ieee80211_node *ni;
1068         struct ath_buf *bf;
1069         struct mbuf *m;
1070         struct ieee80211_frame *wh;
1071         struct ether_header *eh;
1072
1073         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
1074                 return;
1075         for (;;) {
1076                 /*
1077                  * Grab a TX buffer and associated resources.
1078                  */
1079                 ATH_TXBUF_LOCK(sc);
1080                 bf = STAILQ_FIRST(&sc->sc_txbuf);
1081                 if (bf != NULL)
1082                         STAILQ_REMOVE_HEAD(&sc->sc_txbuf, bf_list);
1083                 ATH_TXBUF_UNLOCK(sc);
1084                 if (bf == NULL) {
1085                         DPRINTF(sc, ATH_DEBUG_ANY, "%s: out of xmit buffers\n",
1086                                 __func__);
1087                         sc->sc_stats.ast_tx_qstop++;
1088                         ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1089                         break;
1090                 }
1091                 /*
1092                  * Poll the management queue for frames; they
1093                  * have priority over normal data frames.
1094                  */
1095                 IF_DEQUEUE(&ic->ic_mgtq, m);
1096                 if (m == NULL) {
1097                         /*
1098                          * No data frames go out unless we're associated.
1099                          */
1100                         if (ic->ic_state != IEEE80211_S_RUN) {
1101                                 DPRINTF(sc, ATH_DEBUG_ANY,
1102                                         "%s: ignore data packet, state %u\n",
1103                                         __func__, ic->ic_state);
1104                                 sc->sc_stats.ast_tx_discard++;
1105                                 ATH_TXBUF_LOCK(sc);
1106                                 STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1107                                 ATH_TXBUF_UNLOCK(sc);
1108                                 break;
1109                         }
1110                         IFQ_DRV_DEQUEUE(&ifp->if_snd, m);       /* XXX: LOCK */
1111                         if (m == NULL) {
1112                                 ATH_TXBUF_LOCK(sc);
1113                                 STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1114                                 ATH_TXBUF_UNLOCK(sc);
1115                                 break;
1116                         }
1117                         /* 
1118                          * Find the node for the destination so we can do
1119                          * things like power save and fast frames aggregation.
1120                          */
1121                         if (m->m_len < sizeof(struct ether_header) &&
1122                            (m = m_pullup(m, sizeof(struct ether_header))) == NULL) {
1123                                 ic->ic_stats.is_tx_nobuf++;     /* XXX */
1124                                 ni = NULL;
1125                                 goto bad;
1126                         }
1127                         eh = mtod(m, struct ether_header *);
1128                         ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1129                         if (ni == NULL) {
1130                                 /* NB: ieee80211_find_txnode does stat+msg */
1131                                 m_freem(m);
1132                                 goto bad;
1133                         }
1134                         if ((ni->ni_flags & IEEE80211_NODE_PWR_MGT) &&
1135                             (m->m_flags & M_PWR_SAV) == 0) {
1136                                 /*
1137                                  * Station in power save mode; pass the frame
1138                                  * to the 802.11 layer and continue.  We'll get
1139                                  * the frame back when the time is right.
1140                                  */
1141                                 ieee80211_pwrsave(ic, ni, m);
1142                                 goto reclaim;
1143                         }
1144                         /* calculate priority so we can find the tx queue */
1145                         if (ieee80211_classify(ic, m, ni)) {
1146                                 DPRINTF(sc, ATH_DEBUG_XMIT,
1147                                         "%s: discard, classification failure\n",
1148                                         __func__);
1149                                 m_freem(m);
1150                                 goto bad;
1151                         }
1152                         ifp->if_opackets++;
1153                         BPF_MTAP(ifp, m);
1154                         /*
1155                          * Encapsulate the packet in prep for transmission.
1156                          */
1157                         m = ieee80211_encap(ic, m, ni);
1158                         if (m == NULL) {
1159                                 DPRINTF(sc, ATH_DEBUG_ANY,
1160                                         "%s: encapsulation failure\n",
1161                                         __func__);
1162                                 sc->sc_stats.ast_tx_encap++;
1163                                 goto bad;
1164                         }
1165                 } else {
1166                         /*
1167                          * Hack!  The referenced node pointer is in the
1168                          * rcvif field of the packet header.  This is
1169                          * placed there by ieee80211_mgmt_output because
1170                          * we need to hold the reference with the frame
1171                          * and there's no other way (other than packet
1172                          * tags which we consider too expensive to use)
1173                          * to pass it along.
1174                          */
1175                         ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1176                         m->m_pkthdr.rcvif = NULL;
1177
1178                         wh = mtod(m, struct ieee80211_frame *);
1179                         if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
1180                             IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
1181                                 /* fill time stamp */
1182                                 u_int64_t tsf;
1183                                 u_int32_t *tstamp;
1184
1185                                 tsf = ath_hal_gettsf64(ah);
1186                                 /* XXX: adjust 100us delay to xmit */
1187                                 tsf += 100;
1188                                 tstamp = (u_int32_t *)&wh[1];
1189                                 tstamp[0] = htole32(tsf & 0xffffffff);
1190                                 tstamp[1] = htole32(tsf >> 32);
1191                         }
1192                         sc->sc_stats.ast_tx_mgmt++;
1193                 }
1194
1195                 if (ath_tx_start(sc, ni, bf, m)) {
1196         bad:
1197                         ifp->if_oerrors++;
1198         reclaim:
1199                         ATH_TXBUF_LOCK(sc);
1200                         STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1201                         ATH_TXBUF_UNLOCK(sc);
1202                         if (ni != NULL)
1203                                 ieee80211_free_node(ni);
1204                         continue;
1205                 }
1206
1207                 sc->sc_tx_timer = 5;
1208                 ifp->if_timer = 1;
1209         }
1210 }
1211
1212 static int
1213 ath_media_change(struct ifnet *ifp)
1214 {
1215 #define IS_UP(ifp) \
1216         ((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
1217         int error;
1218
1219         error = ieee80211_media_change(ifp);
1220         if (error == ENETRESET) {
1221                 if (IS_UP(ifp))
1222                         ath_init(ifp->if_softc);        /* XXX lose error */
1223                 error = 0;
1224         }
1225         return error;
1226 #undef IS_UP
1227 }
1228
1229 #ifdef AR_DEBUG
1230 static void
1231 ath_keyprint(const char *tag, u_int ix,
1232         const HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1233 {
1234         static const char *ciphers[] = {
1235                 "WEP",
1236                 "AES-OCB",
1237                 "AES-CCM",
1238                 "CKIP",
1239                 "TKIP",
1240                 "CLR",
1241         };
1242         int i, n;
1243
1244         printf("%s: [%02u] %-7s ", tag, ix, ciphers[hk->kv_type]);
1245         for (i = 0, n = hk->kv_len; i < n; i++)
1246                 printf("%02x", hk->kv_val[i]);
1247         printf(" mac %s", ether_sprintf(mac));
1248         if (hk->kv_type == HAL_CIPHER_TKIP) {
1249                 printf(" mic ");
1250                 for (i = 0; i < sizeof(hk->kv_mic); i++)
1251                         printf("%02x", hk->kv_mic[i]);
1252         }
1253         printf("\n");
1254 }
1255 #endif
1256
1257 /*
1258  * Set a TKIP key into the hardware.  This handles the
1259  * potential distribution of key state to multiple key
1260  * cache slots for TKIP.
1261  */
1262 static int
1263 ath_keyset_tkip(struct ath_softc *sc, const struct ieee80211_key *k,
1264         HAL_KEYVAL *hk, const u_int8_t mac[IEEE80211_ADDR_LEN])
1265 {
1266 #define IEEE80211_KEY_XR        (IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV)
1267         static const u_int8_t zerobssid[IEEE80211_ADDR_LEN];
1268         struct ath_hal *ah = sc->sc_ah;
1269
1270         KASSERT(k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP,
1271                 ("got a non-TKIP key, cipher %u", k->wk_cipher->ic_cipher));
1272         KASSERT(sc->sc_splitmic, ("key cache !split"));
1273         if ((k->wk_flags & IEEE80211_KEY_XR) == IEEE80211_KEY_XR) {
1274                 /*
1275                  * TX key goes at first index, RX key at the rx index.
1276                  * The hal handles the MIC keys at index+64.
1277                  */
1278                 memcpy(hk->kv_mic, k->wk_txmic, sizeof(hk->kv_mic));
1279                 KEYPRINTF(sc, k->wk_keyix, hk, zerobssid);
1280                 if (!ath_hal_keyset(ah, k->wk_keyix, hk, zerobssid))
1281                         return 0;
1282
1283                 memcpy(hk->kv_mic, k->wk_rxmic, sizeof(hk->kv_mic));
1284                 KEYPRINTF(sc, k->wk_keyix+32, hk, mac);
1285                 /* XXX delete tx key on failure? */
1286                 return ath_hal_keyset(ah, k->wk_keyix+32, hk, mac);
1287         } else if (k->wk_flags & IEEE80211_KEY_XR) {
1288                 /*
1289                  * TX/RX key goes at first index.
1290                  * The hal handles the MIC keys are index+64.
1291                  */
1292                 memcpy(hk->kv_mic, k->wk_flags & IEEE80211_KEY_XMIT ?
1293                         k->wk_txmic : k->wk_rxmic, sizeof(hk->kv_mic));
1294                 KEYPRINTF(sc, k->wk_keyix, hk, mac);
1295                 return ath_hal_keyset(ah, k->wk_keyix, hk, mac);
1296         }
1297         return 0;
1298 #undef IEEE80211_KEY_XR
1299 }
1300
1301 /*
1302  * Set a net80211 key into the hardware.  This handles the
1303  * potential distribution of key state to multiple key
1304  * cache slots for TKIP with hardware MIC support.
1305  */
1306 static int
1307 ath_keyset(struct ath_softc *sc, const struct ieee80211_key *k,
1308         const u_int8_t mac0[IEEE80211_ADDR_LEN],
1309         struct ieee80211_node *bss)
1310 {
1311 #define N(a)    (sizeof(a)/sizeof(a[0]))
1312         static const u_int8_t ciphermap[] = {
1313                 HAL_CIPHER_WEP,         /* IEEE80211_CIPHER_WEP */
1314                 HAL_CIPHER_TKIP,        /* IEEE80211_CIPHER_TKIP */
1315                 HAL_CIPHER_AES_OCB,     /* IEEE80211_CIPHER_AES_OCB */
1316                 HAL_CIPHER_AES_CCM,     /* IEEE80211_CIPHER_AES_CCM */
1317                 (u_int8_t) -1,          /* 4 is not allocated */
1318                 HAL_CIPHER_CKIP,        /* IEEE80211_CIPHER_CKIP */
1319                 HAL_CIPHER_CLR,         /* IEEE80211_CIPHER_NONE */
1320         };
1321         struct ath_hal *ah = sc->sc_ah;
1322         const struct ieee80211_cipher *cip = k->wk_cipher;
1323         u_int8_t gmac[IEEE80211_ADDR_LEN];
1324         const u_int8_t *mac;
1325         HAL_KEYVAL hk;
1326
1327         memset(&hk, 0, sizeof(hk));
1328         /*
1329          * Software crypto uses a "clear key" so non-crypto
1330          * state kept in the key cache are maintained and
1331          * so that rx frames have an entry to match.
1332          */
1333         if ((k->wk_flags & IEEE80211_KEY_SWCRYPT) == 0) {
1334                 KASSERT(cip->ic_cipher < N(ciphermap),
1335                         ("invalid cipher type %u", cip->ic_cipher));
1336                 hk.kv_type = ciphermap[cip->ic_cipher];
1337                 hk.kv_len = k->wk_keylen;
1338                 memcpy(hk.kv_val, k->wk_key, k->wk_keylen);
1339         } else
1340                 hk.kv_type = HAL_CIPHER_CLR;
1341
1342         if ((k->wk_flags & IEEE80211_KEY_GROUP) && sc->sc_mcastkey) {
1343                 /*
1344                  * Group keys on hardware that supports multicast frame
1345                  * key search use a mac that is the sender's address with
1346                  * the high bit set instead of the app-specified address.
1347                  */
1348                 IEEE80211_ADDR_COPY(gmac, bss->ni_macaddr);
1349                 gmac[0] |= 0x80;
1350                 mac = gmac;
1351         } else
1352                 mac = mac0;
1353
1354         if (hk.kv_type == HAL_CIPHER_TKIP &&
1355             (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 &&
1356             sc->sc_splitmic) {
1357                 return ath_keyset_tkip(sc, k, &hk, mac);
1358         } else {
1359                 KEYPRINTF(sc, k->wk_keyix, &hk, mac);
1360                 return ath_hal_keyset(ah, k->wk_keyix, &hk, mac);
1361         }
1362 #undef N
1363 }
1364
1365 /*
1366  * Allocate tx/rx key slots for TKIP.  We allocate two slots for
1367  * each key, one for decrypt/encrypt and the other for the MIC.
1368  */
1369 static u_int16_t
1370 key_alloc_2pair(struct ath_softc *sc,
1371         ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
1372 {
1373 #define N(a)    (sizeof(a)/sizeof(a[0]))
1374         u_int i, keyix;
1375
1376         KASSERT(sc->sc_splitmic, ("key cache !split"));
1377         /* XXX could optimize */
1378         for (i = 0; i < N(sc->sc_keymap)/4; i++) {
1379                 u_int8_t b = sc->sc_keymap[i];
1380                 if (b != 0xff) {
1381                         /*
1382                          * One or more slots in this byte are free.
1383                          */
1384                         keyix = i*NBBY;
1385                         while (b & 1) {
1386                 again:
1387                                 keyix++;
1388                                 b >>= 1;
1389                         }
1390                         /* XXX IEEE80211_KEY_XMIT | IEEE80211_KEY_RECV */
1391                         if (isset(sc->sc_keymap, keyix+32) ||
1392                             isset(sc->sc_keymap, keyix+64) ||
1393                             isset(sc->sc_keymap, keyix+32+64)) {
1394                                 /* full pair unavailable */
1395                                 /* XXX statistic */
1396                                 if (keyix == (i+1)*NBBY) {
1397                                         /* no slots were appropriate, advance */
1398                                         continue;
1399                                 }
1400                                 goto again;
1401                         }
1402                         setbit(sc->sc_keymap, keyix);
1403                         setbit(sc->sc_keymap, keyix+64);
1404                         setbit(sc->sc_keymap, keyix+32);
1405                         setbit(sc->sc_keymap, keyix+32+64);
1406                         DPRINTF(sc, ATH_DEBUG_KEYCACHE,
1407                                 "%s: key pair %u,%u %u,%u\n",
1408                                 __func__, keyix, keyix+64,
1409                                 keyix+32, keyix+32+64);
1410                         *txkeyix = keyix;
1411                         *rxkeyix = keyix+32;
1412                         return 1;
1413                 }
1414         }
1415         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of pair space\n", __func__);
1416         return 0;
1417 #undef N
1418 }
1419
1420 /*
1421  * Allocate a single key cache slot.
1422  */
1423 static int
1424 key_alloc_single(struct ath_softc *sc,
1425         ieee80211_keyix *txkeyix, ieee80211_keyix *rxkeyix)
1426 {
1427 #define N(a)    (sizeof(a)/sizeof(a[0]))
1428         u_int i, keyix;
1429
1430         /* XXX try i,i+32,i+64,i+32+64 to minimize key pair conflicts */
1431         for (i = 0; i < N(sc->sc_keymap); i++) {
1432                 u_int8_t b = sc->sc_keymap[i];
1433                 if (b != 0xff) {
1434                         /*
1435                          * One or more slots are free.
1436                          */
1437                         keyix = i*NBBY;
1438                         while (b & 1)
1439                                 keyix++, b >>= 1;
1440                         setbit(sc->sc_keymap, keyix);
1441                         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: key %u\n",
1442                                 __func__, keyix);
1443                         *txkeyix = *rxkeyix = keyix;
1444                         return 1;
1445                 }
1446         }
1447         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: out of space\n", __func__);
1448         return 0;
1449 #undef N
1450 }
1451
1452 /*
1453  * Allocate one or more key cache slots for a uniacst key.  The
1454  * key itself is needed only to identify the cipher.  For hardware
1455  * TKIP with split cipher+MIC keys we allocate two key cache slot
1456  * pairs so that we can setup separate TX and RX MIC keys.  Note
1457  * that the MIC key for a TKIP key at slot i is assumed by the
1458  * hardware to be at slot i+64.  This limits TKIP keys to the first
1459  * 64 entries.
1460  */
1461 static int
1462 ath_key_alloc(struct ieee80211com *ic, const struct ieee80211_key *k,
1463         ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
1464 {
1465         struct ath_softc *sc = ic->ic_ifp->if_softc;
1466
1467         /*
1468          * Group key allocation must be handled specially for
1469          * parts that do not support multicast key cache search
1470          * functionality.  For those parts the key id must match
1471          * the h/w key index so lookups find the right key.  On
1472          * parts w/ the key search facility we install the sender's
1473          * mac address (with the high bit set) and let the hardware
1474          * find the key w/o using the key id.  This is preferred as
1475          * it permits us to support multiple users for adhoc and/or
1476          * multi-station operation.
1477          */
1478         if ((k->wk_flags & IEEE80211_KEY_GROUP) && !sc->sc_mcastkey) {
1479                 if (!(&ic->ic_nw_keys[0] <= k &&
1480                       k < &ic->ic_nw_keys[IEEE80211_WEP_NKID])) {
1481                         /* should not happen */
1482                         DPRINTF(sc, ATH_DEBUG_KEYCACHE,
1483                                 "%s: bogus group key\n", __func__);
1484                         return 0;
1485                 }
1486                 /*
1487                  * XXX we pre-allocate the global keys so
1488                  * have no way to check if they've already been allocated.
1489                  */
1490                 *keyix = *rxkeyix = k - ic->ic_nw_keys;
1491                 return 1;
1492         }
1493
1494         /*
1495          * We allocate two pair for TKIP when using the h/w to do
1496          * the MIC.  For everything else, including software crypto,
1497          * we allocate a single entry.  Note that s/w crypto requires
1498          * a pass-through slot on the 5211 and 5212.  The 5210 does
1499          * not support pass-through cache entries and we map all
1500          * those requests to slot 0.
1501          */
1502         if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
1503                 return key_alloc_single(sc, keyix, rxkeyix);
1504         } else if (k->wk_cipher->ic_cipher == IEEE80211_CIPHER_TKIP &&
1505             (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic) {
1506                 return key_alloc_2pair(sc, keyix, rxkeyix);
1507         } else {
1508                 return key_alloc_single(sc, keyix, rxkeyix);
1509         }
1510 }
1511
1512 /*
1513  * Delete an entry in the key cache allocated by ath_key_alloc.
1514  */
1515 static int
1516 ath_key_delete(struct ieee80211com *ic, const struct ieee80211_key *k)
1517 {
1518         struct ath_softc *sc = ic->ic_ifp->if_softc;
1519         struct ath_hal *ah = sc->sc_ah;
1520         const struct ieee80211_cipher *cip = k->wk_cipher;
1521         u_int keyix = k->wk_keyix;
1522
1523         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s: delete key %u\n", __func__, keyix);
1524
1525         ath_hal_keyreset(ah, keyix);
1526         /*
1527          * Handle split tx/rx keying required for TKIP with h/w MIC.
1528          */
1529         if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
1530             (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 && sc->sc_splitmic)
1531                 ath_hal_keyreset(ah, keyix+32);         /* RX key */
1532         if (keyix >= IEEE80211_WEP_NKID) {
1533                 /*
1534                  * Don't touch keymap entries for global keys so
1535                  * they are never considered for dynamic allocation.
1536                  */
1537                 clrbit(sc->sc_keymap, keyix);
1538                 if (cip->ic_cipher == IEEE80211_CIPHER_TKIP &&
1539                     (k->wk_flags & IEEE80211_KEY_SWMIC) == 0 &&
1540                     sc->sc_splitmic) {
1541                         clrbit(sc->sc_keymap, keyix+64);        /* TX key MIC */
1542                         clrbit(sc->sc_keymap, keyix+32);        /* RX key */
1543                         clrbit(sc->sc_keymap, keyix+32+64);     /* RX key MIC */
1544                 }
1545         }
1546         return 1;
1547 }
1548
1549 /*
1550  * Set the key cache contents for the specified key.  Key cache
1551  * slot(s) must already have been allocated by ath_key_alloc.
1552  */
1553 static int
1554 ath_key_set(struct ieee80211com *ic, const struct ieee80211_key *k,
1555         const u_int8_t mac[IEEE80211_ADDR_LEN])
1556 {
1557         struct ath_softc *sc = ic->ic_ifp->if_softc;
1558
1559         return ath_keyset(sc, k, mac, ic->ic_bss);
1560 }
1561
1562 /*
1563  * Block/unblock tx+rx processing while a key change is done.
1564  * We assume the caller serializes key management operations
1565  * so we only need to worry about synchronization with other
1566  * uses that originate in the driver.
1567  */
1568 static void
1569 ath_key_update_begin(struct ieee80211com *ic)
1570 {
1571         struct ifnet *ifp = ic->ic_ifp;
1572         struct ath_softc *sc = ifp->if_softc;
1573
1574         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
1575 #if 0
1576         tasklet_disable(&sc->sc_rxtq);
1577 #endif
1578         IF_LOCK(&ifp->if_snd);          /* NB: doesn't block mgmt frames */
1579 }
1580
1581 static void
1582 ath_key_update_end(struct ieee80211com *ic)
1583 {
1584         struct ifnet *ifp = ic->ic_ifp;
1585         struct ath_softc *sc = ifp->if_softc;
1586
1587         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
1588         IF_UNLOCK(&ifp->if_snd);
1589 #if 0
1590         tasklet_enable(&sc->sc_rxtq);
1591 #endif
1592 }
1593
1594 /*
1595  * Calculate the receive filter according to the
1596  * operating mode and state:
1597  *
1598  * o always accept unicast, broadcast, and multicast traffic
1599  * o maintain current state of phy error reception (the hal
1600  *   may enable phy error frames for noise immunity work)
1601  * o probe request frames are accepted only when operating in
1602  *   hostap, adhoc, or monitor modes
1603  * o enable promiscuous mode according to the interface state
1604  * o accept beacons:
1605  *   - when operating in adhoc mode so the 802.11 layer creates
1606  *     node table entries for peers,
1607  *   - when operating in station mode for collecting rssi data when
1608  *     the station is otherwise quiet, or
1609  *   - when scanning
1610  */
1611 static u_int32_t
1612 ath_calcrxfilter(struct ath_softc *sc, enum ieee80211_state state)
1613 {
1614         struct ieee80211com *ic = &sc->sc_ic;
1615         struct ath_hal *ah = sc->sc_ah;
1616         struct ifnet *ifp = sc->sc_ifp;
1617         u_int32_t rfilt;
1618
1619         rfilt = (ath_hal_getrxfilter(ah) & HAL_RX_FILTER_PHYERR)
1620               | HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
1621         if (ic->ic_opmode != IEEE80211_M_STA)
1622                 rfilt |= HAL_RX_FILTER_PROBEREQ;
1623         if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
1624             (ifp->if_flags & IFF_PROMISC))
1625                 rfilt |= HAL_RX_FILTER_PROM;
1626         if (ic->ic_opmode == IEEE80211_M_STA ||
1627             ic->ic_opmode == IEEE80211_M_IBSS ||
1628             state == IEEE80211_S_SCAN)
1629                 rfilt |= HAL_RX_FILTER_BEACON;
1630         return rfilt;
1631 }
1632
1633 static void
1634 ath_mode_init(struct ath_softc *sc)
1635 {
1636         struct ieee80211com *ic = &sc->sc_ic;
1637         struct ath_hal *ah = sc->sc_ah;
1638         struct ifnet *ifp = sc->sc_ifp;
1639         u_int32_t rfilt, mfilt[2], val;
1640         u_int8_t pos;
1641         struct ifmultiaddr *ifma;
1642
1643         /* configure rx filter */
1644         rfilt = ath_calcrxfilter(sc, ic->ic_state);
1645         ath_hal_setrxfilter(ah, rfilt);
1646
1647         /* configure operational mode */
1648         ath_hal_setopmode(ah);
1649
1650         /*
1651          * Handle any link-level address change.  Note that we only
1652          * need to force ic_myaddr; any other addresses are handled
1653          * as a byproduct of the ifnet code marking the interface
1654          * down then up.
1655          *
1656          * XXX should get from lladdr instead of arpcom but that's more work
1657          */
1658         IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
1659         ath_hal_setmac(ah, ic->ic_myaddr);
1660
1661         /* calculate and install multicast filter */
1662         if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
1663                 mfilt[0] = mfilt[1] = 0;
1664                 IF_ADDR_LOCK(ifp);
1665                 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
1666                         caddr_t dl;
1667
1668                         /* calculate XOR of eight 6bit values */
1669                         dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
1670                         val = LE_READ_4(dl + 0);
1671                         pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
1672                         val = LE_READ_4(dl + 3);
1673                         pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
1674                         pos &= 0x3f;
1675                         mfilt[pos / 32] |= (1 << (pos % 32));
1676                 }
1677                 IF_ADDR_UNLOCK(ifp);
1678         } else {
1679                 mfilt[0] = mfilt[1] = ~0;
1680         }
1681         ath_hal_setmcastfilter(ah, mfilt[0], mfilt[1]);
1682         DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x, MC filter %08x:%08x\n",
1683                 __func__, rfilt, mfilt[0], mfilt[1]);
1684 }
1685
1686 /*
1687  * Set the slot time based on the current setting.
1688  */
1689 static void
1690 ath_setslottime(struct ath_softc *sc)
1691 {
1692         struct ieee80211com *ic = &sc->sc_ic;
1693         struct ath_hal *ah = sc->sc_ah;
1694
1695         if (ic->ic_flags & IEEE80211_F_SHSLOT)
1696                 ath_hal_setslottime(ah, HAL_SLOT_TIME_9);
1697         else
1698                 ath_hal_setslottime(ah, HAL_SLOT_TIME_20);
1699         sc->sc_updateslot = OK;
1700 }
1701
1702 /*
1703  * Callback from the 802.11 layer to update the
1704  * slot time based on the current setting.
1705  */
1706 static void
1707 ath_updateslot(struct ifnet *ifp)
1708 {
1709         struct ath_softc *sc = ifp->if_softc;
1710         struct ieee80211com *ic = &sc->sc_ic;
1711
1712         /*
1713          * When not coordinating the BSS, change the hardware
1714          * immediately.  For other operation we defer the change
1715          * until beacon updates have propagated to the stations.
1716          */
1717         if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1718                 sc->sc_updateslot = UPDATE;
1719         else
1720                 ath_setslottime(sc);
1721 }
1722
1723 /*
1724  * Setup a h/w transmit queue for beacons.
1725  */
1726 static int
1727 ath_beaconq_setup(struct ath_hal *ah)
1728 {
1729         HAL_TXQ_INFO qi;
1730
1731         memset(&qi, 0, sizeof(qi));
1732         qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
1733         qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
1734         qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
1735         /* NB: for dynamic turbo, don't enable any other interrupts */
1736         qi.tqi_qflags = TXQ_FLAG_TXDESCINT_ENABLE;
1737         return ath_hal_setuptxqueue(ah, HAL_TX_QUEUE_BEACON, &qi);
1738 }
1739
1740 /*
1741  * Setup the transmit queue parameters for the beacon queue.
1742  */
1743 static int
1744 ath_beaconq_config(struct ath_softc *sc)
1745 {
1746 #define ATH_EXPONENT_TO_VALUE(v)        ((1<<(v))-1)
1747         struct ieee80211com *ic = &sc->sc_ic;
1748         struct ath_hal *ah = sc->sc_ah;
1749         HAL_TXQ_INFO qi;
1750
1751         ath_hal_gettxqueueprops(ah, sc->sc_bhalq, &qi);
1752         if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1753                 /*
1754                  * Always burst out beacon and CAB traffic.
1755                  */
1756                 qi.tqi_aifs = ATH_BEACON_AIFS_DEFAULT;
1757                 qi.tqi_cwmin = ATH_BEACON_CWMIN_DEFAULT;
1758                 qi.tqi_cwmax = ATH_BEACON_CWMAX_DEFAULT;
1759         } else {
1760                 struct wmeParams *wmep =
1761                         &ic->ic_wme.wme_chanParams.cap_wmeParams[WME_AC_BE];
1762                 /*
1763                  * Adhoc mode; important thing is to use 2x cwmin.
1764                  */
1765                 qi.tqi_aifs = wmep->wmep_aifsn;
1766                 qi.tqi_cwmin = 2*ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
1767                 qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
1768         }
1769
1770         if (!ath_hal_settxqueueprops(ah, sc->sc_bhalq, &qi)) {
1771                 device_printf(sc->sc_dev, "unable to update parameters for "
1772                         "beacon hardware queue!\n");
1773                 return 0;
1774         } else {
1775                 ath_hal_resettxqueue(ah, sc->sc_bhalq); /* push to h/w */
1776                 return 1;
1777         }
1778 #undef ATH_EXPONENT_TO_VALUE
1779 }
1780
1781 /*
1782  * Allocate and setup an initial beacon frame.
1783  */
1784 static int
1785 ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
1786 {
1787         struct ieee80211com *ic = ni->ni_ic;
1788         struct ath_buf *bf;
1789         struct mbuf *m;
1790         int error;
1791
1792         bf = STAILQ_FIRST(&sc->sc_bbuf);
1793         if (bf == NULL) {
1794                 DPRINTF(sc, ATH_DEBUG_BEACON, "%s: no dma buffers\n", __func__);
1795                 sc->sc_stats.ast_be_nombuf++;   /* XXX */
1796                 return ENOMEM;                  /* XXX */
1797         }
1798         /*
1799          * NB: the beacon data buffer must be 32-bit aligned;
1800          * we assume the mbuf routines will return us something
1801          * with this alignment (perhaps should assert).
1802          */
1803         m = ieee80211_beacon_alloc(ic, ni, &sc->sc_boff);
1804         if (m == NULL) {
1805                 DPRINTF(sc, ATH_DEBUG_BEACON, "%s: cannot get mbuf\n",
1806                         __func__);
1807                 sc->sc_stats.ast_be_nombuf++;
1808                 return ENOMEM;
1809         }
1810         error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
1811                                      bf->bf_segs, &bf->bf_nseg,
1812                                      BUS_DMA_NOWAIT);
1813         if (error == 0) {
1814                 bf->bf_m = m;
1815                 bf->bf_node = ieee80211_ref_node(ni);
1816         } else {
1817                 m_freem(m);
1818         }
1819         return error;
1820 }
1821
1822 /*
1823  * Setup the beacon frame for transmit.
1824  */
1825 static void
1826 ath_beacon_setup(struct ath_softc *sc, struct ath_buf *bf)
1827 {
1828 #define USE_SHPREAMBLE(_ic) \
1829         (((_ic)->ic_flags & (IEEE80211_F_SHPREAMBLE | IEEE80211_F_USEBARKER))\
1830                 == IEEE80211_F_SHPREAMBLE)
1831         struct ieee80211_node *ni = bf->bf_node;
1832         struct ieee80211com *ic = ni->ni_ic;
1833         struct mbuf *m = bf->bf_m;
1834         struct ath_hal *ah = sc->sc_ah;
1835         struct ath_desc *ds;
1836         int flags, antenna;
1837         const HAL_RATE_TABLE *rt;
1838         u_int8_t rix, rate;
1839
1840         DPRINTF(sc, ATH_DEBUG_BEACON, "%s: m %p len %u\n",
1841                 __func__, m, m->m_len);
1842
1843         /* setup descriptors */
1844         ds = bf->bf_desc;
1845
1846         flags = HAL_TXDESC_NOACK;
1847         if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol) {
1848                 ds->ds_link = bf->bf_daddr;     /* self-linked */
1849                 flags |= HAL_TXDESC_VEOL;
1850                 /*
1851                  * Let hardware handle antenna switching.
1852                  */
1853                 antenna = sc->sc_txantenna;
1854         } else {
1855                 ds->ds_link = 0;
1856                 /*
1857                  * Switch antenna every 4 beacons.
1858                  * XXX assumes two antenna
1859                  */
1860                 antenna = (sc->sc_stats.ast_be_xmit & 4 ? 2 : 1);
1861         }
1862
1863         KASSERT(bf->bf_nseg == 1,
1864                 ("multi-segment beacon frame; nseg %u", bf->bf_nseg));
1865         ds->ds_data = bf->bf_segs[0].ds_addr;
1866         /*
1867          * Calculate rate code.
1868          * XXX everything at min xmit rate
1869          */
1870         rix = sc->sc_minrateix;
1871         rt = sc->sc_currates;
1872         rate = rt->info[rix].rateCode;
1873         if (USE_SHPREAMBLE(ic))
1874                 rate |= rt->info[rix].shortPreamble;
1875         ath_hal_setuptxdesc(ah, ds
1876                 , m->m_len + IEEE80211_CRC_LEN  /* frame length */
1877                 , sizeof(struct ieee80211_frame)/* header length */
1878                 , HAL_PKT_TYPE_BEACON           /* Atheros packet type */
1879                 , ni->ni_txpower                /* txpower XXX */
1880                 , rate, 1                       /* series 0 rate/tries */
1881                 , HAL_TXKEYIX_INVALID           /* no encryption */
1882                 , antenna                       /* antenna mode */
1883                 , flags                         /* no ack, veol for beacons */
1884                 , 0                             /* rts/cts rate */
1885                 , 0                             /* rts/cts duration */
1886         );
1887         /* NB: beacon's BufLen must be a multiple of 4 bytes */
1888         ath_hal_filltxdesc(ah, ds
1889                 , roundup(m->m_len, 4)          /* buffer length */
1890                 , AH_TRUE                       /* first segment */
1891                 , AH_TRUE                       /* last segment */
1892                 , ds                            /* first descriptor */
1893         );
1894 #undef USE_SHPREAMBLE
1895 }
1896
1897 /*
1898  * Transmit a beacon frame at SWBA.  Dynamic updates to the
1899  * frame contents are done as needed and the slot time is
1900  * also adjusted based on current state.
1901  */
1902 static void
1903 ath_beacon_proc(void *arg, int pending)
1904 {
1905         struct ath_softc *sc = arg;
1906         struct ath_buf *bf = STAILQ_FIRST(&sc->sc_bbuf);
1907         struct ieee80211_node *ni = bf->bf_node;
1908         struct ieee80211com *ic = ni->ni_ic;
1909         struct ath_hal *ah = sc->sc_ah;
1910         struct mbuf *m;
1911         int ncabq, error, otherant;
1912
1913         DPRINTF(sc, ATH_DEBUG_BEACON_PROC, "%s: pending %u\n",
1914                 __func__, pending);
1915
1916         if (ic->ic_opmode == IEEE80211_M_STA ||
1917             ic->ic_opmode == IEEE80211_M_MONITOR ||
1918             bf == NULL || bf->bf_m == NULL) {
1919                 DPRINTF(sc, ATH_DEBUG_ANY, "%s: ic_flags=%x bf=%p bf_m=%p\n",
1920                         __func__, ic->ic_flags, bf, bf ? bf->bf_m : NULL);
1921                 return;
1922         }
1923         /*
1924          * Check if the previous beacon has gone out.  If
1925          * not don't don't try to post another, skip this
1926          * period and wait for the next.  Missed beacons
1927          * indicate a problem and should not occur.  If we
1928          * miss too many consecutive beacons reset the device.
1929          */
1930         if (ath_hal_numtxpending(ah, sc->sc_bhalq) != 0) {
1931                 sc->sc_bmisscount++;
1932                 DPRINTF(sc, ATH_DEBUG_BEACON_PROC,
1933                         "%s: missed %u consecutive beacons\n",
1934                         __func__, sc->sc_bmisscount);
1935                 if (sc->sc_bmisscount > 3)              /* NB: 3 is a guess */
1936                         taskqueue_enqueue(taskqueue_swi, &sc->sc_bstucktask);
1937                 return;
1938         }
1939         if (sc->sc_bmisscount != 0) {
1940                 DPRINTF(sc, ATH_DEBUG_BEACON,
1941                         "%s: resume beacon xmit after %u misses\n",
1942                         __func__, sc->sc_bmisscount);
1943                 sc->sc_bmisscount = 0;
1944         }
1945
1946         /*
1947          * Update dynamic beacon contents.  If this returns
1948          * non-zero then we need to remap the memory because
1949          * the beacon frame changed size (probably because
1950          * of the TIM bitmap).
1951          */
1952         m = bf->bf_m;
1953         ncabq = ath_hal_numtxpending(ah, sc->sc_cabq->axq_qnum);
1954         if (ieee80211_beacon_update(ic, bf->bf_node, &sc->sc_boff, m, ncabq)) {
1955                 /* XXX too conservative? */
1956                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
1957                 error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m,
1958                                              bf->bf_segs, &bf->bf_nseg,
1959                                              BUS_DMA_NOWAIT);
1960                 if (error != 0) {
1961                         if_printf(ic->ic_ifp,
1962                             "%s: bus_dmamap_load_mbuf_sg failed, error %u\n",
1963                             __func__, error);
1964                         return;
1965                 }
1966         }
1967
1968         /*
1969          * Handle slot time change when a non-ERP station joins/leaves
1970          * an 11g network.  The 802.11 layer notifies us via callback,
1971          * we mark updateslot, then wait one beacon before effecting
1972          * the change.  This gives associated stations at least one
1973          * beacon interval to note the state change.
1974          */
1975         /* XXX locking */
1976         if (sc->sc_updateslot == UPDATE)
1977                 sc->sc_updateslot = COMMIT;     /* commit next beacon */
1978         else if (sc->sc_updateslot == COMMIT)
1979                 ath_setslottime(sc);            /* commit change to h/w */
1980
1981         /*
1982          * Check recent per-antenna transmit statistics and flip
1983          * the default antenna if noticeably more frames went out
1984          * on the non-default antenna.
1985          * XXX assumes 2 anntenae
1986          */
1987         otherant = sc->sc_defant & 1 ? 2 : 1;
1988         if (sc->sc_ant_tx[otherant] > sc->sc_ant_tx[sc->sc_defant] + 2)
1989                 ath_setdefantenna(sc, otherant);
1990         sc->sc_ant_tx[1] = sc->sc_ant_tx[2] = 0;
1991
1992         /*
1993          * Construct tx descriptor.
1994          */
1995         ath_beacon_setup(sc, bf);
1996
1997         /*
1998          * Stop any current dma and put the new frame on the queue.
1999          * This should never fail since we check above that no frames
2000          * are still pending on the queue.
2001          */
2002         if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
2003                 DPRINTF(sc, ATH_DEBUG_ANY,
2004                         "%s: beacon queue %u did not stop?\n",
2005                         __func__, sc->sc_bhalq);
2006         }
2007         bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
2008
2009         /*
2010          * Enable the CAB queue before the beacon queue to
2011          * insure cab frames are triggered by this beacon.
2012          */
2013         if (sc->sc_boff.bo_tim[4] & 1)          /* NB: only at DTIM */
2014                 ath_hal_txstart(ah, sc->sc_cabq->axq_qnum);
2015         ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
2016         ath_hal_txstart(ah, sc->sc_bhalq);
2017         DPRINTF(sc, ATH_DEBUG_BEACON_PROC,
2018                 "%s: TXDP[%u] = %p (%p)\n", __func__,
2019                 sc->sc_bhalq, (caddr_t)bf->bf_daddr, bf->bf_desc);
2020
2021         sc->sc_stats.ast_be_xmit++;
2022 }
2023
2024 /*
2025  * Reset the hardware after detecting beacons have stopped.
2026  */
2027 static void
2028 ath_bstuck_proc(void *arg, int pending)
2029 {
2030         struct ath_softc *sc = arg;
2031         struct ifnet *ifp = sc->sc_ifp;
2032
2033         if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
2034                 sc->sc_bmisscount);
2035         ath_reset(ifp);
2036 }
2037
2038 /*
2039  * Reclaim beacon resources.
2040  */
2041 static void
2042 ath_beacon_free(struct ath_softc *sc)
2043 {
2044         struct ath_buf *bf;
2045
2046         STAILQ_FOREACH(bf, &sc->sc_bbuf, bf_list) {
2047                 if (bf->bf_m != NULL) {
2048                         bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2049                         m_freem(bf->bf_m);
2050                         bf->bf_m = NULL;
2051                 }
2052                 if (bf->bf_node != NULL) {
2053                         ieee80211_free_node(bf->bf_node);
2054                         bf->bf_node = NULL;
2055                 }
2056         }
2057 }
2058
2059 /*
2060  * Configure the beacon and sleep timers.
2061  *
2062  * When operating as an AP this resets the TSF and sets
2063  * up the hardware to notify us when we need to issue beacons.
2064  *
2065  * When operating in station mode this sets up the beacon
2066  * timers according to the timestamp of the last received
2067  * beacon and the current TSF, configures PCF and DTIM
2068  * handling, programs the sleep registers so the hardware
2069  * will wakeup in time to receive beacons, and configures
2070  * the beacon miss handling so we'll receive a BMISS
2071  * interrupt when we stop seeing beacons from the AP
2072  * we've associated with.
2073  */
2074 static void
2075 ath_beacon_config(struct ath_softc *sc)
2076 {
2077 #define TSF_TO_TU(_h,_l)        (((_h) << 22) | ((_l) >> 10))
2078         struct ath_hal *ah = sc->sc_ah;
2079         struct ieee80211com *ic = &sc->sc_ic;
2080         struct ieee80211_node *ni = ic->ic_bss;
2081         u_int32_t nexttbtt, intval;
2082
2083         /* extract tstamp from last beacon and convert to TU */
2084         nexttbtt = TSF_TO_TU(LE_READ_4(ni->ni_tstamp.data + 4),
2085                              LE_READ_4(ni->ni_tstamp.data));
2086         /* NB: the beacon interval is kept internally in TU's */
2087         intval = ni->ni_intval & HAL_BEACON_PERIOD;
2088         if (nexttbtt == 0)              /* e.g. for ap mode */
2089                 nexttbtt = intval;
2090         else if (intval)                /* NB: can be 0 for monitor mode */
2091                 nexttbtt = roundup(nexttbtt, intval);
2092         DPRINTF(sc, ATH_DEBUG_BEACON, "%s: nexttbtt %u intval %u (%u)\n",
2093                 __func__, nexttbtt, intval, ni->ni_intval);
2094         if (ic->ic_opmode == IEEE80211_M_STA) {
2095                 HAL_BEACON_STATE bs;
2096                 u_int64_t tsf;
2097                 u_int32_t tsftu;
2098                 int dtimperiod, dtimcount;
2099                 int cfpperiod, cfpcount;
2100
2101                 /*
2102                  * Setup dtim and cfp parameters according to
2103                  * last beacon we received (which may be none).
2104                  */
2105                 dtimperiod = ni->ni_dtim_period;
2106                 if (dtimperiod <= 0)            /* NB: 0 if not known */
2107                         dtimperiod = 1;
2108                 dtimcount = ni->ni_dtim_count;
2109                 if (dtimcount >= dtimperiod)    /* NB: sanity check */
2110                         dtimcount = 0;          /* XXX? */
2111                 cfpperiod = 1;                  /* NB: no PCF support yet */
2112                 cfpcount = 0;
2113 #define FUDGE   2
2114                 /*
2115                  * Pull nexttbtt forward to reflect the current
2116                  * TSF and calculate dtim+cfp state for the result.
2117                  */
2118                 tsf = ath_hal_gettsf64(ah);
2119                 tsftu = TSF_TO_TU((u_int32_t)(tsf>>32), (u_int32_t)tsf) + FUDGE;
2120                 do {
2121                         nexttbtt += intval;
2122                         if (--dtimcount < 0) {
2123                                 dtimcount = dtimperiod - 1;
2124                                 if (--cfpcount < 0)
2125                                         cfpcount = cfpperiod - 1;
2126                         }
2127                 } while (nexttbtt < tsftu);
2128 #undef FUDGE
2129                 memset(&bs, 0, sizeof(bs));
2130                 bs.bs_intval = intval;
2131                 bs.bs_nexttbtt = nexttbtt;
2132                 bs.bs_dtimperiod = dtimperiod*intval;
2133                 bs.bs_nextdtim = bs.bs_nexttbtt + dtimcount*intval;
2134                 bs.bs_cfpperiod = cfpperiod*bs.bs_dtimperiod;
2135                 bs.bs_cfpnext = bs.bs_nextdtim + cfpcount*bs.bs_dtimperiod;
2136                 bs.bs_cfpmaxduration = 0;
2137 #if 0
2138                 /*
2139                  * The 802.11 layer records the offset to the DTIM
2140                  * bitmap while receiving beacons; use it here to
2141                  * enable h/w detection of our AID being marked in
2142                  * the bitmap vector (to indicate frames for us are
2143                  * pending at the AP).
2144                  * XXX do DTIM handling in s/w to WAR old h/w bugs
2145                  * XXX enable based on h/w rev for newer chips
2146                  */
2147                 bs.bs_timoffset = ni->ni_timoff;
2148 #endif
2149                 /*
2150                  * Calculate the number of consecutive beacons to miss
2151                  * before taking a BMISS interrupt.  The configuration
2152                  * is specified in ms, so we need to convert that to
2153                  * TU's and then calculate based on the beacon interval.
2154                  * Note that we clamp the result to at most 10 beacons.
2155                  */
2156                 bs.bs_bmissthreshold = ic->ic_bmissthreshold;
2157                 if (bs.bs_bmissthreshold > 10)
2158                         bs.bs_bmissthreshold = 10;
2159                 else if (bs.bs_bmissthreshold <= 0)
2160                         bs.bs_bmissthreshold = 1;
2161
2162                 /*
2163                  * Calculate sleep duration.  The configuration is
2164                  * given in ms.  We insure a multiple of the beacon
2165                  * period is used.  Also, if the sleep duration is
2166                  * greater than the DTIM period then it makes senses
2167                  * to make it a multiple of that.
2168                  *
2169                  * XXX fixed at 100ms
2170                  */
2171                 bs.bs_sleepduration =
2172                         roundup(IEEE80211_MS_TO_TU(100), bs.bs_intval);
2173                 if (bs.bs_sleepduration > bs.bs_dtimperiod)
2174                         bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
2175
2176                 DPRINTF(sc, ATH_DEBUG_BEACON, 
2177                         "%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"
2178                         , __func__
2179                         , tsf, tsftu
2180                         , bs.bs_intval
2181                         , bs.bs_nexttbtt
2182                         , bs.bs_dtimperiod
2183                         , bs.bs_nextdtim
2184                         , bs.bs_bmissthreshold
2185                         , bs.bs_sleepduration
2186                         , bs.bs_cfpperiod
2187                         , bs.bs_cfpmaxduration
2188                         , bs.bs_cfpnext
2189                         , bs.bs_timoffset
2190                 );
2191                 ath_hal_intrset(ah, 0);
2192                 ath_hal_beacontimers(ah, &bs);
2193                 sc->sc_imask |= HAL_INT_BMISS;
2194                 ath_hal_intrset(ah, sc->sc_imask);
2195         } else {
2196                 ath_hal_intrset(ah, 0);
2197                 if (nexttbtt == intval)
2198                         intval |= HAL_BEACON_RESET_TSF;
2199                 if (ic->ic_opmode == IEEE80211_M_IBSS) {
2200                         /*
2201                          * In IBSS mode enable the beacon timers but only
2202                          * enable SWBA interrupts if we need to manually
2203                          * prepare beacon frames.  Otherwise we use a
2204                          * self-linked tx descriptor and let the hardware
2205                          * deal with things.
2206                          */
2207                         intval |= HAL_BEACON_ENA;
2208                         if (!sc->sc_hasveol)
2209                                 sc->sc_imask |= HAL_INT_SWBA;
2210                         ath_beaconq_config(sc);
2211                 } else if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2212                         /*
2213                          * In AP mode we enable the beacon timers and
2214                          * SWBA interrupts to prepare beacon frames.
2215                          */
2216                         intval |= HAL_BEACON_ENA;
2217                         sc->sc_imask |= HAL_INT_SWBA;   /* beacon prepare */
2218                         ath_beaconq_config(sc);
2219                 }
2220                 ath_hal_beaconinit(ah, nexttbtt, intval);
2221                 sc->sc_bmisscount = 0;
2222                 ath_hal_intrset(ah, sc->sc_imask);
2223                 /*
2224                  * When using a self-linked beacon descriptor in
2225                  * ibss mode load it once here.
2226                  */
2227                 if (ic->ic_opmode == IEEE80211_M_IBSS && sc->sc_hasveol)
2228                         ath_beacon_proc(sc, 0);
2229         }
2230 #undef TSF_TO_TU
2231 }
2232
2233 static void
2234 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
2235 {
2236         bus_addr_t *paddr = (bus_addr_t*) arg;
2237         KASSERT(error == 0, ("error %u on bus_dma callback", error));
2238         *paddr = segs->ds_addr;
2239 }
2240
2241 static int
2242 ath_descdma_setup(struct ath_softc *sc,
2243         struct ath_descdma *dd, ath_bufhead *head,
2244         const char *name, int nbuf, int ndesc)
2245 {
2246 #define DS2PHYS(_dd, _ds) \
2247         ((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
2248         struct ifnet *ifp = sc->sc_ifp;
2249         struct ath_desc *ds;
2250         struct ath_buf *bf;
2251         int i, bsize, error;
2252
2253         DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers %u desc/buf\n",
2254             __func__, name, nbuf, ndesc);
2255
2256         dd->dd_name = name;
2257         dd->dd_desc_len = sizeof(struct ath_desc) * nbuf * ndesc;
2258
2259         /*
2260          * Setup DMA descriptor area.
2261          */
2262         error = bus_dma_tag_create(NULL,        /* parent */
2263                        PAGE_SIZE, 0,            /* alignment, bounds */
2264                        BUS_SPACE_MAXADDR_32BIT, /* lowaddr */
2265                        BUS_SPACE_MAXADDR,       /* highaddr */
2266                        NULL, NULL,              /* filter, filterarg */
2267                        dd->dd_desc_len,         /* maxsize */
2268                        1,                       /* nsegments */
2269                        BUS_SPACE_MAXADDR,       /* maxsegsize */
2270                        BUS_DMA_ALLOCNOW,        /* flags */
2271                        NULL,                    /* lockfunc */
2272                        NULL,                    /* lockarg */
2273                        &dd->dd_dmat);
2274         if (error != 0) {
2275                 if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
2276                 return error;
2277         }
2278
2279         /* allocate descriptors */
2280         error = bus_dmamap_create(dd->dd_dmat, BUS_DMA_NOWAIT, &dd->dd_dmamap);
2281         if (error != 0) {
2282                 if_printf(ifp, "unable to create dmamap for %s descriptors, "
2283                         "error %u\n", dd->dd_name, error);
2284                 goto fail0;
2285         }
2286
2287         error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
2288                                  BUS_DMA_NOWAIT, &dd->dd_dmamap);
2289         if (error != 0) {
2290                 if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
2291                         "error %u\n", nbuf * ndesc, dd->dd_name, error);
2292                 goto fail1;
2293         }
2294
2295         error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
2296                                 dd->dd_desc, dd->dd_desc_len,
2297                                 ath_load_cb, &dd->dd_desc_paddr,
2298                                 BUS_DMA_NOWAIT);
2299         if (error != 0) {
2300                 if_printf(ifp, "unable to map %s descriptors, error %u\n",
2301                         dd->dd_name, error);
2302                 goto fail2;
2303         }
2304
2305         ds = dd->dd_desc;
2306         DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
2307             __func__, dd->dd_name, ds, (u_long) dd->dd_desc_len,
2308             (caddr_t) dd->dd_desc_paddr, /*XXX*/ (u_long) dd->dd_desc_len);
2309
2310         /* allocate rx buffers */
2311         bsize = sizeof(struct ath_buf) * nbuf;
2312         bf = malloc(bsize, M_ATHDEV, M_NOWAIT | M_ZERO);
2313         if (bf == NULL) {
2314                 if_printf(ifp, "malloc of %s buffers failed, size %u\n",
2315                         dd->dd_name, bsize);
2316                 goto fail3;
2317         }
2318         dd->dd_bufptr = bf;
2319
2320         STAILQ_INIT(head);
2321         for (i = 0; i < nbuf; i++, bf++, ds += ndesc) {
2322                 bf->bf_desc = ds;
2323                 bf->bf_daddr = DS2PHYS(dd, ds);
2324                 error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
2325                                 &bf->bf_dmamap);
2326                 if (error != 0) {
2327                         if_printf(ifp, "unable to create dmamap for %s "
2328                                 "buffer %u, error %u\n", dd->dd_name, i, error);
2329                         ath_descdma_cleanup(sc, dd, head);
2330                         return error;
2331                 }
2332                 STAILQ_INSERT_TAIL(head, bf, bf_list);
2333         }
2334         return 0;
2335 fail3:
2336         bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2337 fail2:
2338         bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2339 fail1:
2340         bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2341 fail0:
2342         bus_dma_tag_destroy(dd->dd_dmat);
2343         memset(dd, 0, sizeof(*dd));
2344         return error;
2345 #undef DS2PHYS
2346 }
2347
2348 static void
2349 ath_descdma_cleanup(struct ath_softc *sc,
2350         struct ath_descdma *dd, ath_bufhead *head)
2351 {
2352         struct ath_buf *bf;
2353         struct ieee80211_node *ni;
2354
2355         bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
2356         bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
2357         bus_dmamap_destroy(dd->dd_dmat, dd->dd_dmamap);
2358         bus_dma_tag_destroy(dd->dd_dmat);
2359
2360         STAILQ_FOREACH(bf, head, bf_list) {
2361                 if (bf->bf_m) {
2362                         m_freem(bf->bf_m);
2363                         bf->bf_m = NULL;
2364                 }
2365                 if (bf->bf_dmamap != NULL) {
2366                         bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
2367                         bf->bf_dmamap = NULL;
2368                 }
2369                 ni = bf->bf_node;
2370                 bf->bf_node = NULL;
2371                 if (ni != NULL) {
2372                         /*
2373                          * Reclaim node reference.
2374                          */
2375                         ieee80211_free_node(ni);
2376                 }
2377         }
2378
2379         STAILQ_INIT(head);
2380         free(dd->dd_bufptr, M_ATHDEV);
2381         memset(dd, 0, sizeof(*dd));
2382 }
2383
2384 static int
2385 ath_desc_alloc(struct ath_softc *sc)
2386 {
2387         int error;
2388
2389         error = ath_descdma_setup(sc, &sc->sc_rxdma, &sc->sc_rxbuf,
2390                         "rx", ath_rxbuf, 1);
2391         if (error != 0)
2392                 return error;
2393
2394         error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
2395                         "tx", ath_txbuf, ATH_TXDESC);
2396         if (error != 0) {
2397                 ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2398                 return error;
2399         }
2400
2401         error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
2402                         "beacon", 1, 1);
2403         if (error != 0) {
2404                 ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2405                 ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2406                 return error;
2407         }
2408         return 0;
2409 }
2410
2411 static void
2412 ath_desc_free(struct ath_softc *sc)
2413 {
2414
2415         if (sc->sc_bdma.dd_desc_len != 0)
2416                 ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
2417         if (sc->sc_txdma.dd_desc_len != 0)
2418                 ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
2419         if (sc->sc_rxdma.dd_desc_len != 0)
2420                 ath_descdma_cleanup(sc, &sc->sc_rxdma, &sc->sc_rxbuf);
2421 }
2422
2423 static struct ieee80211_node *
2424 ath_node_alloc(struct ieee80211_node_table *nt)
2425 {
2426         struct ieee80211com *ic = nt->nt_ic;
2427         struct ath_softc *sc = ic->ic_ifp->if_softc;
2428         const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
2429         struct ath_node *an;
2430
2431         an = malloc(space, M_80211_NODE, M_NOWAIT|M_ZERO);
2432         if (an == NULL) {
2433                 /* XXX stat+msg */
2434                 return NULL;
2435         }
2436         an->an_avgrssi = ATH_RSSI_DUMMY_MARKER;
2437         an->an_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
2438         an->an_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
2439         an->an_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
2440         ath_rate_node_init(sc, an);
2441
2442         DPRINTF(sc, ATH_DEBUG_NODE, "%s: an %p\n", __func__, an);
2443         return &an->an_node;
2444 }
2445
2446 static void
2447 ath_node_free(struct ieee80211_node *ni)
2448 {
2449         struct ieee80211com *ic = ni->ni_ic;
2450         struct ath_softc *sc = ic->ic_ifp->if_softc;
2451
2452         DPRINTF(sc, ATH_DEBUG_NODE, "%s: ni %p\n", __func__, ni);
2453
2454         ath_rate_node_cleanup(sc, ATH_NODE(ni));
2455         sc->sc_node_free(ni);
2456 }
2457
2458 static u_int8_t
2459 ath_node_getrssi(const struct ieee80211_node *ni)
2460 {
2461 #define HAL_EP_RND(x, mul) \
2462         ((((x)%(mul)) >= ((mul)/2)) ? ((x) + ((mul) - 1)) / (mul) : (x)/(mul))
2463         u_int32_t avgrssi = ATH_NODE_CONST(ni)->an_avgrssi;
2464         int32_t rssi;
2465
2466         /*
2467          * When only one frame is received there will be no state in
2468          * avgrssi so fallback on the value recorded by the 802.11 layer.
2469          */
2470         if (avgrssi != ATH_RSSI_DUMMY_MARKER)
2471                 rssi = HAL_EP_RND(avgrssi, HAL_RSSI_EP_MULTIPLIER);
2472         else
2473                 rssi = ni->ni_rssi;
2474         /* NB: theoretically we shouldn't need this, but be paranoid */
2475         return rssi < 0 ? 0 : rssi > 127 ? 127 : rssi;
2476 #undef HAL_EP_RND
2477 }
2478
2479 static int
2480 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
2481 {
2482         struct ath_hal *ah = sc->sc_ah;
2483         int error;
2484         struct mbuf *m;
2485         struct ath_desc *ds;
2486
2487         m = bf->bf_m;
2488         if (m == NULL) {
2489                 /*
2490                  * NB: by assigning a page to the rx dma buffer we
2491                  * implicitly satisfy the Atheros requirement that
2492                  * this buffer be cache-line-aligned and sized to be
2493                  * multiple of the cache line size.  Not doing this
2494                  * causes weird stuff to happen (for the 5210 at least).
2495                  */
2496                 m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
2497                 if (m == NULL) {
2498                         DPRINTF(sc, ATH_DEBUG_ANY,
2499                                 "%s: no mbuf/cluster\n", __func__);
2500                         sc->sc_stats.ast_rx_nombuf++;
2501                         return ENOMEM;
2502                 }
2503                 bf->bf_m = m;
2504                 m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
2505
2506                 error = bus_dmamap_load_mbuf_sg(sc->sc_dmat,
2507                                              bf->bf_dmamap, m,
2508                                              bf->bf_segs, &bf->bf_nseg,
2509                                              BUS_DMA_NOWAIT);
2510                 if (error != 0) {
2511                         DPRINTF(sc, ATH_DEBUG_ANY,
2512                             "%s: bus_dmamap_load_mbuf_sg failed; error %d\n",
2513                             __func__, error);
2514                         sc->sc_stats.ast_rx_busdma++;
2515                         return error;
2516                 }
2517                 KASSERT(bf->bf_nseg == 1,
2518                         ("multi-segment packet; nseg %u", bf->bf_nseg));
2519         }
2520         bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
2521
2522         /*
2523          * Setup descriptors.  For receive we always terminate
2524          * the descriptor list with a self-linked entry so we'll
2525          * not get overrun under high load (as can happen with a
2526          * 5212 when ANI processing enables PHY error frames).
2527          *
2528          * To insure the last descriptor is self-linked we create
2529          * each descriptor as self-linked and add it to the end.  As
2530          * each additional descriptor is added the previous self-linked
2531          * entry is ``fixed'' naturally.  This should be safe even
2532          * if DMA is happening.  When processing RX interrupts we
2533          * never remove/process the last, self-linked, entry on the
2534          * descriptor list.  This insures the hardware always has
2535          * someplace to write a new frame.
2536          */
2537         ds = bf->bf_desc;
2538         ds->ds_link = bf->bf_daddr;     /* link to self */
2539         ds->ds_data = bf->bf_segs[0].ds_addr;
2540         ath_hal_setuprxdesc(ah, ds
2541                 , m->m_len              /* buffer size */
2542                 , 0
2543         );
2544
2545         if (sc->sc_rxlink != NULL)
2546                 *sc->sc_rxlink = bf->bf_daddr;
2547         sc->sc_rxlink = &ds->ds_link;
2548         return 0;
2549 }
2550
2551 /*
2552  * Extend 15-bit time stamp from rx descriptor to
2553  * a full 64-bit TSF using the specified TSF.
2554  */
2555 static __inline u_int64_t
2556 ath_extend_tsf(u_int32_t rstamp, u_int64_t tsf)
2557 {
2558         if ((tsf & 0x7fff) < rstamp)
2559                 tsf -= 0x8000;
2560         return ((tsf &~ 0x7fff) | rstamp);
2561 }
2562
2563 /*
2564  * Intercept management frames to collect beacon rssi data
2565  * and to do ibss merges.
2566  */
2567 static void
2568 ath_recv_mgmt(struct ieee80211com *ic, struct mbuf *m,
2569         struct ieee80211_node *ni,
2570         int subtype, int rssi, u_int32_t rstamp)
2571 {
2572         struct ath_softc *sc = ic->ic_ifp->if_softc;
2573
2574         /*
2575          * Call up first so subsequent work can use information
2576          * potentially stored in the node (e.g. for ibss merge).
2577          */
2578         sc->sc_recv_mgmt(ic, m, ni, subtype, rssi, rstamp);
2579         switch (subtype) {
2580         case IEEE80211_FC0_SUBTYPE_BEACON:
2581                 /* update rssi statistics for use by the hal */
2582                 ATH_RSSI_LPF(ATH_NODE(ni)->an_halstats.ns_avgbrssi, rssi);
2583                 /* fall thru... */
2584         case IEEE80211_FC0_SUBTYPE_PROBE_RESP:
2585                 if (ic->ic_opmode == IEEE80211_M_IBSS &&
2586                     ic->ic_state == IEEE80211_S_RUN) {
2587                         u_int64_t tsf = ath_extend_tsf(rstamp,
2588                                 ath_hal_gettsf64(sc->sc_ah));
2589                         /*
2590                          * Handle ibss merge as needed; check the tsf on the
2591                          * frame before attempting the merge.  The 802.11 spec
2592                          * says the station should change it's bssid to match
2593                          * the oldest station with the same ssid, where oldest
2594                          * is determined by the tsf.  Note that hardware
2595                          * reconfiguration happens through callback to
2596                          * ath_newstate as the state machine will go from
2597                          * RUN -> RUN when this happens.
2598                          */
2599                         if (le64toh(ni->ni_tstamp.tsf) >= tsf) {
2600                                 DPRINTF(sc, ATH_DEBUG_STATE,
2601                                     "ibss merge, rstamp %u tsf %ju "
2602                                     "tstamp %ju\n", rstamp, (uintmax_t)tsf,
2603                                     (uintmax_t)ni->ni_tstamp.tsf);
2604                                 (void) ieee80211_ibss_merge(ni);
2605                         }
2606                 }
2607                 break;
2608         }
2609 }
2610
2611 /*
2612  * Set the default antenna.
2613  */
2614 static void
2615 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
2616 {
2617         struct ath_hal *ah = sc->sc_ah;
2618
2619         /* XXX block beacon interrupts */
2620         ath_hal_setdefantenna(ah, antenna);
2621         if (sc->sc_defant != antenna)
2622                 sc->sc_stats.ast_ant_defswitch++;
2623         sc->sc_defant = antenna;
2624         sc->sc_rxotherant = 0;
2625 }
2626
2627 static int
2628 ath_rx_tap(struct ath_softc *sc, struct mbuf *m,
2629         const struct ath_desc *ds, u_int64_t tsf, int16_t nf)
2630 {
2631         u_int8_t rix;
2632
2633         KASSERT(sc->sc_drvbpf != NULL, ("no tap"));
2634
2635         /*
2636          * Discard anything shorter than an ack or cts.
2637          */
2638         if (m->m_pkthdr.len < IEEE80211_ACK_LEN) {
2639                 DPRINTF(sc, ATH_DEBUG_RECV, "%s: runt packet %d\n",
2640                         __func__, m->m_pkthdr.len);
2641                 sc->sc_stats.ast_rx_tooshort++;
2642                 return 0;
2643         }
2644         sc->sc_rx_th.wr_tsf = htole64(
2645                 ath_extend_tsf(ds->ds_rxstat.rs_tstamp, tsf));
2646         rix = ds->ds_rxstat.rs_rate;
2647         sc->sc_rx_th.wr_flags = sc->sc_hwmap[rix].rxflags;
2648         if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
2649                 sc->sc_rx_th.wr_flags |= IEEE80211_RADIOTAP_F_BADFCS;
2650         /* XXX propagate other error flags from descriptor */
2651         sc->sc_rx_th.wr_rate = sc->sc_hwmap[rix].ieeerate;
2652         sc->sc_rx_th.wr_antsignal = ds->ds_rxstat.rs_rssi + nf;
2653         sc->sc_rx_th.wr_antnoise = nf;
2654         sc->sc_rx_th.wr_antenna = ds->ds_rxstat.rs_antenna;
2655
2656         bpf_mtap2(sc->sc_drvbpf, &sc->sc_rx_th, sc->sc_rx_th_len, m);
2657
2658         return 1;
2659 }
2660
2661 static void
2662 ath_rx_proc(void *arg, int npending)
2663 {
2664 #define PA2DESC(_sc, _pa) \
2665         ((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
2666                 ((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
2667         struct ath_softc *sc = arg;
2668         struct ath_buf *bf;
2669         struct ieee80211com *ic = &sc->sc_ic;
2670         struct ifnet *ifp = sc->sc_ifp;
2671         struct ath_hal *ah = sc->sc_ah;
2672         struct ath_desc *ds;
2673         struct mbuf *m;
2674         struct ieee80211_node *ni;
2675         struct ath_node *an;
2676         int len, type;
2677         u_int phyerr;
2678         HAL_STATUS status;
2679         int16_t nf;
2680         u_int64_t tsf;
2681
2682         NET_LOCK_GIANT();               /* XXX */
2683
2684         DPRINTF(sc, ATH_DEBUG_RX_PROC, "%s: pending %u\n", __func__, npending);
2685         nf = ath_hal_getchannoise(ah, &sc->sc_curchan);
2686         tsf = ath_hal_gettsf64(ah);
2687         do {
2688                 bf = STAILQ_FIRST(&sc->sc_rxbuf);
2689                 if (bf == NULL) {               /* NB: shouldn't happen */
2690                         if_printf(ifp, "%s: no buffer!\n", __func__);
2691                         break;
2692                 }
2693                 ds = bf->bf_desc;
2694                 if (ds->ds_link == bf->bf_daddr) {
2695                         /* NB: never process the self-linked entry at the end */
2696                         break;
2697                 }
2698                 m = bf->bf_m;
2699                 if (m == NULL) {                /* NB: shouldn't happen */
2700                         if_printf(ifp, "%s: no mbuf!\n", __func__);
2701                         continue;
2702                 }
2703                 /* XXX sync descriptor memory */
2704                 /*
2705                  * Must provide the virtual address of the current
2706                  * descriptor, the physical address, and the virtual
2707                  * address of the next descriptor in the h/w chain.
2708                  * This allows the HAL to look ahead to see if the
2709                  * hardware is done with a descriptor by checking the
2710                  * done bit in the following descriptor and the address
2711                  * of the current descriptor the DMA engine is working
2712                  * on.  All this is necessary because of our use of
2713                  * a self-linked list to avoid rx overruns.
2714                  */
2715                 status = ath_hal_rxprocdesc(ah, ds,
2716                                 bf->bf_daddr, PA2DESC(sc, ds->ds_link));
2717 #ifdef AR_DEBUG
2718                 if (sc->sc_debug & ATH_DEBUG_RECV_DESC)
2719                         ath_printrxbuf(bf, status == HAL_OK); 
2720 #endif
2721                 if (status == HAL_EINPROGRESS)
2722                         break;
2723                 STAILQ_REMOVE_HEAD(&sc->sc_rxbuf, bf_list);
2724                 if (ds->ds_rxstat.rs_more) {
2725                         /*
2726                          * Frame spans multiple descriptors; this
2727                          * cannot happen yet as we don't support
2728                          * jumbograms.  If not in monitor mode,
2729                          * discard the frame.
2730                          */
2731                         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2732                                 sc->sc_stats.ast_rx_toobig++;
2733                                 goto rx_next;
2734                         }
2735                         /* fall thru for monitor mode handling... */
2736                 } else if (ds->ds_rxstat.rs_status != 0) {
2737                         if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
2738                                 sc->sc_stats.ast_rx_crcerr++;
2739                         if (ds->ds_rxstat.rs_status & HAL_RXERR_FIFO)
2740                                 sc->sc_stats.ast_rx_fifoerr++;
2741                         if (ds->ds_rxstat.rs_status & HAL_RXERR_PHY) {
2742                                 sc->sc_stats.ast_rx_phyerr++;
2743                                 phyerr = ds->ds_rxstat.rs_phyerr & 0x1f;
2744                                 sc->sc_stats.ast_rx_phy[phyerr]++;
2745                                 goto rx_next;
2746                         }
2747                         if (ds->ds_rxstat.rs_status & HAL_RXERR_DECRYPT) {
2748                                 /*
2749                                  * Decrypt error.  If the error occurred
2750                                  * because there was no hardware key, then
2751                                  * let the frame through so the upper layers
2752                                  * can process it.  This is necessary for 5210
2753                                  * parts which have no way to setup a ``clear''
2754                                  * key cache entry.
2755                                  *
2756                                  * XXX do key cache faulting
2757                                  */
2758                                 if (ds->ds_rxstat.rs_keyix == HAL_RXKEYIX_INVALID)
2759                                         goto rx_accept;
2760                                 sc->sc_stats.ast_rx_badcrypt++;
2761                         }
2762                         if (ds->ds_rxstat.rs_status & HAL_RXERR_MIC) {
2763                                 sc->sc_stats.ast_rx_badmic++;
2764                                 /*
2765                                  * Do minimal work required to hand off
2766                                  * the 802.11 header for notifcation.
2767                                  */
2768                                 /* XXX frag's and qos frames */
2769                                 len = ds->ds_rxstat.rs_datalen;
2770                                 if (len >= sizeof (struct ieee80211_frame)) {
2771                                         bus_dmamap_sync(sc->sc_dmat,
2772                                             bf->bf_dmamap,
2773                                             BUS_DMASYNC_POSTREAD);
2774                                         ieee80211_notify_michael_failure(ic,
2775                                             mtod(m, struct ieee80211_frame *),
2776                                             sc->sc_splitmic ?
2777                                                 ds->ds_rxstat.rs_keyix-32 :
2778                                                 ds->ds_rxstat.rs_keyix
2779                                         );
2780                                 }
2781                         }
2782                         ifp->if_ierrors++;
2783                         /*
2784                          * When a tap is present pass error frames
2785                          * that have been requested.  By default we
2786                          * pass decrypt+mic errors but others may be
2787                          * interesting (e.g. crc).
2788                          */
2789                         if (sc->sc_drvbpf != NULL &&
2790                             (ds->ds_rxstat.rs_status & sc->sc_monpass)) {
2791                                 bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
2792                                     BUS_DMASYNC_POSTREAD);
2793                                 /* NB: bpf needs the mbuf length setup */
2794                                 len = ds->ds_rxstat.rs_datalen;
2795                                 m->m_pkthdr.len = m->m_len = len;
2796                                 (void) ath_rx_tap(sc, m, ds, tsf, nf);
2797                         }
2798                         /* XXX pass MIC errors up for s/w reclaculation */
2799                         goto rx_next;
2800                 }
2801 rx_accept:
2802                 /*
2803                  * Sync and unmap the frame.  At this point we're
2804                  * committed to passing the mbuf somewhere so clear
2805                  * bf_m; this means a new sk_buff must be allocated
2806                  * when the rx descriptor is setup again to receive
2807                  * another frame.
2808                  */
2809                 bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
2810                     BUS_DMASYNC_POSTREAD);
2811                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2812                 bf->bf_m = NULL;
2813
2814                 m->m_pkthdr.rcvif = ifp;
2815                 len = ds->ds_rxstat.rs_datalen;
2816                 m->m_pkthdr.len = m->m_len = len;
2817
2818                 sc->sc_stats.ast_ant_rx[ds->ds_rxstat.rs_antenna]++;
2819
2820                 if (sc->sc_drvbpf != NULL && !ath_rx_tap(sc, m, ds, tsf, nf)) {
2821                         m_freem(m);             /* XXX reclaim */
2822                         goto rx_next;
2823                 }
2824
2825                 /*
2826                  * From this point on we assume the frame is at least
2827                  * as large as ieee80211_frame_min; verify that.
2828                  */
2829                 if (len < IEEE80211_MIN_LEN) {
2830                         DPRINTF(sc, ATH_DEBUG_RECV, "%s: short packet %d\n",
2831                                 __func__, len);
2832                         sc->sc_stats.ast_rx_tooshort++;
2833                         m_freem(m);
2834                         goto rx_next;
2835                 }
2836
2837                 if (IFF_DUMPPKTS(sc, ATH_DEBUG_RECV)) {
2838                         ieee80211_dump_pkt(mtod(m, caddr_t), len,
2839                                    sc->sc_hwmap[ds->ds_rxstat.rs_rate].ieeerate,
2840                                    ds->ds_rxstat.rs_rssi);
2841                 }
2842
2843                 m_adj(m, -IEEE80211_CRC_LEN);
2844
2845                 /*
2846                  * Locate the node for sender, track state, and then
2847                  * pass the (referenced) node up to the 802.11 layer
2848                  * for its use.
2849                  */
2850                 ni = ieee80211_find_rxnode_withkey(ic,
2851                         mtod(m, const struct ieee80211_frame_min *),
2852                         ds->ds_rxstat.rs_keyix == HAL_RXKEYIX_INVALID ?
2853                                 IEEE80211_KEYIX_NONE : ds->ds_rxstat.rs_keyix);
2854                 /*
2855                  * Track rx rssi and do any rx antenna management.
2856                  */
2857                 an = ATH_NODE(ni);
2858                 ATH_RSSI_LPF(an->an_avgrssi, ds->ds_rxstat.rs_rssi);
2859                 /*
2860                  * Send frame up for processing.
2861                  */
2862                 type = ieee80211_input(ic, m, ni,
2863                         ds->ds_rxstat.rs_rssi, ds->ds_rxstat.rs_tstamp);
2864                 ieee80211_free_node(ni);
2865                 if (sc->sc_diversity) {
2866                         /*
2867                          * When using fast diversity, change the default rx
2868                          * antenna if diversity chooses the other antenna 3
2869                          * times in a row.
2870                          */
2871                         if (sc->sc_defant != ds->ds_rxstat.rs_antenna) {
2872                                 if (++sc->sc_rxotherant >= 3)
2873                                         ath_setdefantenna(sc,
2874                                                 ds->ds_rxstat.rs_antenna);
2875                         } else
2876                                 sc->sc_rxotherant = 0;
2877                 }
2878                 if (sc->sc_softled) {
2879                         /*
2880                          * Blink for any data frame.  Otherwise do a
2881                          * heartbeat-style blink when idle.  The latter
2882                          * is mainly for station mode where we depend on
2883                          * periodic beacon frames to trigger the poll event.
2884                          */
2885                         if (type == IEEE80211_FC0_TYPE_DATA) {
2886                                 sc->sc_rxrate = ds->ds_rxstat.rs_rate;
2887                                 ath_led_event(sc, ATH_LED_RX);
2888                         } else if (ticks - sc->sc_ledevent >= sc->sc_ledidle)
2889                                 ath_led_event(sc, ATH_LED_POLL);
2890                 }
2891 rx_next:
2892                 STAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
2893         } while (ath_rxbuf_init(sc, bf) == 0);
2894
2895         /* rx signal state monitoring */
2896         ath_hal_rxmonitor(ah, &ATH_NODE(ic->ic_bss)->an_halstats);
2897
2898         NET_UNLOCK_GIANT();             /* XXX */
2899 #undef PA2DESC
2900 }
2901
2902 /*
2903  * Setup a h/w transmit queue.
2904  */
2905 static struct ath_txq *
2906 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
2907 {
2908 #define N(a)    (sizeof(a)/sizeof(a[0]))
2909         struct ath_hal *ah = sc->sc_ah;
2910         HAL_TXQ_INFO qi;
2911         int qnum;
2912
2913         memset(&qi, 0, sizeof(qi));
2914         qi.tqi_subtype = subtype;
2915         qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
2916         qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
2917         qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
2918         /*
2919          * Enable interrupts only for EOL and DESC conditions.
2920          * We mark tx descriptors to receive a DESC interrupt
2921          * when a tx queue gets deep; otherwise waiting for the
2922          * EOL to reap descriptors.  Note that this is done to
2923          * reduce interrupt load and this only defers reaping
2924          * descriptors, never transmitting frames.  Aside from
2925          * reducing interrupts this also permits more concurrency.
2926          * The only potential downside is if the tx queue backs
2927          * up in which case the top half of the kernel may backup
2928          * due to a lack of tx descriptors.
2929          */
2930         qi.tqi_qflags = TXQ_FLAG_TXEOLINT_ENABLE | TXQ_FLAG_TXDESCINT_ENABLE;
2931         qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
2932         if (qnum == -1) {
2933                 /*
2934                  * NB: don't print a message, this happens
2935                  * normally on parts with too few tx queues
2936                  */
2937                 return NULL;
2938         }
2939         if (qnum >= N(sc->sc_txq)) {
2940                 device_printf(sc->sc_dev,
2941                         "hal qnum %u out of range, max %zu!\n",
2942                         qnum, N(sc->sc_txq));
2943                 ath_hal_releasetxqueue(ah, qnum);
2944                 return NULL;
2945         }
2946         if (!ATH_TXQ_SETUP(sc, qnum)) {
2947                 struct ath_txq *txq = &sc->sc_txq[qnum];
2948
2949                 txq->axq_qnum = qnum;
2950                 txq->axq_depth = 0;
2951                 txq->axq_intrcnt = 0;
2952                 txq->axq_link = NULL;
2953                 STAILQ_INIT(&txq->axq_q);
2954                 ATH_TXQ_LOCK_INIT(sc, txq);
2955                 sc->sc_txqsetup |= 1<<qnum;
2956         }
2957         return &sc->sc_txq[qnum];
2958 #undef N
2959 }
2960
2961 /*
2962  * Setup a hardware data transmit queue for the specified
2963  * access control.  The hal may not support all requested
2964  * queues in which case it will return a reference to a
2965  * previously setup queue.  We record the mapping from ac's
2966  * to h/w queues for use by ath_tx_start and also track
2967  * the set of h/w queues being used to optimize work in the
2968  * transmit interrupt handler and related routines.
2969  */
2970 static int
2971 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
2972 {
2973 #define N(a)    (sizeof(a)/sizeof(a[0]))
2974         struct ath_txq *txq;
2975
2976         if (ac >= N(sc->sc_ac2q)) {
2977                 device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
2978                         ac, N(sc->sc_ac2q));
2979                 return 0;
2980         }
2981         txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
2982         if (txq != NULL) {
2983                 sc->sc_ac2q[ac] = txq;
2984                 return 1;
2985         } else
2986                 return 0;
2987 #undef N
2988 }
2989
2990 /*
2991  * Update WME parameters for a transmit queue.
2992  */
2993 static int
2994 ath_txq_update(struct ath_softc *sc, int ac)
2995 {
2996 #define ATH_EXPONENT_TO_VALUE(v)        ((1<<v)-1)
2997 #define ATH_TXOP_TO_US(v)               (v<<5)
2998         struct ieee80211com *ic = &sc->sc_ic;
2999         struct ath_txq *txq = sc->sc_ac2q[ac];
3000         struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
3001         struct ath_hal *ah = sc->sc_ah;
3002         HAL_TXQ_INFO qi;
3003
3004         ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
3005         qi.tqi_aifs = wmep->wmep_aifsn;
3006         qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
3007         qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);      
3008         qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
3009
3010         if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
3011                 device_printf(sc->sc_dev, "unable to update hardware queue "
3012                         "parameters for %s traffic!\n",
3013                         ieee80211_wme_acnames[ac]);
3014                 return 0;
3015         } else {
3016                 ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
3017                 return 1;
3018         }
3019 #undef ATH_TXOP_TO_US
3020 #undef ATH_EXPONENT_TO_VALUE
3021 }
3022
3023 /*
3024  * Callback from the 802.11 layer to update WME parameters.
3025  */
3026 static int
3027 ath_wme_update(struct ieee80211com *ic)
3028 {
3029         struct ath_softc *sc = ic->ic_ifp->if_softc;
3030
3031         return !ath_txq_update(sc, WME_AC_BE) ||
3032             !ath_txq_update(sc, WME_AC_BK) ||
3033             !ath_txq_update(sc, WME_AC_VI) ||
3034             !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
3035 }
3036
3037 /*
3038  * Reclaim resources for a setup queue.
3039  */
3040 static void
3041 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
3042 {
3043
3044         ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
3045         ATH_TXQ_LOCK_DESTROY(txq);
3046         sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
3047 }
3048
3049 /*
3050  * Reclaim all tx queue resources.
3051  */
3052 static void
3053 ath_tx_cleanup(struct ath_softc *sc)
3054 {
3055         int i;
3056
3057         ATH_TXBUF_LOCK_DESTROY(sc);
3058         for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3059                 if (ATH_TXQ_SETUP(sc, i))
3060                         ath_tx_cleanupq(sc, &sc->sc_txq[i]);
3061 }
3062
3063 /*
3064  * Defragment an mbuf chain, returning at most maxfrags separate
3065  * mbufs+clusters.  If this is not possible NULL is returned and
3066  * the original mbuf chain is left in it's present (potentially
3067  * modified) state.  We use two techniques: collapsing consecutive
3068  * mbufs and replacing consecutive mbufs by a cluster.
3069  */
3070 static struct mbuf *
3071 ath_defrag(struct mbuf *m0, int how, int maxfrags)
3072 {
3073         struct mbuf *m, *n, *n2, **prev;
3074         u_int curfrags;
3075
3076         /*
3077          * Calculate the current number of frags.
3078          */
3079         curfrags = 0;
3080         for (m = m0; m != NULL; m = m->m_next)
3081                 curfrags++;
3082         /*
3083          * First, try to collapse mbufs.  Note that we always collapse
3084          * towards the front so we don't need to deal with moving the
3085          * pkthdr.  This may be suboptimal if the first mbuf has much
3086          * less data than the following.
3087          */
3088         m = m0;
3089 again:
3090         for (;;) {
3091                 n = m->m_next;
3092                 if (n == NULL)
3093                         break;
3094                 if ((m->m_flags & M_RDONLY) == 0 &&
3095                     n->m_len < M_TRAILINGSPACE(m)) {
3096                         bcopy(mtod(n, void *), mtod(m, char *) + m->m_len,
3097                                 n->m_len);
3098                         m->m_len += n->m_len;
3099                         m->m_next = n->m_next;
3100                         m_free(n);
3101                         if (--curfrags <= maxfrags)
3102                                 return m0;
3103                 } else
3104                         m = n;
3105         }
3106         KASSERT(maxfrags > 1,
3107                 ("maxfrags %u, but normal collapse failed", maxfrags));
3108         /*
3109          * Collapse consecutive mbufs to a cluster.
3110          */
3111         prev = &m0->m_next;             /* NB: not the first mbuf */
3112         while ((n = *prev) != NULL) {
3113                 if ((n2 = n->m_next) != NULL &&
3114                     n->m_len + n2->m_len < MCLBYTES) {
3115                         m = m_getcl(how, MT_DATA, 0);
3116                         if (m == NULL)
3117                                 goto bad;
3118                         bcopy(mtod(n, void *), mtod(m, void *), n->m_len);
3119                         bcopy(mtod(n2, void *), mtod(m, char *) + n->m_len,
3120                                 n2->m_len);
3121                         m->m_len = n->m_len + n2->m_len;
3122                         m->m_next = n2->m_next;
3123                         *prev = m;
3124                         m_free(n);
3125                         m_free(n2);
3126                         if (--curfrags <= maxfrags)     /* +1 cl -2 mbufs */
3127                                 return m0;
3128                         /*
3129                          * Still not there, try the normal collapse
3130                          * again before we allocate another cluster.
3131                          */
3132                         goto again;
3133                 }
3134                 prev = &n->m_next;
3135         }
3136         /*
3137          * No place where we can collapse to a cluster; punt.
3138          * This can occur if, for example, you request 2 frags
3139          * but the packet requires that both be clusters (we
3140          * never reallocate the first mbuf to avoid moving the
3141          * packet header).
3142          */
3143 bad:
3144         return NULL;
3145 }
3146
3147 /*
3148  * Return h/w rate index for an IEEE rate (w/o basic rate bit).
3149  */
3150 static int
3151 ath_tx_findrix(const HAL_RATE_TABLE *rt, int rate)
3152 {
3153         int i;
3154
3155         for (i = 0; i < rt->rateCount; i++)
3156                 if ((rt->info[i].dot11Rate & IEEE80211_RATE_VAL) == rate)
3157                         return i;
3158         return 0;               /* NB: lowest rate */
3159 }
3160
3161 static int
3162 ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
3163     struct mbuf *m0)
3164 {
3165         struct ieee80211com *ic = &sc->sc_ic;
3166         struct ath_hal *ah = sc->sc_ah;
3167         struct ifnet *ifp = sc->sc_ifp;
3168         const struct chanAccParams *cap = &ic->ic_wme.wme_chanParams;
3169         int i, error, iswep, ismcast, ismrr;
3170         int keyix, hdrlen, pktlen, try0;
3171         u_int8_t rix, txrate, ctsrate;
3172         u_int8_t cix = 0xff;            /* NB: silence compiler */
3173         struct ath_desc *ds, *ds0;
3174         struct ath_txq *txq;
3175         struct ieee80211_frame *wh;
3176         u_int subtype, flags, ctsduration;
3177         HAL_PKT_TYPE atype;
3178         const HAL_RATE_TABLE *rt;
3179         HAL_BOOL shortPreamble;
3180         struct ath_node *an;
3181         struct mbuf *m;
3182         u_int pri;
3183
3184         wh = mtod(m0, struct ieee80211_frame *);
3185         iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
3186         ismcast = IEEE80211_IS_MULTICAST(wh->i_addr1);
3187         hdrlen = ieee80211_anyhdrsize(wh);
3188         /*
3189          * Packet length must not include any
3190          * pad bytes; deduct them here.
3191          */
3192         pktlen = m0->m_pkthdr.len - (hdrlen & 3);
3193
3194         if (iswep) {
3195                 const struct ieee80211_cipher *cip;
3196                 struct ieee80211_key *k;
3197
3198                 /*
3199                  * Construct the 802.11 header+trailer for an encrypted
3200                  * frame. The only reason this can fail is because of an
3201                  * unknown or unsupported cipher/key type.
3202                  */
3203                 k = ieee80211_crypto_encap(ic, ni, m0);
3204                 if (k == NULL) {
3205                         /*
3206                          * This can happen when the key is yanked after the
3207                          * frame was queued.  Just discard the frame; the
3208                          * 802.11 layer counts failures and provides
3209                          * debugging/diagnostics.
3210                          */
3211                         m_freem(m0);
3212                         return EIO;
3213                 }
3214                 /*
3215                  * Adjust the packet + header lengths for the crypto
3216                  * additions and calculate the h/w key index.  When
3217                  * a s/w mic is done the frame will have had any mic
3218                  * added to it prior to entry so skb->len above will
3219                  * account for it. Otherwise we need to add it to the
3220                  * packet length.
3221                  */
3222                 cip = k->wk_cipher;
3223                 hdrlen += cip->ic_header;
3224                 pktlen += cip->ic_header + cip->ic_trailer;
3225                 if ((k->wk_flags & IEEE80211_KEY_SWMIC) == 0)
3226                         pktlen += cip->ic_miclen;
3227                 keyix = k->wk_keyix;
3228
3229                 /* packet header may have moved, reset our local pointer */
3230                 wh = mtod(m0, struct ieee80211_frame *);
3231         } else if (ni->ni_ucastkey.wk_cipher == &ieee80211_cipher_none) {
3232                 /*
3233                  * Use station key cache slot, if assigned.
3234                  */
3235                 keyix = ni->ni_ucastkey.wk_keyix;
3236                 if (keyix == IEEE80211_KEYIX_NONE)
3237                         keyix = HAL_TXKEYIX_INVALID;
3238         } else
3239                 keyix = HAL_TXKEYIX_INVALID;
3240
3241         pktlen += IEEE80211_CRC_LEN;
3242
3243         /*
3244          * Load the DMA map so any coalescing is done.  This
3245          * also calculates the number of descriptors we need.
3246          */
3247         error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3248                                      bf->bf_segs, &bf->bf_nseg,
3249                                      BUS_DMA_NOWAIT);
3250         if (error == EFBIG) {
3251                 /* XXX packet requires too many descriptors */
3252                 bf->bf_nseg = ATH_TXDESC+1;
3253         } else if (error != 0) {
3254                 sc->sc_stats.ast_tx_busdma++;
3255                 m_freem(m0);
3256                 return error;
3257         }
3258         /*
3259          * Discard null packets and check for packets that
3260          * require too many TX descriptors.  We try to convert
3261          * the latter to a cluster.
3262          */
3263         if (bf->bf_nseg > ATH_TXDESC) {         /* too many desc's, linearize */
3264                 sc->sc_stats.ast_tx_linear++;
3265                 m = ath_defrag(m0, M_DONTWAIT, ATH_TXDESC);
3266                 if (m == NULL) {
3267                         m_freem(m0);
3268                         sc->sc_stats.ast_tx_nombuf++;
3269                         return ENOMEM;
3270                 }
3271                 m0 = m;
3272                 error = bus_dmamap_load_mbuf_sg(sc->sc_dmat, bf->bf_dmamap, m0,
3273                                              bf->bf_segs, &bf->bf_nseg,
3274                                              BUS_DMA_NOWAIT);
3275                 if (error != 0) {
3276                         sc->sc_stats.ast_tx_busdma++;
3277                         m_freem(m0);
3278                         return error;
3279                 }
3280                 KASSERT(bf->bf_nseg <= ATH_TXDESC,
3281                     ("too many segments after defrag; nseg %u", bf->bf_nseg));
3282         } else if (bf->bf_nseg == 0) {          /* null packet, discard */
3283                 sc->sc_stats.ast_tx_nodata++;
3284                 m_freem(m0);
3285                 return EIO;
3286         }
3287         DPRINTF(sc, ATH_DEBUG_XMIT, "%s: m %p len %u\n", __func__, m0, pktlen);
3288         bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
3289         bf->bf_m = m0;
3290         bf->bf_node = ni;                       /* NB: held reference */
3291
3292         /* setup descriptors */
3293         ds = bf->bf_desc;
3294         rt = sc->sc_currates;
3295         KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
3296
3297         /*
3298          * NB: the 802.11 layer marks whether or not we should
3299          * use short preamble based on the current mode and
3300          * negotiated parameters.
3301          */
3302         if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
3303             (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
3304                 shortPreamble = AH_TRUE;
3305                 sc->sc_stats.ast_tx_shortpre++;
3306         } else {
3307                 shortPreamble = AH_FALSE;
3308         }
3309
3310         an = ATH_NODE(ni);
3311         flags = HAL_TXDESC_CLRDMASK;            /* XXX needed for crypto errs */
3312         ismrr = 0;                              /* default no multi-rate retry*/
3313         /*
3314          * Calculate Atheros packet type from IEEE80211 packet header,
3315          * setup for rate calculations, and select h/w transmit queue.
3316          */
3317         switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
3318         case IEEE80211_FC0_TYPE_MGT:
3319                 subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
3320                 if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
3321                         atype = HAL_PKT_TYPE_BEACON;
3322                 else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
3323                         atype = HAL_PKT_TYPE_PROBE_RESP;
3324                 else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
3325                         atype = HAL_PKT_TYPE_ATIM;
3326                 else
3327                         atype = HAL_PKT_TYPE_NORMAL;    /* XXX */
3328                 rix = sc->sc_minrateix;
3329                 txrate = rt->info[rix].rateCode;
3330                 if (shortPreamble)
3331                         txrate |= rt->info[rix].shortPreamble;
3332                 try0 = ATH_TXMGTTRY;
3333                 /* NB: force all management frames to highest queue */
3334                 if (ni->ni_flags & IEEE80211_NODE_QOS) {
3335                         /* NB: force all management frames to highest queue */
3336                         pri = WME_AC_VO;
3337                 } else
3338                         pri = WME_AC_BE;
3339                 flags |= HAL_TXDESC_INTREQ;     /* force interrupt */
3340                 break;
3341         case IEEE80211_FC0_TYPE_CTL:
3342                 atype = HAL_PKT_TYPE_PSPOLL;    /* stop setting of duration */
3343                 rix = sc->sc_minrateix;
3344                 txrate = rt->info[rix].rateCode;
3345                 if (shortPreamble)
3346                         txrate |= rt->info[rix].shortPreamble;
3347                 try0 = ATH_TXMGTTRY;
3348                 /* NB: force all ctl frames to highest queue */
3349                 if (ni->ni_flags & IEEE80211_NODE_QOS) {
3350                         /* NB: force all ctl frames to highest queue */
3351                         pri = WME_AC_VO;
3352                 } else
3353                         pri = WME_AC_BE;
3354                 flags |= HAL_TXDESC_INTREQ;     /* force interrupt */
3355                 break;
3356         case IEEE80211_FC0_TYPE_DATA:
3357                 atype = HAL_PKT_TYPE_NORMAL;            /* default */
3358                 /*
3359                  * Data frames: multicast frames go out at a fixed rate,
3360                  * otherwise consult the rate control module for the
3361                  * rate to use.
3362                  */
3363                 if (ismcast) {
3364                         /*
3365                          * Check mcast rate setting in case it's changed.
3366                          * XXX move out of fastpath
3367                          */
3368                         if (ic->ic_mcast_rate != sc->sc_mcastrate) {
3369                                 sc->sc_mcastrix =
3370                                         ath_tx_findrix(rt, ic->ic_mcast_rate);
3371                                 sc->sc_mcastrate = ic->ic_mcast_rate;
3372                         }
3373                         rix = sc->sc_mcastrix;
3374                         txrate = rt->info[rix].rateCode;
3375                         if (shortPreamble)
3376                                 txrate |= rt->info[rix].shortPreamble;
3377                         try0 = 1;
3378                 } else {
3379                         ath_rate_findrate(sc, an, shortPreamble, pktlen,
3380                                 &rix, &try0, &txrate);
3381                         sc->sc_txrate = txrate;         /* for LED blinking */
3382                         if (try0 != ATH_TXMAXTRY)
3383                                 ismrr = 1;
3384                 }
3385                 /*
3386                  * Default all non-QoS traffic to the background queue.
3387                  */
3388                 if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
3389                         pri = M_WME_GETAC(m0);
3390                         if (cap->cap_wmeParams[pri].wmep_noackPolicy) {
3391                                 flags |= HAL_TXDESC_NOACK;
3392                                 sc->sc_stats.ast_tx_noack++;
3393                         }
3394                 } else
3395                         pri = WME_AC_BE;
3396                 break;
3397         default:
3398                 if_printf(ifp, "bogus frame type 0x%x (%s)\n",
3399                         wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK, __func__);
3400                 /* XXX statistic */
3401                 m_freem(m0);
3402                 return EIO;
3403         }
3404         txq = sc->sc_ac2q[pri];
3405
3406         /*
3407          * When servicing one or more stations in power-save mode
3408          * multicast frames must be buffered until after the beacon.
3409          * We use the CAB queue for that.
3410          */
3411         if (ismcast && ic->ic_ps_sta) {
3412                 txq = sc->sc_cabq;
3413                 /* XXX? more bit in 802.11 frame header */
3414         }
3415
3416         /*
3417          * Calculate miscellaneous flags.
3418          */
3419         if (ismcast) {
3420                 flags |= HAL_TXDESC_NOACK;      /* no ack on broad/multicast */
3421                 sc->sc_stats.ast_tx_noack++;
3422         } else if (pktlen > ic->ic_rtsthreshold) {
3423                 flags |= HAL_TXDESC_RTSENA;     /* RTS based on frame length */
3424                 cix = rt->info[rix].controlRate;
3425                 sc->sc_stats.ast_tx_rts++;
3426         }
3427
3428         /*
3429          * If 802.11g protection is enabled, determine whether
3430          * to use RTS/CTS or just CTS.  Note that this is only
3431          * done for OFDM unicast frames.
3432          */
3433         if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
3434             rt->info[rix].phy == IEEE80211_T_OFDM &&
3435             (flags & HAL_TXDESC_NOACK) == 0) {
3436                 /* XXX fragments must use CCK rates w/ protection */
3437                 if (ic->ic_protmode == IEEE80211_PROT_RTSCTS)
3438                         flags |= HAL_TXDESC_RTSENA;
3439                 else if (ic->ic_protmode == IEEE80211_PROT_CTSONLY)
3440                         flags |= HAL_TXDESC_CTSENA;
3441                 cix = rt->info[sc->sc_protrix].controlRate;
3442                 sc->sc_stats.ast_tx_protect++;
3443         }
3444
3445         /*
3446          * Calculate duration.  This logically belongs in the 802.11
3447          * layer but it lacks sufficient information to calculate it.
3448          */
3449         if ((flags & HAL_TXDESC_NOACK) == 0 &&
3450             (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
3451                 u_int16_t dur;
3452                 /*
3453                  * XXX not right with fragmentation.
3454                  */
3455                 if (shortPreamble)
3456                         dur = rt->info[rix].spAckDuration;
3457                 else
3458                         dur = rt->info[rix].lpAckDuration;
3459                 *(u_int16_t *)wh->i_dur = htole16(dur);
3460         }
3461
3462         /*
3463          * Calculate RTS/CTS rate and duration if needed.
3464          */
3465         ctsduration = 0;
3466         if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
3467                 /*
3468                  * CTS transmit rate is derived from the transmit rate
3469                  * by looking in the h/w rate table.  We must also factor
3470                  * in whether or not a short preamble is to be used.
3471                  */
3472                 /* NB: cix is set above where RTS/CTS is enabled */
3473                 KASSERT(cix != 0xff, ("cix not setup"));
3474                 ctsrate = rt->info[cix].rateCode;
3475                 /*
3476                  * Compute the transmit duration based on the frame
3477                  * size and the size of an ACK frame.  We call into the
3478                  * HAL to do the computation since it depends on the
3479                  * characteristics of the actual PHY being used.
3480                  *
3481                  * NB: CTS is assumed the same size as an ACK so we can
3482                  *     use the precalculated ACK durations.
3483                  */
3484                 if (shortPreamble) {
3485                         ctsrate |= rt->info[cix].shortPreamble;
3486                         if (flags & HAL_TXDESC_RTSENA)          /* SIFS + CTS */
3487                                 ctsduration += rt->info[cix].spAckDuration;
3488                         ctsduration += ath_hal_computetxtime(ah,
3489                                 rt, pktlen, rix, AH_TRUE);
3490                         if ((flags & HAL_TXDESC_NOACK) == 0)    /* SIFS + ACK */
3491                                 ctsduration += rt->info[rix].spAckDuration;
3492                 } else {
3493                         if (flags & HAL_TXDESC_RTSENA)          /* SIFS + CTS */
3494                                 ctsduration += rt->info[cix].lpAckDuration;
3495                         ctsduration += ath_hal_computetxtime(ah,
3496                                 rt, pktlen, rix, AH_FALSE);
3497                         if ((flags & HAL_TXDESC_NOACK) == 0)    /* SIFS + ACK */
3498                                 ctsduration += rt->info[rix].lpAckDuration;
3499                 }
3500                 /*
3501                  * Must disable multi-rate retry when using RTS/CTS.
3502                  */
3503                 ismrr = 0;
3504                 try0 = ATH_TXMGTTRY;            /* XXX */
3505         } else
3506                 ctsrate = 0;
3507
3508         if (IFF_DUMPPKTS(sc, ATH_DEBUG_XMIT))
3509                 ieee80211_dump_pkt(mtod(m0, caddr_t), m0->m_len,
3510                         sc->sc_hwmap[txrate].ieeerate, -1);
3511
3512         if (ic->ic_rawbpf)
3513                 bpf_mtap(ic->ic_rawbpf, m0);
3514         if (sc->sc_drvbpf) {
3515                 u_int64_t tsf = ath_hal_gettsf64(ah);
3516
3517                 sc->sc_tx_th.wt_tsf = htole64(tsf);
3518                 sc->sc_tx_th.wt_flags = sc->sc_hwmap[txrate].txflags;
3519                 if (iswep)
3520                         sc->sc_tx_th.wt_flags |= IEEE80211_RADIOTAP_F_WEP;
3521                 sc->sc_tx_th.wt_rate = sc->sc_hwmap[txrate].ieeerate;
3522                 sc->sc_tx_th.wt_txpower = ni->ni_txpower;
3523                 sc->sc_tx_th.wt_antenna = sc->sc_txantenna;
3524
3525                 bpf_mtap2(sc->sc_drvbpf,
3526                         &sc->sc_tx_th, sc->sc_tx_th_len, m0);
3527         }
3528
3529         /* 
3530          * Determine if a tx interrupt should be generated for
3531          * this descriptor.  We take a tx interrupt to reap
3532          * descriptors when the h/w hits an EOL condition or
3533          * when the descriptor is specifically marked to generate
3534          * an interrupt.  We periodically mark descriptors in this
3535          * way to insure timely replenishing of the supply needed
3536          * for sending frames.  Defering interrupts reduces system
3537          * load and potentially allows more concurrent work to be
3538          * done but if done to aggressively can cause senders to
3539          * backup.
3540          *
3541          * NB: use >= to deal with sc_txintrperiod changing
3542          *     dynamically through sysctl.
3543          */
3544         if (flags & HAL_TXDESC_INTREQ) {
3545                 txq->axq_intrcnt = 0;
3546         } else if (++txq->axq_intrcnt >= sc->sc_txintrperiod) {
3547                 flags |= HAL_TXDESC_INTREQ;
3548                 txq->axq_intrcnt = 0;
3549         }
3550
3551         /*
3552          * Formulate first tx descriptor with tx controls.
3553          */
3554         /* XXX check return value? */
3555         ath_hal_setuptxdesc(ah, ds
3556                 , pktlen                /* packet length */
3557                 , hdrlen                /* header length */
3558                 , atype                 /* Atheros packet type */
3559                 , ni->ni_txpower        /* txpower */
3560                 , txrate, try0          /* series 0 rate/tries */
3561                 , keyix                 /* key cache index */
3562                 , sc->sc_txantenna      /* antenna mode */
3563                 , flags                 /* flags */
3564                 , ctsrate               /* rts/cts rate */
3565                 , ctsduration           /* rts/cts duration */
3566         );
3567         bf->bf_flags = flags;
3568         /*
3569          * Setup the multi-rate retry state only when we're
3570          * going to use it.  This assumes ath_hal_setuptxdesc
3571          * initializes the descriptors (so we don't have to)
3572          * when the hardware supports multi-rate retry and
3573          * we don't use it.
3574          */
3575         if (ismrr)
3576                 ath_rate_setupxtxdesc(sc, an, ds, shortPreamble, rix);
3577
3578         /*
3579          * Fillin the remainder of the descriptor info.
3580          */
3581         ds0 = ds;
3582         for (i = 0; i < bf->bf_nseg; i++, ds++) {
3583                 ds->ds_data = bf->bf_segs[i].ds_addr;
3584                 if (i == bf->bf_nseg - 1)
3585                         ds->ds_link = 0;
3586                 else
3587                         ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
3588                 ath_hal_filltxdesc(ah, ds
3589                         , bf->bf_segs[i].ds_len /* segment length */
3590                         , i == 0                /* first segment */
3591                         , i == bf->bf_nseg - 1  /* last segment */
3592                         , ds0                   /* first descriptor */
3593                 );
3594                 DPRINTF(sc, ATH_DEBUG_XMIT,
3595                         "%s: %d: %08x %08x %08x %08x %08x %08x\n",
3596                         __func__, i, ds->ds_link, ds->ds_data,
3597                         ds->ds_ctl0, ds->ds_ctl1, ds->ds_hw[0], ds->ds_hw[1]);
3598         }
3599         /*
3600          * Insert the frame on the outbound list and
3601          * pass it on to the hardware.
3602          */
3603         ATH_TXQ_LOCK(txq);
3604         ATH_TXQ_INSERT_TAIL(txq, bf, bf_list);
3605         if (txq->axq_link == NULL) {
3606                 ath_hal_puttxbuf(ah, txq->axq_qnum, bf->bf_daddr);
3607                 DPRINTF(sc, ATH_DEBUG_XMIT,
3608                         "%s: TXDP[%u] = %p (%p) depth %d\n", __func__,
3609                         txq->axq_qnum, (caddr_t)bf->bf_daddr, bf->bf_desc,
3610                         txq->axq_depth);
3611         } else {
3612                 *txq->axq_link = bf->bf_daddr;
3613                 DPRINTF(sc, ATH_DEBUG_XMIT,
3614                         "%s: link[%u](%p)=%p (%p) depth %d\n", __func__,
3615                         txq->axq_qnum, txq->axq_link,
3616                         (caddr_t)bf->bf_daddr, bf->bf_desc, txq->axq_depth);
3617         }
3618         txq->axq_link = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
3619         /*
3620          * The CAB queue is started from the SWBA handler since
3621          * frames only go out on DTIM and to avoid possible races.
3622          */
3623         if (txq != sc->sc_cabq)
3624                 ath_hal_txstart(ah, txq->axq_qnum);
3625         ATH_TXQ_UNLOCK(txq);
3626
3627         return 0;
3628 }
3629
3630 /*
3631  * Process completed xmit descriptors from the specified queue.
3632  */
3633 static void
3634 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq)
3635 {
3636         struct ath_hal *ah = sc->sc_ah;
3637         struct ieee80211com *ic = &sc->sc_ic;
3638         struct ath_buf *bf;
3639         struct ath_desc *ds, *ds0;
3640         struct ieee80211_node *ni;
3641         struct ath_node *an;
3642         int sr, lr, pri;
3643         HAL_STATUS status;
3644
3645         DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
3646                 __func__, txq->axq_qnum,
3647                 (caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
3648                 txq->axq_link);
3649         for (;;) {
3650                 ATH_TXQ_LOCK(txq);
3651                 txq->axq_intrcnt = 0;   /* reset periodic desc intr count */
3652                 bf = STAILQ_FIRST(&txq->axq_q);
3653                 if (bf == NULL) {
3654                         txq->axq_link = NULL;
3655                         ATH_TXQ_UNLOCK(txq);
3656                         break;
3657                 }
3658                 ds0 = &bf->bf_desc[0];
3659                 ds = &bf->bf_desc[bf->bf_nseg - 1];
3660                 status = ath_hal_txprocdesc(ah, ds);
3661 #ifdef AR_DEBUG
3662                 if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
3663                         ath_printtxbuf(bf, status == HAL_OK);
3664 #endif
3665                 if (status == HAL_EINPROGRESS) {
3666                         ATH_TXQ_UNLOCK(txq);
3667                         break;
3668                 }
3669                 ATH_TXQ_REMOVE_HEAD(txq, bf_list);
3670                 ATH_TXQ_UNLOCK(txq);
3671
3672                 ni = bf->bf_node;
3673                 if (ni != NULL) {
3674                         an = ATH_NODE(ni);
3675                         if (ds->ds_txstat.ts_status == 0) {
3676                                 u_int8_t txant = ds->ds_txstat.ts_antenna;
3677                                 sc->sc_stats.ast_ant_tx[txant]++;
3678                                 sc->sc_ant_tx[txant]++;
3679                                 if (ds->ds_txstat.ts_rate & HAL_TXSTAT_ALTRATE)
3680                                         sc->sc_stats.ast_tx_altrate++;
3681                                 sc->sc_stats.ast_tx_rssi =
3682                                         ds->ds_txstat.ts_rssi;
3683                                 ATH_RSSI_LPF(an->an_halstats.ns_avgtxrssi,
3684                                         ds->ds_txstat.ts_rssi);
3685                                 pri = M_WME_GETAC(bf->bf_m);
3686                                 if (pri >= WME_AC_VO)
3687                                         ic->ic_wme.wme_hipri_traffic++;
3688                                 ni->ni_inact = ni->ni_inact_reload;
3689                         } else {
3690                                 if (ds->ds_txstat.ts_status & HAL_TXERR_XRETRY)
3691                                         sc->sc_stats.ast_tx_xretries++;
3692                                 if (ds->ds_txstat.ts_status & HAL_TXERR_FIFO)
3693                                         sc->sc_stats.ast_tx_fifoerr++;
3694                                 if (ds->ds_txstat.ts_status & HAL_TXERR_FILT)
3695                                         sc->sc_stats.ast_tx_filtered++;
3696                         }
3697                         sr = ds->ds_txstat.ts_shortretry;
3698                         lr = ds->ds_txstat.ts_longretry;
3699                         sc->sc_stats.ast_tx_shortretry += sr;
3700                         sc->sc_stats.ast_tx_longretry += lr;
3701                         /*
3702                          * Hand the descriptor to the rate control algorithm.
3703                          */
3704                         if ((ds->ds_txstat.ts_status & HAL_TXERR_FILT) == 0 &&
3705                             (bf->bf_flags & HAL_TXDESC_NOACK) == 0)
3706                                 ath_rate_tx_complete(sc, an, ds, ds0);
3707                         /*
3708                          * Reclaim reference to node.
3709                          *
3710                          * NB: the node may be reclaimed here if, for example
3711                          *     this is a DEAUTH message that was sent and the
3712                          *     node was timed out due to inactivity.
3713                          */
3714                         ieee80211_free_node(ni);
3715                 }
3716                 bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3717                     BUS_DMASYNC_POSTWRITE);
3718                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3719                 m_freem(bf->bf_m);
3720                 bf->bf_m = NULL;
3721                 bf->bf_node = NULL;
3722
3723                 ATH_TXBUF_LOCK(sc);
3724                 STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
3725                 ATH_TXBUF_UNLOCK(sc);
3726         }
3727 }
3728
3729 /*
3730  * Deferred processing of transmit interrupt; special-cased
3731  * for a single hardware transmit queue (e.g. 5210 and 5211).
3732  */
3733 static void
3734 ath_tx_proc_q0(void *arg, int npending)
3735 {
3736         struct ath_softc *sc = arg;
3737         struct ifnet *ifp = sc->sc_ifp;
3738
3739         ath_tx_processq(sc, &sc->sc_txq[0]);
3740         ath_tx_processq(sc, sc->sc_cabq);
3741         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3742         sc->sc_tx_timer = 0;
3743
3744         if (sc->sc_softled)
3745                 ath_led_event(sc, ATH_LED_TX);
3746
3747         ath_start(ifp);
3748 }
3749
3750 /*
3751  * Deferred processing of transmit interrupt; special-cased
3752  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
3753  */
3754 static void
3755 ath_tx_proc_q0123(void *arg, int npending)
3756 {
3757         struct ath_softc *sc = arg;
3758         struct ifnet *ifp = sc->sc_ifp;
3759
3760         /*
3761          * Process each active queue.
3762          */
3763         ath_tx_processq(sc, &sc->sc_txq[0]);
3764         ath_tx_processq(sc, &sc->sc_txq[1]);
3765         ath_tx_processq(sc, &sc->sc_txq[2]);
3766         ath_tx_processq(sc, &sc->sc_txq[3]);
3767         ath_tx_processq(sc, sc->sc_cabq);
3768
3769         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3770         sc->sc_tx_timer = 0;
3771
3772         if (sc->sc_softled)
3773                 ath_led_event(sc, ATH_LED_TX);
3774
3775         ath_start(ifp);
3776 }
3777
3778 /*
3779  * Deferred processing of transmit interrupt.
3780  */
3781 static void
3782 ath_tx_proc(void *arg, int npending)
3783 {
3784         struct ath_softc *sc = arg;
3785         struct ifnet *ifp = sc->sc_ifp;
3786         int i;
3787
3788         /*
3789          * Process each active queue.
3790          */
3791         /* XXX faster to read ISR_S0_S and ISR_S1_S to determine q's? */
3792         for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3793                 if (ATH_TXQ_SETUP(sc, i))
3794                         ath_tx_processq(sc, &sc->sc_txq[i]);
3795
3796         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3797         sc->sc_tx_timer = 0;
3798
3799         if (sc->sc_softled)
3800                 ath_led_event(sc, ATH_LED_TX);
3801
3802         ath_start(ifp);
3803 }
3804
3805 static void
3806 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
3807 {
3808         struct ath_hal *ah = sc->sc_ah;
3809         struct ieee80211_node *ni;
3810         struct ath_buf *bf;
3811
3812         /*
3813          * NB: this assumes output has been stopped and
3814          *     we do not need to block ath_tx_tasklet
3815          */
3816         for (;;) {
3817                 ATH_TXQ_LOCK(txq);
3818                 bf = STAILQ_FIRST(&txq->axq_q);
3819                 if (bf == NULL) {
3820                         txq->axq_link = NULL;
3821                         ATH_TXQ_UNLOCK(txq);
3822                         break;
3823                 }
3824                 ATH_TXQ_REMOVE_HEAD(txq, bf_list);
3825                 ATH_TXQ_UNLOCK(txq);
3826 #ifdef AR_DEBUG
3827                 if (sc->sc_debug & ATH_DEBUG_RESET)
3828                         ath_printtxbuf(bf,
3829                                 ath_hal_txprocdesc(ah, bf->bf_desc) == HAL_OK);
3830 #endif /* AR_DEBUG */
3831                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3832                 m_freem(bf->bf_m);
3833                 bf->bf_m = NULL;
3834                 ni = bf->bf_node;
3835                 bf->bf_node = NULL;
3836                 if (ni != NULL) {
3837                         /*
3838                          * Reclaim node reference.
3839                          */
3840                         ieee80211_free_node(ni);
3841                 }
3842                 ATH_TXBUF_LOCK(sc);
3843                 STAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
3844                 ATH_TXBUF_UNLOCK(sc);
3845         }
3846 }
3847
3848 static void
3849 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
3850 {
3851         struct ath_hal *ah = sc->sc_ah;
3852
3853         (void) ath_hal_stoptxdma(ah, txq->axq_qnum);
3854         DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
3855             __func__, txq->axq_qnum,
3856             (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
3857             txq->axq_link);
3858 }
3859
3860 /*
3861  * Drain the transmit queues and reclaim resources.
3862  */
3863 static void
3864 ath_draintxq(struct ath_softc *sc)
3865 {
3866         struct ath_hal *ah = sc->sc_ah;
3867         struct ifnet *ifp = sc->sc_ifp;
3868         int i;
3869
3870         /* XXX return value */
3871         if (!sc->sc_invalid) {
3872                 /* don't touch the hardware if marked invalid */
3873                 (void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
3874                 DPRINTF(sc, ATH_DEBUG_RESET,
3875                     "%s: beacon queue %p\n", __func__,
3876                     (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq));
3877                 for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3878                         if (ATH_TXQ_SETUP(sc, i))
3879                                 ath_tx_stopdma(sc, &sc->sc_txq[i]);
3880         }
3881         for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
3882                 if (ATH_TXQ_SETUP(sc, i))
3883                         ath_tx_draintxq(sc, &sc->sc_txq[i]);
3884         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3885         sc->sc_tx_timer = 0;
3886 }
3887
3888 /*
3889  * Disable the receive h/w in preparation for a reset.
3890  */
3891 static void
3892 ath_stoprecv(struct ath_softc *sc)
3893 {
3894 #define PA2DESC(_sc, _pa) \
3895         ((struct ath_desc *)((caddr_t)(_sc)->sc_rxdma.dd_desc + \
3896                 ((_pa) - (_sc)->sc_rxdma.dd_desc_paddr)))
3897         struct ath_hal *ah = sc->sc_ah;
3898
3899         ath_hal_stoppcurecv(ah);        /* disable PCU */
3900         ath_hal_setrxfilter(ah, 0);     /* clear recv filter */
3901         ath_hal_stopdmarecv(ah);        /* disable DMA engine */
3902         DELAY(3000);                    /* 3ms is long enough for 1 frame */
3903 #ifdef AR_DEBUG
3904         if (sc->sc_debug & (ATH_DEBUG_RESET | ATH_DEBUG_FATAL)) {
3905                 struct ath_buf *bf;
3906
3907                 printf("%s: rx queue %p, link %p\n", __func__,
3908                         (caddr_t)(uintptr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink);
3909                 STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
3910                         struct ath_desc *ds = bf->bf_desc;
3911                         HAL_STATUS status = ath_hal_rxprocdesc(ah, ds,
3912                                 bf->bf_daddr, PA2DESC(sc, ds->ds_link));
3913                         if (status == HAL_OK || (sc->sc_debug & ATH_DEBUG_FATAL))
3914                                 ath_printrxbuf(bf, status == HAL_OK);
3915                 }
3916         }
3917 #endif
3918         sc->sc_rxlink = NULL;           /* just in case */
3919 #undef PA2DESC
3920 }
3921
3922 /*
3923  * Enable the receive h/w following a reset.
3924  */
3925 static int
3926 ath_startrecv(struct ath_softc *sc)
3927 {
3928         struct ath_hal *ah = sc->sc_ah;
3929         struct ath_buf *bf;
3930
3931         sc->sc_rxlink = NULL;
3932         STAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
3933                 int error = ath_rxbuf_init(sc, bf);
3934                 if (error != 0) {
3935                         DPRINTF(sc, ATH_DEBUG_RECV,
3936                                 "%s: ath_rxbuf_init failed %d\n",
3937                                 __func__, error);
3938                         return error;
3939                 }
3940         }
3941
3942         bf = STAILQ_FIRST(&sc->sc_rxbuf);
3943         ath_hal_putrxbuf(ah, bf->bf_daddr);
3944         ath_hal_rxena(ah);              /* enable recv descriptors */
3945         ath_mode_init(sc);              /* set filters, etc. */
3946         ath_hal_startpcurecv(ah);       /* re-enable PCU/DMA engine */
3947         return 0;
3948 }
3949
3950 /* 
3951  * Update internal state after a channel change.
3952  */
3953 static void
3954 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
3955 {
3956         struct ieee80211com *ic = &sc->sc_ic;
3957         enum ieee80211_phymode mode;
3958         u_int16_t flags;
3959
3960         /*
3961          * Change channels and update the h/w rate map
3962          * if we're switching; e.g. 11a to 11b/g.
3963          */
3964         mode = ieee80211_chan2mode(ic, chan);
3965         if (mode != sc->sc_curmode)
3966                 ath_setcurmode(sc, mode);
3967         /*
3968          * Update BPF state.  NB: ethereal et. al. don't handle
3969          * merged flags well so pick a unique mode for their use.
3970          */
3971         if (IEEE80211_IS_CHAN_A(chan))
3972                 flags = IEEE80211_CHAN_A;
3973         /* XXX 11g schizophrenia */
3974         else if (IEEE80211_IS_CHAN_G(chan) ||
3975             IEEE80211_IS_CHAN_PUREG(chan))
3976                 flags = IEEE80211_CHAN_G;
3977         else
3978                 flags = IEEE80211_CHAN_B;
3979         if (IEEE80211_IS_CHAN_T(chan))
3980                 flags |= IEEE80211_CHAN_TURBO;
3981         sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq =
3982                 htole16(chan->ic_freq);
3983         sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags =
3984                 htole16(flags);
3985 }
3986
3987 /*
3988  * Set/change channels.  If the channel is really being changed,
3989  * it's done by reseting the chip.  To accomplish this we must
3990  * first cleanup any pending DMA, then restart stuff after a la
3991  * ath_init.
3992  */
3993 static int
3994 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
3995 {
3996         struct ath_hal *ah = sc->sc_ah;
3997         struct ieee80211com *ic = &sc->sc_ic;
3998         HAL_CHANNEL hchan;
3999
4000         /*
4001          * Convert to a HAL channel description with
4002          * the flags constrained to reflect the current
4003          * operating mode.
4004          */
4005         hchan.channel = chan->ic_freq;
4006         hchan.channelFlags = ath_chan2flags(ic, chan);
4007
4008         DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz) -> %u (%u MHz)\n",
4009             __func__,
4010             ath_hal_mhz2ieee(sc->sc_curchan.channel,
4011                 sc->sc_curchan.channelFlags),
4012                 sc->sc_curchan.channel,
4013             ath_hal_mhz2ieee(hchan.channel, hchan.channelFlags), hchan.channel);
4014         if (hchan.channel != sc->sc_curchan.channel ||
4015             hchan.channelFlags != sc->sc_curchan.channelFlags) {
4016                 HAL_STATUS status;
4017
4018                 /*
4019                  * To switch channels clear any pending DMA operations;
4020                  * wait long enough for the RX fifo to drain, reset the
4021                  * hardware at the new frequency, and then re-enable
4022                  * the relevant bits of the h/w.
4023                  */
4024                 ath_hal_intrset(ah, 0);         /* disable interrupts */
4025                 ath_draintxq(sc);               /* clear pending tx frames */
4026                 ath_stoprecv(sc);               /* turn off frame recv */
4027                 if (!ath_hal_reset(ah, ic->ic_opmode, &hchan, AH_TRUE, &status)) {
4028                         if_printf(ic->ic_ifp, "ath_chan_set: unable to reset "
4029                                 "channel %u (%u Mhz)\n",
4030                                 ieee80211_chan2ieee(ic, chan), chan->ic_freq);
4031                         return EIO;
4032                 }
4033                 sc->sc_curchan = hchan;
4034                 ath_update_txpow(sc);           /* update tx power state */
4035                 sc->sc_diversity = ath_hal_getdiversity(ah);
4036
4037                 /*
4038                  * Re-enable rx framework.
4039                  */
4040                 if (ath_startrecv(sc) != 0) {
4041                         if_printf(ic->ic_ifp,
4042                                 "ath_chan_set: unable to restart recv logic\n");
4043                         return EIO;
4044                 }
4045
4046                 /*
4047                  * Change channels and update the h/w rate map
4048                  * if we're switching; e.g. 11a to 11b/g.
4049                  */
4050                 ic->ic_ibss_chan = chan;
4051                 ath_chan_change(sc, chan);
4052
4053                 /*
4054                  * Re-enable interrupts.
4055                  */
4056                 ath_hal_intrset(ah, sc->sc_imask);
4057         }
4058         return 0;
4059 }
4060
4061 static void
4062 ath_next_scan(void *arg)
4063 {
4064         struct ath_softc *sc = arg;
4065         struct ieee80211com *ic = &sc->sc_ic;
4066
4067         if (ic->ic_state == IEEE80211_S_SCAN)
4068                 ieee80211_next_scan(ic);
4069 }
4070
4071 /*
4072  * Periodically recalibrate the PHY to account
4073  * for temperature/environment changes.
4074  */
4075 static void
4076 ath_calibrate(void *arg)
4077 {
4078         struct ath_softc *sc = arg;
4079         struct ath_hal *ah = sc->sc_ah;
4080
4081         sc->sc_stats.ast_per_cal++;
4082
4083         DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: channel %u/%x\n",
4084                 __func__, sc->sc_curchan.channel, sc->sc_curchan.channelFlags);
4085
4086         if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
4087                 /*
4088                  * Rfgain is out of bounds, reset the chip
4089                  * to load new gain values.
4090                  */
4091                 sc->sc_stats.ast_per_rfgain++;
4092                 ath_reset(sc->sc_ifp);
4093         }
4094         if (!ath_hal_calibrate(ah, &sc->sc_curchan)) {
4095                 DPRINTF(sc, ATH_DEBUG_ANY,
4096                         "%s: calibration of channel %u failed\n",
4097                         __func__, sc->sc_curchan.channel);
4098                 sc->sc_stats.ast_per_calfail++;
4099         }
4100         /*
4101          * Calibrate noise floor data again in case of change.
4102          */
4103         ath_hal_process_noisefloor(ah);
4104         callout_reset(&sc->sc_cal_ch, ath_calinterval * hz, ath_calibrate, sc);
4105 }
4106
4107 static int
4108 ath_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
4109 {
4110         struct ifnet *ifp = ic->ic_ifp;
4111         struct ath_softc *sc = ifp->if_softc;
4112         struct ath_hal *ah = sc->sc_ah;
4113         struct ieee80211_node *ni;
4114         int i, error;
4115         const u_int8_t *bssid;
4116         u_int32_t rfilt;
4117         static const HAL_LED_STATE leds[] = {
4118             HAL_LED_INIT,       /* IEEE80211_S_INIT */
4119             HAL_LED_SCAN,       /* IEEE80211_S_SCAN */
4120             HAL_LED_AUTH,       /* IEEE80211_S_AUTH */
4121             HAL_LED_ASSOC,      /* IEEE80211_S_ASSOC */
4122             HAL_LED_RUN,        /* IEEE80211_S_RUN */
4123         };
4124
4125         DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
4126                 ieee80211_state_name[ic->ic_state],
4127                 ieee80211_state_name[nstate]);
4128
4129         callout_stop(&sc->sc_scan_ch);
4130         callout_stop(&sc->sc_cal_ch);
4131         ath_hal_setledstate(ah, leds[nstate]);  /* set LED */
4132
4133         if (nstate == IEEE80211_S_INIT) {
4134                 sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4135                 /*
4136                  * NB: disable interrupts so we don't rx frames.
4137                  */
4138                 ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
4139                 /*
4140                  * Notify the rate control algorithm.
4141                  */
4142                 ath_rate_newstate(sc, nstate);
4143                 goto done;
4144         }
4145         ni = ic->ic_bss;
4146         error = ath_chan_set(sc, ic->ic_curchan);
4147         if (error != 0)
4148                 goto bad;
4149         rfilt = ath_calcrxfilter(sc, nstate);
4150         if (nstate == IEEE80211_S_SCAN)
4151                 bssid = ifp->if_broadcastaddr;
4152         else
4153                 bssid = ni->ni_bssid;
4154         ath_hal_setrxfilter(ah, rfilt);
4155         DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s\n",
4156                  __func__, rfilt, ether_sprintf(bssid));
4157
4158         if (nstate == IEEE80211_S_RUN && ic->ic_opmode == IEEE80211_M_STA)
4159                 ath_hal_setassocid(ah, bssid, ni->ni_associd);
4160         else
4161                 ath_hal_setassocid(ah, bssid, 0);
4162         if (ic->ic_flags & IEEE80211_F_PRIVACY) {
4163                 for (i = 0; i < IEEE80211_WEP_NKID; i++)
4164                         if (ath_hal_keyisvalid(ah, i))
4165                                 ath_hal_keysetmac(ah, i, bssid);
4166         }
4167
4168         /*
4169          * Notify the rate control algorithm so rates
4170          * are setup should ath_beacon_alloc be called.
4171          */
4172         ath_rate_newstate(sc, nstate);
4173
4174         if (ic->ic_opmode == IEEE80211_M_MONITOR) {
4175                 /* nothing to do */;
4176         } else if (nstate == IEEE80211_S_RUN) {
4177                 DPRINTF(sc, ATH_DEBUG_STATE,
4178                         "%s(RUN): ic_flags=0x%08x iv=%d bssid=%s "
4179                         "capinfo=0x%04x chan=%d\n"
4180                          , __func__
4181                          , ic->ic_flags
4182                          , ni->ni_intval
4183                          , ether_sprintf(ni->ni_bssid)
4184                          , ni->ni_capinfo
4185                          , ieee80211_chan2ieee(ic, ic->ic_curchan));
4186
4187                 switch (ic->ic_opmode) {
4188                 case IEEE80211_M_HOSTAP:
4189                 case IEEE80211_M_IBSS:
4190                         /*
4191                          * Allocate and setup the beacon frame.
4192                          *
4193                          * Stop any previous beacon DMA.  This may be
4194                          * necessary, for example, when an ibss merge
4195                          * causes reconfiguration; there will be a state
4196                          * transition from RUN->RUN that means we may
4197                          * be called with beacon transmission active.
4198                          */
4199                         ath_hal_stoptxdma(ah, sc->sc_bhalq);
4200                         ath_beacon_free(sc);
4201                         error = ath_beacon_alloc(sc, ni);
4202                         if (error != 0)
4203                                 goto bad;
4204                         break;
4205                 case IEEE80211_M_STA:
4206                         /*
4207                          * Allocate a key cache slot to the station.
4208                          */
4209                         if ((ic->ic_flags & IEEE80211_F_PRIVACY) == 0 &&
4210                             sc->sc_hasclrkey &&
4211                             ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
4212                                 ath_setup_stationkey(ni);
4213                         break;
4214                 default:
4215                         break;
4216                 }
4217
4218                 /*
4219                  * Let the hal process statistics collected during a
4220                  * scan so it can provide calibrated noise floor data.
4221                  */
4222                 ath_hal_process_noisefloor(ah);
4223                 /*
4224                  * Configure the beacon and sleep timers.
4225                  */
4226                 ath_beacon_config(sc);
4227         } else {
4228                 ath_hal_intrset(ah,
4229                         sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
4230                 sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
4231         }
4232 done:
4233         /*
4234          * Invoke the parent method to complete the work.
4235          */
4236         error = sc->sc_newstate(ic, nstate, arg);
4237         /*
4238          * Finally, start any timers.
4239          */
4240         if (nstate == IEEE80211_S_RUN) {
4241                 /* start periodic recalibration timer */
4242                 callout_reset(&sc->sc_cal_ch, ath_calinterval * hz,
4243                         ath_calibrate, sc);
4244         } else if (nstate == IEEE80211_S_SCAN) {
4245                 /* start ap/neighbor scan timer */
4246                 callout_reset(&sc->sc_scan_ch, (ath_dwelltime * hz) / 1000,
4247                         ath_next_scan, sc);
4248         }
4249 bad:
4250         return error;
4251 }
4252
4253 /*
4254  * Allocate a key cache slot to the station so we can
4255  * setup a mapping from key index to node. The key cache
4256  * slot is needed for managing antenna state and for
4257  * compression when stations do not use crypto.  We do
4258  * it uniliaterally here; if crypto is employed this slot
4259  * will be reassigned.
4260  */
4261 static void
4262 ath_setup_stationkey(struct ieee80211_node *ni)
4263 {
4264         struct ieee80211com *ic = ni->ni_ic;
4265         struct ath_softc *sc = ic->ic_ifp->if_softc;
4266         ieee80211_keyix keyix, rxkeyix;
4267
4268         if (!ath_key_alloc(ic, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
4269                 /*
4270                  * Key cache is full; we'll fall back to doing
4271                  * the more expensive lookup in software.  Note
4272                  * this also means no h/w compression.
4273                  */
4274                 /* XXX msg+statistic */
4275         } else {
4276                 /* XXX locking? */
4277                 ni->ni_ucastkey.wk_keyix = keyix;
4278                 ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
4279                 /* NB: this will create a pass-thru key entry */
4280                 ath_keyset(sc, &ni->ni_ucastkey, ni->ni_macaddr, ic->ic_bss);
4281         }
4282 }
4283
4284 /*
4285  * Setup driver-specific state for a newly associated node.
4286  * Note that we're called also on a re-associate, the isnew
4287  * param tells us if this is the first time or not.
4288  */
4289 static void
4290 ath_newassoc(struct ieee80211_node *ni, int isnew)
4291 {
4292         struct ieee80211com *ic = ni->ni_ic;
4293         struct ath_softc *sc = ic->ic_ifp->if_softc;
4294
4295         ath_rate_newassoc(sc, ATH_NODE(ni), isnew);
4296         if (isnew &&
4297             (ic->ic_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey) {
4298                 KASSERT(ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE,
4299                     ("new assoc with a unicast key already setup (keyix %u)",
4300                     ni->ni_ucastkey.wk_keyix));
4301                 ath_setup_stationkey(ni);
4302         }
4303 }
4304
4305 static int
4306 ath_getchannels(struct ath_softc *sc, u_int cc,
4307         HAL_BOOL outdoor, HAL_BOOL xchanmode)
4308 {
4309         struct ieee80211com *ic = &sc->sc_ic;
4310         struct ifnet *ifp = sc->sc_ifp;
4311         struct ath_hal *ah = sc->sc_ah;
4312         HAL_CHANNEL *chans;
4313         int i, ix, nchan;
4314
4315         chans = malloc(IEEE80211_CHAN_MAX * sizeof(HAL_CHANNEL),
4316                         M_TEMP, M_NOWAIT);
4317         if (chans == NULL) {
4318                 if_printf(ifp, "unable to allocate channel table\n");
4319                 return ENOMEM;
4320         }
4321         if (!ath_hal_init_channels(ah, chans, IEEE80211_CHAN_MAX, &nchan,
4322             cc, HAL_MODE_ALL, outdoor, xchanmode)) {
4323                 u_int32_t rd;
4324
4325                 ath_hal_getregdomain(ah, &rd);
4326                 if_printf(ifp, "unable to collect channel list from hal; "
4327                         "regdomain likely %u country code %u\n", rd, cc);
4328                 free(chans, M_TEMP);
4329                 return EINVAL;
4330         }
4331
4332         /*
4333          * Convert HAL channels to ieee80211 ones and insert
4334          * them in the table according to their channel number.
4335          */
4336         for (i = 0; i < nchan; i++) {
4337                 HAL_CHANNEL *c = &chans[i];
4338                 ix = ath_hal_mhz2ieee(c->channel, c->channelFlags);
4339                 if (ix > IEEE80211_CHAN_MAX) {
4340                         if_printf(ifp, "bad hal channel %u (%u/%x) ignored\n",
4341                                 ix, c->channel, c->channelFlags);
4342                         continue;
4343                 }
4344                 /* NB: flags are known to be compatible */
4345                 if (ic->ic_channels[ix].ic_freq == 0) {
4346                         ic->ic_channels[ix].ic_freq = c->channel;
4347                         ic->ic_channels[ix].ic_flags = c->channelFlags;
4348                 } else {
4349                         /* channels overlap; e.g. 11g and 11b */
4350                         ic->ic_channels[ix].ic_flags |= c->channelFlags;
4351                 }
4352         }
4353         free(chans, M_TEMP);
4354         return 0;
4355 }
4356
4357 static void
4358 ath_led_done(void *arg)
4359 {
4360         struct ath_softc *sc = arg;
4361
4362         sc->sc_blinking = 0;
4363 }
4364
4365 /*
4366  * Turn the LED off: flip the pin and then set a timer so no
4367  * update will happen for the specified duration.
4368  */
4369 static void
4370 ath_led_off(void *arg)
4371 {
4372         struct ath_softc *sc = arg;
4373
4374         ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, !sc->sc_ledon);
4375         callout_reset(&sc->sc_ledtimer, sc->sc_ledoff, ath_led_done, sc);
4376 }
4377
4378 /*
4379  * Blink the LED according to the specified on/off times.
4380  */
4381 static void
4382 ath_led_blink(struct ath_softc *sc, int on, int off)
4383 {
4384         DPRINTF(sc, ATH_DEBUG_LED, "%s: on %u off %u\n", __func__, on, off);
4385         ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin, sc->sc_ledon);
4386         sc->sc_blinking = 1;
4387         sc->sc_ledoff = off;
4388         callout_reset(&sc->sc_ledtimer, on, ath_led_off, sc);
4389 }
4390
4391 static void
4392 ath_led_event(struct ath_softc *sc, int event)
4393 {
4394
4395         sc->sc_ledevent = ticks;        /* time of last event */
4396         if (sc->sc_blinking)            /* don't interrupt active blink */
4397                 return;
4398         switch (event) {
4399         case ATH_LED_POLL:
4400                 ath_led_blink(sc, sc->sc_hwmap[0].ledon,
4401                         sc->sc_hwmap[0].ledoff);
4402                 break;
4403         case ATH_LED_TX:
4404                 ath_led_blink(sc, sc->sc_hwmap[sc->sc_txrate].ledon,
4405                         sc->sc_hwmap[sc->sc_txrate].ledoff);
4406                 break;
4407         case ATH_LED_RX:
4408                 ath_led_blink(sc, sc->sc_hwmap[sc->sc_rxrate].ledon,
4409                         sc->sc_hwmap[sc->sc_rxrate].ledoff);
4410                 break;
4411         }
4412 }
4413
4414 static void
4415 ath_update_txpow(struct ath_softc *sc)
4416 {
4417         struct ieee80211com *ic = &sc->sc_ic;
4418         struct ath_hal *ah = sc->sc_ah;
4419         u_int32_t txpow;
4420
4421         if (sc->sc_curtxpow != ic->ic_txpowlimit) {
4422                 ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
4423                 /* read back in case value is clamped */
4424                 ath_hal_gettxpowlimit(ah, &txpow);
4425                 ic->ic_txpowlimit = sc->sc_curtxpow = txpow;
4426         }
4427         /* 
4428          * Fetch max tx power level for status requests.
4429          */
4430         ath_hal_getmaxtxpow(sc->sc_ah, &txpow);
4431         ic->ic_bss->ni_txpower = txpow;
4432 }
4433
4434 static int
4435 ath_rate_setup(struct ath_softc *sc, u_int mode)
4436 {
4437         struct ath_hal *ah = sc->sc_ah;
4438         struct ieee80211com *ic = &sc->sc_ic;
4439         const HAL_RATE_TABLE *rt;
4440         struct ieee80211_rateset *rs;
4441         int i, maxrates;
4442
4443         switch (mode) {
4444         case IEEE80211_MODE_11A:
4445                 sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11A);
4446                 break;
4447         case IEEE80211_MODE_11B:
4448                 sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11B);
4449                 break;
4450         case IEEE80211_MODE_11G:
4451                 sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11G);
4452                 break;
4453         case IEEE80211_MODE_TURBO_A:
4454                 sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_TURBO);
4455                 break;
4456         case IEEE80211_MODE_TURBO_G:
4457                 sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_108G);
4458                 break;
4459         default:
4460                 DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
4461                         __func__, mode);
4462                 return 0;
4463         }
4464         rt = sc->sc_rates[mode];
4465         if (rt == NULL)
4466                 return 0;
4467         if (rt->rateCount > IEEE80211_RATE_MAXSIZE) {
4468                 DPRINTF(sc, ATH_DEBUG_ANY,
4469                         "%s: rate table too small (%u > %u)\n",
4470                         __func__, rt->rateCount, IEEE80211_RATE_MAXSIZE);
4471                 maxrates = IEEE80211_RATE_MAXSIZE;
4472         } else
4473                 maxrates = rt->rateCount;
4474         rs = &ic->ic_sup_rates[mode];
4475         for (i = 0; i < maxrates; i++)
4476                 rs->rs_rates[i] = rt->info[i].dot11Rate;
4477         rs->rs_nrates = maxrates;
4478         return 1;
4479 }
4480
4481 static void
4482 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
4483 {
4484 #define N(a)    (sizeof(a)/sizeof(a[0]))
4485         /* NB: on/off times from the Atheros NDIS driver, w/ permission */
4486         static const struct {
4487                 u_int           rate;           /* tx/rx 802.11 rate */
4488                 u_int16_t       timeOn;         /* LED on time (ms) */
4489                 u_int16_t       timeOff;        /* LED off time (ms) */
4490         } blinkrates[] = {
4491                 { 108,  40,  10 },
4492                 {  96,  44,  11 },
4493                 {  72,  50,  13 },
4494                 {  48,  57,  14 },
4495                 {  36,  67,  16 },
4496                 {  24,  80,  20 },
4497                 {  22, 100,  25 },
4498                 {  18, 133,  34 },
4499                 {  12, 160,  40 },
4500                 {  10, 200,  50 },
4501                 {   6, 240,  58 },
4502                 {   4, 267,  66 },
4503                 {   2, 400, 100 },
4504                 {   0, 500, 130 },
4505         };
4506         const HAL_RATE_TABLE *rt;
4507         int i, j;
4508
4509         memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
4510         rt = sc->sc_rates[mode];
4511         KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
4512         for (i = 0; i < rt->rateCount; i++)
4513                 sc->sc_rixmap[rt->info[i].dot11Rate & IEEE80211_RATE_VAL] = i;
4514         memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
4515         for (i = 0; i < 32; i++) {
4516                 u_int8_t ix = rt->rateCodeToIndex[i];
4517                 if (ix == 0xff) {
4518                         sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
4519                         sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
4520                         continue;
4521                 }
4522                 sc->sc_hwmap[i].ieeerate =
4523                         rt->info[ix].dot11Rate & IEEE80211_RATE_VAL;
4524                 sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
4525                 if (rt->info[ix].shortPreamble ||
4526                     rt->info[ix].phy == IEEE80211_T_OFDM)
4527                         sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
4528                 /* NB: receive frames include FCS */
4529                 sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags |
4530                         IEEE80211_RADIOTAP_F_FCS;
4531                 /* setup blink rate table to avoid per-packet lookup */
4532                 for (j = 0; j < N(blinkrates)-1; j++)
4533                         if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
4534                                 break;
4535                 /* NB: this uses the last entry if the rate isn't found */
4536                 /* XXX beware of overlow */
4537                 sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
4538                 sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
4539         }
4540         sc->sc_currates = rt;
4541         sc->sc_curmode = mode;
4542         /*
4543          * All protection frames are transmited at 2Mb/s for
4544          * 11g, otherwise at 1Mb/s.
4545          */
4546         if (mode == IEEE80211_MODE_11G)
4547                 sc->sc_protrix = ath_tx_findrix(rt, 2*2);
4548         else
4549                 sc->sc_protrix = ath_tx_findrix(rt, 2*1);
4550         /* rate index used to send management frames */
4551         sc->sc_minrateix = 0;
4552         /*
4553          * Setup multicast rate state.
4554          */
4555         /* XXX layering violation */
4556         sc->sc_mcastrix = ath_tx_findrix(rt, sc->sc_ic.ic_mcast_rate);
4557         sc->sc_mcastrate = sc->sc_ic.ic_mcast_rate;
4558         /* NB: caller is responsible for reseting rate control state */
4559 #undef N
4560 }
4561
4562 #ifdef AR_DEBUG
4563 static void
4564 ath_printrxbuf(struct ath_buf *bf, int done)
4565 {
4566         struct ath_desc *ds;
4567         int i;
4568
4569         for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
4570                 printf("R%d (%p %p) %08x %08x %08x %08x %08x %08x %c\n",
4571                     i, ds, (struct ath_desc *)bf->bf_daddr + i,
4572                     ds->ds_link, ds->ds_data,
4573                     ds->ds_ctl0, ds->ds_ctl1,
4574                     ds->ds_hw[0], ds->ds_hw[1],
4575                     !done ? ' ' : (ds->ds_rxstat.rs_status == 0) ? '*' : '!');
4576         }
4577 }
4578
4579 static void
4580 ath_printtxbuf(struct ath_buf *bf, int done)
4581 {
4582         struct ath_desc *ds;
4583         int i;
4584
4585         for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
4586                 printf("T%d (%p %p) %08x %08x %08x %08x %08x %08x %08x %08x %c\n",
4587                     i, ds, (struct ath_desc *)bf->bf_daddr + i,
4588                     ds->ds_link, ds->ds_data,
4589                     ds->ds_ctl0, ds->ds_ctl1,
4590                     ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3],
4591                     !done ? ' ' : (ds->ds_txstat.ts_status == 0) ? '*' : '!');
4592         }
4593 }
4594 #endif /* AR_DEBUG */
4595
4596 static void
4597 ath_watchdog(struct ifnet *ifp)
4598 {
4599         struct ath_softc *sc = ifp->if_softc;
4600         struct ieee80211com *ic = &sc->sc_ic;
4601
4602         ifp->if_timer = 0;
4603         if ((ifp->if_drv_flags & IFF_DRV_RUNNING) == 0 || sc->sc_invalid)
4604                 return;
4605         if (sc->sc_tx_timer) {
4606                 if (--sc->sc_tx_timer == 0) {
4607                         if_printf(ifp, "device timeout\n");
4608                         ath_reset(ifp);
4609                         ifp->if_oerrors++;
4610                         sc->sc_stats.ast_watchdog++;
4611                 } else
4612                         ifp->if_timer = 1;
4613         }
4614         ieee80211_watchdog(ic);
4615 }
4616
4617 /*
4618  * Diagnostic interface to the HAL.  This is used by various
4619  * tools to do things like retrieve register contents for
4620  * debugging.  The mechanism is intentionally opaque so that
4621  * it can change frequently w/o concern for compatiblity.
4622  */
4623 static int
4624 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
4625 {
4626         struct ath_hal *ah = sc->sc_ah;
4627         u_int id = ad->ad_id & ATH_DIAG_ID;
4628         void *indata = NULL;
4629         void *outdata = NULL;
4630         u_int32_t insize = ad->ad_in_size;
4631         u_int32_t outsize = ad->ad_out_size;
4632         int error = 0;
4633
4634         if (ad->ad_id & ATH_DIAG_IN) {
4635                 /*
4636                  * Copy in data.
4637                  */
4638                 indata = malloc(insize, M_TEMP, M_NOWAIT);
4639                 if (indata == NULL) {
4640                         error = ENOMEM;
4641                         goto bad;
4642                 }
4643                 error = copyin(ad->ad_in_data, indata, insize);
4644                 if (error)
4645                         goto bad;
4646         }
4647         if (ad->ad_id & ATH_DIAG_DYN) {
4648                 /*
4649                  * Allocate a buffer for the results (otherwise the HAL
4650                  * returns a pointer to a buffer where we can read the
4651                  * results).  Note that we depend on the HAL leaving this
4652                  * pointer for us to use below in reclaiming the buffer;
4653                  * may want to be more defensive.
4654                  */
4655                 outdata = malloc(outsize, M_TEMP, M_NOWAIT);
4656                 if (outdata == NULL) {
4657                         error = ENOMEM;
4658                         goto bad;
4659                 }
4660         }
4661         if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
4662                 if (outsize < ad->ad_out_size)
4663                         ad->ad_out_size = outsize;
4664                 if (outdata != NULL)
4665                         error = copyout(outdata, ad->ad_out_data,
4666                                         ad->ad_out_size);
4667         } else {
4668                 error = EINVAL;
4669         }
4670 bad:
4671         if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
4672                 free(indata, M_TEMP);
4673         if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
4674                 free(outdata, M_TEMP);
4675         return error;
4676 }
4677
4678 static int
4679 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
4680 {
4681 #define IS_RUNNING(ifp) \
4682         ((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
4683         struct ath_softc *sc = ifp->if_softc;
4684         struct ieee80211com *ic = &sc->sc_ic;
4685         struct ifreq *ifr = (struct ifreq *)data;
4686         int error = 0;
4687
4688         ATH_LOCK(sc);
4689         switch (cmd) {
4690         case SIOCSIFFLAGS:
4691                 if (IS_RUNNING(ifp)) {
4692                         /*
4693                          * To avoid rescanning another access point,
4694                          * do not call ath_init() here.  Instead,
4695                          * only reflect promisc mode settings.
4696                          */
4697                         ath_mode_init(sc);
4698                 } else if (ifp->if_flags & IFF_UP) {
4699                         /*
4700                          * Beware of being called during attach/detach
4701                          * to reset promiscuous mode.  In that case we
4702                          * will still be marked UP but not RUNNING.
4703                          * However trying to re-init the interface
4704                          * is the wrong thing to do as we've already
4705                          * torn down much of our state.  There's
4706                          * probably a better way to deal with this.
4707                          */
4708                         if (!sc->sc_invalid && ic->ic_bss != NULL)
4709                                 ath_init(sc);   /* XXX lose error */
4710                 } else
4711                         ath_stop_locked(ifp);
4712                 break;
4713         case SIOCADDMULTI:
4714         case SIOCDELMULTI:
4715                 /*
4716                  * The upper layer has already installed/removed
4717                  * the multicast address(es), just recalculate the
4718                  * multicast filter for the card.
4719                  */
4720                 if (ifp->if_drv_flags & IFF_DRV_RUNNING)
4721                         ath_mode_init(sc);
4722                 break;
4723         case SIOCGATHSTATS:
4724                 /* NB: embed these numbers to get a consistent view */
4725                 sc->sc_stats.ast_tx_packets = ifp->if_opackets;
4726                 sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
4727                 sc->sc_stats.ast_rx_rssi = ieee80211_getrssi(ic);
4728                 ATH_UNLOCK(sc);
4729                 /*
4730                  * NB: Drop the softc lock in case of a page fault;
4731                  * we'll accept any potential inconsisentcy in the
4732                  * statistics.  The alternative is to copy the data
4733                  * to a local structure.
4734                  */
4735                 return copyout(&sc->sc_stats,
4736                                 ifr->ifr_data, sizeof (sc->sc_stats));
4737         case SIOCGATHDIAG:
4738                 error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
4739                 break;
4740         default:
4741                 error = ieee80211_ioctl(ic, cmd, data);
4742                 if (error == ENETRESET) {
4743                         if (IS_RUNNING(ifp) && 
4744                             ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
4745                                 ath_init(sc);   /* XXX lose error */
4746                         error = 0;
4747                 }
4748                 if (error == ERESTART)
4749                         error = IS_RUNNING(ifp) ? ath_reset(ifp) : 0;
4750                 break;
4751         }
4752         ATH_UNLOCK(sc);
4753         return error;
4754 #undef IS_RUNNING
4755 }
4756
4757 static int
4758 ath_sysctl_slottime(SYSCTL_HANDLER_ARGS)
4759 {
4760         struct ath_softc *sc = arg1;
4761         u_int slottime = ath_hal_getslottime(sc->sc_ah);
4762         int error;
4763
4764         error = sysctl_handle_int(oidp, &slottime, 0, req);
4765         if (error || !req->newptr)
4766                 return error;
4767         return !ath_hal_setslottime(sc->sc_ah, slottime) ? EINVAL : 0;
4768 }
4769
4770 static int
4771 ath_sysctl_acktimeout(SYSCTL_HANDLER_ARGS)
4772 {
4773         struct ath_softc *sc = arg1;
4774         u_int acktimeout = ath_hal_getacktimeout(sc->sc_ah);
4775         int error;
4776
4777         error = sysctl_handle_int(oidp, &acktimeout, 0, req);
4778         if (error || !req->newptr)
4779                 return error;
4780         return !ath_hal_setacktimeout(sc->sc_ah, acktimeout) ? EINVAL : 0;
4781 }
4782
4783 static int
4784 ath_sysctl_ctstimeout(SYSCTL_HANDLER_ARGS)
4785 {
4786         struct ath_softc *sc = arg1;
4787         u_int ctstimeout = ath_hal_getctstimeout(sc->sc_ah);
4788         int error;
4789
4790         error = sysctl_handle_int(oidp, &ctstimeout, 0, req);
4791         if (error || !req->newptr)
4792                 return error;
4793         return !ath_hal_setctstimeout(sc->sc_ah, ctstimeout) ? EINVAL : 0;
4794 }
4795
4796 static int
4797 ath_sysctl_softled(SYSCTL_HANDLER_ARGS)
4798 {
4799         struct ath_softc *sc = arg1;
4800         int softled = sc->sc_softled;
4801         int error;
4802
4803         error = sysctl_handle_int(oidp, &softled, 0, req);
4804         if (error || !req->newptr)
4805                 return error;
4806         softled = (softled != 0);
4807         if (softled != sc->sc_softled) {
4808                 if (softled) {
4809                         /* NB: handle any sc_ledpin change */
4810                         ath_hal_gpioCfgOutput(sc->sc_ah, sc->sc_ledpin);
4811                         ath_hal_gpioset(sc->sc_ah, sc->sc_ledpin,
4812                                 !sc->sc_ledon);
4813                 }
4814                 sc->sc_softled = softled;
4815         }
4816         return 0;
4817 }
4818
4819 static int
4820 ath_sysctl_rxantenna(SYSCTL_HANDLER_ARGS)
4821 {
4822         struct ath_softc *sc = arg1;
4823         u_int defantenna = ath_hal_getdefantenna(sc->sc_ah);
4824         int error;
4825
4826         error = sysctl_handle_int(oidp, &defantenna, 0, req);
4827         if (!error && req->newptr)
4828                 ath_hal_setdefantenna(sc->sc_ah, defantenna);
4829         return error;
4830 }
4831
4832 static int
4833 ath_sysctl_diversity(SYSCTL_HANDLER_ARGS)
4834 {
4835         struct ath_softc *sc = arg1;
4836         u_int diversity = ath_hal_getdiversity(sc->sc_ah);
4837         int error;
4838
4839         error = sysctl_handle_int(oidp, &diversity, 0, req);
4840         if (error || !req->newptr)
4841                 return error;
4842         if (!ath_hal_setdiversity(sc->sc_ah, diversity))
4843                 return EINVAL;
4844         sc->sc_diversity = diversity;
4845         return 0;
4846 }
4847
4848 static int
4849 ath_sysctl_diag(SYSCTL_HANDLER_ARGS)
4850 {
4851         struct ath_softc *sc = arg1;
4852         u_int32_t diag;
4853         int error;
4854
4855         if (!ath_hal_getdiag(sc->sc_ah, &diag))
4856                 return EINVAL;
4857         error = sysctl_handle_int(oidp, &diag, 0, req);
4858         if (error || !req->newptr)
4859                 return error;
4860         return !ath_hal_setdiag(sc->sc_ah, diag) ? EINVAL : 0;
4861 }
4862
4863 static int
4864 ath_sysctl_tpscale(SYSCTL_HANDLER_ARGS)
4865 {
4866         struct ath_softc *sc = arg1;
4867         struct ifnet *ifp = sc->sc_ifp;
4868         u_int32_t scale;
4869         int error;
4870
4871         ath_hal_gettpscale(sc->sc_ah, &scale);
4872         error = sysctl_handle_int(oidp, &scale, 0, req);
4873         if (error || !req->newptr)
4874                 return error;
4875         return !ath_hal_settpscale(sc->sc_ah, scale) ? EINVAL : ath_reset(ifp);
4876 }
4877
4878 static int
4879 ath_sysctl_tpc(SYSCTL_HANDLER_ARGS)
4880 {
4881         struct ath_softc *sc = arg1;
4882         u_int tpc = ath_hal_gettpc(sc->sc_ah);
4883         int error;
4884
4885         error = sysctl_handle_int(oidp, &tpc, 0, req);
4886         if (error || !req->newptr)
4887                 return error;
4888         return !ath_hal_settpc(sc->sc_ah, tpc) ? EINVAL : 0;
4889 }
4890
4891 static void
4892 ath_sysctlattach(struct ath_softc *sc)
4893 {
4894         struct sysctl_ctx_list *ctx = device_get_sysctl_ctx(sc->sc_dev);
4895         struct sysctl_oid *tree = device_get_sysctl_tree(sc->sc_dev);
4896         struct ath_hal *ah = sc->sc_ah;
4897
4898         ath_hal_getcountrycode(sc->sc_ah, &sc->sc_countrycode);
4899         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4900                 "countrycode", CTLFLAG_RD, &sc->sc_countrycode, 0,
4901                 "EEPROM country code");
4902         ath_hal_getregdomain(sc->sc_ah, &sc->sc_regdomain);
4903         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4904                 "regdomain", CTLFLAG_RD, &sc->sc_regdomain, 0,
4905                 "EEPROM regdomain code");
4906         sc->sc_debug = ath_debug;
4907         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4908                 "debug", CTLFLAG_RW, &sc->sc_debug, 0,
4909                 "control debugging printfs");
4910
4911         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4912                 "slottime", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4913                 ath_sysctl_slottime, "I", "802.11 slot time (us)");
4914         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4915                 "acktimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4916                 ath_sysctl_acktimeout, "I", "802.11 ACK timeout (us)");
4917         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4918                 "ctstimeout", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4919                 ath_sysctl_ctstimeout, "I", "802.11 CTS timeout (us)");
4920         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4921                 "softled", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4922                 ath_sysctl_softled, "I", "enable/disable software LED support");
4923         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4924                 "ledpin", CTLFLAG_RW, &sc->sc_ledpin, 0,
4925                 "GPIO pin connected to LED");
4926         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4927                 "ledon", CTLFLAG_RW, &sc->sc_ledon, 0,
4928                 "setting to turn LED on");
4929         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4930                 "ledidle", CTLFLAG_RW, &sc->sc_ledidle, 0,
4931                 "idle time for inactivity LED (ticks)");
4932         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4933                 "txantenna", CTLFLAG_RW, &sc->sc_txantenna, 0,
4934                 "tx antenna (0=auto)");
4935         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4936                 "rxantenna", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4937                 ath_sysctl_rxantenna, "I", "default/rx antenna");
4938         if (ath_hal_hasdiversity(ah))
4939                 SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4940                         "diversity", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4941                         ath_sysctl_diversity, "I", "antenna diversity");
4942         sc->sc_txintrperiod = ATH_TXINTR_PERIOD;
4943         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4944                 "txintrperiod", CTLFLAG_RW, &sc->sc_txintrperiod, 0,
4945                 "tx descriptor batching");
4946         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4947                 "diag", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4948                 ath_sysctl_diag, "I", "h/w diagnostic control");
4949         SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4950                 "tpscale", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4951                 ath_sysctl_tpscale, "I", "tx power scaling");
4952         if (ath_hal_hastpc(ah))
4953                 SYSCTL_ADD_PROC(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4954                         "tpc", CTLTYPE_INT | CTLFLAG_RW, sc, 0,
4955                         ath_sysctl_tpc, "I", "enable/disable per-packet TPC");
4956         sc->sc_monpass = HAL_RXERR_DECRYPT | HAL_RXERR_MIC;
4957         SYSCTL_ADD_INT(ctx, SYSCTL_CHILDREN(tree), OID_AUTO,
4958                 "monpass", CTLFLAG_RW, &sc->sc_monpass, 0,
4959                 "mask of error frames to pass when monitoring");
4960 }
4961
4962 static void
4963 ath_bpfattach(struct ath_softc *sc)
4964 {
4965         struct ifnet *ifp = sc->sc_ifp;
4966
4967         bpfattach2(ifp, DLT_IEEE802_11_RADIO,
4968                 sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th),
4969                 &sc->sc_drvbpf);
4970         /*
4971          * Initialize constant fields.
4972          * XXX make header lengths a multiple of 32-bits so subsequent
4973          *     headers are properly aligned; this is a kludge to keep
4974          *     certain applications happy.
4975          *
4976          * NB: the channel is setup each time we transition to the
4977          *     RUN state to avoid filling it in for each frame.
4978          */
4979         sc->sc_tx_th_len = roundup(sizeof(sc->sc_tx_th), sizeof(u_int32_t));
4980         sc->sc_tx_th.wt_ihdr.it_len = htole16(sc->sc_tx_th_len);
4981         sc->sc_tx_th.wt_ihdr.it_present = htole32(ATH_TX_RADIOTAP_PRESENT);
4982
4983         sc->sc_rx_th_len = roundup(sizeof(sc->sc_rx_th), sizeof(u_int32_t));
4984         sc->sc_rx_th.wr_ihdr.it_len = htole16(sc->sc_rx_th_len);
4985         sc->sc_rx_th.wr_ihdr.it_present = htole32(ATH_RX_RADIOTAP_PRESENT);
4986 }
4987
4988 /*
4989  * Announce various information on device/driver attach.
4990  */
4991 static void
4992 ath_announce(struct ath_softc *sc)
4993 {
4994 #define HAL_MODE_DUALBAND       (HAL_MODE_11A|HAL_MODE_11B)
4995         struct ifnet *ifp = sc->sc_ifp;
4996         struct ath_hal *ah = sc->sc_ah;
4997         u_int modes, cc;
4998
4999         if_printf(ifp, "mac %d.%d phy %d.%d",
5000                 ah->ah_macVersion, ah->ah_macRev,
5001                 ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
5002         /*
5003          * Print radio revision(s).  We check the wireless modes
5004          * to avoid falsely printing revs for inoperable parts.
5005          * Dual-band radio revs are returned in the 5Ghz rev number.
5006          */
5007         ath_hal_getcountrycode(ah, &cc);
5008         modes = ath_hal_getwirelessmodes(ah, cc);
5009         if ((modes & HAL_MODE_DUALBAND) == HAL_MODE_DUALBAND) {
5010                 if (ah->ah_analog5GhzRev && ah->ah_analog2GhzRev)
5011                         printf(" 5ghz radio %d.%d 2ghz radio %d.%d",
5012                                 ah->ah_analog5GhzRev >> 4,
5013                                 ah->ah_analog5GhzRev & 0xf,
5014                                 ah->ah_analog2GhzRev >> 4,
5015                                 ah->ah_analog2GhzRev & 0xf);
5016                 else
5017                         printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
5018                                 ah->ah_analog5GhzRev & 0xf);
5019         } else
5020                 printf(" radio %d.%d", ah->ah_analog5GhzRev >> 4,
5021                         ah->ah_analog5GhzRev & 0xf);
5022         printf("\n");
5023         if (bootverbose) {
5024                 int i;
5025                 for (i = 0; i <= WME_AC_VO; i++) {
5026                         struct ath_txq *txq = sc->sc_ac2q[i];
5027                         if_printf(ifp, "Use hw queue %u for %s traffic\n",
5028                                 txq->axq_qnum, ieee80211_wme_acnames[i]);
5029                 }
5030                 if_printf(ifp, "Use hw queue %u for CAB traffic\n",
5031                         sc->sc_cabq->axq_qnum);
5032                 if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
5033         }
5034         if (ath_rxbuf != ATH_RXBUF)
5035                 if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
5036         if (ath_txbuf != ATH_TXBUF)
5037                 if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
5038 #undef HAL_MODE_DUALBAND
5039 }