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