xref: /openbsd-src/sys/dev/ic/athn.c (revision 1a8dbaac879b9f3335ad7fb25429ce63ac1d6bac)
1 /*	$OpenBSD: athn.c,v 1.109 2020/07/10 13:22:19 patrick Exp $	*/
2 
3 /*-
4  * Copyright (c) 2009 Damien Bergamini <damien.bergamini@free.fr>
5  * Copyright (c) 2008-2010 Atheros Communications Inc.
6  *
7  * Permission to use, copy, modify, and/or distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 /*
21  * Driver for Atheros 802.11a/g/n chipsets.
22  */
23 
24 #include "athn_usb.h"
25 #include "bpfilter.h"
26 
27 #include <sys/param.h>
28 #include <sys/sockio.h>
29 #include <sys/mbuf.h>
30 #include <sys/kernel.h>
31 #include <sys/socket.h>
32 #include <sys/systm.h>
33 #include <sys/malloc.h>
34 #include <sys/queue.h>
35 #include <sys/timeout.h>
36 #include <sys/conf.h>
37 #include <sys/device.h>
38 #include <sys/stdint.h>	/* uintptr_t */
39 #include <sys/endian.h>
40 
41 #include <machine/bus.h>
42 #include <machine/intr.h>
43 
44 #if NBPFILTER > 0
45 #include <net/bpf.h>
46 #endif
47 #include <net/if.h>
48 #include <net/if_dl.h>
49 #include <net/if_media.h>
50 
51 #include <netinet/in.h>
52 #include <netinet/if_ether.h>
53 
54 #include <net80211/ieee80211_var.h>
55 #include <net80211/ieee80211_amrr.h>
56 #include <net80211/ieee80211_mira.h>
57 #include <net80211/ieee80211_radiotap.h>
58 
59 #include <dev/ic/athnreg.h>
60 #include <dev/ic/athnvar.h>
61 
62 #ifdef ATHN_DEBUG
63 int athn_debug = 0;
64 #endif
65 
66 void		athn_radiotap_attach(struct athn_softc *);
67 void		athn_get_chanlist(struct athn_softc *);
68 const char *	athn_get_mac_name(struct athn_softc *);
69 const char *	athn_get_rf_name(struct athn_softc *);
70 void		athn_led_init(struct athn_softc *);
71 void		athn_set_led(struct athn_softc *, int);
72 void		athn_btcoex_init(struct athn_softc *);
73 void		athn_btcoex_enable(struct athn_softc *);
74 void		athn_btcoex_disable(struct athn_softc *);
75 void		athn_set_rxfilter(struct athn_softc *, uint32_t);
76 void		athn_get_chipid(struct athn_softc *);
77 int		athn_reset_power_on(struct athn_softc *);
78 int		athn_reset(struct athn_softc *, int);
79 void		athn_init_pll(struct athn_softc *,
80 		    const struct ieee80211_channel *);
81 int		athn_set_power_awake(struct athn_softc *);
82 void		athn_set_power_sleep(struct athn_softc *);
83 void		athn_write_serdes(struct athn_softc *,
84 		    const struct athn_serdes *);
85 void		athn_config_pcie(struct athn_softc *);
86 void		athn_config_nonpcie(struct athn_softc *);
87 int		athn_set_chan(struct athn_softc *, struct ieee80211_channel *,
88 		    struct ieee80211_channel *);
89 int		athn_switch_chan(struct athn_softc *,
90 		    struct ieee80211_channel *, struct ieee80211_channel *);
91 void		athn_get_delta_slope(uint32_t, uint32_t *, uint32_t *);
92 void		athn_reset_key(struct athn_softc *, int);
93 int		athn_set_key(struct ieee80211com *, struct ieee80211_node *,
94 		    struct ieee80211_key *);
95 void		athn_delete_key(struct ieee80211com *, struct ieee80211_node *,
96 		    struct ieee80211_key *);
97 void		athn_iter_calib(void *, struct ieee80211_node *);
98 int		athn_cap_noisefloor(struct athn_softc *, int);
99 int		athn_nf_hist_mid(int *, int);
100 void		athn_filter_noisefloor(struct athn_softc *);
101 void		athn_start_noisefloor_calib(struct athn_softc *, int);
102 void		athn_calib_to(void *);
103 int		athn_init_calib(struct athn_softc *,
104 		    struct ieee80211_channel *, struct ieee80211_channel *);
105 uint8_t		athn_chan2fbin(struct ieee80211_channel *);
106 int		athn_interpolate(int, int, int, int, int);
107 void		athn_get_pier_ival(uint8_t, const uint8_t *, int, int *,
108 		    int *);
109 void		athn_init_dma(struct athn_softc *);
110 void		athn_rx_start(struct athn_softc *);
111 void		athn_inc_tx_trigger_level(struct athn_softc *);
112 int		athn_stop_rx_dma(struct athn_softc *);
113 int		athn_rx_abort(struct athn_softc *);
114 void		athn_tx_reclaim(struct athn_softc *, int);
115 int		athn_tx_pending(struct athn_softc *, int);
116 void		athn_stop_tx_dma(struct athn_softc *, int);
117 int		athn_txtime(struct athn_softc *, int, int, u_int);
118 void		athn_set_sta_timers(struct athn_softc *);
119 void		athn_set_hostap_timers(struct athn_softc *);
120 void		athn_set_opmode(struct athn_softc *);
121 void		athn_set_bss(struct athn_softc *, struct ieee80211_node *);
122 void		athn_enable_interrupts(struct athn_softc *);
123 void		athn_disable_interrupts(struct athn_softc *);
124 void		athn_init_qos(struct athn_softc *);
125 int		athn_hw_reset(struct athn_softc *, struct ieee80211_channel *,
126 		    struct ieee80211_channel *, int);
127 struct		ieee80211_node *athn_node_alloc(struct ieee80211com *);
128 void		athn_newassoc(struct ieee80211com *, struct ieee80211_node *,
129 		    int);
130 void		athn_node_leave(struct ieee80211com *, struct ieee80211_node *);
131 int		athn_media_change(struct ifnet *);
132 void		athn_next_scan(void *);
133 void		athn_iter_mira_delete(void *, struct ieee80211_node *);
134 void		athn_delete_mira_nodes(struct athn_softc *);
135 int		athn_newstate(struct ieee80211com *, enum ieee80211_state,
136 		    int);
137 void		athn_updateedca(struct ieee80211com *);
138 int		athn_clock_rate(struct athn_softc *);
139 int		athn_chan_sifs(struct ieee80211_channel *);
140 void		athn_setsifs(struct athn_softc *);
141 int		athn_acktimeout(struct ieee80211_channel *, int);
142 void		athn_setacktimeout(struct athn_softc *,
143 		    struct ieee80211_channel *, int);
144 void		athn_setctstimeout(struct athn_softc *,
145 		    struct ieee80211_channel *, int);
146 void		athn_setclockrate(struct athn_softc *);
147 void		athn_updateslot(struct ieee80211com *);
148 void		athn_start(struct ifnet *);
149 void		athn_watchdog(struct ifnet *);
150 void		athn_set_multi(struct athn_softc *);
151 int		athn_ioctl(struct ifnet *, u_long, caddr_t);
152 int		athn_init(struct ifnet *);
153 void		athn_stop(struct ifnet *, int);
154 void		athn_init_tx_queues(struct athn_softc *);
155 int32_t		athn_ani_get_rssi(struct athn_softc *);
156 void		athn_ani_ofdm_err_trigger(struct athn_softc *);
157 void		athn_ani_cck_err_trigger(struct athn_softc *);
158 void		athn_ani_lower_immunity(struct athn_softc *);
159 void		athn_ani_restart(struct athn_softc *);
160 void		athn_ani_monitor(struct athn_softc *);
161 
162 /* Extern functions. */
163 int		ar5416_attach(struct athn_softc *);
164 int		ar9280_attach(struct athn_softc *);
165 int		ar9285_attach(struct athn_softc *);
166 int		ar9287_attach(struct athn_softc *);
167 int		ar9380_attach(struct athn_softc *);
168 int		ar5416_init_calib(struct athn_softc *,
169 		    struct ieee80211_channel *, struct ieee80211_channel *);
170 int		ar9285_init_calib(struct athn_softc *,
171 		    struct ieee80211_channel *, struct ieee80211_channel *);
172 int		ar9003_init_calib(struct athn_softc *);
173 void		ar9285_pa_calib(struct athn_softc *);
174 void		ar9271_pa_calib(struct athn_softc *);
175 void		ar9287_1_3_enable_async_fifo(struct athn_softc *);
176 void		ar9287_1_3_setup_async_fifo(struct athn_softc *);
177 void		ar9003_reset_txsring(struct athn_softc *);
178 
179 struct cfdriver athn_cd = {
180 	NULL, "athn", DV_IFNET
181 };
182 
183 void
184 athn_config_ht(struct athn_softc *sc)
185 {
186 	struct ieee80211com *ic = &sc->sc_ic;
187 	int i, ntxstreams, nrxstreams;
188 
189 	if ((sc->flags & ATHN_FLAG_11N) == 0)
190 		return;
191 
192 	/* Set HT capabilities. */
193 	ic->ic_htcaps = (IEEE80211_HTCAP_SMPS_DIS <<
194 	    IEEE80211_HTCAP_SMPS_SHIFT);
195 #ifdef notyet
196 	ic->ic_htcaps |= IEEE80211_HTCAP_CBW20_40 |
197 	    IEEE80211_HTCAP_SGI40 |
198 	    IEEE80211_HTCAP_DSSSCCK40;
199 #endif
200 	ic->ic_htxcaps = 0;
201 #ifdef notyet
202 	if (AR_SREV_9271(sc) || AR_SREV_9287_10_OR_LATER(sc))
203 		ic->ic_htcaps |= IEEE80211_HTCAP_SGI20;
204 	if (AR_SREV_9380_10_OR_LATER(sc))
205 		ic->ic_htcaps |= IEEE80211_HTCAP_LDPC;
206 	if (AR_SREV_9280_10_OR_LATER(sc)) {
207 		ic->ic_htcaps |= IEEE80211_HTCAP_TXSTBC;
208 		ic->ic_htcaps |= 1 << IEEE80211_HTCAP_RXSTBC_SHIFT;
209 	}
210 #endif
211 	ntxstreams = sc->ntxchains;
212 	nrxstreams = sc->nrxchains;
213 	if (!AR_SREV_9380_10_OR_LATER(sc)) {
214 		ntxstreams = MIN(ntxstreams, 2);
215 		nrxstreams = MIN(nrxstreams, 2);
216 	}
217 	/* Set supported HT rates. */
218 	if (ic->ic_userflags & IEEE80211_F_NOMIMO)
219 		ntxstreams = nrxstreams = 1;
220 	memset(ic->ic_sup_mcs, 0, sizeof(ic->ic_sup_mcs));
221 	for (i = 0; i < nrxstreams; i++)
222 		ic->ic_sup_mcs[i] = 0xff;
223 	ic->ic_tx_mcs_set = IEEE80211_TX_MCS_SET_DEFINED;
224 	if (ntxstreams != nrxstreams) {
225 		ic->ic_tx_mcs_set |= IEEE80211_TX_RX_MCS_NOT_EQUAL;
226 		ic->ic_tx_mcs_set |= (ntxstreams - 1) << 2;
227 	}
228 }
229 
230 int
231 athn_attach(struct athn_softc *sc)
232 {
233 	struct ieee80211com *ic = &sc->sc_ic;
234 	struct ifnet *ifp = &ic->ic_if;
235 	int error;
236 
237 	/* Read hardware revision. */
238 	athn_get_chipid(sc);
239 
240 	if ((error = athn_reset_power_on(sc)) != 0) {
241 		printf("%s: could not reset chip\n", sc->sc_dev.dv_xname);
242 		return (error);
243 	}
244 
245 	if ((error = athn_set_power_awake(sc)) != 0) {
246 		printf("%s: could not wakeup chip\n", sc->sc_dev.dv_xname);
247 		return (error);
248 	}
249 
250 	if (AR_SREV_5416(sc) || AR_SREV_9160(sc))
251 		error = ar5416_attach(sc);
252 	else if (AR_SREV_9280(sc))
253 		error = ar9280_attach(sc);
254 	else if (AR_SREV_9285(sc))
255 		error = ar9285_attach(sc);
256 #if NATHN_USB > 0
257 	else if (AR_SREV_9271(sc))
258 		error = ar9285_attach(sc);
259 #endif
260 	else if (AR_SREV_9287(sc))
261 		error = ar9287_attach(sc);
262 	else if (AR_SREV_9380(sc) || AR_SREV_9485(sc))
263 		error = ar9380_attach(sc);
264 	else
265 		error = ENOTSUP;
266 	if (error != 0) {
267 		printf("%s: could not attach chip\n", sc->sc_dev.dv_xname);
268 		return (error);
269 	}
270 
271 	/* We can put the chip in sleep state now. */
272 	athn_set_power_sleep(sc);
273 
274 	if (!(sc->flags & ATHN_FLAG_USB)) {
275 		error = sc->ops.dma_alloc(sc);
276 		if (error != 0) {
277 			printf("%s: could not allocate DMA resources\n",
278 			    sc->sc_dev.dv_xname);
279 			return (error);
280 		}
281 		/* Steal one Tx buffer for beacons. */
282 		sc->bcnbuf = SIMPLEQ_FIRST(&sc->txbufs);
283 		SIMPLEQ_REMOVE_HEAD(&sc->txbufs, bf_list);
284 	}
285 
286 	if (sc->flags & ATHN_FLAG_RFSILENT) {
287 		DPRINTF(("found RF switch connected to GPIO pin %d\n",
288 		    sc->rfsilent_pin));
289 	}
290 	DPRINTF(("%d key cache entries\n", sc->kc_entries));
291 	/*
292 	 * In HostAP mode, the number of STAs that we can handle is
293 	 * limited by the number of entries in the HW key cache.
294 	 * TKIP keys would consume 2 entries in this cache but we
295 	 * only use the hardware crypto engine for CCMP.
296 	 */
297 	ic->ic_max_nnodes = sc->kc_entries - IEEE80211_WEP_NKID;
298 	if (ic->ic_max_nnodes > IEEE80211_CACHE_SIZE)
299 		ic->ic_max_nnodes = IEEE80211_CACHE_SIZE;
300 
301 	DPRINTF(("using %s loop power control\n",
302 	    (sc->flags & ATHN_FLAG_OLPC) ? "open" : "closed"));
303 
304 	DPRINTF(("txchainmask=0x%x rxchainmask=0x%x\n",
305 	    sc->txchainmask, sc->rxchainmask));
306 	/* Count the number of bits set (in lowest 3 bits). */
307 	sc->ntxchains =
308 	    ((sc->txchainmask >> 2) & 1) +
309 	    ((sc->txchainmask >> 1) & 1) +
310 	    ((sc->txchainmask >> 0) & 1);
311 	sc->nrxchains =
312 	    ((sc->rxchainmask >> 2) & 1) +
313 	    ((sc->rxchainmask >> 1) & 1) +
314 	    ((sc->rxchainmask >> 0) & 1);
315 
316 	if (AR_SINGLE_CHIP(sc)) {
317 		printf("%s: %s rev %d (%dT%dR), ROM rev %d, address %s\n",
318 		    sc->sc_dev.dv_xname, athn_get_mac_name(sc), sc->mac_rev,
319 		    sc->ntxchains, sc->nrxchains, sc->eep_rev,
320 		    ether_sprintf(ic->ic_myaddr));
321 	} else {
322 		printf("%s: MAC %s rev %d, RF %s (%dT%dR), ROM rev %d, "
323 		    "address %s\n",
324 		    sc->sc_dev.dv_xname, athn_get_mac_name(sc), sc->mac_rev,
325 		    athn_get_rf_name(sc), sc->ntxchains, sc->nrxchains,
326 		    sc->eep_rev, ether_sprintf(ic->ic_myaddr));
327 	}
328 
329 	timeout_set(&sc->scan_to, athn_next_scan, sc);
330 	timeout_set(&sc->calib_to, athn_calib_to, sc);
331 
332 	sc->amrr.amrr_min_success_threshold =  1;
333 	sc->amrr.amrr_max_success_threshold = 15;
334 
335 	ic->ic_phytype = IEEE80211_T_OFDM;	/* not only, but not used */
336 	ic->ic_opmode = IEEE80211_M_STA;	/* default to BSS mode */
337 	ic->ic_state = IEEE80211_S_INIT;
338 
339 	/* Set device capabilities. */
340 	ic->ic_caps =
341 	    IEEE80211_C_WEP |		/* WEP. */
342 	    IEEE80211_C_RSN |		/* WPA/RSN. */
343 #ifndef IEEE80211_STA_ONLY
344 	    IEEE80211_C_HOSTAP |	/* Host AP mode supported. */
345 	    IEEE80211_C_APPMGT |	/* Host AP power saving supported. */
346 #endif
347 	    IEEE80211_C_MONITOR |	/* Monitor mode supported. */
348 	    IEEE80211_C_SHSLOT |	/* Short slot time supported. */
349 	    IEEE80211_C_SHPREAMBLE |	/* Short preamble supported. */
350 	    IEEE80211_C_PMGT;		/* Power saving supported. */
351 
352 	athn_config_ht(sc);
353 
354 	/* Set supported rates. */
355 	if (sc->flags & ATHN_FLAG_11G) {
356 		ic->ic_sup_rates[IEEE80211_MODE_11B] =
357 		    ieee80211_std_rateset_11b;
358 		ic->ic_sup_rates[IEEE80211_MODE_11G] =
359 		    ieee80211_std_rateset_11g;
360 	}
361 	if (sc->flags & ATHN_FLAG_11A) {
362 		ic->ic_sup_rates[IEEE80211_MODE_11A] =
363 		    ieee80211_std_rateset_11a;
364 	}
365 
366 	/* Get the list of authorized/supported channels. */
367 	athn_get_chanlist(sc);
368 
369 	/* IBSS channel undefined for now. */
370 	ic->ic_ibss_chan = &ic->ic_channels[0];
371 
372 	ifp->if_softc = sc;
373 	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
374 	ifp->if_ioctl = athn_ioctl;
375 	ifp->if_start = athn_start;
376 	ifp->if_watchdog = athn_watchdog;
377 	memcpy(ifp->if_xname, sc->sc_dev.dv_xname, IFNAMSIZ);
378 
379 	if_attach(ifp);
380 	ieee80211_ifattach(ifp);
381 	ic->ic_node_alloc = athn_node_alloc;
382 #ifndef IEEE80211_STA_ONLY
383 	ic->ic_node_leave = athn_node_leave;
384 #endif
385 	ic->ic_newassoc = athn_newassoc;
386 	ic->ic_updateslot = athn_updateslot;
387 	ic->ic_updateedca = athn_updateedca;
388 	ic->ic_set_key = athn_set_key;
389 	ic->ic_delete_key = athn_delete_key;
390 
391 	/* Override 802.11 state transition machine. */
392 	sc->sc_newstate = ic->ic_newstate;
393 	ic->ic_newstate = athn_newstate;
394 	ieee80211_media_init(ifp, athn_media_change, ieee80211_media_status);
395 
396 #if NBPFILTER > 0
397 	athn_radiotap_attach(sc);
398 #endif
399 
400 	return (0);
401 }
402 
403 void
404 athn_detach(struct athn_softc *sc)
405 {
406 	struct ifnet *ifp = &sc->sc_ic.ic_if;
407 	struct ieee80211com *ic = &sc->sc_ic;
408 	int qid;
409 
410 	timeout_del(&sc->scan_to);
411 	timeout_del(&sc->calib_to);
412 	if (ic->ic_flags & IEEE80211_F_HTON)
413 		athn_delete_mira_nodes(sc);
414 
415 	if (!(sc->flags & ATHN_FLAG_USB)) {
416 		for (qid = 0; qid < ATHN_QID_COUNT; qid++)
417 			athn_tx_reclaim(sc, qid);
418 
419 		/* Free Tx/Rx DMA resources. */
420 		sc->ops.dma_free(sc);
421 	}
422 	/* Free ROM copy. */
423 	if (sc->eep != NULL)
424 		free(sc->eep, M_DEVBUF, 0);
425 
426 	ieee80211_ifdetach(ifp);
427 	if_detach(ifp);
428 }
429 
430 #if NBPFILTER > 0
431 /*
432  * Attach the interface to 802.11 radiotap.
433  */
434 void
435 athn_radiotap_attach(struct athn_softc *sc)
436 {
437 	bpfattach(&sc->sc_drvbpf, &sc->sc_ic.ic_if, DLT_IEEE802_11_RADIO,
438 	    sizeof(struct ieee80211_frame) + IEEE80211_RADIOTAP_HDRLEN);
439 
440 	sc->sc_rxtap_len = sizeof(sc->sc_rxtapu);
441 	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
442 	sc->sc_rxtap.wr_ihdr.it_present = htole32(ATHN_RX_RADIOTAP_PRESENT);
443 
444 	sc->sc_txtap_len = sizeof(sc->sc_txtapu);
445 	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
446 	sc->sc_txtap.wt_ihdr.it_present = htole32(ATHN_TX_RADIOTAP_PRESENT);
447 }
448 #endif
449 
450 void
451 athn_get_chanlist(struct athn_softc *sc)
452 {
453 	struct ieee80211com *ic = &sc->sc_ic;
454 	uint8_t chan;
455 	int i;
456 
457 	if (sc->flags & ATHN_FLAG_11G) {
458 		for (i = 1; i <= 14; i++) {
459 			chan = i;
460 			ic->ic_channels[chan].ic_freq =
461 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_2GHZ);
462 			ic->ic_channels[chan].ic_flags =
463 			    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
464 			    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
465 			if (sc->flags & ATHN_FLAG_11N)
466 				ic->ic_channels[chan].ic_flags |=
467 				    IEEE80211_CHAN_HT;
468 		}
469 	}
470 	if (sc->flags & ATHN_FLAG_11A) {
471 		for (i = 0; i < nitems(athn_5ghz_chans); i++) {
472 			chan = athn_5ghz_chans[i];
473 			ic->ic_channels[chan].ic_freq =
474 			    ieee80211_ieee2mhz(chan, IEEE80211_CHAN_5GHZ);
475 			ic->ic_channels[chan].ic_flags = IEEE80211_CHAN_A;
476 			if (sc->flags & ATHN_FLAG_11N)
477 				ic->ic_channels[chan].ic_flags |=
478 				    IEEE80211_CHAN_HT;
479 		}
480 	}
481 }
482 
483 void
484 athn_rx_start(struct athn_softc *sc)
485 {
486 	struct ieee80211com *ic = &sc->sc_ic;
487 	uint32_t rfilt;
488 
489 	/* Setup Rx DMA descriptors. */
490 	sc->ops.rx_enable(sc);
491 
492 	/* Set Rx filter. */
493 	rfilt = AR_RX_FILTER_UCAST | AR_RX_FILTER_BCAST | AR_RX_FILTER_MCAST;
494 	/* Want Compressed Block Ack Requests. */
495 	rfilt |= AR_RX_FILTER_COMPR_BAR;
496 	rfilt |= AR_RX_FILTER_BEACON;
497 	if (ic->ic_opmode != IEEE80211_M_STA) {
498 		rfilt |= AR_RX_FILTER_PROBEREQ;
499 		if (ic->ic_opmode == IEEE80211_M_MONITOR)
500 			rfilt |= AR_RX_FILTER_PROM;
501 #ifndef IEEE80211_STA_ONLY
502 		if (AR_SREV_9280_10_OR_LATER(sc) &&
503 		    ic->ic_opmode == IEEE80211_M_HOSTAP)
504 			rfilt |= AR_RX_FILTER_PSPOLL;
505 #endif
506 	}
507 	athn_set_rxfilter(sc, rfilt);
508 
509 	/* Set BSSID mask. */
510 	AR_WRITE(sc, AR_BSSMSKL, 0xffffffff);
511 	AR_WRITE(sc, AR_BSSMSKU, 0xffff);
512 
513 	athn_set_opmode(sc);
514 
515 	/* Set multicast filter. */
516 	AR_WRITE(sc, AR_MCAST_FIL0, 0xffffffff);
517 	AR_WRITE(sc, AR_MCAST_FIL1, 0xffffffff);
518 
519 	AR_WRITE(sc, AR_FILT_OFDM, 0);
520 	AR_WRITE(sc, AR_FILT_CCK, 0);
521 	AR_WRITE(sc, AR_MIBC, 0);
522 	AR_WRITE(sc, AR_PHY_ERR_MASK_1, AR_PHY_ERR_OFDM_TIMING);
523 	AR_WRITE(sc, AR_PHY_ERR_MASK_2, AR_PHY_ERR_CCK_TIMING);
524 
525 	/* XXX ANI. */
526 	AR_WRITE(sc, AR_PHY_ERR_1, 0);
527 	AR_WRITE(sc, AR_PHY_ERR_2, 0);
528 
529 	/* Disable HW crypto for now. */
530 	AR_SETBITS(sc, AR_DIAG_SW, AR_DIAG_ENCRYPT_DIS | AR_DIAG_DECRYPT_DIS);
531 
532 	/* Start PCU Rx. */
533 	AR_CLRBITS(sc, AR_DIAG_SW, AR_DIAG_RX_DIS | AR_DIAG_RX_ABORT);
534 	AR_WRITE_BARRIER(sc);
535 }
536 
537 void
538 athn_set_rxfilter(struct athn_softc *sc, uint32_t rfilt)
539 {
540 	AR_WRITE(sc, AR_RX_FILTER, rfilt);
541 
542 #ifdef notyet
543 	reg = AR_READ(sc, AR_PHY_ERR);
544 	reg &= (AR_PHY_ERR_RADAR | AR_PHY_ERR_OFDM_TIMING |
545 	    AR_PHY_ERR_CCK_TIMING);
546 	AR_WRITE(sc, AR_PHY_ERR, reg);
547 	if (reg != 0)
548 		AR_SETBITS(sc, AR_RXCFG, AR_RXCFG_ZLFDMA);
549 	else
550 		AR_CLRBITS(sc, AR_RXCFG, AR_RXCFG_ZLFDMA);
551 #else
552 	AR_WRITE(sc, AR_PHY_ERR, 0);
553 	AR_CLRBITS(sc, AR_RXCFG, AR_RXCFG_ZLFDMA);
554 #endif
555 	AR_WRITE_BARRIER(sc);
556 }
557 
558 int
559 athn_intr(void *xsc)
560 {
561 	struct athn_softc *sc = xsc;
562 	struct ifnet *ifp = &sc->sc_ic.ic_if;
563 
564 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) !=
565 	    (IFF_UP | IFF_RUNNING))
566 		return (0);
567 
568 	return (sc->ops.intr(sc));
569 }
570 
571 void
572 athn_get_chipid(struct athn_softc *sc)
573 {
574 	uint32_t reg;
575 
576 	reg = AR_READ(sc, AR_SREV);
577 	if (MS(reg, AR_SREV_ID) == 0xff) {
578 		sc->mac_ver = MS(reg, AR_SREV_VERSION2);
579 		sc->mac_rev = MS(reg, AR_SREV_REVISION2);
580 		if (!(reg & AR_SREV_TYPE2_HOST_MODE))
581 			sc->flags |= ATHN_FLAG_PCIE;
582 	} else {
583 		sc->mac_ver = MS(reg, AR_SREV_VERSION);
584 		sc->mac_rev = MS(reg, AR_SREV_REVISION);
585 		if (sc->mac_ver == AR_SREV_VERSION_5416_PCIE)
586 			sc->flags |= ATHN_FLAG_PCIE;
587 	}
588 }
589 
590 const char *
591 athn_get_mac_name(struct athn_softc *sc)
592 {
593 	switch (sc->mac_ver) {
594 	case AR_SREV_VERSION_5416_PCI:
595 		return ("AR5416");
596 	case AR_SREV_VERSION_5416_PCIE:
597 		return ("AR5418");
598 	case AR_SREV_VERSION_9160:
599 		return ("AR9160");
600 	case AR_SREV_VERSION_9280:
601 		return ("AR9280");
602 	case AR_SREV_VERSION_9285:
603 		return ("AR9285");
604 	case AR_SREV_VERSION_9271:
605 		return ("AR9271");
606 	case AR_SREV_VERSION_9287:
607 		return ("AR9287");
608 	case AR_SREV_VERSION_9380:
609 		return ("AR9380");
610 	case AR_SREV_VERSION_9485:
611 		return ("AR9485");
612 	}
613 	return ("unknown");
614 }
615 
616 /*
617  * Return RF chip name (not for single-chip solutions).
618  */
619 const char *
620 athn_get_rf_name(struct athn_softc *sc)
621 {
622 	KASSERT(!AR_SINGLE_CHIP(sc));
623 
624 	switch (sc->rf_rev) {
625 	case AR_RAD5133_SREV_MAJOR:	/* Dual-band 3T3R. */
626 		return ("AR5133");
627 	case AR_RAD2133_SREV_MAJOR:	/* Single-band 3T3R. */
628 		return ("AR2133");
629 	case AR_RAD5122_SREV_MAJOR:	/* Dual-band 2T2R. */
630 		return ("AR5122");
631 	case AR_RAD2122_SREV_MAJOR:	/* Single-band 2T2R. */
632 		return ("AR2122");
633 	}
634 	return ("unknown");
635 }
636 
637 int
638 athn_reset_power_on(struct athn_softc *sc)
639 {
640 	int ntries;
641 
642 	/* Set force wake. */
643 	AR_WRITE(sc, AR_RTC_FORCE_WAKE,
644 	    AR_RTC_FORCE_WAKE_EN | AR_RTC_FORCE_WAKE_ON_INT);
645 
646 	if (!AR_SREV_9380_10_OR_LATER(sc)) {
647 		/* Make sure no DMA is active by doing an AHB reset. */
648 		AR_WRITE(sc, AR_RC, AR_RC_AHB);
649 	}
650 	/* RTC reset and clear. */
651 	AR_WRITE(sc, AR_RTC_RESET, 0);
652 	AR_WRITE_BARRIER(sc);
653 	DELAY(2);
654 	if (!AR_SREV_9380_10_OR_LATER(sc))
655 		AR_WRITE(sc, AR_RC, 0);
656 	AR_WRITE(sc, AR_RTC_RESET, 1);
657 
658 	/* Poll until RTC is ON. */
659 	for (ntries = 0; ntries < 1000; ntries++) {
660 		if ((AR_READ(sc, AR_RTC_STATUS) & AR_RTC_STATUS_M) ==
661 		    AR_RTC_STATUS_ON)
662 			break;
663 		DELAY(10);
664 	}
665 	if (ntries == 1000) {
666 		DPRINTF(("RTC not waking up\n"));
667 		return (ETIMEDOUT);
668 	}
669 	return (athn_reset(sc, 0));
670 }
671 
672 int
673 athn_reset(struct athn_softc *sc, int cold)
674 {
675 	int ntries;
676 
677 	/* Set force wake. */
678 	AR_WRITE(sc, AR_RTC_FORCE_WAKE,
679 	    AR_RTC_FORCE_WAKE_EN | AR_RTC_FORCE_WAKE_ON_INT);
680 
681 	if (AR_READ(sc, AR_INTR_SYNC_CAUSE) &
682 	    (AR_INTR_SYNC_LOCAL_TIMEOUT | AR_INTR_SYNC_RADM_CPL_TIMEOUT)) {
683 		AR_WRITE(sc, AR_INTR_SYNC_ENABLE, 0);
684 		AR_WRITE(sc, AR_RC, AR_RC_HOSTIF |
685 		    (!AR_SREV_9380_10_OR_LATER(sc) ? AR_RC_AHB : 0));
686 	} else if (!AR_SREV_9380_10_OR_LATER(sc))
687 		AR_WRITE(sc, AR_RC, AR_RC_AHB);
688 
689 	AR_WRITE(sc, AR_RTC_RC, AR_RTC_RC_MAC_WARM |
690 	    (cold ? AR_RTC_RC_MAC_COLD : 0));
691 	AR_WRITE_BARRIER(sc);
692 	DELAY(50);
693 	AR_WRITE(sc, AR_RTC_RC, 0);
694 	for (ntries = 0; ntries < 1000; ntries++) {
695 		if (!(AR_READ(sc, AR_RTC_RC) &
696 		      (AR_RTC_RC_MAC_WARM | AR_RTC_RC_MAC_COLD)))
697 			break;
698 		DELAY(10);
699 	}
700 	if (ntries == 1000) {
701 		DPRINTF(("RTC stuck in MAC reset\n"));
702 		return (ETIMEDOUT);
703 	}
704 	AR_WRITE(sc, AR_RC, 0);
705 	AR_WRITE_BARRIER(sc);
706 	return (0);
707 }
708 
709 int
710 athn_set_power_awake(struct athn_softc *sc)
711 {
712 	int ntries, error;
713 
714 	/* Do a Power-On-Reset if shutdown. */
715 	if ((AR_READ(sc, AR_RTC_STATUS) & AR_RTC_STATUS_M) ==
716 	    AR_RTC_STATUS_SHUTDOWN) {
717 		if ((error = athn_reset_power_on(sc)) != 0)
718 			return (error);
719 		if (!AR_SREV_9380_10_OR_LATER(sc))
720 			athn_init_pll(sc, NULL);
721 	}
722 	AR_SETBITS(sc, AR_RTC_FORCE_WAKE, AR_RTC_FORCE_WAKE_EN);
723 	AR_WRITE_BARRIER(sc);
724 	DELAY(50);	/* Give chip the chance to awake. */
725 
726 	/* Poll until RTC is ON. */
727 	for (ntries = 0; ntries < 4000; ntries++) {
728 		if ((AR_READ(sc, AR_RTC_STATUS) & AR_RTC_STATUS_M) ==
729 		    AR_RTC_STATUS_ON)
730 			break;
731 		DELAY(50);
732 		AR_SETBITS(sc, AR_RTC_FORCE_WAKE, AR_RTC_FORCE_WAKE_EN);
733 	}
734 	if (ntries == 4000) {
735 		DPRINTF(("RTC not waking up\n"));
736 		return (ETIMEDOUT);
737 	}
738 
739 	AR_CLRBITS(sc, AR_STA_ID1, AR_STA_ID1_PWR_SAV);
740 	AR_WRITE_BARRIER(sc);
741 	return (0);
742 }
743 
744 void
745 athn_set_power_sleep(struct athn_softc *sc)
746 {
747 	AR_SETBITS(sc, AR_STA_ID1, AR_STA_ID1_PWR_SAV);
748 	/* Allow the MAC to go to sleep. */
749 	AR_CLRBITS(sc, AR_RTC_FORCE_WAKE, AR_RTC_FORCE_WAKE_EN);
750 	if (!AR_SREV_9380_10_OR_LATER(sc))
751 		AR_WRITE(sc, AR_RC, AR_RC_AHB | AR_RC_HOSTIF);
752 	/*
753 	 * NB: Clearing RTC_RESET_EN when setting the chip to sleep mode
754 	 * results in high power consumption on AR5416 chipsets.
755 	 */
756 	if (!AR_SREV_5416(sc) && !AR_SREV_9271(sc))
757 		AR_CLRBITS(sc, AR_RTC_RESET, AR_RTC_RESET_EN);
758 	AR_WRITE_BARRIER(sc);
759 }
760 
761 void
762 athn_init_pll(struct athn_softc *sc, const struct ieee80211_channel *c)
763 {
764 	uint32_t pll;
765 
766 	if (AR_SREV_9380_10_OR_LATER(sc)) {
767 		if (AR_SREV_9485(sc))
768 			AR_WRITE(sc, AR_RTC_PLL_CONTROL2, 0x886666);
769 		pll = SM(AR_RTC_9160_PLL_REFDIV, 0x5);
770 		pll |= SM(AR_RTC_9160_PLL_DIV, 0x2c);
771 	} else if (AR_SREV_9280_10_OR_LATER(sc)) {
772 		pll = SM(AR_RTC_9160_PLL_REFDIV, 0x05);
773 		if (c != NULL && IEEE80211_IS_CHAN_5GHZ(c)) {
774 			if (sc->flags & ATHN_FLAG_FAST_PLL_CLOCK)
775 				pll = 0x142c;
776 			else if (AR_SREV_9280_20(sc))
777 		 		pll = 0x2850;
778 			else
779 				pll |= SM(AR_RTC_9160_PLL_DIV, 0x28);
780 		} else
781 			pll |= SM(AR_RTC_9160_PLL_DIV, 0x2c);
782 	} else if (AR_SREV_9160_10_OR_LATER(sc)) {
783 		pll = SM(AR_RTC_9160_PLL_REFDIV, 0x05);
784 		if (c != NULL && IEEE80211_IS_CHAN_5GHZ(c))
785 			pll |= SM(AR_RTC_9160_PLL_DIV, 0x50);
786 		else
787 			pll |= SM(AR_RTC_9160_PLL_DIV, 0x58);
788 	} else {
789 		pll = AR_RTC_PLL_REFDIV_5 | AR_RTC_PLL_DIV2;
790 		if (c != NULL && IEEE80211_IS_CHAN_5GHZ(c))
791 			pll |= SM(AR_RTC_PLL_DIV, 0x0a);
792 		else
793 			pll |= SM(AR_RTC_PLL_DIV, 0x0b);
794 	}
795 	DPRINTFN(5, ("AR_RTC_PLL_CONTROL=0x%08x\n", pll));
796 	AR_WRITE(sc, AR_RTC_PLL_CONTROL, pll);
797 	if (AR_SREV_9271(sc)) {
798 		/* Switch core clock to 117MHz. */
799 		AR_WRITE_BARRIER(sc);
800 		DELAY(500);
801 		AR_WRITE(sc, AR9271_CLOCK_CONTROL, 0x304);
802 	}
803 	AR_WRITE_BARRIER(sc);
804 	DELAY(100);
805 	AR_WRITE(sc, AR_RTC_SLEEP_CLK, AR_RTC_FORCE_DERIVED_CLK);
806 	AR_WRITE_BARRIER(sc);
807 }
808 
809 void
810 athn_write_serdes(struct athn_softc *sc, const struct athn_serdes *serdes)
811 {
812 	int i;
813 
814 	/* Write sequence to Serializer/Deserializer. */
815 	for (i = 0; i < serdes->nvals; i++)
816 		AR_WRITE(sc, serdes->regs[i], serdes->vals[i]);
817 	AR_WRITE_BARRIER(sc);
818 }
819 
820 void
821 athn_config_pcie(struct athn_softc *sc)
822 {
823 	/* Disable PLL when in L0s as well as receiver clock when in L1. */
824 	athn_write_serdes(sc, sc->serdes);
825 
826 	DELAY(1000);
827 	/* Allow forcing of PCIe core into L1 state. */
828 	AR_SETBITS(sc, AR_PCIE_PM_CTRL, AR_PCIE_PM_CTRL_ENA);
829 
830 #ifndef ATHN_PCIE_WAEN
831 	AR_WRITE(sc, AR_WA, sc->workaround);
832 #else
833 	AR_WRITE(sc, AR_WA, ATHN_PCIE_WAEN);
834 #endif
835 	AR_WRITE_BARRIER(sc);
836 }
837 
838 /*
839  * Serializer/Deserializer programming for non-PCIe devices.
840  */
841 static const uint32_t ar_nonpcie_serdes_regs[] = {
842 	AR_PCIE_SERDES,
843 	AR_PCIE_SERDES,
844 	AR_PCIE_SERDES,
845 	AR_PCIE_SERDES,
846 	AR_PCIE_SERDES,
847 	AR_PCIE_SERDES,
848 	AR_PCIE_SERDES,
849 	AR_PCIE_SERDES,
850 	AR_PCIE_SERDES,
851 	AR_PCIE_SERDES2,
852 };
853 
854 static const uint32_t ar_nonpcie_serdes_vals[] = {
855 	0x9248fc00,
856 	0x24924924,
857 	0x28000029,
858 	0x57160824,
859 	0x25980579,
860 	0x00000000,
861 	0x1aaabe40,
862 	0xbe105554,
863 	0x000e1007,
864 	0x00000000
865 };
866 
867 static const struct athn_serdes ar_nonpcie_serdes = {
868 	nitems(ar_nonpcie_serdes_vals),
869 	ar_nonpcie_serdes_regs,
870 	ar_nonpcie_serdes_vals
871 };
872 
873 void
874 athn_config_nonpcie(struct athn_softc *sc)
875 {
876 	athn_write_serdes(sc, &ar_nonpcie_serdes);
877 }
878 
879 int
880 athn_set_chan(struct athn_softc *sc, struct ieee80211_channel *c,
881     struct ieee80211_channel *extc)
882 {
883 	struct athn_ops *ops = &sc->ops;
884 	int error, qid;
885 
886 	/* Check that Tx is stopped, otherwise RF Bus grant will not work. */
887 	for (qid = 0; qid < ATHN_QID_COUNT; qid++)
888 		if (athn_tx_pending(sc, qid))
889 			return (EBUSY);
890 
891 	/* Request RF Bus grant. */
892 	if ((error = ops->rf_bus_request(sc)) != 0)
893 		return (error);
894 
895 	ops->set_phy(sc, c, extc);
896 
897 	/* Change the synthesizer. */
898 	if ((error = ops->set_synth(sc, c, extc)) != 0)
899 		return (error);
900 
901 	sc->curchan = c;
902 	sc->curchanext = extc;
903 
904 	/* Set transmit power values for new channel. */
905 	ops->set_txpower(sc, c, extc);
906 
907 	/* Release the RF Bus grant. */
908 	ops->rf_bus_release(sc);
909 
910 	/* Write delta slope coeffs for modes where OFDM may be used. */
911 	if (sc->sc_ic.ic_curmode != IEEE80211_MODE_11B)
912 		ops->set_delta_slope(sc, c, extc);
913 
914 	ops->spur_mitigate(sc, c, extc);
915 
916 	return (0);
917 }
918 
919 int
920 athn_switch_chan(struct athn_softc *sc, struct ieee80211_channel *c,
921     struct ieee80211_channel *extc)
922 {
923 	int error, qid;
924 
925 	/* Disable interrupts. */
926 	athn_disable_interrupts(sc);
927 
928 	/* Stop all Tx queues. */
929 	for (qid = 0; qid < ATHN_QID_COUNT; qid++)
930 		athn_stop_tx_dma(sc, qid);
931 	for (qid = 0; qid < ATHN_QID_COUNT; qid++)
932 		athn_tx_reclaim(sc, qid);
933 
934 	/* Stop Rx. */
935 	AR_SETBITS(sc, AR_DIAG_SW, AR_DIAG_RX_DIS | AR_DIAG_RX_ABORT);
936 	AR_WRITE(sc, AR_MIBC, AR_MIBC_FMC);
937 	AR_WRITE(sc, AR_MIBC, AR_MIBC_CMC);
938 	AR_WRITE(sc, AR_FILT_OFDM, 0);
939 	AR_WRITE(sc, AR_FILT_CCK, 0);
940 	athn_set_rxfilter(sc, 0);
941 	error = athn_stop_rx_dma(sc);
942 	if (error != 0)
943 		goto reset;
944 
945 #ifdef notyet
946 	/* AR9280 needs a full reset. */
947 	if (AR_SREV_9280(sc))
948 #endif
949 		goto reset;
950 
951 	/* If band or bandwidth changes, we need to do a full reset. */
952 	if (c->ic_flags != sc->curchan->ic_flags ||
953 	    ((extc != NULL) ^ (sc->curchanext != NULL))) {
954 		DPRINTFN(2, ("channel band switch\n"));
955 		goto reset;
956 	}
957 	error = athn_set_power_awake(sc);
958 	if (error != 0)
959 		goto reset;
960 
961 	error = athn_set_chan(sc, c, extc);
962 	if (error != 0) {
963  reset:		/* Error found, try a full reset. */
964 		DPRINTFN(3, ("needs a full reset\n"));
965 		error = athn_hw_reset(sc, c, extc, 0);
966 		if (error != 0)	/* Hopeless case. */
967 			return (error);
968 	}
969 	athn_rx_start(sc);
970 
971 	/* Re-enable interrupts. */
972 	athn_enable_interrupts(sc);
973 	return (0);
974 }
975 
976 void
977 athn_get_delta_slope(uint32_t coeff, uint32_t *exponent, uint32_t *mantissa)
978 {
979 #define COEFF_SCALE_SHIFT	24
980 	uint32_t exp, man;
981 
982 	/* exponent = 14 - floor(log2(coeff)) */
983 	for (exp = 31; exp > 0; exp--)
984 		if (coeff & (1 << exp))
985 			break;
986 	exp = 14 - (exp - COEFF_SCALE_SHIFT);
987 
988 	/* mantissa = floor(coeff * 2^exponent + 0.5) */
989 	man = coeff + (1 << (COEFF_SCALE_SHIFT - exp - 1));
990 
991 	*mantissa = man >> (COEFF_SCALE_SHIFT - exp);
992 	*exponent = exp - 16;
993 #undef COEFF_SCALE_SHIFT
994 }
995 
996 void
997 athn_reset_key(struct athn_softc *sc, int entry)
998 {
999 	/*
1000 	 * NB: Key cache registers access special memory area that requires
1001 	 * two 32-bit writes to actually update the values in the internal
1002 	 * memory.  Consequently, writes must be grouped by pair.
1003 	 *
1004 	 * All writes to registers with an offset of 0x0 or 0x8 write to a
1005 	 * temporary register. A write to a register with an offset of 0x4
1006 	 * or 0xc writes concatenates the written value with the value in
1007 	 * the temporary register and writes the result to key cache memory.
1008 	 * The actual written memory area is 50 bits wide.
1009 	 */
1010 	AR_WRITE(sc, AR_KEYTABLE_KEY0(entry), 0);
1011 	AR_WRITE(sc, AR_KEYTABLE_KEY1(entry), 0);
1012 
1013 	AR_WRITE(sc, AR_KEYTABLE_KEY2(entry), 0);
1014 	AR_WRITE(sc, AR_KEYTABLE_KEY3(entry), 0);
1015 
1016 	AR_WRITE(sc, AR_KEYTABLE_KEY4(entry), 0);
1017 	AR_WRITE(sc, AR_KEYTABLE_TYPE(entry), AR_KEYTABLE_TYPE_CLR);
1018 
1019 	AR_WRITE(sc, AR_KEYTABLE_MAC0(entry), 0);
1020 	AR_WRITE(sc, AR_KEYTABLE_MAC1(entry), 0);
1021 
1022 	AR_WRITE_BARRIER(sc);
1023 }
1024 
1025 int
1026 athn_set_key(struct ieee80211com *ic, struct ieee80211_node *ni,
1027     struct ieee80211_key *k)
1028 {
1029 	struct athn_softc *sc = ic->ic_softc;
1030 	const uint8_t *key, *addr;
1031 	uintptr_t entry;
1032 	uint32_t lo, hi, unicast;
1033 
1034 	if (k->k_cipher != IEEE80211_CIPHER_CCMP) {
1035 		/* Use software crypto for ciphers other than CCMP. */
1036 		return ieee80211_set_key(ic, ni, k);
1037 	}
1038 
1039 	if (!(k->k_flags & IEEE80211_KEY_GROUP)) {
1040 #ifndef IEEE80211_STA_ONLY
1041 		if (ic->ic_opmode == IEEE80211_M_HOSTAP)
1042 			entry = IEEE80211_WEP_NKID + IEEE80211_AID(ni->ni_associd);
1043 		else
1044 #endif
1045 			entry = IEEE80211_WEP_NKID;
1046 		if (entry >= sc->kc_entries - IEEE80211_WEP_NKID)
1047 			return ENOSPC;
1048 	} else {
1049 		entry = k->k_id;
1050 		if (entry >= IEEE80211_WEP_NKID)
1051 			return ENOSPC;
1052 	}
1053 	k->k_priv = (void *)entry;
1054 
1055 	/* NB: See note about key cache registers access above. */
1056 	key = k->k_key;
1057 
1058 	AR_WRITE(sc, AR_KEYTABLE_KEY0(entry), LE_READ_4(&key[ 0]));
1059 	AR_WRITE(sc, AR_KEYTABLE_KEY1(entry), LE_READ_2(&key[ 4]));
1060 
1061 	AR_WRITE(sc, AR_KEYTABLE_KEY2(entry), LE_READ_4(&key[ 6]));
1062 	AR_WRITE(sc, AR_KEYTABLE_KEY3(entry), LE_READ_2(&key[10]));
1063 
1064 	AR_WRITE(sc, AR_KEYTABLE_KEY4(entry), LE_READ_4(&key[12]));
1065 	AR_WRITE(sc, AR_KEYTABLE_TYPE(entry), AR_KEYTABLE_TYPE_CCM);
1066 
1067 	unicast = AR_KEYTABLE_VALID;
1068 	if (!(k->k_flags & IEEE80211_KEY_GROUP)) {
1069 		addr = ni->ni_macaddr;
1070 		lo = LE_READ_4(&addr[0]);
1071 		hi = LE_READ_2(&addr[4]);
1072 		lo = lo >> 1 | hi << 31;
1073 		hi = hi >> 1;
1074 	} else {
1075 #ifndef IEEE80211_STA_ONLY
1076 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
1077 			uint8_t groupaddr[ETHER_ADDR_LEN];
1078 			IEEE80211_ADDR_COPY(groupaddr, ic->ic_myaddr);
1079 			groupaddr[0] |= 0x01;
1080 			lo = LE_READ_4(&groupaddr[0]);
1081 			hi = LE_READ_2(&groupaddr[4]);
1082 			lo = lo >> 1 | hi << 31;
1083 			hi = hi >> 1;
1084 			/*
1085 			 * KEYTABLE_VALID indicates that the address
1086 			 * is a unicast address which must match the
1087 			 * transmitter address when decrypting frames.
1088 			 * Not setting KEYTABLE_VALID allows hardware to
1089 			 * use this key for multicast frame decryption.
1090 			 */
1091 			unicast = 0;
1092 		} else
1093 #endif
1094 			lo = hi = 0;
1095 	}
1096 	AR_WRITE(sc, AR_KEYTABLE_MAC0(entry), lo);
1097 	AR_WRITE(sc, AR_KEYTABLE_MAC1(entry), hi | unicast);
1098 
1099 	AR_WRITE_BARRIER(sc);
1100 
1101 	/* Enable HW crypto. */
1102 	AR_CLRBITS(sc, AR_DIAG_SW, AR_DIAG_ENCRYPT_DIS | AR_DIAG_DECRYPT_DIS);
1103 
1104 	AR_WRITE_BARRIER(sc);
1105 	return (0);
1106 }
1107 
1108 void
1109 athn_delete_key(struct ieee80211com *ic, struct ieee80211_node *ni,
1110     struct ieee80211_key *k)
1111 {
1112 	struct athn_softc *sc = ic->ic_softc;
1113 	uintptr_t entry;
1114 
1115 	if (k->k_cipher == IEEE80211_CIPHER_CCMP) {
1116 		entry = (uintptr_t)k->k_priv;
1117 		athn_reset_key(sc, entry);
1118 		explicit_bzero(k, sizeof(*k));
1119 	} else
1120 		ieee80211_delete_key(ic, ni, k);
1121 }
1122 
1123 void
1124 athn_led_init(struct athn_softc *sc)
1125 {
1126 	struct athn_ops *ops = &sc->ops;
1127 
1128 	ops->gpio_config_output(sc, sc->led_pin, AR_GPIO_OUTPUT_MUX_AS_OUTPUT);
1129 	/* LED off, active low. */
1130 	athn_set_led(sc, 0);
1131 }
1132 
1133 void
1134 athn_set_led(struct athn_softc *sc, int on)
1135 {
1136 	struct athn_ops *ops = &sc->ops;
1137 
1138 	sc->led_state = on;
1139 	ops->gpio_write(sc, sc->led_pin, !sc->led_state);
1140 }
1141 
1142 #ifdef ATHN_BT_COEXISTENCE
1143 void
1144 athn_btcoex_init(struct athn_softc *sc)
1145 {
1146 	struct athn_ops *ops = &sc->ops;
1147 	uint32_t reg;
1148 
1149 	if (sc->flags & ATHN_FLAG_BTCOEX2WIRE) {
1150 		/* Connect bt_active to baseband. */
1151 		AR_CLRBITS(sc, sc->gpio_input_en_off,
1152 		    AR_GPIO_INPUT_EN_VAL_BT_PRIORITY_DEF |
1153 		    AR_GPIO_INPUT_EN_VAL_BT_FREQUENCY_DEF);
1154 		AR_SETBITS(sc, sc->gpio_input_en_off,
1155 		    AR_GPIO_INPUT_EN_VAL_BT_ACTIVE_BB);
1156 
1157 		reg = AR_READ(sc, AR_GPIO_INPUT_MUX1);
1158 		reg = RW(reg, AR_GPIO_INPUT_MUX1_BT_ACTIVE,
1159 		    AR_GPIO_BTACTIVE_PIN);
1160 		AR_WRITE(sc, AR_GPIO_INPUT_MUX1, reg);
1161 		AR_WRITE_BARRIER(sc);
1162 
1163 		ops->gpio_config_input(sc, AR_GPIO_BTACTIVE_PIN);
1164 	} else {	/* 3-wire. */
1165 		AR_SETBITS(sc, sc->gpio_input_en_off,
1166 		    AR_GPIO_INPUT_EN_VAL_BT_PRIORITY_BB |
1167 		    AR_GPIO_INPUT_EN_VAL_BT_ACTIVE_BB);
1168 
1169 		reg = AR_READ(sc, AR_GPIO_INPUT_MUX1);
1170 		reg = RW(reg, AR_GPIO_INPUT_MUX1_BT_ACTIVE,
1171 		    AR_GPIO_BTACTIVE_PIN);
1172 		reg = RW(reg, AR_GPIO_INPUT_MUX1_BT_PRIORITY,
1173 		    AR_GPIO_BTPRIORITY_PIN);
1174 		AR_WRITE(sc, AR_GPIO_INPUT_MUX1, reg);
1175 		AR_WRITE_BARRIER(sc);
1176 
1177 		ops->gpio_config_input(sc, AR_GPIO_BTACTIVE_PIN);
1178 		ops->gpio_config_input(sc, AR_GPIO_BTPRIORITY_PIN);
1179 	}
1180 }
1181 
1182 void
1183 athn_btcoex_enable(struct athn_softc *sc)
1184 {
1185 	struct athn_ops *ops = &sc->ops;
1186 	uint32_t reg;
1187 
1188 	if (sc->flags & ATHN_FLAG_BTCOEX3WIRE) {
1189 		AR_WRITE(sc, AR_BT_COEX_MODE,
1190 		    SM(AR_BT_MODE, AR_BT_MODE_SLOTTED) |
1191 		    SM(AR_BT_PRIORITY_TIME, 2) |
1192 		    SM(AR_BT_FIRST_SLOT_TIME, 5) |
1193 		    SM(AR_BT_QCU_THRESH, ATHN_QID_AC_BE) |
1194 		    AR_BT_TXSTATE_EXTEND | AR_BT_TX_FRAME_EXTEND |
1195 		    AR_BT_QUIET | AR_BT_RX_CLEAR_POLARITY);
1196 		AR_WRITE(sc, AR_BT_COEX_WEIGHT,
1197 		    SM(AR_BTCOEX_BT_WGHT, AR_STOMP_LOW_BT_WGHT) |
1198 		    SM(AR_BTCOEX_WL_WGHT, AR_STOMP_LOW_WL_WGHT));
1199 		AR_WRITE(sc, AR_BT_COEX_MODE2,
1200 		    SM(AR_BT_BCN_MISS_THRESH, 50) |
1201 		    AR_BT_HOLD_RX_CLEAR | AR_BT_DISABLE_BT_ANT);
1202 
1203 		AR_SETBITS(sc, AR_QUIET1, AR_QUIET1_QUIET_ACK_CTS_ENABLE);
1204 		AR_CLRBITS(sc, AR_PCU_MISC, AR_PCU_BT_ANT_PREVENT_RX);
1205 		AR_WRITE_BARRIER(sc);
1206 
1207 		ops->gpio_config_output(sc, AR_GPIO_WLANACTIVE_PIN,
1208 		    AR_GPIO_OUTPUT_MUX_AS_RX_CLEAR_EXTERNAL);
1209 
1210 	} else {	/* 2-wire. */
1211 		ops->gpio_config_output(sc, AR_GPIO_WLANACTIVE_PIN,
1212 		    AR_GPIO_OUTPUT_MUX_AS_TX_FRAME);
1213 	}
1214 	reg = AR_READ(sc, AR_GPIO_PDPU);
1215 	reg &= ~(0x3 << (AR_GPIO_WLANACTIVE_PIN * 2));
1216 	reg |= 0x2 << (AR_GPIO_WLANACTIVE_PIN * 2);
1217 	AR_WRITE(sc, AR_GPIO_PDPU, reg);
1218 	AR_WRITE_BARRIER(sc);
1219 
1220 	/* Disable PCIe Active State Power Management (ASPM). */
1221 	if (sc->sc_disable_aspm != NULL)
1222 		sc->sc_disable_aspm(sc);
1223 
1224 	/* XXX Start periodic timer. */
1225 }
1226 
1227 void
1228 athn_btcoex_disable(struct athn_softc *sc)
1229 {
1230 	struct athn_ops *ops = &sc->ops;
1231 
1232 	ops->gpio_write(sc, AR_GPIO_WLANACTIVE_PIN, 0);
1233 
1234 	ops->gpio_config_output(sc, AR_GPIO_WLANACTIVE_PIN,
1235 	    AR_GPIO_OUTPUT_MUX_AS_OUTPUT);
1236 
1237 	if (sc->flags & ATHN_FLAG_BTCOEX3WIRE) {
1238 		AR_WRITE(sc, AR_BT_COEX_MODE,
1239 		    SM(AR_BT_MODE, AR_BT_MODE_DISABLED) | AR_BT_QUIET);
1240 		AR_WRITE(sc, AR_BT_COEX_WEIGHT, 0);
1241 		AR_WRITE(sc, AR_BT_COEX_MODE2, 0);
1242 		/* XXX Stop periodic timer. */
1243 	}
1244 	AR_WRITE_BARRIER(sc);
1245 	/* XXX Restore ASPM setting? */
1246 }
1247 #endif
1248 
1249 void
1250 athn_iter_calib(void *arg, struct ieee80211_node *ni)
1251 {
1252 	struct athn_softc *sc = arg;
1253 	struct athn_node *an = (struct athn_node *)ni;
1254 
1255 	if ((ni->ni_flags & IEEE80211_NODE_HT) == 0)
1256 		ieee80211_amrr_choose(&sc->amrr, ni, &an->amn);
1257 }
1258 
1259 int
1260 athn_cap_noisefloor(struct athn_softc *sc, int nf)
1261 {
1262 	int16_t min, max;
1263 
1264 	if (nf == 0 || nf == -1) /* invalid measurement */
1265 		return AR_DEFAULT_NOISE_FLOOR;
1266 
1267 	if (IEEE80211_IS_CHAN_2GHZ(sc->sc_ic.ic_bss->ni_chan)) {
1268 		min = sc->cca_min_2g;
1269 		max = sc->cca_max_2g;
1270 	} else {
1271 		min = sc->cca_min_5g;
1272 		max = sc->cca_max_5g;
1273 	}
1274 
1275 	if (nf < min)
1276 		return min;
1277 	if (nf > max)
1278 		return max;
1279 
1280 	return nf;
1281 }
1282 
1283 int
1284 athn_nf_hist_mid(int *nf_vals, int nvalid)
1285 {
1286 	int nf_sorted[ATHN_NF_CAL_HIST_MAX];
1287 	int i, j, nf;
1288 
1289 	if (nvalid <= 1)
1290 		return nf_vals[0];
1291 
1292 	for (i = 0; i < nvalid; i++)
1293 		nf_sorted[i] = nf_vals[i];
1294 
1295 	for (i = 0; i < nvalid; i++) {
1296 		for (j = 1; j < nvalid - i; j++) {
1297 			if (nf_sorted[j] > nf_sorted[j - 1]) {
1298 				nf = nf_sorted[j];
1299 				nf_sorted[j] = nf_sorted[j - 1];
1300 				nf_sorted[j - 1] = nf;
1301 			}
1302 		}
1303 	}
1304 
1305 	return nf_sorted[nvalid / 2];
1306 }
1307 
1308 void
1309 athn_filter_noisefloor(struct athn_softc *sc)
1310 {
1311 	int nf_vals[ATHN_NF_CAL_HIST_MAX];
1312 	int nf_ext_vals[ATHN_NF_CAL_HIST_MAX];
1313 	int i, cur, n;
1314 
1315 	for (i = 0; i < sc->nrxchains; i++) {
1316 		if (sc->nf_hist_cur > 0)
1317 			cur = sc->nf_hist_cur - 1;
1318 		else
1319 			cur = ATHN_NF_CAL_HIST_MAX - 1;
1320 		for (n = 0; n < sc->nf_hist_nvalid; n++) {
1321 			nf_vals[n] = sc->nf_hist[cur].nf[i];
1322 			nf_ext_vals[n] = sc->nf_hist[cur].nf_ext[i];
1323 			if (++cur >= ATHN_NF_CAL_HIST_MAX)
1324 				cur = 0;
1325 		}
1326 		sc->nf_priv[i] = athn_cap_noisefloor(sc,
1327 		    athn_nf_hist_mid(nf_vals, sc->nf_hist_nvalid));
1328 		sc->nf_ext_priv[i] = athn_cap_noisefloor(sc,
1329 		    athn_nf_hist_mid(nf_ext_vals, sc->nf_hist_nvalid));
1330 	}
1331 }
1332 
1333 void
1334 athn_start_noisefloor_calib(struct athn_softc *sc, int reset_history)
1335 {
1336 	extern int ticks;
1337 
1338 	if (reset_history)
1339 		sc->nf_hist_nvalid = 0;
1340 
1341 	sc->nf_calib_pending = 1;
1342 	sc->nf_calib_ticks = ticks;
1343 
1344 	sc->ops.noisefloor_calib(sc);
1345 }
1346 
1347 void
1348 athn_calib_to(void *arg)
1349 {
1350 	extern int ticks;
1351 	struct athn_softc *sc = arg;
1352 	struct athn_ops *ops = &sc->ops;
1353 	struct ieee80211com *ic = &sc->sc_ic;
1354 	int s;
1355 
1356 	s = splnet();
1357 
1358 	/* Do periodic (every 4 minutes) PA calibration. */
1359 	if (AR_SREV_9285_11_OR_LATER(sc) &&
1360 	    !AR_SREV_9380_10_OR_LATER(sc) &&
1361 	    (ticks - (sc->pa_calib_ticks + 240 * hz)) >= 0) {
1362 		sc->pa_calib_ticks = ticks;
1363 		if (AR_SREV_9271(sc))
1364 			ar9271_pa_calib(sc);
1365 		else
1366 			ar9285_pa_calib(sc);
1367 	}
1368 
1369 	/* Do periodic (every 4 minutes) NF calibration. */
1370 	if (sc->nf_calib_pending && ops->get_noisefloor(sc)) {
1371 		if (sc->nf_hist_nvalid < ATHN_NF_CAL_HIST_MAX)
1372 			sc->nf_hist_nvalid++;
1373 		athn_filter_noisefloor(sc);
1374 		ops->apply_noisefloor(sc);
1375 		sc->nf_calib_pending = 0;
1376 	}
1377 	if (ticks - (sc->nf_calib_ticks + 240 * hz) >= 0)
1378 		athn_start_noisefloor_calib(sc, 0);
1379 
1380 	/* Do periodic (every 30 seconds) temperature compensation. */
1381 	if ((sc->flags & ATHN_FLAG_OLPC) &&
1382 	    ticks >= sc->olpc_ticks + 30 * hz) {
1383 		sc->olpc_ticks = ticks;
1384 		ops->olpc_temp_compensation(sc);
1385 	}
1386 
1387 #ifdef notyet
1388 	/* XXX ANI. */
1389 	athn_ani_monitor(sc);
1390 #endif
1391 
1392 	/* Do periodic (every 30 seconds) ADC/IQ calibration. */
1393 	if (sc->cur_calib_mask != 0) {
1394 		ops->next_calib(sc);
1395 		sc->iqcal_ticks = ticks;
1396 	} else if (sc->sup_calib_mask != 0 &&
1397 	    ticks >= sc->iqcal_ticks + 30 * hz) {
1398 		memset(&sc->calib, 0, sizeof(sc->calib));
1399 		sc->cur_calib_mask = sc->sup_calib_mask;
1400 		ops->do_calib(sc);
1401 		sc->iqcal_ticks = ticks;
1402 	}
1403 
1404 	if (ic->ic_fixed_rate == -1) {
1405 		if (ic->ic_opmode == IEEE80211_M_STA)
1406 			athn_iter_calib(sc, ic->ic_bss);
1407 		else
1408 			ieee80211_iterate_nodes(ic, athn_iter_calib, sc);
1409 	}
1410 	timeout_add_msec(&sc->calib_to, 500);
1411 	splx(s);
1412 }
1413 
1414 int
1415 athn_init_calib(struct athn_softc *sc, struct ieee80211_channel *c,
1416     struct ieee80211_channel *extc)
1417 {
1418 	struct athn_ops *ops = &sc->ops;
1419 	int error;
1420 
1421 	if (AR_SREV_9380_10_OR_LATER(sc))
1422 		error = ar9003_init_calib(sc);
1423 	else if (AR_SREV_9285_10_OR_LATER(sc))
1424 		error = ar9285_init_calib(sc, c, extc);
1425 	else
1426 		error = ar5416_init_calib(sc, c, extc);
1427 	if (error != 0)
1428 		return (error);
1429 
1430 	if (!AR_SREV_9380_10_OR_LATER(sc)) {
1431 		/* Do PA calibration. */
1432 		if (AR_SREV_9285_11_OR_LATER(sc)) {
1433 			extern int ticks;
1434 			sc->pa_calib_ticks = ticks;
1435 			if (AR_SREV_9271(sc))
1436 				ar9271_pa_calib(sc);
1437 			else
1438 				ar9285_pa_calib(sc);
1439 		}
1440 	}
1441 
1442 	/* Do noisefloor calibration. */
1443 	ops->init_noisefloor_calib(sc);
1444 
1445 	if (AR_SREV_9160_10_OR_LATER(sc)) {
1446 		/* Support IQ calibration. */
1447 		sc->sup_calib_mask = ATHN_CAL_IQ;
1448 		if (AR_SREV_9380_10_OR_LATER(sc)) {
1449 			/* Support temperature compensation calibration. */
1450 			sc->sup_calib_mask |= ATHN_CAL_TEMP;
1451 		} else if (IEEE80211_IS_CHAN_5GHZ(c) || extc != NULL) {
1452 			/*
1453 			 * ADC gain calibration causes uplink throughput
1454 			 * drops in HT40 mode on AR9287.
1455 			 */
1456 			if (!AR_SREV_9287(sc)) {
1457 				/* Support ADC gain calibration. */
1458 				sc->sup_calib_mask |= ATHN_CAL_ADC_GAIN;
1459 			}
1460 			/* Support ADC DC offset calibration. */
1461 			sc->sup_calib_mask |= ATHN_CAL_ADC_DC;
1462 		}
1463 	}
1464 	return (0);
1465 }
1466 
1467 /*
1468  * Adaptive noise immunity.
1469  */
1470 int32_t
1471 athn_ani_get_rssi(struct athn_softc *sc)
1472 {
1473 	return (0);	/* XXX */
1474 }
1475 
1476 void
1477 athn_ani_ofdm_err_trigger(struct athn_softc *sc)
1478 {
1479 	struct athn_ani *ani = &sc->ani;
1480 	struct athn_ops *ops = &sc->ops;
1481 	int32_t rssi;
1482 
1483 	/* First, raise noise immunity level, up to max. */
1484 	if (ani->noise_immunity_level < 4) {
1485 		ani->noise_immunity_level++;
1486 		ops->set_noise_immunity_level(sc, ani->noise_immunity_level);
1487 		return;
1488 	}
1489 
1490 	/* Then, raise our spur immunity level, up to max. */
1491 	if (ani->spur_immunity_level < 7) {
1492 		ani->spur_immunity_level++;
1493 		ops->set_spur_immunity_level(sc, ani->spur_immunity_level);
1494 		return;
1495 	}
1496 
1497 #ifndef IEEE80211_STA_ONLY
1498 	if (sc->sc_ic.ic_opmode == IEEE80211_M_HOSTAP) {
1499 		if (ani->firstep_level < 2) {
1500 			ani->firstep_level++;
1501 			ops->set_firstep_level(sc, ani->firstep_level);
1502 		}
1503 		return;
1504 	}
1505 #endif
1506 	rssi = athn_ani_get_rssi(sc);
1507 	if (rssi > ATHN_ANI_RSSI_THR_HIGH) {
1508 		/*
1509 		 * Beacon RSSI is high, turn off OFDM weak signal detection
1510 		 * or raise first step level as last resort.
1511 		 */
1512 		if (ani->ofdm_weak_signal) {
1513 			ani->ofdm_weak_signal = 0;
1514 			ops->disable_ofdm_weak_signal(sc);
1515 			ani->spur_immunity_level = 0;
1516 			ops->set_spur_immunity_level(sc, 0);
1517 		} else if (ani->firstep_level < 2) {
1518 			ani->firstep_level++;
1519 			ops->set_firstep_level(sc, ani->firstep_level);
1520 		}
1521 	} else if (rssi > ATHN_ANI_RSSI_THR_LOW) {
1522 		/*
1523 		 * Beacon RSSI is in mid range, we need OFDM weak signal
1524 		 * detection but we can raise first step level.
1525 		 */
1526 		if (!ani->ofdm_weak_signal) {
1527 			ani->ofdm_weak_signal = 1;
1528 			ops->enable_ofdm_weak_signal(sc);
1529 		}
1530 		if (ani->firstep_level < 2) {
1531 			ani->firstep_level++;
1532 			ops->set_firstep_level(sc, ani->firstep_level);
1533 		}
1534 	} else if (IEEE80211_IS_CHAN_2GHZ(sc->sc_ic.ic_bss->ni_chan)) {
1535 		/*
1536 		 * Beacon RSSI is low, if in b/g mode, turn off OFDM weak
1537 		 * signal detection and zero first step level to maximize
1538 		 * CCK sensitivity.
1539 		 */
1540 		if (ani->ofdm_weak_signal) {
1541 			ani->ofdm_weak_signal = 0;
1542 			ops->disable_ofdm_weak_signal(sc);
1543 		}
1544 		if (ani->firstep_level > 0) {
1545 			ani->firstep_level = 0;
1546 			ops->set_firstep_level(sc, 0);
1547 		}
1548 	}
1549 }
1550 
1551 void
1552 athn_ani_cck_err_trigger(struct athn_softc *sc)
1553 {
1554 	struct athn_ani *ani = &sc->ani;
1555 	struct athn_ops *ops = &sc->ops;
1556 	int32_t rssi;
1557 
1558 	/* Raise noise immunity level, up to max. */
1559 	if (ani->noise_immunity_level < 4) {
1560 		ani->noise_immunity_level++;
1561 		ops->set_noise_immunity_level(sc, ani->noise_immunity_level);
1562 		return;
1563 	}
1564 
1565 #ifndef IEEE80211_STA_ONLY
1566 	if (sc->sc_ic.ic_opmode == IEEE80211_M_HOSTAP) {
1567 		if (ani->firstep_level < 2) {
1568 			ani->firstep_level++;
1569 			ops->set_firstep_level(sc, ani->firstep_level);
1570 		}
1571 		return;
1572 	}
1573 #endif
1574 	rssi = athn_ani_get_rssi(sc);
1575 	if (rssi > ATHN_ANI_RSSI_THR_LOW) {
1576 		/*
1577 		 * Beacon RSSI is in mid or high range, raise first step
1578 		 * level.
1579 		 */
1580 		if (ani->firstep_level < 2) {
1581 			ani->firstep_level++;
1582 			ops->set_firstep_level(sc, ani->firstep_level);
1583 		}
1584 	} else if (IEEE80211_IS_CHAN_2GHZ(sc->sc_ic.ic_bss->ni_chan)) {
1585 		/*
1586 		 * Beacon RSSI is low, zero first step level to maximize
1587 		 * CCK sensitivity.
1588 		 */
1589 		if (ani->firstep_level > 0) {
1590 			ani->firstep_level = 0;
1591 			ops->set_firstep_level(sc, 0);
1592 		}
1593 	}
1594 }
1595 
1596 void
1597 athn_ani_lower_immunity(struct athn_softc *sc)
1598 {
1599 	struct athn_ani *ani = &sc->ani;
1600 	struct athn_ops *ops = &sc->ops;
1601 	int32_t rssi;
1602 
1603 #ifndef IEEE80211_STA_ONLY
1604 	if (sc->sc_ic.ic_opmode == IEEE80211_M_HOSTAP) {
1605 		if (ani->firstep_level > 0) {
1606 			ani->firstep_level--;
1607 			ops->set_firstep_level(sc, ani->firstep_level);
1608 		}
1609 		return;
1610 	}
1611 #endif
1612 	rssi = athn_ani_get_rssi(sc);
1613 	if (rssi > ATHN_ANI_RSSI_THR_HIGH) {
1614 		/*
1615 		 * Beacon RSSI is high, leave OFDM weak signal detection
1616 		 * off or it may oscillate.
1617 		 */
1618 	} else if (rssi > ATHN_ANI_RSSI_THR_LOW) {
1619 		/*
1620 		 * Beacon RSSI is in mid range, turn on OFDM weak signal
1621 		 * detection or lower first step level.
1622 		 */
1623 		if (!ani->ofdm_weak_signal) {
1624 			ani->ofdm_weak_signal = 1;
1625 			ops->enable_ofdm_weak_signal(sc);
1626 			return;
1627 		}
1628 		if (ani->firstep_level > 0) {
1629 			ani->firstep_level--;
1630 			ops->set_firstep_level(sc, ani->firstep_level);
1631 			return;
1632 		}
1633 	} else {
1634 		/* Beacon RSSI is low, lower first step level. */
1635 		if (ani->firstep_level > 0) {
1636 			ani->firstep_level--;
1637 			ops->set_firstep_level(sc, ani->firstep_level);
1638 			return;
1639 		}
1640 	}
1641 	/*
1642 	 * Lower spur immunity level down to zero, or if all else fails,
1643 	 * lower noise immunity level down to zero.
1644 	 */
1645 	if (ani->spur_immunity_level > 0) {
1646 		ani->spur_immunity_level--;
1647 		ops->set_spur_immunity_level(sc, ani->spur_immunity_level);
1648 	} else if (ani->noise_immunity_level > 0) {
1649 		ani->noise_immunity_level--;
1650 		ops->set_noise_immunity_level(sc, ani->noise_immunity_level);
1651 	}
1652 }
1653 
1654 void
1655 athn_ani_restart(struct athn_softc *sc)
1656 {
1657 	struct athn_ani *ani = &sc->ani;
1658 
1659 	AR_WRITE(sc, AR_PHY_ERR_1, 0);
1660 	AR_WRITE(sc, AR_PHY_ERR_2, 0);
1661 	AR_WRITE(sc, AR_PHY_ERR_MASK_1, AR_PHY_ERR_OFDM_TIMING);
1662 	AR_WRITE(sc, AR_PHY_ERR_MASK_2, AR_PHY_ERR_CCK_TIMING);
1663 	AR_WRITE_BARRIER(sc);
1664 
1665 	ani->listen_time = 0;
1666 	ani->ofdm_phy_err_count = 0;
1667 	ani->cck_phy_err_count = 0;
1668 }
1669 
1670 void
1671 athn_ani_monitor(struct athn_softc *sc)
1672 {
1673 	struct athn_ani *ani = &sc->ani;
1674 	uint32_t cyccnt, txfcnt, rxfcnt, phy1, phy2;
1675 	int32_t cycdelta, txfdelta, rxfdelta;
1676 	int32_t listen_time;
1677 
1678 	txfcnt = AR_READ(sc, AR_TFCNT);	/* Tx frame count. */
1679 	rxfcnt = AR_READ(sc, AR_RFCNT);	/* Rx frame count. */
1680 	cyccnt = AR_READ(sc, AR_CCCNT);	/* Cycle count. */
1681 
1682 	if (ani->cyccnt != 0 && ani->cyccnt <= cyccnt) {
1683 		cycdelta = cyccnt - ani->cyccnt;
1684 		txfdelta = txfcnt - ani->txfcnt;
1685 		rxfdelta = rxfcnt - ani->rxfcnt;
1686 
1687 		listen_time = (cycdelta - txfdelta - rxfdelta) /
1688 		    (athn_clock_rate(sc) * 1000);
1689 	} else
1690 		listen_time = 0;
1691 
1692 	ani->cyccnt = cyccnt;
1693 	ani->txfcnt = txfcnt;
1694 	ani->rxfcnt = rxfcnt;
1695 
1696 	if (listen_time < 0) {
1697 		athn_ani_restart(sc);
1698 		return;
1699 	}
1700 	ani->listen_time += listen_time;
1701 
1702 	phy1 = AR_READ(sc, AR_PHY_ERR_1);
1703 	phy2 = AR_READ(sc, AR_PHY_ERR_2);
1704 
1705 	if (phy1 < ani->ofdm_phy_err_base) {
1706 		AR_WRITE(sc, AR_PHY_ERR_1, ani->ofdm_phy_err_base);
1707 		AR_WRITE(sc, AR_PHY_ERR_MASK_1, AR_PHY_ERR_OFDM_TIMING);
1708 	}
1709 	if (phy2 < ani->cck_phy_err_base) {
1710 		AR_WRITE(sc, AR_PHY_ERR_2, ani->cck_phy_err_base);
1711 		AR_WRITE(sc, AR_PHY_ERR_MASK_2, AR_PHY_ERR_CCK_TIMING);
1712 	}
1713 	if (phy1 < ani->ofdm_phy_err_base || phy2 < ani->cck_phy_err_base) {
1714 		AR_WRITE_BARRIER(sc);
1715 		return;
1716 	}
1717 	ani->ofdm_phy_err_count = phy1 - ani->ofdm_phy_err_base;
1718 	ani->cck_phy_err_count = phy2 - ani->cck_phy_err_base;
1719 
1720 	if (ani->listen_time > 5 * ATHN_ANI_PERIOD) {
1721 		/* Check to see if we need to lower immunity. */
1722 		if (ani->ofdm_phy_err_count <=
1723 		    ani->listen_time * ani->ofdm_trig_low / 1000 &&
1724 		    ani->cck_phy_err_count <=
1725 		    ani->listen_time * ani->cck_trig_low / 1000)
1726 			athn_ani_lower_immunity(sc);
1727 		athn_ani_restart(sc);
1728 
1729 	} else if (ani->listen_time > ATHN_ANI_PERIOD) {
1730 		/* Check to see if we need to raise immunity. */
1731 		if (ani->ofdm_phy_err_count >
1732 		    ani->listen_time * ani->ofdm_trig_high / 1000) {
1733 			athn_ani_ofdm_err_trigger(sc);
1734 			athn_ani_restart(sc);
1735 		} else if (ani->cck_phy_err_count >
1736 		    ani->listen_time * ani->cck_trig_high / 1000) {
1737 			athn_ani_cck_err_trigger(sc);
1738 			athn_ani_restart(sc);
1739 		}
1740 	}
1741 }
1742 
1743 uint8_t
1744 athn_chan2fbin(struct ieee80211_channel *c)
1745 {
1746 	if (IEEE80211_IS_CHAN_2GHZ(c))
1747 		return (c->ic_freq - 2300);
1748 	else
1749 		return ((c->ic_freq - 4800) / 5);
1750 }
1751 
1752 int
1753 athn_interpolate(int x, int x1, int y1, int x2, int y2)
1754 {
1755 	if (x1 == x2)	/* Prevents division by zero. */
1756 		return (y1);
1757 	/* Linear interpolation. */
1758 	return (y1 + ((x - x1) * (y2 - y1)) / (x2 - x1));
1759 }
1760 
1761 void
1762 athn_get_pier_ival(uint8_t fbin, const uint8_t *pierfreq, int npiers,
1763     int *lo, int *hi)
1764 {
1765 	int i;
1766 
1767 	for (i = 0; i < npiers; i++)
1768 		if (pierfreq[i] == AR_BCHAN_UNUSED ||
1769 		    pierfreq[i] > fbin)
1770 			break;
1771 	*hi = i;
1772 	*lo = *hi - 1;
1773 	if (*lo == -1)
1774 		*lo = *hi;
1775 	else if (*hi == npiers || pierfreq[*hi] == AR_BCHAN_UNUSED)
1776 		*hi = *lo;
1777 }
1778 
1779 void
1780 athn_init_dma(struct athn_softc *sc)
1781 {
1782 	uint32_t reg;
1783 
1784 	if (!AR_SREV_9380_10_OR_LATER(sc)) {
1785 		/* Set AHB not to do cacheline prefetches. */
1786 		AR_SETBITS(sc, AR_AHB_MODE, AR_AHB_PREFETCH_RD_EN);
1787 	}
1788 	reg = AR_READ(sc, AR_TXCFG);
1789 	/* Let MAC DMA reads be in 128-byte chunks. */
1790 	reg = RW(reg, AR_TXCFG_DMASZ, AR_DMASZ_128B);
1791 
1792 	/* Set initial Tx trigger level. */
1793 	if (AR_SREV_9285(sc) || AR_SREV_9271(sc))
1794 		reg = RW(reg, AR_TXCFG_FTRIG, AR_TXCFG_FTRIG_256B);
1795 	else if (!AR_SREV_9380_10_OR_LATER(sc))
1796 		reg = RW(reg, AR_TXCFG_FTRIG, AR_TXCFG_FTRIG_512B);
1797 	AR_WRITE(sc, AR_TXCFG, reg);
1798 
1799 	/* Let MAC DMA writes be in 128-byte chunks. */
1800 	reg = AR_READ(sc, AR_RXCFG);
1801 	reg = RW(reg, AR_RXCFG_DMASZ, AR_DMASZ_128B);
1802 	AR_WRITE(sc, AR_RXCFG, reg);
1803 
1804 	/* Setup Rx FIFO threshold to hold off Tx activities. */
1805 	AR_WRITE(sc, AR_RXFIFO_CFG, 512);
1806 
1807 	/* Reduce the number of entries in PCU TXBUF to avoid wrap around. */
1808 	if (AR_SREV_9285(sc)) {
1809 		AR_WRITE(sc, AR_PCU_TXBUF_CTRL,
1810 		    AR9285_PCU_TXBUF_CTRL_USABLE_SIZE);
1811 	} else if (!AR_SREV_9271(sc)) {
1812 		AR_WRITE(sc, AR_PCU_TXBUF_CTRL,
1813 		    AR_PCU_TXBUF_CTRL_USABLE_SIZE);
1814 	}
1815 	AR_WRITE_BARRIER(sc);
1816 
1817 	/* Reset Tx status ring. */
1818 	if (AR_SREV_9380_10_OR_LATER(sc))
1819 		ar9003_reset_txsring(sc);
1820 }
1821 
1822 void
1823 athn_inc_tx_trigger_level(struct athn_softc *sc)
1824 {
1825 	uint32_t reg, ftrig;
1826 
1827 	reg = AR_READ(sc, AR_TXCFG);
1828 	ftrig = MS(reg, AR_TXCFG_FTRIG);
1829 	/*
1830 	 * NB: The AR9285 and all single-stream parts have an issue that
1831 	 * limits the size of the PCU Tx FIFO to 2KB instead of 4KB.
1832 	 */
1833 	if (ftrig == ((AR_SREV_9285(sc) || AR_SREV_9271(sc)) ? 0x1f : 0x3f))
1834 		return;		/* Already at max. */
1835 	reg = RW(reg, AR_TXCFG_FTRIG, ftrig + 1);
1836 	AR_WRITE(sc, AR_TXCFG, reg);
1837 	AR_WRITE_BARRIER(sc);
1838 }
1839 
1840 int
1841 athn_stop_rx_dma(struct athn_softc *sc)
1842 {
1843 	int ntries;
1844 
1845 	AR_WRITE(sc, AR_CR, AR_CR_RXD);
1846 	/* Wait for Rx enable bit to go low. */
1847 	for (ntries = 0; ntries < 100; ntries++) {
1848 		if (!(AR_READ(sc, AR_CR) & AR_CR_RXE))
1849 			return (0);
1850 		DELAY(100);
1851 	}
1852 	DPRINTF(("Rx DMA failed to stop\n"));
1853 	return (ETIMEDOUT);
1854 }
1855 
1856 int
1857 athn_rx_abort(struct athn_softc *sc)
1858 {
1859 	int ntries;
1860 
1861 	AR_SETBITS(sc, AR_DIAG_SW, AR_DIAG_RX_DIS | AR_DIAG_RX_ABORT);
1862 	for (ntries = 0; ntries < 1000; ntries++) {
1863 		if (MS(AR_READ(sc, AR_OBS_BUS_1), AR_OBS_BUS_1_RX_STATE) == 0)
1864 			return (0);
1865 		DELAY(10);
1866 	}
1867 	DPRINTF(("Rx failed to go idle in 10ms\n"));
1868 	AR_CLRBITS(sc, AR_DIAG_SW, AR_DIAG_RX_DIS | AR_DIAG_RX_ABORT);
1869 	AR_WRITE_BARRIER(sc);
1870 	return (ETIMEDOUT);
1871 }
1872 
1873 void
1874 athn_tx_reclaim(struct athn_softc *sc, int qid)
1875 {
1876 	struct athn_txq *txq = &sc->txq[qid];
1877 	struct athn_tx_buf *bf;
1878 
1879 	/* Reclaim all buffers queued in the specified Tx queue. */
1880 	/* NB: Tx DMA must be stopped. */
1881 	while ((bf = SIMPLEQ_FIRST(&txq->head)) != NULL) {
1882 		SIMPLEQ_REMOVE_HEAD(&txq->head, bf_list);
1883 
1884 		bus_dmamap_sync(sc->sc_dmat, bf->bf_map, 0,
1885 		    bf->bf_map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
1886 		bus_dmamap_unload(sc->sc_dmat, bf->bf_map);
1887 		m_freem(bf->bf_m);
1888 		bf->bf_m = NULL;
1889 		bf->bf_ni = NULL;	/* Nodes already freed! */
1890 
1891 		/* Link Tx buffer back to global free list. */
1892 		SIMPLEQ_INSERT_TAIL(&sc->txbufs, bf, bf_list);
1893 	}
1894 }
1895 
1896 int
1897 athn_tx_pending(struct athn_softc *sc, int qid)
1898 {
1899 	return (MS(AR_READ(sc, AR_QSTS(qid)), AR_Q_STS_PEND_FR_CNT) != 0 ||
1900 	    (AR_READ(sc, AR_Q_TXE) & (1 << qid)) != 0);
1901 }
1902 
1903 void
1904 athn_stop_tx_dma(struct athn_softc *sc, int qid)
1905 {
1906 	uint32_t tsflo;
1907 	int ntries, i;
1908 
1909 	AR_WRITE(sc, AR_Q_TXD, 1 << qid);
1910 	for (ntries = 0; ntries < 40; ntries++) {
1911 		if (!athn_tx_pending(sc, qid))
1912 			break;
1913 		DELAY(100);
1914 	}
1915 	if (ntries == 40) {
1916 		for (i = 0; i < 2; i++) {
1917 			tsflo = AR_READ(sc, AR_TSF_L32) / 1024;
1918 			AR_WRITE(sc, AR_QUIET2,
1919 			    SM(AR_QUIET2_QUIET_DUR, 10));
1920 			AR_WRITE(sc, AR_QUIET_PERIOD, 100);
1921 			AR_WRITE(sc, AR_NEXT_QUIET_TIMER, tsflo);
1922 			AR_SETBITS(sc, AR_TIMER_MODE, AR_QUIET_TIMER_EN);
1923 			if (AR_READ(sc, AR_TSF_L32) / 1024 == tsflo)
1924 				break;
1925 		}
1926 		AR_SETBITS(sc, AR_DIAG_SW, AR_DIAG_FORCE_CH_IDLE_HIGH);
1927 		AR_WRITE_BARRIER(sc);
1928 		DELAY(200);
1929 		AR_CLRBITS(sc, AR_TIMER_MODE, AR_QUIET_TIMER_EN);
1930 		AR_WRITE_BARRIER(sc);
1931 
1932 		for (ntries = 0; ntries < 40; ntries++) {
1933 			if (!athn_tx_pending(sc, qid))
1934 				break;
1935 			DELAY(100);
1936 		}
1937 
1938 		AR_CLRBITS(sc, AR_DIAG_SW, AR_DIAG_FORCE_CH_IDLE_HIGH);
1939 	}
1940 	AR_WRITE(sc, AR_Q_TXD, 0);
1941 	AR_WRITE_BARRIER(sc);
1942 }
1943 
1944 int
1945 athn_txtime(struct athn_softc *sc, int len, int ridx, u_int flags)
1946 {
1947 	struct ieee80211com *ic = &sc->sc_ic;
1948 #define divround(a, b)	(((a) + (b) - 1) / (b))
1949 	int txtime;
1950 
1951 	if (athn_rates[ridx].hwrate & 0x80) { /* MCS */
1952 	 	/* Assumes a 20MHz channel, HT-mixed frame format, no STBC. */
1953 		txtime = 8 + 8 + 4 + 4 + 4 * 4 + 8 /* HT PLCP */
1954 		    + 4 * ((8 * len + 16 + 6) / (athn_rates[ridx].rate * 2));
1955 		if (IEEE80211_IS_CHAN_2GHZ(ic->ic_bss->ni_chan))
1956 			txtime += 6; /* aSignalExtension */
1957 	} else if (athn_rates[ridx].phy == IEEE80211_T_OFDM) {
1958 		txtime = divround(8 + 4 * len + 3, athn_rates[ridx].rate);
1959 		/* SIFS is 10us for 11g but Signal Extension adds 6us. */
1960 		txtime = 16 + 4 + 4 * txtime + 16;
1961 	} else {
1962 		txtime = divround(16 * len, athn_rates[ridx].rate);
1963 		if (ridx != ATHN_RIDX_CCK1 && (flags & IEEE80211_F_SHPREAMBLE))
1964 			txtime +=  72 + 24;
1965 		else
1966 			txtime += 144 + 48;
1967 		txtime += 10;	/* 10us SIFS. */
1968 	}
1969 	return (txtime);
1970 #undef divround
1971 }
1972 
1973 void
1974 athn_init_tx_queues(struct athn_softc *sc)
1975 {
1976 	int qid;
1977 
1978 	for (qid = 0; qid < ATHN_QID_COUNT; qid++) {
1979 		SIMPLEQ_INIT(&sc->txq[qid].head);
1980 		sc->txq[qid].lastds = NULL;
1981 		sc->txq[qid].wait = NULL;
1982 		sc->txq[qid].queued = 0;
1983 
1984 		AR_WRITE(sc, AR_DRETRY_LIMIT(qid),
1985 		    SM(AR_D_RETRY_LIMIT_STA_SH, 32) |
1986 		    SM(AR_D_RETRY_LIMIT_STA_LG, 32) |
1987 		    SM(AR_D_RETRY_LIMIT_FR_SH, 10));
1988 		AR_WRITE(sc, AR_QMISC(qid),
1989 		    AR_Q_MISC_DCU_EARLY_TERM_REQ);
1990 		AR_WRITE(sc, AR_DMISC(qid),
1991 		    SM(AR_D_MISC_BKOFF_THRESH, 2) |
1992 		    AR_D_MISC_CW_BKOFF_EN | AR_D_MISC_FRAG_WAIT_EN);
1993 	}
1994 
1995 	/* Init beacon queue. */
1996 	AR_SETBITS(sc, AR_QMISC(ATHN_QID_BEACON),
1997 	    AR_Q_MISC_FSP_DBA_GATED | AR_Q_MISC_BEACON_USE |
1998 	    AR_Q_MISC_CBR_INCR_DIS1);
1999 	AR_SETBITS(sc, AR_DMISC(ATHN_QID_BEACON),
2000 	    SM(AR_D_MISC_ARB_LOCKOUT_CNTRL,
2001 	       AR_D_MISC_ARB_LOCKOUT_CNTRL_GLOBAL) |
2002 	    AR_D_MISC_BEACON_USE |
2003 	    AR_D_MISC_POST_FR_BKOFF_DIS);
2004 	AR_WRITE(sc, AR_DLCL_IFS(ATHN_QID_BEACON),
2005 	    SM(AR_D_LCL_IFS_CWMIN, 0) |
2006 	    SM(AR_D_LCL_IFS_CWMAX, 0) |
2007 	    SM(AR_D_LCL_IFS_AIFS,  1));
2008 
2009 	/* Init CAB (Content After Beacon) queue. */
2010 	AR_SETBITS(sc, AR_QMISC(ATHN_QID_CAB),
2011 	    AR_Q_MISC_FSP_DBA_GATED | AR_Q_MISC_CBR_INCR_DIS1 |
2012 	    AR_Q_MISC_CBR_INCR_DIS0);
2013 	AR_SETBITS(sc, AR_DMISC(ATHN_QID_CAB),
2014 	    SM(AR_D_MISC_ARB_LOCKOUT_CNTRL,
2015 	       AR_D_MISC_ARB_LOCKOUT_CNTRL_GLOBAL));
2016 
2017 	/* Init PS-Poll queue. */
2018 	AR_SETBITS(sc, AR_QMISC(ATHN_QID_PSPOLL),
2019 	    AR_Q_MISC_CBR_INCR_DIS1);
2020 
2021 	/* Init UAPSD queue. */
2022 	AR_SETBITS(sc, AR_DMISC(ATHN_QID_UAPSD),
2023 	    AR_D_MISC_POST_FR_BKOFF_DIS);
2024 
2025 	if (AR_SREV_9380_10_OR_LATER(sc)) {
2026 		/* Enable MAC descriptor CRC check. */
2027 		AR_WRITE(sc, AR_Q_DESC_CRCCHK, AR_Q_DESC_CRCCHK_EN);
2028 	}
2029 	/* Enable DESC interrupts for all Tx queues. */
2030 	AR_WRITE(sc, AR_IMR_S0, 0x00ff0000);
2031 	/* Enable EOL interrupts for all Tx queues except UAPSD. */
2032 	AR_WRITE(sc, AR_IMR_S1, 0x00df0000);
2033 	AR_WRITE_BARRIER(sc);
2034 }
2035 
2036 void
2037 athn_set_sta_timers(struct athn_softc *sc)
2038 {
2039 	struct ieee80211com *ic = &sc->sc_ic;
2040 	uint32_t tsfhi, tsflo, tsftu, reg;
2041 	uint32_t intval, next_tbtt, next_dtim;
2042 	int dtim_period, dtim_count, rem_dtim_count;
2043 
2044 	tsfhi = AR_READ(sc, AR_TSF_U32);
2045 	tsflo = AR_READ(sc, AR_TSF_L32);
2046 	tsftu = AR_TSF_TO_TU(tsfhi, tsflo) + AR_FUDGE;
2047 
2048 	/* Beacon interval in TU. */
2049 	intval = ic->ic_bss->ni_intval;
2050 
2051 	next_tbtt = roundup(tsftu, intval);
2052 #ifdef notyet
2053 	dtim_period = ic->ic_dtim_period;
2054 	if (dtim_period <= 0)
2055 #endif
2056 		dtim_period = 1;	/* Assume all TIMs are DTIMs. */
2057 
2058 #ifdef notyet
2059 	dtim_count = ic->ic_dtim_count;
2060 	if (dtim_count >= dtim_period)	/* Should not happen. */
2061 #endif
2062 		dtim_count = 0;	/* Assume last TIM was a DTIM. */
2063 
2064 	/* Compute number of remaining TIMs until next DTIM. */
2065 	rem_dtim_count = 0;	/* XXX */
2066 	next_dtim = next_tbtt + rem_dtim_count * intval;
2067 
2068 	AR_WRITE(sc, AR_NEXT_TBTT_TIMER, next_tbtt * IEEE80211_DUR_TU);
2069 	AR_WRITE(sc, AR_BEACON_PERIOD, intval * IEEE80211_DUR_TU);
2070 	AR_WRITE(sc, AR_DMA_BEACON_PERIOD, intval * IEEE80211_DUR_TU);
2071 
2072 	/*
2073 	 * Set the number of consecutive beacons to miss before raising
2074 	 * a BMISS interrupt to 10.
2075 	 */
2076 	reg = AR_READ(sc, AR_RSSI_THR);
2077 	reg = RW(reg, AR_RSSI_THR_BM_THR, 10);
2078 	AR_WRITE(sc, AR_RSSI_THR, reg);
2079 
2080 	AR_WRITE(sc, AR_NEXT_DTIM,
2081 	    (next_dtim - AR_SLEEP_SLOP) * IEEE80211_DUR_TU);
2082 	AR_WRITE(sc, AR_NEXT_TIM,
2083 	    (next_tbtt - AR_SLEEP_SLOP) * IEEE80211_DUR_TU);
2084 
2085 	/* CAB timeout is in 1/8 TU. */
2086 	AR_WRITE(sc, AR_SLEEP1,
2087 	    SM(AR_SLEEP1_CAB_TIMEOUT, AR_CAB_TIMEOUT_VAL * 8) |
2088 	    AR_SLEEP1_ASSUME_DTIM);
2089 	AR_WRITE(sc, AR_SLEEP2,
2090 	    SM(AR_SLEEP2_BEACON_TIMEOUT, AR_MIN_BEACON_TIMEOUT_VAL));
2091 
2092 	AR_WRITE(sc, AR_TIM_PERIOD, intval * IEEE80211_DUR_TU);
2093 	AR_WRITE(sc, AR_DTIM_PERIOD, dtim_period * intval * IEEE80211_DUR_TU);
2094 
2095 	AR_SETBITS(sc, AR_TIMER_MODE,
2096 	    AR_TBTT_TIMER_EN | AR_TIM_TIMER_EN | AR_DTIM_TIMER_EN);
2097 
2098 	/* Set TSF out-of-range threshold (fixed at 16k us). */
2099 	AR_WRITE(sc, AR_TSFOOR_THRESHOLD, 0x4240);
2100 
2101 	AR_WRITE_BARRIER(sc);
2102 }
2103 
2104 #ifndef IEEE80211_STA_ONLY
2105 void
2106 athn_set_hostap_timers(struct athn_softc *sc)
2107 {
2108 	struct ieee80211com *ic = &sc->sc_ic;
2109 	uint32_t intval, next_tbtt;
2110 
2111 	/* Beacon interval in TU. */
2112 	intval = ic->ic_bss->ni_intval;
2113 	next_tbtt = intval;
2114 
2115 	AR_WRITE(sc, AR_NEXT_TBTT_TIMER, next_tbtt * IEEE80211_DUR_TU);
2116 	AR_WRITE(sc, AR_NEXT_DMA_BEACON_ALERT,
2117 	    (next_tbtt - AR_BEACON_DMA_DELAY) * IEEE80211_DUR_TU);
2118 	AR_WRITE(sc, AR_NEXT_CFP,
2119 	    (next_tbtt - AR_SWBA_DELAY) * IEEE80211_DUR_TU);
2120 
2121 	AR_WRITE(sc, AR_BEACON_PERIOD, intval * IEEE80211_DUR_TU);
2122 	AR_WRITE(sc, AR_DMA_BEACON_PERIOD, intval * IEEE80211_DUR_TU);
2123 	AR_WRITE(sc, AR_SWBA_PERIOD, intval * IEEE80211_DUR_TU);
2124 	AR_WRITE(sc, AR_NDP_PERIOD, intval * IEEE80211_DUR_TU);
2125 
2126 	AR_WRITE(sc, AR_TIMER_MODE,
2127 	    AR_TBTT_TIMER_EN | AR_DBA_TIMER_EN | AR_SWBA_TIMER_EN);
2128 
2129 	AR_WRITE_BARRIER(sc);
2130 }
2131 #endif
2132 
2133 void
2134 athn_set_opmode(struct athn_softc *sc)
2135 {
2136 	uint32_t reg;
2137 
2138 	switch (sc->sc_ic.ic_opmode) {
2139 #ifndef IEEE80211_STA_ONLY
2140 	case IEEE80211_M_HOSTAP:
2141 		reg = AR_READ(sc, AR_STA_ID1);
2142 		reg &= ~AR_STA_ID1_ADHOC;
2143 		reg |= AR_STA_ID1_STA_AP | AR_STA_ID1_KSRCH_MODE;
2144 		AR_WRITE(sc, AR_STA_ID1, reg);
2145 
2146 		AR_CLRBITS(sc, AR_CFG, AR_CFG_AP_ADHOC_INDICATION);
2147 		break;
2148 	case IEEE80211_M_IBSS:
2149 	case IEEE80211_M_AHDEMO:
2150 		reg = AR_READ(sc, AR_STA_ID1);
2151 		reg &= ~AR_STA_ID1_STA_AP;
2152 		reg |= AR_STA_ID1_ADHOC | AR_STA_ID1_KSRCH_MODE;
2153 		AR_WRITE(sc, AR_STA_ID1, reg);
2154 
2155 		AR_SETBITS(sc, AR_CFG, AR_CFG_AP_ADHOC_INDICATION);
2156 		break;
2157 #endif
2158 	default:
2159 		reg = AR_READ(sc, AR_STA_ID1);
2160 		reg &= ~(AR_STA_ID1_ADHOC | AR_STA_ID1_STA_AP);
2161 		reg |= AR_STA_ID1_KSRCH_MODE;
2162 		AR_WRITE(sc, AR_STA_ID1, reg);
2163 		break;
2164 	}
2165 	AR_WRITE_BARRIER(sc);
2166 }
2167 
2168 void
2169 athn_set_bss(struct athn_softc *sc, struct ieee80211_node *ni)
2170 {
2171 	const uint8_t *bssid = ni->ni_bssid;
2172 
2173 	AR_WRITE(sc, AR_BSS_ID0, LE_READ_4(&bssid[0]));
2174 	AR_WRITE(sc, AR_BSS_ID1, LE_READ_2(&bssid[4]) |
2175 	    SM(AR_BSS_ID1_AID, IEEE80211_AID(ni->ni_associd)));
2176 	AR_WRITE_BARRIER(sc);
2177 }
2178 
2179 void
2180 athn_enable_interrupts(struct athn_softc *sc)
2181 {
2182 	uint32_t mask2;
2183 
2184 	athn_disable_interrupts(sc);	/* XXX */
2185 
2186 	AR_WRITE(sc, AR_IMR, sc->imask);
2187 
2188 	mask2 = AR_READ(sc, AR_IMR_S2);
2189 	mask2 &= ~(AR_IMR_S2_TIM | AR_IMR_S2_DTIM | AR_IMR_S2_DTIMSYNC |
2190 	    AR_IMR_S2_CABEND | AR_IMR_S2_CABTO | AR_IMR_S2_TSFOOR);
2191 	mask2 |= AR_IMR_S2_GTT | AR_IMR_S2_CST;
2192 	AR_WRITE(sc, AR_IMR_S2, mask2);
2193 
2194 	AR_CLRBITS(sc, AR_IMR_S5, AR_IMR_S5_TIM_TIMER);
2195 
2196 	AR_WRITE(sc, AR_IER, AR_IER_ENABLE);
2197 
2198 	AR_WRITE(sc, AR_INTR_ASYNC_ENABLE, AR_INTR_MAC_IRQ);
2199 	AR_WRITE(sc, AR_INTR_ASYNC_MASK, AR_INTR_MAC_IRQ);
2200 
2201 	AR_WRITE(sc, AR_INTR_SYNC_ENABLE, sc->isync);
2202 	AR_WRITE(sc, AR_INTR_SYNC_MASK, sc->isync);
2203 	AR_WRITE_BARRIER(sc);
2204 }
2205 
2206 void
2207 athn_disable_interrupts(struct athn_softc *sc)
2208 {
2209 	AR_WRITE(sc, AR_IER, 0);
2210 	(void)AR_READ(sc, AR_IER);
2211 
2212 	AR_WRITE(sc, AR_INTR_ASYNC_ENABLE, 0);
2213 	(void)AR_READ(sc, AR_INTR_ASYNC_ENABLE);
2214 
2215 	AR_WRITE(sc, AR_INTR_SYNC_ENABLE, 0);
2216 	(void)AR_READ(sc, AR_INTR_SYNC_ENABLE);
2217 
2218 	AR_WRITE(sc, AR_IMR, 0);
2219 
2220 	AR_CLRBITS(sc, AR_IMR_S2, AR_IMR_S2_TIM | AR_IMR_S2_DTIM |
2221 	    AR_IMR_S2_DTIMSYNC | AR_IMR_S2_CABEND | AR_IMR_S2_CABTO |
2222 	    AR_IMR_S2_TSFOOR | AR_IMR_S2_GTT | AR_IMR_S2_CST);
2223 
2224 	AR_CLRBITS(sc, AR_IMR_S5, AR_IMR_S5_TIM_TIMER);
2225 	AR_WRITE_BARRIER(sc);
2226 }
2227 
2228 void
2229 athn_init_qos(struct athn_softc *sc)
2230 {
2231 	/* Initialize QoS settings. */
2232 	AR_WRITE(sc, AR_MIC_QOS_CONTROL, 0x100aa);
2233 	AR_WRITE(sc, AR_MIC_QOS_SELECT, 0x3210);
2234 	AR_WRITE(sc, AR_QOS_NO_ACK,
2235 	    SM(AR_QOS_NO_ACK_TWO_BIT, 2) |
2236 	    SM(AR_QOS_NO_ACK_BIT_OFF, 5) |
2237 	    SM(AR_QOS_NO_ACK_BYTE_OFF, 0));
2238 	AR_WRITE(sc, AR_TXOP_X, AR_TXOP_X_VAL);
2239 	/* Initialize TXOP for all TIDs. */
2240 	AR_WRITE(sc, AR_TXOP_0_3,   0xffffffff);
2241 	AR_WRITE(sc, AR_TXOP_4_7,   0xffffffff);
2242 	AR_WRITE(sc, AR_TXOP_8_11,  0xffffffff);
2243 	AR_WRITE(sc, AR_TXOP_12_15, 0xffffffff);
2244 	AR_WRITE_BARRIER(sc);
2245 }
2246 
2247 int
2248 athn_hw_reset(struct athn_softc *sc, struct ieee80211_channel *c,
2249     struct ieee80211_channel *extc, int init)
2250 {
2251 	struct ieee80211com *ic = &sc->sc_ic;
2252 	struct athn_ops *ops = &sc->ops;
2253 	uint32_t reg, def_ant, sta_id1, cfg_led, tsflo, tsfhi;
2254 	int i, error;
2255 
2256 	/* XXX not if already awake */
2257 	if ((error = athn_set_power_awake(sc)) != 0) {
2258 		printf("%s: could not wakeup chip\n", sc->sc_dev.dv_xname);
2259 		return (error);
2260 	}
2261 
2262 	/* Preserve the antenna on a channel switch. */
2263 	if ((def_ant = AR_READ(sc, AR_DEF_ANTENNA)) == 0)
2264 		def_ant = 1;
2265 	/* Preserve other registers. */
2266 	sta_id1 = AR_READ(sc, AR_STA_ID1) & AR_STA_ID1_BASE_RATE_11B;
2267 	cfg_led = AR_READ(sc, AR_CFG_LED) & (AR_CFG_LED_ASSOC_CTL_M |
2268 	    AR_CFG_LED_MODE_SEL_M | AR_CFG_LED_BLINK_THRESH_SEL_M |
2269 	    AR_CFG_LED_BLINK_SLOW);
2270 
2271 	/* Mark PHY as inactive. */
2272 	ops->disable_phy(sc);
2273 
2274 	if (init && AR_SREV_9271(sc)) {
2275 		AR_WRITE(sc, AR9271_RESET_POWER_DOWN_CONTROL,
2276 		    AR9271_RADIO_RF_RST);
2277 		DELAY(50);
2278 	}
2279 	if (AR_SREV_9280(sc) && (sc->flags & ATHN_FLAG_OLPC)) {
2280 		/* Save TSF before it gets cleared. */
2281 		tsfhi = AR_READ(sc, AR_TSF_U32);
2282 		tsflo = AR_READ(sc, AR_TSF_L32);
2283 
2284 		/* NB: RTC reset clears TSF. */
2285 		error = athn_reset_power_on(sc);
2286 	} else
2287 		error = athn_reset(sc, 0);
2288 	if (error != 0) {
2289 		printf("%s: could not reset chip (error=%d)\n",
2290 		    sc->sc_dev.dv_xname, error);
2291 		return (error);
2292 	}
2293 
2294 	/* XXX not if already awake */
2295 	if ((error = athn_set_power_awake(sc)) != 0) {
2296 		printf("%s: could not wakeup chip\n", sc->sc_dev.dv_xname);
2297 		return (error);
2298 	}
2299 
2300 	athn_init_pll(sc, c);
2301 	ops->set_rf_mode(sc, c);
2302 
2303 	if (sc->flags & ATHN_FLAG_RFSILENT) {
2304 		/* Check that the radio is not disabled by hardware switch. */
2305 		reg = ops->gpio_read(sc, sc->rfsilent_pin);
2306 		if (sc->flags & ATHN_FLAG_RFSILENT_REVERSED)
2307 			reg = !reg;
2308 		if (!reg) {
2309 			printf("%s: radio is disabled by hardware switch\n",
2310 			    sc->sc_dev.dv_xname);
2311 			return (EPERM);
2312 		}
2313 	}
2314 	if (init && AR_SREV_9271(sc)) {
2315 		AR_WRITE(sc, AR9271_RESET_POWER_DOWN_CONTROL,
2316 		    AR9271_GATE_MAC_CTL);
2317 		DELAY(50);
2318 	}
2319 	if (AR_SREV_9280(sc) && (sc->flags & ATHN_FLAG_OLPC)) {
2320 		/* Restore TSF if it got cleared. */
2321 		AR_WRITE(sc, AR_TSF_L32, tsflo);
2322 		AR_WRITE(sc, AR_TSF_U32, tsfhi);
2323 	}
2324 
2325 	if (AR_SREV_9280_10_OR_LATER(sc))
2326 		AR_SETBITS(sc, sc->gpio_input_en_off, AR_GPIO_JTAG_DISABLE);
2327 
2328 	if (AR_SREV_9287_13_OR_LATER(sc) && !AR_SREV_9380_10_OR_LATER(sc))
2329 		ar9287_1_3_enable_async_fifo(sc);
2330 
2331 	/* Write init values to hardware. */
2332 	ops->hw_init(sc, c, extc);
2333 
2334 	/*
2335 	 * Only >=AR9280 2.0 parts are capable of encrypting unicast
2336 	 * management frames using CCMP.
2337 	 */
2338 	if (AR_SREV_9280_20_OR_LATER(sc)) {
2339 		reg = AR_READ(sc, AR_AES_MUTE_MASK1);
2340 		/* Do not mask the subtype field in management frames. */
2341 		reg = RW(reg, AR_AES_MUTE_MASK1_FC0_MGMT, 0xff);
2342 		reg = RW(reg, AR_AES_MUTE_MASK1_FC1_MGMT,
2343 		    ~(IEEE80211_FC1_RETRY | IEEE80211_FC1_PWR_MGT |
2344 		      IEEE80211_FC1_MORE_DATA));
2345 		AR_WRITE(sc, AR_AES_MUTE_MASK1, reg);
2346 	} else if (AR_SREV_9160_10_OR_LATER(sc)) {
2347 		/* Disable hardware crypto for management frames. */
2348 		AR_CLRBITS(sc, AR_PCU_MISC_MODE2,
2349 		    AR_PCU_MISC_MODE2_MGMT_CRYPTO_ENABLE);
2350 		AR_SETBITS(sc, AR_PCU_MISC_MODE2,
2351 		    AR_PCU_MISC_MODE2_NO_CRYPTO_FOR_NON_DATA_PKT);
2352 	}
2353 
2354 	if (ic->ic_curmode != IEEE80211_MODE_11B)
2355 		ops->set_delta_slope(sc, c, extc);
2356 
2357 	ops->spur_mitigate(sc, c, extc);
2358 	ops->init_from_rom(sc, c, extc);
2359 
2360 	/* XXX */
2361 	AR_WRITE(sc, AR_STA_ID0, LE_READ_4(&ic->ic_myaddr[0]));
2362 	AR_WRITE(sc, AR_STA_ID1, LE_READ_2(&ic->ic_myaddr[4]) |
2363 	    sta_id1 | AR_STA_ID1_RTS_USE_DEF | AR_STA_ID1_CRPT_MIC_ENABLE);
2364 
2365 	athn_set_opmode(sc);
2366 
2367 	AR_WRITE(sc, AR_BSSMSKL, 0xffffffff);
2368 	AR_WRITE(sc, AR_BSSMSKU, 0xffff);
2369 
2370 	/* Restore previous antenna. */
2371 	AR_WRITE(sc, AR_DEF_ANTENNA, def_ant);
2372 
2373 	AR_WRITE(sc, AR_BSS_ID0, 0);
2374 	AR_WRITE(sc, AR_BSS_ID1, 0);
2375 
2376 	AR_WRITE(sc, AR_ISR, 0xffffffff);
2377 
2378 	AR_WRITE(sc, AR_RSSI_THR, SM(AR_RSSI_THR_BM_THR, 7));
2379 
2380 	if ((error = ops->set_synth(sc, c, extc)) != 0) {
2381 		printf("%s: could not set channel\n", sc->sc_dev.dv_xname);
2382 		return (error);
2383 	}
2384 	sc->curchan = c;
2385 	sc->curchanext = extc;
2386 
2387 	for (i = 0; i < AR_NUM_DCU; i++)
2388 		AR_WRITE(sc, AR_DQCUMASK(i), 1 << i);
2389 
2390 	athn_init_tx_queues(sc);
2391 
2392 	/* Initialize interrupt mask. */
2393 	sc->imask =
2394 	    AR_IMR_TXDESC | AR_IMR_TXEOL |
2395 	    AR_IMR_RXERR | AR_IMR_RXEOL | AR_IMR_RXORN |
2396 	    AR_IMR_RXMINTR | AR_IMR_RXINTM |
2397 	    AR_IMR_GENTMR | AR_IMR_BCNMISC;
2398 	if (AR_SREV_9380_10_OR_LATER(sc))
2399 		sc->imask |= AR_IMR_RXERR | AR_IMR_HP_RXOK;
2400 #ifndef IEEE80211_STA_ONLY
2401 	if (0 && ic->ic_opmode == IEEE80211_M_HOSTAP)
2402 		sc->imask |= AR_IMR_MIB;
2403 #endif
2404 	AR_WRITE(sc, AR_IMR, sc->imask);
2405 	AR_SETBITS(sc, AR_IMR_S2, AR_IMR_S2_GTT);
2406 	AR_WRITE(sc, AR_INTR_SYNC_CAUSE, 0xffffffff);
2407 	sc->isync = AR_INTR_SYNC_DEFAULT;
2408 	if (sc->flags & ATHN_FLAG_RFSILENT)
2409 		sc->isync |= AR_INTR_SYNC_GPIO_PIN(sc->rfsilent_pin);
2410 	AR_WRITE(sc, AR_INTR_SYNC_ENABLE, sc->isync);
2411 	AR_WRITE(sc, AR_INTR_SYNC_MASK, 0);
2412 	if (AR_SREV_9380_10_OR_LATER(sc)) {
2413 		AR_WRITE(sc, AR_INTR_PRIO_ASYNC_ENABLE, 0);
2414 		AR_WRITE(sc, AR_INTR_PRIO_ASYNC_MASK, 0);
2415 		AR_WRITE(sc, AR_INTR_PRIO_SYNC_ENABLE, 0);
2416 		AR_WRITE(sc, AR_INTR_PRIO_SYNC_MASK, 0);
2417 	}
2418 
2419 	athn_init_qos(sc);
2420 
2421 	AR_SETBITS(sc, AR_PCU_MISC, AR_PCU_MIC_NEW_LOC_ENA);
2422 
2423 	athn_setsifs(sc);
2424 	athn_updateslot(ic);
2425 	athn_setclockrate(sc);
2426 	if (AR_SREV_9287_13_OR_LATER(sc) && !AR_SREV_9380_10_OR_LATER(sc))
2427 		ar9287_1_3_setup_async_fifo(sc);
2428 
2429 	/* Disable sequence number generation in hardware. */
2430 	AR_SETBITS(sc, AR_STA_ID1, AR_STA_ID1_PRESERVE_SEQNUM);
2431 
2432 	athn_init_dma(sc);
2433 
2434 	/* Program observation bus to see MAC interrupts. */
2435 	AR_WRITE(sc, sc->obs_off, 8);
2436 
2437 	/* Setup Rx interrupt mitigation. */
2438 	AR_WRITE(sc, AR_RIMT, SM(AR_RIMT_FIRST, 2000) | SM(AR_RIMT_LAST, 500));
2439 
2440 	/* Setup Tx interrupt mitigation. */
2441 	AR_WRITE(sc, AR_TIMT, SM(AR_TIMT_FIRST, 2000) | SM(AR_TIMT_LAST, 500));
2442 
2443 	/* Set maximum interrupt rate threshold (in micro seconds). */
2444 	AR_WRITE(sc, AR_MIRT, SM(AR_MIRT_RATE_THRES, 2000));
2445 
2446 	ops->init_baseband(sc);
2447 
2448 	if ((error = athn_init_calib(sc, c, extc)) != 0) {
2449 		printf("%s: could not initialize calibration\n",
2450 		    sc->sc_dev.dv_xname);
2451 		return (error);
2452 	}
2453 
2454 	ops->set_rxchains(sc);
2455 
2456 	AR_WRITE(sc, AR_CFG_LED, cfg_led | AR_CFG_SCLK_32KHZ);
2457 
2458 	if (sc->flags & ATHN_FLAG_USB) {
2459 		if (AR_SREV_9271(sc))
2460 			AR_WRITE(sc, AR_CFG, AR_CFG_SWRB | AR_CFG_SWTB);
2461 		else
2462 			AR_WRITE(sc, AR_CFG, AR_CFG_SWTD | AR_CFG_SWRD);
2463 	}
2464 #if BYTE_ORDER == BIG_ENDIAN
2465 	else {
2466 		/* Default is LE, turn on swapping for BE. */
2467 		AR_WRITE(sc, AR_CFG, AR_CFG_SWTD | AR_CFG_SWRD);
2468 	}
2469 #endif
2470 	AR_WRITE_BARRIER(sc);
2471 
2472 	return (0);
2473 }
2474 
2475 struct ieee80211_node *
2476 athn_node_alloc(struct ieee80211com *ic)
2477 {
2478 	struct athn_node *an;
2479 
2480 	an = malloc(sizeof(struct athn_node), M_DEVBUF, M_NOWAIT | M_ZERO);
2481 	if (an && (ic->ic_flags & IEEE80211_F_HTON))
2482 		ieee80211_mira_node_init(&an->mn);
2483 	return (struct ieee80211_node *)an;
2484 }
2485 
2486 void
2487 athn_newassoc(struct ieee80211com *ic, struct ieee80211_node *ni, int isnew)
2488 {
2489 	struct athn_softc *sc = ic->ic_softc;
2490 	struct athn_node *an = (void *)ni;
2491 	struct ieee80211_rateset *rs = &ni->ni_rates;
2492 	uint8_t rate;
2493 	int ridx, i, j;
2494 
2495 	if ((ni->ni_flags & IEEE80211_NODE_HT) == 0)
2496 		ieee80211_amrr_node_init(&sc->amrr, &an->amn);
2497 	else if (ic->ic_opmode == IEEE80211_M_STA)
2498 		ieee80211_mira_node_init(&an->mn);
2499 
2500 	/* Start at lowest available bit-rate, AMRR will raise. */
2501 	ni->ni_txrate = 0;
2502 
2503 	for (i = 0; i < rs->rs_nrates; i++) {
2504 		rate = rs->rs_rates[i] & IEEE80211_RATE_VAL;
2505 
2506 		/* Map 802.11 rate to HW rate index. */
2507 		for (ridx = 0; ridx <= ATHN_RIDX_MAX; ridx++)
2508 			if (athn_rates[ridx].rate == rate)
2509 				break;
2510 		an->ridx[i] = ridx;
2511 		DPRINTFN(2, ("rate %d index %d\n", rate, ridx));
2512 
2513 		/* Compute fallback rate for retries. */
2514 		an->fallback[i] = i;
2515 		for (j = i - 1; j >= 0; j--) {
2516 			if (athn_rates[an->ridx[j]].phy ==
2517 			    athn_rates[an->ridx[i]].phy) {
2518 				an->fallback[i] = j;
2519 				break;
2520 			}
2521 		}
2522 		DPRINTFN(2, ("%d fallbacks to %d\n", i, an->fallback[i]));
2523 	}
2524 
2525 	/* In 11n mode, start at lowest available bit-rate, MiRA will raise. */
2526 	ni->ni_txmcs = 0;
2527 
2528 	for (i = 0; i <= ATHN_MCS_MAX; i++) {
2529 		/* Map MCS index to HW rate index. */
2530 		ridx = ATHN_NUM_LEGACY_RATES + i;
2531 		an->ridx[ridx] = ATHN_RIDX_MCS0 + i;
2532 
2533 		DPRINTFN(2, ("mcs %d index %d ", i, ridx));
2534 		/* Compute fallback rate for retries. */
2535 		if (i == 0 || i == 8) {
2536 		 	/* MCS 0 and 8 fall back to the lowest legacy rate. */
2537 			if (IEEE80211_IS_CHAN_5GHZ(ni->ni_chan))
2538 				an->fallback[ridx] = ATHN_RIDX_OFDM6;
2539 			else
2540 				an->fallback[ridx] = ATHN_RIDX_CCK1;
2541 		} else {
2542 			/* Other MCS fall back to next supported lower MCS. */
2543 			an->fallback[ridx] = ATHN_NUM_LEGACY_RATES + i;
2544 			for (j = i - 1; j >= 0; j--) {
2545 				if (!isset(ni->ni_rxmcs, j))
2546 					continue;
2547 				an->fallback[ridx] = ATHN_NUM_LEGACY_RATES + j;
2548 				break;
2549 			}
2550 		}
2551 		DPRINTFN(2, (" fallback to %d\n", an->fallback[ridx]));
2552 	}
2553 }
2554 
2555 #ifndef IEEE80211_STA_ONLY
2556 void
2557 athn_node_leave(struct ieee80211com *ic, struct ieee80211_node *ni)
2558 {
2559 	struct athn_node *an = (void *)ni;
2560 	if (ic->ic_flags & IEEE80211_F_HTON)
2561 		ieee80211_mira_cancel_timeouts(&an->mn);
2562 }
2563 #endif
2564 
2565 int
2566 athn_media_change(struct ifnet *ifp)
2567 {
2568 	struct athn_softc *sc = ifp->if_softc;
2569 	struct ieee80211com *ic = &sc->sc_ic;
2570 	uint8_t rate, ridx;
2571 	int error;
2572 
2573 	error = ieee80211_media_change(ifp);
2574 	if (error != ENETRESET)
2575 		return (error);
2576 
2577 	if (ic->ic_fixed_rate != -1) {
2578 		rate = ic->ic_sup_rates[ic->ic_curmode].
2579 		    rs_rates[ic->ic_fixed_rate] & IEEE80211_RATE_VAL;
2580 		/* Map 802.11 rate to HW rate index. */
2581 		for (ridx = 0; ridx <= ATHN_RIDX_MAX; ridx++)
2582 			if (athn_rates[ridx].rate == rate)
2583 				break;
2584 		sc->fixed_ridx = ridx;
2585 	}
2586 	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
2587 	    (IFF_UP | IFF_RUNNING)) {
2588 		athn_stop(ifp, 0);
2589 		error = athn_init(ifp);
2590 	}
2591 	return (error);
2592 }
2593 
2594 void
2595 athn_next_scan(void *arg)
2596 {
2597 	struct athn_softc *sc = arg;
2598 	struct ieee80211com *ic = &sc->sc_ic;
2599 	int s;
2600 
2601 	s = splnet();
2602 	if (ic->ic_state == IEEE80211_S_SCAN)
2603 		ieee80211_next_scan(&ic->ic_if);
2604 	splx(s);
2605 }
2606 
2607 void
2608 athn_iter_mira_delete(void *arg, struct ieee80211_node *ni)
2609 {
2610 	struct athn_node *an = (struct athn_node *)ni;
2611 	ieee80211_mira_cancel_timeouts(&an->mn);
2612 }
2613 
2614 /* Delete pending timeouts managed by MiRA. */
2615 void
2616 athn_delete_mira_nodes(struct athn_softc *sc)
2617 {
2618 	struct ieee80211com *ic = &sc->sc_ic;
2619 
2620 	if (ic->ic_opmode == IEEE80211_M_STA) {
2621 		struct athn_node *an = (struct athn_node *)ic->ic_bss;
2622 		ieee80211_mira_cancel_timeouts(&an->mn);
2623 	} else
2624 		ieee80211_iterate_nodes(ic, athn_iter_mira_delete, sc);
2625 }
2626 
2627 int
2628 athn_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
2629 {
2630 	struct ifnet *ifp = &ic->ic_if;
2631 	struct athn_softc *sc = ifp->if_softc;
2632 	uint32_t reg;
2633 	int error;
2634 
2635 	timeout_del(&sc->calib_to);
2636 
2637 	if ((ic->ic_flags & IEEE80211_F_HTON) &&
2638 	    ic->ic_state == IEEE80211_S_RUN && nstate != IEEE80211_S_RUN)
2639 		athn_delete_mira_nodes(sc);
2640 
2641 	switch (nstate) {
2642 	case IEEE80211_S_INIT:
2643 		athn_set_led(sc, 0);
2644 		break;
2645 	case IEEE80211_S_SCAN:
2646 		/* Make the LED blink while scanning. */
2647 		athn_set_led(sc, !sc->led_state);
2648 		error = athn_switch_chan(sc, ic->ic_bss->ni_chan, NULL);
2649 		if (error != 0)
2650 			return (error);
2651 		timeout_add_msec(&sc->scan_to, 200);
2652 		break;
2653 	case IEEE80211_S_AUTH:
2654 		athn_set_led(sc, 0);
2655 		error = athn_switch_chan(sc, ic->ic_bss->ni_chan, NULL);
2656 		if (error != 0)
2657 			return (error);
2658 		break;
2659 	case IEEE80211_S_ASSOC:
2660 		break;
2661 	case IEEE80211_S_RUN:
2662 		athn_set_led(sc, 1);
2663 
2664 		if (ic->ic_opmode == IEEE80211_M_MONITOR)
2665 			break;
2666 
2667 		/* Fake a join to initialize the Tx rate. */
2668 		athn_newassoc(ic, ic->ic_bss, 1);
2669 
2670 		athn_set_bss(sc, ic->ic_bss);
2671 		athn_disable_interrupts(sc);
2672 #ifndef IEEE80211_STA_ONLY
2673 		if (ic->ic_opmode == IEEE80211_M_HOSTAP) {
2674 			athn_set_hostap_timers(sc);
2675 			/* Enable software beacon alert interrupts. */
2676 			sc->imask |= AR_IMR_SWBA;
2677 		} else
2678 #endif
2679 		{
2680 			athn_set_sta_timers(sc);
2681 			/* Enable beacon miss interrupts. */
2682 			sc->imask |= AR_IMR_BMISS;
2683 
2684 			/* Stop receiving beacons from other BSS. */
2685 			reg = AR_READ(sc, AR_RX_FILTER);
2686 			reg = (reg & ~AR_RX_FILTER_BEACON) |
2687 			    AR_RX_FILTER_MYBEACON;
2688 			AR_WRITE(sc, AR_RX_FILTER, reg);
2689 			AR_WRITE_BARRIER(sc);
2690 		}
2691 		athn_enable_interrupts(sc);
2692 
2693 		if (sc->sup_calib_mask != 0) {
2694 			memset(&sc->calib, 0, sizeof(sc->calib));
2695 			sc->cur_calib_mask = sc->sup_calib_mask;
2696 			sc->ops.do_calib(sc);
2697 		}
2698 		/* XXX Start ANI. */
2699 
2700 		athn_start_noisefloor_calib(sc, 1);
2701 		timeout_add_msec(&sc->calib_to, 500);
2702 		break;
2703 	}
2704 
2705 	return (sc->sc_newstate(ic, nstate, arg));
2706 }
2707 
2708 void
2709 athn_updateedca(struct ieee80211com *ic)
2710 {
2711 #define ATHN_EXP2(x)	((1 << (x)) - 1)	/* CWmin = 2^ECWmin - 1 */
2712 	struct athn_softc *sc = ic->ic_softc;
2713 	const struct ieee80211_edca_ac_params *ac;
2714 	int aci, qid;
2715 
2716 	for (aci = 0; aci < EDCA_NUM_AC; aci++) {
2717 		ac = &ic->ic_edca_ac[aci];
2718 		qid = athn_ac2qid[aci];
2719 
2720 		AR_WRITE(sc, AR_DLCL_IFS(qid),
2721 		    SM(AR_D_LCL_IFS_CWMIN, ATHN_EXP2(ac->ac_ecwmin)) |
2722 		    SM(AR_D_LCL_IFS_CWMAX, ATHN_EXP2(ac->ac_ecwmax)) |
2723 		    SM(AR_D_LCL_IFS_AIFS, ac->ac_aifsn));
2724 		if (ac->ac_txoplimit != 0) {
2725 			AR_WRITE(sc, AR_DCHNTIME(qid),
2726 			    SM(AR_D_CHNTIME_DUR,
2727 			       IEEE80211_TXOP_TO_US(ac->ac_txoplimit)) |
2728 			    AR_D_CHNTIME_EN);
2729 		} else
2730 			AR_WRITE(sc, AR_DCHNTIME(qid), 0);
2731 	}
2732 	AR_WRITE_BARRIER(sc);
2733 #undef ATHN_EXP2
2734 }
2735 
2736 int
2737 athn_clock_rate(struct athn_softc *sc)
2738 {
2739 	struct ieee80211com *ic = &sc->sc_ic;
2740 	int clockrate;	/* MHz. */
2741 
2742 	/*
2743 	 * AR9287 v1.3+ MAC runs at 117MHz (instead of 88/44MHz) when
2744 	 * ASYNC FIFO is enabled.
2745 	 */
2746 	if (AR_SREV_9287_13_OR_LATER(sc) && !AR_SREV_9380_10_OR_LATER(sc))
2747 		clockrate = 117;
2748 	else if (ic->ic_bss->ni_chan != IEEE80211_CHAN_ANYC &&
2749 	    IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan)) {
2750 		if (sc->flags & ATHN_FLAG_FAST_PLL_CLOCK)
2751 			clockrate = AR_CLOCK_RATE_FAST_5GHZ_OFDM;
2752 		else
2753 			clockrate = AR_CLOCK_RATE_5GHZ_OFDM;
2754 	} else if (ic->ic_curmode == IEEE80211_MODE_11B) {
2755 		clockrate = AR_CLOCK_RATE_CCK;
2756 	} else
2757 		clockrate = AR_CLOCK_RATE_2GHZ_OFDM;
2758 	if (sc->curchanext != NULL)
2759 		clockrate *= 2;
2760 
2761 	return (clockrate);
2762 }
2763 
2764 int
2765 athn_chan_sifs(struct ieee80211_channel *c)
2766 {
2767 	return IEEE80211_IS_CHAN_2GHZ(c) ? IEEE80211_DUR_DS_SIFS : 16;
2768 }
2769 
2770 void
2771 athn_setsifs(struct athn_softc *sc)
2772 {
2773 	int sifs = athn_chan_sifs(sc->sc_ic.ic_bss->ni_chan);
2774 	AR_WRITE(sc, AR_D_GBL_IFS_SIFS, (sifs - 2) * athn_clock_rate(sc));
2775 	AR_WRITE_BARRIER(sc);
2776 }
2777 
2778 int
2779 athn_acktimeout(struct ieee80211_channel *c, int slot)
2780 {
2781 	int sifs = athn_chan_sifs(c);
2782 	int ackto = sifs + slot;
2783 
2784 	/* Workaround for early ACK timeouts. */
2785 	if (IEEE80211_IS_CHAN_2GHZ(c))
2786 		ackto += 64 - sifs - slot;
2787 
2788 	return ackto;
2789 }
2790 
2791 void
2792 athn_setacktimeout(struct athn_softc *sc, struct ieee80211_channel *c, int slot)
2793 {
2794 	int ackto = athn_acktimeout(c, slot);
2795 	uint32_t reg = AR_READ(sc, AR_TIME_OUT);
2796 	reg = RW(reg, AR_TIME_OUT_ACK, ackto * athn_clock_rate(sc));
2797 	AR_WRITE(sc, AR_TIME_OUT, reg);
2798 	AR_WRITE_BARRIER(sc);
2799 }
2800 
2801 void
2802 athn_setctstimeout(struct athn_softc *sc, struct ieee80211_channel *c, int slot)
2803 {
2804 	int ctsto = athn_acktimeout(c, slot);
2805 	int sifs = athn_chan_sifs(c);
2806 	uint32_t reg = AR_READ(sc, AR_TIME_OUT);
2807 
2808 	/* Workaround for early CTS timeouts. */
2809 	if (IEEE80211_IS_CHAN_2GHZ(c))
2810 		ctsto += 48 - sifs - slot;
2811 
2812 	reg = RW(reg, AR_TIME_OUT_CTS, ctsto * athn_clock_rate(sc));
2813 	AR_WRITE(sc, AR_TIME_OUT, reg);
2814 	AR_WRITE_BARRIER(sc);
2815 }
2816 
2817 void
2818 athn_setclockrate(struct athn_softc *sc)
2819 {
2820 	int clockrate = athn_clock_rate(sc);
2821 	uint32_t reg = AR_READ(sc, AR_USEC);
2822 	reg = RW(reg, AR_USEC_USEC, clockrate - 1);
2823 	AR_WRITE(sc, AR_USEC, reg);
2824 	AR_WRITE_BARRIER(sc);
2825 }
2826 
2827 void
2828 athn_updateslot(struct ieee80211com *ic)
2829 {
2830 	struct athn_softc *sc = ic->ic_softc;
2831 	int slot;
2832 
2833 	slot = (ic->ic_flags & IEEE80211_F_SHSLOT) ?
2834 	    IEEE80211_DUR_DS_SHSLOT : IEEE80211_DUR_DS_SLOT;
2835 	AR_WRITE(sc, AR_D_GBL_IFS_SLOT, slot * athn_clock_rate(sc));
2836 	AR_WRITE_BARRIER(sc);
2837 
2838 	athn_setacktimeout(sc, ic->ic_bss->ni_chan, slot);
2839 	athn_setctstimeout(sc, ic->ic_bss->ni_chan, slot);
2840 }
2841 
2842 void
2843 athn_start(struct ifnet *ifp)
2844 {
2845 	struct athn_softc *sc = ifp->if_softc;
2846 	struct ieee80211com *ic = &sc->sc_ic;
2847 	struct ieee80211_node *ni;
2848 	struct mbuf *m;
2849 
2850 	if (!(ifp->if_flags & IFF_RUNNING) || ifq_is_oactive(&ifp->if_snd))
2851 		return;
2852 
2853 	for (;;) {
2854 		if (SIMPLEQ_EMPTY(&sc->txbufs)) {
2855 			ifq_set_oactive(&ifp->if_snd);
2856 			break;
2857 		}
2858 		/* Send pending management frames first. */
2859 		m = mq_dequeue(&ic->ic_mgtq);
2860 		if (m != NULL) {
2861 			ni = m->m_pkthdr.ph_cookie;
2862 			goto sendit;
2863 		}
2864 		if (ic->ic_state != IEEE80211_S_RUN)
2865 			break;
2866 
2867 		m = mq_dequeue(&ic->ic_pwrsaveq);
2868 		if (m != NULL) {
2869 			ni = m->m_pkthdr.ph_cookie;
2870 			goto sendit;
2871 		}
2872 		if (ic->ic_state != IEEE80211_S_RUN)
2873 			break;
2874 
2875 		/* Encapsulate and send data frames. */
2876 		m = ifq_dequeue(&ifp->if_snd);
2877 		if (m == NULL)
2878 			break;
2879 #if NBPFILTER > 0
2880 		if (ifp->if_bpf != NULL)
2881 			bpf_mtap(ifp->if_bpf, m, BPF_DIRECTION_OUT);
2882 #endif
2883 		if ((m = ieee80211_encap(ifp, m, &ni)) == NULL)
2884 			continue;
2885  sendit:
2886 #if NBPFILTER > 0
2887 		if (ic->ic_rawbpf != NULL)
2888 			bpf_mtap(ic->ic_rawbpf, m, BPF_DIRECTION_OUT);
2889 #endif
2890 		if (sc->ops.tx(sc, m, ni, 0) != 0) {
2891 			ieee80211_release_node(ic, ni);
2892 			ifp->if_oerrors++;
2893 			continue;
2894 		}
2895 
2896 		sc->sc_tx_timer = 5;
2897 		ifp->if_timer = 1;
2898 	}
2899 }
2900 
2901 void
2902 athn_watchdog(struct ifnet *ifp)
2903 {
2904 	struct athn_softc *sc = ifp->if_softc;
2905 
2906 	ifp->if_timer = 0;
2907 
2908 	if (sc->sc_tx_timer > 0) {
2909 		if (--sc->sc_tx_timer == 0) {
2910 			printf("%s: device timeout\n", sc->sc_dev.dv_xname);
2911 			athn_stop(ifp, 1);
2912 			(void)athn_init(ifp);
2913 			ifp->if_oerrors++;
2914 			return;
2915 		}
2916 		ifp->if_timer = 1;
2917 	}
2918 
2919 	ieee80211_watchdog(ifp);
2920 }
2921 
2922 void
2923 athn_set_multi(struct athn_softc *sc)
2924 {
2925 	struct arpcom *ac = &sc->sc_ic.ic_ac;
2926 	struct ifnet *ifp = &ac->ac_if;
2927 	struct ether_multi *enm;
2928 	struct ether_multistep step;
2929 	const uint8_t *addr;
2930 	uint32_t val, lo, hi;
2931 	uint8_t bit;
2932 
2933 	if (ac->ac_multirangecnt > 0)
2934 		ifp->if_flags |= IFF_ALLMULTI;
2935 
2936 	if ((ifp->if_flags & (IFF_ALLMULTI | IFF_PROMISC)) != 0) {
2937 		lo = hi = 0xffffffff;
2938 		goto done;
2939 	}
2940 	lo = hi = 0;
2941 	ETHER_FIRST_MULTI(step, ac, enm);
2942 	while (enm != NULL) {
2943 		addr = enm->enm_addrlo;
2944 		/* Calculate the XOR value of all eight 6-bit words. */
2945 		val = addr[0] | addr[1] << 8 | addr[2] << 16;
2946 		bit  = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2947 		val = addr[3] | addr[4] << 8 | addr[5] << 16;
2948 		bit ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
2949 		bit &= 0x3f;
2950 		if (bit < 32)
2951 			lo |= 1 << bit;
2952 		else
2953 			hi |= 1 << (bit - 32);
2954 		ETHER_NEXT_MULTI(step, enm);
2955 	}
2956  done:
2957 	AR_WRITE(sc, AR_MCAST_FIL0, lo);
2958 	AR_WRITE(sc, AR_MCAST_FIL1, hi);
2959 	AR_WRITE_BARRIER(sc);
2960 }
2961 
2962 int
2963 athn_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
2964 {
2965 	struct athn_softc *sc = ifp->if_softc;
2966 	struct ieee80211com *ic = &sc->sc_ic;
2967 	struct ifreq *ifr;
2968 	int s, error = 0;
2969 
2970 	s = splnet();
2971 
2972 	switch (cmd) {
2973 	case SIOCSIFADDR:
2974 		ifp->if_flags |= IFF_UP;
2975 		/* FALLTHROUGH */
2976 	case SIOCSIFFLAGS:
2977 		if (ifp->if_flags & IFF_UP) {
2978 			if ((ifp->if_flags & IFF_RUNNING) &&
2979 			    ((ifp->if_flags ^ sc->sc_if_flags) &
2980 			     (IFF_ALLMULTI | IFF_PROMISC)) != 0) {
2981 				athn_set_multi(sc);
2982 			} else if (!(ifp->if_flags & IFF_RUNNING))
2983 				error = athn_init(ifp);
2984 		} else {
2985 			if (ifp->if_flags & IFF_RUNNING)
2986 				athn_stop(ifp, 1);
2987 		}
2988 		sc->sc_if_flags = ifp->if_flags;
2989 		break;
2990 
2991 	case SIOCADDMULTI:
2992 	case SIOCDELMULTI:
2993 		ifr = (struct ifreq *)data;
2994 		error = (cmd == SIOCADDMULTI) ?
2995 		    ether_addmulti(ifr, &ic->ic_ac) :
2996 		    ether_delmulti(ifr, &ic->ic_ac);
2997 		if (error == ENETRESET) {
2998 			athn_set_multi(sc);
2999 			error = 0;
3000 		}
3001 		break;
3002 
3003 	case SIOCS80211CHANNEL:
3004 		error = ieee80211_ioctl(ifp, cmd, data);
3005 		if (error == ENETRESET &&
3006 		    ic->ic_opmode == IEEE80211_M_MONITOR) {
3007 			if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
3008 			    (IFF_UP | IFF_RUNNING))
3009 				athn_switch_chan(sc, ic->ic_ibss_chan, NULL);
3010 			error = 0;
3011 		}
3012 		break;
3013 
3014 	default:
3015 		error = ieee80211_ioctl(ifp, cmd, data);
3016 	}
3017 
3018 	if (error == ENETRESET) {
3019 		error = 0;
3020 		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
3021 		    (IFF_UP | IFF_RUNNING)) {
3022 			athn_stop(ifp, 0);
3023 			error = athn_init(ifp);
3024 		}
3025 	}
3026 
3027 	splx(s);
3028 	return (error);
3029 }
3030 
3031 int
3032 athn_init(struct ifnet *ifp)
3033 {
3034 	struct athn_softc *sc = ifp->if_softc;
3035 	struct athn_ops *ops = &sc->ops;
3036 	struct ieee80211com *ic = &sc->sc_ic;
3037 	struct ieee80211_channel *c, *extc;
3038 	int i, error;
3039 
3040 	c = ic->ic_bss->ni_chan = ic->ic_ibss_chan;
3041 	extc = NULL;
3042 
3043 	/* In case a new MAC address has been configured. */
3044 	IEEE80211_ADDR_COPY(ic->ic_myaddr, LLADDR(ifp->if_sadl));
3045 
3046 	/* For CardBus, power on the socket. */
3047 	if (sc->sc_enable != NULL) {
3048 		if ((error = sc->sc_enable(sc)) != 0) {
3049 			printf("%s: could not enable device\n",
3050 			    sc->sc_dev.dv_xname);
3051 			goto fail;
3052 		}
3053 		if ((error = athn_reset_power_on(sc)) != 0) {
3054 			printf("%s: could not power on device\n",
3055 			    sc->sc_dev.dv_xname);
3056 			goto fail;
3057 		}
3058 	}
3059 	if (!(sc->flags & ATHN_FLAG_PCIE))
3060 		athn_config_nonpcie(sc);
3061 	else
3062 		athn_config_pcie(sc);
3063 
3064 	ops->enable_antenna_diversity(sc);
3065 
3066 #ifdef ATHN_BT_COEXISTENCE
3067 	/* Configure bluetooth coexistence for combo chips. */
3068 	if (sc->flags & ATHN_FLAG_BTCOEX)
3069 		athn_btcoex_init(sc);
3070 #endif
3071 
3072 	/* Configure LED. */
3073 	athn_led_init(sc);
3074 
3075 	/* Configure hardware radio switch. */
3076 	if (sc->flags & ATHN_FLAG_RFSILENT)
3077 		ops->rfsilent_init(sc);
3078 
3079 	if ((error = athn_hw_reset(sc, c, extc, 1)) != 0) {
3080 		printf("%s: unable to reset hardware; reset status %d\n",
3081 		    sc->sc_dev.dv_xname, error);
3082 		goto fail;
3083 	}
3084 
3085 	athn_config_ht(sc);
3086 
3087 	/* Enable Rx. */
3088 	athn_rx_start(sc);
3089 
3090 	/* Reset HW key cache entries. */
3091 	for (i = 0; i < sc->kc_entries; i++)
3092 		athn_reset_key(sc, i);
3093 
3094 	/* Enable interrupts. */
3095 	athn_enable_interrupts(sc);
3096 
3097 #ifdef ATHN_BT_COEXISTENCE
3098 	/* Enable bluetooth coexistence for combo chips. */
3099 	if (sc->flags & ATHN_FLAG_BTCOEX)
3100 		athn_btcoex_enable(sc);
3101 #endif
3102 
3103 	ifq_clr_oactive(&ifp->if_snd);
3104 	ifp->if_flags |= IFF_RUNNING;
3105 
3106 #ifdef notyet
3107 	if (ic->ic_flags & IEEE80211_F_WEPON) {
3108 		/* Configure WEP keys. */
3109 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
3110 			athn_set_key(ic, NULL, &ic->ic_nw_keys[i]);
3111 	}
3112 #endif
3113 	if (ic->ic_opmode == IEEE80211_M_MONITOR)
3114 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
3115 	else
3116 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
3117 
3118 	return (0);
3119  fail:
3120 	athn_stop(ifp, 1);
3121 	return (error);
3122 }
3123 
3124 void
3125 athn_stop(struct ifnet *ifp, int disable)
3126 {
3127 	struct athn_softc *sc = ifp->if_softc;
3128 	struct ieee80211com *ic = &sc->sc_ic;
3129 	int qid, i;
3130 
3131 	ifp->if_timer = sc->sc_tx_timer = 0;
3132 	ifp->if_flags &= ~IFF_RUNNING;
3133 	ifq_clr_oactive(&ifp->if_snd);
3134 
3135 	timeout_del(&sc->scan_to);
3136 
3137 	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
3138 
3139 #ifdef ATHN_BT_COEXISTENCE
3140 	/* Disable bluetooth coexistence for combo chips. */
3141 	if (sc->flags & ATHN_FLAG_BTCOEX)
3142 		athn_btcoex_disable(sc);
3143 #endif
3144 
3145 	/* Disable interrupts. */
3146 	athn_disable_interrupts(sc);
3147 	/* Acknowledge interrupts (avoids interrupt storms). */
3148 	AR_WRITE(sc, AR_INTR_SYNC_CAUSE, 0xffffffff);
3149 	AR_WRITE(sc, AR_INTR_SYNC_MASK, 0);
3150 
3151 	for (qid = 0; qid < ATHN_QID_COUNT; qid++)
3152 		athn_stop_tx_dma(sc, qid);
3153 	/* XXX call athn_hw_reset if Tx still pending? */
3154 	for (qid = 0; qid < ATHN_QID_COUNT; qid++)
3155 		athn_tx_reclaim(sc, qid);
3156 
3157 	/* Stop Rx. */
3158 	AR_SETBITS(sc, AR_DIAG_SW, AR_DIAG_RX_DIS | AR_DIAG_RX_ABORT);
3159 	AR_WRITE(sc, AR_MIBC, AR_MIBC_FMC);
3160 	AR_WRITE(sc, AR_MIBC, AR_MIBC_CMC);
3161 	AR_WRITE(sc, AR_FILT_OFDM, 0);
3162 	AR_WRITE(sc, AR_FILT_CCK, 0);
3163 	AR_WRITE_BARRIER(sc);
3164 	athn_set_rxfilter(sc, 0);
3165 	athn_stop_rx_dma(sc);
3166 
3167 	/* Reset HW key cache entries. */
3168 	for (i = 0; i < sc->kc_entries; i++)
3169 		athn_reset_key(sc, i);
3170 
3171 	athn_reset(sc, 0);
3172 	athn_init_pll(sc, NULL);
3173 	athn_set_power_awake(sc);
3174 	athn_reset(sc, 1);
3175 	athn_init_pll(sc, NULL);
3176 
3177 	athn_set_power_sleep(sc);
3178 
3179 	/* For CardBus, power down the socket. */
3180 	if (disable && sc->sc_disable != NULL)
3181 		sc->sc_disable(sc);
3182 }
3183 
3184 void
3185 athn_suspend(struct athn_softc *sc)
3186 {
3187 	struct ifnet *ifp = &sc->sc_ic.ic_if;
3188 
3189 	if (ifp->if_flags & IFF_RUNNING)
3190 		athn_stop(ifp, 1);
3191 }
3192 
3193 void
3194 athn_wakeup(struct athn_softc *sc)
3195 {
3196 	struct ifnet *ifp = &sc->sc_ic.ic_if;
3197 
3198 	if (ifp->if_flags & IFF_UP)
3199 		athn_init(ifp);
3200 }
3201