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