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