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