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