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