kernel/wlan: Fix up the MAC address printing and add back __printflike()s.
[dragonfly.git] / sys / dev / netif / ath / ath / if_ath.c
1 /*-
2  * Copyright (c) 2002-2009 Sam Leffler, Errno Consulting
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification.
11  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13  *    redistribution must be conditioned upon including a substantially
14  *    similar Disclaimer requirement for further binary redistribution.
15  *
16  * NO WARRANTY
17  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
20  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
21  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
22  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
25  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
27  * THE POSSIBILITY OF SUCH DAMAGES.
28  */
29
30 #include <sys/cdefs.h>
31 __FBSDID("$FreeBSD$");
32
33 #define CTLFLAG_RWTUN   CTLFLAG_RW
34
35 /*
36  * Driver for the Atheros Wireless LAN controller.
37  *
38  * This software is derived from work of Atsushi Onoe; his contribution
39  * is greatly appreciated.
40  */
41
42 #include "opt_inet.h"
43 #include "opt_ath.h"
44 /*
45  * This is needed for register operations which are performed
46  * by the driver - eg, calls to ath_hal_gettsf32().
47  *
48  * It's also required for any AH_DEBUG checks in here, eg the
49  * module dependencies.
50  */
51 #include "opt_ah.h"
52 #include "opt_wlan.h"
53
54 #include <sys/param.h>
55 #include <sys/systm.h>
56 #include <sys/sysctl.h>
57 #include <sys/mbuf.h>
58 #include <sys/malloc.h>
59 #include <sys/lock.h>
60 #include <sys/mutex.h>
61 #include <sys/kernel.h>
62 #include <sys/socket.h>
63 #include <sys/sockio.h>
64 #include <sys/errno.h>
65 #include <sys/callout.h>
66 #include <sys/bus.h>
67 #include <sys/endian.h>
68 #include <sys/kthread.h>
69 #include <sys/taskqueue.h>
70 #include <sys/priv.h>
71 #include <sys/module.h>
72 #include <sys/ktr.h>
73
74 #include <net/if.h>
75 #include <net/if_var.h>
76 #include <net/if_dl.h>
77 #include <net/if_media.h>
78 #include <net/if_types.h>
79 #include <net/if_arp.h>
80 #include <net/ethernet.h>
81 #include <net/if_llc.h>
82 #include <net/ifq_var.h>
83
84 #include <netproto/802_11/ieee80211_var.h>
85 #include <netproto/802_11/ieee80211_regdomain.h>
86 #ifdef IEEE80211_SUPPORT_SUPERG
87 #include <netproto/802_11/ieee80211_superg.h>
88 #endif
89 #ifdef IEEE80211_SUPPORT_TDMA
90 #include <netproto/802_11/ieee80211_tdma.h>
91 #endif
92
93 #include <net/bpf.h>
94
95 #ifdef INET
96 #include <netinet/in.h>
97 #include <netinet/if_ether.h>
98 #endif
99
100 #include <dev/netif/ath/ath/if_athvar.h>
101 #include <dev/netif/ath/ath_hal/ah_devid.h>             /* XXX for softled */
102 #include <dev/netif/ath/ath_hal/ah_diagcodes.h>
103
104 #include <dev/netif/ath/ath/if_ath_debug.h>
105 #include <dev/netif/ath/ath/if_ath_misc.h>
106 #include <dev/netif/ath/ath/if_ath_tsf.h>
107 #include <dev/netif/ath/ath/if_ath_tx.h>
108 #include <dev/netif/ath/ath/if_ath_sysctl.h>
109 #include <dev/netif/ath/ath/if_ath_led.h>
110 #include <dev/netif/ath/ath/if_ath_keycache.h>
111 #include <dev/netif/ath/ath/if_ath_rx.h>
112 #include <dev/netif/ath/ath/if_ath_rx_edma.h>
113 #include <dev/netif/ath/ath/if_ath_tx_edma.h>
114 #include <dev/netif/ath/ath/if_ath_beacon.h>
115 #include <dev/netif/ath/ath/if_ath_btcoex.h>
116 #include <dev/netif/ath/ath/if_ath_spectral.h>
117 #include <dev/netif/ath/ath/if_ath_lna_div.h>
118 #include <dev/netif/ath/ath/if_athdfs.h>
119
120 #ifdef ATH_TX99_DIAG
121 #include <dev/netif/ath/ath/ath_tx99/ath_tx99.h>
122 #endif
123
124 #ifdef  ATH_DEBUG_ALQ
125 #include <dev/netif/ath/ath/if_ath_alq.h>
126 #endif
127
128 /*
129  * Only enable this if you're working on PS-POLL support.
130  */
131 #define ATH_SW_PSQ
132
133 /*
134  * ATH_BCBUF determines the number of vap's that can transmit
135  * beacons and also (currently) the number of vap's that can
136  * have unique mac addresses/bssid.  When staggering beacons
137  * 4 is probably a good max as otherwise the beacons become
138  * very closely spaced and there is limited time for cab q traffic
139  * to go out.  You can burst beacons instead but that is not good
140  * for stations in power save and at some point you really want
141  * another radio (and channel).
142  *
143  * The limit on the number of mac addresses is tied to our use of
144  * the U/L bit and tracking addresses in a byte; it would be
145  * worthwhile to allow more for applications like proxy sta.
146  */
147 CTASSERT(ATH_BCBUF <= 8);
148
149 static struct ieee80211vap *ath_vap_create(struct ieee80211com *,
150                     const char [IFNAMSIZ], int, enum ieee80211_opmode, int,
151                     const uint8_t [IEEE80211_ADDR_LEN],
152                     const uint8_t [IEEE80211_ADDR_LEN]);
153 static void     ath_vap_delete(struct ieee80211vap *);
154 static void     ath_init(void *);
155 static void     ath_stop_locked(struct ifnet *);
156 static void     ath_stop(struct ifnet *);
157 static int      ath_reset_vap(struct ieee80211vap *, u_long);
158 static int      ath_transmit(struct ifnet *ifp, struct mbuf *m);
159 #if !defined(__DragonFly__)
160 static void     ath_qflush(struct ifnet *ifp);
161 #endif
162 static int      ath_media_change(struct ifnet *);
163 static void     ath_watchdog(void *);
164 #if defined(__DragonFly__)
165 static int      ath_ioctl(struct ifnet *, u_long, caddr_t, struct ucred * __unused);
166 #else
167 static int      ath_ioctl(struct ifnet *, u_long, caddr_t);
168 #endif
169 static void     ath_fatal_proc(void *, int);
170 static void     ath_bmiss_vap(struct ieee80211vap *);
171 static void     ath_bmiss_proc(void *, int);
172 static void     ath_key_update_begin(struct ieee80211vap *);
173 static void     ath_key_update_end(struct ieee80211vap *);
174 static void     ath_update_mcast_hw(struct ath_softc *);
175 static void     ath_update_mcast(struct ifnet *);
176 static void     ath_update_promisc(struct ifnet *);
177 static void     ath_updateslot(struct ifnet *);
178 static void     ath_bstuck_proc(void *, int);
179 static void     ath_reset_proc(void *, int);
180 static int      ath_desc_alloc(struct ath_softc *);
181 static void     ath_desc_free(struct ath_softc *);
182 static struct ieee80211_node *ath_node_alloc(struct ieee80211vap *,
183                         const uint8_t [IEEE80211_ADDR_LEN]);
184 static void     ath_node_cleanup(struct ieee80211_node *);
185 static void     ath_node_free(struct ieee80211_node *);
186 static void     ath_node_getsignal(const struct ieee80211_node *,
187                         int8_t *, int8_t *);
188 static void     ath_txq_init(struct ath_softc *sc, struct ath_txq *, int);
189 static struct ath_txq *ath_txq_setup(struct ath_softc*, int qtype, int subtype);
190 static int      ath_tx_setup(struct ath_softc *, int, int);
191 static void     ath_tx_cleanupq(struct ath_softc *, struct ath_txq *);
192 static void     ath_tx_cleanup(struct ath_softc *);
193 static int      ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq,
194                     int dosched);
195 static void     ath_tx_proc_q0(void *, int);
196 static void     ath_tx_proc_q0123(void *, int);
197 static void     ath_tx_proc(void *, int);
198 static void     ath_txq_sched_tasklet(void *, int);
199 static int      ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
200 static void     ath_chan_change(struct ath_softc *, struct ieee80211_channel *);
201 static void     ath_scan_start(struct ieee80211com *);
202 static void     ath_scan_end(struct ieee80211com *);
203 static void     ath_set_channel(struct ieee80211com *);
204 #ifdef  ATH_ENABLE_11N
205 static void     ath_update_chw(struct ieee80211com *);
206 #endif  /* ATH_ENABLE_11N */
207 static void     ath_calibrate(void *);
208 static int      ath_newstate(struct ieee80211vap *, enum ieee80211_state, int);
209 static void     ath_setup_stationkey(struct ieee80211_node *);
210 static void     ath_newassoc(struct ieee80211_node *, int);
211 static int      ath_setregdomain(struct ieee80211com *,
212                     struct ieee80211_regdomain *, int,
213                     struct ieee80211_channel []);
214 static void     ath_getradiocaps(struct ieee80211com *, int, int *,
215                     struct ieee80211_channel []);
216 static int      ath_getchannels(struct ath_softc *);
217
218 static int      ath_rate_setup(struct ath_softc *, u_int mode);
219 static void     ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
220
221 static void     ath_announce(struct ath_softc *);
222
223 static void     ath_dfs_tasklet(void *, int);
224 static void     ath_node_powersave(struct ieee80211_node *, int);
225 static int      ath_node_set_tim(struct ieee80211_node *, int);
226 static void     ath_node_recv_pspoll(struct ieee80211_node *, struct mbuf *);
227
228 #if defined(__DragonFly__)
229 static void     ath_start(struct ifnet *ifp, struct ifaltq_subque *ifsq);
230 #endif
231
232 #ifdef IEEE80211_SUPPORT_TDMA
233 #include <dev/netif/ath/ath/if_ath_tdma.h>
234 #endif
235
236 extern  const char* ath_hal_ether_sprintf(const u_int8_t *mac);
237
238 SYSCTL_DECL(_hw_ath);
239
240 /* XXX validate sysctl values */
241 static  int ath_longcalinterval = 30;           /* long cals every 30 secs */
242 SYSCTL_INT(_hw_ath, OID_AUTO, longcal, CTLFLAG_RW, &ath_longcalinterval,
243             0, "long chip calibration interval (secs)");
244 static  int ath_shortcalinterval = 100;         /* short cals every 100 ms */
245 SYSCTL_INT(_hw_ath, OID_AUTO, shortcal, CTLFLAG_RW, &ath_shortcalinterval,
246             0, "short chip calibration interval (msecs)");
247 static  int ath_resetcalinterval = 20*60;       /* reset cal state 20 mins */
248 SYSCTL_INT(_hw_ath, OID_AUTO, resetcal, CTLFLAG_RW, &ath_resetcalinterval,
249             0, "reset chip calibration results (secs)");
250 static  int ath_anicalinterval = 100;           /* ANI calibration - 100 msec */
251 SYSCTL_INT(_hw_ath, OID_AUTO, anical, CTLFLAG_RW, &ath_anicalinterval,
252             0, "ANI calibration (msecs)");
253
254 int ath_rxbuf = ATH_RXBUF;              /* # rx buffers to allocate */
255 SYSCTL_INT(_hw_ath, OID_AUTO, rxbuf, CTLFLAG_RWTUN, &ath_rxbuf,
256             0, "rx buffers allocated");
257 TUNABLE_INT("hw.ath.rxbuf", &ath_rxbuf);
258
259 int ath_txbuf = ATH_TXBUF;              /* # tx buffers to allocate */
260 SYSCTL_INT(_hw_ath, OID_AUTO, txbuf, CTLFLAG_RWTUN, &ath_txbuf,
261             0, "tx buffers allocated");
262 TUNABLE_INT("hw.ath.txbuf", &ath_txbuf);
263
264 int ath_txbuf_mgmt = ATH_MGMT_TXBUF;    /* # mgmt tx buffers to allocate */
265 SYSCTL_INT(_hw_ath, OID_AUTO, txbuf_mgmt, CTLFLAG_RWTUN, &ath_txbuf_mgmt,
266             0, "tx (mgmt) buffers allocated");
267 TUNABLE_INT("hw.ath.txbuf_mgmt", &ath_txbuf_mgmt);
268
269 int ath_bstuck_threshold = 4;           /* max missed beacons */
270 SYSCTL_INT(_hw_ath, OID_AUTO, bstuck, CTLFLAG_RW, &ath_bstuck_threshold,
271             0, "max missed beacon xmits before chip reset");
272
273 MALLOC_DEFINE(M_ATHDEV, "athdev", "ath driver dma buffers");
274
275 void
276 ath_legacy_attach_comp_func(struct ath_softc *sc)
277 {
278
279         /*
280          * Special case certain configurations.  Note the
281          * CAB queue is handled by these specially so don't
282          * include them when checking the txq setup mask.
283          */
284         switch (sc->sc_txqsetup &~ (1<<sc->sc_cabq->axq_qnum)) {
285         case 0x01:
286                 TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0, sc);
287                 break;
288         case 0x0f:
289                 TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc_q0123, sc);
290                 break;
291         default:
292                 TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
293                 break;
294         }
295 }
296
297 /*
298  * Set the target power mode.
299  *
300  * If this is called during a point in time where
301  * the hardware is being programmed elsewhere, it will
302  * simply store it away and update it when all current
303  * uses of the hardware are completed.
304  */
305 void
306 _ath_power_setpower(struct ath_softc *sc, int power_state, const char *file, int line)
307 {
308         ATH_LOCK_ASSERT(sc);
309
310         sc->sc_target_powerstate = power_state;
311
312         DPRINTF(sc, ATH_DEBUG_PWRSAVE, "%s: (%s:%d) state=%d, refcnt=%d\n",
313             __func__,
314             file,
315             line,
316             power_state,
317             sc->sc_powersave_refcnt);
318
319         if (sc->sc_powersave_refcnt == 0 &&
320             power_state != sc->sc_cur_powerstate) {
321                 sc->sc_cur_powerstate = power_state;
322                 ath_hal_setpower(sc->sc_ah, power_state);
323
324                 /*
325                  * If the NIC is force-awake, then set the
326                  * self-gen frame state appropriately.
327                  *
328                  * If the nic is in network sleep or full-sleep,
329                  * we let the above call leave the self-gen
330                  * state as "sleep".
331                  */
332                 if (sc->sc_cur_powerstate == HAL_PM_AWAKE &&
333                     sc->sc_target_selfgen_state != HAL_PM_AWAKE) {
334                         ath_hal_setselfgenpower(sc->sc_ah,
335                             sc->sc_target_selfgen_state);
336                 }
337         }
338 }
339
340 /*
341  * Set the current self-generated frames state.
342  *
343  * This is separate from the target power mode.  The chip may be
344  * awake but the desired state is "sleep", so frames sent to the
345  * destination has PWRMGT=1 in the 802.11 header.  The NIC also
346  * needs to know to set PWRMGT=1 in self-generated frames.
347  */
348 void
349 _ath_power_set_selfgen(struct ath_softc *sc, int power_state, const char *file, int line)
350 {
351
352         ATH_LOCK_ASSERT(sc);
353
354         DPRINTF(sc, ATH_DEBUG_PWRSAVE, "%s: (%s:%d) state=%d, refcnt=%d\n",
355             __func__,
356             file,
357             line,
358             power_state,
359             sc->sc_target_selfgen_state);
360
361         sc->sc_target_selfgen_state = power_state;
362
363         /*
364          * If the NIC is force-awake, then set the power state.
365          * Network-state and full-sleep will already transition it to
366          * mark self-gen frames as sleeping - and we can't
367          * guarantee the NIC is awake to program the self-gen frame
368          * setting anyway.
369          */
370         if (sc->sc_cur_powerstate == HAL_PM_AWAKE) {
371                 ath_hal_setselfgenpower(sc->sc_ah, power_state);
372         }
373 }
374
375 /*
376  * Set the hardware power mode and take a reference.
377  *
378  * This doesn't update the target power mode in the driver;
379  * it just updates the hardware power state.
380  *
381  * XXX it should only ever force the hardware awake; it should
382  * never be called to set it asleep.
383  */
384 void
385 _ath_power_set_power_state(struct ath_softc *sc, int power_state, const char *file, int line)
386 {
387         ATH_LOCK_ASSERT(sc);
388
389         DPRINTF(sc, ATH_DEBUG_PWRSAVE, "%s: (%s:%d) state=%d, refcnt=%d\n",
390             __func__,
391             file,
392             line,
393             power_state,
394             sc->sc_powersave_refcnt);
395
396         sc->sc_powersave_refcnt++;
397
398         if (power_state != sc->sc_cur_powerstate) {
399                 ath_hal_setpower(sc->sc_ah, power_state);
400                 sc->sc_cur_powerstate = power_state;
401
402                 /*
403                  * Adjust the self-gen powerstate if appropriate.
404                  */
405                 if (sc->sc_cur_powerstate == HAL_PM_AWAKE &&
406                     sc->sc_target_selfgen_state != HAL_PM_AWAKE) {
407                         ath_hal_setselfgenpower(sc->sc_ah,
408                             sc->sc_target_selfgen_state);
409                 }
410
411         }
412 }
413
414 /*
415  * Restore the power save mode to what it once was.
416  *
417  * This will decrement the reference counter and once it hits
418  * zero, it'll restore the powersave state.
419  */
420 void
421 _ath_power_restore_power_state(struct ath_softc *sc, const char *file, int line)
422 {
423
424         ATH_LOCK_ASSERT(sc);
425
426         DPRINTF(sc, ATH_DEBUG_PWRSAVE, "%s: (%s:%d) refcnt=%d, target state=%d\n",
427             __func__,
428             file,
429             line,
430             sc->sc_powersave_refcnt,
431             sc->sc_target_powerstate);
432
433         if (sc->sc_powersave_refcnt == 0)
434                 device_printf(sc->sc_dev, "%s: refcnt=0?\n", __func__);
435         else
436                 sc->sc_powersave_refcnt--;
437
438         if (sc->sc_powersave_refcnt == 0 &&
439             sc->sc_target_powerstate != sc->sc_cur_powerstate) {
440                 sc->sc_cur_powerstate = sc->sc_target_powerstate;
441                 ath_hal_setpower(sc->sc_ah, sc->sc_target_powerstate);
442         }
443
444         /*
445          * Adjust the self-gen powerstate if appropriate.
446          */
447         if (sc->sc_cur_powerstate == HAL_PM_AWAKE &&
448             sc->sc_target_selfgen_state != HAL_PM_AWAKE) {
449                 ath_hal_setselfgenpower(sc->sc_ah,
450                     sc->sc_target_selfgen_state);
451         }
452
453 }
454
455 /*
456  * Configure the initial HAL configuration values based on bus
457  * specific parameters.
458  *
459  * Some PCI IDs and other information may need tweaking.
460  *
461  * XXX TODO: ath9k and the Atheros HAL only program comm2g_switch_enable
462  * if BT antenna diversity isn't enabled.
463  *
464  * So, let's also figure out how to enable BT diversity for AR9485.
465  */
466 static void
467 ath_setup_hal_config(struct ath_softc *sc, HAL_OPS_CONFIG *ah_config)
468 {
469         /* XXX TODO: only for PCI devices? */
470
471         if (sc->sc_pci_devinfo & (ATH_PCI_CUS198 | ATH_PCI_CUS230)) {
472                 ah_config->ath_hal_ext_lna_ctl_gpio = 0x200; /* bit 9 */
473                 ah_config->ath_hal_ext_atten_margin_cfg = AH_TRUE;
474                 ah_config->ath_hal_min_gainidx = AH_TRUE;
475                 ah_config->ath_hal_ant_ctrl_comm2g_switch_enable = 0x000bbb88;
476                 /* XXX low_rssi_thresh */
477                 /* XXX fast_div_bias */
478                 device_printf(sc->sc_dev, "configuring for %s\n",
479                     (sc->sc_pci_devinfo & ATH_PCI_CUS198) ?
480                     "CUS198" : "CUS230");
481         }
482
483         if (sc->sc_pci_devinfo & ATH_PCI_CUS217)
484                 device_printf(sc->sc_dev, "CUS217 card detected\n");
485
486         if (sc->sc_pci_devinfo & ATH_PCI_CUS252)
487                 device_printf(sc->sc_dev, "CUS252 card detected\n");
488
489         if (sc->sc_pci_devinfo & ATH_PCI_AR9565_1ANT)
490                 device_printf(sc->sc_dev, "WB335 1-ANT card detected\n");
491
492         if (sc->sc_pci_devinfo & ATH_PCI_AR9565_2ANT)
493                 device_printf(sc->sc_dev, "WB335 2-ANT card detected\n");
494
495         if (sc->sc_pci_devinfo & ATH_PCI_KILLER)
496                 device_printf(sc->sc_dev, "Killer Wireless card detected\n");
497
498 #if 0
499         /*
500          * Some WB335 cards do not support antenna diversity. Since
501          * we use a hardcoded value for AR9565 instead of using the
502          * EEPROM/OTP data, remove the combining feature from
503          * the HW capabilities bitmap.
504          */
505         if (sc->sc_pci_devinfo & (ATH9K_PCI_AR9565_1ANT | ATH9K_PCI_AR9565_2ANT)) {
506                 if (!(sc->sc_pci_devinfo & ATH9K_PCI_BT_ANT_DIV))
507                         pCap->hw_caps &= ~ATH9K_HW_CAP_ANT_DIV_COMB;
508         }
509
510         if (sc->sc_pci_devinfo & ATH9K_PCI_BT_ANT_DIV) {
511                 pCap->hw_caps |= ATH9K_HW_CAP_BT_ANT_DIV;
512                 device_printf(sc->sc_dev, "Set BT/WLAN RX diversity capability\n");
513         }
514 #endif
515
516         if (sc->sc_pci_devinfo & ATH_PCI_D3_L1_WAR) {
517                 ah_config->ath_hal_pcie_waen = 0x0040473b;
518                 device_printf(sc->sc_dev, "Enable WAR for ASPM D3/L1\n");
519         }
520
521 #if 0
522         if (sc->sc_pci_devinfo & ATH9K_PCI_NO_PLL_PWRSAVE) {
523                 ah->config.no_pll_pwrsave = true;
524                 device_printf(sc->sc_dev, "Disable PLL PowerSave\n");
525         }
526 #endif
527
528 }
529
530 #define HAL_MODE_HT20 (HAL_MODE_11NG_HT20 | HAL_MODE_11NA_HT20)
531 #define HAL_MODE_HT40 \
532         (HAL_MODE_11NG_HT40PLUS | HAL_MODE_11NG_HT40MINUS | \
533         HAL_MODE_11NA_HT40PLUS | HAL_MODE_11NA_HT40MINUS)
534 int
535 ath_attach(u_int16_t devid, struct ath_softc *sc)
536 {
537         struct ifnet *ifp;
538         struct ieee80211com *ic;
539         struct ath_hal *ah = NULL;
540         HAL_STATUS status;
541         int error = 0, i;
542         u_int wmodes;
543         uint8_t macaddr[IEEE80211_ADDR_LEN];
544         int rx_chainmask, tx_chainmask;
545         HAL_OPS_CONFIG ah_config;
546
547         DPRINTF(sc, ATH_DEBUG_ANY, "%s: devid 0x%x\n", __func__, devid);
548
549         wlan_serialize_enter();
550         CURVNET_SET(vnet0);
551         ifp = sc->sc_ifp = if_alloc(IFT_IEEE80211);
552         if (ifp == NULL) {
553                 device_printf(sc->sc_dev, "can not if_alloc()\n");
554                 error = ENOSPC;
555                 CURVNET_RESTORE();
556                 goto bad;
557         }
558         ic = ifp->if_l2com;
559
560         /* set these up early for if_printf use */
561         if_initname(ifp, device_get_name(sc->sc_dev),
562                 device_get_unit(sc->sc_dev));
563         CURVNET_RESTORE();
564
565         /*
566          * Configure the initial configuration data.
567          *
568          * This is stuff that may be needed early during attach
569          * rather than done via configuration calls later.
570          */
571         bzero(&ah_config, sizeof(ah_config));
572         ath_setup_hal_config(sc, &ah_config);
573
574         ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh,
575             sc->sc_eepromdata, &ah_config, &status);
576         if (ah == NULL) {
577                 if_printf(ifp, "unable to attach hardware; HAL status %u\n",
578                         status);
579                 error = ENXIO;
580                 goto bad;
581         }
582         sc->sc_ah = ah;
583         sc->sc_invalid = 0;     /* ready to go, enable interrupt handling */
584 #ifdef  ATH_DEBUG
585         sc->sc_debug = ath_debug;
586 #endif
587
588         /*
589          * Setup the DMA/EDMA functions based on the current
590          * hardware support.
591          *
592          * This is required before the descriptors are allocated.
593          */
594         if (ath_hal_hasedma(sc->sc_ah)) {
595                 sc->sc_isedma = 1;
596                 ath_recv_setup_edma(sc);
597                 ath_xmit_setup_edma(sc);
598         } else {
599                 ath_recv_setup_legacy(sc);
600                 ath_xmit_setup_legacy(sc);
601         }
602
603         if (ath_hal_hasmybeacon(sc->sc_ah)) {
604                 sc->sc_do_mybeacon = 1;
605         }
606
607         /*
608          * Check if the MAC has multi-rate retry support.
609          * We do this by trying to setup a fake extended
610          * descriptor.  MAC's that don't have support will
611          * return false w/o doing anything.  MAC's that do
612          * support it will return true w/o doing anything.
613          */
614         sc->sc_mrretry = ath_hal_setupxtxdesc(ah, NULL, 0,0, 0,0, 0,0);
615
616         /*
617          * Check if the device has hardware counters for PHY
618          * errors.  If so we need to enable the MIB interrupt
619          * so we can act on stat triggers.
620          */
621         if (ath_hal_hwphycounters(ah))
622                 sc->sc_needmib = 1;
623
624         /*
625          * Get the hardware key cache size.
626          */
627         sc->sc_keymax = ath_hal_keycachesize(ah);
628         if (sc->sc_keymax > ATH_KEYMAX) {
629                 if_printf(ifp, "Warning, using only %u of %u key cache slots\n",
630                         ATH_KEYMAX, sc->sc_keymax);
631                 sc->sc_keymax = ATH_KEYMAX;
632         }
633         /*
634          * Reset the key cache since some parts do not
635          * reset the contents on initial power up.
636          */
637         for (i = 0; i < sc->sc_keymax; i++)
638                 ath_hal_keyreset(ah, i);
639
640         /*
641          * Collect the default channel list.
642          */
643         error = ath_getchannels(sc);
644         if (error != 0)
645                 goto bad;
646
647         /*
648          * Setup rate tables for all potential media types.
649          */
650         ath_rate_setup(sc, IEEE80211_MODE_11A);
651         ath_rate_setup(sc, IEEE80211_MODE_11B);
652         ath_rate_setup(sc, IEEE80211_MODE_11G);
653         ath_rate_setup(sc, IEEE80211_MODE_TURBO_A);
654         ath_rate_setup(sc, IEEE80211_MODE_TURBO_G);
655         ath_rate_setup(sc, IEEE80211_MODE_STURBO_A);
656         ath_rate_setup(sc, IEEE80211_MODE_11NA);
657         ath_rate_setup(sc, IEEE80211_MODE_11NG);
658         ath_rate_setup(sc, IEEE80211_MODE_HALF);
659         ath_rate_setup(sc, IEEE80211_MODE_QUARTER);
660
661         /* NB: setup here so ath_rate_update is happy */
662         ath_setcurmode(sc, IEEE80211_MODE_11A);
663
664         /*
665          * Allocate TX descriptors and populate the lists.
666          */
667         error = ath_desc_alloc(sc);
668         if (error != 0) {
669                 if_printf(ifp, "failed to allocate TX descriptors: %d\n",
670                     error);
671                 goto bad;
672         }
673         error = ath_txdma_setup(sc);
674         if (error != 0) {
675                 if_printf(ifp, "failed to allocate TX descriptors: %d\n",
676                     error);
677                 goto bad;
678         }
679
680         /*
681          * Allocate RX descriptors and populate the lists.
682          */
683         error = ath_rxdma_setup(sc);
684         if (error != 0) {
685                 if_printf(ifp, "failed to allocate RX descriptors: %d\n",
686                     error);
687                 goto bad;
688         }
689
690         callout_init_lk(&sc->sc_cal_ch, &sc->sc_mtx);
691         callout_init_lk(&sc->sc_wd_ch, &sc->sc_mtx);
692
693         ATH_TXBUF_LOCK_INIT(sc);
694
695         sc->sc_tq = taskqueue_create("ath_taskq", M_INTWAIT,
696                 taskqueue_thread_enqueue, &sc->sc_tq);
697         taskqueue_start_threads(&sc->sc_tq, 1, TDPRI_KERN_DAEMON, -1,
698                 "%s taskq", ifp->if_xname);
699
700         TASK_INIT(&sc->sc_rxtask, 0, sc->sc_rx.recv_tasklet, sc);
701         TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
702         TASK_INIT(&sc->sc_bstucktask,0, ath_bstuck_proc, sc);
703         TASK_INIT(&sc->sc_resettask,0, ath_reset_proc, sc);
704         TASK_INIT(&sc->sc_txqtask, 0, ath_txq_sched_tasklet, sc);
705         TASK_INIT(&sc->sc_fataltask, 0, ath_fatal_proc, sc);
706
707         /*
708          * Allocate hardware transmit queues: one queue for
709          * beacon frames and one data queue for each QoS
710          * priority.  Note that the hal handles resetting
711          * these queues at the needed time.
712          *
713          * XXX PS-Poll
714          */
715         sc->sc_bhalq = ath_beaconq_setup(sc);
716         if (sc->sc_bhalq == (u_int) -1) {
717                 if_printf(ifp, "unable to setup a beacon xmit queue!\n");
718                 error = EIO;
719                 goto bad2;
720         }
721         sc->sc_cabq = ath_txq_setup(sc, HAL_TX_QUEUE_CAB, 0);
722         if (sc->sc_cabq == NULL) {
723                 if_printf(ifp, "unable to setup CAB xmit queue!\n");
724                 error = EIO;
725                 goto bad2;
726         }
727         /* NB: insure BK queue is the lowest priority h/w queue */
728         if (!ath_tx_setup(sc, WME_AC_BK, HAL_WME_AC_BK)) {
729                 if_printf(ifp, "unable to setup xmit queue for %s traffic!\n",
730                         ieee80211_wme_acnames[WME_AC_BK]);
731                 error = EIO;
732                 goto bad2;
733         }
734         if (!ath_tx_setup(sc, WME_AC_BE, HAL_WME_AC_BE) ||
735             !ath_tx_setup(sc, WME_AC_VI, HAL_WME_AC_VI) ||
736             !ath_tx_setup(sc, WME_AC_VO, HAL_WME_AC_VO)) {
737                 /*
738                  * Not enough hardware tx queues to properly do WME;
739                  * just punt and assign them all to the same h/w queue.
740                  * We could do a better job of this if, for example,
741                  * we allocate queues when we switch from station to
742                  * AP mode.
743                  */
744                 if (sc->sc_ac2q[WME_AC_VI] != NULL)
745                         ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_VI]);
746                 if (sc->sc_ac2q[WME_AC_BE] != NULL)
747                         ath_tx_cleanupq(sc, sc->sc_ac2q[WME_AC_BE]);
748                 sc->sc_ac2q[WME_AC_BE] = sc->sc_ac2q[WME_AC_BK];
749                 sc->sc_ac2q[WME_AC_VI] = sc->sc_ac2q[WME_AC_BK];
750                 sc->sc_ac2q[WME_AC_VO] = sc->sc_ac2q[WME_AC_BK];
751         }
752
753         /*
754          * Attach the TX completion function.
755          *
756          * The non-EDMA chips may have some special case optimisations;
757          * this method gives everyone a chance to attach cleanly.
758          */
759         sc->sc_tx.xmit_attach_comp_func(sc);
760
761         /*
762          * Setup rate control.  Some rate control modules
763          * call back to change the anntena state so expose
764          * the necessary entry points.
765          * XXX maybe belongs in struct ath_ratectrl?
766          */
767         sc->sc_setdefantenna = ath_setdefantenna;
768         sc->sc_rc = ath_rate_attach(sc);
769         if (sc->sc_rc == NULL) {
770                 error = EIO;
771                 goto bad2;
772         }
773
774         /* Attach DFS module */
775         if (! ath_dfs_attach(sc)) {
776                 device_printf(sc->sc_dev,
777                     "%s: unable to attach DFS\n", __func__);
778                 error = EIO;
779                 goto bad2;
780         }
781
782         /* Attach spectral module */
783         if (ath_spectral_attach(sc) < 0) {
784                 device_printf(sc->sc_dev,
785                     "%s: unable to attach spectral\n", __func__);
786                 error = EIO;
787                 goto bad2;
788         }
789
790         /* Attach bluetooth coexistence module */
791         if (ath_btcoex_attach(sc) < 0) {
792                 device_printf(sc->sc_dev,
793                     "%s: unable to attach bluetooth coexistence\n", __func__);
794                 error = EIO;
795                 goto bad2;
796         }
797
798         /* Attach LNA diversity module */
799         if (ath_lna_div_attach(sc) < 0) {
800                 device_printf(sc->sc_dev,
801                     "%s: unable to attach LNA diversity\n", __func__);
802                 error = EIO;
803                 goto bad2;
804         }
805
806         /* Start DFS processing tasklet */
807         TASK_INIT(&sc->sc_dfstask, 0, ath_dfs_tasklet, sc);
808
809         /* Configure LED state */
810         sc->sc_blinking = 0;
811         sc->sc_ledstate = 1;
812         sc->sc_ledon = 0;                       /* low true */
813         sc->sc_ledidle = (2700*hz)/1000;        /* 2.7sec */
814         callout_init_mp(&sc->sc_ledtimer);
815
816         /*
817          * Don't setup hardware-based blinking.
818          *
819          * Although some NICs may have this configured in the
820          * default reset register values, the user may wish
821          * to alter which pins have which function.
822          *
823          * The reference driver attaches the MAC network LED to GPIO1 and
824          * the MAC power LED to GPIO2.  However, the DWA-552 cardbus
825          * NIC has these reversed.
826          */
827         sc->sc_hardled = (1 == 0);
828         sc->sc_led_net_pin = -1;
829         sc->sc_led_pwr_pin = -1;
830         /*
831          * Auto-enable soft led processing for IBM cards and for
832          * 5211 minipci cards.  Users can also manually enable/disable
833          * support with a sysctl.
834          */
835         sc->sc_softled = (devid == AR5212_DEVID_IBM || devid == AR5211_DEVID);
836         ath_led_config(sc);
837         ath_hal_setledstate(ah, HAL_LED_INIT);
838
839         ifp->if_softc = sc;
840         ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
841 #if defined(__DragonFly__)
842         ifp->if_start = ath_start;
843 #else
844         ifp->if_transmit = ath_transmit;
845         ifp->if_qflush = ath_qflush;
846 #endif
847         ifp->if_ioctl = ath_ioctl;
848         ifp->if_init = ath_init;
849 #if defined(__DragonFly__)
850         ifq_set_maxlen(&ifp->if_snd, IFQ_MAXLEN);
851 #else
852         IFQ_SET_MAXLEN(&ifp->if_snd, ifqmaxlen);
853         ifp->if_snd.ifq_drv_maxlen = ifqmaxlen;
854         IFQ_SET_READY(&ifp->if_snd);
855 #endif
856
857         ic->ic_ifp = ifp;
858         /* XXX not right but it's not used anywhere important */
859         ic->ic_phytype = IEEE80211_T_OFDM;
860         ic->ic_opmode = IEEE80211_M_STA;
861         ic->ic_caps =
862                   IEEE80211_C_STA               /* station mode */
863                 | IEEE80211_C_IBSS              /* ibss, nee adhoc, mode */
864                 | IEEE80211_C_HOSTAP            /* hostap mode */
865                 | IEEE80211_C_MONITOR           /* monitor mode */
866                 | IEEE80211_C_AHDEMO            /* adhoc demo mode */
867                 | IEEE80211_C_WDS               /* 4-address traffic works */
868                 | IEEE80211_C_MBSS              /* mesh point link mode */
869                 | IEEE80211_C_SHPREAMBLE        /* short preamble supported */
870                 | IEEE80211_C_SHSLOT            /* short slot time supported */
871                 | IEEE80211_C_WPA               /* capable of WPA1+WPA2 */
872 #ifndef ATH_ENABLE_11N
873                 | IEEE80211_C_BGSCAN            /* capable of bg scanning */
874 #endif
875                 | IEEE80211_C_TXFRAG            /* handle tx frags */
876 #ifdef  ATH_ENABLE_DFS
877                 | IEEE80211_C_DFS               /* Enable radar detection */
878 #endif
879                 | IEEE80211_C_PMGT              /* Station side power mgmt */
880                 | IEEE80211_C_SWSLEEP
881                 ;
882         /*
883          * Query the hal to figure out h/w crypto support.
884          */
885         if (ath_hal_ciphersupported(ah, HAL_CIPHER_WEP))
886                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_WEP;
887         if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_OCB))
888                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_OCB;
889         if (ath_hal_ciphersupported(ah, HAL_CIPHER_AES_CCM))
890                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_AES_CCM;
891         if (ath_hal_ciphersupported(ah, HAL_CIPHER_CKIP))
892                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_CKIP;
893         if (ath_hal_ciphersupported(ah, HAL_CIPHER_TKIP)) {
894                 ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIP;
895                 /*
896                  * Check if h/w does the MIC and/or whether the
897                  * separate key cache entries are required to
898                  * handle both tx+rx MIC keys.
899                  */
900                 if (ath_hal_ciphersupported(ah, HAL_CIPHER_MIC))
901                         ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
902                 /*
903                  * If the h/w supports storing tx+rx MIC keys
904                  * in one cache slot automatically enable use.
905                  */
906                 if (ath_hal_hastkipsplit(ah) ||
907                     !ath_hal_settkipsplit(ah, AH_FALSE))
908                         sc->sc_splitmic = 1;
909                 /*
910                  * If the h/w can do TKIP MIC together with WME then
911                  * we use it; otherwise we force the MIC to be done
912                  * in software by the net80211 layer.
913                  */
914                 if (ath_hal_haswmetkipmic(ah))
915                         sc->sc_wmetkipmic = 1;
916         }
917         sc->sc_hasclrkey = ath_hal_ciphersupported(ah, HAL_CIPHER_CLR);
918         /*
919          * Check for multicast key search support.
920          */
921         if (ath_hal_hasmcastkeysearch(sc->sc_ah) &&
922             !ath_hal_getmcastkeysearch(sc->sc_ah)) {
923                 ath_hal_setmcastkeysearch(sc->sc_ah, 1);
924         }
925         sc->sc_mcastkey = ath_hal_getmcastkeysearch(ah);
926         /*
927          * Mark key cache slots associated with global keys
928          * as in use.  If we knew TKIP was not to be used we
929          * could leave the +32, +64, and +32+64 slots free.
930          */
931         for (i = 0; i < IEEE80211_WEP_NKID; i++) {
932                 setbit(sc->sc_keymap, i);
933                 setbit(sc->sc_keymap, i+64);
934                 if (sc->sc_splitmic) {
935                         setbit(sc->sc_keymap, i+32);
936                         setbit(sc->sc_keymap, i+32+64);
937                 }
938         }
939         /*
940          * TPC support can be done either with a global cap or
941          * per-packet support.  The latter is not available on
942          * all parts.  We're a bit pedantic here as all parts
943          * support a global cap.
944          */
945         if (ath_hal_hastpc(ah) || ath_hal_hastxpowlimit(ah))
946                 ic->ic_caps |= IEEE80211_C_TXPMGT;
947
948         /*
949          * Mark WME capability only if we have sufficient
950          * hardware queues to do proper priority scheduling.
951          */
952         if (sc->sc_ac2q[WME_AC_BE] != sc->sc_ac2q[WME_AC_BK])
953                 ic->ic_caps |= IEEE80211_C_WME;
954         /*
955          * Check for misc other capabilities.
956          */
957         if (ath_hal_hasbursting(ah))
958                 ic->ic_caps |= IEEE80211_C_BURST;
959         sc->sc_hasbmask = ath_hal_hasbssidmask(ah);
960         sc->sc_hasbmatch = ath_hal_hasbssidmatch(ah);
961         sc->sc_hastsfadd = ath_hal_hastsfadjust(ah);
962         sc->sc_rxslink = ath_hal_self_linked_final_rxdesc(ah);
963         sc->sc_rxtsf32 = ath_hal_has_long_rxdesc_tsf(ah);
964         sc->sc_hasenforcetxop = ath_hal_hasenforcetxop(ah);
965         sc->sc_rx_lnamixer = ath_hal_hasrxlnamixer(ah);
966         sc->sc_hasdivcomb = ath_hal_hasdivantcomb(ah);
967
968         if (ath_hal_hasfastframes(ah))
969                 ic->ic_caps |= IEEE80211_C_FF;
970         wmodes = ath_hal_getwirelessmodes(ah);
971         if (wmodes & (HAL_MODE_108G|HAL_MODE_TURBO))
972                 ic->ic_caps |= IEEE80211_C_TURBOP;
973 #ifdef IEEE80211_SUPPORT_TDMA
974         if (ath_hal_macversion(ah) > 0x78) {
975                 ic->ic_caps |= IEEE80211_C_TDMA; /* capable of TDMA */
976                 ic->ic_tdma_update = ath_tdma_update;
977         }
978 #endif
979
980         /*
981          * TODO: enforce that at least this many frames are available
982          * in the txbuf list before allowing data frames (raw or
983          * otherwise) to be transmitted.
984          */
985         sc->sc_txq_data_minfree = 10;
986         /*
987          * Leave this as default to maintain legacy behaviour.
988          * Shortening the cabq/mcastq may end up causing some
989          * undesirable behaviour.
990          */
991         sc->sc_txq_mcastq_maxdepth = ath_txbuf;
992
993         /*
994          * How deep can the node software TX queue get whilst it's asleep.
995          */
996         sc->sc_txq_node_psq_maxdepth = 16;
997
998         /*
999          * Default the maximum queue depth for a given node
1000          * to 1/4'th the TX buffers, or 64, whichever
1001          * is larger.
1002          */
1003         sc->sc_txq_node_maxdepth = MAX(64, ath_txbuf / 4);
1004
1005         /* Enable CABQ by default */
1006         sc->sc_cabq_enable = 1;
1007
1008         /*
1009          * Allow the TX and RX chainmasks to be overridden by
1010          * environment variables and/or device.hints.
1011          *
1012          * This must be done early - before the hardware is
1013          * calibrated or before the 802.11n stream calculation
1014          * is done.
1015          */
1016         if (resource_int_value(device_get_name(sc->sc_dev),
1017             device_get_unit(sc->sc_dev), "rx_chainmask",
1018             &rx_chainmask) == 0) {
1019                 device_printf(sc->sc_dev, "Setting RX chainmask to 0x%x\n",
1020                     rx_chainmask);
1021                 (void) ath_hal_setrxchainmask(sc->sc_ah, rx_chainmask);
1022         }
1023         if (resource_int_value(device_get_name(sc->sc_dev),
1024             device_get_unit(sc->sc_dev), "tx_chainmask",
1025             &tx_chainmask) == 0) {
1026                 device_printf(sc->sc_dev, "Setting TX chainmask to 0x%x\n",
1027                     tx_chainmask);
1028                 (void) ath_hal_settxchainmask(sc->sc_ah, tx_chainmask);
1029         }
1030
1031         /*
1032          * Query the TX/RX chainmask configuration.
1033          *
1034          * This is only relevant for 11n devices.
1035          */
1036         ath_hal_getrxchainmask(ah, &sc->sc_rxchainmask);
1037         ath_hal_gettxchainmask(ah, &sc->sc_txchainmask);
1038
1039         /*
1040          * Disable MRR with protected frames by default.
1041          * Only 802.11n series NICs can handle this.
1042          */
1043         sc->sc_mrrprot = 0;     /* XXX should be a capability */
1044
1045         /*
1046          * Query the enterprise mode information the HAL.
1047          */
1048         if (ath_hal_getcapability(ah, HAL_CAP_ENTERPRISE_MODE, 0,
1049             &sc->sc_ent_cfg) == HAL_OK)
1050                 sc->sc_use_ent = 1;
1051
1052 #ifdef  ATH_ENABLE_11N
1053         /*
1054          * Query HT capabilities
1055          */
1056         if (ath_hal_getcapability(ah, HAL_CAP_HT, 0, NULL) == HAL_OK &&
1057             (wmodes & (HAL_MODE_HT20 | HAL_MODE_HT40))) {
1058                 uint32_t rxs, txs;
1059
1060                 device_printf(sc->sc_dev, "[HT] enabling HT modes\n");
1061
1062                 sc->sc_mrrprot = 1;     /* XXX should be a capability */
1063
1064                 ic->ic_htcaps = IEEE80211_HTC_HT        /* HT operation */
1065                             | IEEE80211_HTC_AMPDU       /* A-MPDU tx/rx */
1066                             | IEEE80211_HTC_AMSDU       /* A-MSDU tx/rx */
1067                             | IEEE80211_HTCAP_MAXAMSDU_3839
1068                                                         /* max A-MSDU length */
1069                             | IEEE80211_HTCAP_SMPS_OFF; /* SM power save off */
1070                         ;
1071
1072                 /*
1073                  * Enable short-GI for HT20 only if the hardware
1074                  * advertises support.
1075                  * Notably, anything earlier than the AR9287 doesn't.
1076                  */
1077                 if ((ath_hal_getcapability(ah,
1078                     HAL_CAP_HT20_SGI, 0, NULL) == HAL_OK) &&
1079                     (wmodes & HAL_MODE_HT20)) {
1080                         device_printf(sc->sc_dev,
1081                             "[HT] enabling short-GI in 20MHz mode\n");
1082                         ic->ic_htcaps |= IEEE80211_HTCAP_SHORTGI20;
1083                 }
1084
1085                 if (wmodes & HAL_MODE_HT40)
1086                         ic->ic_htcaps |= IEEE80211_HTCAP_CHWIDTH40
1087                             |  IEEE80211_HTCAP_SHORTGI40;
1088
1089                 /*
1090                  * TX/RX streams need to be taken into account when
1091                  * negotiating which MCS rates it'll receive and
1092                  * what MCS rates are available for TX.
1093                  */
1094                 (void) ath_hal_getcapability(ah, HAL_CAP_STREAMS, 0, &txs);
1095                 (void) ath_hal_getcapability(ah, HAL_CAP_STREAMS, 1, &rxs);
1096                 ic->ic_txstream = txs;
1097                 ic->ic_rxstream = rxs;
1098
1099                 /*
1100                  * Setup TX and RX STBC based on what the HAL allows and
1101                  * the currently configured chainmask set.
1102                  * Ie - don't enable STBC TX if only one chain is enabled.
1103                  * STBC RX is fine on a single RX chain; it just won't
1104                  * provide any real benefit.
1105                  */
1106                 if (ath_hal_getcapability(ah, HAL_CAP_RX_STBC, 0,
1107                     NULL) == HAL_OK) {
1108                         sc->sc_rx_stbc = 1;
1109                         device_printf(sc->sc_dev,
1110                             "[HT] 1 stream STBC receive enabled\n");
1111                         ic->ic_htcaps |= IEEE80211_HTCAP_RXSTBC_1STREAM;
1112                 }
1113                 if (txs > 1 && ath_hal_getcapability(ah, HAL_CAP_TX_STBC, 0,
1114                     NULL) == HAL_OK) {
1115                         sc->sc_tx_stbc = 1;
1116                         device_printf(sc->sc_dev,
1117                             "[HT] 1 stream STBC transmit enabled\n");
1118                         ic->ic_htcaps |= IEEE80211_HTCAP_TXSTBC;
1119                 }
1120
1121                 (void) ath_hal_getcapability(ah, HAL_CAP_RTS_AGGR_LIMIT, 1,
1122                     &sc->sc_rts_aggr_limit);
1123                 if (sc->sc_rts_aggr_limit != (64 * 1024))
1124                         device_printf(sc->sc_dev,
1125                             "[HT] RTS aggregates limited to %d KiB\n",
1126                             sc->sc_rts_aggr_limit / 1024);
1127
1128                 device_printf(sc->sc_dev,
1129                     "[HT] %d RX streams; %d TX streams\n", rxs, txs);
1130         }
1131 #endif
1132
1133         /*
1134          * Initial aggregation settings.
1135          */
1136         sc->sc_hwq_limit_aggr = ATH_AGGR_MIN_QDEPTH;
1137         sc->sc_hwq_limit_nonaggr = ATH_NONAGGR_MIN_QDEPTH;
1138         sc->sc_tid_hwq_lo = ATH_AGGR_SCHED_LOW;
1139         sc->sc_tid_hwq_hi = ATH_AGGR_SCHED_HIGH;
1140         sc->sc_aggr_limit = ATH_AGGR_MAXSIZE;
1141         sc->sc_delim_min_pad = 0;
1142
1143         /*
1144          * Check if the hardware requires PCI register serialisation.
1145          * Some of the Owl based MACs require this.
1146          */
1147         if (ncpus > 1 &&
1148             ath_hal_getcapability(ah, HAL_CAP_SERIALISE_WAR,
1149              0, NULL) == HAL_OK) {
1150                 sc->sc_ah->ah_config.ah_serialise_reg_war = 1;
1151                 device_printf(sc->sc_dev,
1152                     "Enabling register serialisation\n");
1153         }
1154
1155         /*
1156          * Initialise the deferred completed RX buffer list.
1157          */
1158         TAILQ_INIT(&sc->sc_rx_rxlist[HAL_RX_QUEUE_HP]);
1159         TAILQ_INIT(&sc->sc_rx_rxlist[HAL_RX_QUEUE_LP]);
1160
1161         /*
1162          * Indicate we need the 802.11 header padded to a
1163          * 32-bit boundary for 4-address and QoS frames.
1164          */
1165         ic->ic_flags |= IEEE80211_F_DATAPAD;
1166
1167         /*
1168          * Query the hal about antenna support.
1169          */
1170         sc->sc_defant = ath_hal_getdefantenna(ah);
1171
1172         /*
1173          * Not all chips have the VEOL support we want to
1174          * use with IBSS beacons; check here for it.
1175          */
1176         sc->sc_hasveol = ath_hal_hasveol(ah);
1177
1178         /* get mac address from hardware */
1179         ath_hal_getmac(ah, macaddr);
1180         if (sc->sc_hasbmask)
1181                 ath_hal_getbssidmask(ah, sc->sc_hwbssidmask);
1182
1183         /* NB: used to size node table key mapping array */
1184         ic->ic_max_keyix = sc->sc_keymax;
1185         /* Call MI attach routine. */
1186         ieee80211_ifattach(ic, macaddr);
1187         ic->ic_setregdomain = ath_setregdomain;
1188         ic->ic_getradiocaps = ath_getradiocaps;
1189         sc->sc_opmode = HAL_M_STA;
1190
1191         /* override default methods */
1192         ic->ic_newassoc = ath_newassoc;
1193         ic->ic_updateslot = ath_updateslot;
1194         ic->ic_wme.wme_update = ath_wme_update;
1195         ic->ic_vap_create = ath_vap_create;
1196         ic->ic_vap_delete = ath_vap_delete;
1197         ic->ic_raw_xmit = ath_raw_xmit;
1198         ic->ic_update_mcast = ath_update_mcast;
1199         ic->ic_update_promisc = ath_update_promisc;
1200         ic->ic_node_alloc = ath_node_alloc;
1201         sc->sc_node_free = ic->ic_node_free;
1202         ic->ic_node_free = ath_node_free;
1203         sc->sc_node_cleanup = ic->ic_node_cleanup;
1204         ic->ic_node_cleanup = ath_node_cleanup;
1205         ic->ic_node_getsignal = ath_node_getsignal;
1206         ic->ic_scan_start = ath_scan_start;
1207         ic->ic_scan_end = ath_scan_end;
1208         ic->ic_set_channel = ath_set_channel;
1209 #ifdef  ATH_ENABLE_11N
1210         /* 802.11n specific - but just override anyway */
1211         sc->sc_addba_request = ic->ic_addba_request;
1212         sc->sc_addba_response = ic->ic_addba_response;
1213         sc->sc_addba_stop = ic->ic_addba_stop;
1214         sc->sc_bar_response = ic->ic_bar_response;
1215         sc->sc_addba_response_timeout = ic->ic_addba_response_timeout;
1216
1217         ic->ic_addba_request = ath_addba_request;
1218         ic->ic_addba_response = ath_addba_response;
1219         ic->ic_addba_response_timeout = ath_addba_response_timeout;
1220         ic->ic_addba_stop = ath_addba_stop;
1221         ic->ic_bar_response = ath_bar_response;
1222
1223         ic->ic_update_chw = ath_update_chw;
1224 #endif  /* ATH_ENABLE_11N */
1225
1226 #ifdef  ATH_ENABLE_RADIOTAP_VENDOR_EXT
1227         /*
1228          * There's one vendor bitmap entry in the RX radiotap
1229          * header; make sure that's taken into account.
1230          */
1231         ieee80211_radiotap_attachv(ic,
1232             &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th), 0,
1233                 ATH_TX_RADIOTAP_PRESENT,
1234             &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th), 1,
1235                 ATH_RX_RADIOTAP_PRESENT);
1236 #else
1237         /*
1238          * No vendor bitmap/extensions are present.
1239          */
1240         ieee80211_radiotap_attach(ic,
1241             &sc->sc_tx_th.wt_ihdr, sizeof(sc->sc_tx_th),
1242                 ATH_TX_RADIOTAP_PRESENT,
1243             &sc->sc_rx_th.wr_ihdr, sizeof(sc->sc_rx_th),
1244                 ATH_RX_RADIOTAP_PRESENT);
1245 #endif  /* ATH_ENABLE_RADIOTAP_VENDOR_EXT */
1246
1247         /*
1248          * Setup the ALQ logging if required
1249          */
1250 #ifdef  ATH_DEBUG_ALQ
1251         if_ath_alq_init(&sc->sc_alq, device_get_nameunit(sc->sc_dev));
1252         if_ath_alq_setcfg(&sc->sc_alq,
1253             sc->sc_ah->ah_macVersion,
1254             sc->sc_ah->ah_macRev,
1255             sc->sc_ah->ah_phyRev,
1256             sc->sc_ah->ah_magic);
1257 #endif
1258
1259         /*
1260          * Setup dynamic sysctl's now that country code and
1261          * regdomain are available from the hal.
1262          */
1263         ath_sysctlattach(sc);
1264         ath_sysctl_stats_attach(sc);
1265         ath_sysctl_hal_attach(sc);
1266
1267         if (bootverbose)
1268                 ieee80211_announce(ic);
1269         ath_announce(sc);
1270
1271         /*
1272          * Put it to sleep for now.
1273          */
1274         ATH_LOCK(sc);
1275         ath_power_setpower(sc, HAL_PM_FULL_SLEEP);
1276         ATH_UNLOCK(sc);
1277
1278         wlan_serialize_exit();
1279
1280         return 0;
1281 bad2:
1282         ath_tx_cleanup(sc);
1283         ath_desc_free(sc);
1284         ath_txdma_teardown(sc);
1285         ath_rxdma_teardown(sc);
1286 bad:
1287         if (ah)
1288                 ath_hal_detach(ah);
1289
1290         /*
1291          * To work around scoping issues with CURVNET_SET/CURVNET_RESTORE..
1292          */
1293 #if !defined(__DragonFly__)
1294         if (ifp != NULL && ifp->if_vnet) {
1295                 CURVNET_SET(ifp->if_vnet);
1296                 if_free(ifp);
1297                 CURVNET_RESTORE();
1298         } else 
1299 #endif
1300         if (ifp != NULL)
1301                 if_free(ifp);
1302         sc->sc_invalid = 1;
1303         wlan_serialize_exit();
1304
1305         return error;
1306 }
1307
1308 int
1309 ath_detach(struct ath_softc *sc)
1310 {
1311         struct ifnet *ifp = sc->sc_ifp;
1312
1313         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1314                 __func__, ifp->if_flags);
1315
1316         /*
1317          * NB: the order of these is important:
1318          * o stop the chip so no more interrupts will fire
1319          * o call the 802.11 layer before detaching the hal to
1320          *   insure callbacks into the driver to delete global
1321          *   key cache entries can be handled
1322          * o free the taskqueue which drains any pending tasks
1323          * o reclaim the tx queue data structures after calling
1324          *   the 802.11 layer as we'll get called back to reclaim
1325          *   node state and potentially want to use them
1326          * o to cleanup the tx queues the hal is called, so detach
1327          *   it last
1328          * Other than that, it's straightforward...
1329          */
1330
1331         /*
1332          * XXX Wake the hardware up first.  ath_stop() will still
1333          * wake it up first, but I'd rather do it here just to
1334          * ensure it's awake.
1335          */
1336         ATH_LOCK(sc);
1337         ath_power_set_power_state(sc, HAL_PM_AWAKE);
1338         ath_power_setpower(sc, HAL_PM_AWAKE);
1339         ATH_UNLOCK(sc);
1340
1341         /*
1342          * Stop things cleanly.
1343          */
1344         ath_stop(ifp);
1345
1346         wlan_serialize_enter();
1347         ieee80211_ifdetach(ifp->if_l2com);
1348         wlan_serialize_exit();
1349         taskqueue_free(sc->sc_tq);
1350 #ifdef ATH_TX99_DIAG
1351         if (sc->sc_tx99 != NULL)
1352                 sc->sc_tx99->detach(sc->sc_tx99);
1353 #endif
1354         ath_rate_detach(sc->sc_rc);
1355 #ifdef  ATH_DEBUG_ALQ
1356         if_ath_alq_tidyup(&sc->sc_alq);
1357 #endif
1358         ath_lna_div_detach(sc);
1359         ath_btcoex_detach(sc);
1360         ath_spectral_detach(sc);
1361         ath_dfs_detach(sc);
1362         ath_desc_free(sc);
1363         ath_txdma_teardown(sc);
1364         ath_rxdma_teardown(sc);
1365         ath_tx_cleanup(sc);
1366         ath_hal_detach(sc->sc_ah);      /* NB: sets chip in full sleep */
1367
1368         CURVNET_SET(ifp->if_vnet);
1369         if_free(ifp);
1370         CURVNET_RESTORE();
1371
1372         return 0;
1373 }
1374
1375 /*
1376  * MAC address handling for multiple BSS on the same radio.
1377  * The first vap uses the MAC address from the EEPROM.  For
1378  * subsequent vap's we set the U/L bit (bit 1) in the MAC
1379  * address and use the next six bits as an index.
1380  */
1381 static void
1382 assign_address(struct ath_softc *sc, uint8_t mac[IEEE80211_ADDR_LEN], int clone)
1383 {
1384         int i;
1385
1386         if (clone && sc->sc_hasbmask) {
1387                 /* NB: we only do this if h/w supports multiple bssid */
1388                 for (i = 0; i < 8; i++)
1389                         if ((sc->sc_bssidmask & (1<<i)) == 0)
1390                                 break;
1391                 if (i != 0)
1392                         mac[0] |= (i << 2)|0x2;
1393         } else
1394                 i = 0;
1395         sc->sc_bssidmask |= 1<<i;
1396         sc->sc_hwbssidmask[0] &= ~mac[0];
1397         if (i == 0)
1398                 sc->sc_nbssid0++;
1399 }
1400
1401 static void
1402 reclaim_address(struct ath_softc *sc, const uint8_t mac[IEEE80211_ADDR_LEN])
1403 {
1404         int i = mac[0] >> 2;
1405         uint8_t mask;
1406
1407         if (i != 0 || --sc->sc_nbssid0 == 0) {
1408                 sc->sc_bssidmask &= ~(1<<i);
1409                 /* recalculate bssid mask from remaining addresses */
1410                 mask = 0xff;
1411                 for (i = 1; i < 8; i++)
1412                         if (sc->sc_bssidmask & (1<<i))
1413                                 mask &= ~((i<<2)|0x2);
1414                 sc->sc_hwbssidmask[0] |= mask;
1415         }
1416 }
1417
1418 /*
1419  * Assign a beacon xmit slot.  We try to space out
1420  * assignments so when beacons are staggered the
1421  * traffic coming out of the cab q has maximal time
1422  * to go out before the next beacon is scheduled.
1423  */
1424 static int
1425 assign_bslot(struct ath_softc *sc)
1426 {
1427         u_int slot, free;
1428
1429         free = 0;
1430         for (slot = 0; slot < ATH_BCBUF; slot++)
1431                 if (sc->sc_bslot[slot] == NULL) {
1432                         if (sc->sc_bslot[(slot+1)%ATH_BCBUF] == NULL &&
1433                             sc->sc_bslot[(slot-1)%ATH_BCBUF] == NULL)
1434                                 return slot;
1435                         free = slot;
1436                         /* NB: keep looking for a double slot */
1437                 }
1438         return free;
1439 }
1440
1441 static struct ieee80211vap *
1442 ath_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
1443     enum ieee80211_opmode opmode, int flags,
1444     const uint8_t bssid[IEEE80211_ADDR_LEN],
1445     const uint8_t mac0[IEEE80211_ADDR_LEN])
1446 {
1447         struct ath_softc *sc = ic->ic_ifp->if_softc;
1448         struct ath_vap *avp;
1449         struct ieee80211vap *vap;
1450         uint8_t mac[IEEE80211_ADDR_LEN];
1451         int needbeacon, error;
1452         enum ieee80211_opmode ic_opmode;
1453
1454         avp = kmalloc(sizeof(struct ath_vap), M_80211_VAP, M_WAITOK | M_ZERO);
1455         needbeacon = 0;
1456         IEEE80211_ADDR_COPY(mac, mac0);
1457
1458         ATH_LOCK(sc);
1459         ic_opmode = opmode;             /* default to opmode of new vap */
1460         switch (opmode) {
1461         case IEEE80211_M_STA:
1462                 if (sc->sc_nstavaps != 0) {     /* XXX only 1 for now */
1463                         device_printf(sc->sc_dev, "only 1 sta vap supported\n");
1464                         goto bad;
1465                 }
1466                 if (sc->sc_nvaps) {
1467                         /*
1468                          * With multiple vaps we must fall back
1469                          * to s/w beacon miss handling.
1470                          */
1471                         flags |= IEEE80211_CLONE_NOBEACONS;
1472                 }
1473                 if (flags & IEEE80211_CLONE_NOBEACONS) {
1474                         /*
1475                          * Station mode w/o beacons are implemented w/ AP mode.
1476                          */
1477                         ic_opmode = IEEE80211_M_HOSTAP;
1478                 }
1479                 break;
1480         case IEEE80211_M_IBSS:
1481                 if (sc->sc_nvaps != 0) {        /* XXX only 1 for now */
1482                         device_printf(sc->sc_dev,
1483                             "only 1 ibss vap supported\n");
1484                         goto bad;
1485                 }
1486                 needbeacon = 1;
1487                 break;
1488         case IEEE80211_M_AHDEMO:
1489 #ifdef IEEE80211_SUPPORT_TDMA
1490                 if (flags & IEEE80211_CLONE_TDMA) {
1491                         if (sc->sc_nvaps != 0) {
1492                                 device_printf(sc->sc_dev,
1493                                     "only 1 tdma vap supported\n");
1494                                 goto bad;
1495                         }
1496                         needbeacon = 1;
1497                         flags |= IEEE80211_CLONE_NOBEACONS;
1498                 }
1499                 /* fall thru... */
1500 #endif
1501         case IEEE80211_M_MONITOR:
1502                 if (sc->sc_nvaps != 0 && ic->ic_opmode != opmode) {
1503                         /*
1504                          * Adopt existing mode.  Adding a monitor or ahdemo
1505                          * vap to an existing configuration is of dubious
1506                          * value but should be ok.
1507                          */
1508                         /* XXX not right for monitor mode */
1509                         ic_opmode = ic->ic_opmode;
1510                 }
1511                 break;
1512         case IEEE80211_M_HOSTAP:
1513         case IEEE80211_M_MBSS:
1514                 needbeacon = 1;
1515                 break;
1516         case IEEE80211_M_WDS:
1517                 if (sc->sc_nvaps != 0 && ic->ic_opmode == IEEE80211_M_STA) {
1518                         device_printf(sc->sc_dev,
1519                             "wds not supported in sta mode\n");
1520                         goto bad;
1521                 }
1522                 /*
1523                  * Silently remove any request for a unique
1524                  * bssid; WDS vap's always share the local
1525                  * mac address.
1526                  */
1527                 flags &= ~IEEE80211_CLONE_BSSID;
1528                 if (sc->sc_nvaps == 0)
1529                         ic_opmode = IEEE80211_M_HOSTAP;
1530                 else
1531                         ic_opmode = ic->ic_opmode;
1532                 break;
1533         default:
1534                 device_printf(sc->sc_dev, "unknown opmode %d\n", opmode);
1535                 goto bad;
1536         }
1537         /*
1538          * Check that a beacon buffer is available; the code below assumes it.
1539          */
1540         if (needbeacon & TAILQ_EMPTY(&sc->sc_bbuf)) {
1541                 device_printf(sc->sc_dev, "no beacon buffer available\n");
1542                 goto bad;
1543         }
1544
1545         /* STA, AHDEMO? */
1546         if (opmode == IEEE80211_M_HOSTAP || opmode == IEEE80211_M_MBSS) {
1547                 assign_address(sc, mac, flags & IEEE80211_CLONE_BSSID);
1548                 ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
1549         }
1550
1551         vap = &avp->av_vap;
1552         /* XXX can't hold mutex across if_alloc */
1553         ATH_UNLOCK(sc);
1554         error = ieee80211_vap_setup(ic, vap, name, unit, opmode, flags,
1555             bssid, mac);
1556         ATH_LOCK(sc);
1557         if (error != 0) {
1558                 device_printf(sc->sc_dev, "%s: error %d creating vap\n",
1559                     __func__, error);
1560                 goto bad2;
1561         }
1562
1563         /* h/w crypto support */
1564         vap->iv_key_alloc = ath_key_alloc;
1565         vap->iv_key_delete = ath_key_delete;
1566         vap->iv_key_set = ath_key_set;
1567         vap->iv_key_update_begin = ath_key_update_begin;
1568         vap->iv_key_update_end = ath_key_update_end;
1569
1570         /* override various methods */
1571         avp->av_recv_mgmt = vap->iv_recv_mgmt;
1572         vap->iv_recv_mgmt = ath_recv_mgmt;
1573         vap->iv_reset = ath_reset_vap;
1574         vap->iv_update_beacon = ath_beacon_update;
1575         avp->av_newstate = vap->iv_newstate;
1576         vap->iv_newstate = ath_newstate;
1577         avp->av_bmiss = vap->iv_bmiss;
1578         vap->iv_bmiss = ath_bmiss_vap;
1579
1580         avp->av_node_ps = vap->iv_node_ps;
1581         vap->iv_node_ps = ath_node_powersave;
1582
1583         avp->av_set_tim = vap->iv_set_tim;
1584         vap->iv_set_tim = ath_node_set_tim;
1585
1586         avp->av_recv_pspoll = vap->iv_recv_pspoll;
1587         vap->iv_recv_pspoll = ath_node_recv_pspoll;
1588
1589         /* Set default parameters */
1590
1591         /*
1592          * Anything earlier than some AR9300 series MACs don't
1593          * support a smaller MPDU density.
1594          */
1595         vap->iv_ampdu_density = IEEE80211_HTCAP_MPDUDENSITY_8;
1596         /*
1597          * All NICs can handle the maximum size, however
1598          * AR5416 based MACs can only TX aggregates w/ RTS
1599          * protection when the total aggregate size is <= 8k.
1600          * However, for now that's enforced by the TX path.
1601          */
1602         vap->iv_ampdu_rxmax = IEEE80211_HTCAP_MAXRXAMPDU_64K;
1603
1604         avp->av_bslot = -1;
1605         if (needbeacon) {
1606                 /*
1607                  * Allocate beacon state and setup the q for buffered
1608                  * multicast frames.  We know a beacon buffer is
1609                  * available because we checked above.
1610                  */
1611                 avp->av_bcbuf = TAILQ_FIRST(&sc->sc_bbuf);
1612                 TAILQ_REMOVE(&sc->sc_bbuf, avp->av_bcbuf, bf_list);
1613                 if (opmode != IEEE80211_M_IBSS || !sc->sc_hasveol) {
1614                         /*
1615                          * Assign the vap to a beacon xmit slot.  As above
1616                          * this cannot fail to find a free one.
1617                          */
1618                         avp->av_bslot = assign_bslot(sc);
1619                         KASSERT(sc->sc_bslot[avp->av_bslot] == NULL,
1620                             ("beacon slot %u not empty", avp->av_bslot));
1621                         sc->sc_bslot[avp->av_bslot] = vap;
1622                         sc->sc_nbcnvaps++;
1623                 }
1624                 if (sc->sc_hastsfadd && sc->sc_nbcnvaps > 0) {
1625                         /*
1626                          * Multple vaps are to transmit beacons and we
1627                          * have h/w support for TSF adjusting; enable
1628                          * use of staggered beacons.
1629                          */
1630                         sc->sc_stagbeacons = 1;
1631                 }
1632                 ath_txq_init(sc, &avp->av_mcastq, ATH_TXQ_SWQ);
1633         }
1634
1635         ic->ic_opmode = ic_opmode;
1636         if (opmode != IEEE80211_M_WDS) {
1637                 sc->sc_nvaps++;
1638                 if (opmode == IEEE80211_M_STA)
1639                         sc->sc_nstavaps++;
1640                 if (opmode == IEEE80211_M_MBSS)
1641                         sc->sc_nmeshvaps++;
1642         }
1643         switch (ic_opmode) {
1644         case IEEE80211_M_IBSS:
1645                 sc->sc_opmode = HAL_M_IBSS;
1646                 break;
1647         case IEEE80211_M_STA:
1648                 sc->sc_opmode = HAL_M_STA;
1649                 break;
1650         case IEEE80211_M_AHDEMO:
1651 #ifdef IEEE80211_SUPPORT_TDMA
1652                 if (vap->iv_caps & IEEE80211_C_TDMA) {
1653                         sc->sc_tdma = 1;
1654                         /* NB: disable tsf adjust */
1655                         sc->sc_stagbeacons = 0;
1656                 }
1657                 /*
1658                  * NB: adhoc demo mode is a pseudo mode; to the hal it's
1659                  * just ap mode.
1660                  */
1661                 /* fall thru... */
1662 #endif
1663         case IEEE80211_M_HOSTAP:
1664         case IEEE80211_M_MBSS:
1665                 sc->sc_opmode = HAL_M_HOSTAP;
1666                 break;
1667         case IEEE80211_M_MONITOR:
1668                 sc->sc_opmode = HAL_M_MONITOR;
1669                 break;
1670         default:
1671                 /* XXX should not happen */
1672                 break;
1673         }
1674         if (sc->sc_hastsfadd) {
1675                 /*
1676                  * Configure whether or not TSF adjust should be done.
1677                  */
1678                 ath_hal_settsfadjust(sc->sc_ah, sc->sc_stagbeacons);
1679         }
1680         if (flags & IEEE80211_CLONE_NOBEACONS) {
1681                 /*
1682                  * Enable s/w beacon miss handling.
1683                  */
1684                 sc->sc_swbmiss = 1;
1685         }
1686         ATH_UNLOCK(sc);
1687
1688         /* complete setup */
1689         ieee80211_vap_attach(vap, ath_media_change, ieee80211_media_status);
1690         return vap;
1691 bad2:
1692         reclaim_address(sc, mac);
1693         ath_hal_setbssidmask(sc->sc_ah, sc->sc_hwbssidmask);
1694 bad:
1695         kfree(avp, M_80211_VAP);
1696         ATH_UNLOCK(sc);
1697         return NULL;
1698 }
1699
1700 static void
1701 ath_vap_delete(struct ieee80211vap *vap)
1702 {
1703         struct ieee80211com *ic = vap->iv_ic;
1704         struct ifnet *ifp = ic->ic_ifp;
1705         struct ath_softc *sc = ifp->if_softc;
1706         struct ath_hal *ah = sc->sc_ah;
1707         struct ath_vap *avp = ATH_VAP(vap);
1708
1709         ATH_LOCK(sc);
1710         ath_power_set_power_state(sc, HAL_PM_AWAKE);
1711         ATH_UNLOCK(sc);
1712
1713         DPRINTF(sc, ATH_DEBUG_RESET, "%s: called\n", __func__);
1714         if (ifp->if_flags & IFF_RUNNING) {
1715                 /*
1716                  * Quiesce the hardware while we remove the vap.  In
1717                  * particular we need to reclaim all references to
1718                  * the vap state by any frames pending on the tx queues.
1719                  */
1720                 ath_hal_intrset(ah, 0);         /* disable interrupts */
1721                 /* XXX Do all frames from all vaps/nodes need draining here? */
1722                 ath_stoprecv(sc, 1);            /* stop recv side */
1723                 ath_draintxq(sc, ATH_RESET_DEFAULT);            /* stop hw xmit side */
1724         }
1725
1726         /* .. leave the hardware awake for now. */
1727
1728         ieee80211_vap_detach(vap);
1729
1730         /*
1731          * XXX Danger Will Robinson! Danger!
1732          *
1733          * Because ieee80211_vap_detach() can queue a frame (the station
1734          * diassociate message?) after we've drained the TXQ and
1735          * flushed the software TXQ, we will end up with a frame queued
1736          * to a node whose vap is about to be freed.
1737          *
1738          * To work around this, flush the hardware/software again.
1739          * This may be racy - the ath task may be running and the packet
1740          * may be being scheduled between sw->hw txq. Tsk.
1741          *
1742          * TODO: figure out why a new node gets allocated somewhere around
1743          * here (after the ath_tx_swq() call; and after an ath_stop_locked()
1744          * call!)
1745          */
1746
1747         ath_draintxq(sc, ATH_RESET_DEFAULT);
1748
1749         ATH_LOCK(sc);
1750         /*
1751          * Reclaim beacon state.  Note this must be done before
1752          * the vap instance is reclaimed as we may have a reference
1753          * to it in the buffer for the beacon frame.
1754          */
1755         if (avp->av_bcbuf != NULL) {
1756                 if (avp->av_bslot != -1) {
1757                         sc->sc_bslot[avp->av_bslot] = NULL;
1758                         sc->sc_nbcnvaps--;
1759                 }
1760                 ath_beacon_return(sc, avp->av_bcbuf);
1761                 avp->av_bcbuf = NULL;
1762                 if (sc->sc_nbcnvaps == 0) {
1763                         sc->sc_stagbeacons = 0;
1764                         if (sc->sc_hastsfadd)
1765                                 ath_hal_settsfadjust(sc->sc_ah, 0);
1766                 }
1767                 /*
1768                  * Reclaim any pending mcast frames for the vap.
1769                  */
1770                 ath_tx_draintxq(sc, &avp->av_mcastq);
1771         }
1772         /*
1773          * Update bookkeeping.
1774          */
1775         if (vap->iv_opmode == IEEE80211_M_STA) {
1776                 sc->sc_nstavaps--;
1777                 if (sc->sc_nstavaps == 0 && sc->sc_swbmiss)
1778                         sc->sc_swbmiss = 0;
1779         } else if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
1780             vap->iv_opmode == IEEE80211_M_MBSS) {
1781                 reclaim_address(sc, vap->iv_myaddr);
1782                 ath_hal_setbssidmask(ah, sc->sc_hwbssidmask);
1783                 if (vap->iv_opmode == IEEE80211_M_MBSS)
1784                         sc->sc_nmeshvaps--;
1785         }
1786         if (vap->iv_opmode != IEEE80211_M_WDS)
1787                 sc->sc_nvaps--;
1788 #ifdef IEEE80211_SUPPORT_TDMA
1789         /* TDMA operation ceases when the last vap is destroyed */
1790         if (sc->sc_tdma && sc->sc_nvaps == 0) {
1791                 sc->sc_tdma = 0;
1792                 sc->sc_swbmiss = 0;
1793         }
1794 #endif
1795         kfree(avp, M_80211_VAP);
1796
1797         if (ifp->if_flags & IFF_RUNNING) {
1798                 /*
1799                  * Restart rx+tx machines if still running (RUNNING will
1800                  * be reset if we just destroyed the last vap).
1801                  */
1802                 if (ath_startrecv(sc) != 0)
1803                         if_printf(ifp, "%s: unable to restart recv logic\n",
1804                             __func__);
1805                 if (sc->sc_beacons) {           /* restart beacons */
1806 #ifdef IEEE80211_SUPPORT_TDMA
1807                         if (sc->sc_tdma)
1808                                 ath_tdma_config(sc, NULL);
1809                         else
1810 #endif
1811                                 ath_beacon_config(sc, NULL);
1812                 }
1813                 ath_hal_intrset(ah, sc->sc_imask);
1814         }
1815
1816         /* Ok, let the hardware asleep. */
1817         ath_power_restore_power_state(sc);
1818         ATH_UNLOCK(sc);
1819 }
1820
1821 void
1822 ath_suspend(struct ath_softc *sc)
1823 {
1824         struct ifnet *ifp = sc->sc_ifp;
1825         struct ieee80211com *ic = ifp->if_l2com;
1826
1827         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1828                 __func__, ifp->if_flags);
1829
1830         sc->sc_resume_up = (ifp->if_flags & IFF_UP) != 0;
1831
1832         ieee80211_suspend_all(ic);
1833         /*
1834          * NB: don't worry about putting the chip in low power
1835          * mode; pci will power off our socket on suspend and
1836          * CardBus detaches the device.
1837          *
1838          * XXX TODO: well, that's great, except for non-cardbus
1839          * devices!
1840          */
1841
1842         /*
1843          * XXX This doesn't wait until all pending taskqueue
1844          * items and parallel transmit/receive/other threads
1845          * are running!
1846          */
1847         ath_hal_intrset(sc->sc_ah, 0);
1848         taskqueue_block(sc->sc_tq);
1849
1850         ATH_LOCK(sc);
1851         callout_stop_sync(&sc->sc_cal_ch);
1852         ATH_UNLOCK(sc);
1853
1854         /*
1855          * XXX ensure sc_invalid is 1
1856          */
1857
1858         /* Disable the PCIe PHY, complete with workarounds */
1859         ath_hal_enablepcie(sc->sc_ah, 1, 1);
1860 }
1861
1862 /*
1863  * Reset the key cache since some parts do not reset the
1864  * contents on resume.  First we clear all entries, then
1865  * re-load keys that the 802.11 layer assumes are setup
1866  * in h/w.
1867  */
1868 static void
1869 ath_reset_keycache(struct ath_softc *sc)
1870 {
1871         struct ifnet *ifp = sc->sc_ifp;
1872         struct ieee80211com *ic = ifp->if_l2com;
1873         struct ath_hal *ah = sc->sc_ah;
1874         int i;
1875
1876         ATH_LOCK(sc);
1877         ath_power_set_power_state(sc, HAL_PM_AWAKE);
1878         for (i = 0; i < sc->sc_keymax; i++)
1879                 ath_hal_keyreset(ah, i);
1880         ath_power_restore_power_state(sc);
1881         ATH_UNLOCK(sc);
1882         ieee80211_crypto_reload_keys(ic);
1883 }
1884
1885 /*
1886  * Fetch the current chainmask configuration based on the current
1887  * operating channel and options.
1888  */
1889 static void
1890 ath_update_chainmasks(struct ath_softc *sc, struct ieee80211_channel *chan)
1891 {
1892
1893         /*
1894          * Set TX chainmask to the currently configured chainmask;
1895          * the TX chainmask depends upon the current operating mode.
1896          */
1897         sc->sc_cur_rxchainmask = sc->sc_rxchainmask;
1898         if (IEEE80211_IS_CHAN_HT(chan)) {
1899                 sc->sc_cur_txchainmask = sc->sc_txchainmask;
1900         } else {
1901                 sc->sc_cur_txchainmask = 1;
1902         }
1903
1904         DPRINTF(sc, ATH_DEBUG_RESET,
1905             "%s: TX chainmask is now 0x%x, RX is now 0x%x\n",
1906             __func__,
1907             sc->sc_cur_txchainmask,
1908             sc->sc_cur_rxchainmask);
1909 }
1910
1911 void
1912 ath_resume(struct ath_softc *sc)
1913 {
1914         struct ifnet *ifp = sc->sc_ifp;
1915         struct ieee80211com *ic = ifp->if_l2com;
1916         struct ath_hal *ah = sc->sc_ah;
1917         HAL_STATUS status;
1918
1919         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1920                 __func__, ifp->if_flags);
1921
1922         /* Re-enable PCIe, re-enable the PCIe bus */
1923         ath_hal_enablepcie(ah, 0, 0);
1924
1925         /*
1926          * Must reset the chip before we reload the
1927          * keycache as we were powered down on suspend.
1928          */
1929         ath_update_chainmasks(sc,
1930             sc->sc_curchan != NULL ? sc->sc_curchan : ic->ic_curchan);
1931         ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
1932             sc->sc_cur_rxchainmask);
1933
1934         /* Ensure we set the current power state to on */
1935         ATH_LOCK(sc);
1936         ath_power_setselfgen(sc, HAL_PM_AWAKE);
1937         ath_power_set_power_state(sc, HAL_PM_AWAKE);
1938         ath_power_setpower(sc, HAL_PM_AWAKE);
1939         ATH_UNLOCK(sc);
1940
1941         ath_hal_reset(ah, sc->sc_opmode,
1942             sc->sc_curchan != NULL ? sc->sc_curchan : ic->ic_curchan,
1943             AH_FALSE, &status);
1944         ath_reset_keycache(sc);
1945
1946         ATH_RX_LOCK(sc);
1947         sc->sc_rx_stopped = 1;
1948         sc->sc_rx_resetted = 1;
1949         ATH_RX_UNLOCK(sc);
1950
1951         /* Let DFS at it in case it's a DFS channel */
1952         ath_dfs_radar_enable(sc, ic->ic_curchan);
1953
1954         /* Let spectral at in case spectral is enabled */
1955         ath_spectral_enable(sc, ic->ic_curchan);
1956
1957         /*
1958          * Let bluetooth coexistence at in case it's needed for this channel
1959          */
1960         ath_btcoex_enable(sc, ic->ic_curchan);
1961
1962         /*
1963          * If we're doing TDMA, enforce the TXOP limitation for chips that
1964          * support it.
1965          */
1966         if (sc->sc_hasenforcetxop && sc->sc_tdma)
1967                 ath_hal_setenforcetxop(sc->sc_ah, 1);
1968         else
1969                 ath_hal_setenforcetxop(sc->sc_ah, 0);
1970
1971         /* Restore the LED configuration */
1972         ath_led_config(sc);
1973         ath_hal_setledstate(ah, HAL_LED_INIT);
1974
1975         if (sc->sc_resume_up)
1976                 ieee80211_resume_all(ic);
1977
1978         ATH_LOCK(sc);
1979         ath_power_restore_power_state(sc);
1980         ATH_UNLOCK(sc);
1981
1982         /* XXX beacons ? */
1983 }
1984
1985 void
1986 ath_shutdown(struct ath_softc *sc)
1987 {
1988         struct ifnet *ifp = sc->sc_ifp;
1989
1990         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags %x\n",
1991                 __func__, ifp->if_flags);
1992
1993         ath_stop(ifp);
1994         /* NB: no point powering down chip as we're about to reboot */
1995 }
1996
1997 /*
1998  * Interrupt handler.  Most of the actual processing is deferred.
1999  */
2000 void
2001 ath_intr(void *arg)
2002 {
2003         struct ath_softc *sc = arg;
2004         struct ifnet *ifp = sc->sc_ifp;
2005         struct ath_hal *ah = sc->sc_ah;
2006         HAL_INT status = 0;
2007         uint32_t txqs;
2008
2009         /*
2010          * If we're inside a reset path, just print a warning and
2011          * clear the ISR. The reset routine will finish it for us.
2012          */
2013         ATH_PCU_LOCK(sc);
2014         if (sc->sc_inreset_cnt) {
2015                 HAL_INT status;
2016                 ath_hal_getisr(ah, &status);    /* clear ISR */
2017                 ath_hal_intrset(ah, 0);         /* disable further intr's */
2018                 DPRINTF(sc, ATH_DEBUG_ANY,
2019                     "%s: in reset, ignoring: status=0x%x\n",
2020                     __func__, status);
2021                 ATH_PCU_UNLOCK(sc);
2022                 return;
2023         }
2024
2025         if (sc->sc_invalid) {
2026                 /*
2027                  * The hardware is not ready/present, don't touch anything.
2028                  * Note this can happen early on if the IRQ is shared.
2029                  */
2030                 DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid; ignored\n", __func__);
2031                 ATH_PCU_UNLOCK(sc);
2032                 return;
2033         }
2034         if (!ath_hal_intrpend(ah)) {            /* shared irq, not for us */
2035                 ATH_PCU_UNLOCK(sc);
2036                 return;
2037         }
2038
2039         ATH_LOCK(sc);
2040         ath_power_set_power_state(sc, HAL_PM_AWAKE);
2041         ATH_UNLOCK(sc);
2042
2043         if ((ifp->if_flags & IFF_UP) == 0 ||
2044             (ifp->if_flags & IFF_RUNNING) == 0) {
2045                 HAL_INT status;
2046
2047                 DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
2048                         __func__, ifp->if_flags);
2049                 ath_hal_getisr(ah, &status);    /* clear ISR */
2050                 ath_hal_intrset(ah, 0);         /* disable further intr's */
2051                 ATH_PCU_UNLOCK(sc);
2052
2053                 ATH_LOCK(sc);
2054                 ath_power_restore_power_state(sc);
2055                 ATH_UNLOCK(sc);
2056                 return;
2057         }
2058
2059         /*
2060          * Figure out the reason(s) for the interrupt.  Note
2061          * that the hal returns a pseudo-ISR that may include
2062          * bits we haven't explicitly enabled so we mask the
2063          * value to insure we only process bits we requested.
2064          */
2065         ath_hal_getisr(ah, &status);            /* NB: clears ISR too */
2066         DPRINTF(sc, ATH_DEBUG_INTR, "%s: status 0x%x\n", __func__, status);
2067         ATH_KTR(sc, ATH_KTR_INTERRUPTS, 1, "ath_intr: mask=0x%.8x", status);
2068 #ifdef  ATH_DEBUG_ALQ
2069         if_ath_alq_post_intr(&sc->sc_alq, status, ah->ah_intrstate,
2070             ah->ah_syncstate);
2071 #endif  /* ATH_DEBUG_ALQ */
2072 #ifdef  ATH_KTR_INTR_DEBUG
2073         ATH_KTR(sc, ATH_KTR_INTERRUPTS, 5,
2074             "ath_intr: ISR=0x%.8x, ISR_S0=0x%.8x, ISR_S1=0x%.8x, ISR_S2=0x%.8x, ISR_S5=0x%.8x",
2075             ah->ah_intrstate[0],
2076             ah->ah_intrstate[1],
2077             ah->ah_intrstate[2],
2078             ah->ah_intrstate[3],
2079             ah->ah_intrstate[6]);
2080 #endif
2081
2082         /* Squirrel away SYNC interrupt debugging */
2083         if (ah->ah_syncstate != 0) {
2084                 int i;
2085                 for (i = 0; i < 32; i++)
2086                         if (ah->ah_syncstate & (i << i))
2087                                 sc->sc_intr_stats.sync_intr[i]++;
2088         }
2089
2090         status &= sc->sc_imask;                 /* discard unasked for bits */
2091
2092         /* Short-circuit un-handled interrupts */
2093         if (status == 0x0) {
2094                 ATH_PCU_UNLOCK(sc);
2095
2096                 ATH_LOCK(sc);
2097                 ath_power_restore_power_state(sc);
2098                 ATH_UNLOCK(sc);
2099
2100                 return;
2101         }
2102
2103         /*
2104          * Take a note that we're inside the interrupt handler, so
2105          * the reset routines know to wait.
2106          */
2107         sc->sc_intr_cnt++;
2108         ATH_PCU_UNLOCK(sc);
2109
2110         /*
2111          * Handle the interrupt. We won't run concurrent with the reset
2112          * or channel change routines as they'll wait for sc_intr_cnt
2113          * to be 0 before continuing.
2114          */
2115         if (status & HAL_INT_FATAL) {
2116                 sc->sc_stats.ast_hardware++;
2117                 ath_hal_intrset(ah, 0);         /* disable intr's until reset */
2118                 taskqueue_enqueue(sc->sc_tq, &sc->sc_fataltask);
2119         } else {
2120                 if (status & HAL_INT_SWBA) {
2121                         /*
2122                          * Software beacon alert--time to send a beacon.
2123                          * Handle beacon transmission directly; deferring
2124                          * this is too slow to meet timing constraints
2125                          * under load.
2126                          */
2127 #ifdef IEEE80211_SUPPORT_TDMA
2128                         if (sc->sc_tdma) {
2129                                 if (sc->sc_tdmaswba == 0) {
2130                                         struct ieee80211com *ic = ifp->if_l2com;
2131                                         struct ieee80211vap *vap =
2132                                             TAILQ_FIRST(&ic->ic_vaps);
2133                                         ath_tdma_beacon_send(sc, vap);
2134                                         sc->sc_tdmaswba =
2135                                             vap->iv_tdma->tdma_bintval;
2136                                 } else
2137                                         sc->sc_tdmaswba--;
2138                         } else
2139 #endif
2140                         {
2141                                 ath_beacon_proc(sc, 0);
2142 #ifdef IEEE80211_SUPPORT_SUPERG
2143                                 /*
2144                                  * Schedule the rx taskq in case there's no
2145                                  * traffic so any frames held on the staging
2146                                  * queue are aged and potentially flushed.
2147                                  */
2148                                 sc->sc_rx.recv_sched(sc, 1);
2149 #endif
2150                         }
2151                 }
2152                 if (status & HAL_INT_RXEOL) {
2153                         int imask;
2154                         ATH_KTR(sc, ATH_KTR_ERROR, 0, "ath_intr: RXEOL");
2155                         if (! sc->sc_isedma) {
2156                                 ATH_PCU_LOCK(sc);
2157                                 /*
2158                                  * NB: the hardware should re-read the link when
2159                                  *     RXE bit is written, but it doesn't work at
2160                                  *     least on older hardware revs.
2161                                  */
2162                                 sc->sc_stats.ast_rxeol++;
2163                                 /*
2164                                  * Disable RXEOL/RXORN - prevent an interrupt
2165                                  * storm until the PCU logic can be reset.
2166                                  * In case the interface is reset some other
2167                                  * way before "sc_kickpcu" is called, don't
2168                                  * modify sc_imask - that way if it is reset
2169                                  * by a call to ath_reset() somehow, the
2170                                  * interrupt mask will be correctly reprogrammed.
2171                                  */
2172                                 imask = sc->sc_imask;
2173                                 imask &= ~(HAL_INT_RXEOL | HAL_INT_RXORN);
2174                                 ath_hal_intrset(ah, imask);
2175                                 /*
2176                                  * Only blank sc_rxlink if we've not yet kicked
2177                                  * the PCU.
2178                                  *
2179                                  * This isn't entirely correct - the correct solution
2180                                  * would be to have a PCU lock and engage that for
2181                                  * the duration of the PCU fiddling; which would include
2182                                  * running the RX process. Otherwise we could end up
2183                                  * messing up the RX descriptor chain and making the
2184                                  * RX desc list much shorter.
2185                                  */
2186                                 if (! sc->sc_kickpcu)
2187                                         sc->sc_rxlink = NULL;
2188                                 sc->sc_kickpcu = 1;
2189                                 ATH_PCU_UNLOCK(sc);
2190                         }
2191                         /*
2192                          * Enqueue an RX proc to handle whatever
2193                          * is in the RX queue.
2194                          * This will then kick the PCU if required.
2195                          */
2196                         sc->sc_rx.recv_sched(sc, 1);
2197                 }
2198                 if (status & HAL_INT_TXURN) {
2199                         sc->sc_stats.ast_txurn++;
2200                         /* bump tx trigger level */
2201                         ath_hal_updatetxtriglevel(ah, AH_TRUE);
2202                 }
2203                 /*
2204                  * Handle both the legacy and RX EDMA interrupt bits.
2205                  * Note that HAL_INT_RXLP is also HAL_INT_RXDESC.
2206                  */
2207                 if (status & (HAL_INT_RX | HAL_INT_RXHP | HAL_INT_RXLP)) {
2208                         sc->sc_stats.ast_rx_intr++;
2209                         sc->sc_rx.recv_sched(sc, 1);
2210                 }
2211                 if (status & HAL_INT_TX) {
2212                         sc->sc_stats.ast_tx_intr++;
2213                         /*
2214                          * Grab all the currently set bits in the HAL txq bitmap
2215                          * and blank them. This is the only place we should be
2216                          * doing this.
2217                          */
2218                         if (! sc->sc_isedma) {
2219                                 ATH_PCU_LOCK(sc);
2220                                 txqs = 0xffffffff;
2221                                 ath_hal_gettxintrtxqs(sc->sc_ah, &txqs);
2222                                 ATH_KTR(sc, ATH_KTR_INTERRUPTS, 3,
2223                                     "ath_intr: TX; txqs=0x%08x, txq_active was 0x%08x, now 0x%08x",
2224                                     txqs,
2225                                     sc->sc_txq_active,
2226                                     sc->sc_txq_active | txqs);
2227                                 sc->sc_txq_active |= txqs;
2228                                 ATH_PCU_UNLOCK(sc);
2229                         }
2230                         taskqueue_enqueue(sc->sc_tq, &sc->sc_txtask);
2231                 }
2232                 if (status & HAL_INT_BMISS) {
2233                         sc->sc_stats.ast_bmiss++;
2234                         taskqueue_enqueue(sc->sc_tq, &sc->sc_bmisstask);
2235                 }
2236                 if (status & HAL_INT_GTT)
2237                         sc->sc_stats.ast_tx_timeout++;
2238                 if (status & HAL_INT_CST)
2239                         sc->sc_stats.ast_tx_cst++;
2240                 if (status & HAL_INT_MIB) {
2241                         sc->sc_stats.ast_mib++;
2242                         ATH_PCU_LOCK(sc);
2243                         /*
2244                          * Disable interrupts until we service the MIB
2245                          * interrupt; otherwise it will continue to fire.
2246                          */
2247                         ath_hal_intrset(ah, 0);
2248                         /*
2249                          * Let the hal handle the event.  We assume it will
2250                          * clear whatever condition caused the interrupt.
2251                          */
2252                         ath_hal_mibevent(ah, &sc->sc_halstats);
2253                         /*
2254                          * Don't reset the interrupt if we've just
2255                          * kicked the PCU, or we may get a nested
2256                          * RXEOL before the rxproc has had a chance
2257                          * to run.
2258                          */
2259                         if (sc->sc_kickpcu == 0)
2260                                 ath_hal_intrset(ah, sc->sc_imask);
2261                         ATH_PCU_UNLOCK(sc);
2262                 }
2263                 if (status & HAL_INT_RXORN) {
2264                         /* NB: hal marks HAL_INT_FATAL when RXORN is fatal */
2265                         ATH_KTR(sc, ATH_KTR_ERROR, 0, "ath_intr: RXORN");
2266                         sc->sc_stats.ast_rxorn++;
2267                 }
2268                 if (status & HAL_INT_TSFOOR) {
2269                         device_printf(sc->sc_dev, "%s: TSFOOR\n", __func__);
2270                         sc->sc_syncbeacon = 1;
2271                 }
2272         }
2273         ATH_PCU_LOCK(sc);
2274         sc->sc_intr_cnt--;
2275         ATH_PCU_UNLOCK(sc);
2276
2277         ATH_LOCK(sc);
2278         ath_power_restore_power_state(sc);
2279         ATH_UNLOCK(sc);
2280 }
2281
2282 static void
2283 ath_fatal_proc(void *arg, int pending)
2284 {
2285         struct ath_softc *sc = arg;
2286         struct ifnet *ifp = sc->sc_ifp;
2287         u_int32_t *state;
2288         u_int32_t len;
2289         void *sp;
2290
2291         if_printf(ifp, "hardware error; resetting\n");
2292         /*
2293          * Fatal errors are unrecoverable.  Typically these
2294          * are caused by DMA errors.  Collect h/w state from
2295          * the hal so we can diagnose what's going on.
2296          */
2297         wlan_serialize_enter();
2298         if (ath_hal_getfatalstate(sc->sc_ah, &sp, &len)) {
2299                 KASSERT(len >= 6*sizeof(u_int32_t), ("len %u bytes", len));
2300                 state = sp;
2301                 if_printf(ifp, "0x%08x 0x%08x 0x%08x, 0x%08x 0x%08x 0x%08x\n",
2302                     state[0], state[1] , state[2], state[3],
2303                     state[4], state[5]);
2304         }
2305         ath_reset(ifp, ATH_RESET_NOLOSS);
2306         wlan_serialize_exit();
2307 }
2308
2309 static void
2310 ath_bmiss_vap(struct ieee80211vap *vap)
2311 {
2312         struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
2313
2314         /*
2315          * Workaround phantom bmiss interrupts by sanity-checking
2316          * the time of our last rx'd frame.  If it is within the
2317          * beacon miss interval then ignore the interrupt.  If it's
2318          * truly a bmiss we'll get another interrupt soon and that'll
2319          * be dispatched up for processing.  Note this applies only
2320          * for h/w beacon miss events.
2321          */
2322
2323         /*
2324          * XXX TODO: Just read the TSF during the interrupt path;
2325          * that way we don't have to wake up again just to read it
2326          * again.
2327          */
2328         ATH_LOCK(sc);
2329         ath_power_set_power_state(sc, HAL_PM_AWAKE);
2330         ATH_UNLOCK(sc);
2331
2332         if ((vap->iv_flags_ext & IEEE80211_FEXT_SWBMISS) == 0) {
2333                 struct ifnet *ifp = vap->iv_ic->ic_ifp;
2334                 struct ath_softc *sc = ifp->if_softc;
2335                 u_int64_t lastrx = sc->sc_lastrx;
2336                 u_int64_t tsf = ath_hal_gettsf64(sc->sc_ah);
2337                 /* XXX should take a locked ref to iv_bss */
2338                 u_int bmisstimeout =
2339                         vap->iv_bmissthreshold * vap->iv_bss->ni_intval * 1024;
2340
2341                 DPRINTF(sc, ATH_DEBUG_BEACON,
2342                     "%s: tsf %llu lastrx %lld (%llu) bmiss %u\n",
2343                     __func__, (unsigned long long) tsf,
2344                     (unsigned long long)(tsf - lastrx),
2345                     (unsigned long long) lastrx, bmisstimeout);
2346
2347                 if (tsf - lastrx <= bmisstimeout) {
2348                         sc->sc_stats.ast_bmiss_phantom++;
2349
2350                         ATH_LOCK(sc);
2351                         ath_power_restore_power_state(sc);
2352                         ATH_UNLOCK(sc);
2353
2354                         return;
2355                 }
2356         }
2357
2358         /*
2359          * There's no need to keep the hardware awake during the call
2360          * to av_bmiss().
2361          */
2362         ATH_LOCK(sc);
2363         ath_power_restore_power_state(sc);
2364         ATH_UNLOCK(sc);
2365
2366         /*
2367          * Attempt to force a beacon resync.
2368          */
2369         sc->sc_syncbeacon = 1;
2370
2371         ATH_VAP(vap)->av_bmiss(vap);
2372 }
2373
2374 /* XXX this needs a force wakeup! */
2375 int
2376 ath_hal_gethangstate(struct ath_hal *ah, uint32_t mask, uint32_t *hangs)
2377 {
2378         uint32_t rsize;
2379         void *sp;
2380
2381         if (!ath_hal_getdiagstate(ah, HAL_DIAG_CHECK_HANGS, &mask, sizeof(mask), &sp, &rsize))
2382                 return 0;
2383         KASSERT(rsize == sizeof(uint32_t), ("resultsize %u", rsize));
2384         *hangs = *(uint32_t *)sp;
2385         return 1;
2386 }
2387
2388 static void
2389 ath_bmiss_proc(void *arg, int pending)
2390 {
2391         struct ath_softc *sc = arg;
2392         struct ifnet *ifp = sc->sc_ifp;
2393         uint32_t hangs;
2394
2395         DPRINTF(sc, ATH_DEBUG_ANY, "%s: pending %u\n", __func__, pending);
2396
2397         ATH_LOCK(sc);
2398         ath_power_set_power_state(sc, HAL_PM_AWAKE);
2399         ATH_UNLOCK(sc);
2400
2401         ath_beacon_miss(sc);
2402
2403         /*
2404          * Do a reset upon any becaon miss event.
2405          *
2406          * It may be a non-recognised RX clear hang which needs a reset
2407          * to clear.
2408          */
2409         if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0) {
2410                 ath_reset(ifp, ATH_RESET_NOLOSS);
2411                 if_printf(ifp, "bb hang detected (0x%x), resetting\n", hangs);
2412         } else {
2413                 ath_reset(ifp, ATH_RESET_NOLOSS);
2414                 ieee80211_beacon_miss(ifp->if_l2com);
2415         }
2416
2417         /* Force a beacon resync, in case they've drifted */
2418         sc->sc_syncbeacon = 1;
2419
2420         ATH_LOCK(sc);
2421         ath_power_restore_power_state(sc);
2422         ATH_UNLOCK(sc);
2423 }
2424
2425 /*
2426  * Handle TKIP MIC setup to deal hardware that doesn't do MIC
2427  * calcs together with WME.  If necessary disable the crypto
2428  * hardware and mark the 802.11 state so keys will be setup
2429  * with the MIC work done in software.
2430  */
2431 static void
2432 ath_settkipmic(struct ath_softc *sc)
2433 {
2434         struct ifnet *ifp = sc->sc_ifp;
2435         struct ieee80211com *ic = ifp->if_l2com;
2436
2437         if ((ic->ic_cryptocaps & IEEE80211_CRYPTO_TKIP) && !sc->sc_wmetkipmic) {
2438                 if (ic->ic_flags & IEEE80211_F_WME) {
2439                         ath_hal_settkipmic(sc->sc_ah, AH_FALSE);
2440                         ic->ic_cryptocaps &= ~IEEE80211_CRYPTO_TKIPMIC;
2441                 } else {
2442                         ath_hal_settkipmic(sc->sc_ah, AH_TRUE);
2443                         ic->ic_cryptocaps |= IEEE80211_CRYPTO_TKIPMIC;
2444                 }
2445         }
2446 }
2447
2448 static void
2449 ath_init(void *arg)
2450 {
2451         struct ath_softc *sc = (struct ath_softc *) arg;
2452         struct ifnet *ifp = sc->sc_ifp;
2453         struct ieee80211com *ic = ifp->if_l2com;
2454         struct ath_hal *ah = sc->sc_ah;
2455         HAL_STATUS status;
2456
2457         DPRINTF(sc, ATH_DEBUG_ANY, "%s: if_flags 0x%x\n",
2458                 __func__, ifp->if_flags);
2459
2460         ATH_LOCK(sc);
2461         /*
2462          * Force the sleep state awake.
2463          */
2464         ath_power_setselfgen(sc, HAL_PM_AWAKE);
2465         ath_power_set_power_state(sc, HAL_PM_AWAKE);
2466         ath_power_setpower(sc, HAL_PM_AWAKE);
2467
2468         /*
2469          * Stop anything previously setup.  This is safe
2470          * whether this is the first time through or not.
2471          */
2472         ath_stop_locked(ifp);
2473
2474         /*
2475          * The basic interface to setting the hardware in a good
2476          * state is ``reset''.  On return the hardware is known to
2477          * be powered up and with interrupts disabled.  This must
2478          * be followed by initialization of the appropriate bits
2479          * and then setup of the interrupt mask.
2480          */
2481         ath_settkipmic(sc);
2482         ath_update_chainmasks(sc, ic->ic_curchan);
2483         ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
2484             sc->sc_cur_rxchainmask);
2485
2486         if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_FALSE, &status)) {
2487                 if_printf(ifp, "unable to reset hardware; hal status %u\n",
2488                         status);
2489                 ATH_UNLOCK(sc);
2490                 return;
2491         }
2492
2493         ATH_RX_LOCK(sc);
2494         sc->sc_rx_stopped = 1;
2495         sc->sc_rx_resetted = 1;
2496         ATH_RX_UNLOCK(sc);
2497
2498         ath_chan_change(sc, ic->ic_curchan);
2499
2500         /* Let DFS at it in case it's a DFS channel */
2501         ath_dfs_radar_enable(sc, ic->ic_curchan);
2502
2503         /* Let spectral at in case spectral is enabled */
2504         ath_spectral_enable(sc, ic->ic_curchan);
2505
2506         /*
2507          * Let bluetooth coexistence at in case it's needed for this channel
2508          */
2509         ath_btcoex_enable(sc, ic->ic_curchan);
2510
2511         /*
2512          * If we're doing TDMA, enforce the TXOP limitation for chips that
2513          * support it.
2514          */
2515         if (sc->sc_hasenforcetxop && sc->sc_tdma)
2516                 ath_hal_setenforcetxop(sc->sc_ah, 1);
2517         else
2518                 ath_hal_setenforcetxop(sc->sc_ah, 0);
2519
2520         /*
2521          * Likewise this is set during reset so update
2522          * state cached in the driver.
2523          */
2524         sc->sc_diversity = ath_hal_getdiversity(ah);
2525         sc->sc_lastlongcal = 0;
2526         sc->sc_resetcal = 1;
2527         sc->sc_lastcalreset = 0;
2528         sc->sc_lastani = 0;
2529         sc->sc_lastshortcal = 0;
2530         sc->sc_doresetcal = AH_FALSE;
2531         /*
2532          * Beacon timers were cleared here; give ath_newstate()
2533          * a hint that the beacon timers should be poked when
2534          * things transition to the RUN state.
2535          */
2536         sc->sc_beacons = 0;
2537
2538         /*
2539          * Setup the hardware after reset: the key cache
2540          * is filled as needed and the receive engine is
2541          * set going.  Frame transmit is handled entirely
2542          * in the frame output path; there's nothing to do
2543          * here except setup the interrupt mask.
2544          */
2545         if (ath_startrecv(sc) != 0) {
2546                 if_printf(ifp, "unable to start recv logic\n");
2547                 ath_power_restore_power_state(sc);
2548                 ATH_UNLOCK(sc);
2549                 return;
2550         }
2551
2552         /*
2553          * Enable interrupts.
2554          */
2555         sc->sc_imask = HAL_INT_RX | HAL_INT_TX
2556                   | HAL_INT_RXORN | HAL_INT_TXURN
2557                   | HAL_INT_FATAL | HAL_INT_GLOBAL;
2558
2559         /*
2560          * Enable RX EDMA bits.  Note these overlap with
2561          * HAL_INT_RX and HAL_INT_RXDESC respectively.
2562          */
2563         if (sc->sc_isedma)
2564                 sc->sc_imask |= (HAL_INT_RXHP | HAL_INT_RXLP);
2565
2566         /*
2567          * If we're an EDMA NIC, we don't care about RXEOL.
2568          * Writing a new descriptor in will simply restart
2569          * RX DMA.
2570          */
2571         if (! sc->sc_isedma)
2572                 sc->sc_imask |= HAL_INT_RXEOL;
2573
2574         /*
2575          * Enable MIB interrupts when there are hardware phy counters.
2576          * Note we only do this (at the moment) for station mode.
2577          */
2578         if (sc->sc_needmib && ic->ic_opmode == IEEE80211_M_STA)
2579                 sc->sc_imask |= HAL_INT_MIB;
2580
2581         /*
2582          * XXX add capability for this.
2583          *
2584          * If we're in STA mode (and maybe IBSS?) then register for
2585          * TSFOOR interrupts.
2586          */
2587         if (ic->ic_opmode == IEEE80211_M_STA)
2588                 sc->sc_imask |= HAL_INT_TSFOOR;
2589
2590         /* Enable global TX timeout and carrier sense timeout if available */
2591         if (ath_hal_gtxto_supported(ah))
2592                 sc->sc_imask |= HAL_INT_GTT;
2593
2594         DPRINTF(sc, ATH_DEBUG_RESET, "%s: imask=0x%x\n",
2595                 __func__, sc->sc_imask);
2596
2597         ifp->if_flags |= IFF_RUNNING;
2598         callout_reset(&sc->sc_wd_ch, hz, ath_watchdog, sc);
2599         ath_hal_intrset(ah, sc->sc_imask);
2600
2601         ath_power_restore_power_state(sc);
2602         ATH_UNLOCK(sc);
2603
2604 #ifdef ATH_TX99_DIAG
2605         if (sc->sc_tx99 != NULL)
2606                 sc->sc_tx99->start(sc->sc_tx99);
2607         else
2608 #endif
2609         ieee80211_start_all(ic);                /* start all vap's */
2610 }
2611
2612 static void
2613 ath_stop_locked(struct ifnet *ifp)
2614 {
2615         struct ath_softc *sc = ifp->if_softc;
2616         struct ath_hal *ah = sc->sc_ah;
2617
2618         DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid %u if_flags 0x%x\n",
2619                 __func__, sc->sc_invalid, ifp->if_flags);
2620
2621         ATH_LOCK_ASSERT(sc);
2622
2623         /*
2624          * Wake the hardware up before fiddling with it.
2625          */
2626         ath_power_set_power_state(sc, HAL_PM_AWAKE);
2627
2628         if (ifp->if_flags & IFF_RUNNING) {
2629                 /*
2630                  * Shutdown the hardware and driver:
2631                  *    reset 802.11 state machine
2632                  *    turn off timers
2633                  *    disable interrupts
2634                  *    turn off the radio
2635                  *    clear transmit machinery
2636                  *    clear receive machinery
2637                  *    drain and release tx queues
2638                  *    reclaim beacon resources
2639                  *    power down hardware
2640                  *
2641                  * Note that some of this work is not possible if the
2642                  * hardware is gone (invalid).
2643                  */
2644 #ifdef ATH_TX99_DIAG
2645                 if (sc->sc_tx99 != NULL)
2646                         sc->sc_tx99->stop(sc->sc_tx99);
2647 #endif
2648                 callout_stop_sync(&sc->sc_wd_ch);
2649                 sc->sc_wd_timer = 0;
2650                 ifp->if_flags &= ~IFF_RUNNING;
2651                 if (!sc->sc_invalid) {
2652                         if (sc->sc_softled) {
2653                                 callout_stop_sync(&sc->sc_ledtimer);
2654                                 ath_hal_gpioset(ah, sc->sc_ledpin,
2655                                         !sc->sc_ledon);
2656                                 sc->sc_blinking = 0;
2657                         }
2658                         ath_hal_intrset(ah, 0);
2659                 }
2660                 /* XXX we should stop RX regardless of whether it's valid */
2661                 if (!sc->sc_invalid) {
2662                         ath_stoprecv(sc, 1);
2663                         ath_hal_phydisable(ah);
2664                 } else
2665                         sc->sc_rxlink = NULL;
2666                 ath_draintxq(sc, ATH_RESET_DEFAULT);
2667                 ath_beacon_free(sc);    /* XXX not needed */
2668         }
2669
2670         /* And now, restore the current power state */
2671         ath_power_restore_power_state(sc);
2672 }
2673
2674 /*
2675  * Wait until all pending TX/RX has completed.
2676  *
2677  * This waits until all existing transmit, receive and interrupts
2678  * have completed.  It's assumed that the caller has first
2679  * grabbed the reset lock so it doesn't try to do overlapping
2680  * chip resets.
2681  */
2682 #define MAX_TXRX_ITERATIONS     100
2683 static void
2684 ath_txrx_stop_locked(struct ath_softc *sc)
2685 {
2686         int i = MAX_TXRX_ITERATIONS;
2687
2688         ATH_UNLOCK_ASSERT(sc);
2689         ATH_PCU_LOCK_ASSERT(sc);
2690
2691         /*
2692          * Sleep until all the pending operations have completed.
2693          *
2694          * The caller must ensure that reset has been incremented
2695          * or the pending operations may continue being queued.
2696          */
2697         while (sc->sc_rxproc_cnt || sc->sc_txproc_cnt ||
2698             sc->sc_txstart_cnt || sc->sc_intr_cnt) {
2699                 if (i <= 0)
2700                         break;
2701                 if (wlan_is_serialized()) {
2702                         wlan_serialize_exit();
2703                         lksleep(sc, &sc->sc_pcu_mtx, 0, "ath_txrx_stop",
2704                                 msecs_to_ticks(10));
2705                         wlan_serialize_enter();
2706                 } else {
2707                         lksleep(sc, &sc->sc_pcu_mtx, 0, "ath_txrx_stop",
2708                                 msecs_to_ticks(10));
2709                 }
2710                 i--;
2711         }
2712
2713         if (i <= 0)
2714                 device_printf(sc->sc_dev,
2715                     "%s: didn't finish after %d iterations\n",
2716                     __func__, MAX_TXRX_ITERATIONS);
2717 }
2718 #undef  MAX_TXRX_ITERATIONS
2719
2720 #if 0
2721 static void
2722 ath_txrx_stop(struct ath_softc *sc)
2723 {
2724         ATH_UNLOCK_ASSERT(sc);
2725         ATH_PCU_UNLOCK_ASSERT(sc);
2726
2727         ATH_PCU_LOCK(sc);
2728         ath_txrx_stop_locked(sc);
2729         ATH_PCU_UNLOCK(sc);
2730 }
2731 #endif
2732
2733 static void
2734 ath_txrx_start(struct ath_softc *sc)
2735 {
2736
2737         taskqueue_unblock(sc->sc_tq);
2738 }
2739
2740 /*
2741  * Grab the reset lock, and wait around until noone else
2742  * is trying to do anything with it.
2743  *
2744  * This is totally horrible but we can't hold this lock for
2745  * long enough to do TX/RX or we end up with net80211/ip stack
2746  * LORs and eventual deadlock.
2747  *
2748  * "dowait" signals whether to spin, waiting for the reset
2749  * lock count to reach 0. This should (for now) only be used
2750  * during the reset path, as the rest of the code may not
2751  * be locking-reentrant enough to behave correctly.
2752  *
2753  * Another, cleaner way should be found to serialise all of
2754  * these operations.
2755  */
2756 #define MAX_RESET_ITERATIONS    25
2757 static int
2758 ath_reset_grablock(struct ath_softc *sc, int dowait)
2759 {
2760         int w = 0;
2761         int i = MAX_RESET_ITERATIONS;
2762
2763         ATH_PCU_LOCK_ASSERT(sc);
2764         do {
2765                 if (sc->sc_inreset_cnt == 0) {
2766                         w = 1;
2767                         break;
2768                 }
2769                 if (dowait == 0) {
2770                         w = 0;
2771                         break;
2772                 }
2773                 ATH_PCU_UNLOCK(sc);
2774
2775                 /*
2776                  * 1 tick is likely not enough time for long calibrations
2777                  * to complete.  So we should wait quite a while.
2778                  */
2779 #if defined(__DragonFly__)
2780                 tsleep(&sc->sc_inreset_cnt, 0,
2781                        "ath_reset_grablock", (hz + 99) / 100);
2782 #else
2783                 pause("ath_reset_grablock", msecs_to_ticks(100));
2784 #endif
2785                 i--;
2786                 ATH_PCU_LOCK(sc);
2787         } while (i > 0);
2788
2789         /*
2790          * We always increment the refcounter, regardless
2791          * of whether we succeeded to get it in an exclusive
2792          * way.
2793          */
2794         sc->sc_inreset_cnt++;
2795
2796         if (i <= 0)
2797                 device_printf(sc->sc_dev,
2798                     "%s: didn't finish after %d iterations\n",
2799                     __func__, MAX_RESET_ITERATIONS);
2800
2801         if (w == 0)
2802                 device_printf(sc->sc_dev,
2803                     "%s: warning, recursive reset path!\n",
2804                     __func__);
2805
2806         return w;
2807 }
2808 #undef MAX_RESET_ITERATIONS
2809
2810 /*
2811  * XXX TODO: write ath_reset_releaselock
2812  */
2813
2814 static void
2815 ath_stop(struct ifnet *ifp)
2816 {
2817         struct ath_softc *sc = ifp->if_softc;
2818
2819         ATH_LOCK(sc);
2820         ath_stop_locked(ifp);
2821         ATH_UNLOCK(sc);
2822 }
2823
2824 /*
2825  * Reset the hardware w/o losing operational state.  This is
2826  * basically a more efficient way of doing ath_stop, ath_init,
2827  * followed by state transitions to the current 802.11
2828  * operational state.  Used to recover from various errors and
2829  * to reset or reload hardware state.
2830  */
2831 int
2832 ath_reset(struct ifnet *ifp, ATH_RESET_TYPE reset_type)
2833 {
2834         struct ath_softc *sc = ifp->if_softc;
2835         struct ieee80211com *ic = ifp->if_l2com;
2836         struct ath_hal *ah = sc->sc_ah;
2837         HAL_STATUS status;
2838         int i;
2839
2840         DPRINTF(sc, ATH_DEBUG_RESET, "%s: called\n", __func__);
2841
2842         /* Ensure ATH_LOCK isn't held; ath_rx_proc can't be locked */
2843         ATH_PCU_UNLOCK_ASSERT(sc);
2844         ATH_UNLOCK_ASSERT(sc);
2845
2846         /* Try to (stop any further TX/RX from occuring */
2847         taskqueue_block(sc->sc_tq);
2848
2849         /*
2850          * Wake the hardware up.
2851          */
2852         ATH_LOCK(sc);
2853         ath_power_set_power_state(sc, HAL_PM_AWAKE);
2854         ATH_UNLOCK(sc);
2855
2856         ATH_PCU_LOCK(sc);
2857
2858         /*
2859          * Grab the reset lock before TX/RX is stopped.
2860          *
2861          * This is needed to ensure that when the TX/RX actually does finish,
2862          * no further TX/RX/reset runs in parallel with this.
2863          */
2864         if (ath_reset_grablock(sc, 1) == 0) {
2865                 device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
2866                     __func__);
2867         }
2868
2869         /* disable interrupts */
2870         ath_hal_intrset(ah, 0);
2871
2872         /*
2873          * Now, ensure that any in progress TX/RX completes before we
2874          * continue.
2875          */
2876         ath_txrx_stop_locked(sc);
2877
2878         ATH_PCU_UNLOCK(sc);
2879
2880         /*
2881          * Regardless of whether we're doing a no-loss flush or
2882          * not, stop the PCU and handle what's in the RX queue.
2883          * That way frames aren't dropped which shouldn't be.
2884          */
2885         ath_stoprecv(sc, (reset_type != ATH_RESET_NOLOSS));
2886         ath_rx_flush(sc);
2887
2888         /*
2889          * Should now wait for pending TX/RX to complete
2890          * and block future ones from occuring. This needs to be
2891          * done before the TX queue is drained.
2892          */
2893         ath_draintxq(sc, reset_type);   /* stop xmit side */
2894
2895         ath_settkipmic(sc);             /* configure TKIP MIC handling */
2896         /* NB: indicate channel change so we do a full reset */
2897         ath_update_chainmasks(sc, ic->ic_curchan);
2898         ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
2899             sc->sc_cur_rxchainmask);
2900         if (!ath_hal_reset(ah, sc->sc_opmode, ic->ic_curchan, AH_TRUE, &status))
2901                 if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
2902                         __func__, status);
2903         sc->sc_diversity = ath_hal_getdiversity(ah);
2904
2905         ATH_RX_LOCK(sc);
2906         sc->sc_rx_stopped = 1;
2907         sc->sc_rx_resetted = 1;
2908         ATH_RX_UNLOCK(sc);
2909
2910         /* Let DFS at it in case it's a DFS channel */
2911         ath_dfs_radar_enable(sc, ic->ic_curchan);
2912
2913         /* Let spectral at in case spectral is enabled */
2914         ath_spectral_enable(sc, ic->ic_curchan);
2915
2916         /*
2917          * Let bluetooth coexistence at in case it's needed for this channel
2918          */
2919         ath_btcoex_enable(sc, ic->ic_curchan);
2920
2921         /*
2922          * If we're doing TDMA, enforce the TXOP limitation for chips that
2923          * support it.
2924          */
2925         if (sc->sc_hasenforcetxop && sc->sc_tdma)
2926                 ath_hal_setenforcetxop(sc->sc_ah, 1);
2927         else
2928                 ath_hal_setenforcetxop(sc->sc_ah, 0);
2929
2930         if (ath_startrecv(sc) != 0)     /* restart recv */
2931                 if_printf(ifp, "%s: unable to start recv logic\n", __func__);
2932         /*
2933          * We may be doing a reset in response to an ioctl
2934          * that changes the channel so update any state that
2935          * might change as a result.
2936          */
2937         ath_chan_change(sc, ic->ic_curchan);
2938         if (sc->sc_beacons) {           /* restart beacons */
2939 #ifdef IEEE80211_SUPPORT_TDMA
2940                 if (sc->sc_tdma)
2941                         ath_tdma_config(sc, NULL);
2942                 else
2943 #endif
2944                         ath_beacon_config(sc, NULL);
2945         }
2946
2947         /*
2948          * Release the reset lock and re-enable interrupts here.
2949          * If an interrupt was being processed in ath_intr(),
2950          * it would disable interrupts at this point. So we have
2951          * to atomically enable interrupts and decrement the
2952          * reset counter - this way ath_intr() doesn't end up
2953          * disabling interrupts without a corresponding enable
2954          * in the rest or channel change path.
2955          *
2956          * Grab the TX reference in case we need to transmit.
2957          * That way a parallel transmit doesn't.
2958          */
2959         ATH_PCU_LOCK(sc);
2960         sc->sc_inreset_cnt--;
2961         sc->sc_txstart_cnt++;
2962         /* XXX only do this if sc_inreset_cnt == 0? */
2963         ath_hal_intrset(ah, sc->sc_imask);
2964         ATH_PCU_UNLOCK(sc);
2965
2966         /*
2967          * TX and RX can be started here. If it were started with
2968          * sc_inreset_cnt > 0, the TX and RX path would abort.
2969          * Thus if this is a nested call through the reset or
2970          * channel change code, TX completion will occur but
2971          * RX completion and ath_start / ath_tx_start will not
2972          * run.
2973          */
2974
2975         /* Restart TX/RX as needed */
2976         ath_txrx_start(sc);
2977
2978         /* XXX TODO: we need to hold the tx refcount here! */
2979
2980         /* Restart TX completion and pending TX */
2981         if (reset_type == ATH_RESET_NOLOSS) {
2982                 for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
2983                         if (ATH_TXQ_SETUP(sc, i)) {
2984                                 ATH_TXQ_LOCK(&sc->sc_txq[i]);
2985                                 ath_txq_restart_dma(sc, &sc->sc_txq[i]);
2986                                 ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
2987
2988                                 ATH_TX_LOCK(sc);
2989                                 ath_txq_sched(sc, &sc->sc_txq[i]);
2990                                 ATH_TX_UNLOCK(sc);
2991                         }
2992                 }
2993         }
2994
2995         /*
2996          * This may have been set during an ath_start() call which
2997          * set this once it detected a concurrent TX was going on.
2998          * So, clear it.
2999          */
3000         IF_LOCK(&ifp->if_snd);
3001 #if defined(__DragonFly__)
3002         ifq_clr_oactive(&ifp->if_snd);
3003 #else
3004         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
3005 #endif
3006         IF_UNLOCK(&ifp->if_snd);
3007
3008         ATH_LOCK(sc);
3009         ath_power_restore_power_state(sc);
3010         ATH_UNLOCK(sc);
3011
3012         ATH_PCU_LOCK(sc);
3013         sc->sc_txstart_cnt--;
3014         ATH_PCU_UNLOCK(sc);
3015
3016         /* Handle any frames in the TX queue */
3017         /*
3018          * XXX should this be done by the caller, rather than
3019          * ath_reset() ?
3020          */
3021         ath_tx_kick(sc);                /* restart xmit */
3022         return 0;
3023 }
3024
3025 static int
3026 ath_reset_vap(struct ieee80211vap *vap, u_long cmd)
3027 {
3028         struct ieee80211com *ic = vap->iv_ic;
3029         struct ifnet *ifp = ic->ic_ifp;
3030         struct ath_softc *sc = ifp->if_softc;
3031         struct ath_hal *ah = sc->sc_ah;
3032
3033         switch (cmd) {
3034         case IEEE80211_IOC_TXPOWER:
3035                 /*
3036                  * If per-packet TPC is enabled, then we have nothing
3037                  * to do; otherwise we need to force the global limit.
3038                  * All this can happen directly; no need to reset.
3039                  */
3040                 if (!ath_hal_gettpc(ah))
3041                         ath_hal_settxpowlimit(ah, ic->ic_txpowlimit);
3042                 return 0;
3043         }
3044         /* XXX? Full or NOLOSS? */
3045         return ath_reset(ifp, ATH_RESET_FULL);
3046 }
3047
3048 struct ath_buf *
3049 _ath_getbuf_locked(struct ath_softc *sc, ath_buf_type_t btype)
3050 {
3051         struct ath_buf *bf;
3052
3053         ATH_TXBUF_LOCK_ASSERT(sc);
3054
3055         if (btype == ATH_BUFTYPE_MGMT)
3056                 bf = TAILQ_FIRST(&sc->sc_txbuf_mgmt);
3057         else
3058                 bf = TAILQ_FIRST(&sc->sc_txbuf);
3059
3060         if (bf == NULL) {
3061                 sc->sc_stats.ast_tx_getnobuf++;
3062         } else {
3063                 if (bf->bf_flags & ATH_BUF_BUSY) {
3064                         sc->sc_stats.ast_tx_getbusybuf++;
3065                         bf = NULL;
3066                 }
3067         }
3068
3069         if (bf != NULL && (bf->bf_flags & ATH_BUF_BUSY) == 0) {
3070                 if (btype == ATH_BUFTYPE_MGMT)
3071                         TAILQ_REMOVE(&sc->sc_txbuf_mgmt, bf, bf_list);
3072                 else {
3073                         TAILQ_REMOVE(&sc->sc_txbuf, bf, bf_list);
3074                         sc->sc_txbuf_cnt--;
3075
3076                         /*
3077                          * This shuldn't happen; however just to be
3078                          * safe print a warning and fudge the txbuf
3079                          * count.
3080                          */
3081                         if (sc->sc_txbuf_cnt < 0) {
3082                                 device_printf(sc->sc_dev,
3083                                     "%s: sc_txbuf_cnt < 0?\n",
3084                                     __func__);
3085                                 sc->sc_txbuf_cnt = 0;
3086                         }
3087                 }
3088         } else
3089                 bf = NULL;
3090
3091         if (bf == NULL) {
3092                 /* XXX should check which list, mgmt or otherwise */
3093                 DPRINTF(sc, ATH_DEBUG_XMIT, "%s: %s\n", __func__,
3094                     TAILQ_FIRST(&sc->sc_txbuf) == NULL ?
3095                         "out of xmit buffers" : "xmit buffer busy");
3096                 return NULL;
3097         }
3098
3099         /* XXX TODO: should do this at buffer list initialisation */
3100         /* XXX (then, ensure the buffer has the right flag set) */
3101         bf->bf_flags = 0;
3102         if (btype == ATH_BUFTYPE_MGMT)
3103                 bf->bf_flags |= ATH_BUF_MGMT;
3104         else
3105                 bf->bf_flags &= (~ATH_BUF_MGMT);
3106
3107         /* Valid bf here; clear some basic fields */
3108         bf->bf_next = NULL;     /* XXX just to be sure */
3109         bf->bf_last = NULL;     /* XXX again, just to be sure */
3110         bf->bf_comp = NULL;     /* XXX again, just to be sure */
3111         bzero(&bf->bf_state, sizeof(bf->bf_state));
3112
3113         /*
3114          * Track the descriptor ID only if doing EDMA
3115          */
3116         if (sc->sc_isedma) {
3117                 bf->bf_descid = sc->sc_txbuf_descid;
3118                 sc->sc_txbuf_descid++;
3119         }
3120
3121         return bf;
3122 }
3123
3124 /*
3125  * When retrying a software frame, buffers marked ATH_BUF_BUSY
3126  * can't be thrown back on the queue as they could still be
3127  * in use by the hardware.
3128  *
3129  * This duplicates the buffer, or returns NULL.
3130  *
3131  * The descriptor is also copied but the link pointers and
3132  * the DMA segments aren't copied; this frame should thus
3133  * be again passed through the descriptor setup/chain routines
3134  * so the link is correct.
3135  *
3136  * The caller must free the buffer using ath_freebuf().
3137  */
3138 struct ath_buf *
3139 ath_buf_clone(struct ath_softc *sc, struct ath_buf *bf)
3140 {
3141         struct ath_buf *tbf;
3142
3143         tbf = ath_getbuf(sc,
3144             (bf->bf_flags & ATH_BUF_MGMT) ?
3145              ATH_BUFTYPE_MGMT : ATH_BUFTYPE_NORMAL);
3146         if (tbf == NULL)
3147                 return NULL;    /* XXX failure? Why? */
3148
3149         /* Copy basics */
3150         tbf->bf_next = NULL;
3151         tbf->bf_nseg = bf->bf_nseg;
3152         tbf->bf_flags = bf->bf_flags & ATH_BUF_FLAGS_CLONE;
3153         tbf->bf_status = bf->bf_status;
3154         tbf->bf_m = bf->bf_m;
3155         tbf->bf_node = bf->bf_node;
3156         KASSERT((bf->bf_node != NULL), ("%s: bf_node=NULL!", __func__));
3157         /* will be setup by the chain/setup function */
3158         tbf->bf_lastds = NULL;
3159         /* for now, last == self */
3160         tbf->bf_last = tbf;
3161         tbf->bf_comp = bf->bf_comp;
3162
3163         /* NOTE: DMA segments will be setup by the setup/chain functions */
3164
3165         /* The caller has to re-init the descriptor + links */
3166
3167         /*
3168          * Free the DMA mapping here, before we NULL the mbuf.
3169          * We must only call bus_dmamap_unload() once per mbuf chain
3170          * or behaviour is undefined.
3171          */
3172         if (bf->bf_m != NULL) {
3173                 /*
3174                  * XXX is this POSTWRITE call required?
3175                  */
3176                 bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
3177                     BUS_DMASYNC_POSTWRITE);
3178                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
3179         }
3180
3181         bf->bf_m = NULL;
3182         bf->bf_node = NULL;
3183
3184         /* Copy state */
3185         memcpy(&tbf->bf_state, &bf->bf_state, sizeof(bf->bf_state));
3186
3187         return tbf;
3188 }
3189
3190 struct ath_buf *
3191 ath_getbuf(struct ath_softc *sc, ath_buf_type_t btype)
3192 {
3193         struct ath_buf *bf;
3194
3195         ATH_TXBUF_LOCK(sc);
3196         bf = _ath_getbuf_locked(sc, btype);
3197         /*
3198          * If a mgmt buffer was requested but we're out of those,
3199          * try requesting a normal one.
3200          */
3201         if (bf == NULL && btype == ATH_BUFTYPE_MGMT)
3202                 bf = _ath_getbuf_locked(sc, ATH_BUFTYPE_NORMAL);
3203         ATH_TXBUF_UNLOCK(sc);
3204         if (bf == NULL) {
3205                 struct ifnet *ifp = sc->sc_ifp;
3206
3207                 DPRINTF(sc, ATH_DEBUG_XMIT, "%s: stop queue\n", __func__);
3208                 sc->sc_stats.ast_tx_qstop++;
3209                 IF_LOCK(&ifp->if_snd);
3210 #if defined(__DragonFly__)
3211                 ifq_set_oactive(&ifp->if_snd);
3212 #else
3213                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3214 #endif
3215                 IF_UNLOCK(&ifp->if_snd);
3216         }
3217         return bf;
3218 }
3219
3220 #if !defined(__DragonFly__)
3221
3222 static void
3223 ath_qflush(struct ifnet *ifp)
3224 {
3225
3226         /* XXX TODO */
3227 }
3228
3229 #endif
3230
3231 /*
3232  * Transmit a single frame.
3233  *
3234  * net80211 will free the node reference if the transmit
3235  * fails, so don't free the node reference here.
3236  */
3237 static int
3238 ath_transmit(struct ifnet *ifp, struct mbuf *m)
3239 {
3240         struct ieee80211com *ic = ifp->if_l2com;
3241         struct ath_softc *sc = ic->ic_ifp->if_softc;
3242         struct ieee80211_node *ni;
3243         struct mbuf *next;
3244         struct ath_buf *bf;
3245         ath_bufhead frags;
3246         int retval = 0;
3247
3248         /*
3249          * Tell the reset path that we're currently transmitting.
3250          */
3251         ATH_PCU_LOCK(sc);
3252         if (sc->sc_inreset_cnt > 0) {
3253                 DPRINTF(sc, ATH_DEBUG_XMIT,
3254                     "%s: sc_inreset_cnt > 0; bailing\n", __func__);
3255                 ATH_PCU_UNLOCK(sc);
3256                 IF_LOCK(&ifp->if_snd);
3257                 sc->sc_stats.ast_tx_qstop++;
3258 #if defined(__DragonFly__)
3259                 /* removed, DragonFly uses OACTIVE to control if_start calls */
3260                 /*ifq_set_oactive(&ifp->if_snd);*/
3261 #else
3262                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3263 #endif
3264                 IF_UNLOCK(&ifp->if_snd);
3265                 ATH_KTR(sc, ATH_KTR_TX, 0, "ath_start_task: OACTIVE, finish");
3266 #if defined(__DragonFly__)
3267                 m_freem(m);
3268                 m = NULL;
3269 #endif
3270                 return (ENOBUFS);       /* XXX should be EINVAL or? */
3271         }
3272         sc->sc_txstart_cnt++;
3273         ATH_PCU_UNLOCK(sc);
3274
3275         /* Wake the hardware up already */
3276         ATH_LOCK(sc);
3277         ath_power_set_power_state(sc, HAL_PM_AWAKE);
3278         ATH_UNLOCK(sc);
3279
3280         ATH_KTR(sc, ATH_KTR_TX, 0, "ath_transmit: start");
3281         /*
3282          * Grab the TX lock - it's ok to do this here; we haven't
3283          * yet started transmitting.
3284          */
3285         ATH_TX_LOCK(sc);
3286
3287         /*
3288          * Node reference, if there's one.
3289          */
3290         ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
3291
3292         /*
3293          * Enforce how deep a node queue can get.
3294          *
3295          * XXX it would be nicer if we kept an mbuf queue per
3296          * node and only whacked them into ath_bufs when we
3297          * are ready to schedule some traffic from them.
3298          * .. that may come later.
3299          *
3300          * XXX we should also track the per-node hardware queue
3301          * depth so it is easy to limit the _SUM_ of the swq and
3302          * hwq frames.  Since we only schedule two HWQ frames
3303          * at a time, this should be OK for now.
3304          */
3305         if ((!(m->m_flags & M_EAPOL)) &&
3306             (ATH_NODE(ni)->an_swq_depth > sc->sc_txq_node_maxdepth)) {
3307                 sc->sc_stats.ast_tx_nodeq_overflow++;
3308                 m_freem(m);
3309                 m = NULL;
3310                 retval = ENOBUFS;
3311                 goto finish;
3312         }
3313
3314         /*
3315          * Check how many TX buffers are available.
3316          *
3317          * If this is for non-EAPOL traffic, just leave some
3318          * space free in order for buffer cloning and raw
3319          * frame transmission to occur.
3320          *
3321          * If it's for EAPOL traffic, ignore this for now.
3322          * Management traffic will be sent via the raw transmit
3323          * method which bypasses this check.
3324          *
3325          * This is needed to ensure that EAPOL frames during
3326          * (re) keying have a chance to go out.
3327          *
3328          * See kern/138379 for more information.
3329          */
3330         if ((!(m->m_flags & M_EAPOL)) &&
3331             (sc->sc_txbuf_cnt <= sc->sc_txq_data_minfree)) {
3332                 sc->sc_stats.ast_tx_nobuf++;
3333                 m_freem(m);
3334                 m = NULL;
3335                 retval = ENOBUFS;
3336                 goto finish;
3337         }
3338
3339         /*
3340          * Grab a TX buffer and associated resources.
3341          *
3342          * If it's an EAPOL frame, allocate a MGMT ath_buf.
3343          * That way even with temporary buffer exhaustion due to
3344          * the data path doesn't leave us without the ability
3345          * to transmit management frames.
3346          *
3347          * Otherwise allocate a normal buffer.
3348          */
3349         if (m->m_flags & M_EAPOL)
3350                 bf = ath_getbuf(sc, ATH_BUFTYPE_MGMT);
3351         else
3352                 bf = ath_getbuf(sc, ATH_BUFTYPE_NORMAL);
3353
3354         if (bf == NULL) {
3355                 /*
3356                  * If we failed to allocate a buffer, fail.
3357                  *
3358                  * We shouldn't fail normally, due to the check
3359                  * above.
3360                  */
3361                 sc->sc_stats.ast_tx_nobuf++;
3362                 IF_LOCK(&ifp->if_snd);
3363 #if defined(__DragonFly__)
3364                 /* removed, DragonFly uses OACTIVE to control if_start calls */
3365                 /*ifq_set_oactive(&ifp->if_snd);*/
3366 #else
3367                 ifp->if_drv_flags |= IFF_DRV_OACTIVE;
3368 #endif
3369                 IF_UNLOCK(&ifp->if_snd);
3370                 m_freem(m);
3371                 m = NULL;
3372                 retval = ENOBUFS;
3373                 goto finish;
3374         }
3375
3376         /*
3377          * At this point we have a buffer; so we need to free it
3378          * if we hit any error conditions.
3379          */
3380
3381         /*
3382          * Check for fragmentation.  If this frame
3383          * has been broken up verify we have enough
3384          * buffers to send all the fragments so all
3385          * go out or none...
3386          */
3387         TAILQ_INIT(&frags);
3388         if ((m->m_flags & M_FRAG) &&
3389             !ath_txfrag_setup(sc, &frags, m, ni)) {
3390                 DPRINTF(sc, ATH_DEBUG_XMIT,
3391                     "%s: out of txfrag buffers\n", __func__);
3392                 sc->sc_stats.ast_tx_nofrag++;
3393 #if defined(__DragonFly__)
3394                 ++ifp->if_oerrors;
3395 #else
3396                 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
3397 #endif
3398                 ath_freetx(m);
3399                 goto bad;
3400         }
3401
3402         /*
3403          * At this point if we have any TX fragments, then we will
3404          * have bumped the node reference once for each of those.
3405          */
3406
3407         /*
3408          * XXX Is there anything actually _enforcing_ that the
3409          * fragments are being transmitted in one hit, rather than
3410          * being interleaved with other transmissions on that
3411          * hardware queue?
3412          *
3413          * The ATH TX output lock is the only thing serialising this
3414          * right now.
3415          */
3416
3417         /*
3418          * Calculate the "next fragment" length field in ath_buf
3419          * in order to let the transmit path know enough about
3420          * what to next write to the hardware.
3421          */
3422         if (m->m_flags & M_FRAG) {
3423                 struct ath_buf *fbf = bf;
3424                 struct ath_buf *n_fbf = NULL;
3425                 struct mbuf *fm = m->m_nextpkt;
3426
3427                 /*
3428                  * We need to walk the list of fragments and set
3429                  * the next size to the following buffer.
3430                  * However, the first buffer isn't in the frag
3431                  * list, so we have to do some gymnastics here.
3432                  */
3433                 TAILQ_FOREACH(n_fbf, &frags, bf_list) {
3434                         fbf->bf_nextfraglen = fm->m_pkthdr.len;
3435                         fbf = n_fbf;
3436                         fm = fm->m_nextpkt;
3437                 }
3438         }
3439
3440         /*
3441          * Bump the ifp output counter.
3442          *
3443          * XXX should use atomics?
3444          */
3445 #if defined(__DragonFly__)
3446         ++ifp->if_opackets;
3447 #else
3448         if_inc_counter(ifp, IFCOUNTER_OPACKETS, 1);
3449 #endif
3450 nextfrag:
3451         /*
3452          * Pass the frame to the h/w for transmission.
3453          * Fragmented frames have each frag chained together
3454          * with m_nextpkt.  We know there are sufficient ath_buf's
3455          * to send all the frags because of work done by
3456          * ath_txfrag_setup.  We leave m_nextpkt set while
3457          * calling ath_tx_start so it can use it to extend the
3458          * the tx duration to cover the subsequent frag and
3459          * so it can reclaim all the mbufs in case of an error;
3460          * ath_tx_start clears m_nextpkt once it commits to
3461          * handing the frame to the hardware.
3462          *
3463          * Note: if this fails, then the mbufs are freed but
3464          * not the node reference.
3465          */
3466         next = m->m_nextpkt;
3467         if (ath_tx_start(sc, ni, bf, m)) {
3468 bad:
3469 #if defined(__DragonFly__)
3470                 ++ifp->if_oerrors;
3471 #else
3472                 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
3473 #endif
3474 reclaim:
3475                 bf->bf_m = NULL;
3476                 bf->bf_node = NULL;
3477                 ATH_TXBUF_LOCK(sc);
3478                 ath_returnbuf_head(sc, bf);
3479                 /*
3480                  * Free the rest of the node references and
3481                  * buffers for the fragment list.
3482                  */
3483                 ath_txfrag_cleanup(sc, &frags, ni);
3484                 ATH_TXBUF_UNLOCK(sc);
3485                 retval = ENOBUFS;
3486                 goto finish;
3487         }
3488
3489         /*
3490          * Check here if the node is in power save state.
3491          */
3492         ath_tx_update_tim(sc, ni, 1);
3493
3494         if (next != NULL) {
3495                 /*
3496                  * Beware of state changing between frags.
3497                  * XXX check sta power-save state?
3498                  */
3499                 if (ni->ni_vap->iv_state != IEEE80211_S_RUN) {
3500                         DPRINTF(sc, ATH_DEBUG_XMIT,
3501                             "%s: flush fragmented packet, state %s\n",
3502                             __func__,
3503                             ieee80211_state_name[ni->ni_vap->iv_state]);
3504                         /* XXX dmamap */
3505                         ath_freetx(next);
3506                         goto reclaim;
3507                 }
3508                 m = next;
3509                 bf = TAILQ_FIRST(&frags);
3510                 KASSERT(bf != NULL, ("no buf for txfrag"));
3511                 TAILQ_REMOVE(&frags, bf, bf_list);
3512                 goto nextfrag;
3513         }
3514
3515         /*
3516          * Bump watchdog timer.
3517          */
3518         sc->sc_wd_timer = 5;
3519
3520 finish:
3521         ATH_TX_UNLOCK(sc);
3522
3523         /*
3524          * Finished transmitting!
3525          */
3526         ATH_PCU_LOCK(sc);
3527         sc->sc_txstart_cnt--;
3528         ATH_PCU_UNLOCK(sc);
3529
3530         /* Sleep the hardware if required */
3531         ATH_LOCK(sc);
3532         ath_power_restore_power_state(sc);
3533         ATH_UNLOCK(sc);
3534
3535         ATH_KTR(sc, ATH_KTR_TX, 0, "ath_transmit: finished");
3536         
3537         return (retval);
3538 }
3539
3540 static int
3541 ath_media_change(struct ifnet *ifp)
3542 {
3543         int error = ieee80211_media_change(ifp);
3544         /* NB: only the fixed rate can change and that doesn't need a reset */
3545         return (error == ENETRESET ? 0 : error);
3546 }
3547
3548 /*
3549  * Block/unblock tx+rx processing while a key change is done.
3550  * We assume the caller serializes key management operations
3551  * so we only need to worry about synchronization with other
3552  * uses that originate in the driver.
3553  */
3554 static void
3555 ath_key_update_begin(struct ieee80211vap *vap)
3556 {
3557         struct ifnet *ifp = vap->iv_ic->ic_ifp;
3558         struct ath_softc *sc = ifp->if_softc;
3559
3560         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
3561         taskqueue_block(sc->sc_tq);
3562 }
3563
3564 static void
3565 ath_key_update_end(struct ieee80211vap *vap)
3566 {
3567         struct ifnet *ifp = vap->iv_ic->ic_ifp;
3568         struct ath_softc *sc = ifp->if_softc;
3569
3570         DPRINTF(sc, ATH_DEBUG_KEYCACHE, "%s:\n", __func__);
3571         taskqueue_unblock(sc->sc_tq);
3572 }
3573
3574 static void
3575 ath_update_promisc(struct ifnet *ifp)
3576 {
3577         struct ath_softc *sc = ifp->if_softc;
3578         u_int32_t rfilt;
3579
3580         /* configure rx filter */
3581         ATH_LOCK(sc);
3582         ath_power_set_power_state(sc, HAL_PM_AWAKE);
3583         rfilt = ath_calcrxfilter(sc);
3584         ath_hal_setrxfilter(sc->sc_ah, rfilt);
3585         ath_power_restore_power_state(sc);
3586         ATH_UNLOCK(sc);
3587
3588         DPRINTF(sc, ATH_DEBUG_MODE, "%s: RX filter 0x%x\n", __func__, rfilt);
3589 }
3590
3591 /*
3592  * Driver-internal mcast update call.
3593  *
3594  * Assumes the hardware is already awake.
3595  */
3596 static void
3597 ath_update_mcast_hw(struct ath_softc *sc)
3598 {
3599         struct ifnet *ifp = sc->sc_ifp;
3600         u_int32_t mfilt[2];
3601
3602         /* calculate and install multicast filter */
3603         if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
3604                 struct ifmultiaddr *ifma;
3605                 /*
3606                  * Merge multicast addresses to form the hardware filter.
3607                  */
3608                 mfilt[0] = mfilt[1] = 0;
3609 #if defined(__DragonFly__)
3610                 /* nothing */
3611 #else
3612                 if_maddr_rlock(ifp);    /* XXX need some fiddling to remove? */
3613 #endif
3614                 TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
3615                         caddr_t dl;
3616                         u_int32_t val;
3617                         u_int8_t pos;
3618
3619                         /* calculate XOR of eight 6bit values */
3620                         dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
3621                         val = LE_READ_4(dl + 0);
3622                         pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
3623                         val = LE_READ_4(dl + 3);
3624                         pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
3625                         pos &= 0x3f;
3626                         mfilt[pos / 32] |= (1 << (pos % 32));
3627                 }
3628 #if defined(__DragonFly__)
3629                 /* nothing */
3630 #else
3631                 if_maddr_runlock(ifp);
3632 #endif
3633         } else
3634                 mfilt[0] = mfilt[1] = ~0;
3635
3636         ath_hal_setmcastfilter(sc->sc_ah, mfilt[0], mfilt[1]);
3637
3638         DPRINTF(sc, ATH_DEBUG_MODE, "%s: MC filter %08x:%08x\n",
3639                 __func__, mfilt[0], mfilt[1]);
3640 }
3641
3642 /*
3643  * Called from the net80211 layer - force the hardware
3644  * awake before operating.
3645  */
3646 static void
3647 ath_update_mcast(struct ifnet *ifp)
3648 {
3649         struct ath_softc *sc = ifp->if_softc;
3650
3651         ATH_LOCK(sc);
3652         ath_power_set_power_state(sc, HAL_PM_AWAKE);
3653         ATH_UNLOCK(sc);
3654
3655         ath_update_mcast_hw(sc);
3656
3657         ATH_LOCK(sc);
3658         ath_power_restore_power_state(sc);
3659         ATH_UNLOCK(sc);
3660 }
3661
3662 void
3663 ath_mode_init(struct ath_softc *sc)
3664 {
3665         struct ifnet *ifp = sc->sc_ifp;
3666         struct ath_hal *ah = sc->sc_ah;
3667         u_int32_t rfilt;
3668
3669         /* configure rx filter */
3670         rfilt = ath_calcrxfilter(sc);
3671         ath_hal_setrxfilter(ah, rfilt);
3672
3673         /* configure operational mode */
3674         ath_hal_setopmode(ah);
3675
3676 #if !defined(__DragonFly__)
3677         DPRINTF(sc, ATH_DEBUG_STATE | ATH_DEBUG_MODE,
3678             "%s: ah=%p, ifp=%p, if_addr=%p\n",
3679             __func__,
3680             ah,
3681             ifp,
3682             (ifp == NULL) ? NULL : ifp->if_addr);
3683 #endif
3684
3685         /* handle any link-level address change */
3686         ath_hal_setmac(ah, IF_LLADDR(ifp));
3687
3688         /* calculate and install multicast filter */
3689         ath_update_mcast_hw(sc);
3690 }
3691
3692 /*
3693  * Set the slot time based on the current setting.
3694  */
3695 void
3696 ath_setslottime(struct ath_softc *sc)
3697 {
3698         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
3699         struct ath_hal *ah = sc->sc_ah;
3700         u_int usec;
3701
3702         if (IEEE80211_IS_CHAN_HALF(ic->ic_curchan))
3703                 usec = 13;
3704         else if (IEEE80211_IS_CHAN_QUARTER(ic->ic_curchan))
3705                 usec = 21;
3706         else if (IEEE80211_IS_CHAN_ANYG(ic->ic_curchan)) {
3707                 /* honor short/long slot time only in 11g */
3708                 /* XXX shouldn't honor on pure g or turbo g channel */
3709                 if (ic->ic_flags & IEEE80211_F_SHSLOT)
3710                         usec = HAL_SLOT_TIME_9;
3711                 else
3712                         usec = HAL_SLOT_TIME_20;
3713         } else
3714                 usec = HAL_SLOT_TIME_9;
3715
3716         DPRINTF(sc, ATH_DEBUG_RESET,
3717             "%s: chan %u MHz flags 0x%x %s slot, %u usec\n",
3718             __func__, ic->ic_curchan->ic_freq, ic->ic_curchan->ic_flags,
3719             ic->ic_flags & IEEE80211_F_SHSLOT ? "short" : "long", usec);
3720
3721         /* Wake up the hardware first before updating the slot time */
3722         ATH_LOCK(sc);
3723         ath_power_set_power_state(sc, HAL_PM_AWAKE);
3724         ath_hal_setslottime(ah, usec);
3725         ath_power_restore_power_state(sc);
3726         sc->sc_updateslot = OK;
3727         ATH_UNLOCK(sc);
3728 }
3729
3730 /*
3731  * Callback from the 802.11 layer to update the
3732  * slot time based on the current setting.
3733  */
3734 static void
3735 ath_updateslot(struct ifnet *ifp)
3736 {
3737         struct ath_softc *sc = ifp->if_softc;
3738         struct ieee80211com *ic = ifp->if_l2com;
3739
3740         /*
3741          * When not coordinating the BSS, change the hardware
3742          * immediately.  For other operation we defer the change
3743          * until beacon updates have propagated to the stations.
3744          *
3745          * XXX sc_updateslot isn't changed behind a lock?
3746          */
3747         if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
3748             ic->ic_opmode == IEEE80211_M_MBSS)
3749                 sc->sc_updateslot = UPDATE;
3750         else
3751                 ath_setslottime(sc);
3752 }
3753
3754 /*
3755  * Append the contents of src to dst; both queues
3756  * are assumed to be locked.
3757  */
3758 void
3759 ath_txqmove(struct ath_txq *dst, struct ath_txq *src)
3760 {
3761
3762         ATH_TXQ_LOCK_ASSERT(src);
3763         ATH_TXQ_LOCK_ASSERT(dst);
3764
3765         TAILQ_CONCAT(&dst->axq_q, &src->axq_q, bf_list);
3766         dst->axq_link = src->axq_link;
3767         src->axq_link = NULL;
3768         dst->axq_depth += src->axq_depth;
3769         dst->axq_aggr_depth += src->axq_aggr_depth;
3770         src->axq_depth = 0;
3771         src->axq_aggr_depth = 0;
3772 }
3773
3774 /*
3775  * Reset the hardware, with no loss.
3776  *
3777  * This can't be used for a general case reset.
3778  */
3779 static void
3780 ath_reset_proc(void *arg, int pending)
3781 {
3782         struct ath_softc *sc = arg;
3783         struct ifnet *ifp = sc->sc_ifp;
3784
3785 #if 0
3786         if_printf(ifp, "%s: resetting\n", __func__);
3787 #endif
3788         wlan_serialize_enter();
3789         ath_reset(ifp, ATH_RESET_NOLOSS);
3790         wlan_serialize_exit();
3791 }
3792
3793 /*
3794  * Reset the hardware after detecting beacons have stopped.
3795  */
3796 static void
3797 ath_bstuck_proc(void *arg, int pending)
3798 {
3799         struct ath_softc *sc = arg;
3800         struct ifnet *ifp = sc->sc_ifp;
3801         uint32_t hangs = 0;
3802
3803         wlan_serialize_enter();
3804         if (ath_hal_gethangstate(sc->sc_ah, 0xff, &hangs) && hangs != 0)
3805                 if_printf(ifp, "bb hang detected (0x%x)\n", hangs);
3806
3807 #ifdef  ATH_DEBUG_ALQ
3808         if (if_ath_alq_checkdebug(&sc->sc_alq, ATH_ALQ_STUCK_BEACON))
3809                 if_ath_alq_post(&sc->sc_alq, ATH_ALQ_STUCK_BEACON, 0, NULL);
3810 #endif
3811
3812         if_printf(ifp, "stuck beacon; resetting (bmiss count %u)\n",
3813                 sc->sc_bmisscount);
3814         sc->sc_stats.ast_bstuck++;
3815         /*
3816          * This assumes that there's no simultaneous channel mode change
3817          * occuring.
3818          */
3819         ath_reset(ifp, ATH_RESET_NOLOSS);
3820         wlan_serialize_exit();
3821 }
3822
3823 static void
3824 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
3825 {
3826         bus_addr_t *paddr = (bus_addr_t*) arg;
3827         KASSERT(error == 0, ("error %u on bus_dma callback", error));
3828         *paddr = segs->ds_addr;
3829 }
3830
3831 /*
3832  * Allocate the descriptors and appropriate DMA tag/setup.
3833  *
3834  * For some situations (eg EDMA TX completion), there isn't a requirement
3835  * for the ath_buf entries to be allocated.
3836  */
3837 int
3838 ath_descdma_alloc_desc(struct ath_softc *sc,
3839         struct ath_descdma *dd, ath_bufhead *head,
3840         const char *name, int ds_size, int ndesc)
3841 {
3842 #define DS2PHYS(_dd, _ds) \
3843         ((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3844 #define ATH_DESC_4KB_BOUND_CHECK(_daddr, _len) \
3845         ((((u_int32_t)(_daddr) & 0xFFF) > (0x1000 - (_len))) ? 1 : 0)
3846         struct ifnet *ifp = sc->sc_ifp;
3847         int error;
3848
3849         dd->dd_descsize = ds_size;
3850
3851         DPRINTF(sc, ATH_DEBUG_RESET,
3852             "%s: %s DMA: %u desc, %d bytes per descriptor\n",
3853             __func__, name, ndesc, dd->dd_descsize);
3854
3855         dd->dd_name = name;
3856         dd->dd_desc_len = dd->dd_descsize * ndesc;
3857
3858         /*
3859          * Merlin work-around:
3860          * Descriptors that cross the 4KB boundary can't be used.
3861          * Assume one skipped descriptor per 4KB page.
3862          */
3863         if (! ath_hal_split4ktrans(sc->sc_ah)) {
3864                 int numpages = dd->dd_desc_len / 4096;
3865                 dd->dd_desc_len += ds_size * numpages;
3866         }
3867
3868         /*
3869          * Setup DMA descriptor area.
3870          *
3871          * BUS_DMA_ALLOCNOW is not used; we never use bounce
3872          * buffers for the descriptors themselves.
3873          */
3874         error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), /* parent */
3875                        PAGE_SIZE, 0,            /* alignment, bounds */
3876                        BUS_SPACE_MAXADDR_32BIT, /* lowaddr */
3877                        BUS_SPACE_MAXADDR,       /* highaddr */
3878                        NULL, NULL,              /* filter, filterarg */
3879                        dd->dd_desc_len,         /* maxsize */
3880                        1,                       /* nsegments */
3881                        dd->dd_desc_len,         /* maxsegsize */
3882                        0,                       /* flags */
3883 #if !defined(__DragonFly__)
3884                        NULL,                    /* lockfunc */
3885                        NULL,                    /* lockarg */
3886 #endif
3887                        &dd->dd_dmat);
3888         if (error != 0) {
3889                 if_printf(ifp, "cannot allocate %s DMA tag\n", dd->dd_name);
3890                 return error;
3891         }
3892
3893         /* allocate descriptors */
3894         error = bus_dmamem_alloc(dd->dd_dmat, (void**) &dd->dd_desc,
3895                                  BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
3896                                  &dd->dd_dmamap);
3897         if (error != 0) {
3898                 if_printf(ifp, "unable to alloc memory for %u %s descriptors, "
3899                         "error %u\n", ndesc, dd->dd_name, error);
3900                 goto fail1;
3901         }
3902
3903         error = bus_dmamap_load(dd->dd_dmat, dd->dd_dmamap,
3904                                 dd->dd_desc, dd->dd_desc_len,
3905                                 ath_load_cb, &dd->dd_desc_paddr,
3906                                 BUS_DMA_NOWAIT);
3907         if (error != 0) {
3908                 if_printf(ifp, "unable to map %s descriptors, error %u\n",
3909                         dd->dd_name, error);
3910                 goto fail2;
3911         }
3912
3913         DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA map: %p (%lu) -> %p (%lu)\n",
3914             __func__, dd->dd_name, (uint8_t *) dd->dd_desc,
3915             (u_long) dd->dd_desc_len, (caddr_t) dd->dd_desc_paddr,
3916             /*XXX*/ (u_long) dd->dd_desc_len);
3917
3918         return (0);
3919
3920 fail2:
3921         bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
3922 fail1:
3923         bus_dma_tag_destroy(dd->dd_dmat);
3924         memset(dd, 0, sizeof(*dd));
3925         return error;
3926 #undef DS2PHYS
3927 #undef ATH_DESC_4KB_BOUND_CHECK
3928 }
3929
3930 int
3931 ath_descdma_setup(struct ath_softc *sc,
3932         struct ath_descdma *dd, ath_bufhead *head,
3933         const char *name, int ds_size, int nbuf, int ndesc)
3934 {
3935 #define DS2PHYS(_dd, _ds) \
3936         ((_dd)->dd_desc_paddr + ((caddr_t)(_ds) - (caddr_t)(_dd)->dd_desc))
3937 #define ATH_DESC_4KB_BOUND_CHECK(_daddr, _len) \
3938         ((((u_int32_t)(_daddr) & 0xFFF) > (0x1000 - (_len))) ? 1 : 0)
3939         struct ifnet *ifp = sc->sc_ifp;
3940         uint8_t *ds;
3941         struct ath_buf *bf;
3942         int i, bsize, error;
3943
3944         /* Allocate descriptors */
3945         error = ath_descdma_alloc_desc(sc, dd, head, name, ds_size,
3946             nbuf * ndesc);
3947
3948         /* Assume any errors during allocation were dealt with */
3949         if (error != 0) {
3950                 return (error);
3951         }
3952
3953         ds = (uint8_t *) dd->dd_desc;
3954
3955         /* allocate rx buffers */
3956         bsize = sizeof(struct ath_buf) * nbuf;
3957         bf = kmalloc(bsize, M_ATHDEV, M_INTWAIT | M_ZERO);
3958         if (bf == NULL) {
3959                 if_printf(ifp, "malloc of %s buffers failed, size %u\n",
3960                         dd->dd_name, bsize);
3961                 goto fail3;
3962         }
3963         dd->dd_bufptr = bf;
3964
3965         TAILQ_INIT(head);
3966         for (i = 0; i < nbuf; i++, bf++, ds += (ndesc * dd->dd_descsize)) {
3967                 bf->bf_desc = (struct ath_desc *) ds;
3968                 bf->bf_daddr = DS2PHYS(dd, ds);
3969                 if (! ath_hal_split4ktrans(sc->sc_ah)) {
3970                         /*
3971                          * Merlin WAR: Skip descriptor addresses which
3972                          * cause 4KB boundary crossing along any point
3973                          * in the descriptor.
3974                          */
3975                          if (ATH_DESC_4KB_BOUND_CHECK(bf->bf_daddr,
3976                              dd->dd_descsize)) {
3977                                 /* Start at the next page */
3978                                 ds += 0x1000 - (bf->bf_daddr & 0xFFF);
3979                                 bf->bf_desc = (struct ath_desc *) ds;
3980                                 bf->bf_daddr = DS2PHYS(dd, ds);
3981                         }
3982                 }
3983                 error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
3984                                 &bf->bf_dmamap);
3985                 if (error != 0) {
3986                         if_printf(ifp, "unable to create dmamap for %s "
3987                                 "buffer %u, error %u\n", dd->dd_name, i, error);
3988                         ath_descdma_cleanup(sc, dd, head);
3989                         return error;
3990                 }
3991                 bf->bf_lastds = bf->bf_desc;    /* Just an initial value */
3992                 TAILQ_INSERT_TAIL(head, bf, bf_list);
3993         }
3994
3995         /*
3996          * XXX TODO: ensure that ds doesn't overflow the descriptor
3997          * allocation otherwise weird stuff will occur and crash your
3998          * machine.
3999          */
4000         return 0;
4001         /* XXX this should likely just call ath_descdma_cleanup() */
4002 fail3:
4003         bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
4004         bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
4005         bus_dma_tag_destroy(dd->dd_dmat);
4006         memset(dd, 0, sizeof(*dd));
4007         return error;
4008 #undef DS2PHYS
4009 #undef ATH_DESC_4KB_BOUND_CHECK
4010 }
4011
4012 /*
4013  * Allocate ath_buf entries but no descriptor contents.
4014  *
4015  * This is for RX EDMA where the descriptors are the header part of
4016  * the RX buffer.
4017  */
4018 int
4019 ath_descdma_setup_rx_edma(struct ath_softc *sc,
4020         struct ath_descdma *dd, ath_bufhead *head,
4021         const char *name, int nbuf, int rx_status_len)
4022 {
4023         struct ifnet *ifp = sc->sc_ifp;
4024         struct ath_buf *bf;
4025         int i, bsize, error;
4026
4027         DPRINTF(sc, ATH_DEBUG_RESET, "%s: %s DMA: %u buffers\n",
4028             __func__, name, nbuf);
4029
4030         dd->dd_name = name;
4031         /*
4032          * This is (mostly) purely for show.  We're not allocating any actual
4033          * descriptors here as EDMA RX has the descriptor be part
4034          * of the RX buffer.
4035          *
4036          * However, dd_desc_len is used by ath_descdma_free() to determine
4037          * whether we have already freed this DMA mapping.
4038          */
4039         dd->dd_desc_len = rx_status_len * nbuf;
4040         dd->dd_descsize = rx_status_len;
4041
4042         /* allocate rx buffers */
4043         bsize = sizeof(struct ath_buf) * nbuf;
4044         bf = kmalloc(bsize, M_ATHDEV, M_INTWAIT | M_ZERO);
4045         if (bf == NULL) {
4046                 if_printf(ifp, "malloc of %s buffers failed, size %u\n",
4047                         dd->dd_name, bsize);
4048                 error = ENOMEM;
4049                 goto fail3;
4050         }
4051         dd->dd_bufptr = bf;
4052
4053         TAILQ_INIT(head);
4054         for (i = 0; i < nbuf; i++, bf++) {
4055                 bf->bf_desc = NULL;
4056                 bf->bf_daddr = 0;
4057                 bf->bf_lastds = NULL;   /* Just an initial value */
4058
4059                 error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
4060                                 &bf->bf_dmamap);
4061                 if (error != 0) {
4062                         if_printf(ifp, "unable to create dmamap for %s "
4063                                 "buffer %u, error %u\n", dd->dd_name, i, error);
4064                         ath_descdma_cleanup(sc, dd, head);
4065                         return error;
4066                 }
4067                 TAILQ_INSERT_TAIL(head, bf, bf_list);
4068         }
4069         return 0;
4070 fail3:
4071         memset(dd, 0, sizeof(*dd));
4072         return error;
4073 }
4074
4075 void
4076 ath_descdma_cleanup(struct ath_softc *sc,
4077         struct ath_descdma *dd, ath_bufhead *head)
4078 {
4079         struct ath_buf *bf;
4080         struct ieee80211_node *ni;
4081         int do_warning = 0;
4082
4083         if (dd->dd_dmamap != 0) {
4084                 bus_dmamap_unload(dd->dd_dmat, dd->dd_dmamap);
4085                 bus_dmamem_free(dd->dd_dmat, dd->dd_desc, dd->dd_dmamap);
4086                 bus_dma_tag_destroy(dd->dd_dmat);
4087         }
4088
4089         if (head != NULL) {
4090                 TAILQ_FOREACH(bf, head, bf_list) {
4091                         if (bf->bf_m) {
4092                                 /*
4093                                  * XXX warn if there's buffers here.
4094                                  * XXX it should have been freed by the
4095                                  * owner!
4096                                  */
4097                                 
4098                                 if (do_warning == 0) {
4099                                         do_warning = 1;
4100                                         device_printf(sc->sc_dev,
4101                                             "%s: %s: mbuf should've been"
4102                                             " unmapped/freed!\n",
4103                                             __func__,
4104                                             dd->dd_name);
4105                                 }
4106                                 bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
4107                                     BUS_DMASYNC_POSTREAD);
4108                                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
4109                                 m_freem(bf->bf_m);
4110                                 bf->bf_m = NULL;
4111                         }
4112                         if (bf->bf_dmamap != NULL) {
4113                                 bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
4114                                 bf->bf_dmamap = NULL;
4115                         }
4116                         ni = bf->bf_node;
4117                         bf->bf_node = NULL;
4118                         if (ni != NULL) {
4119                                 /*
4120                                  * Reclaim node reference.
4121                                  */
4122                                 ieee80211_free_node(ni);
4123                         }
4124                 }
4125         }
4126
4127         if (head != NULL)
4128                 TAILQ_INIT(head);
4129
4130         if (dd->dd_bufptr != NULL)
4131                 kfree(dd->dd_bufptr, M_ATHDEV);
4132         memset(dd, 0, sizeof(*dd));
4133 }
4134
4135 static int
4136 ath_desc_alloc(struct ath_softc *sc)
4137 {
4138         int error;
4139
4140         error = ath_descdma_setup(sc, &sc->sc_txdma, &sc->sc_txbuf,
4141                     "tx", sc->sc_tx_desclen, ath_txbuf, ATH_MAX_SCATTER);
4142         if (error != 0) {
4143                 return error;
4144         }
4145         sc->sc_txbuf_cnt = ath_txbuf;
4146
4147         error = ath_descdma_setup(sc, &sc->sc_txdma_mgmt, &sc->sc_txbuf_mgmt,
4148                     "tx_mgmt", sc->sc_tx_desclen, ath_txbuf_mgmt,
4149                     ATH_TXDESC);
4150         if (error != 0) {
4151                 ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
4152                 return error;
4153         }
4154
4155         /*
4156          * XXX mark txbuf_mgmt frames with ATH_BUF_MGMT, so the
4157          * flag doesn't have to be set in ath_getbuf_locked().
4158          */
4159
4160         error = ath_descdma_setup(sc, &sc->sc_bdma, &sc->sc_bbuf,
4161                         "beacon", sc->sc_tx_desclen, ATH_BCBUF, 1);
4162         if (error != 0) {
4163                 ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
4164                 ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
4165                     &sc->sc_txbuf_mgmt);
4166                 return error;
4167         }
4168         return 0;
4169 }
4170
4171 static void
4172 ath_desc_free(struct ath_softc *sc)
4173 {
4174
4175         if (sc->sc_bdma.dd_desc_len != 0)
4176                 ath_descdma_cleanup(sc, &sc->sc_bdma, &sc->sc_bbuf);
4177         if (sc->sc_txdma.dd_desc_len != 0)
4178                 ath_descdma_cleanup(sc, &sc->sc_txdma, &sc->sc_txbuf);
4179         if (sc->sc_txdma_mgmt.dd_desc_len != 0)
4180                 ath_descdma_cleanup(sc, &sc->sc_txdma_mgmt,
4181                     &sc->sc_txbuf_mgmt);
4182 }
4183
4184 static struct ieee80211_node *
4185 ath_node_alloc(struct ieee80211vap *vap, const uint8_t mac[IEEE80211_ADDR_LEN])
4186 {
4187         struct ieee80211com *ic = vap->iv_ic;
4188         struct ath_softc *sc = ic->ic_ifp->if_softc;
4189         const size_t space = sizeof(struct ath_node) + sc->sc_rc->arc_space;
4190         struct ath_node *an;
4191
4192         an = kmalloc(space, M_80211_NODE, M_INTWAIT | M_ZERO);
4193         if (an == NULL) {
4194                 /* XXX stat+msg */
4195                 return NULL;
4196         }
4197         ath_rate_node_init(sc, an);
4198
4199         /* Setup the mutex - there's no associd yet so set the name to NULL */
4200         ksnprintf(an->an_name, sizeof(an->an_name), "%s: node %p",
4201             device_get_nameunit(sc->sc_dev), an);
4202         lockinit(&an->an_mtx, an->an_name, 0, 0);
4203
4204         /* XXX setup ath_tid */
4205         ath_tx_tid_init(sc, an);
4206
4207         DPRINTF(sc, ATH_DEBUG_NODE, "%s: %s: an %p\n", __func__,
4208             ath_hal_ether_sprintf(mac), an);
4209         return &an->an_node;
4210 }
4211
4212 static void
4213 ath_node_cleanup(struct ieee80211_node *ni)
4214 {
4215         struct ieee80211com *ic = ni->ni_ic;
4216         struct ath_softc *sc = ic->ic_ifp->if_softc;
4217
4218         DPRINTF(sc, ATH_DEBUG_NODE, "%s: %s: an %p\n", __func__,
4219             ath_hal_ether_sprintf(ni->ni_macaddr), ATH_NODE(ni));
4220
4221         /* Cleanup ath_tid, free unused bufs, unlink bufs in TXQ */
4222         ath_tx_node_flush(sc, ATH_NODE(ni));
4223         ath_rate_node_cleanup(sc, ATH_NODE(ni));
4224         sc->sc_node_cleanup(ni);
4225 }
4226
4227 static void
4228 ath_node_free(struct ieee80211_node *ni)
4229 {
4230         struct ieee80211com *ic = ni->ni_ic;
4231         struct ath_softc *sc = ic->ic_ifp->if_softc;
4232
4233         DPRINTF(sc, ATH_DEBUG_NODE, "%s: %s: an %p\n", __func__,
4234             ath_hal_ether_sprintf(ni->ni_macaddr), ATH_NODE(ni));
4235         lockuninit(&ATH_NODE(ni)->an_mtx);
4236         sc->sc_node_free(ni);
4237 }
4238
4239 static void
4240 ath_node_getsignal(const struct ieee80211_node *ni, int8_t *rssi, int8_t *noise)
4241 {
4242         struct ieee80211com *ic = ni->ni_ic;
4243         struct ath_softc *sc = ic->ic_ifp->if_softc;
4244         struct ath_hal *ah = sc->sc_ah;
4245
4246         *rssi = ic->ic_node_getrssi(ni);
4247         if (ni->ni_chan != IEEE80211_CHAN_ANYC)
4248                 *noise = ath_hal_getchannoise(ah, ni->ni_chan);
4249         else
4250                 *noise = -95;           /* nominally correct */
4251 }
4252
4253 /*
4254  * Set the default antenna.
4255  */
4256 void
4257 ath_setdefantenna(struct ath_softc *sc, u_int antenna)
4258 {
4259         struct ath_hal *ah = sc->sc_ah;
4260
4261         /* XXX block beacon interrupts */
4262         ath_hal_setdefantenna(ah, antenna);
4263         if (sc->sc_defant != antenna)
4264                 sc->sc_stats.ast_ant_defswitch++;
4265         sc->sc_defant = antenna;
4266         sc->sc_rxotherant = 0;
4267 }
4268
4269 static void
4270 ath_txq_init(struct ath_softc *sc, struct ath_txq *txq, int qnum)
4271 {
4272         txq->axq_qnum = qnum;
4273         txq->axq_ac = 0;
4274         txq->axq_depth = 0;
4275         txq->axq_aggr_depth = 0;
4276         txq->axq_intrcnt = 0;
4277         txq->axq_link = NULL;
4278         txq->axq_softc = sc;
4279         TAILQ_INIT(&txq->axq_q);
4280         TAILQ_INIT(&txq->axq_tidq);
4281         TAILQ_INIT(&txq->fifo.axq_q);
4282         ATH_TXQ_LOCK_INIT(sc, txq);
4283 }
4284
4285 /*
4286  * Setup a h/w transmit queue.
4287  */
4288 static struct ath_txq *
4289 ath_txq_setup(struct ath_softc *sc, int qtype, int subtype)
4290 {
4291 #define N(a)    (sizeof(a)/sizeof(a[0]))
4292         struct ath_hal *ah = sc->sc_ah;
4293         HAL_TXQ_INFO qi;
4294         int qnum;
4295
4296         memset(&qi, 0, sizeof(qi));
4297         qi.tqi_subtype = subtype;
4298         qi.tqi_aifs = HAL_TXQ_USEDEFAULT;
4299         qi.tqi_cwmin = HAL_TXQ_USEDEFAULT;
4300         qi.tqi_cwmax = HAL_TXQ_USEDEFAULT;
4301         /*
4302          * Enable interrupts only for EOL and DESC conditions.
4303          * We mark tx descriptors to receive a DESC interrupt
4304          * when a tx queue gets deep; otherwise waiting for the
4305          * EOL to reap descriptors.  Note that this is done to
4306          * reduce interrupt load and this only defers reaping
4307          * descriptors, never transmitting frames.  Aside from
4308          * reducing interrupts this also permits more concurrency.
4309          * The only potential downside is if the tx queue backs
4310          * up in which case the top half of the kernel may backup
4311          * due to a lack of tx descriptors.
4312          */
4313         if (sc->sc_isedma)
4314                 qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE |
4315                     HAL_TXQ_TXOKINT_ENABLE;
4316         else
4317                 qi.tqi_qflags = HAL_TXQ_TXEOLINT_ENABLE |
4318                     HAL_TXQ_TXDESCINT_ENABLE;
4319
4320         qnum = ath_hal_setuptxqueue(ah, qtype, &qi);
4321         if (qnum == -1) {
4322                 /*
4323                  * NB: don't print a message, this happens
4324                  * normally on parts with too few tx queues
4325                  */
4326                 return NULL;
4327         }
4328         if (qnum >= N(sc->sc_txq)) {
4329                 device_printf(sc->sc_dev,
4330                         "hal qnum %u out of range, max %zu!\n",
4331                         qnum, N(sc->sc_txq));
4332                 ath_hal_releasetxqueue(ah, qnum);
4333                 return NULL;
4334         }
4335         if (!ATH_TXQ_SETUP(sc, qnum)) {
4336                 ath_txq_init(sc, &sc->sc_txq[qnum], qnum);
4337                 sc->sc_txqsetup |= 1<<qnum;
4338         }
4339         return &sc->sc_txq[qnum];
4340 #undef N
4341 }
4342
4343 /*
4344  * Setup a hardware data transmit queue for the specified
4345  * access control.  The hal may not support all requested
4346  * queues in which case it will return a reference to a
4347  * previously setup queue.  We record the mapping from ac's
4348  * to h/w queues for use by ath_tx_start and also track
4349  * the set of h/w queues being used to optimize work in the
4350  * transmit interrupt handler and related routines.
4351  */
4352 static int
4353 ath_tx_setup(struct ath_softc *sc, int ac, int haltype)
4354 {
4355 #define N(a)    (sizeof(a)/sizeof(a[0]))
4356         struct ath_txq *txq;
4357
4358         if (ac >= N(sc->sc_ac2q)) {
4359                 device_printf(sc->sc_dev, "AC %u out of range, max %zu!\n",
4360                         ac, N(sc->sc_ac2q));
4361                 return 0;
4362         }
4363         txq = ath_txq_setup(sc, HAL_TX_QUEUE_DATA, haltype);
4364         if (txq != NULL) {
4365                 txq->axq_ac = ac;
4366                 sc->sc_ac2q[ac] = txq;
4367                 return 1;
4368         } else
4369                 return 0;
4370 #undef N
4371 }
4372
4373 /*
4374  * Update WME parameters for a transmit queue.
4375  */
4376 static int
4377 ath_txq_update(struct ath_softc *sc, int ac)
4378 {
4379 #define ATH_EXPONENT_TO_VALUE(v)        ((1<<v)-1)
4380 #define ATH_TXOP_TO_US(v)               (v<<5)
4381         struct ifnet *ifp = sc->sc_ifp;
4382         struct ieee80211com *ic = ifp->if_l2com;
4383         struct ath_txq *txq = sc->sc_ac2q[ac];
4384         struct wmeParams *wmep = &ic->ic_wme.wme_chanParams.cap_wmeParams[ac];
4385         struct ath_hal *ah = sc->sc_ah;
4386         HAL_TXQ_INFO qi;
4387
4388         ath_hal_gettxqueueprops(ah, txq->axq_qnum, &qi);
4389 #ifdef IEEE80211_SUPPORT_TDMA
4390         if (sc->sc_tdma) {
4391                 /*
4392                  * AIFS is zero so there's no pre-transmit wait.  The
4393                  * burst time defines the slot duration and is configured
4394                  * through net80211.  The QCU is setup to not do post-xmit
4395                  * back off, lockout all lower-priority QCU's, and fire
4396                  * off the DMA beacon alert timer which is setup based
4397                  * on the slot configuration.
4398                  */
4399                 qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4400                               | HAL_TXQ_TXERRINT_ENABLE
4401                               | HAL_TXQ_TXURNINT_ENABLE
4402                               | HAL_TXQ_TXEOLINT_ENABLE
4403                               | HAL_TXQ_DBA_GATED
4404                               | HAL_TXQ_BACKOFF_DISABLE
4405                               | HAL_TXQ_ARB_LOCKOUT_GLOBAL
4406                               ;
4407                 qi.tqi_aifs = 0;
4408                 /* XXX +dbaprep? */
4409                 qi.tqi_readyTime = sc->sc_tdmaslotlen;
4410                 qi.tqi_burstTime = qi.tqi_readyTime;
4411         } else {
4412 #endif
4413                 /*
4414                  * XXX shouldn't this just use the default flags
4415                  * used in the previous queue setup?
4416                  */
4417                 qi.tqi_qflags = HAL_TXQ_TXOKINT_ENABLE
4418                               | HAL_TXQ_TXERRINT_ENABLE
4419                               | HAL_TXQ_TXDESCINT_ENABLE
4420                               | HAL_TXQ_TXURNINT_ENABLE
4421                               | HAL_TXQ_TXEOLINT_ENABLE
4422                               ;
4423                 qi.tqi_aifs = wmep->wmep_aifsn;
4424                 qi.tqi_cwmin = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmin);
4425                 qi.tqi_cwmax = ATH_EXPONENT_TO_VALUE(wmep->wmep_logcwmax);
4426                 qi.tqi_readyTime = 0;
4427                 qi.tqi_burstTime = ATH_TXOP_TO_US(wmep->wmep_txopLimit);
4428 #ifdef IEEE80211_SUPPORT_TDMA
4429         }
4430 #endif
4431
4432         DPRINTF(sc, ATH_DEBUG_RESET,
4433             "%s: Q%u qflags 0x%x aifs %u cwmin %u cwmax %u burstTime %u\n",
4434             __func__, txq->axq_qnum, qi.tqi_qflags,
4435             qi.tqi_aifs, qi.tqi_cwmin, qi.tqi_cwmax, qi.tqi_burstTime);
4436
4437         if (!ath_hal_settxqueueprops(ah, txq->axq_qnum, &qi)) {
4438                 if_printf(ifp, "unable to update hardware queue "
4439                         "parameters for %s traffic!\n",
4440                         ieee80211_wme_acnames[ac]);
4441                 return 0;
4442         } else {
4443                 ath_hal_resettxqueue(ah, txq->axq_qnum); /* push to h/w */
4444                 return 1;
4445         }
4446 #undef ATH_TXOP_TO_US
4447 #undef ATH_EXPONENT_TO_VALUE
4448 }
4449
4450 /*
4451  * Callback from the 802.11 layer to update WME parameters.
4452  */
4453 int
4454 ath_wme_update(struct ieee80211com *ic)
4455 {
4456         struct ath_softc *sc = ic->ic_ifp->if_softc;
4457
4458         return !ath_txq_update(sc, WME_AC_BE) ||
4459             !ath_txq_update(sc, WME_AC_BK) ||
4460             !ath_txq_update(sc, WME_AC_VI) ||
4461             !ath_txq_update(sc, WME_AC_VO) ? EIO : 0;
4462 }
4463
4464 /*
4465  * Reclaim resources for a setup queue.
4466  */
4467 static void
4468 ath_tx_cleanupq(struct ath_softc *sc, struct ath_txq *txq)
4469 {
4470
4471         ath_hal_releasetxqueue(sc->sc_ah, txq->axq_qnum);
4472         sc->sc_txqsetup &= ~(1<<txq->axq_qnum);
4473         ATH_TXQ_LOCK_DESTROY(txq);
4474 }
4475
4476 /*
4477  * Reclaim all tx queue resources.
4478  */
4479 static void
4480 ath_tx_cleanup(struct ath_softc *sc)
4481 {
4482         int i;
4483
4484         ATH_TXBUF_LOCK_DESTROY(sc);
4485         for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
4486                 if (ATH_TXQ_SETUP(sc, i))
4487                         ath_tx_cleanupq(sc, &sc->sc_txq[i]);
4488 }
4489
4490 /*
4491  * Return h/w rate index for an IEEE rate (w/o basic rate bit)
4492  * using the current rates in sc_rixmap.
4493  */
4494 int
4495 ath_tx_findrix(const struct ath_softc *sc, uint8_t rate)
4496 {
4497         int rix = sc->sc_rixmap[rate];
4498         /* NB: return lowest rix for invalid rate */
4499         return (rix == 0xff ? 0 : rix);
4500 }
4501
4502 static void
4503 ath_tx_update_stats(struct ath_softc *sc, struct ath_tx_status *ts,
4504     struct ath_buf *bf)
4505 {
4506         struct ieee80211_node *ni = bf->bf_node;
4507         struct ifnet *ifp = sc->sc_ifp;
4508         struct ieee80211com *ic = ifp->if_l2com;
4509         int sr, lr, pri;
4510
4511         if (ts->ts_status == 0) {
4512                 u_int8_t txant = ts->ts_antenna;
4513                 sc->sc_stats.ast_ant_tx[txant]++;
4514                 sc->sc_ant_tx[txant]++;
4515                 if (ts->ts_finaltsi != 0)
4516                         sc->sc_stats.ast_tx_altrate++;
4517                 pri = M_WME_GETAC(bf->bf_m);
4518                 if (pri >= WME_AC_VO)
4519                         ic->ic_wme.wme_hipri_traffic++;
4520                 if ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)
4521                         ni->ni_inact = ni->ni_inact_reload;
4522         } else {
4523                 if (ts->ts_status & HAL_TXERR_XRETRY)
4524                         sc->sc_stats.ast_tx_xretries++;
4525                 if (ts->ts_status & HAL_TXERR_FIFO)
4526                         sc->sc_stats.ast_tx_fifoerr++;
4527                 if (ts->ts_status & HAL_TXERR_FILT)
4528                         sc->sc_stats.ast_tx_filtered++;
4529                 if (ts->ts_status & HAL_TXERR_XTXOP)
4530                         sc->sc_stats.ast_tx_xtxop++;
4531                 if (ts->ts_status & HAL_TXERR_TIMER_EXPIRED)
4532                         sc->sc_stats.ast_tx_timerexpired++;
4533
4534                 if (bf->bf_m->m_flags & M_FF)
4535                         sc->sc_stats.ast_ff_txerr++;
4536         }
4537         /* XXX when is this valid? */
4538         if (ts->ts_flags & HAL_TX_DESC_CFG_ERR)
4539                 sc->sc_stats.ast_tx_desccfgerr++;
4540         /*
4541          * This can be valid for successful frame transmission!
4542          * If there's a TX FIFO underrun during aggregate transmission,
4543          * the MAC will pad the rest of the aggregate with delimiters.
4544          * If a BA is returned, the frame is marked as "OK" and it's up
4545          * to the TX completion code to notice which frames weren't
4546          * successfully transmitted.
4547          */
4548         if (ts->ts_flags & HAL_TX_DATA_UNDERRUN)
4549                 sc->sc_stats.ast_tx_data_underrun++;
4550         if (ts->ts_flags & HAL_TX_DELIM_UNDERRUN)
4551                 sc->sc_stats.ast_tx_delim_underrun++;
4552
4553         sr = ts->ts_shortretry;
4554         lr = ts->ts_longretry;
4555         sc->sc_stats.ast_tx_shortretry += sr;
4556         sc->sc_stats.ast_tx_longretry += lr;
4557
4558 }
4559
4560 /*
4561  * The default completion. If fail is 1, this means
4562  * "please don't retry the frame, and just return -1 status
4563  * to the net80211 stack.
4564  */
4565 void
4566 ath_tx_default_comp(struct ath_softc *sc, struct ath_buf *bf, int fail)
4567 {
4568         struct ath_tx_status *ts = &bf->bf_status.ds_txstat;
4569         int st;
4570
4571         if (fail == 1)
4572                 st = -1;
4573         else
4574                 st = ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) ?
4575                     ts->ts_status : HAL_TXERR_XRETRY;
4576
4577 #if 0
4578         if (bf->bf_state.bfs_dobaw)
4579                 device_printf(sc->sc_dev,
4580                     "%s: bf %p: seqno %d: dobaw should've been cleared!\n",
4581                     __func__,
4582                     bf,
4583                     SEQNO(bf->bf_state.bfs_seqno));
4584 #endif
4585         if (bf->bf_next != NULL)
4586                 device_printf(sc->sc_dev,
4587                     "%s: bf %p: seqno %d: bf_next not NULL!\n",
4588                     __func__,
4589                     bf,
4590                     SEQNO(bf->bf_state.bfs_seqno));
4591
4592         /*
4593          * Check if the node software queue is empty; if so
4594          * then clear the TIM.
4595          *
4596          * This needs to be done before the buffer is freed as
4597          * otherwise the node reference will have been released
4598          * and the node may not actually exist any longer.
4599          *
4600          * XXX I don't like this belonging here, but it's cleaner
4601          * to do it here right now then all the other places
4602          * where ath_tx_default_comp() is called.
4603          *
4604          * XXX TODO: during drain, ensure that the callback is
4605          * being called so we get a chance to update the TIM.
4606          */
4607         if (bf->bf_node) {
4608                 ATH_TX_LOCK(sc);
4609                 ath_tx_update_tim(sc, bf->bf_node, 0);
4610                 ATH_TX_UNLOCK(sc);
4611         }
4612
4613         /*
4614          * Do any tx complete callback.  Note this must
4615          * be done before releasing the node reference.
4616          * This will free the mbuf, release the net80211
4617          * node and recycle the ath_buf.
4618          */
4619         ath_tx_freebuf(sc, bf, st);
4620 }
4621
4622 /*
4623  * Update rate control with the given completion status.
4624  */
4625 void
4626 ath_tx_update_ratectrl(struct ath_softc *sc, struct ieee80211_node *ni,
4627     struct ath_rc_series *rc, struct ath_tx_status *ts, int frmlen,
4628     int nframes, int nbad)
4629 {
4630         struct ath_node *an;
4631
4632         /* Only for unicast frames */
4633         if (ni == NULL)
4634                 return;
4635
4636         an = ATH_NODE(ni);
4637         ATH_NODE_UNLOCK_ASSERT(an);
4638
4639         if ((ts->ts_status & HAL_TXERR_FILT) == 0) {
4640                 ATH_NODE_LOCK(an);
4641                 ath_rate_tx_complete(sc, an, rc, ts, frmlen, nframes, nbad);
4642                 ATH_NODE_UNLOCK(an);
4643         }
4644 }
4645
4646 /*
4647  * Process the completion of the given buffer.
4648  *
4649  * This calls the rate control update and then the buffer completion.
4650  * This will either free the buffer or requeue it.  In any case, the
4651  * bf pointer should be treated as invalid after this function is called.
4652  */
4653 void
4654 ath_tx_process_buf_completion(struct ath_softc *sc, struct ath_txq *txq,
4655     struct ath_tx_status *ts, struct ath_buf *bf)
4656 {
4657         struct ieee80211_node *ni = bf->bf_node;
4658
4659         ATH_TX_UNLOCK_ASSERT(sc);
4660         ATH_TXQ_UNLOCK_ASSERT(txq);
4661
4662         /* If unicast frame, update general statistics */
4663         if (ni != NULL) {
4664                 /* update statistics */
4665                 ath_tx_update_stats(sc, ts, bf);
4666         }
4667
4668         /*
4669          * Call the completion handler.
4670          * The completion handler is responsible for
4671          * calling the rate control code.
4672          *
4673          * Frames with no completion handler get the
4674          * rate control code called here.
4675          */
4676         if (bf->bf_comp == NULL) {
4677                 if ((ts->ts_status & HAL_TXERR_FILT) == 0 &&
4678                     (bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0) {
4679                         /*
4680                          * XXX assume this isn't an aggregate
4681                          * frame.
4682                          */
4683                         ath_tx_update_ratectrl(sc, ni,
4684                              bf->bf_state.bfs_rc, ts,
4685                             bf->bf_state.bfs_pktlen, 1,
4686                             (ts->ts_status == 0 ? 0 : 1));
4687                 }
4688                 ath_tx_default_comp(sc, bf, 0);
4689         } else
4690                 bf->bf_comp(sc, bf, 0);
4691 }
4692
4693
4694
4695 /*
4696  * Process completed xmit descriptors from the specified queue.
4697  * Kick the packet scheduler if needed. This can occur from this
4698  * particular task.
4699  */
4700 static int
4701 ath_tx_processq(struct ath_softc *sc, struct ath_txq *txq, int dosched)
4702 {
4703         struct ath_hal *ah = sc->sc_ah;
4704         struct ath_buf *bf;
4705         struct ath_desc *ds;
4706         struct ath_tx_status *ts;
4707         struct ieee80211_node *ni;
4708 #ifdef  IEEE80211_SUPPORT_SUPERG
4709         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
4710 #endif  /* IEEE80211_SUPPORT_SUPERG */
4711         int nacked;
4712         HAL_STATUS status;
4713
4714         DPRINTF(sc, ATH_DEBUG_TX_PROC, "%s: tx queue %u head %p link %p\n",
4715                 __func__, txq->axq_qnum,
4716                 (caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4717                 txq->axq_link);
4718
4719         ATH_KTR(sc, ATH_KTR_TXCOMP, 4,
4720             "ath_tx_processq: txq=%u head %p link %p depth %p",
4721             txq->axq_qnum,
4722             (caddr_t)(uintptr_t) ath_hal_gettxbuf(sc->sc_ah, txq->axq_qnum),
4723             txq->axq_link,
4724             txq->axq_depth);
4725
4726         nacked = 0;
4727         for (;;) {
4728                 ATH_TXQ_LOCK(txq);
4729                 txq->axq_intrcnt = 0;   /* reset periodic desc intr count */
4730                 bf = TAILQ_FIRST(&txq->axq_q);
4731                 if (bf == NULL) {
4732                         ATH_TXQ_UNLOCK(txq);
4733                         break;
4734                 }
4735                 ds = bf->bf_lastds;     /* XXX must be setup correctly! */
4736                 ts = &bf->bf_status.ds_txstat;
4737
4738                 status = ath_hal_txprocdesc(ah, ds, ts);
4739 #ifdef ATH_DEBUG
4740                 if (sc->sc_debug & ATH_DEBUG_XMIT_DESC)
4741                         ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4742                             status == HAL_OK);
4743                 else if ((sc->sc_debug & ATH_DEBUG_RESET) && (dosched == 0))
4744                         ath_printtxbuf(sc, bf, txq->axq_qnum, 0,
4745                             status == HAL_OK);
4746 #endif
4747 #ifdef  ATH_DEBUG_ALQ
4748                 if (if_ath_alq_checkdebug(&sc->sc_alq,
4749                     ATH_ALQ_EDMA_TXSTATUS)) {
4750                         if_ath_alq_post(&sc->sc_alq, ATH_ALQ_EDMA_TXSTATUS,
4751                         sc->sc_tx_statuslen,
4752                         (char *) ds);
4753                 }
4754 #endif
4755
4756                 if (status == HAL_EINPROGRESS) {
4757                         ATH_KTR(sc, ATH_KTR_TXCOMP, 3,
4758                             "ath_tx_processq: txq=%u, bf=%p ds=%p, HAL_EINPROGRESS",
4759                             txq->axq_qnum, bf, ds);
4760                         ATH_TXQ_UNLOCK(txq);
4761                         break;
4762                 }
4763                 ATH_TXQ_REMOVE(txq, bf, bf_list);
4764
4765                 /*
4766                  * Sanity check.
4767                  */
4768                 if (txq->axq_qnum != bf->bf_state.bfs_tx_queue) {
4769                         device_printf(sc->sc_dev,
4770                             "%s: TXQ=%d: bf=%p, bfs_tx_queue=%d\n",
4771                             __func__,
4772                             txq->axq_qnum,
4773                             bf,
4774                             bf->bf_state.bfs_tx_queue);
4775                 }
4776                 if (txq->axq_qnum != bf->bf_last->bf_state.bfs_tx_queue) {
4777                         device_printf(sc->sc_dev,
4778                             "%s: TXQ=%d: bf_last=%p, bfs_tx_queue=%d\n",
4779                             __func__,
4780                             txq->axq_qnum,
4781                             bf->bf_last,
4782                             bf->bf_last->bf_state.bfs_tx_queue);
4783                 }
4784
4785 #if 0
4786                 if (txq->axq_depth > 0) {
4787                         /*
4788                          * More frames follow.  Mark the buffer busy
4789                          * so it's not re-used while the hardware may
4790                          * still re-read the link field in the descriptor.
4791                          *
4792                          * Use the last buffer in an aggregate as that
4793                          * is where the hardware may be - intermediate
4794                          * descriptors won't be "busy".
4795                          */
4796                         bf->bf_last->bf_flags |= ATH_BUF_BUSY;
4797                 } else
4798                         txq->axq_link = NULL;
4799 #else
4800                 bf->bf_last->bf_flags |= ATH_BUF_BUSY;
4801 #endif
4802                 if (bf->bf_state.bfs_aggr)
4803                         txq->axq_aggr_depth--;
4804
4805                 ni = bf->bf_node;
4806
4807                 ATH_KTR(sc, ATH_KTR_TXCOMP, 5,
4808                     "ath_tx_processq: txq=%u, bf=%p, ds=%p, ni=%p, ts_status=0x%08x",
4809                     txq->axq_qnum, bf, ds, ni, ts->ts_status);
4810                 /*
4811                  * If unicast frame was ack'd update RSSI,
4812                  * including the last rx time used to
4813                  * workaround phantom bmiss interrupts.
4814                  */
4815                 if (ni != NULL && ts->ts_status == 0 &&
4816                     ((bf->bf_state.bfs_txflags & HAL_TXDESC_NOACK) == 0)) {
4817                         nacked++;
4818                         sc->sc_stats.ast_tx_rssi = ts->ts_rssi;
4819                         ATH_RSSI_LPF(sc->sc_halstats.ns_avgtxrssi,
4820                                 ts->ts_rssi);
4821                 }
4822                 ATH_TXQ_UNLOCK(txq);
4823
4824                 /*
4825                  * Update statistics and call completion
4826                  */
4827                 ath_tx_process_buf_completion(sc, txq, ts, bf);
4828
4829                 /* XXX at this point, bf and ni may be totally invalid */
4830         }
4831 #ifdef IEEE80211_SUPPORT_SUPERG
4832         /*
4833          * Flush fast-frame staging queue when traffic slows.
4834          */
4835         if (txq->axq_depth <= 1)
4836                 ieee80211_ff_flush(ic, txq->axq_ac);
4837 #endif
4838
4839         /* Kick the software TXQ scheduler */
4840         if (dosched) {
4841                 ATH_TX_LOCK(sc);
4842                 ath_txq_sched(sc, txq);
4843                 ATH_TX_UNLOCK(sc);
4844         }
4845
4846         ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4847             "ath_tx_processq: txq=%u: done",
4848             txq->axq_qnum);
4849
4850         return nacked;
4851 }
4852
4853 #define TXQACTIVE(t, q)         ( (t) & (1 << (q)))
4854
4855 /*
4856  * Deferred processing of transmit interrupt; special-cased
4857  * for a single hardware transmit queue (e.g. 5210 and 5211).
4858  */
4859 static void
4860 ath_tx_proc_q0(void *arg, int npending)
4861 {
4862         struct ath_softc *sc = arg;
4863         struct ifnet *ifp = sc->sc_ifp;
4864         uint32_t txqs;
4865
4866         ATH_PCU_LOCK(sc);
4867         sc->sc_txproc_cnt++;
4868         txqs = sc->sc_txq_active;
4869         sc->sc_txq_active &= ~txqs;
4870         ATH_PCU_UNLOCK(sc);
4871
4872         ATH_LOCK(sc);
4873         ath_power_set_power_state(sc, HAL_PM_AWAKE);
4874         ATH_UNLOCK(sc);
4875
4876         ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4877             "ath_tx_proc_q0: txqs=0x%08x", txqs);
4878
4879         if (TXQACTIVE(txqs, 0) && ath_tx_processq(sc, &sc->sc_txq[0], 1))
4880                 /* XXX why is lastrx updated in tx code? */
4881                 sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4882         if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
4883                 ath_tx_processq(sc, sc->sc_cabq, 1);
4884         IF_LOCK(&ifp->if_snd);
4885 #if defined(__DragonFly__)
4886         ifq_clr_oactive(&ifp->if_snd);
4887 #else
4888         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4889 #endif
4890         IF_UNLOCK(&ifp->if_snd);
4891         sc->sc_wd_timer = 0;
4892
4893         if (sc->sc_softled)
4894                 ath_led_event(sc, sc->sc_txrix);
4895
4896         ATH_PCU_LOCK(sc);
4897         sc->sc_txproc_cnt--;
4898         ATH_PCU_UNLOCK(sc);
4899
4900         ATH_LOCK(sc);
4901         ath_power_restore_power_state(sc);
4902         ATH_UNLOCK(sc);
4903
4904         ath_tx_kick(sc);
4905 }
4906
4907 /*
4908  * Deferred processing of transmit interrupt; special-cased
4909  * for four hardware queues, 0-3 (e.g. 5212 w/ WME support).
4910  */
4911 static void
4912 ath_tx_proc_q0123(void *arg, int npending)
4913 {
4914         struct ath_softc *sc = arg;
4915         struct ifnet *ifp = sc->sc_ifp;
4916         int nacked;
4917         uint32_t txqs;
4918
4919         ATH_PCU_LOCK(sc);
4920         sc->sc_txproc_cnt++;
4921         txqs = sc->sc_txq_active;
4922         sc->sc_txq_active &= ~txqs;
4923         ATH_PCU_UNLOCK(sc);
4924
4925         ATH_LOCK(sc);
4926         ath_power_set_power_state(sc, HAL_PM_AWAKE);
4927         ATH_UNLOCK(sc);
4928
4929         ATH_KTR(sc, ATH_KTR_TXCOMP, 1,
4930             "ath_tx_proc_q0123: txqs=0x%08x", txqs);
4931
4932         /*
4933          * Process each active queue.
4934          */
4935         nacked = 0;
4936         if (TXQACTIVE(txqs, 0))
4937                 nacked += ath_tx_processq(sc, &sc->sc_txq[0], 1);
4938         if (TXQACTIVE(txqs, 1))
4939                 nacked += ath_tx_processq(sc, &sc->sc_txq[1], 1);
4940         if (TXQACTIVE(txqs, 2))
4941                 nacked += ath_tx_processq(sc, &sc->sc_txq[2], 1);
4942         if (TXQACTIVE(txqs, 3))
4943                 nacked += ath_tx_processq(sc, &sc->sc_txq[3], 1);
4944         if (TXQACTIVE(txqs, sc->sc_cabq->axq_qnum))
4945                 ath_tx_processq(sc, sc->sc_cabq, 1);
4946         if (nacked)
4947                 sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
4948
4949         IF_LOCK(&ifp->if_snd);
4950 #if defined(__DragonFly__)
4951         ifq_clr_oactive(&ifp->if_snd);
4952 #else
4953         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
4954 #endif
4955         IF_UNLOCK(&ifp->if_snd);
4956         sc->sc_wd_timer = 0;
4957
4958         if (sc->sc_softled)
4959                 ath_led_event(sc, sc->sc_txrix);
4960
4961         ATH_PCU_LOCK(sc);
4962         sc->sc_txproc_cnt--;
4963         ATH_PCU_UNLOCK(sc);
4964
4965         ATH_LOCK(sc);
4966         ath_power_restore_power_state(sc);
4967         ATH_UNLOCK(sc);
4968
4969         ath_tx_kick(sc);
4970 }
4971
4972 /*
4973  * Deferred processing of transmit interrupt.
4974  */
4975 static void
4976 ath_tx_proc(void *arg, int npending)
4977 {
4978         struct ath_softc *sc = arg;
4979         struct ifnet *ifp = sc->sc_ifp;
4980         int i, nacked;
4981         uint32_t txqs;
4982
4983         ATH_PCU_LOCK(sc);
4984         sc->sc_txproc_cnt++;
4985         txqs = sc->sc_txq_active;
4986         sc->sc_txq_active &= ~txqs;
4987         ATH_PCU_UNLOCK(sc);
4988
4989         ATH_LOCK(sc);
4990         ath_power_set_power_state(sc, HAL_PM_AWAKE);
4991         ATH_UNLOCK(sc);
4992
4993         ATH_KTR(sc, ATH_KTR_TXCOMP, 1, "ath_tx_proc: txqs=0x%08x", txqs);
4994
4995         /*
4996          * Process each active queue.
4997          */
4998         nacked = 0;
4999         for (i = 0; i < HAL_NUM_TX_QUEUES; i++)
5000                 if (ATH_TXQ_SETUP(sc, i) && TXQACTIVE(txqs, i))
5001                         nacked += ath_tx_processq(sc, &sc->sc_txq[i], 1);
5002         if (nacked)
5003                 sc->sc_lastrx = ath_hal_gettsf64(sc->sc_ah);
5004
5005         /* XXX check this inside of IF_LOCK? */
5006         IF_LOCK(&ifp->if_snd);
5007 #if defined(__DragonFly__)
5008         ifq_clr_oactive(&ifp->if_snd);
5009 #else
5010         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5011 #endif
5012         IF_UNLOCK(&ifp->if_snd);
5013         sc->sc_wd_timer = 0;
5014
5015         if (sc->sc_softled)
5016                 ath_led_event(sc, sc->sc_txrix);
5017
5018         ATH_PCU_LOCK(sc);
5019         sc->sc_txproc_cnt--;
5020         ATH_PCU_UNLOCK(sc);
5021
5022         ATH_LOCK(sc);
5023         ath_power_restore_power_state(sc);
5024         ATH_UNLOCK(sc);
5025
5026         ath_tx_kick(sc);
5027 }
5028 #undef  TXQACTIVE
5029
5030 /*
5031  * Deferred processing of TXQ rescheduling.
5032  */
5033 static void
5034 ath_txq_sched_tasklet(void *arg, int npending)
5035 {
5036         struct ath_softc *sc = arg;
5037         int i;
5038
5039         /* XXX is skipping ok? */
5040         ATH_PCU_LOCK(sc);
5041 #if 0
5042         if (sc->sc_inreset_cnt > 0) {
5043                 device_printf(sc->sc_dev,
5044                     "%s: sc_inreset_cnt > 0; skipping\n", __func__);
5045                 ATH_PCU_UNLOCK(sc);
5046                 return;
5047         }
5048 #endif
5049         sc->sc_txproc_cnt++;
5050         ATH_PCU_UNLOCK(sc);
5051
5052         ATH_LOCK(sc);
5053         ath_power_set_power_state(sc, HAL_PM_AWAKE);
5054         ATH_UNLOCK(sc);
5055
5056         ATH_TX_LOCK(sc);
5057         for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
5058                 if (ATH_TXQ_SETUP(sc, i)) {
5059                         ath_txq_sched(sc, &sc->sc_txq[i]);
5060                 }
5061         }
5062         ATH_TX_UNLOCK(sc);
5063
5064         ATH_LOCK(sc);
5065         ath_power_restore_power_state(sc);
5066         ATH_UNLOCK(sc);
5067
5068         ATH_PCU_LOCK(sc);
5069         sc->sc_txproc_cnt--;
5070         ATH_PCU_UNLOCK(sc);
5071 }
5072
5073 void
5074 ath_returnbuf_tail(struct ath_softc *sc, struct ath_buf *bf)
5075 {
5076
5077         ATH_TXBUF_LOCK_ASSERT(sc);
5078
5079         if (bf->bf_flags & ATH_BUF_MGMT)
5080                 TAILQ_INSERT_TAIL(&sc->sc_txbuf_mgmt, bf, bf_list);
5081         else {
5082                 TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
5083                 sc->sc_txbuf_cnt++;
5084                 if (sc->sc_txbuf_cnt > ath_txbuf) {
5085                         device_printf(sc->sc_dev,
5086                             "%s: sc_txbuf_cnt > %d?\n",
5087                             __func__,
5088                             ath_txbuf);
5089                         sc->sc_txbuf_cnt = ath_txbuf;
5090                 }
5091         }
5092 }
5093
5094 void
5095 ath_returnbuf_head(struct ath_softc *sc, struct ath_buf *bf)
5096 {
5097
5098         ATH_TXBUF_LOCK_ASSERT(sc);
5099
5100         if (bf->bf_flags & ATH_BUF_MGMT)
5101                 TAILQ_INSERT_HEAD(&sc->sc_txbuf_mgmt, bf, bf_list);
5102         else {
5103                 TAILQ_INSERT_HEAD(&sc->sc_txbuf, bf, bf_list);
5104                 sc->sc_txbuf_cnt++;
5105                 if (sc->sc_txbuf_cnt > ATH_TXBUF) {
5106                         device_printf(sc->sc_dev,
5107                             "%s: sc_txbuf_cnt > %d?\n",
5108                             __func__,
5109                             ATH_TXBUF);
5110                         sc->sc_txbuf_cnt = ATH_TXBUF;
5111                 }
5112         }
5113 }
5114
5115 /*
5116  * Free the holding buffer if it exists
5117  */
5118 void
5119 ath_txq_freeholdingbuf(struct ath_softc *sc, struct ath_txq *txq)
5120 {
5121         ATH_TXBUF_UNLOCK_ASSERT(sc);
5122         ATH_TXQ_LOCK_ASSERT(txq);
5123
5124         if (txq->axq_holdingbf == NULL)
5125                 return;
5126
5127         txq->axq_holdingbf->bf_flags &= ~ATH_BUF_BUSY;
5128
5129         ATH_TXBUF_LOCK(sc);
5130         ath_returnbuf_tail(sc, txq->axq_holdingbf);
5131         ATH_TXBUF_UNLOCK(sc);
5132
5133         txq->axq_holdingbf = NULL;
5134 }
5135
5136 /*
5137  * Add this buffer to the holding queue, freeing the previous
5138  * one if it exists.
5139  */
5140 static void
5141 ath_txq_addholdingbuf(struct ath_softc *sc, struct ath_buf *bf)
5142 {
5143         struct ath_txq *txq;
5144
5145         txq = &sc->sc_txq[bf->bf_state.bfs_tx_queue];
5146
5147         ATH_TXBUF_UNLOCK_ASSERT(sc);
5148         ATH_TXQ_LOCK_ASSERT(txq);
5149
5150         /* XXX assert ATH_BUF_BUSY is set */
5151
5152         /* XXX assert the tx queue is under the max number */
5153         if (bf->bf_state.bfs_tx_queue > HAL_NUM_TX_QUEUES) {
5154                 device_printf(sc->sc_dev, "%s: bf=%p: invalid tx queue (%d)\n",
5155                     __func__,
5156                     bf,
5157                     bf->bf_state.bfs_tx_queue);
5158                 bf->bf_flags &= ~ATH_BUF_BUSY;
5159                 ath_returnbuf_tail(sc, bf);
5160                 return;
5161         }
5162         ath_txq_freeholdingbuf(sc, txq);
5163         txq->axq_holdingbf = bf;
5164 }
5165
5166 /*
5167  * Return a buffer to the pool and update the 'busy' flag on the
5168  * previous 'tail' entry.
5169  *
5170  * This _must_ only be called when the buffer is involved in a completed
5171  * TX. The logic is that if it was part of an active TX, the previous
5172  * buffer on the list is now not involved in a halted TX DMA queue, waiting
5173  * for restart (eg for TDMA.)
5174  *
5175  * The caller must free the mbuf and recycle the node reference.
5176  *
5177  * XXX This method of handling busy / holding buffers is insanely stupid.
5178  * It requires bf_state.bfs_tx_queue to be correctly assigned.  It would
5179  * be much nicer if buffers in the processq() methods would instead be
5180  * always completed there (pushed onto a txq or ath_bufhead) so we knew
5181  * exactly what hardware queue they came from in the first place.
5182  */
5183 void
5184 ath_freebuf(struct ath_softc *sc, struct ath_buf *bf)
5185 {
5186         struct ath_txq *txq;
5187
5188         txq = &sc->sc_txq[bf->bf_state.bfs_tx_queue];
5189
5190         KASSERT((bf->bf_node == NULL), ("%s: bf->bf_node != NULL\n", __func__));
5191         KASSERT((bf->bf_m == NULL), ("%s: bf->bf_m != NULL\n", __func__));
5192
5193         /*
5194          * If this buffer is busy, push it onto the holding queue.
5195          */
5196         if (bf->bf_flags & ATH_BUF_BUSY) {
5197                 ATH_TXQ_LOCK(txq);
5198                 ath_txq_addholdingbuf(sc, bf);
5199                 ATH_TXQ_UNLOCK(txq);
5200                 return;
5201         }
5202
5203         /*
5204          * Not a busy buffer, so free normally
5205          */
5206         ATH_TXBUF_LOCK(sc);
5207         ath_returnbuf_tail(sc, bf);
5208         ATH_TXBUF_UNLOCK(sc);
5209 }
5210
5211 /*
5212  * This is currently used by ath_tx_draintxq() and
5213  * ath_tx_tid_free_pkts().
5214  *
5215  * It recycles a single ath_buf.
5216  */
5217 void
5218 ath_tx_freebuf(struct ath_softc *sc, struct ath_buf *bf, int status)
5219 {
5220         struct ieee80211_node *ni = bf->bf_node;
5221         struct mbuf *m0 = bf->bf_m;
5222
5223         /*
5224          * Make sure that we only sync/unload if there's an mbuf.
5225          * If not (eg we cloned a buffer), the unload will have already
5226          * occured.
5227          */
5228         if (bf->bf_m != NULL) {
5229                 bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
5230                     BUS_DMASYNC_POSTWRITE);
5231                 bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
5232         }
5233
5234         bf->bf_node = NULL;
5235         bf->bf_m = NULL;
5236
5237         /* Free the buffer, it's not needed any longer */
5238         ath_freebuf(sc, bf);
5239
5240         /* Pass the buffer back to net80211 - completing it */
5241         ieee80211_tx_complete(ni, m0, status);
5242 }
5243
5244 static struct ath_buf *
5245 ath_tx_draintxq_get_one(struct ath_softc *sc, struct ath_txq *txq)
5246 {
5247         struct ath_buf *bf;
5248
5249         ATH_TXQ_LOCK_ASSERT(txq);
5250
5251         /*
5252          * Drain the FIFO queue first, then if it's
5253          * empty, move to the normal frame queue.
5254          */
5255         bf = TAILQ_FIRST(&txq->fifo.axq_q);
5256         if (bf != NULL) {
5257                 /*
5258                  * Is it the last buffer in this set?
5259                  * Decrement the FIFO counter.
5260                  */
5261                 if (bf->bf_flags & ATH_BUF_FIFOEND) {
5262                         if (txq->axq_fifo_depth == 0) {
5263                                 device_printf(sc->sc_dev,
5264                                     "%s: Q%d: fifo_depth=0, fifo.axq_depth=%d?\n",
5265                                     __func__,
5266                                     txq->axq_qnum,
5267                                     txq->fifo.axq_depth);
5268                         } else
5269                                 txq->axq_fifo_depth--;
5270                 }
5271                 ATH_TXQ_REMOVE(&txq->fifo, bf, bf_list);
5272                 return (bf);
5273         }
5274
5275         /*
5276          * Debugging!
5277          */
5278         if (txq->axq_fifo_depth != 0 || txq->fifo.axq_depth != 0) {
5279                 device_printf(sc->sc_dev,
5280                     "%s: Q%d: fifo_depth=%d, fifo.axq_depth=%d\n",
5281                     __func__,
5282                     txq->axq_qnum,
5283                     txq->axq_fifo_depth,
5284                     txq->fifo.axq_depth);
5285         }
5286
5287         /*
5288          * Now drain the pending queue.
5289          */
5290         bf = TAILQ_FIRST(&txq->axq_q);
5291         if (bf == NULL) {
5292                 txq->axq_link = NULL;
5293                 return (NULL);
5294         }
5295         ATH_TXQ_REMOVE(txq, bf, bf_list);
5296         return (bf);
5297 }
5298
5299 void
5300 ath_tx_draintxq(struct ath_softc *sc, struct ath_txq *txq)
5301 {
5302 #ifdef ATH_DEBUG
5303         struct ath_hal *ah = sc->sc_ah;
5304 #endif
5305         struct ath_buf *bf;
5306         u_int ix;
5307
5308         /*
5309          * NB: this assumes output has been stopped and
5310          *     we do not need to block ath_tx_proc
5311          */
5312         for (ix = 0;; ix++) {
5313                 ATH_TXQ_LOCK(txq);
5314                 bf = ath_tx_draintxq_get_one(sc, txq);
5315                 if (bf == NULL) {
5316                         ATH_TXQ_UNLOCK(txq);
5317                         break;
5318                 }
5319                 if (bf->bf_state.bfs_aggr)
5320                         txq->axq_aggr_depth--;
5321 #ifdef ATH_DEBUG
5322                 if (sc->sc_debug & ATH_DEBUG_RESET) {
5323                         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
5324                         int status = 0;
5325
5326                         /*
5327                          * EDMA operation has a TX completion FIFO
5328                          * separate from the TX descriptor, so this
5329                          * method of checking the "completion" status
5330                          * is wrong.
5331                          */
5332                         if (! sc->sc_isedma) {
5333                                 status = (ath_hal_txprocdesc(ah,
5334                                     bf->bf_lastds,
5335                                     &bf->bf_status.ds_txstat) == HAL_OK);
5336                         }
5337                         ath_printtxbuf(sc, bf, txq->axq_qnum, ix, status);
5338                         ieee80211_dump_pkt(ic, mtod(bf->bf_m, const uint8_t *),
5339                             bf->bf_m->m_len, 0, -1);
5340                 }
5341 #endif /* ATH_DEBUG */
5342                 /*
5343                  * Since we're now doing magic in the completion
5344                  * functions, we -must- call it for aggregation
5345                  * destinations or BAW tracking will get upset.
5346                  */
5347                 /*
5348                  * Clear ATH_BUF_BUSY; the completion handler
5349                  * will free the buffer.
5350                  */
5351                 ATH_TXQ_UNLOCK(txq);
5352                 bf->bf_flags &= ~ATH_BUF_BUSY;
5353                 if (bf->bf_comp)
5354                         bf->bf_comp(sc, bf, 1);
5355                 else
5356                         ath_tx_default_comp(sc, bf, 1);
5357         }
5358
5359         /*
5360          * Free the holding buffer if it exists
5361          */
5362         ATH_TXQ_LOCK(txq);
5363         ath_txq_freeholdingbuf(sc, txq);
5364         ATH_TXQ_UNLOCK(txq);
5365
5366         /*
5367          * Drain software queued frames which are on
5368          * active TIDs.
5369          */
5370         ath_tx_txq_drain(sc, txq);
5371 }
5372
5373 static void
5374 ath_tx_stopdma(struct ath_softc *sc, struct ath_txq *txq)
5375 {
5376         struct ath_hal *ah = sc->sc_ah;
5377
5378         ATH_TXQ_LOCK_ASSERT(txq);
5379
5380         DPRINTF(sc, ATH_DEBUG_RESET,
5381             "%s: tx queue [%u] %p, active=%d, hwpending=%d, flags 0x%08x, "
5382             "link %p, holdingbf=%p\n",
5383             __func__,
5384             txq->axq_qnum,
5385             (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, txq->axq_qnum),
5386             (int) (!! ath_hal_txqenabled(ah, txq->axq_qnum)),
5387             (int) ath_hal_numtxpending(ah, txq->axq_qnum),
5388             txq->axq_flags,
5389             txq->axq_link,
5390             txq->axq_holdingbf);
5391
5392         (void) ath_hal_stoptxdma(ah, txq->axq_qnum);
5393         /* We've stopped TX DMA, so mark this as stopped. */
5394         txq->axq_flags &= ~ATH_TXQ_PUTRUNNING;
5395
5396 #ifdef  ATH_DEBUG
5397         if ((sc->sc_debug & ATH_DEBUG_RESET)
5398             && (txq->axq_holdingbf != NULL)) {
5399                 ath_printtxbuf(sc, txq->axq_holdingbf, txq->axq_qnum, 0, 0);
5400         }
5401 #endif
5402 }
5403
5404 int
5405 ath_stoptxdma(struct ath_softc *sc)
5406 {
5407         struct ath_hal *ah = sc->sc_ah;
5408         int i;
5409
5410         /* XXX return value */
5411         if (sc->sc_invalid)
5412                 return 0;
5413
5414         if (!sc->sc_invalid) {
5415                 /* don't touch the hardware if marked invalid */
5416                 DPRINTF(sc, ATH_DEBUG_RESET, "%s: tx queue [%u] %p, link %p\n",
5417                     __func__, sc->sc_bhalq,
5418                     (caddr_t)(uintptr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq),
5419                     NULL);
5420
5421                 /* stop the beacon queue */
5422                 (void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
5423
5424                 /* Stop the data queues */
5425                 for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
5426                         if (ATH_TXQ_SETUP(sc, i)) {
5427                                 ATH_TXQ_LOCK(&sc->sc_txq[i]);
5428                                 ath_tx_stopdma(sc, &sc->sc_txq[i]);
5429                                 ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
5430                         }
5431                 }
5432         }
5433
5434         return 1;
5435 }
5436
5437 #ifdef  ATH_DEBUG
5438 void
5439 ath_tx_dump(struct ath_softc *sc, struct ath_txq *txq)
5440 {
5441         struct ath_hal *ah = sc->sc_ah;
5442         struct ath_buf *bf;
5443         int i = 0;
5444
5445         if (! (sc->sc_debug & ATH_DEBUG_RESET))
5446                 return;
5447
5448         device_printf(sc->sc_dev, "%s: Q%d: begin\n",
5449             __func__, txq->axq_qnum);
5450         TAILQ_FOREACH(bf, &txq->axq_q, bf_list) {
5451                 ath_printtxbuf(sc, bf, txq->axq_qnum, i,
5452                         ath_hal_txprocdesc(ah, bf->bf_lastds,
5453                             &bf->bf_status.ds_txstat) == HAL_OK);
5454                 i++;
5455         }
5456         device_printf(sc->sc_dev, "%s: Q%d: end\n",
5457             __func__, txq->axq_qnum);
5458 }
5459 #endif /* ATH_DEBUG */
5460
5461 /*
5462  * Drain the transmit queues and reclaim resources.
5463  */
5464 void
5465 ath_legacy_tx_drain(struct ath_softc *sc, ATH_RESET_TYPE reset_type)
5466 {
5467         struct ath_hal *ah = sc->sc_ah;
5468         struct ifnet *ifp = sc->sc_ifp;
5469         int i;
5470         struct ath_buf *bf_last;
5471
5472         (void) ath_stoptxdma(sc);
5473
5474         /*
5475          * Dump the queue contents
5476          */
5477         for (i = 0; i < HAL_NUM_TX_QUEUES; i++) {
5478                 /*
5479                  * XXX TODO: should we just handle the completed TX frames
5480                  * here, whether or not the reset is a full one or not?
5481                  */
5482                 if (ATH_TXQ_SETUP(sc, i)) {
5483 #ifdef  ATH_DEBUG
5484                         if (sc->sc_debug & ATH_DEBUG_RESET)
5485                                 ath_tx_dump(sc, &sc->sc_txq[i]);
5486 #endif  /* ATH_DEBUG */
5487                         if (reset_type == ATH_RESET_NOLOSS) {
5488                                 ath_tx_processq(sc, &sc->sc_txq[i], 0);
5489                                 ATH_TXQ_LOCK(&sc->sc_txq[i]);
5490                                 /*
5491                                  * Free the holding buffer; DMA is now
5492                                  * stopped.
5493                                  */
5494                                 ath_txq_freeholdingbuf(sc, &sc->sc_txq[i]);
5495                                 /*
5496                                  * Setup the link pointer to be the
5497                                  * _last_ buffer/descriptor in the list.
5498                                  * If there's nothing in the list, set it
5499                                  * to NULL.
5500                                  */
5501                                 bf_last = ATH_TXQ_LAST(&sc->sc_txq[i],
5502                                     axq_q_s);
5503                                 if (bf_last != NULL) {
5504                                         ath_hal_gettxdesclinkptr(ah,
5505                                             bf_last->bf_lastds,
5506                                             &sc->sc_txq[i].axq_link);
5507                                 } else {
5508                                         sc->sc_txq[i].axq_link = NULL;
5509                                 }
5510                                 ATH_TXQ_UNLOCK(&sc->sc_txq[i]);
5511                         } else
5512                                 ath_tx_draintxq(sc, &sc->sc_txq[i]);
5513                 }
5514         }
5515 #ifdef ATH_DEBUG
5516         if (sc->sc_debug & ATH_DEBUG_RESET) {
5517                 struct ath_buf *bf = TAILQ_FIRST(&sc->sc_bbuf);
5518                 if (bf != NULL && bf->bf_m != NULL) {
5519                         ath_printtxbuf(sc, bf, sc->sc_bhalq, 0,
5520                                 ath_hal_txprocdesc(ah, bf->bf_lastds,
5521                                     &bf->bf_status.ds_txstat) == HAL_OK);
5522                         ieee80211_dump_pkt(ifp->if_l2com,
5523                             mtod(bf->bf_m, const uint8_t *), bf->bf_m->m_len,
5524                             0, -1);
5525                 }
5526         }
5527 #endif /* ATH_DEBUG */
5528         IF_LOCK(&ifp->if_snd);
5529 #if defined(__DragonFly__)
5530         ifq_clr_oactive(&ifp->if_snd);
5531 #else
5532         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5533 #endif
5534         IF_UNLOCK(&ifp->if_snd);
5535         sc->sc_wd_timer = 0;
5536 }
5537
5538 /*
5539  * Update internal state after a channel change.
5540  */
5541 static void
5542 ath_chan_change(struct ath_softc *sc, struct ieee80211_channel *chan)
5543 {
5544         enum ieee80211_phymode mode;
5545
5546         /*
5547          * Change channels and update the h/w rate map
5548          * if we're switching; e.g. 11a to 11b/g.
5549          */
5550         mode = ieee80211_chan2mode(chan);
5551         if (mode != sc->sc_curmode)
5552                 ath_setcurmode(sc, mode);
5553         sc->sc_curchan = chan;
5554 }
5555
5556 /*
5557  * Set/change channels.  If the channel is really being changed,
5558  * it's done by resetting the chip.  To accomplish this we must
5559  * first cleanup any pending DMA, then restart stuff after a la
5560  * ath_init.
5561  */
5562 static int
5563 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
5564 {
5565         struct ifnet *ifp = sc->sc_ifp;
5566         struct ieee80211com *ic = ifp->if_l2com;
5567         struct ath_hal *ah = sc->sc_ah;
5568         int ret = 0;
5569
5570         /* Treat this as an interface reset */
5571         ATH_PCU_UNLOCK_ASSERT(sc);
5572         ATH_UNLOCK_ASSERT(sc);
5573
5574         /* (Try to) stop TX/RX from occuring */
5575         taskqueue_block(sc->sc_tq);
5576
5577         ATH_PCU_LOCK(sc);
5578
5579         /* Disable interrupts */
5580         ath_hal_intrset(ah, 0);
5581
5582         /* Stop new RX/TX/interrupt completion */
5583         if (ath_reset_grablock(sc, 1) == 0) {
5584                 device_printf(sc->sc_dev, "%s: concurrent reset! Danger!\n",
5585                     __func__);
5586         }
5587
5588         /* Stop pending RX/TX completion */
5589         ath_txrx_stop_locked(sc);
5590
5591         ATH_PCU_UNLOCK(sc);
5592
5593         DPRINTF(sc, ATH_DEBUG_RESET, "%s: %u (%u MHz, flags 0x%x)\n",
5594             __func__, ieee80211_chan2ieee(ic, chan),
5595             chan->ic_freq, chan->ic_flags);
5596         if (chan != sc->sc_curchan) {
5597                 HAL_STATUS status;
5598                 /*
5599                  * To switch channels clear any pending DMA operations;
5600                  * wait long enough for the RX fifo to drain, reset the
5601                  * hardware at the new frequency, and then re-enable
5602                  * the relevant bits of the h/w.
5603                  */
5604 #if 0
5605                 ath_hal_intrset(ah, 0);         /* disable interrupts */
5606 #endif
5607                 ath_stoprecv(sc, 1);            /* turn off frame recv */
5608                 /*
5609                  * First, handle completed TX/RX frames.
5610                  */
5611                 ath_rx_flush(sc);
5612                 ath_draintxq(sc, ATH_RESET_NOLOSS);
5613                 /*
5614                  * Next, flush the non-scheduled frames.
5615                  */
5616                 ath_draintxq(sc, ATH_RESET_FULL);       /* clear pending tx frames */
5617
5618                 ath_update_chainmasks(sc, chan);
5619                 ath_hal_setchainmasks(sc->sc_ah, sc->sc_cur_txchainmask,
5620                     sc->sc_cur_rxchainmask);
5621                 if (!ath_hal_reset(ah, sc->sc_opmode, chan, AH_TRUE, &status)) {
5622                         if_printf(ifp, "%s: unable to reset "
5623                             "channel %u (%u MHz, flags 0x%x), hal status %u\n",
5624                             __func__, ieee80211_chan2ieee(ic, chan),
5625                             chan->ic_freq, chan->ic_flags, status);
5626                         ret = EIO;
5627                         goto finish;
5628                 }
5629                 sc->sc_diversity = ath_hal_getdiversity(ah);
5630
5631                 ATH_RX_LOCK(sc);
5632                 sc->sc_rx_stopped = 1;
5633                 sc->sc_rx_resetted = 1;
5634                 ATH_RX_UNLOCK(sc);
5635
5636                 /* Let DFS at it in case it's a DFS channel */
5637                 ath_dfs_radar_enable(sc, chan);
5638
5639                 /* Let spectral at in case spectral is enabled */
5640                 ath_spectral_enable(sc, chan);
5641
5642                 /*
5643                  * Let bluetooth coexistence at in case it's needed for this
5644                  * channel
5645                  */
5646                 ath_btcoex_enable(sc, ic->ic_curchan);
5647
5648                 /*
5649                  * If we're doing TDMA, enforce the TXOP limitation for chips
5650                  * that support it.
5651                  */
5652                 if (sc->sc_hasenforcetxop && sc->sc_tdma)
5653                         ath_hal_setenforcetxop(sc->sc_ah, 1);
5654                 else
5655                         ath_hal_setenforcetxop(sc->sc_ah, 0);
5656
5657                 /*
5658                  * Re-enable rx framework.
5659                  */
5660                 if (ath_startrecv(sc) != 0) {
5661                         if_printf(ifp, "%s: unable to restart recv logic\n",
5662                             __func__);
5663                         ret = EIO;
5664                         goto finish;
5665                 }
5666
5667                 /*
5668                  * Change channels and update the h/w rate map
5669                  * if we're switching; e.g. 11a to 11b/g.
5670                  */
5671                 ath_chan_change(sc, chan);
5672
5673                 /*
5674                  * Reset clears the beacon timers; reset them
5675                  * here if needed.
5676                  */
5677                 if (sc->sc_beacons) {           /* restart beacons */
5678 #ifdef IEEE80211_SUPPORT_TDMA
5679                         if (sc->sc_tdma)
5680                                 ath_tdma_config(sc, NULL);
5681                         else
5682 #endif
5683                         ath_beacon_config(sc, NULL);
5684                 }
5685
5686                 /*
5687                  * Re-enable interrupts.
5688                  */
5689 #if 0
5690                 ath_hal_intrset(ah, sc->sc_imask);
5691 #endif
5692         }
5693
5694 finish:
5695         ATH_PCU_LOCK(sc);
5696         sc->sc_inreset_cnt--;
5697         /* XXX only do this if sc_inreset_cnt == 0? */
5698         ath_hal_intrset(ah, sc->sc_imask);
5699         ATH_PCU_UNLOCK(sc);
5700
5701         IF_LOCK(&ifp->if_snd);
5702 #if defined(__DragonFly__)
5703         ifq_clr_oactive(&ifp->if_snd);
5704 #else
5705         ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
5706 #endif
5707         IF_UNLOCK(&ifp->if_snd);
5708         ath_txrx_start(sc);
5709         /* XXX ath_start? */
5710
5711         return ret;
5712 }
5713
5714 /*
5715  * Periodically recalibrate the PHY to account
5716  * for temperature/environment changes.
5717  */
5718 static void
5719 ath_calibrate(void *arg)
5720 {
5721         struct ath_softc *sc = arg;
5722         struct ath_hal *ah = sc->sc_ah;
5723         struct ifnet *ifp = sc->sc_ifp;
5724         struct ieee80211com *ic = ifp->if_l2com;
5725         HAL_BOOL longCal, isCalDone = AH_TRUE;
5726         HAL_BOOL aniCal, shortCal = AH_FALSE;
5727         int nextcal;
5728
5729         ATH_LOCK_ASSERT(sc);
5730
5731         /*
5732          * Force the hardware awake for ANI work.
5733          */
5734         ath_power_set_power_state(sc, HAL_PM_AWAKE);
5735
5736         /* Skip trying to do this if we're in reset */
5737         if (sc->sc_inreset_cnt)
5738                 goto restart;
5739
5740         if (ic->ic_flags & IEEE80211_F_SCAN)    /* defer, off channel */
5741                 goto restart;
5742         longCal = (ticks - sc->sc_lastlongcal >= ath_longcalinterval*hz);
5743         aniCal = (ticks - sc->sc_lastani >= ath_anicalinterval*hz/1000);
5744         if (sc->sc_doresetcal)
5745                 shortCal = (ticks - sc->sc_lastshortcal >= ath_shortcalinterval*hz/1000);
5746
5747         DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: shortCal=%d; longCal=%d; aniCal=%d\n", __func__, shortCal, longCal, aniCal);
5748         if (aniCal) {
5749                 sc->sc_stats.ast_ani_cal++;
5750                 sc->sc_lastani = ticks;
5751                 ath_hal_ani_poll(ah, sc->sc_curchan);
5752         }
5753
5754         if (longCal) {
5755                 sc->sc_stats.ast_per_cal++;
5756                 sc->sc_lastlongcal = ticks;
5757                 if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
5758                         /*
5759                          * Rfgain is out of bounds, reset the chip
5760                          * to load new gain values.
5761                          */
5762                         DPRINTF(sc, ATH_DEBUG_CALIBRATE,
5763                                 "%s: rfgain change\n", __func__);
5764                         sc->sc_stats.ast_per_rfgain++;
5765                         sc->sc_resetcal = 0;
5766                         sc->sc_doresetcal = AH_TRUE;
5767                         taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
5768                         callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
5769                         ath_power_restore_power_state(sc);
5770                         return;
5771                 }
5772                 /*
5773                  * If this long cal is after an idle period, then
5774                  * reset the data collection state so we start fresh.
5775                  */
5776                 if (sc->sc_resetcal) {
5777                         (void) ath_hal_calreset(ah, sc->sc_curchan);
5778                         sc->sc_lastcalreset = ticks;
5779                         sc->sc_lastshortcal = ticks;
5780                         sc->sc_resetcal = 0;
5781                         sc->sc_doresetcal = AH_TRUE;
5782                 }
5783         }
5784
5785         /* Only call if we're doing a short/long cal, not for ANI calibration */
5786         if (shortCal || longCal) {
5787                 isCalDone = AH_FALSE;
5788                 if (ath_hal_calibrateN(ah, sc->sc_curchan, longCal, &isCalDone)) {
5789                         if (longCal) {
5790                                 /*
5791                                  * Calibrate noise floor data again in case of change.
5792                                  */
5793                                 ath_hal_process_noisefloor(ah);
5794                         }
5795                 } else {
5796                         DPRINTF(sc, ATH_DEBUG_ANY,
5797                                 "%s: calibration of channel %u failed\n",
5798                                 __func__, sc->sc_curchan->ic_freq);
5799                         sc->sc_stats.ast_per_calfail++;
5800                 }
5801                 if (shortCal)
5802                         sc->sc_lastshortcal = ticks;
5803         }
5804         if (!isCalDone) {
5805 restart:
5806                 /*
5807                  * Use a shorter interval to potentially collect multiple
5808                  * data samples required to complete calibration.  Once
5809                  * we're told the work is done we drop back to a longer
5810                  * interval between requests.  We're more aggressive doing
5811                  * work when operating as an AP to improve operation right
5812                  * after startup.
5813                  */
5814                 sc->sc_lastshortcal = ticks;
5815                 nextcal = ath_shortcalinterval*hz/1000;
5816                 if (sc->sc_opmode != HAL_M_HOSTAP)
5817                         nextcal *= 10;
5818                 sc->sc_doresetcal = AH_TRUE;
5819         } else {
5820                 /* nextcal should be the shortest time for next event */
5821                 nextcal = ath_longcalinterval*hz;
5822                 if (sc->sc_lastcalreset == 0)
5823                         sc->sc_lastcalreset = sc->sc_lastlongcal;
5824                 else if (ticks - sc->sc_lastcalreset >= ath_resetcalinterval*hz)
5825                         sc->sc_resetcal = 1;    /* setup reset next trip */
5826                 sc->sc_doresetcal = AH_FALSE;
5827         }
5828         /* ANI calibration may occur more often than short/long/resetcal */
5829         if (ath_anicalinterval > 0)
5830                 nextcal = MIN(nextcal, ath_anicalinterval*hz/1000);
5831
5832         if (nextcal != 0) {
5833                 DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: next +%u (%sisCalDone)\n",
5834                     __func__, nextcal, isCalDone ? "" : "!");
5835                 callout_reset(&sc->sc_cal_ch, nextcal, ath_calibrate, sc);
5836         } else {
5837                 DPRINTF(sc, ATH_DEBUG_CALIBRATE, "%s: calibration disabled\n",
5838                     __func__);
5839                 /* NB: don't rearm timer */
5840         }
5841         /*
5842          * Restore power state now that we're done.
5843          */
5844         ath_power_restore_power_state(sc);
5845 }
5846
5847 static void
5848 ath_scan_start(struct ieee80211com *ic)
5849 {
5850         struct ifnet *ifp = ic->ic_ifp;
5851         struct ath_softc *sc = ifp->if_softc;
5852         struct ath_hal *ah = sc->sc_ah;
5853         u_int32_t rfilt;
5854
5855         /* XXX calibration timer? */
5856
5857         ATH_LOCK(sc);
5858         sc->sc_scanning = 1;
5859         sc->sc_syncbeacon = 0;
5860         rfilt = ath_calcrxfilter(sc);
5861         ATH_UNLOCK(sc);
5862
5863         ATH_PCU_LOCK(sc);
5864         ath_hal_setrxfilter(ah, rfilt);
5865         ath_hal_setassocid(ah, ifp->if_broadcastaddr, 0);
5866         ATH_PCU_UNLOCK(sc);
5867
5868         DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0\n",
5869                  __func__, rfilt, ether_sprintf(ifp->if_broadcastaddr));
5870 }
5871
5872 static void
5873 ath_scan_end(struct ieee80211com *ic)
5874 {
5875         struct ifnet *ifp = ic->ic_ifp;
5876         struct ath_softc *sc = ifp->if_softc;
5877         struct ath_hal *ah = sc->sc_ah;
5878         u_int32_t rfilt;
5879
5880         ATH_LOCK(sc);
5881         sc->sc_scanning = 0;
5882         rfilt = ath_calcrxfilter(sc);
5883         ATH_UNLOCK(sc);
5884
5885         ATH_PCU_LOCK(sc);
5886         ath_hal_setrxfilter(ah, rfilt);
5887         ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
5888
5889         ath_hal_process_noisefloor(ah);
5890         ATH_PCU_UNLOCK(sc);
5891
5892         DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
5893                  __func__, rfilt, ether_sprintf(sc->sc_curbssid),
5894                  sc->sc_curaid);
5895 }
5896
5897 #ifdef  ATH_ENABLE_11N
5898 /*
5899  * For now, just do a channel change.
5900  *
5901  * Later, we'll go through the hard slog of suspending tx/rx, changing rate
5902  * control state and resetting the hardware without dropping frames out
5903  * of the queue.
5904  *
5905  * The unfortunate trouble here is making absolutely sure that the
5906  * channel width change has propagated enough so the hardware
5907  * absolutely isn't handed bogus frames for it's current operating
5908  * mode. (Eg, 40MHz frames in 20MHz mode.) Since TX and RX can and
5909  * does occur in parallel, we need to make certain we've blocked
5910  * any further ongoing TX (and RX, that can cause raw TX)
5911  * before we do this.
5912  */
5913 static void
5914 ath_update_chw(struct ieee80211com *ic)
5915 {
5916         struct ifnet *ifp = ic->ic_ifp;
5917         struct ath_softc *sc = ifp->if_softc;
5918
5919         DPRINTF(sc, ATH_DEBUG_STATE, "%s: called\n", __func__);
5920         ath_set_channel(ic);
5921 }
5922 #endif  /* ATH_ENABLE_11N */
5923
5924 static void
5925 ath_set_channel(struct ieee80211com *ic)
5926 {
5927         struct ifnet *ifp = ic->ic_ifp;
5928         struct ath_softc *sc = ifp->if_softc;
5929
5930         ATH_LOCK(sc);
5931         ath_power_set_power_state(sc, HAL_PM_AWAKE);
5932         ATH_UNLOCK(sc);
5933
5934         (void) ath_chan_set(sc, ic->ic_curchan);
5935         /*
5936          * If we are returning to our bss channel then mark state
5937          * so the next recv'd beacon's tsf will be used to sync the
5938          * beacon timers.  Note that since we only hear beacons in
5939          * sta/ibss mode this has no effect in other operating modes.
5940          */
5941         ATH_LOCK(sc);
5942         if (!sc->sc_scanning && ic->ic_curchan == ic->ic_bsschan)
5943                 sc->sc_syncbeacon = 1;
5944         ath_power_restore_power_state(sc);
5945         ATH_UNLOCK(sc);
5946 }
5947
5948 /*
5949  * Walk the vap list and check if there any vap's in RUN state.
5950  */
5951 static int
5952 ath_isanyrunningvaps(struct ieee80211vap *this)
5953 {
5954         struct ieee80211com *ic = this->iv_ic;
5955         struct ieee80211vap *vap;
5956
5957         IEEE80211_LOCK_ASSERT(ic);
5958
5959         TAILQ_FOREACH(vap, &ic->ic_vaps, iv_next) {
5960                 if (vap != this && vap->iv_state >= IEEE80211_S_RUN)
5961                         return 1;
5962         }
5963         return 0;
5964 }
5965
5966 static int
5967 ath_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
5968 {
5969         struct ieee80211com *ic = vap->iv_ic;
5970         struct ath_softc *sc = ic->ic_ifp->if_softc;
5971         struct ath_vap *avp = ATH_VAP(vap);
5972         struct ath_hal *ah = sc->sc_ah;
5973         struct ieee80211_node *ni = NULL;
5974         int i, error, stamode;
5975         u_int32_t rfilt;
5976         int csa_run_transition = 0;
5977         enum ieee80211_state ostate = vap->iv_state;
5978
5979         static const HAL_LED_STATE leds[] = {
5980             HAL_LED_INIT,       /* IEEE80211_S_INIT */
5981             HAL_LED_SCAN,       /* IEEE80211_S_SCAN */
5982             HAL_LED_AUTH,       /* IEEE80211_S_AUTH */
5983             HAL_LED_ASSOC,      /* IEEE80211_S_ASSOC */
5984             HAL_LED_RUN,        /* IEEE80211_S_CAC */
5985             HAL_LED_RUN,        /* IEEE80211_S_RUN */
5986             HAL_LED_RUN,        /* IEEE80211_S_CSA */
5987             HAL_LED_RUN,        /* IEEE80211_S_SLEEP */
5988         };
5989
5990         DPRINTF(sc, ATH_DEBUG_STATE, "%s: %s -> %s\n", __func__,
5991                 ieee80211_state_name[ostate],
5992                 ieee80211_state_name[nstate]);
5993
5994         /*
5995          * net80211 _should_ have the comlock asserted at this point.
5996          * There are some comments around the calls to vap->iv_newstate
5997          * which indicate that it (newstate) may end up dropping the
5998          * lock.  This and the subsequent lock assert check after newstate
5999          * are an attempt to catch these and figure out how/why.
6000          */
6001         IEEE80211_LOCK_ASSERT(ic);
6002
6003         /* Before we touch the hardware - wake it up */
6004         ATH_LOCK(sc);
6005         /*
6006          * If the NIC is in anything other than SLEEP state,
6007          * we need to ensure that self-generated frames are
6008          * set for PWRMGT=0.  Otherwise we may end up with
6009          * strange situations.
6010          *
6011          * XXX TODO: is this actually the case? :-)
6012          */
6013         if (nstate != IEEE80211_S_SLEEP)
6014                 ath_power_setselfgen(sc, HAL_PM_AWAKE);
6015
6016         /*
6017          * Now, wake the thing up.
6018          */
6019         ath_power_set_power_state(sc, HAL_PM_AWAKE);
6020
6021         /*
6022          * And stop the calibration callout whilst we have
6023          * ATH_LOCK held.
6024          */
6025         callout_stop_sync(&sc->sc_cal_ch);
6026         ATH_UNLOCK(sc);
6027
6028         if (ostate == IEEE80211_S_CSA && nstate == IEEE80211_S_RUN)
6029                 csa_run_transition = 1;
6030
6031         ath_hal_setledstate(ah, leds[nstate]);  /* set LED */
6032
6033         if (nstate == IEEE80211_S_SCAN) {
6034                 /*
6035                  * Scanning: turn off beacon miss and don't beacon.
6036                  * Mark beacon state so when we reach RUN state we'll
6037                  * [re]setup beacons.  Unblock the task q thread so
6038                  * deferred interrupt processing is done.
6039                  */
6040
6041                 /* Ensure we stay awake during scan */
6042                 ATH_LOCK(sc);
6043                 ath_power_setselfgen(sc, HAL_PM_AWAKE);
6044                 ath_power_setpower(sc, HAL_PM_AWAKE);
6045                 ATH_UNLOCK(sc);
6046
6047                 ath_hal_intrset(ah,
6048                     sc->sc_imask &~ (HAL_INT_SWBA | HAL_INT_BMISS));
6049                 sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
6050                 sc->sc_beacons = 0;
6051                 taskqueue_unblock(sc->sc_tq);
6052         }
6053
6054         ni = ieee80211_ref_node(vap->iv_bss);
6055         rfilt = ath_calcrxfilter(sc);
6056         stamode = (vap->iv_opmode == IEEE80211_M_STA ||
6057                    vap->iv_opmode == IEEE80211_M_AHDEMO ||
6058                    vap->iv_opmode == IEEE80211_M_IBSS);
6059
6060         /*
6061          * XXX Dont need to do this (and others) if we've transitioned
6062          * from SLEEP->RUN.
6063          */
6064         if (stamode && nstate == IEEE80211_S_RUN) {
6065                 sc->sc_curaid = ni->ni_associd;
6066                 IEEE80211_ADDR_COPY(sc->sc_curbssid, ni->ni_bssid);
6067                 ath_hal_setassocid(ah, sc->sc_curbssid, sc->sc_curaid);
6068         }
6069         DPRINTF(sc, ATH_DEBUG_STATE, "%s: RX filter 0x%x bssid %s aid 0x%x\n",
6070            __func__, rfilt, ether_sprintf(sc->sc_curbssid), sc->sc_curaid);
6071         ath_hal_setrxfilter(ah, rfilt);
6072
6073         /* XXX is this to restore keycache on resume? */
6074         if (vap->iv_opmode != IEEE80211_M_STA &&
6075             (vap->iv_flags & IEEE80211_F_PRIVACY)) {
6076                 for (i = 0; i < IEEE80211_WEP_NKID; i++)
6077                         if (ath_hal_keyisvalid(ah, i))
6078                                 ath_hal_keysetmac(ah, i, ni->ni_bssid);
6079         }
6080
6081         /*
6082          * Invoke the parent method to do net80211 work.
6083          */
6084         error = avp->av_newstate(vap, nstate, arg);
6085         if (error != 0)
6086                 goto bad;
6087
6088         /*
6089          * See above: ensure av_newstate() doesn't drop the lock
6090          * on us.
6091          */
6092         IEEE80211_LOCK_ASSERT(ic);
6093
6094         if (nstate == IEEE80211_S_RUN) {
6095                 /* NB: collect bss node again, it may have changed */
6096                 ieee80211_free_node(ni);
6097                 ni = ieee80211_ref_node(vap->iv_bss);
6098
6099                 DPRINTF(sc, ATH_DEBUG_STATE,
6100                     "%s(RUN): iv_flags 0x%08x bintvl %d bssid %s "
6101                     "capinfo 0x%04x chan %d\n", __func__,
6102                     vap->iv_flags, ni->ni_intval, ether_sprintf(ni->ni_bssid),
6103                     ni->ni_capinfo, ieee80211_chan2ieee(ic, ic->ic_curchan));
6104
6105                 switch (vap->iv_opmode) {
6106 #ifdef IEEE80211_SUPPORT_TDMA
6107                 case IEEE80211_M_AHDEMO:
6108                         if ((vap->iv_caps & IEEE80211_C_TDMA) == 0)
6109                                 break;
6110                         /* fall thru... */
6111 #endif
6112                 case IEEE80211_M_HOSTAP:
6113                 case IEEE80211_M_IBSS:
6114                 case IEEE80211_M_MBSS:
6115                         /*
6116                          * Allocate and setup the beacon frame.
6117                          *
6118                          * Stop any previous beacon DMA.  This may be
6119                          * necessary, for example, when an ibss merge
6120                          * causes reconfiguration; there will be a state
6121                          * transition from RUN->RUN that means we may
6122                          * be called with beacon transmission active.
6123                          */
6124                         ath_hal_stoptxdma(ah, sc->sc_bhalq);
6125
6126                         error = ath_beacon_alloc(sc, ni);
6127                         if (error != 0)
6128                                 goto bad;
6129                         /*
6130                          * If joining an adhoc network defer beacon timer
6131                          * configuration to the next beacon frame so we
6132                          * have a current TSF to use.  Otherwise we're
6133                          * starting an ibss/bss so there's no need to delay;
6134                          * if this is the first vap moving to RUN state, then
6135                          * beacon state needs to be [re]configured.
6136                          */
6137                         if (vap->iv_opmode == IEEE80211_M_IBSS &&
6138                             ni->ni_tstamp.tsf != 0) {
6139                                 sc->sc_syncbeacon = 1;
6140                         } else if (!sc->sc_beacons) {
6141 #ifdef IEEE80211_SUPPORT_TDMA
6142                                 if (vap->iv_caps & IEEE80211_C_TDMA)
6143                                         ath_tdma_config(sc, vap);
6144                                 else
6145 #endif
6146                                         ath_beacon_config(sc, vap);
6147                                 sc->sc_beacons = 1;
6148                         }
6149                         break;
6150                 case IEEE80211_M_STA:
6151                         /*
6152                          * Defer beacon timer configuration to the next
6153                          * beacon frame so we have a current TSF to use
6154                          * (any TSF collected when scanning is likely old).
6155                          * However if it's due to a CSA -> RUN transition,
6156                          * force a beacon update so we pick up a lack of
6157                          * beacons from an AP in CAC and thus force a
6158                          * scan.
6159                          *
6160                          * And, there's also corner cases here where
6161                          * after a scan, the AP may have disappeared.
6162                          * In that case, we may not receive an actual
6163                          * beacon to update the beacon timer and thus we
6164                          * won't get notified of the missing beacons.
6165                          */
6166                         if (ostate != IEEE80211_S_RUN &&
6167                             ostate != IEEE80211_S_SLEEP) {
6168                                 DPRINTF(sc, ATH_DEBUG_BEACON,
6169                                     "%s: STA; syncbeacon=1\n", __func__);
6170                                 sc->sc_syncbeacon = 1;
6171
6172                                 if (csa_run_transition)
6173                                         ath_beacon_config(sc, vap);
6174
6175                         /*
6176                          * PR: kern/175227
6177                          *
6178                          * Reconfigure beacons during reset; as otherwise
6179                          * we won't get the beacon timers reprogrammed
6180                          * after a reset and thus we won't pick up a
6181                          * beacon miss interrupt.
6182                          *
6183                          * Hopefully we'll see a beacon before the BMISS
6184                          * timer fires (too often), leading to a STA
6185                          * disassociation.
6186                          */
6187                                 sc->sc_beacons = 1;
6188                         }
6189                         break;
6190                 case IEEE80211_M_MONITOR:
6191                         /*
6192                          * Monitor mode vaps have only INIT->RUN and RUN->RUN
6193                          * transitions so we must re-enable interrupts here to
6194                          * handle the case of a single monitor mode vap.
6195                          */
6196                         ath_hal_intrset(ah, sc->sc_imask);
6197                         break;
6198                 case IEEE80211_M_WDS:
6199                         break;
6200                 default:
6201                         break;
6202                 }
6203                 /*
6204                  * Let the hal process statistics collected during a
6205                  * scan so it can provide calibrated noise floor data.
6206                  */
6207                 ath_hal_process_noisefloor(ah);
6208                 /*
6209                  * Reset rssi stats; maybe not the best place...
6210                  */
6211                 sc->sc_halstats.ns_avgbrssi = ATH_RSSI_DUMMY_MARKER;
6212                 sc->sc_halstats.ns_avgrssi = ATH_RSSI_DUMMY_MARKER;
6213                 sc->sc_halstats.ns_avgtxrssi = ATH_RSSI_DUMMY_MARKER;
6214
6215                 /*
6216                  * Force awake for RUN mode.
6217                  */
6218                 ATH_LOCK(sc);
6219                 ath_power_setselfgen(sc, HAL_PM_AWAKE);
6220                 ath_power_setpower(sc, HAL_PM_AWAKE);
6221
6222                 /*
6223                  * Finally, start any timers and the task q thread
6224                  * (in case we didn't go through SCAN state).
6225                  */
6226                 if (ath_longcalinterval != 0) {
6227                         /* start periodic recalibration timer */
6228                         callout_reset(&sc->sc_cal_ch, 1, ath_calibrate, sc);
6229                 } else {
6230                         DPRINTF(sc, ATH_DEBUG_CALIBRATE,
6231                             "%s: calibration disabled\n", __func__);
6232                 }
6233                 ATH_UNLOCK(sc);
6234
6235                 taskqueue_unblock(sc->sc_tq);
6236         } else if (nstate == IEEE80211_S_INIT) {
6237                 /*
6238                  * If there are no vaps left in RUN state then
6239                  * shutdown host/driver operation:
6240                  * o disable interrupts
6241                  * o disable the task queue thread
6242                  * o mark beacon processing as stopped
6243                  */
6244                 if (!ath_isanyrunningvaps(vap)) {
6245                         sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
6246                         /* disable interrupts  */
6247                         ath_hal_intrset(ah, sc->sc_imask &~ HAL_INT_GLOBAL);
6248                         taskqueue_block(sc->sc_tq);
6249                         sc->sc_beacons = 0;
6250                 }
6251 #ifdef IEEE80211_SUPPORT_TDMA
6252                 ath_hal_setcca(ah, AH_TRUE);
6253 #endif
6254         } else if (nstate == IEEE80211_S_SLEEP) {
6255                 /* We're going to sleep, so transition appropriately */
6256                 /* For now, only do this if we're a single STA vap */
6257                 if (sc->sc_nvaps == 1 &&
6258                     vap->iv_opmode == IEEE80211_M_STA) {
6259                         DPRINTF(sc, ATH_DEBUG_BEACON, "%s: syncbeacon=%d\n", __func__, sc->sc_syncbeacon);
6260                         ATH_LOCK(sc);
6261                         /*
6262                          * Always at least set the self-generated
6263                          * frame config to set PWRMGT=1.
6264                          */
6265                         ath_power_setselfgen(sc, HAL_PM_NETWORK_SLEEP);
6266
6267                         /*
6268                          * If we're not syncing beacons, transition
6269                          * to NETWORK_SLEEP.
6270                          *
6271                          * We stay awake if syncbeacon > 0 in case
6272                          * we need to listen for some beacons otherwise
6273                          * our beacon timer config may be wrong.
6274                          */
6275                         if (sc->sc_syncbeacon == 0) {
6276                                 ath_power_setpower(sc, HAL_PM_NETWORK_SLEEP);
6277                         }
6278                         ATH_UNLOCK(sc);
6279                 }
6280         }
6281 bad:
6282         ieee80211_free_node(ni);
6283
6284         /*
6285          * Restore the power state - either to what it was, or
6286          * to network_sleep if it's alright.
6287          */
6288         ATH_LOCK(sc);
6289         ath_power_restore_power_state(sc);
6290         ATH_UNLOCK(sc);
6291         return error;
6292 }
6293
6294 /*
6295  * Allocate a key cache slot to the station so we can
6296  * setup a mapping from key index to node. The key cache
6297  * slot is needed for managing antenna state and for
6298  * compression when stations do not use crypto.  We do
6299  * it uniliaterally here; if crypto is employed this slot
6300  * will be reassigned.
6301  */
6302 static void
6303 ath_setup_stationkey(struct ieee80211_node *ni)
6304 {
6305         struct ieee80211vap *vap = ni->ni_vap;
6306         struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
6307         ieee80211_keyix keyix, rxkeyix;
6308
6309         /* XXX should take a locked ref to vap->iv_bss */
6310         if (!ath_key_alloc(vap, &ni->ni_ucastkey, &keyix, &rxkeyix)) {
6311                 /*
6312                  * Key cache is full; we'll fall back to doing
6313                  * the more expensive lookup in software.  Note
6314                  * this also means no h/w compression.
6315                  */
6316                 /* XXX msg+statistic */
6317         } else {
6318                 /* XXX locking? */
6319                 ni->ni_ucastkey.wk_keyix = keyix;
6320                 ni->ni_ucastkey.wk_rxkeyix = rxkeyix;
6321                 /* NB: must mark device key to get called back on delete */
6322                 ni->ni_ucastkey.wk_flags |= IEEE80211_KEY_DEVKEY;
6323                 IEEE80211_ADDR_COPY(ni->ni_ucastkey.wk_macaddr, ni->ni_macaddr);
6324                 /* NB: this will create a pass-thru key entry */
6325                 ath_keyset(sc, vap, &ni->ni_ucastkey, vap->iv_bss);
6326         }
6327 }
6328
6329 /*
6330  * Setup driver-specific state for a newly associated node.
6331  * Note that we're called also on a re-associate, the isnew
6332  * param tells us if this is the first time or not.
6333  */
6334 static void
6335 ath_newassoc(struct ieee80211_node *ni, int isnew)
6336 {
6337         struct ath_node *an = ATH_NODE(ni);
6338         struct ieee80211vap *vap = ni->ni_vap;
6339         struct ath_softc *sc = vap->iv_ic->ic_ifp->if_softc;
6340         const struct ieee80211_txparam *tp = ni->ni_txparms;
6341
6342         an->an_mcastrix = ath_tx_findrix(sc, tp->mcastrate);
6343         an->an_mgmtrix = ath_tx_findrix(sc, tp->mgmtrate);
6344
6345         DPRINTF(sc, ATH_DEBUG_NODE, "%s: %s: reassoc; isnew=%d, is_powersave=%d\n",
6346             __func__,
6347             ath_hal_ether_sprintf(ni->ni_macaddr),
6348             isnew,
6349             an->an_is_powersave);
6350
6351         ATH_NODE_LOCK(an);
6352         ath_rate_newassoc(sc, an, isnew);
6353         ATH_NODE_UNLOCK(an);
6354
6355         if (isnew &&
6356             (vap->iv_flags & IEEE80211_F_PRIVACY) == 0 && sc->sc_hasclrkey &&
6357             ni->ni_ucastkey.wk_keyix == IEEE80211_KEYIX_NONE)
6358                 ath_setup_stationkey(ni);
6359
6360         /*
6361          * If we're reassociating, make sure that any paused queues
6362          * get unpaused.
6363          *
6364          * Now, we may hvae frames in the hardware queue for this node.
6365          * So if we are reassociating and there are frames in the queue,
6366          * we need to go through the cleanup path to ensure that they're
6367          * marked as non-aggregate.
6368          */
6369         if (! isnew) {
6370                 DPRINTF(sc, ATH_DEBUG_NODE,
6371                     "%s: %s: reassoc; is_powersave=%d\n",
6372                     __func__,
6373                     ath_hal_ether_sprintf(ni->ni_macaddr),
6374                     an->an_is_powersave);
6375
6376                 /* XXX for now, we can't hold the lock across assoc */
6377                 ath_tx_node_reassoc(sc, an);
6378
6379                 /* XXX for now, we can't hold the lock across wakeup */
6380                 if (an->an_is_powersave)
6381                         ath_tx_node_wakeup(sc, an);
6382         }
6383 }
6384
6385 static int
6386 ath_setregdomain(struct ieee80211com *ic, struct ieee80211_regdomain *reg,
6387         int nchans, struct ieee80211_channel chans[])
6388 {
6389         struct ath_softc *sc = ic->ic_ifp->if_softc;
6390         struct ath_hal *ah = sc->sc_ah;
6391         HAL_STATUS status;
6392
6393         DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
6394             "%s: rd %u cc %u location %c%s\n",
6395             __func__, reg->regdomain, reg->country, reg->location,
6396             reg->ecm ? " ecm" : "");
6397
6398         status = ath_hal_set_channels(ah, chans, nchans,
6399             reg->country, reg->regdomain);
6400         if (status != HAL_OK) {
6401                 DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: failed, status %u\n",
6402                     __func__, status);
6403                 return EINVAL;          /* XXX */
6404         }
6405
6406         return 0;
6407 }
6408
6409 static void
6410 ath_getradiocaps(struct ieee80211com *ic,
6411         int maxchans, int *nchans, struct ieee80211_channel chans[])
6412 {
6413         struct ath_softc *sc = ic->ic_ifp->if_softc;
6414         struct ath_hal *ah = sc->sc_ah;
6415
6416         DPRINTF(sc, ATH_DEBUG_REGDOMAIN, "%s: use rd %u cc %d\n",
6417             __func__, SKU_DEBUG, CTRY_DEFAULT);
6418
6419         /* XXX check return */
6420         (void) ath_hal_getchannels(ah, chans, maxchans, nchans,
6421             HAL_MODE_ALL, CTRY_DEFAULT, SKU_DEBUG, AH_TRUE);
6422
6423 }
6424
6425 static int
6426 ath_getchannels(struct ath_softc *sc)
6427 {
6428         struct ifnet *ifp = sc->sc_ifp;
6429         struct ieee80211com *ic = ifp->if_l2com;
6430         struct ath_hal *ah = sc->sc_ah;
6431         HAL_STATUS status;
6432
6433         /*
6434          * Collect channel set based on EEPROM contents.
6435          */
6436         status = ath_hal_init_channels(ah, ic->ic_channels, IEEE80211_CHAN_MAX,
6437             &ic->ic_nchans, HAL_MODE_ALL, CTRY_DEFAULT, SKU_NONE, AH_TRUE);
6438         if (status != HAL_OK) {
6439                 if_printf(ifp, "%s: unable to collect channel list from hal, "
6440                     "status %d\n", __func__, status);
6441                 return EINVAL;
6442         }
6443         (void) ath_hal_getregdomain(ah, &sc->sc_eerd);
6444         ath_hal_getcountrycode(ah, &sc->sc_eecc);       /* NB: cannot fail */
6445         /* XXX map Atheros sku's to net80211 SKU's */
6446         /* XXX net80211 types too small */
6447         ic->ic_regdomain.regdomain = (uint16_t) sc->sc_eerd;
6448         ic->ic_regdomain.country = (uint16_t) sc->sc_eecc;
6449         ic->ic_regdomain.isocc[0] = ' ';        /* XXX don't know */
6450         ic->ic_regdomain.isocc[1] = ' ';
6451
6452         ic->ic_regdomain.ecm = 1;
6453         ic->ic_regdomain.location = 'I';
6454
6455         DPRINTF(sc, ATH_DEBUG_REGDOMAIN,
6456             "%s: eeprom rd %u cc %u (mapped rd %u cc %u) location %c%s\n",
6457             __func__, sc->sc_eerd, sc->sc_eecc,
6458             ic->ic_regdomain.regdomain, ic->ic_regdomain.country,
6459             ic->ic_regdomain.location, ic->ic_regdomain.ecm ? " ecm" : "");
6460         return 0;
6461 }
6462
6463 static int
6464 ath_rate_setup(struct ath_softc *sc, u_int mode)
6465 {
6466         struct ath_hal *ah = sc->sc_ah;
6467         const HAL_RATE_TABLE *rt;
6468
6469         switch (mode) {
6470         case IEEE80211_MODE_11A:
6471                 rt = ath_hal_getratetable(ah, HAL_MODE_11A);
6472                 break;
6473         case IEEE80211_MODE_HALF:
6474                 rt = ath_hal_getratetable(ah, HAL_MODE_11A_HALF_RATE);
6475                 break;
6476         case IEEE80211_MODE_QUARTER:
6477                 rt = ath_hal_getratetable(ah, HAL_MODE_11A_QUARTER_RATE);
6478                 break;
6479         case IEEE80211_MODE_11B:
6480                 rt = ath_hal_getratetable(ah, HAL_MODE_11B);
6481                 break;
6482         case IEEE80211_MODE_11G:
6483                 rt = ath_hal_getratetable(ah, HAL_MODE_11G);
6484                 break;
6485         case IEEE80211_MODE_TURBO_A:
6486                 rt = ath_hal_getratetable(ah, HAL_MODE_108A);
6487                 break;
6488         case IEEE80211_MODE_TURBO_G:
6489                 rt = ath_hal_getratetable(ah, HAL_MODE_108G);
6490                 break;
6491         case IEEE80211_MODE_STURBO_A:
6492                 rt = ath_hal_getratetable(ah, HAL_MODE_TURBO);
6493                 break;
6494         case IEEE80211_MODE_11NA:
6495                 rt = ath_hal_getratetable(ah, HAL_MODE_11NA_HT20);
6496                 break;
6497         case IEEE80211_MODE_11NG:
6498                 rt = ath_hal_getratetable(ah, HAL_MODE_11NG_HT20);
6499                 break;
6500         default:
6501                 DPRINTF(sc, ATH_DEBUG_ANY, "%s: invalid mode %u\n",
6502                         __func__, mode);
6503                 return 0;
6504         }
6505         sc->sc_rates[mode] = rt;
6506         return (rt != NULL);
6507 }
6508
6509 static void
6510 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
6511 {
6512 #define N(a)    (sizeof(a)/sizeof(a[0]))
6513         /* NB: on/off times from the Atheros NDIS driver, w/ permission */
6514         static const struct {
6515                 u_int           rate;           /* tx/rx 802.11 rate */
6516                 u_int16_t       timeOn;         /* LED on time (ms) */
6517                 u_int16_t       timeOff;        /* LED off time (ms) */
6518         } blinkrates[] = {
6519                 { 108,  40,  10 },
6520                 {  96,  44,  11 },
6521                 {  72,  50,  13 },
6522                 {  48,  57,  14 },
6523                 {  36,  67,  16 },
6524                 {  24,  80,  20 },
6525                 {  22, 100,  25 },
6526                 {  18, 133,  34 },
6527                 {  12, 160,  40 },
6528                 {  10, 200,  50 },
6529                 {   6, 240,  58 },
6530                 {   4, 267,  66 },
6531                 {   2, 400, 100 },
6532                 {   0, 500, 130 },
6533                 /* XXX half/quarter rates */
6534         };
6535         const HAL_RATE_TABLE *rt;
6536         int i, j;
6537
6538         memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
6539         rt = sc->sc_rates[mode];
6540         KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
6541         for (i = 0; i < rt->rateCount; i++) {
6542                 uint8_t ieeerate = rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6543                 if (rt->info[i].phy != IEEE80211_T_HT)
6544                         sc->sc_rixmap[ieeerate] = i;
6545                 else
6546                         sc->sc_rixmap[ieeerate | IEEE80211_RATE_MCS] = i;
6547         }
6548         memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
6549         for (i = 0; i < N(sc->sc_hwmap); i++) {
6550                 if (i >= rt->rateCount) {
6551                         sc->sc_hwmap[i].ledon = (500 * hz) / 1000;
6552                         sc->sc_hwmap[i].ledoff = (130 * hz) / 1000;
6553                         continue;
6554                 }
6555                 sc->sc_hwmap[i].ieeerate =
6556                         rt->info[i].dot11Rate & IEEE80211_RATE_VAL;
6557                 if (rt->info[i].phy == IEEE80211_T_HT)
6558                         sc->sc_hwmap[i].ieeerate |= IEEE80211_RATE_MCS;
6559                 sc->sc_hwmap[i].txflags = IEEE80211_RADIOTAP_F_DATAPAD;
6560                 if (rt->info[i].shortPreamble ||
6561                     rt->info[i].phy == IEEE80211_T_OFDM)
6562                         sc->sc_hwmap[i].txflags |= IEEE80211_RADIOTAP_F_SHORTPRE;
6563                 sc->sc_hwmap[i].rxflags = sc->sc_hwmap[i].txflags;
6564                 for (j = 0; j < N(blinkrates)-1; j++)
6565                         if (blinkrates[j].rate == sc->sc_hwmap[i].ieeerate)
6566                                 break;
6567                 /* NB: this uses the last entry if the rate isn't found */
6568                 /* XXX beware of overlow */
6569                 sc->sc_hwmap[i].ledon = (blinkrates[j].timeOn * hz) / 1000;
6570                 sc->sc_hwmap[i].ledoff = (blinkrates[j].timeOff * hz) / 1000;
6571         }
6572         sc->sc_currates = rt;
6573         sc->sc_curmode = mode;
6574         /*
6575          * All protection frames are transmited at 2Mb/s for
6576          * 11g, otherwise at 1Mb/s.
6577          */
6578         if (mode == IEEE80211_MODE_11G)
6579                 sc->sc_protrix = ath_tx_findrix(sc, 2*2);
6580         else
6581                 sc->sc_protrix = ath_tx_findrix(sc, 2*1);
6582         /* NB: caller is responsible for resetting rate control state */
6583 #undef N
6584 }
6585
6586 static void
6587 ath_watchdog(void *arg)
6588 {
6589         struct ath_softc *sc = arg;
6590         int do_reset = 0;
6591
6592         ATH_LOCK_ASSERT(sc);
6593
6594         if (sc->sc_wd_timer != 0 && --sc->sc_wd_timer == 0) {
6595                 struct ifnet *ifp = sc->sc_ifp;
6596                 uint32_t hangs;
6597
6598                 ath_power_set_power_state(sc, HAL_PM_AWAKE);
6599
6600                 if (ath_hal_gethangstate(sc->sc_ah, 0xffff, &hangs) &&
6601                     hangs != 0) {
6602                         if_printf(ifp, "%s hang detected (0x%x)\n",
6603                             hangs & 0xff ? "bb" : "mac", hangs);
6604                 } else
6605                         if_printf(ifp, "device timeout\n");
6606                 do_reset = 1;
6607 #if defined(__DragonFly__)
6608                 ++ifp->if_oerrors;
6609 #else
6610                 if_inc_counter(ifp, IFCOUNTER_OERRORS, 1);
6611 #endif
6612                 sc->sc_stats.ast_watchdog++;
6613
6614                 ath_power_restore_power_state(sc);
6615         }
6616
6617         /*
6618          * We can't hold the lock across the ath_reset() call.
6619          *
6620          * And since this routine can't hold a lock and sleep,
6621          * do the reset deferred.
6622          */
6623         if (do_reset) {
6624                 taskqueue_enqueue(sc->sc_tq, &sc->sc_resettask);
6625         }
6626
6627 #if defined(__DragonFly__)
6628         callout_reset(&sc->sc_wd_ch, hz, ath_watchdog, sc);
6629 #else
6630         callout_schedule(&sc->sc_wd_ch, hz);
6631 #endif
6632 }
6633
6634 #if defined(__DragonFly__)
6635
6636 /*
6637  * (DragonFly network start)
6638  */
6639 static void
6640 ath_start(struct ifnet *ifp, struct ifaltq_subque *ifsq)
6641 {
6642        struct ath_softc *sc = ifp->if_softc;
6643        struct mbuf *m;
6644        int wst;
6645
6646        ASSERT_ALTQ_SQ_DEFAULT(ifp, ifsq);
6647        wst = wlan_serialize_push();
6648
6649        if ((ifp->if_flags & IFF_RUNNING) == 0 || sc->sc_invalid) {
6650                ifq_purge(&ifp->if_snd);
6651                wlan_serialize_pop(wst);
6652                return;
6653        }
6654        ifq_set_oactive(&ifp->if_snd);
6655        for (;;) {
6656                m = ifq_dequeue(&ifp->if_snd);
6657                if (m == NULL)
6658                        break;
6659                ath_transmit(ifp, m);
6660        }
6661        ifq_clr_oactive(&ifp->if_snd);
6662        wlan_serialize_pop(wst);
6663 }
6664
6665 #endif
6666
6667 /*
6668  * Fetch the rate control statistics for the given node.
6669  */
6670 static int
6671 ath_ioctl_ratestats(struct ath_softc *sc, struct ath_rateioctl *rs)
6672 {
6673         struct ath_node *an;
6674         struct ieee80211com *ic = sc->sc_ifp->if_l2com;
6675         struct ieee80211_node *ni;
6676         int error = 0;
6677
6678         /* Perform a lookup on the given node */
6679         ni = ieee80211_find_node(&ic->ic_sta, rs->is_u.macaddr);
6680         if (ni == NULL) {
6681                 error = EINVAL;
6682                 goto bad;
6683         }
6684
6685         /* Lock the ath_node */
6686         an = ATH_NODE(ni);
6687         ATH_NODE_LOCK(an);
6688
6689         /* Fetch the rate control stats for this node */
6690         error = ath_rate_fetch_node_stats(sc, an, rs);
6691
6692         /* No matter what happens here, just drop through */
6693
6694         /* Unlock the ath_node */
6695         ATH_NODE_UNLOCK(an);
6696
6697         /* Unref the node */
6698         ieee80211_node_decref(ni);
6699
6700 bad:
6701         return (error);
6702 }
6703
6704 #ifdef ATH_DIAGAPI
6705 /*
6706  * Diagnostic interface to the HAL.  This is used by various
6707  * tools to do things like retrieve register contents for
6708  * debugging.  The mechanism is intentionally opaque so that
6709  * it can change frequently w/o concern for compatiblity.
6710  */
6711 static int
6712 ath_ioctl_diag(struct ath_softc *sc, struct ath_diag *ad)
6713 {
6714         struct ath_hal *ah = sc->sc_ah;
6715         u_int id = ad->ad_id & ATH_DIAG_ID;
6716         void *indata = NULL;
6717         void *outdata = NULL;
6718         u_int32_t insize = ad->ad_in_size;
6719         u_int32_t outsize = ad->ad_out_size;
6720         int error = 0;
6721
6722         if (ad->ad_id & ATH_DIAG_IN) {
6723                 /*
6724                  * Copy in data.
6725                  */
6726                 indata = kmalloc(insize, M_TEMP, M_INTWAIT);
6727                 if (indata == NULL) {
6728                         error = ENOMEM;
6729                         goto bad;
6730                 }
6731                 error = copyin(ad->ad_in_data, indata, insize);
6732                 if (error)
6733                         goto bad;
6734         }
6735         if (ad->ad_id & ATH_DIAG_DYN) {
6736                 /*
6737                  * Allocate a buffer for the results (otherwise the HAL
6738                  * returns a pointer to a buffer where we can read the
6739                  * results).  Note that we depend on the HAL leaving this
6740                  * pointer for us to use below in reclaiming the buffer;
6741                  * may want to be more defensive.
6742                  */
6743                 outdata = kmalloc(outsize, M_TEMP, M_INTWAIT);
6744                 if (outdata == NULL) {
6745                         error = ENOMEM;
6746                         goto bad;
6747                 }
6748         }
6749
6750
6751         ATH_LOCK(sc);
6752         if (id != HAL_DIAG_REGS)
6753                 ath_power_set_power_state(sc, HAL_PM_AWAKE);
6754         ATH_UNLOCK(sc);
6755
6756         if (ath_hal_getdiagstate(ah, id, indata, insize, &outdata, &outsize)) {
6757                 if (outsize < ad->ad_out_size)
6758                         ad->ad_out_size = outsize;
6759                 if (outdata != NULL)
6760                         error = copyout(outdata, ad->ad_out_data,
6761                                         ad->ad_out_size);
6762         } else {
6763                 error = EINVAL;
6764         }
6765
6766         ATH_LOCK(sc);
6767         if (id != HAL_DIAG_REGS)
6768                 ath_power_restore_power_state(sc);
6769         ATH_UNLOCK(sc);
6770
6771 bad:
6772         if ((ad->ad_id & ATH_DIAG_IN) && indata != NULL)
6773                 kfree(indata, M_TEMP);
6774         if ((ad->ad_id & ATH_DIAG_DYN) && outdata != NULL)
6775                 kfree(outdata, M_TEMP);
6776         return error;
6777 }
6778 #endif /* ATH_DIAGAPI */
6779
6780 #if defined(__DragonFly__)
6781
6782 static int
6783 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data,
6784           struct ucred *cred __unused)
6785
6786 #else
6787
6788 static int
6789 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
6790
6791 #endif
6792 {
6793 #define IS_RUNNING(ifp) \
6794         ((ifp->if_flags & IFF_UP) && (ifp->if_flags & IFF_RUNNING))
6795         struct ath_softc *sc = ifp->if_softc;
6796         struct ieee80211com *ic = ifp->if_l2com;
6797         struct ifreq *ifr = (struct ifreq *)data;
6798         const HAL_RATE_TABLE *rt;
6799         int error = 0;
6800
6801         switch (cmd) {
6802         case SIOCSIFFLAGS:
6803                 if (IS_RUNNING(ifp)) {
6804                         /*
6805                          * To avoid rescanning another access point,
6806                          * do not call ath_init() here.  Instead,
6807                          * only reflect promisc mode settings.
6808                          */
6809                         ATH_LOCK(sc);
6810                         ath_power_set_power_state(sc, HAL_PM_AWAKE);
6811                         ath_mode_init(sc);
6812                         ath_power_restore_power_state(sc);
6813                         ATH_UNLOCK(sc);
6814                 } else if (ifp->if_flags & IFF_UP) {
6815                         /*
6816                          * Beware of being called during attach/detach
6817                          * to reset promiscuous mode.  In that case we
6818                          * will still be marked UP but not RUNNING.
6819                          * However trying to re-init the interface
6820                          * is the wrong thing to do as we've already
6821                          * torn down much of our state.  There's
6822                          * probably a better way to deal with this.
6823                          */
6824                         if (!sc->sc_invalid)
6825                                 ath_init(sc);   /* XXX lose error */
6826                 } else {
6827                         ATH_LOCK(sc);
6828                         ath_stop_locked(ifp);
6829                         if (!sc->sc_invalid)
6830                                 ath_power_setpower(sc, HAL_PM_FULL_SLEEP);
6831                         ATH_UNLOCK(sc);
6832                 }
6833                 break;
6834         case SIOCGIFMEDIA:
6835         case SIOCSIFMEDIA:
6836                 error = ifmedia_ioctl(ifp, ifr, &ic->ic_media, cmd);
6837                 break;
6838         case SIOCGATHSTATS:
6839                 /* NB: embed these numbers to get a consistent view */
6840 #if defined(__DragonFly__)
6841                 sc->sc_stats.ast_tx_packets = ifp->if_opackets;
6842                 sc->sc_stats.ast_rx_packets = ifp->if_ipackets;
6843 #else
6844                 sc->sc_stats.ast_tx_packets = ifp->if_get_counter(ifp,
6845                     IFCOUNTER_OPACKETS);
6846                 sc->sc_stats.ast_rx_packets = ifp->if_get_counter(ifp,
6847                     IFCOUNTER_IPACKETS);
6848 #endif
6849                 sc->sc_stats.ast_tx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgtxrssi);
6850                 sc->sc_stats.ast_rx_rssi = ATH_RSSI(sc->sc_halstats.ns_avgrssi);
6851 #ifdef IEEE80211_SUPPORT_TDMA
6852                 sc->sc_stats.ast_tdma_tsfadjp = TDMA_AVG(sc->sc_avgtsfdeltap);
6853                 sc->sc_stats.ast_tdma_tsfadjm = TDMA_AVG(sc->sc_avgtsfdeltam);
6854 #endif
6855                 rt = sc->sc_currates;
6856                 sc->sc_stats.ast_tx_rate =
6857                     rt->info[sc->sc_txrix].dot11Rate &~ IEEE80211_RATE_BASIC;
6858                 if (rt->info[sc->sc_txrix].phy & IEEE80211_T_HT)
6859                         sc->sc_stats.ast_tx_rate |= IEEE80211_RATE_MCS;
6860                 error = copyout(&sc->sc_stats,
6861                     ifr->ifr_data, sizeof (sc->sc_stats));
6862                 break;
6863         case SIOCGATHAGSTATS:
6864                 error = copyout(&sc->sc_aggr_stats,
6865                     ifr->ifr_data, sizeof (sc->sc_aggr_stats));
6866                 break;
6867         case SIOCZATHSTATS:
6868                 error = priv_check(curthread, PRIV_DRIVER);
6869                 if (error == 0) {
6870                         memset(&sc->sc_stats, 0, sizeof(sc->sc_stats));
6871                         memset(&sc->sc_aggr_stats, 0,
6872                             sizeof(sc->sc_aggr_stats));
6873                         memset(&sc->sc_intr_stats, 0,
6874                             sizeof(sc->sc_intr_stats));
6875                 }
6876                 break;
6877 #ifdef ATH_DIAGAPI
6878         case SIOCGATHDIAG:
6879                 error = ath_ioctl_diag(sc, (struct ath_diag *) ifr);
6880                 break;
6881         case SIOCGATHPHYERR:
6882                 error = ath_ioctl_phyerr(sc,(struct ath_diag*) ifr);
6883                 break;
6884 #endif
6885         case SIOCGATHSPECTRAL:
6886                 error = ath_ioctl_spectral(sc,(struct ath_diag*) ifr);
6887                 break;
6888         case SIOCGATHNODERATESTATS:
6889                 error = ath_ioctl_ratestats(sc, (struct ath_rateioctl *) ifr);
6890                 break;
6891         case SIOCGIFADDR:
6892                 error = ether_ioctl(ifp, cmd, data);
6893                 break;
6894         default:
6895                 error = EINVAL;
6896                 break;
6897         }
6898         return error;
6899 #undef IS_RUNNING
6900 }
6901
6902 /*
6903  * Announce various information on device/driver attach.
6904  */
6905 static void
6906 ath_announce(struct ath_softc *sc)
6907 {
6908         struct ifnet *ifp = sc->sc_ifp;
6909         struct ath_hal *ah = sc->sc_ah;
6910
6911         if_printf(ifp, "AR%s mac %d.%d RF%s phy %d.%d\n",
6912                 ath_hal_mac_name(ah), ah->ah_macVersion, ah->ah_macRev,
6913                 ath_hal_rf_name(ah), ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
6914         if_printf(ifp, "2GHz radio: 0x%.4x; 5GHz radio: 0x%.4x\n",
6915                 ah->ah_analog2GhzRev, ah->ah_analog5GhzRev);
6916         if (bootverbose) {
6917                 int i;
6918                 for (i = 0; i <= WME_AC_VO; i++) {
6919                         struct ath_txq *txq = sc->sc_ac2q[i];
6920                         if_printf(ifp, "Use hw queue %u for %s traffic\n",
6921                                 txq->axq_qnum, ieee80211_wme_acnames[i]);
6922                 }
6923                 if_printf(ifp, "Use hw queue %u for CAB traffic\n",
6924                         sc->sc_cabq->axq_qnum);
6925                 if_printf(ifp, "Use hw queue %u for beacons\n", sc->sc_bhalq);
6926         }
6927         if (ath_rxbuf != ATH_RXBUF)
6928                 if_printf(ifp, "using %u rx buffers\n", ath_rxbuf);
6929         if (ath_txbuf != ATH_TXBUF)
6930                 if_printf(ifp, "using %u tx buffers\n", ath_txbuf);
6931         if (sc->sc_mcastkey && bootverbose)
6932                 if_printf(ifp, "using multicast key search\n");
6933 }
6934
6935 static void
6936 ath_dfs_tasklet(void *p, int npending)
6937 {
6938         struct ath_softc *sc = (struct ath_softc *) p;
6939         struct ifnet *ifp = sc->sc_ifp;
6940         struct ieee80211com *ic = ifp->if_l2com;
6941
6942         /*
6943          * If previous processing has found a radar event,
6944          * signal this to the net80211 layer to begin DFS
6945          * processing.
6946          */
6947         if (ath_dfs_process_radar_event(sc, sc->sc_curchan)) {
6948                 /* DFS event found, initiate channel change */
6949                 /*
6950                  * XXX doesn't currently tell us whether the event
6951                  * XXX was found in the primary or extension
6952                  * XXX channel!
6953                  */
6954                 IEEE80211_LOCK(ic);
6955                 ieee80211_dfs_notify_radar(ic, sc->sc_curchan);
6956                 IEEE80211_UNLOCK(ic);
6957         }
6958 }
6959
6960 /*
6961  * Enable/disable power save.  This must be called with
6962  * no TX driver locks currently held, so it should only
6963  * be called from the RX path (which doesn't hold any
6964  * TX driver locks.)
6965  */
6966 static void
6967 ath_node_powersave(struct ieee80211_node *ni, int enable)
6968 {
6969 #ifdef  ATH_SW_PSQ
6970         struct ath_node *an = ATH_NODE(ni);
6971         struct ieee80211com *ic = ni->ni_ic;
6972         struct ath_softc *sc = ic->ic_ifp->if_softc;
6973         struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6974
6975         /* XXX and no TXQ locks should be held here */
6976
6977         DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE, "%s: %6s: enable=%d\n",
6978             __func__,
6979             ath_hal_ether_sprintf(ni->ni_macaddr),
6980             !! enable);
6981
6982         /* Suspend or resume software queue handling */
6983         if (enable)
6984                 ath_tx_node_sleep(sc, an);
6985         else
6986                 ath_tx_node_wakeup(sc, an);
6987
6988         /* Update net80211 state */
6989         avp->av_node_ps(ni, enable);
6990 #else
6991         struct ath_vap *avp = ATH_VAP(ni->ni_vap);
6992
6993         /* Update net80211 state */
6994         avp->av_node_ps(ni, enable);
6995 #endif/* ATH_SW_PSQ */
6996 }
6997
6998 /*
6999  * Notification from net80211 that the powersave queue state has
7000  * changed.
7001  *
7002  * Since the software queue also may have some frames:
7003  *
7004  * + if the node software queue has frames and the TID state
7005  *   is 0, we set the TIM;
7006  * + if the node and the stack are both empty, we clear the TIM bit.
7007  * + If the stack tries to set the bit, always set it.
7008  * + If the stack tries to clear the bit, only clear it if the
7009  *   software queue in question is also cleared.
7010  *
7011  * TODO: this is called during node teardown; so let's ensure this
7012  * is all correctly handled and that the TIM bit is cleared.
7013  * It may be that the node flush is called _AFTER_ the net80211
7014  * stack clears the TIM.
7015  *
7016  * Here is the racy part.  Since it's possible >1 concurrent,
7017  * overlapping TXes will appear complete with a TX completion in
7018  * another thread, it's possible that the concurrent TIM calls will
7019  * clash.  We can't hold the node lock here because setting the
7020  * TIM grabs the net80211 comlock and this may cause a LOR.
7021  * The solution is either to totally serialise _everything_ at
7022  * this point (ie, all TX, completion and any reset/flush go into
7023  * one taskqueue) or a new "ath TIM lock" needs to be created that
7024  * just wraps the driver state change and this call to avp->av_set_tim().
7025  *
7026  * The same race exists in the net80211 power save queue handling
7027  * as well.  Since multiple transmitting threads may queue frames
7028  * into the driver, as well as ps-poll and the driver transmitting
7029  * frames (and thus clearing the psq), it's quite possible that
7030  * a packet entering the PSQ and a ps-poll being handled will
7031  * race, causing the TIM to be cleared and not re-set.
7032  */
7033 static int
7034 ath_node_set_tim(struct ieee80211_node *ni, int enable)
7035 {
7036 #ifdef  ATH_SW_PSQ
7037         struct ieee80211com *ic = ni->ni_ic;
7038         struct ath_softc *sc = ic->ic_ifp->if_softc;
7039         struct ath_node *an = ATH_NODE(ni);
7040         struct ath_vap *avp = ATH_VAP(ni->ni_vap);
7041         int changed = 0;
7042
7043         ATH_TX_LOCK(sc);
7044         an->an_stack_psq = enable;
7045
7046         /*
7047          * This will get called for all operating modes,
7048          * even if avp->av_set_tim is unset.
7049          * It's currently set for hostap/ibss modes; but
7050          * the same infrastructure is used for both STA
7051          * and AP/IBSS node power save.
7052          */
7053         if (avp->av_set_tim == NULL) {
7054                 ATH_TX_UNLOCK(sc);
7055                 return (0);
7056         }
7057
7058         /*
7059          * If setting the bit, always set it here.
7060          * If clearing the bit, only clear it if the
7061          * software queue is also empty.
7062          *
7063          * If the node has left power save, just clear the TIM
7064          * bit regardless of the state of the power save queue.
7065          *
7066          * XXX TODO: although atomics are used, it's quite possible
7067          * that a race will occur between this and setting/clearing
7068          * in another thread.  TX completion will occur always in
7069          * one thread, however setting/clearing the TIM bit can come
7070          * from a variety of different process contexts!
7071          */
7072         if (enable && an->an_tim_set == 1) {
7073                 DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7074                     "%s: %s: enable=%d, tim_set=1, ignoring\n",
7075                     __func__,
7076                     ath_hal_ether_sprintf(ni->ni_macaddr),
7077                     enable);
7078                 ATH_TX_UNLOCK(sc);
7079         } else if (enable) {
7080                 DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7081                     "%s: %s: enable=%d, enabling TIM\n",
7082                     __func__,
7083                     ath_hal_ether_sprintf(ni->ni_macaddr),
7084                     enable);
7085                 an->an_tim_set = 1;
7086                 ATH_TX_UNLOCK(sc);
7087                 changed = avp->av_set_tim(ni, enable);
7088         } else if (an->an_swq_depth == 0) {
7089                 /* disable */
7090                 DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7091                     "%s: %s: enable=%d, an_swq_depth == 0, disabling\n",
7092                     __func__,
7093                     ath_hal_ether_sprintf(ni->ni_macaddr),
7094                     enable);
7095                 an->an_tim_set = 0;
7096                 ATH_TX_UNLOCK(sc);
7097                 changed = avp->av_set_tim(ni, enable);
7098         } else if (! an->an_is_powersave) {
7099                 /*
7100                  * disable regardless; the node isn't in powersave now
7101                  */
7102                 DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7103                     "%s: %s: enable=%d, an_pwrsave=0, disabling\n",
7104                     __func__,
7105                     ath_hal_ether_sprintf(ni->ni_macaddr),
7106                     enable);
7107                 an->an_tim_set = 0;
7108                 ATH_TX_UNLOCK(sc);
7109                 changed = avp->av_set_tim(ni, enable);
7110         } else {
7111                 /*
7112                  * psq disable, node is currently in powersave, node
7113                  * software queue isn't empty, so don't clear the TIM bit
7114                  * for now.
7115                  */
7116                 ATH_TX_UNLOCK(sc);
7117                 DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7118                     "%s: %s: enable=%d, an_swq_depth > 0, ignoring\n",
7119                     __func__,
7120                     ath_hal_ether_sprintf(ni->ni_macaddr),
7121                     enable);
7122                 changed = 0;
7123         }
7124
7125         return (changed);
7126 #else
7127         struct ath_vap *avp = ATH_VAP(ni->ni_vap);
7128
7129         /*
7130          * Some operating modes don't set av_set_tim(), so don't
7131          * update it here.
7132          */
7133         if (avp->av_set_tim == NULL)
7134                 return (0);
7135
7136         return (avp->av_set_tim(ni, enable));
7137 #endif /* ATH_SW_PSQ */
7138 }
7139
7140 /*
7141  * Set or update the TIM from the software queue.
7142  *
7143  * Check the software queue depth before attempting to do lock
7144  * anything; that avoids trying to obtain the lock.  Then,
7145  * re-check afterwards to ensure nothing has changed in the
7146  * meantime.
7147  *
7148  * set:   This is designed to be called from the TX path, after
7149  *        a frame has been queued; to see if the swq > 0.
7150  *
7151  * clear: This is designed to be called from the buffer completion point
7152  *        (right now it's ath_tx_default_comp()) where the state of
7153  *        a software queue has changed.
7154  *
7155  * It makes sense to place it at buffer free / completion rather
7156  * than after each software queue operation, as there's no real
7157  * point in churning the TIM bit as the last frames in the software
7158  * queue are transmitted.  If they fail and we retry them, we'd
7159  * just be setting the TIM bit again anyway.
7160  */
7161 void
7162 ath_tx_update_tim(struct ath_softc *sc, struct ieee80211_node *ni,
7163      int enable)
7164 {
7165 #ifdef  ATH_SW_PSQ
7166         struct ath_node *an;
7167         struct ath_vap *avp;
7168
7169         /* Don't do this for broadcast/etc frames */
7170         if (ni == NULL)
7171                 return;
7172
7173         an = ATH_NODE(ni);
7174         avp = ATH_VAP(ni->ni_vap);
7175
7176         /*
7177          * And for operating modes without the TIM handler set, let's
7178          * just skip those.
7179          */
7180         if (avp->av_set_tim == NULL)
7181                 return;
7182
7183         ATH_TX_LOCK_ASSERT(sc);
7184
7185         if (enable) {
7186                 if (an->an_is_powersave &&
7187                     an->an_tim_set == 0 &&
7188                     an->an_swq_depth != 0) {
7189                         DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7190                             "%s: %s: swq_depth>0, tim_set=0, set!\n",
7191                             __func__,
7192                             ath_hal_ether_sprintf(ni->ni_macaddr));
7193                         an->an_tim_set = 1;
7194                         (void) avp->av_set_tim(ni, 1);
7195                 }
7196         } else {
7197                 /*
7198                  * Don't bother grabbing the lock unless the queue is empty.
7199                  */
7200                 if (an->an_swq_depth != 0)
7201                         return;
7202
7203                 if (an->an_is_powersave &&
7204                     an->an_stack_psq == 0 &&
7205                     an->an_tim_set == 1 &&
7206                     an->an_swq_depth == 0) {
7207                         DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7208                             "%s: %s: swq_depth=0, tim_set=1, psq_set=0,"
7209                             " clear!\n",
7210                             __func__,
7211                             ath_hal_ether_sprintf(ni->ni_macaddr));
7212                         an->an_tim_set = 0;
7213                         (void) avp->av_set_tim(ni, 0);
7214                 }
7215         }
7216 #else
7217         return;
7218 #endif  /* ATH_SW_PSQ */
7219 }
7220
7221 /*
7222  * Received a ps-poll frame from net80211.
7223  *
7224  * Here we get a chance to serve out a software-queued frame ourselves
7225  * before we punt it to net80211 to transmit us one itself - either
7226  * because there's traffic in the net80211 psq, or a NULL frame to
7227  * indicate there's nothing else.
7228  */
7229 static void
7230 ath_node_recv_pspoll(struct ieee80211_node *ni, struct mbuf *m)
7231 {
7232 #ifdef  ATH_SW_PSQ
7233         struct ath_node *an;
7234         struct ath_vap *avp;
7235         struct ieee80211com *ic = ni->ni_ic;
7236         struct ath_softc *sc = ic->ic_ifp->if_softc;
7237         int tid;
7238
7239         /* Just paranoia */
7240         if (ni == NULL)
7241                 return;
7242
7243         /*
7244          * Unassociated (temporary node) station.
7245          */
7246         if (ni->ni_associd == 0)
7247                 return;
7248
7249         /*
7250          * We do have an active node, so let's begin looking into it.
7251          */
7252         an = ATH_NODE(ni);
7253         avp = ATH_VAP(ni->ni_vap);
7254
7255         /*
7256          * For now, we just call the original ps-poll method.
7257          * Once we're ready to flip this on:
7258          *
7259          * + Set leak to 1, as no matter what we're going to have
7260          *   to send a frame;
7261          * + Check the software queue and if there's something in it,
7262          *   schedule the highest TID thas has traffic from this node.
7263          *   Then make sure we schedule the software scheduler to
7264          *   run so it picks up said frame.
7265          *
7266          * That way whatever happens, we'll at least send _a_ frame
7267          * to the given node.
7268          *
7269          * Again, yes, it's crappy QoS if the node has multiple
7270          * TIDs worth of traffic - but let's get it working first
7271          * before we optimise it.
7272          *
7273          * Also yes, there's definitely latency here - we're not
7274          * direct dispatching to the hardware in this path (and
7275          * we're likely being called from the packet receive path,
7276          * so going back into TX may be a little hairy!) but again
7277          * I'd like to get this working first before optimising
7278          * turn-around time.
7279          */
7280
7281         ATH_TX_LOCK(sc);
7282
7283         /*
7284          * Legacy - we're called and the node isn't asleep.
7285          * Immediately punt.
7286          */
7287         if (! an->an_is_powersave) {
7288                 DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7289                     "%s: %s: not in powersave?\n",
7290                     __func__,
7291                     ath_hal_ether_sprintf(ni->ni_macaddr));
7292                 ATH_TX_UNLOCK(sc);
7293                 avp->av_recv_pspoll(ni, m);
7294                 return;
7295         }
7296
7297         /*
7298          * We're in powersave.
7299          *
7300          * Leak a frame.
7301          */
7302         an->an_leak_count = 1;
7303
7304         /*
7305          * Now, if there's no frames in the node, just punt to
7306          * recv_pspoll.
7307          *
7308          * Don't bother checking if the TIM bit is set, we really
7309          * only care if there are any frames here!
7310          */
7311         if (an->an_swq_depth == 0) {
7312                 ATH_TX_UNLOCK(sc);
7313                 DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7314                     "%s: %s: SWQ empty; punting to net80211\n",
7315                     __func__,
7316                     ath_hal_ether_sprintf(ni->ni_macaddr));
7317                 avp->av_recv_pspoll(ni, m);
7318                 return;
7319         }
7320
7321         /*
7322          * Ok, let's schedule the highest TID that has traffic
7323          * and then schedule something.
7324          */
7325         for (tid = IEEE80211_TID_SIZE - 1; tid >= 0; tid--) {
7326                 struct ath_tid *atid = &an->an_tid[tid];
7327                 /*
7328                  * No frames? Skip.
7329                  */
7330                 if (atid->axq_depth == 0)
7331                         continue;
7332                 ath_tx_tid_sched(sc, atid);
7333                 /*
7334                  * XXX we could do a direct call to the TXQ
7335                  * scheduler code here to optimise latency
7336                  * at the expense of a REALLY deep callstack.
7337                  */
7338                 ATH_TX_UNLOCK(sc);
7339                 taskqueue_enqueue(sc->sc_tq, &sc->sc_txqtask);
7340                 DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7341                     "%s: %s: leaking frame to TID %d\n",
7342                     __func__,
7343                     ath_hal_ether_sprintf(ni->ni_macaddr),
7344                     tid);
7345                 return;
7346         }
7347
7348         ATH_TX_UNLOCK(sc);
7349
7350         /*
7351          * XXX nothing in the TIDs at this point? Eek.
7352          */
7353         DPRINTF(sc, ATH_DEBUG_NODE_PWRSAVE,
7354             "%s: %s: TIDs empty, but ath_node showed traffic?!\n",
7355             __func__,
7356             ath_hal_ether_sprintf(ni->ni_macaddr));
7357         avp->av_recv_pspoll(ni, m);
7358 #else
7359         avp->av_recv_pspoll(ni, m);
7360 #endif  /* ATH_SW_PSQ */
7361 }
7362
7363 MODULE_VERSION(if_ath, 1);
7364 MODULE_DEPEND(if_ath, wlan, 1, 1, 1);          /* 802.11 media layer */
7365 #if     defined(IEEE80211_ALQ) || defined(AH_DEBUG_ALQ) || defined(ATH_DEBUG_ALQ)
7366 MODULE_DEPEND(if_ath, alq, 1, 1, 1);
7367 #endif