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