rt2661.c revision 164982
1193323Sed/*	$FreeBSD: head/sys/dev/ral/rt2661.c 164982 2006-12-07 15:24:38Z kevlo $	*/
2193323Sed
3193323Sed/*-
4193323Sed * Copyright (c) 2006
5193323Sed *	Damien Bergamini <damien.bergamini@free.fr>
6193323Sed *
7193323Sed * Permission to use, copy, modify, and distribute this software for any
8193323Sed * purpose with or without fee is hereby granted, provided that the above
9193323Sed * copyright notice and this permission notice appear in all copies.
10193323Sed *
11193323Sed * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12193323Sed * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13193323Sed * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14193323Sed * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15193323Sed * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16193323Sed * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17193323Sed * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18193323Sed */
19193323Sed
20193323Sed#include <sys/cdefs.h>
21193323Sed__FBSDID("$FreeBSD: head/sys/dev/ral/rt2661.c 164982 2006-12-07 15:24:38Z kevlo $");
22193323Sed
23193323Sed/*-
24193323Sed * Ralink Technology RT2561, RT2561S and RT2661 chipset driver
25193323Sed * http://www.ralinktech.com/
26193323Sed */
27193323Sed
28193323Sed#include <sys/param.h>
29193323Sed#include <sys/sysctl.h>
30193323Sed#include <sys/sockio.h>
31193323Sed#include <sys/mbuf.h>
32193323Sed#include <sys/kernel.h>
33193323Sed#include <sys/socket.h>
34249423Sdim#include <sys/systm.h>
35249423Sdim#include <sys/malloc.h>
36234353Sdim#include <sys/lock.h>
37251662Sdim#include <sys/mutex.h>
38234353Sdim#include <sys/module.h>
39200581Srdivacky#include <sys/bus.h>
40193323Sed#include <sys/endian.h>
41234353Sdim
42193323Sed#include <machine/bus.h>
43263508Sdim#include <machine/resource.h>
44234353Sdim#include <sys/rman.h>
45193323Sed
46193323Sed#include <net/bpf.h>
47193323Sed#include <net/if.h>
48249423Sdim#include <net/if_arp.h>
49218893Sdim#include <net/ethernet.h>
50218893Sdim#include <net/if_dl.h>
51193323Sed#include <net/if_media.h>
52249423Sdim#include <net/if_types.h>
53249423Sdim
54193323Sed#include <net80211/ieee80211_var.h>
55198090Srdivacky#include <net80211/ieee80211_radiotap.h>
56193323Sed
57193323Sed#include <netinet/in.h>
58193323Sed#include <netinet/in_systm.h>
59193323Sed#include <netinet/in_var.h>
60193323Sed#include <netinet/ip.h>
61234353Sdim#include <netinet/if_ether.h>
62193323Sed
63193323Sed#include <dev/ral/if_ralrate.h>
64193323Sed#include <dev/ral/rt2661reg.h>
65193323Sed#include <dev/ral/rt2661var.h>
66193323Sed#include <dev/ral/rt2661_ucode.h>
67204642Srdivacky
68218893Sdim#ifdef RAL_DEBUG
69193323Sed#define DPRINTF(x)	do { if (ral_debug > 0) printf x; } while (0)
70198090Srdivacky#define DPRINTFN(n, x)	do { if (ral_debug >= (n)) printf x; } while (0)
71198090Srdivackyint ral_debug = 0;
72203954SrdivackySYSCTL_INT(_debug, OID_AUTO, ral, CTLFLAG_RW, &ral_debug, 0, "ral debug level");
73203954Srdivacky#else
74198090Srdivacky#define DPRINTF(x)
75234353Sdim#define DPRINTFN(n, x)
76212904Sdim#endif
77234353Sdim
78234353Sdimstatic void		rt2661_dma_map_addr(void *, bus_dma_segment_t *, int,
79234353Sdim			    int);
80234353Sdimstatic int		rt2661_alloc_tx_ring(struct rt2661_softc *,
81212904Sdim			    struct rt2661_tx_ring *, int);
82193323Sedstatic void		rt2661_reset_tx_ring(struct rt2661_softc *,
83193323Sed			    struct rt2661_tx_ring *);
84218893Sdimstatic void		rt2661_free_tx_ring(struct rt2661_softc *,
85218893Sdim			    struct rt2661_tx_ring *);
86218893Sdimstatic int		rt2661_alloc_rx_ring(struct rt2661_softc *,
87218893Sdim			    struct rt2661_rx_ring *, int);
88218893Sdimstatic void		rt2661_reset_rx_ring(struct rt2661_softc *,
89218893Sdim			    struct rt2661_rx_ring *);
90193323Sedstatic void		rt2661_free_rx_ring(struct rt2661_softc *,
91218893Sdim			    struct rt2661_rx_ring *);
92193323Sedstatic struct		ieee80211_node *rt2661_node_alloc(
93218893Sdim			    struct ieee80211_node_table *);
94251662Sdimstatic int		rt2661_media_change(struct ifnet *);
95251662Sdimstatic void		rt2661_next_scan(void *);
96218893Sdimstatic int		rt2661_newstate(struct ieee80211com *,
97218893Sdim			    enum ieee80211_state, int);
98218893Sdimstatic uint16_t		rt2661_eeprom_read(struct rt2661_softc *, uint8_t);
99218893Sdimstatic void		rt2661_rx_intr(struct rt2661_softc *);
100218893Sdimstatic void		rt2661_tx_intr(struct rt2661_softc *);
101193323Sedstatic void		rt2661_tx_dma_intr(struct rt2661_softc *,
102218893Sdim			    struct rt2661_tx_ring *);
103218893Sdimstatic void		rt2661_mcu_beacon_expire(struct rt2661_softc *);
104218893Sdimstatic void		rt2661_mcu_wakeup(struct rt2661_softc *);
105218893Sdimstatic void		rt2661_mcu_cmd_intr(struct rt2661_softc *);
106193323Sedstatic int		rt2661_ack_rate(struct ieee80211com *, int);
107218893Sdimstatic uint16_t		rt2661_txtime(int, int, uint32_t);
108218893Sdimstatic uint8_t		rt2661_rxrate(struct rt2661_rx_desc *);
109193323Sedstatic uint8_t		rt2661_plcp_signal(int);
110218893Sdimstatic void		rt2661_setup_tx_desc(struct rt2661_softc *,
111218893Sdim			    struct rt2661_tx_desc *, uint32_t, uint16_t, int,
112193323Sed			    int, const bus_dma_segment_t *, int, int);
113218893Sdimstatic struct mbuf *	rt2661_get_rts(struct rt2661_softc *,
114212904Sdim			    struct ieee80211_frame *, uint16_t);
115218893Sdimstatic int		rt2661_tx_data(struct rt2661_softc *, struct mbuf *,
116218893Sdim			    struct ieee80211_node *, int);
117218893Sdimstatic int		rt2661_tx_mgt(struct rt2661_softc *, struct mbuf *,
118218893Sdim			    struct ieee80211_node *);
119218893Sdimstatic void		rt2661_start(struct ifnet *);
120218893Sdimstatic void		rt2661_watchdog(struct ifnet *);
121218893Sdimstatic int		rt2661_reset(struct ifnet *);
122212904Sdimstatic int		rt2661_ioctl(struct ifnet *, u_long, caddr_t);
123193323Sedstatic void		rt2661_bbp_write(struct rt2661_softc *, uint8_t,
124251662Sdim			    uint8_t);
125193323Sedstatic uint8_t		rt2661_bbp_read(struct rt2661_softc *, uint8_t);
126224145Sdimstatic void		rt2661_rf_write(struct rt2661_softc *, uint8_t,
127224145Sdim			    uint32_t);
128218893Sdimstatic int		rt2661_tx_cmd(struct rt2661_softc *, uint8_t,
129218893Sdim			    uint16_t);
130218893Sdimstatic void		rt2661_select_antenna(struct rt2661_softc *);
131218893Sdimstatic void		rt2661_enable_mrr(struct rt2661_softc *);
132218893Sdimstatic void		rt2661_set_txpreamble(struct rt2661_softc *);
133263508Sdimstatic void		rt2661_set_basicrates(struct rt2661_softc *,
134203954Srdivacky			    const struct ieee80211_rateset *);
135251662Sdimstatic void		rt2661_select_band(struct rt2661_softc *,
136218893Sdim			    struct ieee80211_channel *);
137218893Sdimstatic void		rt2661_set_chan(struct rt2661_softc *,
138218893Sdim			    struct ieee80211_channel *);
139193323Sedstatic void		rt2661_set_bssid(struct rt2661_softc *,
140218893Sdim			    const uint8_t *);
141193323Sedstatic void		rt2661_set_macaddr(struct rt2661_softc *,
142218893Sdim			   const uint8_t *);
143218893Sdimstatic void		rt2661_update_promisc(struct rt2661_softc *);
144193323Sedstatic int		rt2661_wme_update(struct ieee80211com *) __unused;
145218893Sdimstatic void		rt2661_update_slot(struct ifnet *);
146218893Sdimstatic const char	*rt2661_get_rf(int);
147218893Sdimstatic void		rt2661_read_eeprom(struct rt2661_softc *);
148218893Sdimstatic int		rt2661_bbp_init(struct rt2661_softc *);
149193323Sedstatic void		rt2661_init(void *);
150218893Sdimstatic void		rt2661_stop(void *);
151218893Sdimstatic int		rt2661_load_microcode(struct rt2661_softc *,
152218893Sdim			    const uint8_t *, int);
153193323Sed#ifdef notyet
154218893Sdimstatic void		rt2661_rx_tune(struct rt2661_softc *);
155193323Sedstatic void		rt2661_radar_start(struct rt2661_softc *);
156218893Sdimstatic int		rt2661_radar_stop(struct rt2661_softc *);
157193323Sed#endif
158218893Sdimstatic int		rt2661_prepare_beacon(struct rt2661_softc *);
159193323Sedstatic void		rt2661_enable_tsf_sync(struct rt2661_softc *);
160263508Sdimstatic int		rt2661_get_rssi(struct rt2661_softc *, uint8_t);
161218893Sdim
162218893Sdim/*
163218893Sdim * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
164218893Sdim */
165193323Sedstatic const struct ieee80211_rateset rt2661_rateset_11a =
166263508Sdim	{ 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
167218893Sdim
168218893Sdimstatic const struct ieee80211_rateset rt2661_rateset_11b =
169218893Sdim	{ 4, { 2, 4, 11, 22 } };
170234353Sdim
171218893Sdimstatic const struct ieee80211_rateset rt2661_rateset_11g =
172193323Sed	{ 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
173218893Sdim
174218893Sdimstatic const struct {
175218893Sdim	uint32_t	reg;
176218893Sdim	uint32_t	val;
177218893Sdim} rt2661_def_mac[] = {
178218893Sdim	RT2661_DEF_MAC
179218893Sdim};
180193323Sed
181218893Sdimstatic const struct {
182218893Sdim	uint8_t	reg;
183193323Sed	uint8_t	val;
184218893Sdim} rt2661_def_bbp[] = {
185218893Sdim	RT2661_DEF_BBP
186218893Sdim};
187193323Sed
188193323Sedstatic const struct rfprog {
189251662Sdim	uint8_t		chan;
190263508Sdim	uint32_t	r1, r2, r3, r4;
191251662Sdim}  rt2661_rf5225_1[] = {
192193323Sed	RT2661_RF5225_1
193239462Sdim}, rt2661_rf5225_2[] = {
194218893Sdim	RT2661_RF5225_2
195234353Sdim};
196193323Sed
197251662Sdimint
198218893Sdimrt2661_attach(device_t dev, int id)
199218893Sdim{
200193323Sed	struct rt2661_softc *sc = device_get_softc(dev);
201218893Sdim	struct ieee80211com *ic = &sc->sc_ic;
202239462Sdim	struct ifnet *ifp;
203239462Sdim	uint32_t val;
204239462Sdim	const uint8_t *ucode = NULL;
205239462Sdim	int error, i, ac, ntries, size = 0;
206239462Sdim
207218893Sdim	sc->sc_dev = dev;
208193323Sed
209234353Sdim	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
210218893Sdim	    MTX_DEF | MTX_RECURSE);
211218893Sdim
212218893Sdim	callout_init(&sc->scan_ch, debug_mpsafenet ? CALLOUT_MPSAFE : 0);
213218893Sdim	callout_init(&sc->rssadapt_ch, CALLOUT_MPSAFE);
214239462Sdim
215193323Sed	/* wait for NIC to initialize */
216239462Sdim	for (ntries = 0; ntries < 1000; ntries++) {
217243830Sdim		if ((val = RAL_READ(sc, RT2661_MAC_CSR0)) != 0)
218239462Sdim			break;
219239462Sdim		DELAY(1000);
220218893Sdim	}
221218893Sdim	if (ntries == 1000) {
222218893Sdim		device_printf(sc->sc_dev,
223234353Sdim		    "timeout waiting for NIC to initialize\n");
224224145Sdim		error = EIO;
225224145Sdim		goto fail1;
226243830Sdim	}
227239462Sdim
228193323Sed	/* retrieve RF rev. no and various other things from EEPROM */
229239462Sdim	rt2661_read_eeprom(sc);
230239462Sdim
231218893Sdim	device_printf(dev, "MAC/BBP RT%X, RF %s\n", val,
232193323Sed	    rt2661_get_rf(sc->rf_rev));
233239462Sdim
234239462Sdim	/*
235239462Sdim	 * Load 8051 microcode into NIC.
236239462Sdim	 */
237239462Sdim	switch (id) {
238239462Sdim	case 0x0301:
239234353Sdim		ucode = rt2561s_ucode;
240218893Sdim		size = sizeof rt2561s_ucode;
241239462Sdim		break;
242239462Sdim	case 0x0302:
243193323Sed		ucode = rt2561_ucode;
244239462Sdim		size = sizeof rt2561_ucode;
245239462Sdim		break;
246234353Sdim	case 0x0401:
247234353Sdim		ucode = rt2661_ucode;
248218893Sdim		size = sizeof rt2661_ucode;
249263508Sdim		break;
250218893Sdim	}
251193323Sed
252218893Sdim	error = rt2661_load_microcode(sc, ucode, size);
253218893Sdim	if (error != 0) {
254193323Sed		device_printf(sc->sc_dev, "could not load 8051 microcode\n");
255218893Sdim		goto fail1;
256218893Sdim	}
257193323Sed
258218893Sdim	/*
259218893Sdim	 * Allocate Tx and Rx rings.
260193323Sed	 */
261218893Sdim	for (ac = 0; ac < 4; ac++) {
262218893Sdim		error = rt2661_alloc_tx_ring(sc, &sc->txq[ac],
263218893Sdim		    RT2661_TX_RING_COUNT);
264218893Sdim		if (error != 0) {
265218893Sdim			device_printf(sc->sc_dev,
266193323Sed			    "could not allocate Tx ring %d\n", ac);
267218893Sdim			goto fail2;
268218893Sdim		}
269218893Sdim	}
270218893Sdim
271218893Sdim	error = rt2661_alloc_tx_ring(sc, &sc->mgtq, RT2661_MGT_RING_COUNT);
272193323Sed	if (error != 0) {
273218893Sdim		device_printf(sc->sc_dev, "could not allocate Mgt ring\n");
274218893Sdim		goto fail2;
275263508Sdim	}
276218893Sdim
277218893Sdim	error = rt2661_alloc_rx_ring(sc, &sc->rxq, RT2661_RX_RING_COUNT);
278218893Sdim	if (error != 0) {
279218893Sdim		device_printf(sc->sc_dev, "could not allocate Rx ring\n");
280193323Sed		goto fail3;
281193323Sed	}
282193323Sed
283193323Sed	ifp = sc->sc_ifp = if_alloc(IFT_ETHER);
284251662Sdim	if (ifp == NULL) {
285218893Sdim		device_printf(sc->sc_dev, "can not if_alloc()\n");
286193323Sed		error = ENOMEM;
287218893Sdim		goto fail4;
288218893Sdim	}
289218893Sdim
290193323Sed	ifp->if_softc = sc;
291193323Sed	if_initname(ifp, device_get_name(dev), device_get_unit(dev));
292218893Sdim	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
293218893Sdim	ifp->if_init = rt2661_init;
294218893Sdim	ifp->if_ioctl = rt2661_ioctl;
295218893Sdim	ifp->if_start = rt2661_start;
296218893Sdim	ifp->if_watchdog = rt2661_watchdog;
297218893Sdim	IFQ_SET_MAXLEN(&ifp->if_snd, IFQ_MAXLEN);
298218893Sdim	ifp->if_snd.ifq_drv_maxlen = IFQ_MAXLEN;
299193323Sed	IFQ_SET_READY(&ifp->if_snd);
300218893Sdim
301218893Sdim	ic->ic_ifp = ifp;
302193323Sed	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
303218893Sdim	ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */
304218893Sdim	ic->ic_state = IEEE80211_S_INIT;
305193323Sed
306218893Sdim	/* set device capabilities */
307218893Sdim	ic->ic_caps =
308193323Sed	    IEEE80211_C_IBSS |		/* IBSS mode supported */
309193323Sed	    IEEE80211_C_MONITOR |	/* monitor mode supported */
310193323Sed	    IEEE80211_C_HOSTAP |	/* HostAp mode supported */
311193323Sed	    IEEE80211_C_TXPMGT |	/* tx power management */
312193323Sed	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
313251662Sdim	    IEEE80211_C_SHSLOT |	/* short slot time supported */
314218893Sdim#ifdef notyet
315263508Sdim	    IEEE80211_C_WME |		/* 802.11e */
316218893Sdim#endif
317193323Sed	    IEEE80211_C_WPA;		/* 802.11i */
318263508Sdim
319218893Sdim	if (sc->rf_rev == RT2661_RF_5225 || sc->rf_rev == RT2661_RF_5325) {
320193323Sed		/* set supported .11a rates */
321218893Sdim		ic->ic_sup_rates[IEEE80211_MODE_11A] = rt2661_rateset_11a;
322239462Sdim
323193323Sed		/* set supported .11a channels */
324218893Sdim		for (i = 36; i <= 64; i += 4) {
325218893Sdim			ic->ic_channels[i].ic_freq =
326218893Sdim			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
327218893Sdim			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
328218893Sdim		}
329218893Sdim		for (i = 100; i <= 140; i += 4) {
330193323Sed			ic->ic_channels[i].ic_freq =
331218893Sdim			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
332218893Sdim			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
333218893Sdim		}
334218893Sdim		for (i = 149; i <= 165; i += 4) {
335193323Sed			ic->ic_channels[i].ic_freq =
336218893Sdim			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
337218893Sdim			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
338218893Sdim		}
339193323Sed	}
340218893Sdim
341218893Sdim	/* set supported .11b and .11g rates */
342218893Sdim	ic->ic_sup_rates[IEEE80211_MODE_11B] = rt2661_rateset_11b;
343193323Sed	ic->ic_sup_rates[IEEE80211_MODE_11G] = rt2661_rateset_11g;
344218893Sdim
345218893Sdim	/* set supported .11b and .11g channels (1 through 14) */
346193323Sed	for (i = 1; i <= 14; i++) {
347218893Sdim		ic->ic_channels[i].ic_freq =
348218893Sdim		    ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
349234353Sdim		ic->ic_channels[i].ic_flags =
350218893Sdim		    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
351218893Sdim		    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
352263508Sdim	}
353212904Sdim
354218893Sdim	ieee80211_ifattach(ic);
355243830Sdim	ic->ic_node_alloc = rt2661_node_alloc;
356193323Sed/*	ic->ic_wme.wme_update = rt2661_wme_update;*/
357218893Sdim	ic->ic_updateslot = rt2661_update_slot;
358193323Sed	ic->ic_reset = rt2661_reset;
359218893Sdim	/* enable s/w bmiss handling in sta mode */
360234353Sdim	ic->ic_flags_ext |= IEEE80211_FEXT_SWBMISS;
361218893Sdim
362218893Sdim	/* override state transition machine */
363218893Sdim	sc->sc_newstate = ic->ic_newstate;
364218893Sdim	ic->ic_newstate = rt2661_newstate;
365218893Sdim	ieee80211_media_init(ic, rt2661_media_change, ieee80211_media_status);
366263508Sdim
367218893Sdim	bpfattach2(ifp, DLT_IEEE802_11_RADIO,
368218893Sdim	    sizeof (struct ieee80211_frame) + 64, &sc->sc_drvbpf);
369218893Sdim
370218893Sdim	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
371218893Sdim	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
372263508Sdim	sc->sc_rxtap.wr_ihdr.it_present = htole32(RT2661_RX_RADIOTAP_PRESENT);
373263508Sdim
374263508Sdim	sc->sc_txtap_len = sizeof sc->sc_txtapu;
375263508Sdim	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
376218893Sdim	sc->sc_txtap.wt_ihdr.it_present = htole32(RT2661_TX_RADIOTAP_PRESENT);
377218893Sdim
378218893Sdim	/*
379218893Sdim	 * Add a few sysctl knobs.
380218893Sdim	 */
381218893Sdim	sc->dwelltime = 200;
382218893Sdim
383203954Srdivacky	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
384193323Sed	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO, "dwell",
385234353Sdim	    CTLFLAG_RW, &sc->dwelltime, 0,
386218893Sdim	    "channel dwell time (ms) for AP/station scanning");
387218893Sdim
388218893Sdim	if (bootverbose)
389218893Sdim		ieee80211_announce(ic);
390218893Sdim
391193323Sed	return 0;
392251662Sdim
393218893Sdimfail4:	rt2661_free_rx_ring(sc, &sc->rxq);
394193323Sedfail3:	rt2661_free_tx_ring(sc, &sc->mgtq);
395218893Sdimfail2:	while (--ac >= 0)
396218893Sdim		rt2661_free_tx_ring(sc, &sc->txq[ac]);
397218893Sdimfail1:	mtx_destroy(&sc->sc_mtx);
398218893Sdim
399218893Sdim	return error;
400193323Sed}
401218893Sdim
402218893Sdimint
403218893Sdimrt2661_detach(void *xsc)
404218893Sdim{
405218893Sdim	struct rt2661_softc *sc = xsc;
406193323Sed	struct ieee80211com *ic = &sc->sc_ic;
407218893Sdim	struct ifnet *ifp = ic->ic_ifp;
408218893Sdim
409203954Srdivacky	rt2661_stop(sc);
410218893Sdim	callout_stop(&sc->scan_ch);
411218893Sdim	callout_stop(&sc->rssadapt_ch);
412218893Sdim
413218893Sdim	bpfdetach(ifp);
414193323Sed	ieee80211_ifdetach(ic);
415218893Sdim
416218893Sdim	rt2661_free_tx_ring(sc, &sc->txq[0]);
417234353Sdim	rt2661_free_tx_ring(sc, &sc->txq[1]);
418193323Sed	rt2661_free_tx_ring(sc, &sc->txq[2]);
419193323Sed	rt2661_free_tx_ring(sc, &sc->txq[3]);
420218893Sdim	rt2661_free_tx_ring(sc, &sc->mgtq);
421193323Sed	rt2661_free_rx_ring(sc, &sc->rxq);
422218893Sdim
423218893Sdim	if_free(ifp);
424234353Sdim
425234353Sdim	mtx_destroy(&sc->sc_mtx);
426234353Sdim
427218893Sdim	return 0;
428218893Sdim}
429218893Sdim
430243830Sdimvoid
431218893Sdimrt2661_shutdown(void *xsc)
432224145Sdim{
433224145Sdim	struct rt2661_softc *sc = xsc;
434218893Sdim
435218893Sdim	rt2661_stop(sc);
436263508Sdim}
437263508Sdim
438263508Sdimvoid
439263508Sdimrt2661_suspend(void *xsc)
440234353Sdim{
441234353Sdim	struct rt2661_softc *sc = xsc;
442218893Sdim
443243830Sdim	rt2661_stop(sc);
444218893Sdim}
445193323Sed
446193323Sedvoid
447218893Sdimrt2661_resume(void *xsc)
448193323Sed{
449193323Sed	struct rt2661_softc *sc = xsc;
450239462Sdim	struct ifnet *ifp = sc->sc_ic.ic_ifp;
451239462Sdim
452239462Sdim	if (ifp->if_flags & IFF_UP) {
453193323Sed		ifp->if_init(ifp->if_softc);
454239462Sdim		if (ifp->if_drv_flags & IFF_DRV_RUNNING)
455193323Sed			ifp->if_start(ifp);
456193323Sed	}
457193323Sed}
458193323Sed
459193323Sedstatic void
460218893Sdimrt2661_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
461218893Sdim{
462218893Sdim	if (error != 0)
463193323Sed		return;
464193323Sed
465193323Sed	KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
466193323Sed
467218893Sdim	*(bus_addr_t *)arg = segs[0].ds_addr;
468218893Sdim}
469193323Sed
470193323Sedstatic int
471193323Sedrt2661_alloc_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring,
472193323Sed    int count)
473193323Sed{
474193323Sed	int i, error;
475218893Sdim
476218893Sdim	ring->count = count;
477218893Sdim	ring->queued = 0;
478263508Sdim	ring->cur = ring->next = ring->stat = 0;
479263508Sdim
480263508Sdim	error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
481263508Sdim	    BUS_SPACE_MAXADDR, NULL, NULL, count * RT2661_TX_DESC_SIZE, 1,
482263508Sdim	    count * RT2661_TX_DESC_SIZE, 0, NULL, NULL, &ring->desc_dmat);
483193323Sed	if (error != 0) {
484218893Sdim		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
485234353Sdim		goto fail;
486239462Sdim	}
487239462Sdim
488218893Sdim	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
489234353Sdim	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
490218893Sdim	if (error != 0) {
491218893Sdim		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
492263508Sdim		goto fail;
493239462Sdim	}
494234353Sdim
495193323Sed	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
496239462Sdim	    count * RT2661_TX_DESC_SIZE, rt2661_dma_map_addr, &ring->physaddr,
497234353Sdim	    0);
498193323Sed	if (error != 0) {
499193323Sed		device_printf(sc->sc_dev, "could not load desc DMA map\n");
500193323Sed		goto fail;
501234353Sdim	}
502193323Sed
503263508Sdim	ring->data = malloc(count * sizeof (struct rt2661_tx_data), M_DEVBUF,
504263508Sdim	    M_NOWAIT | M_ZERO);
505263508Sdim	if (ring->data == NULL) {
506263508Sdim		device_printf(sc->sc_dev, "could not allocate soft data\n");
507193323Sed		error = ENOMEM;
508193323Sed		goto fail;
509202375Srdivacky	}
510193323Sed
511193323Sed	error = bus_dma_tag_create(NULL, 1, 0, BUS_SPACE_MAXADDR_32BIT,
512234353Sdim	    BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, RT2661_MAX_SCATTER,
513218893Sdim	    MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
514234353Sdim	if (error != 0) {
515193323Sed		device_printf(sc->sc_dev, "could not create data DMA tag\n");
516193323Sed		goto fail;
517193323Sed	}
518193323Sed
519193323Sed	for (i = 0; i < count; i++) {
520193323Sed		error = bus_dmamap_create(ring->data_dmat, 0,
521218893Sdim		    &ring->data[i].map);
522218893Sdim		if (error != 0) {
523193323Sed			device_printf(sc->sc_dev, "could not create DMA map\n");
524218893Sdim			goto fail;
525218893Sdim		}
526193323Sed	}
527218893Sdim
528193323Sed	return 0;
529249423Sdim
530198090Srdivackyfail:	rt2661_free_tx_ring(sc, ring);
531193323Sed	return error;
532193323Sed}
533224145Sdim
534193323Sedstatic void
535193323Sedrt2661_reset_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring)
536193323Sed{
537193323Sed	struct rt2661_tx_desc *desc;
538193323Sed	struct rt2661_tx_data *data;
539193323Sed	int i;
540218893Sdim
541193323Sed	for (i = 0; i < ring->count; i++) {
542193323Sed		desc = &ring->desc[i];
543193323Sed		data = &ring->data[i];
544193323Sed
545193323Sed		if (data->m != NULL) {
546234353Sdim			bus_dmamap_sync(ring->data_dmat, data->map,
547193323Sed			    BUS_DMASYNC_POSTWRITE);
548193323Sed			bus_dmamap_unload(ring->data_dmat, data->map);
549193323Sed			m_freem(data->m);
550263508Sdim			data->m = NULL;
551193323Sed		}
552263508Sdim
553263508Sdim		if (data->ni != NULL) {
554263508Sdim			ieee80211_free_node(data->ni);
555193323Sed			data->ni = NULL;
556234353Sdim		}
557193323Sed
558234353Sdim		desc->flags = 0;
559212904Sdim	}
560243830Sdim
561193323Sed	bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
562193323Sed
563193323Sed	ring->queued = 0;
564193323Sed	ring->cur = ring->next = ring->stat = 0;
565193323Sed}
566193323Sed
567193323Sedstatic void
568193323Sedrt2661_free_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring)
569193323Sed{
570193323Sed	struct rt2661_tx_data *data;
571193323Sed	int i;
572193323Sed
573193323Sed	if (ring->desc != NULL) {
574243830Sdim		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
575234353Sdim		    BUS_DMASYNC_POSTWRITE);
576234353Sdim		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
577234353Sdim		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
578234353Sdim	}
579243830Sdim
580234353Sdim	if (ring->desc_dmat != NULL)
581193323Sed		bus_dma_tag_destroy(ring->desc_dmat);
582218893Sdim
583193323Sed	if (ring->data != NULL) {
584193323Sed		for (i = 0; i < ring->count; i++) {
585193323Sed			data = &ring->data[i];
586193323Sed
587193323Sed			if (data->m != NULL) {
588202375Srdivacky				bus_dmamap_sync(ring->data_dmat, data->map,
589193323Sed				    BUS_DMASYNC_POSTWRITE);
590251662Sdim				bus_dmamap_unload(ring->data_dmat, data->map);
591263508Sdim				m_freem(data->m);
592234353Sdim			}
593234353Sdim
594234353Sdim			if (data->ni != NULL)
595234353Sdim				ieee80211_free_node(data->ni);
596234353Sdim
597234353Sdim			if (data->map != NULL)
598234353Sdim				bus_dmamap_destroy(ring->data_dmat, data->map);
599234353Sdim		}
600234353Sdim
601234353Sdim		free(ring->data, M_DEVBUF);
602234353Sdim	}
603234353Sdim
604234353Sdim	if (ring->data_dmat != NULL)
605234353Sdim		bus_dma_tag_destroy(ring->data_dmat);
606203954Srdivacky}
607218893Sdim
608218893Sdimstatic int
609193323Sedrt2661_alloc_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring,
610218893Sdim    int count)
611193323Sed{
612193323Sed	struct rt2661_rx_desc *desc;
613193323Sed	struct rt2661_rx_data *data;
614193323Sed	bus_addr_t physaddr;
615193323Sed	int i, error;
616193323Sed
617193323Sed	ring->count = count;
618218893Sdim	ring->cur = ring->next = 0;
619218893Sdim
620193323Sed	error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
621202375Srdivacky	    BUS_SPACE_MAXADDR, NULL, NULL, count * RT2661_RX_DESC_SIZE, 1,
622193323Sed	    count * RT2661_RX_DESC_SIZE, 0, NULL, NULL, &ring->desc_dmat);
623193323Sed	if (error != 0) {
624193323Sed		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
625193323Sed		goto fail;
626218893Sdim	}
627251662Sdim
628224145Sdim	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
629224145Sdim	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
630193323Sed	if (error != 0) {
631193323Sed		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
632218893Sdim		goto fail;
633251662Sdim	}
634251662Sdim
635251662Sdim	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
636251662Sdim	    count * RT2661_RX_DESC_SIZE, rt2661_dma_map_addr, &ring->physaddr,
637251662Sdim	    0);
638251662Sdim	if (error != 0) {
639218893Sdim		device_printf(sc->sc_dev, "could not load desc DMA map\n");
640193323Sed		goto fail;
641193323Sed	}
642
643	ring->data = malloc(count * sizeof (struct rt2661_rx_data), M_DEVBUF,
644	    M_NOWAIT | M_ZERO);
645	if (ring->data == NULL) {
646		device_printf(sc->sc_dev, "could not allocate soft data\n");
647		error = ENOMEM;
648		goto fail;
649	}
650
651	/*
652	 * Pre-allocate Rx buffers and populate Rx ring.
653	 */
654	error = bus_dma_tag_create(NULL, 1, 0, BUS_SPACE_MAXADDR_32BIT,
655	    BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1, MCLBYTES, 0, NULL,
656	    NULL, &ring->data_dmat);
657	if (error != 0) {
658		device_printf(sc->sc_dev, "could not create data DMA tag\n");
659		goto fail;
660	}
661
662	for (i = 0; i < count; i++) {
663		desc = &sc->rxq.desc[i];
664		data = &sc->rxq.data[i];
665
666		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
667		if (error != 0) {
668			device_printf(sc->sc_dev, "could not create DMA map\n");
669			goto fail;
670		}
671
672		data->m = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
673		if (data->m == NULL) {
674			device_printf(sc->sc_dev,
675			    "could not allocate rx mbuf\n");
676			error = ENOMEM;
677			goto fail;
678		}
679
680		error = bus_dmamap_load(ring->data_dmat, data->map,
681		    mtod(data->m, void *), MCLBYTES, rt2661_dma_map_addr,
682		    &physaddr, 0);
683		if (error != 0) {
684			device_printf(sc->sc_dev,
685			    "could not load rx buf DMA map");
686			goto fail;
687		}
688
689		desc->flags = htole32(RT2661_RX_BUSY);
690		desc->physaddr = htole32(physaddr);
691	}
692
693	bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
694
695	return 0;
696
697fail:	rt2661_free_rx_ring(sc, ring);
698	return error;
699}
700
701static void
702rt2661_reset_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring)
703{
704	int i;
705
706	for (i = 0; i < ring->count; i++)
707		ring->desc[i].flags = htole32(RT2661_RX_BUSY);
708
709	bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
710
711	ring->cur = ring->next = 0;
712}
713
714static void
715rt2661_free_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring)
716{
717	struct rt2661_rx_data *data;
718	int i;
719
720	if (ring->desc != NULL) {
721		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
722		    BUS_DMASYNC_POSTWRITE);
723		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
724		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
725	}
726
727	if (ring->desc_dmat != NULL)
728		bus_dma_tag_destroy(ring->desc_dmat);
729
730	if (ring->data != NULL) {
731		for (i = 0; i < ring->count; i++) {
732			data = &ring->data[i];
733
734			if (data->m != NULL) {
735				bus_dmamap_sync(ring->data_dmat, data->map,
736				    BUS_DMASYNC_POSTREAD);
737				bus_dmamap_unload(ring->data_dmat, data->map);
738				m_freem(data->m);
739			}
740
741			if (data->map != NULL)
742				bus_dmamap_destroy(ring->data_dmat, data->map);
743		}
744
745		free(ring->data, M_DEVBUF);
746	}
747
748	if (ring->data_dmat != NULL)
749		bus_dma_tag_destroy(ring->data_dmat);
750}
751
752static struct ieee80211_node *
753rt2661_node_alloc(struct ieee80211_node_table *nt)
754{
755	struct rt2661_node *rn;
756
757	rn = malloc(sizeof (struct rt2661_node), M_80211_NODE,
758	    M_NOWAIT | M_ZERO);
759
760	return (rn != NULL) ? &rn->ni : NULL;
761}
762
763static int
764rt2661_media_change(struct ifnet *ifp)
765{
766	struct rt2661_softc *sc = ifp->if_softc;
767	int error;
768
769	error = ieee80211_media_change(ifp);
770	if (error != ENETRESET)
771		return error;
772
773	if ((ifp->if_flags & IFF_UP) && (ifp->if_drv_flags & IFF_DRV_RUNNING))
774		rt2661_init(sc);
775
776	return 0;
777}
778
779/*
780 * This function is called periodically (every 200ms) during scanning to
781 * switch from one channel to another.
782 */
783static void
784rt2661_next_scan(void *arg)
785{
786	struct rt2661_softc *sc = arg;
787	struct ieee80211com *ic = &sc->sc_ic;
788
789	if (ic->ic_state == IEEE80211_S_SCAN)
790		ieee80211_next_scan(ic);
791}
792
793/*
794 * This function is called for each node present in the node station table.
795 */
796static void
797rt2661_iter_func(void *arg, struct ieee80211_node *ni)
798{
799	struct rt2661_node *rn = (struct rt2661_node *)ni;
800
801	ral_rssadapt_updatestats(&rn->rssadapt);
802}
803
804/*
805 * This function is called periodically (every 100ms) in RUN state to update
806 * the rate adaptation statistics.
807 */
808static void
809rt2661_update_rssadapt(void *arg)
810{
811	struct rt2661_softc *sc = arg;
812	struct ieee80211com *ic = &sc->sc_ic;
813
814	RAL_LOCK(sc);
815
816	ieee80211_iterate_nodes(&ic->ic_sta, rt2661_iter_func, arg);
817	callout_reset(&sc->rssadapt_ch, hz / 10, rt2661_update_rssadapt, sc);
818
819	RAL_UNLOCK(sc);
820}
821
822static int
823rt2661_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
824{
825	struct rt2661_softc *sc = ic->ic_ifp->if_softc;
826	enum ieee80211_state ostate;
827	struct ieee80211_node *ni;
828	uint32_t tmp;
829	int error = 0;
830
831	ostate = ic->ic_state;
832	callout_stop(&sc->scan_ch);
833
834	switch (nstate) {
835	case IEEE80211_S_INIT:
836		callout_stop(&sc->rssadapt_ch);
837
838		if (ostate == IEEE80211_S_RUN) {
839			/* abort TSF synchronization */
840			tmp = RAL_READ(sc, RT2661_TXRX_CSR9);
841			RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp & ~0x00ffffff);
842		}
843		break;
844
845	case IEEE80211_S_SCAN:
846		rt2661_set_chan(sc, ic->ic_curchan);
847		callout_reset(&sc->scan_ch, (sc->dwelltime * hz) / 1000,
848		    rt2661_next_scan, sc);
849		break;
850
851	case IEEE80211_S_AUTH:
852	case IEEE80211_S_ASSOC:
853		rt2661_set_chan(sc, ic->ic_curchan);
854		break;
855
856	case IEEE80211_S_RUN:
857		rt2661_set_chan(sc, ic->ic_curchan);
858
859		ni = ic->ic_bss;
860
861		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
862			rt2661_enable_mrr(sc);
863			rt2661_set_txpreamble(sc);
864			rt2661_set_basicrates(sc, &ni->ni_rates);
865			rt2661_set_bssid(sc, ni->ni_bssid);
866		}
867
868		if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
869		    ic->ic_opmode == IEEE80211_M_IBSS) {
870			if ((error = rt2661_prepare_beacon(sc)) != 0)
871				break;
872		}
873
874		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
875			callout_reset(&sc->rssadapt_ch, hz / 10,
876			    rt2661_update_rssadapt, sc);
877			rt2661_enable_tsf_sync(sc);
878		}
879		break;
880	}
881
882	return (error != 0) ? error : sc->sc_newstate(ic, nstate, arg);
883}
884
885/*
886 * Read 16 bits at address 'addr' from the serial EEPROM (either 93C46 or
887 * 93C66).
888 */
889static uint16_t
890rt2661_eeprom_read(struct rt2661_softc *sc, uint8_t addr)
891{
892	uint32_t tmp;
893	uint16_t val;
894	int n;
895
896	/* clock C once before the first command */
897	RT2661_EEPROM_CTL(sc, 0);
898
899	RT2661_EEPROM_CTL(sc, RT2661_S);
900	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
901	RT2661_EEPROM_CTL(sc, RT2661_S);
902
903	/* write start bit (1) */
904	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
905	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
906
907	/* write READ opcode (10) */
908	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
909	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
910	RT2661_EEPROM_CTL(sc, RT2661_S);
911	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
912
913	/* write address (A5-A0 or A7-A0) */
914	n = (RAL_READ(sc, RT2661_E2PROM_CSR) & RT2661_93C46) ? 5 : 7;
915	for (; n >= 0; n--) {
916		RT2661_EEPROM_CTL(sc, RT2661_S |
917		    (((addr >> n) & 1) << RT2661_SHIFT_D));
918		RT2661_EEPROM_CTL(sc, RT2661_S |
919		    (((addr >> n) & 1) << RT2661_SHIFT_D) | RT2661_C);
920	}
921
922	RT2661_EEPROM_CTL(sc, RT2661_S);
923
924	/* read data Q15-Q0 */
925	val = 0;
926	for (n = 15; n >= 0; n--) {
927		RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
928		tmp = RAL_READ(sc, RT2661_E2PROM_CSR);
929		val |= ((tmp & RT2661_Q) >> RT2661_SHIFT_Q) << n;
930		RT2661_EEPROM_CTL(sc, RT2661_S);
931	}
932
933	RT2661_EEPROM_CTL(sc, 0);
934
935	/* clear Chip Select and clock C */
936	RT2661_EEPROM_CTL(sc, RT2661_S);
937	RT2661_EEPROM_CTL(sc, 0);
938	RT2661_EEPROM_CTL(sc, RT2661_C);
939
940	return val;
941}
942
943static void
944rt2661_tx_intr(struct rt2661_softc *sc)
945{
946	struct ieee80211com *ic = &sc->sc_ic;
947	struct ifnet *ifp = ic->ic_ifp;
948	struct rt2661_tx_ring *txq;
949	struct rt2661_tx_data *data;
950	struct rt2661_node *rn;
951	uint32_t val;
952	int qid, retrycnt;
953
954	for (;;) {
955		val = RAL_READ(sc, RT2661_STA_CSR4);
956		if (!(val & RT2661_TX_STAT_VALID))
957			break;
958
959		/* retrieve the queue in which this frame was sent */
960		qid = RT2661_TX_QID(val);
961		txq = (qid <= 3) ? &sc->txq[qid] : &sc->mgtq;
962
963		/* retrieve rate control algorithm context */
964		data = &txq->data[txq->stat];
965		rn = (struct rt2661_node *)data->ni;
966
967		/* if no frame has been sent, ignore */
968		if (rn == NULL)
969			continue;
970
971		switch (RT2661_TX_RESULT(val)) {
972		case RT2661_TX_SUCCESS:
973			retrycnt = RT2661_TX_RETRYCNT(val);
974
975			DPRINTFN(10, ("data frame sent successfully after "
976			    "%d retries\n", retrycnt));
977			if (retrycnt == 0 && data->id.id_node != NULL) {
978				ral_rssadapt_raise_rate(ic, &rn->rssadapt,
979				    &data->id);
980			}
981			ifp->if_opackets++;
982			break;
983
984		case RT2661_TX_RETRY_FAIL:
985			DPRINTFN(9, ("sending data frame failed (too much "
986			    "retries)\n"));
987			if (data->id.id_node != NULL) {
988				ral_rssadapt_lower_rate(ic, data->ni,
989				    &rn->rssadapt, &data->id);
990			}
991			ifp->if_oerrors++;
992			break;
993
994		default:
995			/* other failure */
996			device_printf(sc->sc_dev,
997			    "sending data frame failed 0x%08x\n", val);
998			ifp->if_oerrors++;
999		}
1000
1001		ieee80211_free_node(data->ni);
1002		data->ni = NULL;
1003
1004		DPRINTFN(15, ("tx done q=%d idx=%u\n", qid, txq->stat));
1005
1006		txq->queued--;
1007		if (++txq->stat >= txq->count)	/* faster than % count */
1008			txq->stat = 0;
1009	}
1010
1011	sc->sc_tx_timer = 0;
1012	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
1013	rt2661_start(ifp);
1014}
1015
1016static void
1017rt2661_tx_dma_intr(struct rt2661_softc *sc, struct rt2661_tx_ring *txq)
1018{
1019	struct rt2661_tx_desc *desc;
1020	struct rt2661_tx_data *data;
1021
1022	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_POSTREAD);
1023
1024	for (;;) {
1025		desc = &txq->desc[txq->next];
1026		data = &txq->data[txq->next];
1027
1028		if ((le32toh(desc->flags) & RT2661_TX_BUSY) ||
1029		    !(le32toh(desc->flags) & RT2661_TX_VALID))
1030			break;
1031
1032		bus_dmamap_sync(txq->data_dmat, data->map,
1033		    BUS_DMASYNC_POSTWRITE);
1034		bus_dmamap_unload(txq->data_dmat, data->map);
1035		m_freem(data->m);
1036		data->m = NULL;
1037		/* node reference is released in rt2661_tx_intr() */
1038
1039		/* descriptor is no longer valid */
1040		desc->flags &= ~htole32(RT2661_TX_VALID);
1041
1042		DPRINTFN(15, ("tx dma done q=%p idx=%u\n", txq, txq->next));
1043
1044		if (++txq->next >= txq->count)	/* faster than % count */
1045			txq->next = 0;
1046	}
1047
1048	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1049}
1050
1051static void
1052rt2661_rx_intr(struct rt2661_softc *sc)
1053{
1054	struct ieee80211com *ic = &sc->sc_ic;
1055	struct ifnet *ifp = ic->ic_ifp;
1056	struct rt2661_rx_desc *desc;
1057	struct rt2661_rx_data *data;
1058	bus_addr_t physaddr;
1059	struct ieee80211_frame *wh;
1060	struct ieee80211_node *ni;
1061	struct rt2661_node *rn;
1062	struct mbuf *mnew, *m;
1063	int error;
1064
1065	bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1066	    BUS_DMASYNC_POSTREAD);
1067
1068	for (;;) {
1069		desc = &sc->rxq.desc[sc->rxq.cur];
1070		data = &sc->rxq.data[sc->rxq.cur];
1071
1072		if (le32toh(desc->flags) & RT2661_RX_BUSY)
1073			break;
1074
1075		if ((le32toh(desc->flags) & RT2661_RX_PHY_ERROR) ||
1076		    (le32toh(desc->flags) & RT2661_RX_CRC_ERROR)) {
1077			/*
1078			 * This should not happen since we did not request
1079			 * to receive those frames when we filled TXRX_CSR0.
1080			 */
1081			DPRINTFN(5, ("PHY or CRC error flags 0x%08x\n",
1082			    le32toh(desc->flags)));
1083			ifp->if_ierrors++;
1084			goto skip;
1085		}
1086
1087		if ((le32toh(desc->flags) & RT2661_RX_CIPHER_MASK) != 0) {
1088			ifp->if_ierrors++;
1089			goto skip;
1090		}
1091
1092		/*
1093		 * Try to allocate a new mbuf for this ring element and load it
1094		 * before processing the current mbuf. If the ring element
1095		 * cannot be loaded, drop the received packet and reuse the old
1096		 * mbuf. In the unlikely case that the old mbuf can't be
1097		 * reloaded either, explicitly panic.
1098		 */
1099		mnew = m_getcl(M_DONTWAIT, MT_DATA, M_PKTHDR);
1100		if (mnew == NULL) {
1101			ifp->if_ierrors++;
1102			goto skip;
1103		}
1104
1105		bus_dmamap_sync(sc->rxq.data_dmat, data->map,
1106		    BUS_DMASYNC_POSTREAD);
1107		bus_dmamap_unload(sc->rxq.data_dmat, data->map);
1108
1109		error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1110		    mtod(mnew, void *), MCLBYTES, rt2661_dma_map_addr,
1111		    &physaddr, 0);
1112		if (error != 0) {
1113			m_freem(mnew);
1114
1115			/* try to reload the old mbuf */
1116			error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1117			    mtod(data->m, void *), MCLBYTES,
1118			    rt2661_dma_map_addr, &physaddr, 0);
1119			if (error != 0) {
1120				/* very unlikely that it will fail... */
1121				panic("%s: could not load old rx mbuf",
1122				    device_get_name(sc->sc_dev));
1123			}
1124			ifp->if_ierrors++;
1125			goto skip;
1126		}
1127
1128		/*
1129	 	 * New mbuf successfully loaded, update Rx ring and continue
1130		 * processing.
1131		 */
1132		m = data->m;
1133		data->m = mnew;
1134		desc->physaddr = htole32(physaddr);
1135
1136		/* finalize mbuf */
1137		m->m_pkthdr.rcvif = ifp;
1138		m->m_pkthdr.len = m->m_len =
1139		    (le32toh(desc->flags) >> 16) & 0xfff;
1140
1141		if (bpf_peers_present(sc->sc_drvbpf)) {
1142			struct rt2661_rx_radiotap_header *tap = &sc->sc_rxtap;
1143			uint32_t tsf_lo, tsf_hi;
1144
1145			/* get timestamp (low and high 32 bits) */
1146			tsf_hi = RAL_READ(sc, RT2661_TXRX_CSR13);
1147			tsf_lo = RAL_READ(sc, RT2661_TXRX_CSR12);
1148
1149			tap->wr_tsf =
1150			    htole64(((uint64_t)tsf_hi << 32) | tsf_lo);
1151			tap->wr_flags = 0;
1152			tap->wr_rate = rt2661_rxrate(desc);
1153			tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
1154			tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
1155			tap->wr_antsignal = desc->rssi;
1156
1157			bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_rxtap_len, m);
1158		}
1159
1160		wh = mtod(m, struct ieee80211_frame *);
1161		ni = ieee80211_find_rxnode(ic,
1162		    (struct ieee80211_frame_min *)wh);
1163
1164		/* send the frame to the 802.11 layer */
1165		ieee80211_input(ic, m, ni, desc->rssi, 0);
1166
1167		/* give rssi to the rate adatation algorithm */
1168		rn = (struct rt2661_node *)ni;
1169		ral_rssadapt_input(ic, ni, &rn->rssadapt,
1170		    rt2661_get_rssi(sc, desc->rssi));
1171
1172		/* node is no longer needed */
1173		ieee80211_free_node(ni);
1174
1175skip:		desc->flags |= htole32(RT2661_RX_BUSY);
1176
1177		DPRINTFN(15, ("rx intr idx=%u\n", sc->rxq.cur));
1178
1179		sc->rxq.cur = (sc->rxq.cur + 1) % RT2661_RX_RING_COUNT;
1180	}
1181
1182	bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1183	    BUS_DMASYNC_PREWRITE);
1184}
1185
1186/* ARGSUSED */
1187static void
1188rt2661_mcu_beacon_expire(struct rt2661_softc *sc)
1189{
1190	/* do nothing */
1191}
1192
1193static void
1194rt2661_mcu_wakeup(struct rt2661_softc *sc)
1195{
1196	RAL_WRITE(sc, RT2661_MAC_CSR11, 5 << 16);
1197
1198	RAL_WRITE(sc, RT2661_SOFT_RESET_CSR, 0x7);
1199	RAL_WRITE(sc, RT2661_IO_CNTL_CSR, 0x18);
1200	RAL_WRITE(sc, RT2661_PCI_USEC_CSR, 0x20);
1201
1202	/* send wakeup command to MCU */
1203	rt2661_tx_cmd(sc, RT2661_MCU_CMD_WAKEUP, 0);
1204}
1205
1206static void
1207rt2661_mcu_cmd_intr(struct rt2661_softc *sc)
1208{
1209	RAL_READ(sc, RT2661_M2H_CMD_DONE_CSR);
1210	RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
1211}
1212
1213void
1214rt2661_intr(void *arg)
1215{
1216	struct rt2661_softc *sc = arg;
1217	struct ifnet *ifp = sc->sc_ifp;
1218	uint32_t r1, r2;
1219
1220	RAL_LOCK(sc);
1221
1222	/* disable MAC and MCU interrupts */
1223	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffff7f);
1224	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
1225
1226	/* don't re-enable interrupts if we're shutting down */
1227	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
1228		RAL_UNLOCK(sc);
1229		return;
1230	}
1231
1232	r1 = RAL_READ(sc, RT2661_INT_SOURCE_CSR);
1233	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, r1);
1234
1235	r2 = RAL_READ(sc, RT2661_MCU_INT_SOURCE_CSR);
1236	RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, r2);
1237
1238	if (r1 & RT2661_MGT_DONE)
1239		rt2661_tx_dma_intr(sc, &sc->mgtq);
1240
1241	if (r1 & RT2661_RX_DONE)
1242		rt2661_rx_intr(sc);
1243
1244	if (r1 & RT2661_TX0_DMA_DONE)
1245		rt2661_tx_dma_intr(sc, &sc->txq[0]);
1246
1247	if (r1 & RT2661_TX1_DMA_DONE)
1248		rt2661_tx_dma_intr(sc, &sc->txq[1]);
1249
1250	if (r1 & RT2661_TX2_DMA_DONE)
1251		rt2661_tx_dma_intr(sc, &sc->txq[2]);
1252
1253	if (r1 & RT2661_TX3_DMA_DONE)
1254		rt2661_tx_dma_intr(sc, &sc->txq[3]);
1255
1256	if (r1 & RT2661_TX_DONE)
1257		rt2661_tx_intr(sc);
1258
1259	if (r2 & RT2661_MCU_CMD_DONE)
1260		rt2661_mcu_cmd_intr(sc);
1261
1262	if (r2 & RT2661_MCU_BEACON_EXPIRE)
1263		rt2661_mcu_beacon_expire(sc);
1264
1265	if (r2 & RT2661_MCU_WAKEUP)
1266		rt2661_mcu_wakeup(sc);
1267
1268	/* re-enable MAC and MCU interrupts */
1269	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
1270	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
1271
1272	RAL_UNLOCK(sc);
1273}
1274
1275/* quickly determine if a given rate is CCK or OFDM */
1276#define RAL_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
1277
1278#define RAL_ACK_SIZE	14	/* 10 + 4(FCS) */
1279#define RAL_CTS_SIZE	14	/* 10 + 4(FCS) */
1280
1281#define RAL_SIFS	10	/* us */
1282
1283/*
1284 * This function is only used by the Rx radiotap code. It returns the rate at
1285 * which a given frame was received.
1286 */
1287static uint8_t
1288rt2661_rxrate(struct rt2661_rx_desc *desc)
1289{
1290	if (le32toh(desc->flags) & RT2661_RX_OFDM) {
1291		/* reverse function of rt2661_plcp_signal */
1292		switch (desc->rate & 0xf) {
1293		case 0xb:	return 12;
1294		case 0xf:	return 18;
1295		case 0xa:	return 24;
1296		case 0xe:	return 36;
1297		case 0x9:	return 48;
1298		case 0xd:	return 72;
1299		case 0x8:	return 96;
1300		case 0xc:	return 108;
1301		}
1302	} else {
1303		if (desc->rate == 10)
1304			return 2;
1305		if (desc->rate == 20)
1306			return 4;
1307		if (desc->rate == 55)
1308			return 11;
1309		if (desc->rate == 110)
1310			return 22;
1311	}
1312	return 2;	/* should not get there */
1313}
1314
1315/*
1316 * Return the expected ack rate for a frame transmitted at rate `rate'.
1317 * XXX: this should depend on the destination node basic rate set.
1318 */
1319static int
1320rt2661_ack_rate(struct ieee80211com *ic, int rate)
1321{
1322	switch (rate) {
1323	/* CCK rates */
1324	case 2:
1325		return 2;
1326	case 4:
1327	case 11:
1328	case 22:
1329		return (ic->ic_curmode == IEEE80211_MODE_11B) ? 4 : rate;
1330
1331	/* OFDM rates */
1332	case 12:
1333	case 18:
1334		return 12;
1335	case 24:
1336	case 36:
1337		return 24;
1338	case 48:
1339	case 72:
1340	case 96:
1341	case 108:
1342		return 48;
1343	}
1344
1345	/* default to 1Mbps */
1346	return 2;
1347}
1348
1349/*
1350 * Compute the duration (in us) needed to transmit `len' bytes at rate `rate'.
1351 * The function automatically determines the operating mode depending on the
1352 * given rate. `flags' indicates whether short preamble is in use or not.
1353 */
1354static uint16_t
1355rt2661_txtime(int len, int rate, uint32_t flags)
1356{
1357	uint16_t txtime;
1358
1359	if (RAL_RATE_IS_OFDM(rate)) {
1360		/* IEEE Std 802.11a-1999, pp. 37 */
1361		txtime = (8 + 4 * len + 3 + rate - 1) / rate;
1362		txtime = 16 + 4 + 4 * txtime + 6;
1363	} else {
1364		/* IEEE Std 802.11b-1999, pp. 28 */
1365		txtime = (16 * len + rate - 1) / rate;
1366		if (rate != 2 && (flags & IEEE80211_F_SHPREAMBLE))
1367			txtime +=  72 + 24;
1368		else
1369			txtime += 144 + 48;
1370	}
1371
1372	return txtime;
1373}
1374
1375static uint8_t
1376rt2661_plcp_signal(int rate)
1377{
1378	switch (rate) {
1379	/* CCK rates (returned values are device-dependent) */
1380	case 2:		return 0x0;
1381	case 4:		return 0x1;
1382	case 11:	return 0x2;
1383	case 22:	return 0x3;
1384
1385	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1386	case 12:	return 0xb;
1387	case 18:	return 0xf;
1388	case 24:	return 0xa;
1389	case 36:	return 0xe;
1390	case 48:	return 0x9;
1391	case 72:	return 0xd;
1392	case 96:	return 0x8;
1393	case 108:	return 0xc;
1394
1395	/* unsupported rates (should not get there) */
1396	default:	return 0xff;
1397	}
1398}
1399
1400static void
1401rt2661_setup_tx_desc(struct rt2661_softc *sc, struct rt2661_tx_desc *desc,
1402    uint32_t flags, uint16_t xflags, int len, int rate,
1403    const bus_dma_segment_t *segs, int nsegs, int ac)
1404{
1405	struct ieee80211com *ic = &sc->sc_ic;
1406	uint16_t plcp_length;
1407	int i, remainder;
1408
1409	desc->flags = htole32(flags);
1410	desc->flags |= htole32(len << 16);
1411	desc->flags |= htole32(RT2661_TX_BUSY | RT2661_TX_VALID);
1412
1413	desc->xflags = htole16(xflags);
1414	desc->xflags |= htole16(nsegs << 13);
1415
1416	desc->wme = htole16(
1417	    RT2661_QID(ac) |
1418	    RT2661_AIFSN(2) |
1419	    RT2661_LOGCWMIN(4) |
1420	    RT2661_LOGCWMAX(10));
1421
1422	/*
1423	 * Remember in which queue this frame was sent. This field is driver
1424	 * private data only. It will be made available by the NIC in STA_CSR4
1425	 * on Tx interrupts.
1426	 */
1427	desc->qid = ac;
1428
1429	/* setup PLCP fields */
1430	desc->plcp_signal  = rt2661_plcp_signal(rate);
1431	desc->plcp_service = 4;
1432
1433	len += IEEE80211_CRC_LEN;
1434	if (RAL_RATE_IS_OFDM(rate)) {
1435		desc->flags |= htole32(RT2661_TX_OFDM);
1436
1437		plcp_length = len & 0xfff;
1438		desc->plcp_length_hi = plcp_length >> 6;
1439		desc->plcp_length_lo = plcp_length & 0x3f;
1440	} else {
1441		plcp_length = (16 * len + rate - 1) / rate;
1442		if (rate == 22) {
1443			remainder = (16 * len) % 22;
1444			if (remainder != 0 && remainder < 7)
1445				desc->plcp_service |= RT2661_PLCP_LENGEXT;
1446		}
1447		desc->plcp_length_hi = plcp_length >> 8;
1448		desc->plcp_length_lo = plcp_length & 0xff;
1449
1450		if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1451			desc->plcp_signal |= 0x08;
1452	}
1453
1454	/* RT2x61 supports scatter with up to 5 segments */
1455	for (i = 0; i < nsegs; i++) {
1456		desc->addr[i] = htole32(segs[i].ds_addr);
1457		desc->len [i] = htole16(segs[i].ds_len);
1458	}
1459}
1460
1461static int
1462rt2661_tx_mgt(struct rt2661_softc *sc, struct mbuf *m0,
1463    struct ieee80211_node *ni)
1464{
1465	struct ieee80211com *ic = &sc->sc_ic;
1466	struct rt2661_tx_desc *desc;
1467	struct rt2661_tx_data *data;
1468	struct ieee80211_frame *wh;
1469	bus_dma_segment_t segs[RT2661_MAX_SCATTER];
1470	uint16_t dur;
1471	uint32_t flags = 0;	/* XXX HWSEQ */
1472	int nsegs, rate, error;
1473
1474	desc = &sc->mgtq.desc[sc->mgtq.cur];
1475	data = &sc->mgtq.data[sc->mgtq.cur];
1476
1477	/* send mgt frames at the lowest available rate */
1478	rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1479
1480	error = bus_dmamap_load_mbuf_sg(sc->mgtq.data_dmat, data->map, m0,
1481	    segs, &nsegs, 0);
1482	if (error != 0) {
1483		device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1484		    error);
1485		m_freem(m0);
1486		return error;
1487	}
1488
1489	if (bpf_peers_present(sc->sc_drvbpf)) {
1490		struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1491
1492		tap->wt_flags = 0;
1493		tap->wt_rate = rate;
1494		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1495		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1496
1497		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
1498	}
1499
1500	data->m = m0;
1501	data->ni = ni;
1502
1503	wh = mtod(m0, struct ieee80211_frame *);
1504
1505	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1506		flags |= RT2661_TX_NEED_ACK;
1507
1508		dur = rt2661_txtime(RAL_ACK_SIZE, rate, ic->ic_flags) +
1509		    RAL_SIFS;
1510		*(uint16_t *)wh->i_dur = htole16(dur);
1511
1512		/* tell hardware to add timestamp in probe responses */
1513		if ((wh->i_fc[0] &
1514		    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1515		    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1516			flags |= RT2661_TX_TIMESTAMP;
1517	}
1518
1519	rt2661_setup_tx_desc(sc, desc, flags, 0 /* XXX HWSEQ */,
1520	    m0->m_pkthdr.len, rate, segs, nsegs, RT2661_QID_MGT);
1521
1522	bus_dmamap_sync(sc->mgtq.data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1523	bus_dmamap_sync(sc->mgtq.desc_dmat, sc->mgtq.desc_map,
1524	    BUS_DMASYNC_PREWRITE);
1525
1526	DPRINTFN(10, ("sending mgt frame len=%u idx=%u rate=%u\n",
1527	    m0->m_pkthdr.len, sc->mgtq.cur, rate));
1528
1529	/* kick mgt */
1530	sc->mgtq.queued++;
1531	sc->mgtq.cur = (sc->mgtq.cur + 1) % RT2661_MGT_RING_COUNT;
1532	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, RT2661_KICK_MGT);
1533
1534	return 0;
1535}
1536
1537/*
1538 * Build a RTS control frame.
1539 */
1540static struct mbuf *
1541rt2661_get_rts(struct rt2661_softc *sc, struct ieee80211_frame *wh,
1542    uint16_t dur)
1543{
1544	struct ieee80211_frame_rts *rts;
1545	struct mbuf *m;
1546
1547	MGETHDR(m, M_DONTWAIT, MT_DATA);
1548	if (m == NULL) {
1549		sc->sc_ic.ic_stats.is_tx_nobuf++;
1550		device_printf(sc->sc_dev, "could not allocate RTS frame\n");
1551		return NULL;
1552	}
1553
1554	rts = mtod(m, struct ieee80211_frame_rts *);
1555
1556	rts->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_CTL |
1557	    IEEE80211_FC0_SUBTYPE_RTS;
1558	rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1559	*(uint16_t *)rts->i_dur = htole16(dur);
1560	IEEE80211_ADDR_COPY(rts->i_ra, wh->i_addr1);
1561	IEEE80211_ADDR_COPY(rts->i_ta, wh->i_addr2);
1562
1563	m->m_pkthdr.len = m->m_len = sizeof (struct ieee80211_frame_rts);
1564
1565	return m;
1566}
1567
1568static int
1569rt2661_tx_data(struct rt2661_softc *sc, struct mbuf *m0,
1570    struct ieee80211_node *ni, int ac)
1571{
1572	struct ieee80211com *ic = &sc->sc_ic;
1573	struct rt2661_tx_ring *txq = &sc->txq[ac];
1574	struct rt2661_tx_desc *desc;
1575	struct rt2661_tx_data *data;
1576	struct rt2661_node *rn;
1577	struct ieee80211_rateset *rs;
1578	struct ieee80211_frame *wh;
1579	struct ieee80211_key *k;
1580	const struct chanAccParams *cap;
1581	struct mbuf *mnew;
1582	bus_dma_segment_t segs[RT2661_MAX_SCATTER];
1583	uint16_t dur;
1584	uint32_t flags = 0;
1585	int error, nsegs, rate, noack = 0;
1586
1587	wh = mtod(m0, struct ieee80211_frame *);
1588
1589	if (ic->ic_fixed_rate != IEEE80211_FIXED_RATE_NONE) {
1590		rs = &ic->ic_sup_rates[ic->ic_curmode];
1591		rate = rs->rs_rates[ic->ic_fixed_rate];
1592	} else {
1593		rs = &ni->ni_rates;
1594		rn = (struct rt2661_node *)ni;
1595		ni->ni_txrate = ral_rssadapt_choose(&rn->rssadapt, rs,
1596		    wh, m0->m_pkthdr.len, NULL, 0);
1597		rate = rs->rs_rates[ni->ni_txrate];
1598	}
1599	rate &= IEEE80211_RATE_VAL;
1600
1601	if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
1602		cap = &ic->ic_wme.wme_chanParams;
1603		noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
1604	}
1605
1606	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1607		k = ieee80211_crypto_encap(ic, ni, m0);
1608		if (k == NULL) {
1609			m_freem(m0);
1610			return ENOBUFS;
1611		}
1612
1613		/* packet header may have moved, reset our local pointer */
1614		wh = mtod(m0, struct ieee80211_frame *);
1615	}
1616
1617	/*
1618	 * IEEE Std 802.11-1999, pp 82: "A STA shall use an RTS/CTS exchange
1619	 * for directed frames only when the length of the MPDU is greater
1620	 * than the length threshold indicated by [...]" ic_rtsthreshold.
1621	 */
1622	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1623	    m0->m_pkthdr.len > ic->ic_rtsthreshold) {
1624		struct mbuf *m;
1625		uint16_t dur;
1626		int rtsrate, ackrate;
1627
1628		rtsrate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1629		ackrate = rt2661_ack_rate(ic, rate);
1630
1631		dur = rt2661_txtime(m0->m_pkthdr.len + 4, rate, ic->ic_flags) +
1632		      rt2661_txtime(RAL_CTS_SIZE, rtsrate, ic->ic_flags) +
1633		      /* XXX: noack (QoS)? */
1634		      rt2661_txtime(RAL_ACK_SIZE, ackrate, ic->ic_flags) +
1635		      3 * RAL_SIFS;
1636
1637		m = rt2661_get_rts(sc, wh, dur);
1638
1639		desc = &txq->desc[txq->cur];
1640		data = &txq->data[txq->cur];
1641
1642		error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m,
1643		    segs, &nsegs, 0);
1644		if (error != 0) {
1645			device_printf(sc->sc_dev,
1646			    "could not map mbuf (error %d)\n", error);
1647			m_freem(m);
1648			m_freem(m0);
1649			return error;
1650		}
1651
1652		/* avoid multiple free() of the same node for each fragment */
1653		ieee80211_ref_node(ni);
1654
1655		data->m = m;
1656		data->ni = ni;
1657
1658		/* RTS frames are not taken into account for rssadapt */
1659		data->id.id_node = NULL;
1660
1661		rt2661_setup_tx_desc(sc, desc, RT2661_TX_NEED_ACK |
1662		    RT2661_TX_MORE_FRAG, 0, m->m_pkthdr.len, rtsrate, segs,
1663		    nsegs, ac);
1664
1665		bus_dmamap_sync(txq->data_dmat, data->map,
1666		    BUS_DMASYNC_PREWRITE);
1667
1668		txq->queued++;
1669		txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1670
1671		/*
1672		 * IEEE Std 802.11-1999: when an RTS/CTS exchange is used, the
1673		 * asynchronous data frame shall be transmitted after the CTS
1674		 * frame and a SIFS period.
1675		 */
1676		flags |= RT2661_TX_LONG_RETRY | RT2661_TX_IFS;
1677	}
1678
1679	data = &txq->data[txq->cur];
1680	desc = &txq->desc[txq->cur];
1681
1682	error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m0, segs,
1683	    &nsegs, 0);
1684	if (error != 0 && error != EFBIG) {
1685		device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1686		    error);
1687		m_freem(m0);
1688		return error;
1689	}
1690	if (error != 0) {
1691		mnew = m_defrag(m0, M_DONTWAIT);
1692		if (mnew == NULL) {
1693			device_printf(sc->sc_dev,
1694			    "could not defragment mbuf\n");
1695			m_freem(m0);
1696			return ENOBUFS;
1697		}
1698		m0 = mnew;
1699
1700		error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m0,
1701		    segs, &nsegs, 0);
1702		if (error != 0) {
1703			device_printf(sc->sc_dev,
1704			    "could not map mbuf (error %d)\n", error);
1705			m_freem(m0);
1706			return error;
1707		}
1708
1709		/* packet header have moved, reset our local pointer */
1710		wh = mtod(m0, struct ieee80211_frame *);
1711	}
1712
1713	if (bpf_peers_present(sc->sc_drvbpf)) {
1714		struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1715
1716		tap->wt_flags = 0;
1717		tap->wt_rate = rate;
1718		tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1719		tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1720
1721		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0);
1722	}
1723
1724	data->m = m0;
1725	data->ni = ni;
1726
1727	/* remember link conditions for rate adaptation algorithm */
1728	if (ic->ic_fixed_rate == IEEE80211_FIXED_RATE_NONE) {
1729		data->id.id_len = m0->m_pkthdr.len;
1730		data->id.id_rateidx = ni->ni_txrate;
1731		data->id.id_node = ni;
1732		data->id.id_rssi = ni->ni_rssi;
1733	} else
1734		data->id.id_node = NULL;
1735
1736	if (!noack && !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1737		flags |= RT2661_TX_NEED_ACK;
1738
1739		dur = rt2661_txtime(RAL_ACK_SIZE, rt2661_ack_rate(ic, rate),
1740		    ic->ic_flags) + RAL_SIFS;
1741		*(uint16_t *)wh->i_dur = htole16(dur);
1742	}
1743
1744	rt2661_setup_tx_desc(sc, desc, flags, 0, m0->m_pkthdr.len, rate, segs,
1745	    nsegs, ac);
1746
1747	bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1748	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1749
1750	DPRINTFN(10, ("sending data frame len=%u idx=%u rate=%u\n",
1751	    m0->m_pkthdr.len, txq->cur, rate));
1752
1753	/* kick Tx */
1754	txq->queued++;
1755	txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1756	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 1 << ac);
1757
1758	return 0;
1759}
1760
1761static void
1762rt2661_start(struct ifnet *ifp)
1763{
1764	struct rt2661_softc *sc = ifp->if_softc;
1765	struct ieee80211com *ic = &sc->sc_ic;
1766	struct mbuf *m0;
1767	struct ether_header *eh;
1768	struct ieee80211_node *ni;
1769	int ac;
1770
1771	RAL_LOCK(sc);
1772
1773	/* prevent management frames from being sent if we're not ready */
1774	if (!(ifp->if_drv_flags & IFF_DRV_RUNNING)) {
1775		RAL_UNLOCK(sc);
1776		return;
1777	}
1778
1779	for (;;) {
1780		IF_POLL(&ic->ic_mgtq, m0);
1781		if (m0 != NULL) {
1782			if (sc->mgtq.queued >= RT2661_MGT_RING_COUNT) {
1783				ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1784				break;
1785			}
1786			IF_DEQUEUE(&ic->ic_mgtq, m0);
1787
1788			ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
1789			m0->m_pkthdr.rcvif = NULL;
1790
1791			if (bpf_peers_present(ic->ic_rawbpf))
1792				bpf_mtap(ic->ic_rawbpf, m0);
1793
1794			if (rt2661_tx_mgt(sc, m0, ni) != 0)
1795				break;
1796
1797		} else {
1798			if (ic->ic_state != IEEE80211_S_RUN)
1799				break;
1800
1801			IFQ_DRV_DEQUEUE(&ifp->if_snd, m0);
1802			if (m0 == NULL)
1803				break;
1804
1805			if (m0->m_len < sizeof (struct ether_header) &&
1806			    !(m0 = m_pullup(m0, sizeof (struct ether_header))))
1807				continue;
1808
1809			eh = mtod(m0, struct ether_header *);
1810			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1811			if (ni == NULL) {
1812				m_freem(m0);
1813				ifp->if_oerrors++;
1814				continue;
1815			}
1816
1817			/* classify mbuf so we can find which tx ring to use */
1818			if (ieee80211_classify(ic, m0, ni) != 0) {
1819				m_freem(m0);
1820				ieee80211_free_node(ni);
1821				ifp->if_oerrors++;
1822				continue;
1823			}
1824
1825			/* no QoS encapsulation for EAPOL frames */
1826			ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
1827			    M_WME_GETAC(m0) : WME_AC_BE;
1828
1829			if (sc->txq[ac].queued >= RT2661_TX_RING_COUNT - 1) {
1830				/* there is no place left in this ring */
1831				IFQ_DRV_PREPEND(&ifp->if_snd, m0);
1832				ifp->if_drv_flags |= IFF_DRV_OACTIVE;
1833				break;
1834			}
1835
1836			BPF_MTAP(ifp, m0);
1837
1838			m0 = ieee80211_encap(ic, m0, ni);
1839			if (m0 == NULL) {
1840				ieee80211_free_node(ni);
1841				ifp->if_oerrors++;
1842				continue;
1843			}
1844
1845			if (bpf_peers_present(ic->ic_rawbpf))
1846				bpf_mtap(ic->ic_rawbpf, m0);
1847
1848			if (rt2661_tx_data(sc, m0, ni, ac) != 0) {
1849				ieee80211_free_node(ni);
1850				ifp->if_oerrors++;
1851				break;
1852			}
1853		}
1854
1855		sc->sc_tx_timer = 5;
1856		ifp->if_timer = 1;
1857	}
1858
1859	RAL_UNLOCK(sc);
1860}
1861
1862static void
1863rt2661_watchdog(struct ifnet *ifp)
1864{
1865	struct rt2661_softc *sc = ifp->if_softc;
1866	struct ieee80211com *ic = &sc->sc_ic;
1867
1868	RAL_LOCK(sc);
1869
1870	ifp->if_timer = 0;
1871
1872	if (sc->sc_tx_timer > 0) {
1873		if (--sc->sc_tx_timer == 0) {
1874			device_printf(sc->sc_dev, "device timeout\n");
1875			rt2661_init(sc);
1876			ifp->if_oerrors++;
1877			RAL_UNLOCK(sc);
1878			return;
1879		}
1880		ifp->if_timer = 1;
1881	}
1882
1883	ieee80211_watchdog(ic);
1884
1885	RAL_UNLOCK(sc);
1886}
1887
1888/*
1889 * This function allows for fast channel switching in monitor mode (used by
1890 * net-mgmt/kismet). In IBSS mode, we must explicitly reset the interface to
1891 * generate a new beacon frame.
1892 */
1893static int
1894rt2661_reset(struct ifnet *ifp)
1895{
1896	struct rt2661_softc *sc = ifp->if_softc;
1897	struct ieee80211com *ic = &sc->sc_ic;
1898
1899	if (ic->ic_opmode != IEEE80211_M_MONITOR)
1900		return ENETRESET;
1901
1902	rt2661_set_chan(sc, ic->ic_curchan);
1903
1904	return 0;
1905}
1906
1907static int
1908rt2661_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data)
1909{
1910	struct rt2661_softc *sc = ifp->if_softc;
1911	struct ieee80211com *ic = &sc->sc_ic;
1912	int error = 0;
1913
1914	RAL_LOCK(sc);
1915
1916	switch (cmd) {
1917	case SIOCSIFFLAGS:
1918		if (ifp->if_flags & IFF_UP) {
1919			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1920				rt2661_update_promisc(sc);
1921			else
1922				rt2661_init(sc);
1923		} else {
1924			if (ifp->if_drv_flags & IFF_DRV_RUNNING)
1925				rt2661_stop(sc);
1926		}
1927		break;
1928
1929	default:
1930		error = ieee80211_ioctl(ic, cmd, data);
1931	}
1932
1933	if (error == ENETRESET) {
1934		if ((ifp->if_flags & IFF_UP) &&
1935		    (ifp->if_drv_flags & IFF_DRV_RUNNING) &&
1936		    (ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
1937			rt2661_init(sc);
1938		error = 0;
1939	}
1940
1941	RAL_UNLOCK(sc);
1942
1943	return error;
1944}
1945
1946static void
1947rt2661_bbp_write(struct rt2661_softc *sc, uint8_t reg, uint8_t val)
1948{
1949	uint32_t tmp;
1950	int ntries;
1951
1952	for (ntries = 0; ntries < 100; ntries++) {
1953		if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
1954			break;
1955		DELAY(1);
1956	}
1957	if (ntries == 100) {
1958		device_printf(sc->sc_dev, "could not write to BBP\n");
1959		return;
1960	}
1961
1962	tmp = RT2661_BBP_BUSY | (reg & 0x7f) << 8 | val;
1963	RAL_WRITE(sc, RT2661_PHY_CSR3, tmp);
1964
1965	DPRINTFN(15, ("BBP R%u <- 0x%02x\n", reg, val));
1966}
1967
1968static uint8_t
1969rt2661_bbp_read(struct rt2661_softc *sc, uint8_t reg)
1970{
1971	uint32_t val;
1972	int ntries;
1973
1974	for (ntries = 0; ntries < 100; ntries++) {
1975		if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
1976			break;
1977		DELAY(1);
1978	}
1979	if (ntries == 100) {
1980		device_printf(sc->sc_dev, "could not read from BBP\n");
1981		return 0;
1982	}
1983
1984	val = RT2661_BBP_BUSY | RT2661_BBP_READ | reg << 8;
1985	RAL_WRITE(sc, RT2661_PHY_CSR3, val);
1986
1987	for (ntries = 0; ntries < 100; ntries++) {
1988		val = RAL_READ(sc, RT2661_PHY_CSR3);
1989		if (!(val & RT2661_BBP_BUSY))
1990			return val & 0xff;
1991		DELAY(1);
1992	}
1993
1994	device_printf(sc->sc_dev, "could not read from BBP\n");
1995	return 0;
1996}
1997
1998static void
1999rt2661_rf_write(struct rt2661_softc *sc, uint8_t reg, uint32_t val)
2000{
2001	uint32_t tmp;
2002	int ntries;
2003
2004	for (ntries = 0; ntries < 100; ntries++) {
2005		if (!(RAL_READ(sc, RT2661_PHY_CSR4) & RT2661_RF_BUSY))
2006			break;
2007		DELAY(1);
2008	}
2009	if (ntries == 100) {
2010		device_printf(sc->sc_dev, "could not write to RF\n");
2011		return;
2012	}
2013
2014	tmp = RT2661_RF_BUSY | RT2661_RF_21BIT | (val & 0x1fffff) << 2 |
2015	    (reg & 3);
2016	RAL_WRITE(sc, RT2661_PHY_CSR4, tmp);
2017
2018	/* remember last written value in sc */
2019	sc->rf_regs[reg] = val;
2020
2021	DPRINTFN(15, ("RF R[%u] <- 0x%05x\n", reg & 3, val & 0x1fffff));
2022}
2023
2024static int
2025rt2661_tx_cmd(struct rt2661_softc *sc, uint8_t cmd, uint16_t arg)
2026{
2027	if (RAL_READ(sc, RT2661_H2M_MAILBOX_CSR) & RT2661_H2M_BUSY)
2028		return EIO;	/* there is already a command pending */
2029
2030	RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR,
2031	    RT2661_H2M_BUSY | RT2661_TOKEN_NO_INTR << 16 | arg);
2032
2033	RAL_WRITE(sc, RT2661_HOST_CMD_CSR, RT2661_KICK_CMD | cmd);
2034
2035	return 0;
2036}
2037
2038static void
2039rt2661_select_antenna(struct rt2661_softc *sc)
2040{
2041	uint8_t bbp4, bbp77;
2042	uint32_t tmp;
2043
2044	bbp4  = rt2661_bbp_read(sc,  4);
2045	bbp77 = rt2661_bbp_read(sc, 77);
2046
2047	/* TBD */
2048
2049	/* make sure Rx is disabled before switching antenna */
2050	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2051	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2052
2053	rt2661_bbp_write(sc,  4, bbp4);
2054	rt2661_bbp_write(sc, 77, bbp77);
2055
2056	/* restore Rx filter */
2057	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2058}
2059
2060/*
2061 * Enable multi-rate retries for frames sent at OFDM rates.
2062 * In 802.11b/g mode, allow fallback to CCK rates.
2063 */
2064static void
2065rt2661_enable_mrr(struct rt2661_softc *sc)
2066{
2067	struct ieee80211com *ic = &sc->sc_ic;
2068	uint32_t tmp;
2069
2070	tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
2071
2072	tmp &= ~RT2661_MRR_CCK_FALLBACK;
2073	if (!IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan))
2074		tmp |= RT2661_MRR_CCK_FALLBACK;
2075	tmp |= RT2661_MRR_ENABLED;
2076
2077	RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
2078}
2079
2080static void
2081rt2661_set_txpreamble(struct rt2661_softc *sc)
2082{
2083	uint32_t tmp;
2084
2085	tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
2086
2087	tmp &= ~RT2661_SHORT_PREAMBLE;
2088	if (sc->sc_ic.ic_flags & IEEE80211_F_SHPREAMBLE)
2089		tmp |= RT2661_SHORT_PREAMBLE;
2090
2091	RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
2092}
2093
2094static void
2095rt2661_set_basicrates(struct rt2661_softc *sc,
2096    const struct ieee80211_rateset *rs)
2097{
2098#define RV(r)	((r) & IEEE80211_RATE_VAL)
2099	uint32_t mask = 0;
2100	uint8_t rate;
2101	int i, j;
2102
2103	for (i = 0; i < rs->rs_nrates; i++) {
2104		rate = rs->rs_rates[i];
2105
2106		if (!(rate & IEEE80211_RATE_BASIC))
2107			continue;
2108
2109		/*
2110		 * Find h/w rate index.  We know it exists because the rate
2111		 * set has already been negotiated.
2112		 */
2113		for (j = 0; rt2661_rateset_11g.rs_rates[j] != RV(rate); j++);
2114
2115		mask |= 1 << j;
2116	}
2117
2118	RAL_WRITE(sc, RT2661_TXRX_CSR5, mask);
2119
2120	DPRINTF(("Setting basic rate mask to 0x%x\n", mask));
2121#undef RV
2122}
2123
2124/*
2125 * Reprogram MAC/BBP to switch to a new band.  Values taken from the reference
2126 * driver.
2127 */
2128static void
2129rt2661_select_band(struct rt2661_softc *sc, struct ieee80211_channel *c)
2130{
2131	uint8_t bbp17, bbp35, bbp96, bbp97, bbp98, bbp104;
2132	uint32_t tmp;
2133
2134	/* update all BBP registers that depend on the band */
2135	bbp17 = 0x20; bbp96 = 0x48; bbp104 = 0x2c;
2136	bbp35 = 0x50; bbp97 = 0x48; bbp98  = 0x48;
2137	if (IEEE80211_IS_CHAN_5GHZ(c)) {
2138		bbp17 += 0x08; bbp96 += 0x10; bbp104 += 0x0c;
2139		bbp35 += 0x10; bbp97 += 0x10; bbp98  += 0x10;
2140	}
2141	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2142	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2143		bbp17 += 0x10; bbp96 += 0x10; bbp104 += 0x10;
2144	}
2145
2146	rt2661_bbp_write(sc,  17, bbp17);
2147	rt2661_bbp_write(sc,  96, bbp96);
2148	rt2661_bbp_write(sc, 104, bbp104);
2149
2150	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2151	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2152		rt2661_bbp_write(sc, 75, 0x80);
2153		rt2661_bbp_write(sc, 86, 0x80);
2154		rt2661_bbp_write(sc, 88, 0x80);
2155	}
2156
2157	rt2661_bbp_write(sc, 35, bbp35);
2158	rt2661_bbp_write(sc, 97, bbp97);
2159	rt2661_bbp_write(sc, 98, bbp98);
2160
2161	tmp = RAL_READ(sc, RT2661_PHY_CSR0);
2162	tmp &= ~(RT2661_PA_PE_2GHZ | RT2661_PA_PE_5GHZ);
2163	if (IEEE80211_IS_CHAN_2GHZ(c))
2164		tmp |= RT2661_PA_PE_2GHZ;
2165	else
2166		tmp |= RT2661_PA_PE_5GHZ;
2167	RAL_WRITE(sc, RT2661_PHY_CSR0, tmp);
2168}
2169
2170static void
2171rt2661_set_chan(struct rt2661_softc *sc, struct ieee80211_channel *c)
2172{
2173	struct ieee80211com *ic = &sc->sc_ic;
2174	const struct rfprog *rfprog;
2175	uint8_t bbp3, bbp94 = RT2661_BBPR94_DEFAULT;
2176	int8_t power;
2177	u_int i, chan;
2178
2179	chan = ieee80211_chan2ieee(ic, c);
2180	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
2181		return;
2182
2183	/* select the appropriate RF settings based on what EEPROM says */
2184	rfprog = (sc->rfprog == 0) ? rt2661_rf5225_1 : rt2661_rf5225_2;
2185
2186	/* find the settings for this channel (we know it exists) */
2187	for (i = 0; rfprog[i].chan != chan; i++);
2188
2189	power = sc->txpow[i];
2190	if (power < 0) {
2191		bbp94 += power;
2192		power = 0;
2193	} else if (power > 31) {
2194		bbp94 += power - 31;
2195		power = 31;
2196	}
2197
2198	/*
2199	 * If we are switching from the 2GHz band to the 5GHz band or
2200	 * vice-versa, BBP registers need to be reprogrammed.
2201	 */
2202	if (c->ic_flags != sc->sc_curchan->ic_flags) {
2203		rt2661_select_band(sc, c);
2204		rt2661_select_antenna(sc);
2205	}
2206	sc->sc_curchan = c;
2207
2208	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2209	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2210	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2211	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2212
2213	DELAY(200);
2214
2215	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2216	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2217	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7 | 1);
2218	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2219
2220	DELAY(200);
2221
2222	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2223	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2224	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2225	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2226
2227	/* enable smart mode for MIMO-capable RFs */
2228	bbp3 = rt2661_bbp_read(sc, 3);
2229
2230	bbp3 &= ~RT2661_SMART_MODE;
2231	if (sc->rf_rev == RT2661_RF_5325 || sc->rf_rev == RT2661_RF_2529)
2232		bbp3 |= RT2661_SMART_MODE;
2233
2234	rt2661_bbp_write(sc, 3, bbp3);
2235
2236	if (bbp94 != RT2661_BBPR94_DEFAULT)
2237		rt2661_bbp_write(sc, 94, bbp94);
2238
2239	/* 5GHz radio needs a 1ms delay here */
2240	if (IEEE80211_IS_CHAN_5GHZ(c))
2241		DELAY(1000);
2242}
2243
2244static void
2245rt2661_set_bssid(struct rt2661_softc *sc, const uint8_t *bssid)
2246{
2247	uint32_t tmp;
2248
2249	tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24;
2250	RAL_WRITE(sc, RT2661_MAC_CSR4, tmp);
2251
2252	tmp = bssid[4] | bssid[5] << 8 | RT2661_ONE_BSSID << 16;
2253	RAL_WRITE(sc, RT2661_MAC_CSR5, tmp);
2254}
2255
2256static void
2257rt2661_set_macaddr(struct rt2661_softc *sc, const uint8_t *addr)
2258{
2259	uint32_t tmp;
2260
2261	tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24;
2262	RAL_WRITE(sc, RT2661_MAC_CSR2, tmp);
2263
2264	tmp = addr[4] | addr[5] << 8;
2265	RAL_WRITE(sc, RT2661_MAC_CSR3, tmp);
2266}
2267
2268static void
2269rt2661_update_promisc(struct rt2661_softc *sc)
2270{
2271	struct ifnet *ifp = sc->sc_ic.ic_ifp;
2272	uint32_t tmp;
2273
2274	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2275
2276	tmp &= ~RT2661_DROP_NOT_TO_ME;
2277	if (!(ifp->if_flags & IFF_PROMISC))
2278		tmp |= RT2661_DROP_NOT_TO_ME;
2279
2280	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2281
2282	DPRINTF(("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
2283	    "entering" : "leaving"));
2284}
2285
2286/*
2287 * Update QoS (802.11e) settings for each h/w Tx ring.
2288 */
2289static int
2290rt2661_wme_update(struct ieee80211com *ic)
2291{
2292	struct rt2661_softc *sc = ic->ic_ifp->if_softc;
2293	const struct wmeParams *wmep;
2294
2295	wmep = ic->ic_wme.wme_chanParams.cap_wmeParams;
2296
2297	/* XXX: not sure about shifts. */
2298	/* XXX: the reference driver plays with AC_VI settings too. */
2299
2300	/* update TxOp */
2301	RAL_WRITE(sc, RT2661_AC_TXOP_CSR0,
2302	    wmep[WME_AC_BE].wmep_txopLimit << 16 |
2303	    wmep[WME_AC_BK].wmep_txopLimit);
2304	RAL_WRITE(sc, RT2661_AC_TXOP_CSR1,
2305	    wmep[WME_AC_VI].wmep_txopLimit << 16 |
2306	    wmep[WME_AC_VO].wmep_txopLimit);
2307
2308	/* update CWmin */
2309	RAL_WRITE(sc, RT2661_CWMIN_CSR,
2310	    wmep[WME_AC_BE].wmep_logcwmin << 12 |
2311	    wmep[WME_AC_BK].wmep_logcwmin <<  8 |
2312	    wmep[WME_AC_VI].wmep_logcwmin <<  4 |
2313	    wmep[WME_AC_VO].wmep_logcwmin);
2314
2315	/* update CWmax */
2316	RAL_WRITE(sc, RT2661_CWMAX_CSR,
2317	    wmep[WME_AC_BE].wmep_logcwmax << 12 |
2318	    wmep[WME_AC_BK].wmep_logcwmax <<  8 |
2319	    wmep[WME_AC_VI].wmep_logcwmax <<  4 |
2320	    wmep[WME_AC_VO].wmep_logcwmax);
2321
2322	/* update Aifsn */
2323	RAL_WRITE(sc, RT2661_AIFSN_CSR,
2324	    wmep[WME_AC_BE].wmep_aifsn << 12 |
2325	    wmep[WME_AC_BK].wmep_aifsn <<  8 |
2326	    wmep[WME_AC_VI].wmep_aifsn <<  4 |
2327	    wmep[WME_AC_VO].wmep_aifsn);
2328
2329	return 0;
2330}
2331
2332static void
2333rt2661_update_slot(struct ifnet *ifp)
2334{
2335	struct rt2661_softc *sc = ifp->if_softc;
2336	struct ieee80211com *ic = &sc->sc_ic;
2337	uint8_t slottime;
2338	uint32_t tmp;
2339
2340	slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
2341
2342	tmp = RAL_READ(sc, RT2661_MAC_CSR9);
2343	tmp = (tmp & ~0xff) | slottime;
2344	RAL_WRITE(sc, RT2661_MAC_CSR9, tmp);
2345}
2346
2347static const char *
2348rt2661_get_rf(int rev)
2349{
2350	switch (rev) {
2351	case RT2661_RF_5225:	return "RT5225";
2352	case RT2661_RF_5325:	return "RT5325 (MIMO XR)";
2353	case RT2661_RF_2527:	return "RT2527";
2354	case RT2661_RF_2529:	return "RT2529 (MIMO XR)";
2355	default:		return "unknown";
2356	}
2357}
2358
2359static void
2360rt2661_read_eeprom(struct rt2661_softc *sc)
2361{
2362	struct ieee80211com *ic = &sc->sc_ic;
2363	uint16_t val;
2364	int i;
2365
2366	/* read MAC address */
2367	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC01);
2368	ic->ic_myaddr[0] = val & 0xff;
2369	ic->ic_myaddr[1] = val >> 8;
2370
2371	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC23);
2372	ic->ic_myaddr[2] = val & 0xff;
2373	ic->ic_myaddr[3] = val >> 8;
2374
2375	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC45);
2376	ic->ic_myaddr[4] = val & 0xff;
2377	ic->ic_myaddr[5] = val >> 8;
2378
2379	val = rt2661_eeprom_read(sc, RT2661_EEPROM_ANTENNA);
2380	/* XXX: test if different from 0xffff? */
2381	sc->rf_rev   = (val >> 11) & 0x1f;
2382	sc->hw_radio = (val >> 10) & 0x1;
2383	sc->rx_ant   = (val >> 4)  & 0x3;
2384	sc->tx_ant   = (val >> 2)  & 0x3;
2385	sc->nb_ant   = val & 0x3;
2386
2387	DPRINTF(("RF revision=%d\n", sc->rf_rev));
2388
2389	val = rt2661_eeprom_read(sc, RT2661_EEPROM_CONFIG2);
2390	sc->ext_5ghz_lna = (val >> 6) & 0x1;
2391	sc->ext_2ghz_lna = (val >> 4) & 0x1;
2392
2393	DPRINTF(("External 2GHz LNA=%d\nExternal 5GHz LNA=%d\n",
2394	    sc->ext_2ghz_lna, sc->ext_5ghz_lna));
2395
2396	val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_2GHZ_OFFSET);
2397	if ((val & 0xff) != 0xff)
2398		sc->rssi_2ghz_corr = (int8_t)(val & 0xff);	/* signed */
2399
2400	val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_5GHZ_OFFSET);
2401	if ((val & 0xff) != 0xff)
2402		sc->rssi_5ghz_corr = (int8_t)(val & 0xff);	/* signed */
2403
2404	/* adjust RSSI correction for external low-noise amplifier */
2405	if (sc->ext_2ghz_lna)
2406		sc->rssi_2ghz_corr -= 14;
2407	if (sc->ext_5ghz_lna)
2408		sc->rssi_5ghz_corr -= 14;
2409
2410	DPRINTF(("RSSI 2GHz corr=%d\nRSSI 5GHz corr=%d\n",
2411	    sc->rssi_2ghz_corr, sc->rssi_5ghz_corr));
2412
2413	val = rt2661_eeprom_read(sc, RT2661_EEPROM_FREQ_OFFSET);
2414	if ((val >> 8) != 0xff)
2415		sc->rfprog = (val >> 8) & 0x3;
2416	if ((val & 0xff) != 0xff)
2417		sc->rffreq = val & 0xff;
2418
2419	DPRINTF(("RF prog=%d\nRF freq=%d\n", sc->rfprog, sc->rffreq));
2420
2421	/* read Tx power for all a/b/g channels */
2422	for (i = 0; i < 19; i++) {
2423		val = rt2661_eeprom_read(sc, RT2661_EEPROM_TXPOWER + i);
2424		sc->txpow[i * 2] = (int8_t)(val >> 8);		/* signed */
2425		DPRINTF(("Channel=%d Tx power=%d\n",
2426		    rt2661_rf5225_1[i * 2].chan, sc->txpow[i * 2]));
2427		sc->txpow[i * 2 + 1] = (int8_t)(val & 0xff);	/* signed */
2428		DPRINTF(("Channel=%d Tx power=%d\n",
2429		    rt2661_rf5225_1[i * 2 + 1].chan, sc->txpow[i * 2 + 1]));
2430	}
2431
2432	/* read vendor-specific BBP values */
2433	for (i = 0; i < 16; i++) {
2434		val = rt2661_eeprom_read(sc, RT2661_EEPROM_BBP_BASE + i);
2435		if (val == 0 || val == 0xffff)
2436			continue;	/* skip invalid entries */
2437		sc->bbp_prom[i].reg = val >> 8;
2438		sc->bbp_prom[i].val = val & 0xff;
2439		DPRINTF(("BBP R%d=%02x\n", sc->bbp_prom[i].reg,
2440		    sc->bbp_prom[i].val));
2441	}
2442}
2443
2444static int
2445rt2661_bbp_init(struct rt2661_softc *sc)
2446{
2447#define N(a)	(sizeof (a) / sizeof ((a)[0]))
2448	int i, ntries;
2449	uint8_t val;
2450
2451	/* wait for BBP to be ready */
2452	for (ntries = 0; ntries < 100; ntries++) {
2453		val = rt2661_bbp_read(sc, 0);
2454		if (val != 0 && val != 0xff)
2455			break;
2456		DELAY(100);
2457	}
2458	if (ntries == 100) {
2459		device_printf(sc->sc_dev, "timeout waiting for BBP\n");
2460		return EIO;
2461	}
2462
2463	/* initialize BBP registers to default values */
2464	for (i = 0; i < N(rt2661_def_bbp); i++) {
2465		rt2661_bbp_write(sc, rt2661_def_bbp[i].reg,
2466		    rt2661_def_bbp[i].val);
2467	}
2468
2469	/* write vendor-specific BBP values (from EEPROM) */
2470	for (i = 0; i < 16; i++) {
2471		if (sc->bbp_prom[i].reg == 0)
2472			continue;
2473		rt2661_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2474	}
2475
2476	return 0;
2477#undef N
2478}
2479
2480static void
2481rt2661_init(void *priv)
2482{
2483#define N(a)	(sizeof (a) / sizeof ((a)[0]))
2484	struct rt2661_softc *sc = priv;
2485	struct ieee80211com *ic = &sc->sc_ic;
2486	struct ifnet *ifp = ic->ic_ifp;
2487	uint32_t tmp, sta[3];
2488	int i, ntries;
2489
2490	RAL_LOCK(sc);
2491
2492	rt2661_stop(sc);
2493
2494	/* initialize Tx rings */
2495	RAL_WRITE(sc, RT2661_AC1_BASE_CSR, sc->txq[1].physaddr);
2496	RAL_WRITE(sc, RT2661_AC0_BASE_CSR, sc->txq[0].physaddr);
2497	RAL_WRITE(sc, RT2661_AC2_BASE_CSR, sc->txq[2].physaddr);
2498	RAL_WRITE(sc, RT2661_AC3_BASE_CSR, sc->txq[3].physaddr);
2499
2500	/* initialize Mgt ring */
2501	RAL_WRITE(sc, RT2661_MGT_BASE_CSR, sc->mgtq.physaddr);
2502
2503	/* initialize Rx ring */
2504	RAL_WRITE(sc, RT2661_RX_BASE_CSR, sc->rxq.physaddr);
2505
2506	/* initialize Tx rings sizes */
2507	RAL_WRITE(sc, RT2661_TX_RING_CSR0,
2508	    RT2661_TX_RING_COUNT << 24 |
2509	    RT2661_TX_RING_COUNT << 16 |
2510	    RT2661_TX_RING_COUNT <<  8 |
2511	    RT2661_TX_RING_COUNT);
2512
2513	RAL_WRITE(sc, RT2661_TX_RING_CSR1,
2514	    RT2661_TX_DESC_WSIZE << 16 |
2515	    RT2661_TX_RING_COUNT <<  8 |	/* XXX: HCCA ring unused */
2516	    RT2661_MGT_RING_COUNT);
2517
2518	/* initialize Rx rings */
2519	RAL_WRITE(sc, RT2661_RX_RING_CSR,
2520	    RT2661_RX_DESC_BACK  << 16 |
2521	    RT2661_RX_DESC_WSIZE <<  8 |
2522	    RT2661_RX_RING_COUNT);
2523
2524	/* XXX: some magic here */
2525	RAL_WRITE(sc, RT2661_TX_DMA_DST_CSR, 0xaa);
2526
2527	/* load base addresses of all 5 Tx rings (4 data + 1 mgt) */
2528	RAL_WRITE(sc, RT2661_LOAD_TX_RING_CSR, 0x1f);
2529
2530	/* load base address of Rx ring */
2531	RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 2);
2532
2533	/* initialize MAC registers to default values */
2534	for (i = 0; i < N(rt2661_def_mac); i++)
2535		RAL_WRITE(sc, rt2661_def_mac[i].reg, rt2661_def_mac[i].val);
2536
2537	IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2538	rt2661_set_macaddr(sc, ic->ic_myaddr);
2539
2540	/* set host ready */
2541	RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2542	RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2543
2544	/* wait for BBP/RF to wakeup */
2545	for (ntries = 0; ntries < 1000; ntries++) {
2546		if (RAL_READ(sc, RT2661_MAC_CSR12) & 8)
2547			break;
2548		DELAY(1000);
2549	}
2550	if (ntries == 1000) {
2551		printf("timeout waiting for BBP/RF to wakeup\n");
2552		rt2661_stop(sc);
2553		RAL_UNLOCK(sc);
2554		return;
2555	}
2556
2557	if (rt2661_bbp_init(sc) != 0) {
2558		rt2661_stop(sc);
2559		RAL_UNLOCK(sc);
2560		return;
2561	}
2562
2563	/* select default channel */
2564	sc->sc_curchan = ic->ic_curchan;
2565	rt2661_select_band(sc, sc->sc_curchan);
2566	rt2661_select_antenna(sc);
2567	rt2661_set_chan(sc, sc->sc_curchan);
2568
2569	/* update Rx filter */
2570	tmp = RAL_READ(sc, RT2661_TXRX_CSR0) & 0xffff;
2571
2572	tmp |= RT2661_DROP_PHY_ERROR | RT2661_DROP_CRC_ERROR;
2573	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2574		tmp |= RT2661_DROP_CTL | RT2661_DROP_VER_ERROR |
2575		       RT2661_DROP_ACKCTS;
2576		if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2577			tmp |= RT2661_DROP_TODS;
2578		if (!(ifp->if_flags & IFF_PROMISC))
2579			tmp |= RT2661_DROP_NOT_TO_ME;
2580	}
2581
2582	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2583
2584	/* clear STA registers */
2585	RAL_READ_REGION_4(sc, RT2661_STA_CSR0, sta, N(sta));
2586
2587	/* initialize ASIC */
2588	RAL_WRITE(sc, RT2661_MAC_CSR1, 4);
2589
2590	/* clear any pending interrupt */
2591	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2592
2593	/* enable interrupts */
2594	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
2595	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
2596
2597	/* kick Rx */
2598	RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 1);
2599
2600	ifp->if_drv_flags &= ~IFF_DRV_OACTIVE;
2601	ifp->if_drv_flags |= IFF_DRV_RUNNING;
2602
2603	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2604		if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
2605			ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2606	} else
2607		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2608
2609	RAL_UNLOCK(sc);
2610#undef N
2611}
2612
2613void
2614rt2661_stop(void *priv)
2615{
2616	struct rt2661_softc *sc = priv;
2617	struct ieee80211com *ic = &sc->sc_ic;
2618	struct ifnet *ifp = ic->ic_ifp;
2619	uint32_t tmp;
2620
2621	sc->sc_tx_timer = 0;
2622	ifp->if_timer = 0;
2623	ifp->if_drv_flags &= ~(IFF_DRV_RUNNING | IFF_DRV_OACTIVE);
2624
2625	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2626
2627	/* abort Tx (for all 5 Tx rings) */
2628	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 0x1f << 16);
2629
2630	/* disable Rx (value remains after reset!) */
2631	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2632	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2633
2634	/* reset ASIC */
2635	RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2636	RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2637
2638	/* disable interrupts */
2639	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffffff);
2640	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
2641
2642	/* clear any pending interrupt */
2643	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2644	RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, 0xffffffff);
2645
2646	/* reset Tx and Rx rings */
2647	rt2661_reset_tx_ring(sc, &sc->txq[0]);
2648	rt2661_reset_tx_ring(sc, &sc->txq[1]);
2649	rt2661_reset_tx_ring(sc, &sc->txq[2]);
2650	rt2661_reset_tx_ring(sc, &sc->txq[3]);
2651	rt2661_reset_tx_ring(sc, &sc->mgtq);
2652	rt2661_reset_rx_ring(sc, &sc->rxq);
2653}
2654
2655static int
2656rt2661_load_microcode(struct rt2661_softc *sc, const uint8_t *ucode, int size)
2657{
2658	int ntries;
2659
2660	/* reset 8051 */
2661	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2662
2663	/* cancel any pending Host to MCU command */
2664	RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR, 0);
2665	RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
2666	RAL_WRITE(sc, RT2661_HOST_CMD_CSR, 0);
2667
2668	/* write 8051's microcode */
2669	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET | RT2661_MCU_SEL);
2670	RAL_WRITE_REGION_1(sc, RT2661_MCU_CODE_BASE, ucode, size);
2671	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2672
2673	/* kick 8051's ass */
2674	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, 0);
2675
2676	/* wait for 8051 to initialize */
2677	for (ntries = 0; ntries < 500; ntries++) {
2678		if (RAL_READ(sc, RT2661_MCU_CNTL_CSR) & RT2661_MCU_READY)
2679			break;
2680		DELAY(100);
2681	}
2682	if (ntries == 500) {
2683		printf("timeout waiting for MCU to initialize\n");
2684		return EIO;
2685	}
2686	return 0;
2687}
2688
2689#ifdef notyet
2690/*
2691 * Dynamically tune Rx sensitivity (BBP register 17) based on average RSSI and
2692 * false CCA count.  This function is called periodically (every seconds) when
2693 * in the RUN state.  Values taken from the reference driver.
2694 */
2695static void
2696rt2661_rx_tune(struct rt2661_softc *sc)
2697{
2698	uint8_t bbp17;
2699	uint16_t cca;
2700	int lo, hi, dbm;
2701
2702	/*
2703	 * Tuning range depends on operating band and on the presence of an
2704	 * external low-noise amplifier.
2705	 */
2706	lo = 0x20;
2707	if (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan))
2708		lo += 0x08;
2709	if ((IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan) && sc->ext_2ghz_lna) ||
2710	    (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan) && sc->ext_5ghz_lna))
2711		lo += 0x10;
2712	hi = lo + 0x20;
2713
2714	/* retrieve false CCA count since last call (clear on read) */
2715	cca = RAL_READ(sc, RT2661_STA_CSR1) & 0xffff;
2716
2717	if (dbm >= -35) {
2718		bbp17 = 0x60;
2719	} else if (dbm >= -58) {
2720		bbp17 = hi;
2721	} else if (dbm >= -66) {
2722		bbp17 = lo + 0x10;
2723	} else if (dbm >= -74) {
2724		bbp17 = lo + 0x08;
2725	} else {
2726		/* RSSI < -74dBm, tune using false CCA count */
2727
2728		bbp17 = sc->bbp17; /* current value */
2729
2730		hi -= 2 * (-74 - dbm);
2731		if (hi < lo)
2732			hi = lo;
2733
2734		if (bbp17 > hi) {
2735			bbp17 = hi;
2736
2737		} else if (cca > 512) {
2738			if (++bbp17 > hi)
2739				bbp17 = hi;
2740		} else if (cca < 100) {
2741			if (--bbp17 < lo)
2742				bbp17 = lo;
2743		}
2744	}
2745
2746	if (bbp17 != sc->bbp17) {
2747		rt2661_bbp_write(sc, 17, bbp17);
2748		sc->bbp17 = bbp17;
2749	}
2750}
2751
2752/*
2753 * Enter/Leave radar detection mode.
2754 * This is for 802.11h additional regulatory domains.
2755 */
2756static void
2757rt2661_radar_start(struct rt2661_softc *sc)
2758{
2759	uint32_t tmp;
2760
2761	/* disable Rx */
2762	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2763	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2764
2765	rt2661_bbp_write(sc, 82, 0x20);
2766	rt2661_bbp_write(sc, 83, 0x00);
2767	rt2661_bbp_write(sc, 84, 0x40);
2768
2769	/* save current BBP registers values */
2770	sc->bbp18 = rt2661_bbp_read(sc, 18);
2771	sc->bbp21 = rt2661_bbp_read(sc, 21);
2772	sc->bbp22 = rt2661_bbp_read(sc, 22);
2773	sc->bbp16 = rt2661_bbp_read(sc, 16);
2774	sc->bbp17 = rt2661_bbp_read(sc, 17);
2775	sc->bbp64 = rt2661_bbp_read(sc, 64);
2776
2777	rt2661_bbp_write(sc, 18, 0xff);
2778	rt2661_bbp_write(sc, 21, 0x3f);
2779	rt2661_bbp_write(sc, 22, 0x3f);
2780	rt2661_bbp_write(sc, 16, 0xbd);
2781	rt2661_bbp_write(sc, 17, sc->ext_5ghz_lna ? 0x44 : 0x34);
2782	rt2661_bbp_write(sc, 64, 0x21);
2783
2784	/* restore Rx filter */
2785	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2786}
2787
2788static int
2789rt2661_radar_stop(struct rt2661_softc *sc)
2790{
2791	uint8_t bbp66;
2792
2793	/* read radar detection result */
2794	bbp66 = rt2661_bbp_read(sc, 66);
2795
2796	/* restore BBP registers values */
2797	rt2661_bbp_write(sc, 16, sc->bbp16);
2798	rt2661_bbp_write(sc, 17, sc->bbp17);
2799	rt2661_bbp_write(sc, 18, sc->bbp18);
2800	rt2661_bbp_write(sc, 21, sc->bbp21);
2801	rt2661_bbp_write(sc, 22, sc->bbp22);
2802	rt2661_bbp_write(sc, 64, sc->bbp64);
2803
2804	return bbp66 == 1;
2805}
2806#endif
2807
2808static int
2809rt2661_prepare_beacon(struct rt2661_softc *sc)
2810{
2811	struct ieee80211com *ic = &sc->sc_ic;
2812	struct ieee80211_beacon_offsets bo;
2813	struct rt2661_tx_desc desc;
2814	struct mbuf *m0;
2815	int rate;
2816
2817	m0 = ieee80211_beacon_alloc(ic, ic->ic_bss, &bo);
2818	if (m0 == NULL) {
2819		device_printf(sc->sc_dev, "could not allocate beacon frame\n");
2820		return ENOBUFS;
2821	}
2822
2823	/* send beacons at the lowest available rate */
2824	rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan) ? 12 : 2;
2825
2826	rt2661_setup_tx_desc(sc, &desc, RT2661_TX_TIMESTAMP, RT2661_TX_HWSEQ,
2827	    m0->m_pkthdr.len, rate, NULL, 0, RT2661_QID_MGT);
2828
2829	/* copy the first 24 bytes of Tx descriptor into NIC memory */
2830	RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0, (uint8_t *)&desc, 24);
2831
2832	/* copy beacon header and payload into NIC memory */
2833	RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0 + 24,
2834	    mtod(m0, uint8_t *), m0->m_pkthdr.len);
2835
2836	m_freem(m0);
2837
2838	return 0;
2839}
2840
2841/*
2842 * Enable TSF synchronization and tell h/w to start sending beacons for IBSS
2843 * and HostAP operating modes.
2844 */
2845static void
2846rt2661_enable_tsf_sync(struct rt2661_softc *sc)
2847{
2848	struct ieee80211com *ic = &sc->sc_ic;
2849	uint32_t tmp;
2850
2851	if (ic->ic_opmode != IEEE80211_M_STA) {
2852		/*
2853		 * Change default 16ms TBTT adjustment to 8ms.
2854		 * Must be done before enabling beacon generation.
2855		 */
2856		RAL_WRITE(sc, RT2661_TXRX_CSR10, 1 << 12 | 8);
2857	}
2858
2859	tmp = RAL_READ(sc, RT2661_TXRX_CSR9) & 0xff000000;
2860
2861	/* set beacon interval (in 1/16ms unit) */
2862	tmp |= ic->ic_bss->ni_intval * 16;
2863
2864	tmp |= RT2661_TSF_TICKING | RT2661_ENABLE_TBTT;
2865	if (ic->ic_opmode == IEEE80211_M_STA)
2866		tmp |= RT2661_TSF_MODE(1);
2867	else
2868		tmp |= RT2661_TSF_MODE(2) | RT2661_GENERATE_BEACON;
2869
2870	RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp);
2871}
2872
2873/*
2874 * Retrieve the "Received Signal Strength Indicator" from the raw values
2875 * contained in Rx descriptors.  The computation depends on which band the
2876 * frame was received.  Correction values taken from the reference driver.
2877 */
2878static int
2879rt2661_get_rssi(struct rt2661_softc *sc, uint8_t raw)
2880{
2881	int lna, agc, rssi;
2882
2883	lna = (raw >> 5) & 0x3;
2884	agc = raw & 0x1f;
2885
2886	rssi = 2 * agc;
2887
2888	if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan)) {
2889		rssi += sc->rssi_2ghz_corr;
2890
2891		if (lna == 1)
2892			rssi -= 64;
2893		else if (lna == 2)
2894			rssi -= 74;
2895		else if (lna == 3)
2896			rssi -= 90;
2897	} else {
2898		rssi += sc->rssi_5ghz_corr;
2899
2900		if (lna == 1)
2901			rssi -= 64;
2902		else if (lna == 2)
2903			rssi -= 86;
2904		else if (lna == 3)
2905			rssi -= 100;
2906	}
2907	return rssi;
2908}
2909