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