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