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