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