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