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