xref: /freebsd/sys/dev/ath/if_ath.c (revision 7773002178c8dbc52b44e4d705f07706409af8e4)
1 /*-
2  * Copyright (c) 2002, 2003 Sam Leffler, Errno Consulting
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer,
10  *    without modification.
11  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
12  *    similar to the "NO WARRANTY" disclaimer below ("Disclaimer") and any
13  *    redistribution must be conditioned upon including a substantially
14  *    similar Disclaimer requirement for further binary redistribution.
15  * 3. Neither the names of the above-listed copyright holders nor the names
16  *    of any contributors may be used to endorse or promote products derived
17  *    from this software without specific prior written permission.
18  *
19  * Alternatively, this software may be distributed under the terms of the
20  * GNU General Public License ("GPL") version 2 as published by the Free
21  * Software Foundation.
22  *
23  * NO WARRANTY
24  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
25  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
26  * LIMITED TO, THE IMPLIED WARRANTIES OF NONINFRINGEMENT, MERCHANTIBILITY
27  * AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
28  * THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY,
29  * OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
32  * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
34  * THE POSSIBILITY OF SUCH DAMAGES.
35  */
36 
37 #include <sys/cdefs.h>
38 __FBSDID("$FreeBSD$");
39 
40 /*
41  * Driver for the Atheros Wireless LAN controller.
42  *
43  * This software is derived from work of Atsushi Onoe; his contribution
44  * is greatly appreciated.
45  */
46 
47 #include "opt_inet.h"
48 
49 #include <sys/param.h>
50 #include <sys/systm.h>
51 #include <sys/sysctl.h>
52 #include <sys/mbuf.h>
53 #include <sys/malloc.h>
54 #include <sys/lock.h>
55 #include <sys/mutex.h>
56 #include <sys/kernel.h>
57 #include <sys/socket.h>
58 #include <sys/sockio.h>
59 #include <sys/errno.h>
60 #include <sys/callout.h>
61 #include <sys/bus.h>
62 #include <sys/endian.h>
63 
64 #include <machine/bus.h>
65 
66 #include <net/if.h>
67 #include <net/if_dl.h>
68 #include <net/if_media.h>
69 #include <net/if_arp.h>
70 #include <net/ethernet.h>
71 #include <net/if_llc.h>
72 
73 #include <net80211/ieee80211_var.h>
74 
75 #include <net/bpf.h>
76 
77 #ifdef INET
78 #include <netinet/in.h>
79 #include <netinet/if_ether.h>
80 #endif
81 
82 #define	AR_DEBUG
83 #include <dev/ath/if_athvar.h>
84 #include <contrib/dev/ath/ah_desc.h>
85 
86 /* unalligned little endian access */
87 #define LE_READ_2(p)							\
88 	((u_int16_t)							\
89 	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8)))
90 #define LE_READ_4(p)							\
91 	((u_int32_t)							\
92 	 ((((u_int8_t *)(p))[0]      ) | (((u_int8_t *)(p))[1] <<  8) |	\
93 	  (((u_int8_t *)(p))[2] << 16) | (((u_int8_t *)(p))[3] << 24)))
94 
95 static void	ath_init(void *);
96 static void	ath_stop(struct ifnet *);
97 static void	ath_start(struct ifnet *);
98 static void	ath_reset(struct ath_softc *);
99 static int	ath_media_change(struct ifnet *);
100 static void	ath_watchdog(struct ifnet *);
101 static int	ath_ioctl(struct ifnet *, u_long, caddr_t);
102 static void	ath_fatal_proc(void *, int);
103 static void	ath_rxorn_proc(void *, int);
104 static void	ath_bmiss_proc(void *, int);
105 static void	ath_initkeytable(struct ath_softc *);
106 static void	ath_mode_init(struct ath_softc *);
107 static int	ath_beacon_alloc(struct ath_softc *, struct ieee80211_node *);
108 static void	ath_beacon_proc(void *, int);
109 static void	ath_beacon_free(struct ath_softc *);
110 static void	ath_beacon_config(struct ath_softc *);
111 static int	ath_desc_alloc(struct ath_softc *);
112 static void	ath_desc_free(struct ath_softc *);
113 static struct ieee80211_node *ath_node_alloc(struct ieee80211com *);
114 static void	ath_node_free(struct ieee80211com *, struct ieee80211_node *);
115 static void	ath_node_copy(struct ieee80211com *,
116 			struct ieee80211_node *, const struct ieee80211_node *);
117 static u_int8_t	ath_node_getrssi(struct ieee80211com *,
118 			struct ieee80211_node *);
119 static int	ath_rxbuf_init(struct ath_softc *, struct ath_buf *);
120 static void	ath_rx_proc(void *, int);
121 static int	ath_tx_start(struct ath_softc *, struct ieee80211_node *,
122 			     struct ath_buf *, struct mbuf *);
123 static void	ath_tx_proc(void *, int);
124 static int	ath_chan_set(struct ath_softc *, struct ieee80211_channel *);
125 static void	ath_draintxq(struct ath_softc *);
126 static void	ath_stoprecv(struct ath_softc *);
127 static int	ath_startrecv(struct ath_softc *);
128 static void	ath_next_scan(void *);
129 static void	ath_calibrate(void *);
130 static int	ath_newstate(struct ieee80211com *, enum ieee80211_state, int);
131 static void	ath_newassoc(struct ieee80211com *,
132 			struct ieee80211_node *, int);
133 static int	ath_getchannels(struct ath_softc *, u_int cc, HAL_BOOL outdoor);
134 
135 static int	ath_rate_setup(struct ath_softc *sc, u_int mode);
136 static void	ath_setcurmode(struct ath_softc *, enum ieee80211_phymode);
137 static void	ath_rate_ctl_reset(struct ath_softc *, enum ieee80211_state);
138 static void	ath_rate_ctl(void *, struct ieee80211_node *);
139 
140 SYSCTL_DECL(_hw_ath);
141 
142 /* XXX validate sysctl values */
143 static	int ath_dwelltime = 200;		/* 5 channels/second */
144 SYSCTL_INT(_hw_ath, OID_AUTO, dwell, CTLFLAG_RW, &ath_dwelltime,
145 	    0, "channel dwell time (ms) for AP/station scanning");
146 static	int ath_calinterval = 30;		/* calibrate every 30 secs */
147 SYSCTL_INT(_hw_ath, OID_AUTO, calibrate, CTLFLAG_RW, &ath_calinterval,
148 	    0, "chip calibration interval (secs)");
149 static	int ath_outdoor = AH_TRUE;		/* outdoor operation */
150 SYSCTL_INT(_hw_ath, OID_AUTO, outdoor, CTLFLAG_RD, &ath_outdoor,
151 	    0, "enable/disable outdoor operation");
152 static	int ath_countrycode = CTRY_DEFAULT;	/* country code */
153 SYSCTL_INT(_hw_ath, OID_AUTO, countrycode, CTLFLAG_RD, &ath_countrycode,
154 	    0, "country code");
155 static	int ath_regdomain = 0;			/* regulatory domain */
156 SYSCTL_INT(_hw_ath, OID_AUTO, regdomain, CTLFLAG_RD, &ath_regdomain,
157 	    0, "regulatory domain");
158 
159 #ifdef AR_DEBUG
160 int	ath_debug = 0;
161 SYSCTL_INT(_hw_ath, OID_AUTO, debug, CTLFLAG_RW, &ath_debug,
162 	    0, "control debugging printfs");
163 #define	IFF_DUMPPKTS(_ifp) \
164 	(ath_debug || \
165 	    ((_ifp)->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
166 static	void ath_printrxbuf(struct ath_buf *bf, int);
167 static	void ath_printtxbuf(struct ath_buf *bf, int);
168 #define	DPRINTF(X)	if (ath_debug) printf X
169 #define	DPRINTF2(X)	if (ath_debug > 1) printf X
170 #else
171 #define	IFF_DUMPPKTS(_ifp) \
172 	(((_ifp)->if_flags & (IFF_DEBUG|IFF_LINK2)) == (IFF_DEBUG|IFF_LINK2))
173 #define	DPRINTF(X)
174 #define	DPRINTF2(X)
175 #endif
176 
177 int
178 ath_attach(u_int16_t devid, struct ath_softc *sc)
179 {
180 	struct ieee80211com *ic = &sc->sc_ic;
181 	struct ifnet *ifp = &ic->ic_if;
182 	struct ath_hal *ah;
183 	HAL_STATUS status;
184 	int error = 0;
185 
186 	DPRINTF(("ath_attach: devid 0x%x\n", devid));
187 
188 	/* set these up early for if_printf use */
189 	if_initname(ifp, device_get_name(sc->sc_dev),
190 	    device_get_unit(sc->sc_dev));
191 
192 	ah = ath_hal_attach(devid, sc, sc->sc_st, sc->sc_sh, &status);
193 	if (ah == NULL) {
194 		if_printf(ifp, "unable to attach hardware; HAL status %u\n",
195 			status);
196 		error = ENXIO;
197 		goto bad;
198 	}
199 	if (ah->ah_abi != HAL_ABI_VERSION) {
200 		if_printf(ifp, "HAL ABI mismatch detected (0x%x != 0x%x)\n",
201 			ah->ah_abi, HAL_ABI_VERSION);
202 		error = ENXIO;
203 		goto bad;
204 	}
205 	if_printf(ifp, "mac %d.%d phy %d.%d",
206 		ah->ah_macVersion, ah->ah_macRev,
207 		ah->ah_phyRev >> 4, ah->ah_phyRev & 0xf);
208 	if (ah->ah_analog5GhzRev)
209 		printf(" 5ghz radio %d.%d",
210 			ah->ah_analog5GhzRev >> 4, ah->ah_analog5GhzRev & 0xf);
211 	if (ah->ah_analog2GhzRev)
212 		printf(" 2ghz radio %d.%d",
213 			ah->ah_analog2GhzRev >> 4, ah->ah_analog2GhzRev & 0xf);
214 	printf("\n");
215 	sc->sc_ah = ah;
216 	sc->sc_invalid = 0;	/* ready to go, enable interrupt handling */
217 
218 	/*
219 	 * Collect the channel list using the default country
220 	 * code and including outdoor channels.  The 802.11 layer
221 	 * is resposible for filtering this list based on settings
222 	 * like the phy mode.
223 	 */
224 	error = ath_getchannels(sc, ath_countrycode, ath_outdoor);
225 	if (error != 0)
226 		goto bad;
227 	/*
228 	 * Copy these back; they are set as a side effect
229 	 * of constructing the channel list.
230 	 */
231 	ath_regdomain = ath_hal_getregdomain(ah);
232 	ath_countrycode = ath_hal_getcountrycode(ah);
233 
234 	/*
235 	 * Setup rate tables for all potential media types.
236 	 */
237 	ath_rate_setup(sc, IEEE80211_MODE_11A);
238 	ath_rate_setup(sc, IEEE80211_MODE_11B);
239 	ath_rate_setup(sc, IEEE80211_MODE_11G);
240 	ath_rate_setup(sc, IEEE80211_MODE_TURBO);
241 
242 	error = ath_desc_alloc(sc);
243 	if (error != 0) {
244 		if_printf(ifp, "failed to allocate descriptors: %d\n", error);
245 		goto bad;
246 	}
247 	callout_init(&sc->sc_scan_ch, CALLOUT_MPSAFE);
248 	callout_init(&sc->sc_cal_ch, CALLOUT_MPSAFE);
249 
250 	ATH_TXBUF_LOCK_INIT(sc);
251 	ATH_TXQ_LOCK_INIT(sc);
252 
253 	TASK_INIT(&sc->sc_txtask, 0, ath_tx_proc, sc);
254 	TASK_INIT(&sc->sc_rxtask, 0, ath_rx_proc, sc);
255 	TASK_INIT(&sc->sc_swbatask, 0, ath_beacon_proc, sc);
256 	TASK_INIT(&sc->sc_rxorntask, 0, ath_rxorn_proc, sc);
257 	TASK_INIT(&sc->sc_fataltask, 0, ath_fatal_proc, sc);
258 	TASK_INIT(&sc->sc_bmisstask, 0, ath_bmiss_proc, sc);
259 
260 	/*
261 	 * For now just pre-allocate one data queue and one
262 	 * beacon queue.  Note that the HAL handles resetting
263 	 * them at the needed time.  Eventually we'll want to
264 	 * allocate more tx queues for splitting management
265 	 * frames and for QOS support.
266 	 */
267 	sc->sc_txhalq = ath_hal_setuptxqueue(ah,
268 		HAL_TX_QUEUE_DATA,
269 		AH_TRUE			/* enable interrupts */
270 	);
271 	if (sc->sc_txhalq == (u_int) -1) {
272 		if_printf(ifp, "unable to setup a data xmit queue!\n");
273 		goto bad;
274 	}
275 	sc->sc_bhalq = ath_hal_setuptxqueue(ah,
276 		HAL_TX_QUEUE_BEACON,
277 		AH_TRUE			/* enable interrupts */
278 	);
279 	if (sc->sc_bhalq == (u_int) -1) {
280 		if_printf(ifp, "unable to setup a beacon xmit queue!\n");
281 		goto bad;
282 	}
283 
284 	ifp->if_softc = sc;
285 	ifp->if_flags = IFF_SIMPLEX | IFF_BROADCAST | IFF_MULTICAST;
286 	ifp->if_start = ath_start;
287 	ifp->if_watchdog = ath_watchdog;
288 	ifp->if_ioctl = ath_ioctl;
289 	ifp->if_init = ath_init;
290 	ifp->if_snd.ifq_maxlen = IFQ_MAXLEN;
291 
292 	ic->ic_softc = sc;
293 	ic->ic_newassoc = ath_newassoc;
294 	/* XXX not right but it's not used anywhere important */
295 	ic->ic_phytype = IEEE80211_T_OFDM;
296 	ic->ic_opmode = IEEE80211_M_STA;
297 	ic->ic_caps = IEEE80211_C_WEP		/* wep supported */
298 		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
299 		| IEEE80211_C_HOSTAP		/* hostap mode */
300 		| IEEE80211_C_MONITOR		/* monitor mode */
301 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
302 		| IEEE80211_C_RCVMGT;		/* recv management frames */
303 
304 	/* get mac address from hardware */
305 	ath_hal_getmac(ah, ic->ic_myaddr);
306 
307 	/* call MI attach routine. */
308 	ieee80211_ifattach(ifp);
309 	/* override default methods */
310 	ic->ic_node_alloc = ath_node_alloc;
311 	ic->ic_node_free = ath_node_free;
312 	ic->ic_node_copy = ath_node_copy;
313 	ic->ic_node_getrssi = ath_node_getrssi;
314 	sc->sc_newstate = ic->ic_newstate;
315 	ic->ic_newstate = ath_newstate;
316 	/* complete initialization */
317 	ieee80211_media_init(ifp, ath_media_change, ieee80211_media_status);
318 
319 	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
320 		sizeof(struct ieee80211_frame) + sizeof(sc->sc_tx_th),
321 		&sc->sc_drvbpf);
322 	/*
323 	 * Initialize constant fields.
324 	 *
325 	 * NB: the channel is setup each time we transition to the
326 	 *     RUN state to avoid filling it in for each frame.
327 	 */
328 	sc->sc_tx_th.wt_ihdr.it_len = sizeof(sc->sc_tx_th);
329 	sc->sc_tx_th.wt_ihdr.it_present = ATH_TX_RADIOTAP_PRESENT;
330 
331 	sc->sc_rx_th.wr_ihdr.it_len = sizeof(sc->sc_rx_th);
332 	sc->sc_rx_th.wr_ihdr.it_present = ATH_RX_RADIOTAP_PRESENT;
333 
334 	if_printf(ifp, "802.11 address: %s\n", ether_sprintf(ic->ic_myaddr));
335 
336 	return 0;
337 bad:
338 	if (ah)
339 		ath_hal_detach(ah);
340 	sc->sc_invalid = 1;
341 	return error;
342 }
343 
344 int
345 ath_detach(struct ath_softc *sc)
346 {
347 	struct ifnet *ifp = &sc->sc_ic.ic_if;
348 
349 	DPRINTF(("ath_detach: if_flags %x\n", ifp->if_flags));
350 
351 	ath_stop(ifp);
352 	bpfdetach(ifp);
353 	ath_desc_free(sc);
354 	ath_hal_detach(sc->sc_ah);
355 	ieee80211_ifdetach(ifp);
356 
357 	ATH_TXBUF_LOCK_DESTROY(sc);
358 	ATH_TXQ_LOCK_DESTROY(sc);
359 
360 	return 0;
361 }
362 
363 void
364 ath_suspend(struct ath_softc *sc)
365 {
366 	struct ifnet *ifp = &sc->sc_ic.ic_if;
367 
368 	DPRINTF(("ath_suspend: if_flags %x\n", ifp->if_flags));
369 
370 	ath_stop(ifp);
371 }
372 
373 void
374 ath_resume(struct ath_softc *sc)
375 {
376 	struct ifnet *ifp = &sc->sc_ic.ic_if;
377 
378 	DPRINTF(("ath_resume: if_flags %x\n", ifp->if_flags));
379 
380 	if (ifp->if_flags & IFF_UP) {
381 		ath_init(ifp);
382 		if (ifp->if_flags & IFF_RUNNING)
383 			ath_start(ifp);
384 	}
385 }
386 
387 void
388 ath_shutdown(struct ath_softc *sc)
389 {
390 	struct ifnet *ifp = &sc->sc_ic.ic_if;
391 
392 	DPRINTF(("ath_shutdown: if_flags %x\n", ifp->if_flags));
393 
394 	ath_stop(ifp);
395 }
396 
397 void
398 ath_intr(void *arg)
399 {
400 	struct ath_softc *sc = arg;
401 	struct ieee80211com *ic = &sc->sc_ic;
402 	struct ifnet *ifp = &ic->ic_if;
403 	struct ath_hal *ah = sc->sc_ah;
404 	HAL_INT status;
405 
406 	if (sc->sc_invalid) {
407 		/*
408 		 * The hardware is not ready/present, don't touch anything.
409 		 * Note this can happen early on if the IRQ is shared.
410 		 */
411 		DPRINTF(("ath_intr: invalid; ignored\n"));
412 		return;
413 	}
414 	if ((ifp->if_flags & (IFF_RUNNING|IFF_UP)) != (IFF_RUNNING|IFF_UP)) {
415 		DPRINTF(("ath_intr: if_flags 0x%x\n", ifp->if_flags));
416 		ath_hal_getisr(ah, &status);	/* clear ISR */
417 		ath_hal_intrset(ah, 0);		/* disable further intr's */
418 		return;
419 	}
420 	ath_hal_getisr(ah, &status);		/* NB: clears ISR too */
421 	DPRINTF2(("ath_intr: status 0x%x\n", status));
422 #ifdef AR_DEBUG
423 	if (ath_debug &&
424 	    (status & (HAL_INT_FATAL|HAL_INT_RXORN|HAL_INT_BMISS))) {
425 		if_printf(ifp, "ath_intr: status 0x%x\n", status);
426 		ath_hal_dumpstate(ah);
427 	}
428 #endif /* AR_DEBUG */
429 	status &= sc->sc_imask;			/* discard unasked for bits */
430 	if (status & HAL_INT_FATAL) {
431 		sc->sc_stats.ast_hardware++;
432 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
433 		taskqueue_enqueue(taskqueue_swi, &sc->sc_fataltask);
434 	} else if (status & HAL_INT_RXORN) {
435 		sc->sc_stats.ast_rxorn++;
436 		ath_hal_intrset(ah, 0);		/* disable intr's until reset */
437 		taskqueue_enqueue(taskqueue_swi, &sc->sc_rxorntask);
438 	} else {
439 		if (status & HAL_INT_RXEOL) {
440 			/*
441 			 * NB: the hardware should re-read the link when
442 			 *     RXE bit is written, but it doesn't work at
443 			 *     least on older hardware revs.
444 			 */
445 			sc->sc_stats.ast_rxeol++;
446 			sc->sc_rxlink = NULL;
447 		}
448 		if (status & HAL_INT_TXURN) {
449 			sc->sc_stats.ast_txurn++;
450 			/* bump tx trigger level */
451 			ath_hal_updatetxtriglevel(ah, AH_TRUE);
452 		}
453 		if (status & HAL_INT_RX)
454 			taskqueue_enqueue(taskqueue_swi, &sc->sc_rxtask);
455 		if (status & HAL_INT_TX)
456 			taskqueue_enqueue(taskqueue_swi, &sc->sc_txtask);
457 		if (status & HAL_INT_SWBA)
458 			taskqueue_enqueue(taskqueue_swi, &sc->sc_swbatask);
459 		if (status & HAL_INT_BMISS) {
460 			sc->sc_stats.ast_bmiss++;
461 			taskqueue_enqueue(taskqueue_swi, &sc->sc_bmisstask);
462 		}
463 	}
464 }
465 
466 static void
467 ath_fatal_proc(void *arg, int pending)
468 {
469 	struct ath_softc *sc = arg;
470 
471 	device_printf(sc->sc_dev, "hardware error; resetting\n");
472 	ath_reset(sc);
473 }
474 
475 static void
476 ath_rxorn_proc(void *arg, int pending)
477 {
478 	struct ath_softc *sc = arg;
479 
480 	device_printf(sc->sc_dev, "rx FIFO overrun; resetting\n");
481 	ath_reset(sc);
482 }
483 
484 static void
485 ath_bmiss_proc(void *arg, int pending)
486 {
487 	struct ath_softc *sc = arg;
488 	struct ieee80211com *ic = &sc->sc_ic;
489 
490 	DPRINTF(("ath_bmiss_proc: pending %u\n", pending));
491 	KASSERT(ic->ic_opmode == IEEE80211_M_STA,
492 		("unexpect operating mode %u", ic->ic_opmode));
493 	if (ic->ic_state == IEEE80211_S_RUN)
494 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
495 }
496 
497 static u_int
498 ath_chan2flags(struct ieee80211com *ic, struct ieee80211_channel *chan)
499 {
500 	static const u_int modeflags[] = {
501 		0,			/* IEEE80211_MODE_AUTO */
502 		CHANNEL_A,		/* IEEE80211_MODE_11A */
503 		CHANNEL_B,		/* IEEE80211_MODE_11B */
504 		CHANNEL_PUREG,		/* IEEE80211_MODE_11G */
505 		CHANNEL_T		/* IEEE80211_MODE_TURBO */
506 	};
507 	return modeflags[ieee80211_chan2mode(ic, chan)];
508 }
509 
510 static void
511 ath_init(void *arg)
512 {
513 	struct ath_softc *sc = (struct ath_softc *) arg;
514 	struct ieee80211com *ic = &sc->sc_ic;
515 	struct ifnet *ifp = &ic->ic_if;
516 	struct ieee80211_node *ni;
517 	enum ieee80211_phymode mode;
518 	struct ath_hal *ah = sc->sc_ah;
519 	HAL_STATUS status;
520 	HAL_CHANNEL hchan;
521 
522 	DPRINTF(("ath_init: if_flags 0x%x\n", ifp->if_flags));
523 
524 	ATH_LOCK(sc);
525 	/*
526 	 * Stop anything previously setup.  This is safe
527 	 * whether this is the first time through or not.
528 	 */
529 	ath_stop(ifp);
530 
531 	/*
532 	 * The basic interface to setting the hardware in a good
533 	 * state is ``reset''.  On return the hardware is known to
534 	 * be powered up and with interrupts disabled.  This must
535 	 * be followed by initialization of the appropriate bits
536 	 * and then setup of the interrupt mask.
537 	 */
538 	hchan.channel = ic->ic_ibss_chan->ic_freq;
539 	hchan.channelFlags = ath_chan2flags(ic, ic->ic_ibss_chan);
540 	if (!ath_hal_reset(ah, ic->ic_opmode, &hchan, AH_FALSE, &status)) {
541 		if_printf(ifp, "unable to reset hardware; hal status %u\n",
542 			status);
543 		goto done;
544 	}
545 
546 	/*
547 	 * Setup the hardware after reset: the key cache
548 	 * is filled as needed and the receive engine is
549 	 * set going.  Frame transmit is handled entirely
550 	 * in the frame output path; there's nothing to do
551 	 * here except setup the interrupt mask.
552 	 */
553 	if (ic->ic_flags & IEEE80211_F_WEPON)
554 		ath_initkeytable(sc);
555 	if (ath_startrecv(sc) != 0) {
556 		if_printf(ifp, "unable to start recv logic\n");
557 		goto done;
558 	}
559 
560 	/*
561 	 * Enable interrupts.
562 	 */
563 	sc->sc_imask = HAL_INT_RX | HAL_INT_TX
564 		  | HAL_INT_RXEOL | HAL_INT_RXORN
565 		  | HAL_INT_FATAL | HAL_INT_GLOBAL;
566 	ath_hal_intrset(ah, sc->sc_imask);
567 
568 	ifp->if_flags |= IFF_RUNNING;
569 	ic->ic_state = IEEE80211_S_INIT;
570 
571 	/*
572 	 * The hardware should be ready to go now so it's safe
573 	 * to kick the 802.11 state machine as it's likely to
574 	 * immediately call back to us to send mgmt frames.
575 	 */
576 	ni = ic->ic_bss;
577 	ni->ni_chan = ic->ic_ibss_chan;
578 	mode = ieee80211_chan2mode(ic, ni->ni_chan);
579 	if (mode != sc->sc_curmode)
580 		ath_setcurmode(sc, mode);
581 	if (ic->ic_opmode != IEEE80211_M_MONITOR)
582 		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
583 	else
584 		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
585 done:
586 	ATH_UNLOCK(sc);
587 }
588 
589 static void
590 ath_stop(struct ifnet *ifp)
591 {
592 	struct ieee80211com *ic = (struct ieee80211com *) ifp;
593 	struct ath_softc *sc = ifp->if_softc;
594 	struct ath_hal *ah = sc->sc_ah;
595 
596 	DPRINTF(("ath_stop: invalid %u if_flags 0x%x\n",
597 		sc->sc_invalid, ifp->if_flags));
598 
599 	ATH_LOCK(sc);
600 	if (ifp->if_flags & IFF_RUNNING) {
601 		/*
602 		 * Shutdown the hardware and driver:
603 		 *    disable interrupts
604 		 *    turn off timers
605 		 *    clear transmit machinery
606 		 *    clear receive machinery
607 		 *    drain and release tx queues
608 		 *    reclaim beacon resources
609 		 *    reset 802.11 state machine
610 		 *    power down hardware
611 		 *
612 		 * Note that some of this work is not possible if the
613 		 * hardware is gone (invalid).
614 		 */
615 		ifp->if_flags &= ~IFF_RUNNING;
616 		ifp->if_timer = 0;
617 		if (!sc->sc_invalid)
618 			ath_hal_intrset(ah, 0);
619 		ath_draintxq(sc);
620 		if (!sc->sc_invalid)
621 			ath_stoprecv(sc);
622 		else
623 			sc->sc_rxlink = NULL;
624 		IF_DRAIN(&ifp->if_snd);
625 		ath_beacon_free(sc);
626 		ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
627 		if (!sc->sc_invalid)
628 			ath_hal_setpower(ah, HAL_PM_FULL_SLEEP, 0);
629 	}
630 	ATH_UNLOCK(sc);
631 }
632 
633 /*
634  * Reset the hardware w/o losing operational state.  This is
635  * basically a more efficient way of doing ath_stop, ath_init,
636  * followed by state transitions to the current 802.11
637  * operational state.  Used to recover from errors rx overrun
638  * and to reset the hardware when rf gain settings must be reset.
639  */
640 static void
641 ath_reset(struct ath_softc *sc)
642 {
643 	struct ieee80211com *ic = &sc->sc_ic;
644 	struct ifnet *ifp = &ic->ic_if;
645 	struct ath_hal *ah = sc->sc_ah;
646 	struct ieee80211_channel *c;
647 	HAL_STATUS status;
648 	HAL_CHANNEL hchan;
649 
650 	/*
651 	 * Convert to a HAL channel description with the flags
652 	 * constrained to reflect the current operating mode.
653 	 */
654 	c = ic->ic_ibss_chan;
655 	hchan.channel = c->ic_freq;
656 	hchan.channelFlags = ath_chan2flags(ic, c);
657 
658 	ath_hal_intrset(ah, 0);		/* disable interrupts */
659 	ath_draintxq(sc);		/* stop xmit side */
660 	ath_stoprecv(sc);		/* stop recv side */
661 	/* NB: indicate channel change so we do a full reset */
662 	if (!ath_hal_reset(ah, ic->ic_opmode, &hchan, AH_TRUE, &status))
663 		if_printf(ifp, "%s: unable to reset hardware; hal status %u\n",
664 			__func__, status);
665 	ath_hal_intrset(ah, sc->sc_imask);
666 	if (ath_startrecv(sc) != 0)	/* restart recv */
667 		if_printf(ifp, "%s: unable to start recv logic\n", __func__);
668 	ath_start(ifp);			/* restart xmit */
669 	if (ic->ic_state == IEEE80211_S_RUN)
670 		ath_beacon_config(sc);	/* restart beacons */
671 }
672 
673 static void
674 ath_start(struct ifnet *ifp)
675 {
676 	struct ath_softc *sc = ifp->if_softc;
677 	struct ath_hal *ah = sc->sc_ah;
678 	struct ieee80211com *ic = &sc->sc_ic;
679 	struct ieee80211_node *ni;
680 	struct ath_buf *bf;
681 	struct mbuf *m;
682 	struct ieee80211_frame *wh;
683 
684 	if ((ifp->if_flags & IFF_RUNNING) == 0 || sc->sc_invalid)
685 		return;
686 	for (;;) {
687 		/*
688 		 * Grab a TX buffer and associated resources.
689 		 */
690 		ATH_TXBUF_LOCK(sc);
691 		bf = TAILQ_FIRST(&sc->sc_txbuf);
692 		if (bf != NULL)
693 			TAILQ_REMOVE(&sc->sc_txbuf, bf, bf_list);
694 		ATH_TXBUF_UNLOCK(sc);
695 		if (bf == NULL) {
696 			DPRINTF(("ath_start: out of xmit buffers\n"));
697 			sc->sc_stats.ast_tx_qstop++;
698 			ifp->if_flags |= IFF_OACTIVE;
699 			break;
700 		}
701 		/*
702 		 * Poll the management queue for frames; they
703 		 * have priority over normal data frames.
704 		 */
705 		IF_DEQUEUE(&ic->ic_mgtq, m);
706 		if (m == NULL) {
707 			/*
708 			 * No data frames go out unless we're associated.
709 			 */
710 			if (ic->ic_state != IEEE80211_S_RUN) {
711 				DPRINTF(("ath_start: ignore data packet, "
712 					"state %u\n", ic->ic_state));
713 				sc->sc_stats.ast_tx_discard++;
714 				ATH_TXBUF_LOCK(sc);
715 				TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
716 				ATH_TXBUF_UNLOCK(sc);
717 				break;
718 			}
719 			IF_DEQUEUE(&ifp->if_snd, m);
720 			if (m == NULL) {
721 				ATH_TXBUF_LOCK(sc);
722 				TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
723 				ATH_TXBUF_UNLOCK(sc);
724 				break;
725 			}
726 			ifp->if_opackets++;
727 			BPF_MTAP(ifp, m);
728 			/*
729 			 * Encapsulate the packet in prep for transmission.
730 			 */
731 			m = ieee80211_encap(ifp, m, &ni);
732 			if (m == NULL) {
733 				DPRINTF(("ath_start: encapsulation failure\n"));
734 				sc->sc_stats.ast_tx_encap++;
735 				goto bad;
736 			}
737 			wh = mtod(m, struct ieee80211_frame *);
738 			if (ic->ic_flags & IEEE80211_F_WEPON)
739 				wh->i_fc[1] |= IEEE80211_FC1_WEP;
740 		} else {
741 			/*
742 			 * Hack!  The referenced node pointer is in the
743 			 * rcvif field of the packet header.  This is
744 			 * placed there by ieee80211_mgmt_output because
745 			 * we need to hold the reference with the frame
746 			 * and there's no other way (other than packet
747 			 * tags which we consider too expensive to use)
748 			 * to pass it along.
749 			 */
750 			ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
751 			m->m_pkthdr.rcvif = NULL;
752 
753 			wh = mtod(m, struct ieee80211_frame *);
754 			if ((wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK) ==
755 			    IEEE80211_FC0_SUBTYPE_PROBE_RESP) {
756 				/* fill time stamp */
757 				u_int64_t tsf;
758 				u_int32_t *tstamp;
759 
760 				tsf = ath_hal_gettsf64(ah);
761 				/* XXX: adjust 100us delay to xmit */
762 				tsf += 100;
763 				tstamp = (u_int32_t *)&wh[1];
764 				tstamp[0] = htole32(tsf & 0xffffffff);
765 				tstamp[1] = htole32(tsf >> 32);
766 			}
767 			sc->sc_stats.ast_tx_mgmt++;
768 		}
769 		if (ic->ic_rawbpf)
770 			bpf_mtap(ic->ic_rawbpf, m);
771 
772 		if (sc->sc_drvbpf) {
773 			struct mbuf *mb;
774 
775 			MGETHDR(mb, M_DONTWAIT, m->m_type);
776 			if (mb != NULL) {
777 				sc->sc_tx_th.wt_rate =
778 					ni->ni_rates.rs_rates[ni->ni_txrate];
779 
780 				mb->m_next = m;
781 				mb->m_data = (caddr_t)&sc->sc_tx_th;
782 				mb->m_len = sizeof(sc->sc_tx_th);
783 				mb->m_pkthdr.len += mb->m_len;
784 				bpf_mtap(sc->sc_drvbpf, mb);
785 				m_free(mb);
786 			}
787 		}
788 
789 		if (ath_tx_start(sc, ni, bf, m)) {
790 	bad:
791 			ATH_TXBUF_LOCK(sc);
792 			TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
793 			ATH_TXBUF_UNLOCK(sc);
794 			ifp->if_oerrors++;
795 			if (ni && ni != ic->ic_bss)
796 				ieee80211_free_node(ic, ni);
797 			continue;
798 		}
799 
800 		sc->sc_tx_timer = 5;
801 		ifp->if_timer = 1;
802 	}
803 }
804 
805 static int
806 ath_media_change(struct ifnet *ifp)
807 {
808 	int error;
809 
810 	error = ieee80211_media_change(ifp);
811 	if (error == ENETRESET) {
812 		if ((ifp->if_flags & (IFF_RUNNING|IFF_UP)) ==
813 		    (IFF_RUNNING|IFF_UP))
814 			ath_init(ifp);		/* XXX lose error */
815 		error = 0;
816 	}
817 	return error;
818 }
819 
820 static void
821 ath_watchdog(struct ifnet *ifp)
822 {
823 	struct ath_softc *sc = ifp->if_softc;
824 	struct ieee80211com *ic = &sc->sc_ic;
825 
826 	ifp->if_timer = 0;
827 	if ((ifp->if_flags & IFF_RUNNING) == 0 || sc->sc_invalid)
828 		return;
829 	if (sc->sc_tx_timer) {
830 		if (--sc->sc_tx_timer == 0) {
831 			if_printf(ifp, "device timeout\n");
832 #ifdef AR_DEBUG
833 			if (ath_debug)
834 				ath_hal_dumpstate(sc->sc_ah);
835 #endif /* AR_DEBUG */
836 			ath_init(ifp);		/* XXX ath_reset??? */
837 			ifp->if_oerrors++;
838 			sc->sc_stats.ast_watchdog++;
839 			return;
840 		}
841 		ifp->if_timer = 1;
842 	}
843 	if (ic->ic_fixed_rate == -1) {
844 		/*
845 		 * Run the rate control algorithm if we're not
846 		 * locked at a fixed rate.
847 		 */
848 		if (ic->ic_opmode == IEEE80211_M_STA)
849 			ath_rate_ctl(sc, ic->ic_bss);
850 		else
851 			ieee80211_iterate_nodes(ic, ath_rate_ctl, sc);
852 	}
853 	ieee80211_watchdog(ifp);
854 }
855 
856 static int
857 ath_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
858 {
859 	struct ath_softc *sc = ifp->if_softc;
860 	struct ifreq *ifr = (struct ifreq *)data;
861 	int error = 0;
862 
863 	ATH_LOCK(sc);
864 	switch (cmd) {
865 	case SIOCSIFFLAGS:
866 		if (ifp->if_flags & IFF_UP) {
867 			if (ifp->if_flags & IFF_RUNNING) {
868 				/*
869 				 * To avoid rescanning another access point,
870 				 * do not call ath_init() here.  Instead,
871 				 * only reflect promisc mode settings.
872 				 */
873 				ath_mode_init(sc);
874 			} else {
875 				/*
876 				 * Beware of being called during detach to
877 				 * reset promiscuous mode.  In that case we
878 				 * will still be marked UP but not RUNNING.
879 				 * However trying to re-init the interface
880 				 * is the wrong thing to do as we've already
881 				 * torn down much of our state.  There's
882 				 * probably a better way to deal with this.
883 				 */
884 				if (!sc->sc_invalid)
885 					ath_init(ifp);	/* XXX lose error */
886 			}
887 		} else
888 			ath_stop(ifp);
889 		break;
890 	case SIOCADDMULTI:
891 	case SIOCDELMULTI:
892 		/*
893 		 * The upper layer has already installed/removed
894 		 * the multicast address(es), just recalculate the
895 		 * multicast filter for the card.
896 		 */
897 		if (ifp->if_flags & IFF_RUNNING)
898 			ath_mode_init(sc);
899 		break;
900 	case SIOCGATHSTATS:
901 		copyout(&sc->sc_stats, ifr->ifr_data, sizeof (sc->sc_stats));
902 		break;
903 	default:
904 		error = ieee80211_ioctl(ifp, cmd, data);
905 		if (error == ENETRESET) {
906 			if ((ifp->if_flags & (IFF_RUNNING|IFF_UP)) ==
907 			    (IFF_RUNNING|IFF_UP))
908 				ath_init(ifp);		/* XXX lose error */
909 			error = 0;
910 		}
911 		break;
912 	}
913 	ATH_UNLOCK(sc);
914 	return error;
915 }
916 
917 /*
918  * Fill the hardware key cache with key entries.
919  */
920 static void
921 ath_initkeytable(struct ath_softc *sc)
922 {
923 	struct ieee80211com *ic = &sc->sc_ic;
924 	struct ath_hal *ah = sc->sc_ah;
925 	int i;
926 
927 	for (i = 0; i < IEEE80211_WEP_NKID; i++) {
928 		struct ieee80211_wepkey *k = &ic->ic_nw_keys[i];
929 		if (k->wk_len == 0)
930 			ath_hal_keyreset(ah, i);
931 		else
932 			/* XXX return value */
933 			/* NB: this uses HAL_KEYVAL == ieee80211_wepkey */
934 			ath_hal_keyset(ah, i, (const HAL_KEYVAL *) k);
935 	}
936 }
937 
938 /*
939  * Calculate the receive filter according to the
940  * operating mode and state:
941  *
942  * o always accept unicast, broadcast, and multicast traffic
943  * o maintain current state of phy error reception
944  * o probe request frames are accepted only when operating in
945  *   hostap, adhoc, or monitor modes
946  * o enable promiscuous mode according to the interface state
947  * o accept beacons:
948  *   - when operating in adhoc mode so the 802.11 layer creates
949  *     node table entries for peers,
950  *   - when operating in station mode for collecting rssi data when
951  *     the station is otherwise quiet, or
952  *   - when scanning
953  */
954 static u_int32_t
955 ath_calcrxfilter(struct ath_softc *sc)
956 {
957 	struct ieee80211com *ic = &sc->sc_ic;
958 	struct ath_hal *ah = sc->sc_ah;
959 	struct ifnet *ifp = &ic->ic_if;
960 	u_int32_t rfilt;
961 
962 	rfilt = (ath_hal_getrxfilter(ah) & HAL_RX_FILTER_PHYERR)
963 	      | HAL_RX_FILTER_UCAST | HAL_RX_FILTER_BCAST | HAL_RX_FILTER_MCAST;
964 	if (ic->ic_opmode != IEEE80211_M_STA)
965 		rfilt |= HAL_RX_FILTER_PROBEREQ;
966 	if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
967 	    (ifp->if_flags & IFF_PROMISC))
968 		rfilt |= HAL_RX_FILTER_PROM;
969 	if (ic->ic_opmode == IEEE80211_M_STA ||
970 	    ic->ic_opmode == IEEE80211_M_IBSS ||
971 	    ic->ic_state == IEEE80211_S_SCAN)
972 		rfilt |= HAL_RX_FILTER_BEACON;
973 	return rfilt;
974 }
975 
976 static void
977 ath_mode_init(struct ath_softc *sc)
978 {
979 	struct ieee80211com *ic = &sc->sc_ic;
980 	struct ath_hal *ah = sc->sc_ah;
981 	struct ifnet *ifp = &ic->ic_if;
982 	u_int32_t rfilt, mfilt[2], val;
983 	u_int8_t pos;
984 	struct ifmultiaddr *ifma;
985 
986 	/* configure rx filter */
987 	rfilt = ath_calcrxfilter(sc);
988 	ath_hal_setrxfilter(ah, rfilt);
989 
990 	/* configure operational mode */
991 	ath_hal_setopmode(ah, ic->ic_opmode);
992 
993 	/* calculate and install multicast filter */
994 	if ((ifp->if_flags & IFF_ALLMULTI) == 0) {
995 		mfilt[0] = mfilt[1] = 0;
996 		TAILQ_FOREACH(ifma, &ifp->if_multiaddrs, ifma_link) {
997 			caddr_t dl;
998 
999 			/* calculate XOR of eight 6bit values */
1000 			dl = LLADDR((struct sockaddr_dl *) ifma->ifma_addr);
1001 			val = LE_READ_4(dl + 0);
1002 			pos = (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
1003 			val = LE_READ_4(dl + 3);
1004 			pos ^= (val >> 18) ^ (val >> 12) ^ (val >> 6) ^ val;
1005 			pos &= 0x3f;
1006 			mfilt[pos / 32] |= (1 << (pos % 32));
1007 		}
1008 	} else {
1009 		mfilt[0] = mfilt[1] = ~0;
1010 	}
1011 	ath_hal_setmcastfilter(ah, mfilt[0], mfilt[1]);
1012 	DPRINTF(("ath_mode_init: RX filter 0x%x, MC filter %08x:%08x\n",
1013 		rfilt, mfilt[0], mfilt[1]));
1014 }
1015 
1016 static void
1017 ath_mbuf_load_cb(void *arg, bus_dma_segment_t *seg, int nseg, bus_size_t mapsize, int error)
1018 {
1019 	struct ath_buf *bf = arg;
1020 
1021 	KASSERT(nseg <= ATH_MAX_SCATTER,
1022 		("ath_mbuf_load_cb: too many DMA segments %u", nseg));
1023 	bf->bf_mapsize = mapsize;
1024 	bf->bf_nseg = nseg;
1025 	bcopy(seg, bf->bf_segs, nseg * sizeof (seg[0]));
1026 }
1027 
1028 static int
1029 ath_beacon_alloc(struct ath_softc *sc, struct ieee80211_node *ni)
1030 {
1031 	struct ieee80211com *ic = &sc->sc_ic;
1032 	struct ifnet *ifp = &ic->ic_if;
1033 	struct ath_hal *ah = sc->sc_ah;
1034 	struct ieee80211_frame *wh;
1035 	struct ath_buf *bf;
1036 	struct ath_desc *ds;
1037 	struct mbuf *m;
1038 	int error, pktlen;
1039 	u_int8_t *frm, rate;
1040 	u_int16_t capinfo;
1041 	struct ieee80211_rateset *rs;
1042 	const HAL_RATE_TABLE *rt;
1043 
1044 	bf = sc->sc_bcbuf;
1045 	if (bf->bf_m != NULL) {
1046 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
1047 		m_freem(bf->bf_m);
1048 		bf->bf_m = NULL;
1049 		bf->bf_node = NULL;
1050 	}
1051 	/*
1052 	 * NB: the beacon data buffer must be 32-bit aligned;
1053 	 * we assume the mbuf routines will return us something
1054 	 * with this alignment (perhaps should assert).
1055 	 */
1056 	rs = &ni->ni_rates;
1057 	pktlen = sizeof (struct ieee80211_frame)
1058 	       + 8 + 2 + 2 + 2+ni->ni_esslen + 2+rs->rs_nrates + 3 + 6;
1059 	if (rs->rs_nrates > IEEE80211_RATE_SIZE)
1060 		pktlen += 2;
1061 	if (pktlen <= MHLEN)
1062 		MGETHDR(m, M_DONTWAIT, MT_DATA);
1063 	else
1064 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1065 	if (m == NULL) {
1066 		DPRINTF(("ath_beacon_alloc: cannot get mbuf/cluster; size %u\n",
1067 			pktlen));
1068 		sc->sc_stats.ast_be_nombuf++;
1069 		return ENOMEM;
1070 	}
1071 
1072 	wh = mtod(m, struct ieee80211_frame *);
1073 	wh->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_MGT |
1074 	    IEEE80211_FC0_SUBTYPE_BEACON;
1075 	wh->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1076 	*(u_int16_t *)wh->i_dur = 0;
1077 	memcpy(wh->i_addr1, ifp->if_broadcastaddr, IEEE80211_ADDR_LEN);
1078 	memcpy(wh->i_addr2, ic->ic_myaddr, IEEE80211_ADDR_LEN);
1079 	memcpy(wh->i_addr3, ni->ni_bssid, IEEE80211_ADDR_LEN);
1080 	*(u_int16_t *)wh->i_seq = 0;
1081 
1082 	/*
1083 	 * beacon frame format
1084 	 *	[8] time stamp
1085 	 *	[2] beacon interval
1086 	 *	[2] cabability information
1087 	 *	[tlv] ssid
1088 	 *	[tlv] supported rates
1089 	 *	[tlv] parameter set (IBSS)
1090 	 *	[tlv] extended supported rates
1091 	 */
1092 	frm = (u_int8_t *)&wh[1];
1093 	memset(frm, 0, 8);	/* timestamp is set by hardware */
1094 	frm += 8;
1095 	*(u_int16_t *)frm = htole16(ni->ni_intval);
1096 	frm += 2;
1097 	if (ic->ic_opmode == IEEE80211_M_IBSS)
1098 		capinfo = IEEE80211_CAPINFO_IBSS;
1099 	else
1100 		capinfo = IEEE80211_CAPINFO_ESS;
1101 	if (ic->ic_flags & IEEE80211_F_WEPON)
1102 		capinfo |= IEEE80211_CAPINFO_PRIVACY;
1103 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1104 	    IEEE80211_IS_CHAN_2GHZ(ni->ni_chan))
1105 		capinfo |= IEEE80211_CAPINFO_SHORT_PREAMBLE;
1106 	if (ic->ic_flags & IEEE80211_F_SHSLOT)
1107 		capinfo |= IEEE80211_CAPINFO_SHORT_SLOTTIME;
1108 	*(u_int16_t *)frm = htole16(capinfo);
1109 	frm += 2;
1110 	*frm++ = IEEE80211_ELEMID_SSID;
1111 	*frm++ = ni->ni_esslen;
1112 	memcpy(frm, ni->ni_essid, ni->ni_esslen);
1113 	frm += ni->ni_esslen;
1114 	frm = ieee80211_add_rates(frm, rs);
1115 	*frm++ = IEEE80211_ELEMID_DSPARMS;
1116 	*frm++ = 1;
1117 	*frm++ = ieee80211_chan2ieee(ic, ni->ni_chan);
1118 	if (ic->ic_opmode == IEEE80211_M_IBSS) {
1119 		*frm++ = IEEE80211_ELEMID_IBSSPARMS;
1120 		*frm++ = 2;
1121 		*frm++ = 0; *frm++ = 0;		/* TODO: ATIM window */
1122 	} else {
1123 		/* TODO: TIM */
1124 		*frm++ = IEEE80211_ELEMID_TIM;
1125 		*frm++ = 4;	/* length */
1126 		*frm++ = 0;	/* DTIM count */
1127 		*frm++ = 1;	/* DTIM period */
1128 		*frm++ = 0;	/* bitmap control */
1129 		*frm++ = 0;	/* Partial Virtual Bitmap (variable length) */
1130 	}
1131 	frm = ieee80211_add_xrates(frm, rs);
1132 	m->m_pkthdr.len = m->m_len = frm - mtod(m, u_int8_t *);
1133 	KASSERT(m->m_pkthdr.len <= pktlen,
1134 		("beacon bigger than expected, len %u calculated %u",
1135 		m->m_pkthdr.len, pktlen));
1136 
1137 	DPRINTF2(("ath_beacon_alloc: m %p len %u\n", m, m->m_len));
1138 	error = bus_dmamap_load_mbuf(sc->sc_dmat, bf->bf_dmamap, m,
1139 				     ath_mbuf_load_cb, bf,
1140 				     BUS_DMA_NOWAIT);
1141 	if (error != 0) {
1142 		m_freem(m);
1143 		return error;
1144 	}
1145 	KASSERT(bf->bf_nseg == 1,
1146 		("ath_beacon_alloc: multi-segment packet; nseg %u",
1147 		bf->bf_nseg));
1148 	bf->bf_m = m;
1149 
1150 	/* setup descriptors */
1151 	ds = bf->bf_desc;
1152 
1153 	ds->ds_link = 0;
1154 	ds->ds_data = bf->bf_segs[0].ds_addr;
1155 	/*
1156 	 * Calculate rate code.
1157 	 * XXX everything at min xmit rate
1158 	 */
1159 	rt = sc->sc_currates;
1160 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
1161 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1162 		rate = rt->info[0].rateCode | rt->info[0].shortPreamble;
1163 	else
1164 		rate = rt->info[0].rateCode;
1165 	ath_hal_setuptxdesc(ah, ds
1166 		, m->m_pkthdr.len + IEEE80211_CRC_LEN	/* packet length */
1167 		, sizeof(struct ieee80211_frame)	/* header length */
1168 		, HAL_PKT_TYPE_BEACON		/* Atheros packet type */
1169 		, 0x20				/* txpower XXX */
1170 		, rate, 1			/* series 0 rate/tries */
1171 		, HAL_TXKEYIX_INVALID		/* no encryption */
1172 		, 0				/* antenna mode */
1173 		, HAL_TXDESC_NOACK		/* no ack for beacons */
1174 		, 0				/* rts/cts rate */
1175 		, 0				/* rts/cts duration */
1176 	);
1177 	/* NB: beacon's BufLen must be a multiple of 4 bytes */
1178 	/* XXX verify mbuf data area covers this roundup */
1179 	ath_hal_filltxdesc(ah, ds
1180 		, roundup(bf->bf_segs[0].ds_len, 4)	/* buffer length */
1181 		, AH_TRUE				/* first segment */
1182 		, AH_TRUE				/* last segment */
1183 	);
1184 
1185 	return 0;
1186 }
1187 
1188 static void
1189 ath_beacon_proc(void *arg, int pending)
1190 {
1191 	struct ath_softc *sc = arg;
1192 	struct ieee80211com *ic = &sc->sc_ic;
1193 	struct ath_buf *bf = sc->sc_bcbuf;
1194 	struct ath_hal *ah = sc->sc_ah;
1195 
1196 	DPRINTF2(("%s: pending %u\n", __func__, pending));
1197 	if (ic->ic_opmode == IEEE80211_M_STA ||
1198 	    bf == NULL || bf->bf_m == NULL) {
1199 		DPRINTF(("%s: ic_flags=%x bf=%p bf_m=%p\n",
1200 			__func__, ic->ic_flags, bf, bf ? bf->bf_m : NULL));
1201 		return;
1202 	}
1203 	/* TODO: update beacon to reflect PS poll state */
1204 	if (!ath_hal_stoptxdma(ah, sc->sc_bhalq)) {
1205 		DPRINTF(("%s: beacon queue %u did not stop?",
1206 			__func__, sc->sc_bhalq));
1207 		return;			/* busy, XXX is this right? */
1208 	}
1209 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
1210 
1211 	ath_hal_puttxbuf(ah, sc->sc_bhalq, bf->bf_daddr);
1212 	ath_hal_txstart(ah, sc->sc_bhalq);
1213 	DPRINTF2(("%s: TXDP%u = %p (%p)\n", __func__,
1214 		sc->sc_bhalq, (caddr_t)bf->bf_daddr, bf->bf_desc));
1215 }
1216 
1217 static void
1218 ath_beacon_free(struct ath_softc *sc)
1219 {
1220 	struct ath_buf *bf = sc->sc_bcbuf;
1221 
1222 	if (bf->bf_m != NULL) {
1223 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
1224 		m_freem(bf->bf_m);
1225 		bf->bf_m = NULL;
1226 		bf->bf_node = NULL;
1227 	}
1228 }
1229 
1230 /*
1231  * Configure the beacon and sleep timers.
1232  *
1233  * When operating as an AP this resets the TSF and sets
1234  * up the hardware to notify us when we need to issue beacons.
1235  *
1236  * When operating in station mode this sets up the beacon
1237  * timers according to the timestamp of the last received
1238  * beacon and the current TSF, configures PCF and DTIM
1239  * handling, programs the sleep registers so the hardware
1240  * will wakeup in time to receive beacons, and configures
1241  * the beacon miss handling so we'll receive a BMISS
1242  * interrupt when we stop seeing beacons from the AP
1243  * we've associated with.
1244  */
1245 static void
1246 ath_beacon_config(struct ath_softc *sc)
1247 {
1248 	struct ath_hal *ah = sc->sc_ah;
1249 	struct ieee80211com *ic = &sc->sc_ic;
1250 	struct ieee80211_node *ni = ic->ic_bss;
1251 	u_int32_t nexttbtt;
1252 
1253 	nexttbtt = (LE_READ_4(ni->ni_tstamp + 4) << 22) |
1254 	    (LE_READ_4(ni->ni_tstamp) >> 10);
1255 	DPRINTF(("%s: nexttbtt=%u\n", __func__, nexttbtt));
1256 	nexttbtt += ni->ni_intval;
1257 	if (ic->ic_opmode == IEEE80211_M_STA) {
1258 		HAL_BEACON_STATE bs;
1259 		u_int32_t bmisstime;
1260 
1261 		/* NB: no PCF support right now */
1262 		memset(&bs, 0, sizeof(bs));
1263 		bs.bs_intval = ni->ni_intval;
1264 		bs.bs_nexttbtt = nexttbtt;
1265 		bs.bs_dtimperiod = bs.bs_intval;
1266 		bs.bs_nextdtim = nexttbtt;
1267 		/*
1268 		 * Calculate the number of consecutive beacons to miss
1269 		 * before taking a BMISS interrupt.  The configuration
1270 		 * is specified in ms, so we need to convert that to
1271 		 * TU's and then calculate based on the beacon interval.
1272 		 * Note that we clamp the result to at most 10 beacons.
1273 		 */
1274 		bmisstime = (ic->ic_bmisstimeout * 1000) / 1024;
1275 		bs.bs_bmissthreshold = howmany(bmisstime,ni->ni_intval);
1276 		if (bs.bs_bmissthreshold > 10)
1277 			bs.bs_bmissthreshold = 10;
1278 		else if (bs.bs_bmissthreshold <= 0)
1279 			bs.bs_bmissthreshold = 1;
1280 
1281 		/*
1282 		 * Calculate sleep duration.  The configuration is
1283 		 * given in ms.  We insure a multiple of the beacon
1284 		 * period is used.  Also, if the sleep duration is
1285 		 * greater than the DTIM period then it makes senses
1286 		 * to make it a multiple of that.
1287 		 *
1288 		 * XXX fixed at 100ms
1289 		 */
1290 		bs.bs_sleepduration =
1291 			roundup((100 * 1000) / 1024, bs.bs_intval);
1292 		if (bs.bs_sleepduration > bs.bs_dtimperiod)
1293 			bs.bs_sleepduration = roundup(bs.bs_sleepduration, bs.bs_dtimperiod);
1294 
1295 		DPRINTF(("%s: intval %u nexttbtt %u dtim %u nextdtim %u bmiss %u sleep %u\n"
1296 			, __func__
1297 			, bs.bs_intval
1298 			, bs.bs_nexttbtt
1299 			, bs.bs_dtimperiod
1300 			, bs.bs_nextdtim
1301 			, bs.bs_bmissthreshold
1302 			, bs.bs_sleepduration
1303 		));
1304 		ath_hal_intrset(ah, 0);
1305 		/*
1306 		 * Reset our tsf so the hardware will update the
1307 		 * tsf register to reflect timestamps found in
1308 		 * received beacons.
1309 		 */
1310 		ath_hal_resettsf(ah);
1311 		ath_hal_beacontimers(ah, &bs, 0/*XXX*/, 0, 0);
1312 		sc->sc_imask |= HAL_INT_BMISS;
1313 		ath_hal_intrset(ah, sc->sc_imask);
1314 	} else {
1315 		DPRINTF(("%s: intval %u nexttbtt %u\n",
1316 			__func__, ni->ni_intval, nexttbtt));
1317 		ath_hal_intrset(ah, 0);
1318 		ath_hal_beaconinit(ah, ic->ic_opmode,
1319 			nexttbtt, ni->ni_intval);
1320 		if (ic->ic_opmode != IEEE80211_M_MONITOR)
1321 			sc->sc_imask |= HAL_INT_SWBA;	/* beacon prepare */
1322 		ath_hal_intrset(ah, sc->sc_imask);
1323 	}
1324 }
1325 
1326 static void
1327 ath_load_cb(void *arg, bus_dma_segment_t *segs, int nsegs, int error)
1328 {
1329 	bus_addr_t *paddr = (bus_addr_t*) arg;
1330 	*paddr = segs->ds_addr;
1331 }
1332 
1333 static int
1334 ath_desc_alloc(struct ath_softc *sc)
1335 {
1336 	int i, bsize, error;
1337 	struct ath_desc *ds;
1338 	struct ath_buf *bf;
1339 
1340 	/* allocate descriptors */
1341 	sc->sc_desc_len = sizeof(struct ath_desc) *
1342 				(ATH_TXBUF * ATH_TXDESC + ATH_RXBUF + 1);
1343 	error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT, &sc->sc_ddmamap);
1344 	if (error != 0)
1345 		return error;
1346 
1347 	error = bus_dmamem_alloc(sc->sc_dmat, (void**) &sc->sc_desc,
1348 				 BUS_DMA_NOWAIT, &sc->sc_ddmamap);
1349 	if (error != 0)
1350 		goto fail0;
1351 
1352 	error = bus_dmamap_load(sc->sc_dmat, sc->sc_ddmamap,
1353 				sc->sc_desc, sc->sc_desc_len,
1354 				ath_load_cb, &sc->sc_desc_paddr,
1355 				BUS_DMA_NOWAIT);
1356 	if (error != 0)
1357 		goto fail1;
1358 
1359 	ds = sc->sc_desc;
1360 	DPRINTF(("ath_desc_alloc: DMA map: %p (%d) -> %p (%lu)\n",
1361 	    ds, sc->sc_desc_len,
1362 	    (caddr_t) sc->sc_desc_paddr, /*XXX*/ (u_long) sc->sc_desc_len));
1363 
1364 	/* allocate buffers */
1365 	bsize = sizeof(struct ath_buf) * (ATH_TXBUF + ATH_RXBUF + 1);
1366 	bf = malloc(bsize, M_DEVBUF, M_NOWAIT | M_ZERO);
1367 	if (bf == NULL)
1368 		goto fail2;
1369 	sc->sc_bufptr = bf;
1370 
1371 	TAILQ_INIT(&sc->sc_rxbuf);
1372 	for (i = 0; i < ATH_RXBUF; i++, bf++, ds++) {
1373 		bf->bf_desc = ds;
1374 		bf->bf_daddr = sc->sc_desc_paddr +
1375 		    ((caddr_t)ds - (caddr_t)sc->sc_desc);
1376 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
1377 					  &bf->bf_dmamap);
1378 		if (error != 0)
1379 			break;
1380 		TAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
1381 	}
1382 
1383 	TAILQ_INIT(&sc->sc_txbuf);
1384 	for (i = 0; i < ATH_TXBUF; i++, bf++, ds += ATH_TXDESC) {
1385 		bf->bf_desc = ds;
1386 		bf->bf_daddr = sc->sc_desc_paddr +
1387 		    ((caddr_t)ds - (caddr_t)sc->sc_desc);
1388 		error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT,
1389 					  &bf->bf_dmamap);
1390 		if (error != 0)
1391 			break;
1392 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
1393 	}
1394 	TAILQ_INIT(&sc->sc_txq);
1395 
1396 	/* beacon buffer */
1397 	bf->bf_desc = ds;
1398 	bf->bf_daddr = sc->sc_desc_paddr + ((caddr_t)ds - (caddr_t)sc->sc_desc);
1399 	error = bus_dmamap_create(sc->sc_dmat, BUS_DMA_NOWAIT, &bf->bf_dmamap);
1400 	if (error != 0)
1401 		return error;
1402 	sc->sc_bcbuf = bf;
1403 	return 0;
1404 
1405 fail2:
1406 	bus_dmamap_unload(sc->sc_dmat, sc->sc_ddmamap);
1407 fail1:
1408 	bus_dmamem_free(sc->sc_dmat, sc->sc_desc, sc->sc_ddmamap);
1409 fail0:
1410 	bus_dmamap_destroy(sc->sc_dmat, sc->sc_ddmamap);
1411 	sc->sc_ddmamap = NULL;
1412 	return error;
1413 }
1414 
1415 static void
1416 ath_desc_free(struct ath_softc *sc)
1417 {
1418 	struct ath_buf *bf;
1419 
1420 	bus_dmamap_unload(sc->sc_dmat, sc->sc_ddmamap);
1421 	bus_dmamem_free(sc->sc_dmat, sc->sc_desc, sc->sc_ddmamap);
1422 	bus_dmamap_destroy(sc->sc_dmat, sc->sc_ddmamap);
1423 
1424 	TAILQ_FOREACH(bf, &sc->sc_txq, bf_list) {
1425 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
1426 		bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
1427 		m_freem(bf->bf_m);
1428 	}
1429 	TAILQ_FOREACH(bf, &sc->sc_txbuf, bf_list)
1430 		bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
1431 	TAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
1432 		if (bf->bf_m) {
1433 			bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
1434 			bus_dmamap_destroy(sc->sc_dmat, bf->bf_dmamap);
1435 			m_freem(bf->bf_m);
1436 			bf->bf_m = NULL;
1437 		}
1438 	}
1439 	if (sc->sc_bcbuf != NULL) {
1440 		bus_dmamap_unload(sc->sc_dmat, sc->sc_bcbuf->bf_dmamap);
1441 		bus_dmamap_destroy(sc->sc_dmat, sc->sc_bcbuf->bf_dmamap);
1442 		sc->sc_bcbuf = NULL;
1443 	}
1444 
1445 	TAILQ_INIT(&sc->sc_rxbuf);
1446 	TAILQ_INIT(&sc->sc_txbuf);
1447 	TAILQ_INIT(&sc->sc_txq);
1448 	free(sc->sc_bufptr, M_DEVBUF);
1449 	sc->sc_bufptr = NULL;
1450 }
1451 
1452 static struct ieee80211_node *
1453 ath_node_alloc(struct ieee80211com *ic)
1454 {
1455 	struct ath_node *an =
1456 		malloc(sizeof(struct ath_node), M_DEVBUF, M_NOWAIT | M_ZERO);
1457 	if (an) {
1458 		int i;
1459 		for (i = 0; i < ATH_RHIST_SIZE; i++)
1460 			an->an_rx_hist[i].arh_ticks = ATH_RHIST_NOTIME;
1461 		an->an_rx_hist_next = ATH_RHIST_SIZE-1;
1462 		return &an->an_node;
1463 	} else
1464 		return NULL;
1465 }
1466 
1467 static void
1468 ath_node_free(struct ieee80211com *ic, struct ieee80211_node *ni)
1469 {
1470         struct ath_softc *sc = ic->ic_if.if_softc;
1471 	struct ath_buf *bf;
1472 
1473 	TAILQ_FOREACH(bf, &sc->sc_txq, bf_list) {
1474 		if (bf->bf_node == ni)
1475 			bf->bf_node = NULL;
1476 	}
1477 	free(ni, M_DEVBUF);
1478 }
1479 
1480 static void
1481 ath_node_copy(struct ieee80211com *ic,
1482 	struct ieee80211_node *dst, const struct ieee80211_node *src)
1483 {
1484 	*(struct ath_node *)dst = *(const struct ath_node *)src;
1485 }
1486 
1487 
1488 static u_int8_t
1489 ath_node_getrssi(struct ieee80211com *ic, struct ieee80211_node *ni)
1490 {
1491 	struct ath_node *an = ATH_NODE(ni);
1492 	int i, now, nsamples, rssi;
1493 
1494 	/*
1495 	 * Calculate the average over the last second of sampled data.
1496 	 */
1497 	now = ticks;
1498 	nsamples = 0;
1499 	rssi = 0;
1500 	i = an->an_rx_hist_next;
1501 	do {
1502 		struct ath_recv_hist *rh = &an->an_rx_hist[i];
1503 		if (rh->arh_ticks == ATH_RHIST_NOTIME)
1504 			goto done;
1505 		if (now - rh->arh_ticks > hz)
1506 			goto done;
1507 		rssi += rh->arh_rssi;
1508 		nsamples++;
1509 		if (i == 0)
1510 			i = ATH_RHIST_SIZE-1;
1511 		else
1512 			i--;
1513 	} while (i != an->an_rx_hist_next);
1514 done:
1515 	/*
1516 	 * Return either the average or the last known
1517 	 * value if there is no recent data.
1518 	 */
1519 	return (nsamples ? rssi / nsamples : an->an_rx_hist[i].arh_rssi);
1520 }
1521 
1522 static int
1523 ath_rxbuf_init(struct ath_softc *sc, struct ath_buf *bf)
1524 {
1525 	struct ath_hal *ah = sc->sc_ah;
1526 	int error;
1527 	struct mbuf *m;
1528 	struct ath_desc *ds;
1529 
1530 	m = bf->bf_m;
1531 	if (m == NULL) {
1532 		/*
1533 		 * NB: by assigning a page to the rx dma buffer we
1534 		 * implicitly satisfy the Atheros requirement that
1535 		 * this buffer be cache-line-aligned and sized to be
1536 		 * multiple of the cache line size.  Not doing this
1537 		 * causes weird stuff to happen (for the 5210 at least).
1538 		 */
1539 		m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1540 		if (m == NULL) {
1541 			DPRINTF(("ath_rxbuf_init: no mbuf/cluster\n"));
1542 			sc->sc_stats.ast_rx_nombuf++;
1543 			return ENOMEM;
1544 		}
1545 		bf->bf_m = m;
1546 		m->m_pkthdr.len = m->m_len = m->m_ext.ext_size;
1547 
1548 		error = bus_dmamap_load_mbuf(sc->sc_dmat, bf->bf_dmamap, m,
1549 					     ath_mbuf_load_cb, bf,
1550 					     BUS_DMA_NOWAIT);
1551 		if (error != 0) {
1552 			DPRINTF(("ath_rxbuf_init: bus_dmamap_load_mbuf failed;"
1553 				" error %d\n", error));
1554 			sc->sc_stats.ast_rx_busdma++;
1555 			return error;
1556 		}
1557 		KASSERT(bf->bf_nseg == 1,
1558 			("ath_rxbuf_init: multi-segment packet; nseg %u",
1559 			bf->bf_nseg));
1560 	}
1561 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREREAD);
1562 
1563 	/*
1564 	 * Setup descriptors.  For receive we always terminate
1565 	 * the descriptor list with a self-linked entry so we'll
1566 	 * not get overrun under high load (as can happen with a
1567 	 * 5212 when ANI processing enables PHY errors).
1568 	 *
1569 	 * To insure the last descriptor is self-linked we create
1570 	 * each descriptor as self-linked and add it to the end.  As
1571 	 * each additional descriptor is added the previous self-linked
1572 	 * entry is ``fixed'' naturally.  This should be safe even
1573 	 * if DMA is happening.  When processing RX interrupts we
1574 	 * never remove/process the last, self-linked, entry on the
1575 	 * descriptor list.  This insures the hardware always has
1576 	 * someplace to write a new frame.
1577 	 */
1578 	ds = bf->bf_desc;
1579 	ds->ds_link = bf->bf_daddr;	/* link to self */
1580 	ds->ds_data = bf->bf_segs[0].ds_addr;
1581 	ath_hal_setuprxdesc(ah, ds
1582 		, m->m_len		/* buffer size */
1583 		, 0
1584 	);
1585 
1586 	if (sc->sc_rxlink != NULL)
1587 		*sc->sc_rxlink = bf->bf_daddr;
1588 	sc->sc_rxlink = &ds->ds_link;
1589 	return 0;
1590 }
1591 
1592 static void
1593 ath_rx_proc(void *arg, int npending)
1594 {
1595 	struct ath_softc *sc = arg;
1596 	struct ath_buf *bf;
1597 	struct ieee80211com *ic = &sc->sc_ic;
1598 	struct ifnet *ifp = &ic->ic_if;
1599 	struct ath_hal *ah = sc->sc_ah;
1600 	struct ath_desc *ds;
1601 	struct mbuf *m;
1602 	struct ieee80211_frame *wh, whbuf;
1603 	struct ieee80211_node *ni;
1604 	struct ath_node *an;
1605 	struct ath_recv_hist *rh;
1606 	int len;
1607 	u_int phyerr;
1608 	HAL_STATUS status;
1609 
1610 	DPRINTF2(("ath_rx_proc: pending %u\n", npending));
1611 	do {
1612 		bf = TAILQ_FIRST(&sc->sc_rxbuf);
1613 		if (bf == NULL) {		/* NB: shouldn't happen */
1614 			if_printf(ifp, "ath_rx_proc: no buffer!\n");
1615 			break;
1616 		}
1617 		ds = bf->bf_desc;
1618 		if (ds->ds_link == bf->bf_daddr) {
1619 			/* NB: never process the self-linked entry at the end */
1620 			break;
1621 		}
1622 		m = bf->bf_m;
1623 		if (m == NULL) {		/* NB: shouldn't happen */
1624 			if_printf(ifp, "ath_rx_proc: no mbuf!\n");
1625 			continue;
1626 		}
1627 		status = ath_hal_rxprocdesc(ah, ds);
1628 #ifdef AR_DEBUG
1629 		if (ath_debug > 1)
1630 			ath_printrxbuf(bf, status == HAL_OK);
1631 #endif
1632 		if (status == HAL_EINPROGRESS)
1633 			break;
1634 		TAILQ_REMOVE(&sc->sc_rxbuf, bf, bf_list);
1635 		if (ds->ds_rxstat.rs_status != 0) {
1636 			ifp->if_ierrors++;
1637 			if (ds->ds_rxstat.rs_status & HAL_RXERR_CRC)
1638 				sc->sc_stats.ast_rx_crcerr++;
1639 			if (ds->ds_rxstat.rs_status & HAL_RXERR_FIFO)
1640 				sc->sc_stats.ast_rx_fifoerr++;
1641 			if (ds->ds_rxstat.rs_status & HAL_RXERR_DECRYPT)
1642 				sc->sc_stats.ast_rx_badcrypt++;
1643 			if (ds->ds_rxstat.rs_status & HAL_RXERR_PHY) {
1644 				sc->sc_stats.ast_rx_phyerr++;
1645 				phyerr = ds->ds_rxstat.rs_phyerr & 0x1f;
1646 				sc->sc_stats.ast_rx_phy[phyerr]++;
1647 			}
1648 			goto rx_next;
1649 		}
1650 
1651 		len = ds->ds_rxstat.rs_datalen;
1652 		if (len < IEEE80211_MIN_LEN) {
1653 			DPRINTF(("ath_rx_proc: short packet %d\n", len));
1654 			sc->sc_stats.ast_rx_tooshort++;
1655 			goto rx_next;
1656 		}
1657 
1658 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
1659 		    BUS_DMASYNC_POSTREAD);
1660 
1661 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
1662 		bf->bf_m = NULL;
1663 		m->m_pkthdr.rcvif = ifp;
1664 		m->m_pkthdr.len = m->m_len = len;
1665 
1666 		if (sc->sc_drvbpf) {
1667 			struct mbuf *mb;
1668 
1669 			/* XXX pre-allocate space when setting up recv's */
1670 			MGETHDR(mb, M_DONTWAIT, m->m_type);
1671 			if (mb != NULL) {
1672 				sc->sc_rx_th.wr_rate =
1673 					sc->sc_hwmap[ds->ds_rxstat.rs_rate];
1674 				sc->sc_rx_th.wr_antsignal =
1675 					ds->ds_rxstat.rs_rssi;
1676 				sc->sc_rx_th.wr_antenna =
1677 					ds->ds_rxstat.rs_antenna;
1678 				/* XXX TSF */
1679 
1680 				(void) m_dup_pkthdr(mb, m, M_DONTWAIT);
1681 				mb->m_next = m;
1682 				mb->m_data = (caddr_t)&sc->sc_rx_th;
1683 				mb->m_len = sizeof(sc->sc_rx_th);
1684 				mb->m_pkthdr.len += mb->m_len;
1685 				bpf_mtap(sc->sc_drvbpf, mb);
1686 				m_free(mb);
1687 			}
1688 		}
1689 
1690 		m_adj(m, -IEEE80211_CRC_LEN);
1691 		wh = mtod(m, struct ieee80211_frame *);
1692 		if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1693 			/*
1694 			 * WEP is decrypted by hardware. Clear WEP bit
1695 			 * and trim WEP header for ieee80211_input().
1696 			 */
1697 			wh->i_fc[1] &= ~IEEE80211_FC1_WEP;
1698 			memcpy(&whbuf, wh, sizeof(whbuf));
1699 			m_adj(m, IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN);
1700 			memcpy(mtod(m, caddr_t), &whbuf, sizeof(whbuf));
1701 			/*
1702 			 * Also trim WEP ICV from the tail.
1703 			 */
1704 			m_adj(m, -IEEE80211_WEP_CRCLEN);
1705 		}
1706 
1707 		/*
1708 		 * Locate the node for sender, track state, and
1709 		 * then pass this node (referenced) up to the 802.11
1710 		 * layer for its use.  We are required to pass
1711 		 * something so we fall back to ic_bss when this frame
1712 		 * is from an unknown sender.
1713 		 */
1714 		if (ic->ic_opmode != IEEE80211_M_STA) {
1715 			ni = ieee80211_find_node(ic, wh->i_addr2);
1716 			if (ni == NULL)
1717 				ni = ieee80211_ref_node(ic->ic_bss);
1718 		} else
1719 			ni = ieee80211_ref_node(ic->ic_bss);
1720 
1721 		/*
1722 		 * Record driver-specific state.
1723 		 */
1724 		an = ATH_NODE(ni);
1725 		if (++(an->an_rx_hist_next) == ATH_RHIST_SIZE)
1726 			an->an_rx_hist_next = 0;
1727 		rh = &an->an_rx_hist[an->an_rx_hist_next];
1728 		rh->arh_ticks = ticks;
1729 		rh->arh_rssi = ds->ds_rxstat.rs_rssi;
1730 		rh->arh_antenna = ds->ds_rxstat.rs_antenna;
1731 
1732 		/*
1733 		 * Send frame up for processing.
1734 		 */
1735 		ieee80211_input(ifp, m, ni,
1736 			ds->ds_rxstat.rs_rssi, ds->ds_rxstat.rs_tstamp);
1737 
1738 		/*
1739 		 * The frame may have caused the node to be marked for
1740 		 * reclamation (e.g. in response to a DEAUTH message)
1741 		 * so use free_node here instead of unref_node.
1742 		 */
1743 		if (ni == ic->ic_bss)
1744 			ieee80211_unref_node(&ni);
1745 		else
1746 			ieee80211_free_node(ic, ni);
1747   rx_next:
1748 		TAILQ_INSERT_TAIL(&sc->sc_rxbuf, bf, bf_list);
1749 	} while (ath_rxbuf_init(sc, bf) == 0);
1750 
1751 	ath_hal_rxmonitor(ah);			/* rx signal state monitoring */
1752 	ath_hal_rxena(ah);			/* in case of RXEOL */
1753 }
1754 
1755 /*
1756  * XXX Size of an ACK control frame in bytes.
1757  */
1758 #define	IEEE80211_ACK_SIZE	(2+2+IEEE80211_ADDR_LEN+4)
1759 
1760 static int
1761 ath_tx_start(struct ath_softc *sc, struct ieee80211_node *ni, struct ath_buf *bf,
1762     struct mbuf *m0)
1763 {
1764 	struct ieee80211com *ic = &sc->sc_ic;
1765 	struct ath_hal *ah = sc->sc_ah;
1766 	struct ifnet *ifp = &sc->sc_ic.ic_if;
1767 	int i, error, iswep, hdrlen, pktlen;
1768 	u_int8_t rix, cix, txrate, ctsrate;
1769 	struct ath_desc *ds;
1770 	struct mbuf *m;
1771 	struct ieee80211_frame *wh;
1772 	u_int32_t iv;
1773 	u_int8_t *ivp;
1774 	u_int8_t hdrbuf[sizeof(struct ieee80211_frame) +
1775 	    IEEE80211_WEP_IVLEN + IEEE80211_WEP_KIDLEN];
1776 	u_int subtype, flags, ctsduration, antenna;
1777 	HAL_PKT_TYPE atype;
1778 	const HAL_RATE_TABLE *rt;
1779 	HAL_BOOL shortPreamble;
1780 	struct ath_node *an;
1781 
1782 	wh = mtod(m0, struct ieee80211_frame *);
1783 	iswep = wh->i_fc[1] & IEEE80211_FC1_WEP;
1784 	hdrlen = sizeof(struct ieee80211_frame);
1785 	pktlen = m0->m_pkthdr.len;
1786 
1787 	if (iswep) {
1788 		memcpy(hdrbuf, mtod(m0, caddr_t), hdrlen);
1789 		m_adj(m0, hdrlen);
1790 		M_PREPEND(m0, sizeof(hdrbuf), M_DONTWAIT);
1791 		if (m0 == NULL) {
1792 			sc->sc_stats.ast_tx_nombuf++;
1793 			return ENOMEM;
1794 		}
1795 		ivp = hdrbuf + hdrlen;
1796 		wh = mtod(m0, struct ieee80211_frame *);
1797 		/*
1798 		 * XXX
1799 		 * IV must not duplicate during the lifetime of the key.
1800 		 * But no mechanism to renew keys is defined in IEEE 802.11
1801 		 * WEP.  And IV may be duplicated between other stations
1802 		 * because of the session key itself is shared.
1803 		 * So we use pseudo random IV for now, though it is not the
1804 		 * right way.
1805 		 */
1806                 iv = ic->ic_iv;
1807 		/*
1808 		 * Skip 'bad' IVs from Fluhrer/Mantin/Shamir:
1809 		 * (B, 255, N) with 3 <= B < 8
1810 		 */
1811 		if (iv >= 0x03ff00 && (iv & 0xf8ff00) == 0x00ff00)
1812 			iv += 0x000100;
1813 		ic->ic_iv = iv + 1;
1814 		for (i = 0; i < IEEE80211_WEP_IVLEN; i++) {
1815 			ivp[i] = iv;
1816 			iv >>= 8;
1817 		}
1818 		ivp[i] = sc->sc_ic.ic_wep_txkey << 6;	/* Key ID and pad */
1819 		memcpy(mtod(m0, caddr_t), hdrbuf, sizeof(hdrbuf));
1820 		/*
1821 		 * The ICV length must be included into hdrlen and pktlen.
1822 		 */
1823 		hdrlen = sizeof(hdrbuf) + IEEE80211_WEP_CRCLEN;
1824 		pktlen = m0->m_pkthdr.len + IEEE80211_WEP_CRCLEN;
1825 	}
1826 	pktlen += IEEE80211_CRC_LEN;
1827 
1828 	/*
1829 	 * Load the DMA map so any coalescing is done.  This
1830 	 * also calculates the number of descriptors we need.
1831 	 */
1832 	error = bus_dmamap_load_mbuf(sc->sc_dmat, bf->bf_dmamap, m0,
1833 				     ath_mbuf_load_cb, bf,
1834 				     BUS_DMA_NOWAIT);
1835 	if (error == EFBIG) {
1836 		/* XXX packet requires too many descriptors */
1837 		bf->bf_nseg = ATH_TXDESC+1;
1838 	} else if (error != 0) {
1839 		sc->sc_stats.ast_tx_busdma++;
1840 		m_freem(m0);
1841 		return error;
1842 	}
1843 	/*
1844 	 * Discard null packets and check for packets that
1845 	 * require too many TX descriptors.  We try to convert
1846 	 * the latter to a cluster.
1847 	 */
1848 	if (bf->bf_nseg > ATH_TXDESC) {		/* too many desc's, linearize */
1849 		sc->sc_stats.ast_tx_linear++;
1850 		MGETHDR(m, M_DONTWAIT, MT_DATA);
1851 		if (m == NULL) {
1852 			sc->sc_stats.ast_tx_nombuf++;
1853 			m_freem(m0);
1854 			return ENOMEM;
1855 		}
1856 		M_MOVE_PKTHDR(m, m0);
1857 		MCLGET(m, M_DONTWAIT);
1858 		if ((m->m_flags & M_EXT) == 0) {
1859 			sc->sc_stats.ast_tx_nomcl++;
1860 			m_freem(m0);
1861 			m_free(m);
1862 			return ENOMEM;
1863 		}
1864 		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(m, caddr_t));
1865 		m_freem(m0);
1866 		m->m_len = m->m_pkthdr.len;
1867 		m0 = m;
1868 		error = bus_dmamap_load_mbuf(sc->sc_dmat, bf->bf_dmamap, m0,
1869 					     ath_mbuf_load_cb, bf,
1870 					     BUS_DMA_NOWAIT);
1871 		if (error != 0) {
1872 			sc->sc_stats.ast_tx_busdma++;
1873 			m_freem(m0);
1874 			return error;
1875 		}
1876 		KASSERT(bf->bf_nseg == 1,
1877 			("ath_tx_start: packet not one segment; nseg %u",
1878 			bf->bf_nseg));
1879 	} else if (bf->bf_nseg == 0) {		/* null packet, discard */
1880 		sc->sc_stats.ast_tx_nodata++;
1881 		m_freem(m0);
1882 		return EIO;
1883 	}
1884 	DPRINTF2(("ath_tx_start: m %p len %u\n", m0, pktlen));
1885 	bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap, BUS_DMASYNC_PREWRITE);
1886 	bf->bf_m = m0;
1887 	bf->bf_node = ni;			/* NB: held reference */
1888 
1889 	/* setup descriptors */
1890 	ds = bf->bf_desc;
1891 	rt = sc->sc_currates;
1892 	KASSERT(rt != NULL, ("no rate table, mode %u", sc->sc_curmode));
1893 
1894 	/*
1895 	 * Calculate Atheros packet type from IEEE80211 packet header
1896 	 * and setup for rate calculations.
1897 	 */
1898 	atype = HAL_PKT_TYPE_NORMAL;			/* default */
1899 	switch (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) {
1900 	case IEEE80211_FC0_TYPE_MGT:
1901 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1902 		if (subtype == IEEE80211_FC0_SUBTYPE_BEACON)
1903 			atype = HAL_PKT_TYPE_BEACON;
1904 		else if (subtype == IEEE80211_FC0_SUBTYPE_PROBE_RESP)
1905 			atype = HAL_PKT_TYPE_PROBE_RESP;
1906 		else if (subtype == IEEE80211_FC0_SUBTYPE_ATIM)
1907 			atype = HAL_PKT_TYPE_ATIM;
1908 		rix = 0;			/* XXX lowest rate */
1909 		break;
1910 	case IEEE80211_FC0_TYPE_CTL:
1911 		subtype = wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_MASK;
1912 		if (subtype == IEEE80211_FC0_SUBTYPE_PS_POLL)
1913 			atype = HAL_PKT_TYPE_PSPOLL;
1914 		rix = 0;			/* XXX lowest rate */
1915 		break;
1916 	default:
1917 		rix = sc->sc_rixmap[ni->ni_rates.rs_rates[ni->ni_txrate] &
1918 				IEEE80211_RATE_VAL];
1919 		if (rix == 0xff) {
1920 			if_printf(ifp, "bogus xmit rate 0x%x\n",
1921 				ni->ni_rates.rs_rates[ni->ni_txrate]);
1922 			sc->sc_stats.ast_tx_badrate++;
1923 			m_freem(m0);
1924 			return EIO;
1925 		}
1926 		break;
1927 	}
1928 	/*
1929 	 * NB: the 802.11 layer marks whether or not we should
1930 	 * use short preamble based on the current mode and
1931 	 * negotiated parameters.
1932 	 */
1933 	if ((ic->ic_flags & IEEE80211_F_SHPREAMBLE) &&
1934 	    (ni->ni_capinfo & IEEE80211_CAPINFO_SHORT_PREAMBLE)) {
1935 		txrate = rt->info[rix].rateCode | rt->info[rix].shortPreamble;
1936 		shortPreamble = AH_TRUE;
1937 		sc->sc_stats.ast_tx_shortpre++;
1938 	} else {
1939 		txrate = rt->info[rix].rateCode;
1940 		shortPreamble = AH_FALSE;
1941 	}
1942 
1943 	/*
1944 	 * Calculate miscellaneous flags.
1945 	 */
1946 	flags = HAL_TXDESC_CLRDMASK;		/* XXX needed for wep errors */
1947 	if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1948 		flags |= HAL_TXDESC_NOACK;	/* no ack on broad/multicast */
1949 		sc->sc_stats.ast_tx_noack++;
1950 	} else if (pktlen > ic->ic_rtsthreshold) {
1951 		flags |= HAL_TXDESC_RTSENA;	/* RTS based on frame length */
1952 		sc->sc_stats.ast_tx_rts++;
1953 	}
1954 
1955 	/*
1956 	 * Calculate duration.  This logically belongs in the 802.11
1957 	 * layer but it lacks sufficient information to calculate it.
1958 	 */
1959 	if ((flags & HAL_TXDESC_NOACK) == 0 &&
1960 	    (wh->i_fc[0] & IEEE80211_FC0_TYPE_MASK) != IEEE80211_FC0_TYPE_CTL) {
1961 		u_int16_t dur;
1962 		/*
1963 		 * XXX not right with fragmentation.
1964 		 */
1965 		dur = ath_hal_computetxtime(ah, rt, IEEE80211_ACK_SIZE,
1966 				rix, shortPreamble);
1967 		*((u_int16_t*) wh->i_dur) = htole16(dur);
1968 	}
1969 
1970 	/*
1971 	 * Calculate RTS/CTS rate and duration if needed.
1972 	 */
1973 	ctsduration = 0;
1974 	if (flags & (HAL_TXDESC_RTSENA|HAL_TXDESC_CTSENA)) {
1975 		/*
1976 		 * CTS transmit rate is derived from the transmit rate
1977 		 * by looking in the h/w rate table.  We must also factor
1978 		 * in whether or not a short preamble is to be used.
1979 		 */
1980 		cix = rt->info[rix].controlRate;
1981 		ctsrate = rt->info[cix].rateCode;
1982 		if (shortPreamble)
1983 			ctsrate |= rt->info[cix].shortPreamble;
1984 		/*
1985 		 * Compute the transmit duration based on the size
1986 		 * of an ACK frame.  We call into the HAL to do the
1987 		 * computation since it depends on the characteristics
1988 		 * of the actual PHY being used.
1989 		 */
1990 		if (flags & HAL_TXDESC_RTSENA) {	/* SIFS + CTS */
1991 			ctsduration += ath_hal_computetxtime(ah,
1992 				rt, IEEE80211_ACK_SIZE, cix, shortPreamble);
1993 		}
1994 		/* SIFS + data */
1995 		ctsduration += ath_hal_computetxtime(ah,
1996 			rt, pktlen, rix, shortPreamble);
1997 		if ((flags & HAL_TXDESC_NOACK) == 0) {	/* SIFS + ACK */
1998 			ctsduration += ath_hal_computetxtime(ah,
1999 				rt, IEEE80211_ACK_SIZE, cix, shortPreamble);
2000 		}
2001 	} else
2002 		ctsrate = 0;
2003 
2004 	/*
2005 	 * For now use the antenna on which the last good
2006 	 * frame was received on.  We assume this field is
2007 	 * initialized to 0 which gives us ``auto'' or the
2008 	 * ``default'' antenna.
2009 	 */
2010 	an = (struct ath_node *) ni;
2011 	if (an->an_tx_antenna)
2012 		antenna = an->an_tx_antenna;
2013 	else
2014 		antenna = an->an_rx_hist[an->an_rx_hist_next].arh_antenna;
2015 
2016 	/*
2017 	 * Formulate first tx descriptor with tx controls.
2018 	 */
2019 	/* XXX check return value? */
2020 	ath_hal_setuptxdesc(ah, ds
2021 		, pktlen		/* packet length */
2022 		, hdrlen		/* header length */
2023 		, atype			/* Atheros packet type */
2024 		, 60			/* txpower XXX */
2025 		, txrate, 1+10		/* series 0 rate/tries */
2026 		, iswep ? sc->sc_ic.ic_wep_txkey : HAL_TXKEYIX_INVALID
2027 		, antenna		/* antenna mode */
2028 		, flags			/* flags */
2029 		, ctsrate		/* rts/cts rate */
2030 		, ctsduration		/* rts/cts duration */
2031 	);
2032 #ifdef notyet
2033 	ath_hal_setupxtxdesc(ah, ds
2034 		, AH_FALSE		/* short preamble */
2035 		, 0, 0			/* series 1 rate/tries */
2036 		, 0, 0			/* series 2 rate/tries */
2037 		, 0, 0			/* series 3 rate/tries */
2038 	);
2039 #endif
2040 	/*
2041 	 * Fillin the remainder of the descriptor info.
2042 	 */
2043 	for (i = 0; i < bf->bf_nseg; i++, ds++) {
2044 		ds->ds_data = bf->bf_segs[i].ds_addr;
2045 		if (i == bf->bf_nseg - 1)
2046 			ds->ds_link = 0;
2047 		else
2048 			ds->ds_link = bf->bf_daddr + sizeof(*ds) * (i + 1);
2049 		ath_hal_filltxdesc(ah, ds
2050 			, bf->bf_segs[i].ds_len	/* segment length */
2051 			, i == 0		/* first segment */
2052 			, i == bf->bf_nseg - 1	/* last segment */
2053 		);
2054 		DPRINTF2(("ath_tx_start: %d: %08x %08x %08x %08x %08x %08x\n",
2055 		    i, ds->ds_link, ds->ds_data, ds->ds_ctl0, ds->ds_ctl1,
2056 		    ds->ds_hw[0], ds->ds_hw[1]));
2057 	}
2058 
2059 	/*
2060 	 * Insert the frame on the outbound list and
2061 	 * pass it on to the hardware.
2062 	 */
2063 	ATH_TXQ_LOCK(sc);
2064 	TAILQ_INSERT_TAIL(&sc->sc_txq, bf, bf_list);
2065 	if (sc->sc_txlink == NULL) {
2066 		ath_hal_puttxbuf(ah, sc->sc_txhalq, bf->bf_daddr);
2067 		DPRINTF2(("ath_tx_start: TXDP0 = %p (%p)\n",
2068 		    (caddr_t)bf->bf_daddr, bf->bf_desc));
2069 	} else {
2070 		*sc->sc_txlink = bf->bf_daddr;
2071 		DPRINTF2(("ath_tx_start: link(%p)=%p (%p)\n",
2072 		    sc->sc_txlink, (caddr_t)bf->bf_daddr, bf->bf_desc));
2073 	}
2074 	sc->sc_txlink = &bf->bf_desc[bf->bf_nseg - 1].ds_link;
2075 	ATH_TXQ_UNLOCK(sc);
2076 
2077 	ath_hal_txstart(ah, sc->sc_txhalq);
2078 	return 0;
2079 }
2080 
2081 static void
2082 ath_tx_proc(void *arg, int npending)
2083 {
2084 	struct ath_softc *sc = arg;
2085 	struct ath_hal *ah = sc->sc_ah;
2086 	struct ath_buf *bf;
2087 	struct ieee80211com *ic = &sc->sc_ic;
2088 	struct ifnet *ifp = &ic->ic_if;
2089 	struct ath_desc *ds;
2090 	struct ieee80211_node *ni;
2091 	struct ath_node *an;
2092 	int sr, lr;
2093 	HAL_STATUS status;
2094 
2095 	DPRINTF2(("ath_tx_proc: pending %u tx queue %p, link %p\n",
2096 		npending, (caddr_t) ath_hal_gettxbuf(sc->sc_ah, sc->sc_txhalq),
2097 		sc->sc_txlink));
2098 	for (;;) {
2099 		ATH_TXQ_LOCK(sc);
2100 		bf = TAILQ_FIRST(&sc->sc_txq);
2101 		if (bf == NULL) {
2102 			sc->sc_txlink = NULL;
2103 			ATH_TXQ_UNLOCK(sc);
2104 			break;
2105 		}
2106 		/* only the last descriptor is needed */
2107 		ds = &bf->bf_desc[bf->bf_nseg - 1];
2108 		status = ath_hal_txprocdesc(ah, ds);
2109 #ifdef AR_DEBUG
2110 		if (ath_debug > 1)
2111 			ath_printtxbuf(bf, status == HAL_OK);
2112 #endif
2113 		if (status == HAL_EINPROGRESS) {
2114 			ATH_TXQ_UNLOCK(sc);
2115 			break;
2116 		}
2117 		TAILQ_REMOVE(&sc->sc_txq, bf, bf_list);
2118 		ATH_TXQ_UNLOCK(sc);
2119 
2120 		ni = bf->bf_node;
2121 		if (ni != NULL) {
2122 			an = (struct ath_node *) ni;
2123 			if (ds->ds_txstat.ts_status == 0) {
2124 				an->an_tx_ok++;
2125 				an->an_tx_antenna = ds->ds_txstat.ts_antenna;
2126 			} else {
2127 				an->an_tx_err++;
2128 				ifp->if_oerrors++;
2129 				if (ds->ds_txstat.ts_status & HAL_TXERR_XRETRY)
2130 					sc->sc_stats.ast_tx_xretries++;
2131 				if (ds->ds_txstat.ts_status & HAL_TXERR_FIFO)
2132 					sc->sc_stats.ast_tx_fifoerr++;
2133 				if (ds->ds_txstat.ts_status & HAL_TXERR_FILT)
2134 					sc->sc_stats.ast_tx_filtered++;
2135 				an->an_tx_antenna = 0;	/* invalidate */
2136 			}
2137 			sr = ds->ds_txstat.ts_shortretry;
2138 			lr = ds->ds_txstat.ts_longretry;
2139 			sc->sc_stats.ast_tx_shortretry += sr;
2140 			sc->sc_stats.ast_tx_longretry += lr;
2141 			if (sr + lr)
2142 				an->an_tx_retr++;
2143 			/*
2144 			 * Reclaim reference to node.
2145 			 *
2146 			 * NB: the node may be reclaimed here if, for example
2147 			 *     this is a DEAUTH message that was sent and the
2148 			 *     node was timed out due to inactivity.
2149 			 */
2150 			if (ni != ic->ic_bss)
2151 				ieee80211_free_node(ic, ni);
2152 		}
2153 		bus_dmamap_sync(sc->sc_dmat, bf->bf_dmamap,
2154 		    BUS_DMASYNC_POSTWRITE);
2155 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2156 		m_freem(bf->bf_m);
2157 		bf->bf_m = NULL;
2158 		bf->bf_node = NULL;
2159 
2160 		ATH_TXBUF_LOCK(sc);
2161 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
2162 		ATH_TXBUF_UNLOCK(sc);
2163 	}
2164 	ifp->if_flags &= ~IFF_OACTIVE;
2165 	sc->sc_tx_timer = 0;
2166 
2167 	ath_start(ifp);
2168 }
2169 
2170 /*
2171  * Drain the transmit queue and reclaim resources.
2172  */
2173 static void
2174 ath_draintxq(struct ath_softc *sc)
2175 {
2176 	struct ath_hal *ah = sc->sc_ah;
2177 	struct ifnet *ifp = &sc->sc_ic.ic_if;
2178 	struct ath_buf *bf;
2179 
2180 	/* XXX return value */
2181 	if (!sc->sc_invalid) {
2182 		/* don't touch the hardware if marked invalid */
2183 		(void) ath_hal_stoptxdma(ah, sc->sc_txhalq);
2184 		DPRINTF(("ath_draintxq: tx queue %p, link %p\n",
2185 		    (caddr_t) ath_hal_gettxbuf(ah, sc->sc_txhalq),
2186 		    sc->sc_txlink));
2187 		(void) ath_hal_stoptxdma(ah, sc->sc_bhalq);
2188 		DPRINTF(("ath_draintxq: beacon queue %p\n",
2189 		    (caddr_t) ath_hal_gettxbuf(ah, sc->sc_bhalq)));
2190 	}
2191 	for (;;) {
2192 		ATH_TXQ_LOCK(sc);
2193 		bf = TAILQ_FIRST(&sc->sc_txq);
2194 		if (bf == NULL) {
2195 			sc->sc_txlink = NULL;
2196 			ATH_TXQ_UNLOCK(sc);
2197 			break;
2198 		}
2199 		TAILQ_REMOVE(&sc->sc_txq, bf, bf_list);
2200 		ATH_TXQ_UNLOCK(sc);
2201 #ifdef AR_DEBUG
2202 		if (ath_debug)
2203 			ath_printtxbuf(bf,
2204 				ath_hal_txprocdesc(ah, bf->bf_desc) == HAL_OK);
2205 #endif /* AR_DEBUG */
2206 		bus_dmamap_unload(sc->sc_dmat, bf->bf_dmamap);
2207 		m_freem(bf->bf_m);
2208 		bf->bf_m = NULL;
2209 		bf->bf_node = NULL;
2210 		ATH_TXBUF_LOCK(sc);
2211 		TAILQ_INSERT_TAIL(&sc->sc_txbuf, bf, bf_list);
2212 		ATH_TXBUF_UNLOCK(sc);
2213 	}
2214 	ifp->if_flags &= ~IFF_OACTIVE;
2215 	sc->sc_tx_timer = 0;
2216 }
2217 
2218 /*
2219  * Disable the receive h/w in preparation for a reset.
2220  */
2221 static void
2222 ath_stoprecv(struct ath_softc *sc)
2223 {
2224 	struct ath_hal *ah = sc->sc_ah;
2225 
2226 	ath_hal_stoppcurecv(ah);	/* disable PCU */
2227 	ath_hal_setrxfilter(ah, 0);	/* clear recv filter */
2228 	ath_hal_stopdmarecv(ah);	/* disable DMA engine */
2229 	DELAY(3000);			/* long enough for 1 frame */
2230 #ifdef AR_DEBUG
2231 	if (ath_debug) {
2232 		struct ath_buf *bf;
2233 
2234 		DPRINTF(("ath_stoprecv: rx queue %p, link %p\n",
2235 		    (caddr_t) ath_hal_getrxbuf(ah), sc->sc_rxlink));
2236 		TAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
2237 			if (ath_hal_rxprocdesc(ah, bf->bf_desc) == HAL_OK)
2238 				ath_printrxbuf(bf, 1);
2239 		}
2240 	}
2241 #endif
2242 	sc->sc_rxlink = NULL;		/* just in case */
2243 }
2244 
2245 /*
2246  * Enable the receive h/w following a reset.
2247  */
2248 static int
2249 ath_startrecv(struct ath_softc *sc)
2250 {
2251 	struct ath_hal *ah = sc->sc_ah;
2252 	struct ath_buf *bf;
2253 
2254 	sc->sc_rxlink = NULL;
2255 	TAILQ_FOREACH(bf, &sc->sc_rxbuf, bf_list) {
2256 		int error = ath_rxbuf_init(sc, bf);
2257 		if (error != 0) {
2258 			DPRINTF(("ath_startrecv: ath_rxbuf_init failed %d\n",
2259 				error));
2260 			return error;
2261 		}
2262 	}
2263 
2264 	bf = TAILQ_FIRST(&sc->sc_rxbuf);
2265 	ath_hal_putrxbuf(ah, bf->bf_daddr);
2266 	ath_hal_rxena(ah);		/* enable recv descriptors */
2267 	ath_mode_init(sc);		/* set filters, etc. */
2268 	ath_hal_startpcurecv(ah);	/* re-enable PCU/DMA engine */
2269 	return 0;
2270 }
2271 
2272 /*
2273  * Set/change channels.  If the channel is really being changed,
2274  * it's done by resetting the chip.  To accomplish this we must
2275  * first cleanup any pending DMA, then restart stuff after a la
2276  * ath_init.
2277  */
2278 static int
2279 ath_chan_set(struct ath_softc *sc, struct ieee80211_channel *chan)
2280 {
2281 	struct ath_hal *ah = sc->sc_ah;
2282 	struct ieee80211com *ic = &sc->sc_ic;
2283 
2284 	DPRINTF(("ath_chan_set: %u (%u MHz) -> %u (%u MHz)\n",
2285 	    ieee80211_chan2ieee(ic, ic->ic_ibss_chan),
2286 		ic->ic_ibss_chan->ic_freq,
2287 	    ieee80211_chan2ieee(ic, chan), chan->ic_freq));
2288 	if (chan != ic->ic_ibss_chan) {
2289 		HAL_STATUS status;
2290 		HAL_CHANNEL hchan;
2291 		enum ieee80211_phymode mode;
2292 
2293 		/*
2294 		 * To switch channels clear any pending DMA operations;
2295 		 * wait long enough for the RX fifo to drain, reset the
2296 		 * hardware at the new frequency, and then re-enable
2297 		 * the relevant bits of the h/w.
2298 		 */
2299 		ath_hal_intrset(ah, 0);		/* disable interrupts */
2300 		ath_draintxq(sc);		/* clear pending tx frames */
2301 		ath_stoprecv(sc);		/* turn off frame recv */
2302 		/*
2303 		 * Convert to a HAL channel description with
2304 		 * the flags constrained to reflect the current
2305 		 * operating mode.
2306 		 */
2307 		hchan.channel = chan->ic_freq;
2308 		hchan.channelFlags = ath_chan2flags(ic, chan);
2309 		if (!ath_hal_reset(ah, ic->ic_opmode, &hchan, AH_TRUE, &status)) {
2310 			if_printf(&ic->ic_if, "ath_chan_set: unable to reset "
2311 				"channel %u (%u Mhz)\n",
2312 				ieee80211_chan2ieee(ic, chan), chan->ic_freq);
2313 			return EIO;
2314 		}
2315 		/*
2316 		 * Re-enable rx framework.
2317 		 */
2318 		if (ath_startrecv(sc) != 0) {
2319 			if_printf(&ic->ic_if,
2320 				"ath_chan_set: unable to restart recv logic\n");
2321 			return EIO;
2322 		}
2323 
2324 		/*
2325 		 * Update BPF state.
2326 		 */
2327 		sc->sc_tx_th.wt_chan_freq = sc->sc_rx_th.wr_chan_freq =
2328 			htole16(chan->ic_freq);
2329 		sc->sc_tx_th.wt_chan_flags = sc->sc_rx_th.wr_chan_flags =
2330 			htole16(chan->ic_flags);
2331 
2332 		/*
2333 		 * Change channels and update the h/w rate map
2334 		 * if we're switching; e.g. 11a to 11b/g.
2335 		 */
2336 		ic->ic_ibss_chan = chan;
2337 		mode = ieee80211_chan2mode(ic, chan);
2338 		if (mode != sc->sc_curmode)
2339 			ath_setcurmode(sc, mode);
2340 
2341 		/*
2342 		 * Re-enable interrupts.
2343 		 */
2344 		ath_hal_intrset(ah, sc->sc_imask);
2345 	}
2346 	return 0;
2347 }
2348 
2349 static void
2350 ath_next_scan(void *arg)
2351 {
2352 	struct ath_softc *sc = arg;
2353 	struct ieee80211com *ic = &sc->sc_ic;
2354 	struct ifnet *ifp = &ic->ic_if;
2355 
2356 	if (ic->ic_state == IEEE80211_S_SCAN)
2357 		ieee80211_next_scan(ifp);
2358 }
2359 
2360 /*
2361  * Periodically recalibrate the PHY to account
2362  * for temperature/environment changes.
2363  */
2364 static void
2365 ath_calibrate(void *arg)
2366 {
2367 	struct ath_softc *sc = arg;
2368 	struct ath_hal *ah = sc->sc_ah;
2369 	struct ieee80211com *ic = &sc->sc_ic;
2370 	struct ieee80211_channel *c;
2371 	HAL_CHANNEL hchan;
2372 
2373 	sc->sc_stats.ast_per_cal++;
2374 
2375 	/*
2376 	 * Convert to a HAL channel description with the flags
2377 	 * constrained to reflect the current operating mode.
2378 	 */
2379 	c = ic->ic_ibss_chan;
2380 	hchan.channel = c->ic_freq;
2381 	hchan.channelFlags = ath_chan2flags(ic, c);
2382 
2383 	DPRINTF(("%s: channel %u/%x\n", __func__, c->ic_freq, c->ic_flags));
2384 
2385 	if (ath_hal_getrfgain(ah) == HAL_RFGAIN_NEED_CHANGE) {
2386 		/*
2387 		 * Rfgain is out of bounds, reset the chip
2388 		 * to load new gain values.
2389 		 */
2390 		sc->sc_stats.ast_per_rfgain++;
2391 		ath_reset(sc);
2392 	}
2393 	if (!ath_hal_calibrate(ah, &hchan)) {
2394 		DPRINTF(("%s: calibration of channel %u failed\n",
2395 			__func__, c->ic_freq));
2396 		sc->sc_stats.ast_per_calfail++;
2397 	}
2398 	callout_reset(&sc->sc_cal_ch, hz * ath_calinterval, ath_calibrate, sc);
2399 }
2400 
2401 static int
2402 ath_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
2403 {
2404 	struct ifnet *ifp = &ic->ic_if;
2405 	struct ath_softc *sc = ifp->if_softc;
2406 	struct ath_hal *ah = sc->sc_ah;
2407 	struct ieee80211_node *ni;
2408 	int i, error;
2409 	u_int8_t *bssid;
2410 	u_int32_t rfilt;
2411 	static const HAL_LED_STATE leds[] = {
2412 	    HAL_LED_INIT,	/* IEEE80211_S_INIT */
2413 	    HAL_LED_SCAN,	/* IEEE80211_S_SCAN */
2414 	    HAL_LED_AUTH,	/* IEEE80211_S_AUTH */
2415 	    HAL_LED_ASSOC, 	/* IEEE80211_S_ASSOC */
2416 	    HAL_LED_RUN, 	/* IEEE80211_S_RUN */
2417 	};
2418 
2419 	DPRINTF(("%s: %s -> %s\n", __func__,
2420 		ieee80211_state_name[ic->ic_state],
2421 		ieee80211_state_name[nstate]));
2422 
2423 	ath_hal_setledstate(ah, leds[nstate]);	/* set LED */
2424 
2425 	if (nstate == IEEE80211_S_INIT) {
2426 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
2427 		ath_hal_intrset(ah, sc->sc_imask);
2428 		callout_stop(&sc->sc_scan_ch);
2429 		callout_stop(&sc->sc_cal_ch);
2430 		return (*sc->sc_newstate)(ic, nstate, arg);
2431 	}
2432 	ni = ic->ic_bss;
2433 	error = ath_chan_set(sc, ni->ni_chan);
2434 	if (error != 0)
2435 		goto bad;
2436 	rfilt = ath_calcrxfilter(sc);
2437 	if (nstate == IEEE80211_S_SCAN) {
2438 		callout_reset(&sc->sc_scan_ch, (hz * ath_dwelltime) / 1000,
2439 			ath_next_scan, sc);
2440 		bssid = ifp->if_broadcastaddr;
2441 	} else {
2442 		callout_stop(&sc->sc_scan_ch);
2443 		bssid = ni->ni_bssid;
2444 	}
2445 	ath_hal_setrxfilter(ah, rfilt);
2446 	DPRINTF(("%s: RX filter 0x%x bssid %s\n",
2447 		 __func__, rfilt, ether_sprintf(bssid)));
2448 
2449 	if (nstate == IEEE80211_S_RUN && ic->ic_opmode == IEEE80211_M_STA)
2450 		ath_hal_setassocid(ah, bssid, ni->ni_associd);
2451 	else
2452 		ath_hal_setassocid(ah, bssid, 0);
2453 	if (ic->ic_flags & IEEE80211_F_WEPON) {
2454 		for (i = 0; i < IEEE80211_WEP_NKID; i++)
2455 			if (ath_hal_keyisvalid(ah, i))
2456 				ath_hal_keysetmac(ah, i, bssid);
2457 	}
2458 
2459 	if (nstate == IEEE80211_S_RUN) {
2460 		DPRINTF(("%s(RUN): ic_flags=0x%08x iv=%d bssid=%s "
2461 			"capinfo=0x%04x chan=%d\n"
2462 			 , __func__
2463 			 , ic->ic_flags
2464 			 , ni->ni_intval
2465 			 , ether_sprintf(ni->ni_bssid)
2466 			 , ni->ni_capinfo
2467 			 , ieee80211_chan2ieee(ic, ni->ni_chan)));
2468 
2469 		/*
2470 		 * Allocate and setup the beacon frame for AP or adhoc mode.
2471 		 */
2472 		if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
2473 		    ic->ic_opmode == IEEE80211_M_IBSS) {
2474 			error = ath_beacon_alloc(sc, ni);
2475 			if (error != 0)
2476 				goto bad;
2477 		}
2478 
2479 		/*
2480 		 * Configure the beacon and sleep timers.
2481 		 */
2482 		ath_beacon_config(sc);
2483 
2484 		/* start periodic recalibration timer */
2485 		callout_reset(&sc->sc_cal_ch, hz * ath_calinterval,
2486 			ath_calibrate, sc);
2487 	} else {
2488 		sc->sc_imask &= ~(HAL_INT_SWBA | HAL_INT_BMISS);
2489 		ath_hal_intrset(ah, sc->sc_imask);
2490 		callout_stop(&sc->sc_cal_ch);		/* no calibration */
2491 	}
2492 	/*
2493 	 * Reset the rate control state.
2494 	 */
2495 	ath_rate_ctl_reset(sc, nstate);
2496 	/*
2497 	 * Invoke the parent method to complete the work.
2498 	 */
2499 	return (*sc->sc_newstate)(ic, nstate, arg);
2500 bad:
2501 	callout_stop(&sc->sc_scan_ch);
2502 	callout_stop(&sc->sc_cal_ch);
2503 	/* NB: do not invoke the parent */
2504 	return error;
2505 }
2506 
2507 /*
2508  * Setup driver-specific state for a newly associated node.
2509  * Note that we're called also on a re-associate, the isnew
2510  * param tells us if this is the first time or not.
2511  */
2512 static void
2513 ath_newassoc(struct ieee80211com *ic, struct ieee80211_node *ni, int isnew)
2514 {
2515 	if (isnew) {
2516 		struct ath_node *an = (struct ath_node *) ni;
2517 
2518 		an->an_tx_ok = an->an_tx_err =
2519 			an->an_tx_retr = an->an_tx_upper = 0;
2520 		/* start with highest negotiated rate */
2521 		/*
2522 		 * XXX should do otherwise but only when
2523 		 * the rate control algorithm is better.
2524 		 */
2525 		KASSERT(ni->ni_rates.rs_nrates > 0,
2526 			("new association w/ no rates!"));
2527 		ni->ni_txrate = ni->ni_rates.rs_nrates - 1;
2528 	}
2529 }
2530 
2531 static int
2532 ath_getchannels(struct ath_softc *sc, u_int cc, HAL_BOOL outdoor)
2533 {
2534 	struct ieee80211com *ic = &sc->sc_ic;
2535 	struct ifnet *ifp = &ic->ic_if;
2536 	struct ath_hal *ah = sc->sc_ah;
2537 	HAL_CHANNEL *chans;
2538 	int i, ix, nchan;
2539 
2540 	chans = malloc(IEEE80211_CHAN_MAX * sizeof(HAL_CHANNEL),
2541 			M_TEMP, M_NOWAIT);
2542 	if (chans == NULL) {
2543 		if_printf(ifp, "unable to allocate channel table\n");
2544 		return ENOMEM;
2545 	}
2546 	if (!ath_hal_init_channels(ah, chans, IEEE80211_CHAN_MAX, &nchan,
2547 	    cc, HAL_MODE_ALL, outdoor)) {
2548 		if_printf(ifp, "unable to collect channel list from hal\n");
2549 		free(chans, M_TEMP);
2550 		return EINVAL;
2551 	}
2552 
2553 	/*
2554 	 * Convert HAL channels to ieee80211 ones and insert
2555 	 * them in the table according to their channel number.
2556 	 */
2557 	for (i = 0; i < nchan; i++) {
2558 		HAL_CHANNEL *c = &chans[i];
2559 		ix = ath_hal_mhz2ieee(c->channel, c->channelFlags);
2560 		if (ix > IEEE80211_CHAN_MAX) {
2561 			if_printf(ifp, "bad hal channel %u (%u/%x) ignored\n",
2562 				ix, c->channel, c->channelFlags);
2563 			continue;
2564 		}
2565 		/* NB: flags are known to be compatible */
2566 		if (ic->ic_channels[ix].ic_freq == 0) {
2567 			ic->ic_channels[ix].ic_freq = c->channel;
2568 			ic->ic_channels[ix].ic_flags = c->channelFlags;
2569 		} else {
2570 			/* channels overlap; e.g. 11g and 11b */
2571 			ic->ic_channels[ix].ic_flags |= c->channelFlags;
2572 		}
2573 	}
2574 	free(chans, M_TEMP);
2575 	return 0;
2576 }
2577 
2578 static int
2579 ath_rate_setup(struct ath_softc *sc, u_int mode)
2580 {
2581 	struct ath_hal *ah = sc->sc_ah;
2582 	struct ieee80211com *ic = &sc->sc_ic;
2583 	const HAL_RATE_TABLE *rt;
2584 	struct ieee80211_rateset *rs;
2585 	int i, maxrates;
2586 
2587 	switch (mode) {
2588 	case IEEE80211_MODE_11A:
2589 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11A);
2590 		break;
2591 	case IEEE80211_MODE_11B:
2592 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11B);
2593 		break;
2594 	case IEEE80211_MODE_11G:
2595 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_11G);
2596 		break;
2597 	case IEEE80211_MODE_TURBO:
2598 		sc->sc_rates[mode] = ath_hal_getratetable(ah, HAL_MODE_TURBO);
2599 		break;
2600 	default:
2601 		DPRINTF(("%s: invalid mode %u\n", __func__, mode));
2602 		return 0;
2603 	}
2604 	rt = sc->sc_rates[mode];
2605 	if (rt == NULL)
2606 		return 0;
2607 	if (rt->rateCount > IEEE80211_RATE_MAXSIZE) {
2608 		DPRINTF(("%s: rate table too small (%u > %u)\n",
2609 			__func__, rt->rateCount, IEEE80211_RATE_MAXSIZE));
2610 		maxrates = IEEE80211_RATE_MAXSIZE;
2611 	} else
2612 		maxrates = rt->rateCount;
2613 	rs = &ic->ic_sup_rates[mode];
2614 	for (i = 0; i < maxrates; i++)
2615 		rs->rs_rates[i] = rt->info[i].dot11Rate;
2616 	rs->rs_nrates = maxrates;
2617 	return 1;
2618 }
2619 
2620 static void
2621 ath_setcurmode(struct ath_softc *sc, enum ieee80211_phymode mode)
2622 {
2623 	const HAL_RATE_TABLE *rt;
2624 	int i;
2625 
2626 	memset(sc->sc_rixmap, 0xff, sizeof(sc->sc_rixmap));
2627 	rt = sc->sc_rates[mode];
2628 	KASSERT(rt != NULL, ("no h/w rate set for phy mode %u", mode));
2629 	for (i = 0; i < rt->rateCount; i++)
2630 		sc->sc_rixmap[rt->info[i].dot11Rate & IEEE80211_RATE_VAL] = i;
2631 	memset(sc->sc_hwmap, 0, sizeof(sc->sc_hwmap));
2632 	for (i = 0; i < 32; i++)
2633 		sc->sc_hwmap[i] = rt->info[rt->rateCodeToIndex[i]].dot11Rate;
2634 	sc->sc_currates = rt;
2635 	sc->sc_curmode = mode;
2636 }
2637 
2638 /*
2639  * Reset the rate control state for each 802.11 state transition.
2640  */
2641 static void
2642 ath_rate_ctl_reset(struct ath_softc *sc, enum ieee80211_state state)
2643 {
2644 	struct ieee80211com *ic = &sc->sc_ic;
2645 	struct ieee80211_node *ni;
2646 	struct ath_node *an;
2647 
2648 	if (ic->ic_opmode != IEEE80211_M_STA) {
2649 		/*
2650 		 * When operating as a station the node table holds
2651 		 * the AP's that were discovered during scanning.
2652 		 * For any other operating mode we want to reset the
2653 		 * tx rate state of each node.
2654 		 */
2655 		TAILQ_FOREACH(ni, &ic->ic_node, ni_list) {
2656 			ni->ni_txrate = 0;		/* use lowest rate */
2657 			an = (struct ath_node *) ni;
2658 			an->an_tx_ok = an->an_tx_err = an->an_tx_retr =
2659 			    an->an_tx_upper = 0;
2660 		}
2661 	}
2662 	/*
2663 	 * Reset local xmit state; this is really only meaningful
2664 	 * when operating in station or adhoc mode.
2665 	 */
2666 	ni = ic->ic_bss;
2667 	an = (struct ath_node *) ni;
2668 	an->an_tx_ok = an->an_tx_err = an->an_tx_retr = an->an_tx_upper = 0;
2669 	if (state == IEEE80211_S_RUN) {
2670 		/* start with highest negotiated rate */
2671 		KASSERT(ni->ni_rates.rs_nrates > 0,
2672 			("transition to RUN state w/ no rates!"));
2673 		ni->ni_txrate = ni->ni_rates.rs_nrates - 1;
2674 	} else {
2675 		/* use lowest rate */
2676 		ni->ni_txrate = 0;
2677 	}
2678 }
2679 
2680 /*
2681  * Examine and potentially adjust the transmit rate.
2682  */
2683 static void
2684 ath_rate_ctl(void *arg, struct ieee80211_node *ni)
2685 {
2686 	struct ath_softc *sc = arg;
2687 	struct ath_node *an = (struct ath_node *) ni;
2688 	struct ieee80211_rateset *rs = &ni->ni_rates;
2689 	int mod = 0, orate, enough;
2690 
2691 	/*
2692 	 * Rate control
2693 	 * XXX: very primitive version.
2694 	 */
2695 	sc->sc_stats.ast_rate_calls++;
2696 
2697 	enough = (an->an_tx_ok + an->an_tx_err >= 10);
2698 
2699 	/* no packet reached -> down */
2700 	if (an->an_tx_err > 0 && an->an_tx_ok == 0)
2701 		mod = -1;
2702 
2703 	/* all packets needs retry in average -> down */
2704 	if (enough && an->an_tx_ok < an->an_tx_retr)
2705 		mod = -1;
2706 
2707 	/* no error and less than 10% of packets needs retry -> up */
2708 	if (enough && an->an_tx_err == 0 && an->an_tx_ok > an->an_tx_retr * 10)
2709 		mod = 1;
2710 
2711 	orate = ni->ni_txrate;
2712 	switch (mod) {
2713 	case 0:
2714 		if (enough && an->an_tx_upper > 0)
2715 			an->an_tx_upper--;
2716 		break;
2717 	case -1:
2718 		if (ni->ni_txrate > 0) {
2719 			ni->ni_txrate--;
2720 			sc->sc_stats.ast_rate_drop++;
2721 		}
2722 		an->an_tx_upper = 0;
2723 		break;
2724 	case 1:
2725 		if (++an->an_tx_upper < 2)
2726 			break;
2727 		an->an_tx_upper = 0;
2728 		if (ni->ni_txrate + 1 < rs->rs_nrates) {
2729 			ni->ni_txrate++;
2730 			sc->sc_stats.ast_rate_raise++;
2731 		}
2732 		break;
2733 	}
2734 
2735 	if (ni->ni_txrate != orate) {
2736 		printf("%s: %dM -> %dM (%d ok, %d err, %d retr)\n",
2737 		    __func__,
2738 		    (rs->rs_rates[orate] & IEEE80211_RATE_VAL) / 2,
2739 		    (rs->rs_rates[ni->ni_txrate] & IEEE80211_RATE_VAL) / 2,
2740 		    an->an_tx_ok, an->an_tx_err, an->an_tx_retr);
2741 	}
2742 	if (ni->ni_txrate != orate || enough)
2743 		an->an_tx_ok = an->an_tx_err = an->an_tx_retr = 0;
2744 }
2745 
2746 #ifdef AR_DEBUG
2747 static int
2748 sysctl_hw_ath_dump(SYSCTL_HANDLER_ARGS)
2749 {
2750 	char dmode[64];
2751 	int error;
2752 
2753 	strncpy(dmode, "", sizeof(dmode) - 1);
2754 	dmode[sizeof(dmode) - 1] = '\0';
2755 	error = sysctl_handle_string(oidp, &dmode[0], sizeof(dmode), req);
2756 
2757 	if (error == 0 && req->newptr != NULL) {
2758 		struct ifnet *ifp;
2759 		struct ath_softc *sc;
2760 
2761 		ifp = ifunit("ath0");		/* XXX */
2762 		if (!ifp)
2763 			return EINVAL;
2764 		sc = ifp->if_softc;
2765 		if (strcmp(dmode, "hal") == 0)
2766 			ath_hal_dumpstate(sc->sc_ah);
2767 		else if (strcmp(dmode, "eeprom") == 0)
2768 			ath_hal_dumpeeprom(sc->sc_ah);
2769 		else if (strcmp(dmode, "rfgain") == 0)
2770 			ath_hal_dumprfgain(sc->sc_ah);
2771 		else if (strcmp(dmode, "ani") == 0)
2772 			ath_hal_dumpani(sc->sc_ah);
2773 		else
2774 			return EINVAL;
2775 	}
2776 	return error;
2777 }
2778 SYSCTL_PROC(_hw_ath, OID_AUTO, dump, CTLTYPE_STRING | CTLFLAG_RW,
2779 	0, 0, sysctl_hw_ath_dump, "A", "Dump driver state");
2780 
2781 static void
2782 ath_printrxbuf(struct ath_buf *bf, int done)
2783 {
2784 	struct ath_desc *ds;
2785 	int i;
2786 
2787 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
2788 		printf("R%d (%p %p) %08x %08x %08x %08x %08x %08x %c\n",
2789 		    i, ds, (struct ath_desc *)bf->bf_daddr + i,
2790 		    ds->ds_link, ds->ds_data,
2791 		    ds->ds_ctl0, ds->ds_ctl1,
2792 		    ds->ds_hw[0], ds->ds_hw[1],
2793 		    !done ? ' ' : (ds->ds_rxstat.rs_status == 0) ? '*' : '!');
2794 	}
2795 }
2796 
2797 static void
2798 ath_printtxbuf(struct ath_buf *bf, int done)
2799 {
2800 	struct ath_desc *ds;
2801 	int i;
2802 
2803 	for (i = 0, ds = bf->bf_desc; i < bf->bf_nseg; i++, ds++) {
2804 		printf("T%d (%p %p) %08x %08x %08x %08x %08x %08x %08x %08x %c\n",
2805 		    i, ds, (struct ath_desc *)bf->bf_daddr + i,
2806 		    ds->ds_link, ds->ds_data,
2807 		    ds->ds_ctl0, ds->ds_ctl1,
2808 		    ds->ds_hw[0], ds->ds_hw[1], ds->ds_hw[2], ds->ds_hw[3],
2809 		    !done ? ' ' : (ds->ds_txstat.ts_status == 0) ? '*' : '!');
2810 	}
2811 }
2812 #endif /* AR_DEBUG */
2813