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