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