1/*	$NetBSD: rt2560.c,v 1.40 2021/12/05 02:47:01 msaitoh Exp $	*/
2/*	$OpenBSD: rt2560.c,v 1.15 2006/04/20 20:31:12 miod Exp $  */
3/*	$FreeBSD: rt2560.c,v 1.3 2006/03/21 21:15:43 damien Exp $*/
4
5/*-
6 * Copyright (c) 2005, 2006
7 *	Damien Bergamini <damien.bergamini@free.fr>
8 *
9 * Permission to use, copy, modify, and distribute this software for any
10 * purpose with or without fee is hereby granted, provided that the above
11 * copyright notice and this permission notice appear in all copies.
12 *
13 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
14 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
15 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
16 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
17 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
18 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
19 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 */
21
22/*-
23 * Ralink Technology RT2560 chipset driver
24 * http://www.ralinktech.com/
25 */
26#include <sys/cdefs.h>
27__KERNEL_RCSID(0, "$NetBSD: rt2560.c,v 1.40 2021/12/05 02:47:01 msaitoh Exp $");
28
29
30#include <sys/param.h>
31#include <sys/sockio.h>
32#include <sys/mbuf.h>
33#include <sys/kernel.h>
34#include <sys/socket.h>
35#include <sys/systm.h>
36#include <sys/malloc.h>
37#include <sys/callout.h>
38#include <sys/conf.h>
39#include <sys/device.h>
40
41#include <sys/bus.h>
42#include <machine/endian.h>
43#include <sys/intr.h>
44
45#include <net/bpf.h>
46#include <net/if.h>
47#include <net/if_arp.h>
48#include <net/if_dl.h>
49#include <net/if_media.h>
50#include <net/if_types.h>
51#include <net/if_ether.h>
52
53#include <netinet/in.h>
54#include <netinet/in_systm.h>
55#include <netinet/in_var.h>
56#include <netinet/ip.h>
57
58#include <net80211/ieee80211_var.h>
59#include <net80211/ieee80211_rssadapt.h>
60#include <net80211/ieee80211_radiotap.h>
61
62#include <dev/ic/rt2560reg.h>
63#include <dev/ic/rt2560var.h>
64
65#ifdef RAL_DEBUG
66#define DPRINTF(x)	do { if (rt2560_debug > 0) printf x; } while (0)
67#define DPRINTFN(n, x)	do { if (rt2560_debug >= (n)) printf x; } while (0)
68int rt2560_debug = 0;
69#else
70#define DPRINTF(x)
71#define DPRINTFN(n, x)
72#endif
73
74static int	rt2560_alloc_tx_ring(struct rt2560_softc *,
75		    struct rt2560_tx_ring *, int);
76static void	rt2560_reset_tx_ring(struct rt2560_softc *,
77		    struct rt2560_tx_ring *);
78static void	rt2560_free_tx_ring(struct rt2560_softc *,
79		    struct rt2560_tx_ring *);
80static int	rt2560_alloc_rx_ring(struct rt2560_softc *,
81		    struct rt2560_rx_ring *, int);
82static void	rt2560_reset_rx_ring(struct rt2560_softc *,
83		    struct rt2560_rx_ring *);
84static void	rt2560_free_rx_ring(struct rt2560_softc *,
85		    struct rt2560_rx_ring *);
86static struct ieee80211_node *
87		rt2560_node_alloc(struct ieee80211_node_table *);
88static int	rt2560_media_change(struct ifnet *);
89static void	rt2560_next_scan(void *);
90static void	rt2560_iter_func(void *, struct ieee80211_node *);
91static void	rt2560_update_rssadapt(void *);
92static int	rt2560_newstate(struct ieee80211com *, enum ieee80211_state,
93    		    int);
94static uint16_t	rt2560_eeprom_read(struct rt2560_softc *, uint8_t);
95static void	rt2560_encryption_intr(struct rt2560_softc *);
96static void	rt2560_tx_intr(struct rt2560_softc *);
97static void	rt2560_prio_intr(struct rt2560_softc *);
98static void	rt2560_decryption_intr(struct rt2560_softc *);
99static void	rt2560_rx_intr(struct rt2560_softc *);
100static void	rt2560_beacon_expire(struct rt2560_softc *);
101static void	rt2560_wakeup_expire(struct rt2560_softc *);
102static uint8_t	rt2560_rxrate(struct rt2560_rx_desc *);
103static int	rt2560_ack_rate(struct ieee80211com *, int);
104static uint16_t	rt2560_txtime(int, int, uint32_t);
105static uint8_t	rt2560_plcp_signal(int);
106static void	rt2560_setup_tx_desc(struct rt2560_softc *,
107		    struct rt2560_tx_desc *, uint32_t, int, int, int,
108		    bus_addr_t);
109static int	rt2560_tx_bcn(struct rt2560_softc *, struct mbuf *,
110		    struct ieee80211_node *);
111static int	rt2560_tx_mgt(struct rt2560_softc *, struct mbuf *,
112		    struct ieee80211_node *);
113static struct mbuf *rt2560_get_rts(struct rt2560_softc *,
114		    struct ieee80211_frame *, uint16_t);
115static int	rt2560_tx_data(struct rt2560_softc *, struct mbuf *,
116		    struct ieee80211_node *);
117static void	rt2560_start(struct ifnet *);
118static void	rt2560_watchdog(struct ifnet *);
119static int	rt2560_reset(struct ifnet *);
120static int	rt2560_ioctl(struct ifnet *, u_long, void *);
121static void	rt2560_bbp_write(struct rt2560_softc *, uint8_t, uint8_t);
122static uint8_t	rt2560_bbp_read(struct rt2560_softc *, uint8_t);
123static void	rt2560_rf_write(struct rt2560_softc *, uint8_t, uint32_t);
124static void	rt2560_set_chan(struct rt2560_softc *,
125		    struct ieee80211_channel *);
126static void	rt2560_disable_rf_tune(struct rt2560_softc *);
127static void	rt2560_enable_tsf_sync(struct rt2560_softc *);
128static void	rt2560_update_plcp(struct rt2560_softc *);
129static void	rt2560_update_slot(struct ifnet *);
130static void	rt2560_set_basicrates(struct rt2560_softc *);
131static void	rt2560_update_led(struct rt2560_softc *, int, int);
132static void	rt2560_set_bssid(struct rt2560_softc *, uint8_t *);
133static void	rt2560_set_macaddr(struct rt2560_softc *, uint8_t *);
134static void	rt2560_get_macaddr(struct rt2560_softc *, uint8_t *);
135static void	rt2560_update_promisc(struct rt2560_softc *);
136static void	rt2560_set_txantenna(struct rt2560_softc *, int);
137static void	rt2560_set_rxantenna(struct rt2560_softc *, int);
138static const char *rt2560_get_rf(int);
139static void	rt2560_read_eeprom(struct rt2560_softc *);
140static int	rt2560_bbp_init(struct rt2560_softc *);
141static int	rt2560_init(struct ifnet *);
142static void	rt2560_stop(struct ifnet *, int);
143static void	rt2560_softintr(void *);
144
145/*
146 * Default values for MAC registers; values taken from the reference driver.
147 */
148static const struct {
149	uint32_t	reg;
150	uint32_t	val;
151} rt2560_def_mac[] = {
152	{ RT2560_PSCSR0,      0x00020002 },
153	{ RT2560_PSCSR1,      0x00000002 },
154	{ RT2560_PSCSR2,      0x00020002 },
155	{ RT2560_PSCSR3,      0x00000002 },
156	{ RT2560_TIMECSR,     0x00003f21 },
157	{ RT2560_CSR9,        0x00000780 },
158	{ RT2560_CSR11,       0x07041483 },
159	{ RT2560_CNT3,        0x00000000 },
160	{ RT2560_TXCSR1,      0x07614562 },
161	{ RT2560_ARSP_PLCP_0, 0x8c8d8b8a },
162	{ RT2560_ACKPCTCSR,   0x7038140a },
163	{ RT2560_ARTCSR1,     0x1d21252d },
164	{ RT2560_ARTCSR2,     0x1919191d },
165	{ RT2560_RXCSR0,      0xffffffff },
166	{ RT2560_RXCSR3,      0xb3aab3af },
167	{ RT2560_PCICSR,      0x000003b8 },
168	{ RT2560_PWRCSR0,     0x3f3b3100 },
169	{ RT2560_GPIOCSR,     0x0000ff00 },
170	{ RT2560_TESTCSR,     0x000000f0 },
171	{ RT2560_PWRCSR1,     0x000001ff },
172	{ RT2560_MACCSR0,     0x00213223 },
173	{ RT2560_MACCSR1,     0x00235518 },
174	{ RT2560_RLPWCSR,     0x00000040 },
175	{ RT2560_RALINKCSR,   0x9a009a11 },
176	{ RT2560_CSR7,        0xffffffff },
177	{ RT2560_BBPCSR1,     0x82188200 },
178	{ RT2560_TXACKCSR0,   0x00000020 },
179	{ RT2560_SECCSR3,     0x0000e78f }
180};
181
182/*
183 * Default values for BBP registers; values taken from the reference driver.
184 */
185static const struct {
186	uint8_t	reg;
187	uint8_t	val;
188} rt2560_def_bbp[] = {
189	{  3, 0x02 },
190	{  4, 0x19 },
191	{ 14, 0x1c },
192	{ 15, 0x30 },
193	{ 16, 0xac },
194	{ 17, 0x48 },
195	{ 18, 0x18 },
196	{ 19, 0xff },
197	{ 20, 0x1e },
198	{ 21, 0x08 },
199	{ 22, 0x08 },
200	{ 23, 0x08 },
201	{ 24, 0x80 },
202	{ 25, 0x50 },
203	{ 26, 0x08 },
204	{ 27, 0x23 },
205	{ 30, 0x10 },
206	{ 31, 0x2b },
207	{ 32, 0xb9 },
208	{ 34, 0x12 },
209	{ 35, 0x50 },
210	{ 39, 0xc4 },
211	{ 40, 0x02 },
212	{ 41, 0x60 },
213	{ 53, 0x10 },
214	{ 54, 0x18 },
215	{ 56, 0x08 },
216	{ 57, 0x10 },
217	{ 58, 0x08 },
218	{ 61, 0x60 },
219	{ 62, 0x10 },
220	{ 75, 0xff }
221};
222
223/*
224 * Default values for RF register R2 indexed by channel numbers; values taken
225 * from the reference driver.
226 */
227static const uint32_t rt2560_rf2522_r2[] = {
228	0x307f6, 0x307fb, 0x30800, 0x30805, 0x3080a, 0x3080f, 0x30814,
229	0x30819, 0x3081e, 0x30823, 0x30828, 0x3082d, 0x30832, 0x3083e
230};
231
232static const uint32_t rt2560_rf2523_r2[] = {
233	0x00327, 0x00328, 0x00329, 0x0032a, 0x0032b, 0x0032c, 0x0032d,
234	0x0032e, 0x0032f, 0x00340, 0x00341, 0x00342, 0x00343, 0x00346
235};
236
237static const uint32_t rt2560_rf2524_r2[] = {
238	0x00327, 0x00328, 0x00329, 0x0032a, 0x0032b, 0x0032c, 0x0032d,
239	0x0032e, 0x0032f, 0x00340, 0x00341, 0x00342, 0x00343, 0x00346
240};
241
242static const uint32_t rt2560_rf2525_r2[] = {
243	0x20327, 0x20328, 0x20329, 0x2032a, 0x2032b, 0x2032c, 0x2032d,
244	0x2032e, 0x2032f, 0x20340, 0x20341, 0x20342, 0x20343, 0x20346
245};
246
247static const uint32_t rt2560_rf2525_hi_r2[] = {
248	0x2032f, 0x20340, 0x20341, 0x20342, 0x20343, 0x20344, 0x20345,
249	0x20346, 0x20347, 0x20348, 0x20349, 0x2034a, 0x2034b, 0x2034e
250};
251
252static const uint32_t rt2560_rf2525e_r2[] = {
253	0x2044d, 0x2044e, 0x2044f, 0x20460, 0x20461, 0x20462, 0x20463,
254	0x20464, 0x20465, 0x20466, 0x20467, 0x20468, 0x20469, 0x2046b
255};
256
257static const uint32_t rt2560_rf2526_hi_r2[] = {
258	0x0022a, 0x0022b, 0x0022b, 0x0022c, 0x0022c, 0x0022d, 0x0022d,
259	0x0022e, 0x0022e, 0x0022f, 0x0022d, 0x00240, 0x00240, 0x00241
260};
261
262static const uint32_t rt2560_rf2526_r2[] = {
263	0x00226, 0x00227, 0x00227, 0x00228, 0x00228, 0x00229, 0x00229,
264	0x0022a, 0x0022a, 0x0022b, 0x0022b, 0x0022c, 0x0022c, 0x0022d
265};
266
267/*
268 * For dual-band RF, RF registers R1 and R4 also depend on channel number;
269 * values taken from the reference driver.
270 */
271static const struct {
272	uint8_t		chan;
273	uint32_t	r1;
274	uint32_t	r2;
275	uint32_t	r4;
276} rt2560_rf5222[] = {
277	{   1, 0x08808, 0x0044d, 0x00282 },
278	{   2, 0x08808, 0x0044e, 0x00282 },
279	{   3, 0x08808, 0x0044f, 0x00282 },
280	{   4, 0x08808, 0x00460, 0x00282 },
281	{   5, 0x08808, 0x00461, 0x00282 },
282	{   6, 0x08808, 0x00462, 0x00282 },
283	{   7, 0x08808, 0x00463, 0x00282 },
284	{   8, 0x08808, 0x00464, 0x00282 },
285	{   9, 0x08808, 0x00465, 0x00282 },
286	{  10, 0x08808, 0x00466, 0x00282 },
287	{  11, 0x08808, 0x00467, 0x00282 },
288	{  12, 0x08808, 0x00468, 0x00282 },
289	{  13, 0x08808, 0x00469, 0x00282 },
290	{  14, 0x08808, 0x0046b, 0x00286 },
291
292	{  36, 0x08804, 0x06225, 0x00287 },
293	{  40, 0x08804, 0x06226, 0x00287 },
294	{  44, 0x08804, 0x06227, 0x00287 },
295	{  48, 0x08804, 0x06228, 0x00287 },
296	{  52, 0x08804, 0x06229, 0x00287 },
297	{  56, 0x08804, 0x0622a, 0x00287 },
298	{  60, 0x08804, 0x0622b, 0x00287 },
299	{  64, 0x08804, 0x0622c, 0x00287 },
300
301	{ 100, 0x08804, 0x02200, 0x00283 },
302	{ 104, 0x08804, 0x02201, 0x00283 },
303	{ 108, 0x08804, 0x02202, 0x00283 },
304	{ 112, 0x08804, 0x02203, 0x00283 },
305	{ 116, 0x08804, 0x02204, 0x00283 },
306	{ 120, 0x08804, 0x02205, 0x00283 },
307	{ 124, 0x08804, 0x02206, 0x00283 },
308	{ 128, 0x08804, 0x02207, 0x00283 },
309	{ 132, 0x08804, 0x02208, 0x00283 },
310	{ 136, 0x08804, 0x02209, 0x00283 },
311	{ 140, 0x08804, 0x0220a, 0x00283 },
312
313	{ 149, 0x08808, 0x02429, 0x00281 },
314	{ 153, 0x08808, 0x0242b, 0x00281 },
315	{ 157, 0x08808, 0x0242d, 0x00281 },
316	{ 161, 0x08808, 0x0242f, 0x00281 }
317};
318
319int
320rt2560_attach(void *xsc, int id)
321{
322	struct rt2560_softc *sc = xsc;
323	struct ieee80211com *ic = &sc->sc_ic;
324	struct ifnet *ifp = &sc->sc_if;
325	int error, i;
326
327	callout_init(&sc->scan_ch, 0);
328	callout_init(&sc->rssadapt_ch, 0);
329
330	/* retrieve RT2560 rev. no */
331	sc->asic_rev = RAL_READ(sc, RT2560_CSR0);
332
333	/* retrieve MAC address */
334	rt2560_get_macaddr(sc, ic->ic_myaddr);
335
336	aprint_normal_dev(sc->sc_dev, "802.11 address %s\n",
337	    ether_sprintf(ic->ic_myaddr));
338
339	/* retrieve RF rev. no and various other things from EEPROM */
340	rt2560_read_eeprom(sc);
341
342	aprint_normal_dev(sc->sc_dev, "MAC/BBP RT2560 (rev 0x%02x), RF %s\n",
343	    sc->asic_rev, rt2560_get_rf(sc->rf_rev));
344
345	sc->sc_soft_ih = softint_establish(SOFTINT_NET, rt2560_softintr, sc);
346	if (sc->sc_soft_ih == NULL) {
347		aprint_error_dev(sc->sc_dev, "could not establish softint\n)");
348		goto fail0;
349	}
350
351	/*
352	 * Allocate Tx and Rx rings.
353	 */
354	error = rt2560_alloc_tx_ring(sc, &sc->txq, RT2560_TX_RING_COUNT);
355	if (error != 0) {
356		aprint_error_dev(sc->sc_dev, "could not allocate Tx ring\n)");
357		goto fail1;
358	}
359
360	error = rt2560_alloc_tx_ring(sc, &sc->atimq, RT2560_ATIM_RING_COUNT);
361	if (error != 0) {
362		aprint_error_dev(sc->sc_dev, "could not allocate ATIM ring\n");
363		goto fail2;
364	}
365
366	error = rt2560_alloc_tx_ring(sc, &sc->prioq, RT2560_PRIO_RING_COUNT);
367	if (error != 0) {
368		aprint_error_dev(sc->sc_dev, "could not allocate Prio ring\n");
369		goto fail3;
370	}
371
372	error = rt2560_alloc_tx_ring(sc, &sc->bcnq, RT2560_BEACON_RING_COUNT);
373	if (error != 0) {
374		aprint_error_dev(sc->sc_dev, "could not allocate Beacon ring\n");
375		goto fail4;
376	}
377
378	error = rt2560_alloc_rx_ring(sc, &sc->rxq, RT2560_RX_RING_COUNT);
379	if (error != 0) {
380		aprint_error_dev(sc->sc_dev, "could not allocate Rx ring\n");
381		goto fail5;
382	}
383
384	ifp->if_softc = sc;
385	ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
386	ifp->if_init = rt2560_init;
387	ifp->if_stop = rt2560_stop;
388	ifp->if_ioctl = rt2560_ioctl;
389	ifp->if_start = rt2560_start;
390	ifp->if_watchdog = rt2560_watchdog;
391	IFQ_SET_READY(&ifp->if_snd);
392	memcpy(ifp->if_xname, device_xname(sc->sc_dev), IFNAMSIZ);
393
394	ic->ic_ifp = ifp;
395	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
396	ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */
397	ic->ic_state = IEEE80211_S_INIT;
398
399	/* set device capabilities */
400	ic->ic_caps =
401	    IEEE80211_C_IBSS |		/* IBSS mode supported */
402	    IEEE80211_C_MONITOR |	/* monitor mode supported */
403	    IEEE80211_C_HOSTAP |	/* HostAp mode supported */
404	    IEEE80211_C_TXPMGT |	/* tx power management */
405	    IEEE80211_C_SHPREAMBLE |	/* short preamble supported */
406	    IEEE80211_C_SHSLOT |	/* short slot time supported */
407	    IEEE80211_C_WPA;		/* 802.11i */
408
409	if (sc->rf_rev == RT2560_RF_5222) {
410		/* set supported .11a rates */
411		ic->ic_sup_rates[IEEE80211_MODE_11A] = ieee80211_std_rateset_11a;
412
413		/* set supported .11a channels */
414		for (i = 36; i <= 64; i += 4) {
415			ic->ic_channels[i].ic_freq =
416			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
417			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
418		}
419		for (i = 100; i <= 140; i += 4) {
420			ic->ic_channels[i].ic_freq =
421			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
422			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
423		}
424		for (i = 149; i <= 161; i += 4) {
425			ic->ic_channels[i].ic_freq =
426			    ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
427			ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
428		}
429	}
430
431	/* set supported .11b and .11g rates */
432	ic->ic_sup_rates[IEEE80211_MODE_11B] = ieee80211_std_rateset_11b;
433	ic->ic_sup_rates[IEEE80211_MODE_11G] = ieee80211_std_rateset_11g;
434
435	/* set supported .11b and .11g channels (1 through 14) */
436	for (i = 1; i <= 14; i++) {
437		ic->ic_channels[i].ic_freq =
438		    ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
439		ic->ic_channels[i].ic_flags =
440		    IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
441		    IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
442	}
443
444	if_initialize(ifp);
445	ieee80211_ifattach(ic);
446	/* Use common softint-based if_input */
447	ifp->if_percpuq = if_percpuq_create(ifp);
448	if_register(ifp);
449
450	ic->ic_node_alloc = rt2560_node_alloc;
451	ic->ic_updateslot = rt2560_update_slot;
452	ic->ic_reset = rt2560_reset;
453
454	/* override state transition machine */
455	sc->sc_newstate = ic->ic_newstate;
456	ic->ic_newstate = rt2560_newstate;
457	ieee80211_media_init(ic, rt2560_media_change, ieee80211_media_status);
458
459	bpf_attach2(ifp, DLT_IEEE802_11_RADIO,
460	    sizeof(struct ieee80211_frame) + 64, &sc->sc_drvbpf);
461
462	sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
463	sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
464	sc->sc_rxtap.wr_ihdr.it_present = htole32(RT2560_RX_RADIOTAP_PRESENT);
465
466	sc->sc_txtap_len = sizeof sc->sc_txtapu;
467	sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
468	sc->sc_txtap.wt_ihdr.it_present = htole32(RT2560_TX_RADIOTAP_PRESENT);
469
470
471	sc->dwelltime = 200;
472
473	ieee80211_announce(ic);
474
475	if (pmf_device_register(sc->sc_dev, NULL, NULL))
476		pmf_class_network_register(sc->sc_dev, ifp);
477	else
478		aprint_error_dev(sc->sc_dev,
479		    "couldn't establish power handler\n");
480
481	return 0;
482
483fail5:	rt2560_free_tx_ring(sc, &sc->bcnq);
484fail4:	rt2560_free_tx_ring(sc, &sc->prioq);
485fail3:	rt2560_free_tx_ring(sc, &sc->atimq);
486fail2:	rt2560_free_tx_ring(sc, &sc->txq);
487fail1:	softint_disestablish(sc->sc_soft_ih);
488	sc->sc_soft_ih = NULL;
489fail0:	return ENXIO;
490}
491
492
493int
494rt2560_detach(void *xsc)
495{
496	struct rt2560_softc *sc = xsc;
497	struct ifnet *ifp = &sc->sc_if;
498
499	callout_stop(&sc->scan_ch);
500	callout_stop(&sc->rssadapt_ch);
501
502	pmf_device_deregister(sc->sc_dev);
503
504	rt2560_stop(ifp, 1);
505
506	ieee80211_ifdetach(&sc->sc_ic);	/* free all nodes */
507	if_detach(ifp);
508
509	rt2560_free_tx_ring(sc, &sc->txq);
510	rt2560_free_tx_ring(sc, &sc->atimq);
511	rt2560_free_tx_ring(sc, &sc->prioq);
512	rt2560_free_tx_ring(sc, &sc->bcnq);
513	rt2560_free_rx_ring(sc, &sc->rxq);
514
515	if (sc->sc_soft_ih != NULL) {
516		softint_disestablish(sc->sc_soft_ih);
517		sc->sc_soft_ih = NULL;
518	}
519
520	return 0;
521}
522
523int
524rt2560_alloc_tx_ring(struct rt2560_softc *sc, struct rt2560_tx_ring *ring,
525    int count)
526{
527	int i, nsegs, error;
528
529	ring->count = count;
530	ring->queued = 0;
531	ring->cur = ring->next = 0;
532	ring->cur_encrypt = ring->next_encrypt = 0;
533
534	error = bus_dmamap_create(sc->sc_dmat, count * RT2560_TX_DESC_SIZE, 1,
535	    count * RT2560_TX_DESC_SIZE, 0, BUS_DMA_NOWAIT, &ring->map);
536	if (error != 0) {
537		aprint_error_dev(sc->sc_dev, "could not create desc DMA map\n");
538		goto fail;
539	}
540
541	error = bus_dmamem_alloc(sc->sc_dmat, count * RT2560_TX_DESC_SIZE,
542	    PAGE_SIZE, 0, &ring->seg, 1, &nsegs, BUS_DMA_NOWAIT);
543	if (error != 0) {
544		aprint_error_dev(sc->sc_dev, "could not allocate DMA memory\n");
545		goto fail;
546	}
547
548	error = bus_dmamem_map(sc->sc_dmat, &ring->seg, nsegs,
549	    count * RT2560_TX_DESC_SIZE, (void **)&ring->desc,
550	    BUS_DMA_NOWAIT);
551	if (error != 0) {
552		aprint_error_dev(sc->sc_dev, "could not map desc DMA memory\n");
553		goto fail;
554	}
555
556	error = bus_dmamap_load(sc->sc_dmat, ring->map, ring->desc,
557	    count * RT2560_TX_DESC_SIZE, NULL, BUS_DMA_NOWAIT);
558	if (error != 0) {
559		aprint_error_dev(sc->sc_dev, "could not load desc DMA map\n");
560		goto fail;
561	}
562
563	memset(ring->desc, 0, count * RT2560_TX_DESC_SIZE);
564	ring->physaddr = ring->map->dm_segs->ds_addr;
565
566	ring->data = malloc(count * sizeof (struct rt2560_tx_data), M_DEVBUF,
567	    M_WAITOK | M_ZERO);
568
569	for (i = 0; i < count; i++) {
570		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES,
571		    RT2560_MAX_SCATTER, MCLBYTES, 0, BUS_DMA_NOWAIT,
572		    &ring->data[i].map);
573		if (error != 0) {
574			aprint_error_dev(sc->sc_dev, "could not create DMA map\n");
575			goto fail;
576		}
577	}
578
579	return 0;
580
581fail:	rt2560_free_tx_ring(sc, ring);
582	return error;
583}
584
585void
586rt2560_reset_tx_ring(struct rt2560_softc *sc, struct rt2560_tx_ring *ring)
587{
588	struct rt2560_tx_desc *desc;
589	struct rt2560_tx_data *data;
590	int i;
591
592	for (i = 0; i < ring->count; i++) {
593		desc = &ring->desc[i];
594		data = &ring->data[i];
595
596		if (data->m != NULL) {
597			bus_dmamap_sync(sc->sc_dmat, data->map, 0,
598			    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
599			bus_dmamap_unload(sc->sc_dmat, data->map);
600			m_freem(data->m);
601			data->m = NULL;
602		}
603
604		if (data->ni != NULL) {
605			ieee80211_free_node(data->ni);
606			data->ni = NULL;
607		}
608
609		desc->flags = 0;
610	}
611
612	bus_dmamap_sync(sc->sc_dmat, ring->map, 0, ring->map->dm_mapsize,
613	    BUS_DMASYNC_PREWRITE);
614
615	ring->queued = 0;
616	ring->cur = ring->next = 0;
617	ring->cur_encrypt = ring->next_encrypt = 0;
618}
619
620void
621rt2560_free_tx_ring(struct rt2560_softc *sc, struct rt2560_tx_ring *ring)
622{
623	struct rt2560_tx_data *data;
624	int i;
625
626	if (ring->desc != NULL) {
627		bus_dmamap_sync(sc->sc_dmat, ring->map, 0,
628		    ring->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
629		bus_dmamap_unload(sc->sc_dmat, ring->map);
630		bus_dmamem_unmap(sc->sc_dmat, (void *)ring->desc,
631		    ring->count * RT2560_TX_DESC_SIZE);
632		bus_dmamem_free(sc->sc_dmat, &ring->seg, 1);
633	}
634
635	if (ring->data != NULL) {
636		for (i = 0; i < ring->count; i++) {
637			data = &ring->data[i];
638
639			if (data->m != NULL) {
640				bus_dmamap_sync(sc->sc_dmat, data->map, 0,
641				    data->map->dm_mapsize,
642				    BUS_DMASYNC_POSTWRITE);
643				bus_dmamap_unload(sc->sc_dmat, data->map);
644				m_freem(data->m);
645			}
646
647			if (data->ni != NULL)
648				ieee80211_free_node(data->ni);
649
650
651			if (data->map != NULL)
652				bus_dmamap_destroy(sc->sc_dmat, data->map);
653		}
654		free(ring->data, M_DEVBUF);
655	}
656}
657
658int
659rt2560_alloc_rx_ring(struct rt2560_softc *sc, struct rt2560_rx_ring *ring,
660    int count)
661{
662	struct rt2560_rx_desc *desc;
663	struct rt2560_rx_data *data;
664	int i, nsegs, error;
665
666	ring->count = count;
667	ring->cur = ring->next = 0;
668	ring->cur_decrypt = 0;
669
670	error = bus_dmamap_create(sc->sc_dmat, count * RT2560_RX_DESC_SIZE, 1,
671	    count * RT2560_RX_DESC_SIZE, 0, BUS_DMA_NOWAIT, &ring->map);
672	if (error != 0) {
673		aprint_error_dev(sc->sc_dev, "could not create desc DMA map\n");
674		goto fail;
675	}
676
677	error = bus_dmamem_alloc(sc->sc_dmat, count * RT2560_RX_DESC_SIZE,
678	    PAGE_SIZE, 0, &ring->seg, 1, &nsegs, BUS_DMA_NOWAIT);
679	if (error != 0) {
680		aprint_error_dev(sc->sc_dev, "could not allocate DMA memory\n");
681		goto fail;
682	}
683
684	error = bus_dmamem_map(sc->sc_dmat, &ring->seg, nsegs,
685	    count * RT2560_RX_DESC_SIZE, (void **)&ring->desc,
686	    BUS_DMA_NOWAIT);
687	if (error != 0) {
688		aprint_error_dev(sc->sc_dev, "could not map desc DMA memory\n");
689		goto fail;
690	}
691
692	error = bus_dmamap_load(sc->sc_dmat, ring->map, ring->desc,
693	    count * RT2560_RX_DESC_SIZE, NULL, BUS_DMA_NOWAIT);
694	if (error != 0) {
695		aprint_error_dev(sc->sc_dev, "could not load desc DMA map\n");
696		goto fail;
697	}
698
699	memset(ring->desc, 0, count * RT2560_RX_DESC_SIZE);
700	ring->physaddr = ring->map->dm_segs->ds_addr;
701
702	ring->data = malloc(count * sizeof (struct rt2560_rx_data), M_DEVBUF,
703	    M_WAITOK | M_ZERO);
704
705	/*
706	 * Pre-allocate Rx buffers and populate Rx ring.
707	 */
708	for (i = 0; i < count; i++) {
709		desc = &sc->rxq.desc[i];
710		data = &sc->rxq.data[i];
711
712		error = bus_dmamap_create(sc->sc_dmat, MCLBYTES, 1, MCLBYTES,
713		    0, BUS_DMA_NOWAIT, &data->map);
714		if (error != 0) {
715			aprint_error_dev(sc->sc_dev, "could not create DMA map\n");
716			goto fail;
717		}
718
719		MGETHDR(data->m, M_DONTWAIT, MT_DATA);
720		if (data->m == NULL) {
721			aprint_error_dev(sc->sc_dev, "could not allocate rx mbuf\n");
722			error = ENOMEM;
723			goto fail;
724		}
725
726		MCLGET(data->m, M_DONTWAIT);
727		if (!(data->m->m_flags & M_EXT)) {
728			aprint_error_dev(sc->sc_dev, "could not allocate rx mbuf cluster\n");
729			error = ENOMEM;
730			goto fail;
731		}
732
733		error = bus_dmamap_load(sc->sc_dmat, data->map,
734		    mtod(data->m, void *), MCLBYTES, NULL, BUS_DMA_NOWAIT);
735		if (error != 0) {
736			aprint_error_dev(sc->sc_dev, "could not load rx buf DMA map");
737			goto fail;
738		}
739
740		desc->flags = htole32(RT2560_RX_BUSY);
741		desc->physaddr = htole32(data->map->dm_segs->ds_addr);
742	}
743
744	bus_dmamap_sync(sc->sc_dmat, ring->map, 0, ring->map->dm_mapsize,
745	    BUS_DMASYNC_PREWRITE);
746
747	return 0;
748
749fail:	rt2560_free_rx_ring(sc, ring);
750	return error;
751}
752
753void
754rt2560_reset_rx_ring(struct rt2560_softc *sc, struct rt2560_rx_ring *ring)
755{
756	int i;
757
758	for (i = 0; i < ring->count; i++) {
759		ring->desc[i].flags = htole32(RT2560_RX_BUSY);
760		ring->data[i].drop = 0;
761	}
762
763	bus_dmamap_sync(sc->sc_dmat, ring->map, 0, ring->map->dm_mapsize,
764	    BUS_DMASYNC_PREWRITE);
765
766	ring->cur = ring->next = 0;
767	ring->cur_decrypt = 0;
768}
769
770void
771rt2560_free_rx_ring(struct rt2560_softc *sc, struct rt2560_rx_ring *ring)
772{
773	struct rt2560_rx_data *data;
774	int i;
775
776	if (ring->desc != NULL) {
777		bus_dmamap_sync(sc->sc_dmat, ring->map, 0,
778		    ring->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
779		bus_dmamap_unload(sc->sc_dmat, ring->map);
780		bus_dmamem_unmap(sc->sc_dmat, (void *)ring->desc,
781		    ring->count * RT2560_RX_DESC_SIZE);
782		bus_dmamem_free(sc->sc_dmat, &ring->seg, 1);
783	}
784
785	if (ring->data != NULL) {
786		for (i = 0; i < ring->count; i++) {
787			data = &ring->data[i];
788
789			if (data->m != NULL) {
790				bus_dmamap_sync(sc->sc_dmat, data->map, 0,
791				    data->map->dm_mapsize,
792				    BUS_DMASYNC_POSTREAD);
793				bus_dmamap_unload(sc->sc_dmat, data->map);
794				m_freem(data->m);
795			}
796
797			if (data->map != NULL)
798				bus_dmamap_destroy(sc->sc_dmat, data->map);
799		}
800		free(ring->data, M_DEVBUF);
801	}
802}
803
804struct ieee80211_node *
805rt2560_node_alloc(struct ieee80211_node_table *nt)
806{
807	struct rt2560_node *rn;
808
809	rn = malloc(sizeof (struct rt2560_node), M_80211_NODE,
810	    M_NOWAIT | M_ZERO);
811
812	return (rn != NULL) ? &rn->ni : NULL;
813}
814
815int
816rt2560_media_change(struct ifnet *ifp)
817{
818	int error;
819
820	error = ieee80211_media_change(ifp);
821	if (error != ENETRESET)
822		return error;
823
824	if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
825		rt2560_init(ifp);
826
827	return 0;
828}
829
830/*
831 * This function is called periodically (every 200ms) during scanning to
832 * switch from one channel to another.
833 */
834void
835rt2560_next_scan(void *arg)
836{
837	struct rt2560_softc *sc = arg;
838	struct ieee80211com *ic = &sc->sc_ic;
839	int s;
840
841	s = splnet();
842	if (ic->ic_state == IEEE80211_S_SCAN)
843		ieee80211_next_scan(ic);
844	splx(s);
845}
846
847/*
848 * This function is called for each neighbor node.
849 */
850void
851rt2560_iter_func(void *arg, struct ieee80211_node *ni)
852{
853	struct rt2560_node *rn = (struct rt2560_node *)ni;
854
855	ieee80211_rssadapt_updatestats(&rn->rssadapt);
856}
857
858/*
859 * This function is called periodically (every 100ms) in RUN state to update
860 * the rate adaptation statistics.
861 */
862void
863rt2560_update_rssadapt(void *arg)
864{
865	struct rt2560_softc *sc = arg;
866	struct ieee80211com *ic = &sc->sc_ic;
867	int s;
868
869	s = splnet();
870	ieee80211_iterate_nodes(&ic->ic_sta, rt2560_iter_func, arg);
871
872	callout_reset(&sc->rssadapt_ch, hz / 10, rt2560_update_rssadapt, sc);
873	splx(s);
874}
875
876int
877rt2560_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
878{
879	struct rt2560_softc *sc = ic->ic_ifp->if_softc;
880	enum ieee80211_state ostate;
881	struct ieee80211_node *ni;
882	struct mbuf *m;
883	int error = 0;
884
885	ostate = ic->ic_state;
886	callout_stop(&sc->scan_ch);
887
888	switch (nstate) {
889	case IEEE80211_S_INIT:
890		callout_stop(&sc->rssadapt_ch);
891
892		if (ostate == IEEE80211_S_RUN) {
893			/* abort TSF synchronization */
894			RAL_WRITE(sc, RT2560_CSR14, 0);
895
896			/* turn association led off */
897			rt2560_update_led(sc, 0, 0);
898		}
899		break;
900
901	case IEEE80211_S_SCAN:
902		rt2560_set_chan(sc, ic->ic_curchan);
903		callout_reset(&sc->scan_ch, (sc->dwelltime * hz) / 1000,
904		    rt2560_next_scan, sc);
905		break;
906
907	case IEEE80211_S_AUTH:
908		rt2560_set_chan(sc, ic->ic_curchan);
909		break;
910
911	case IEEE80211_S_ASSOC:
912		rt2560_set_chan(sc, ic->ic_curchan);
913		break;
914
915	case IEEE80211_S_RUN:
916		rt2560_set_chan(sc, ic->ic_curchan);
917
918		ni = ic->ic_bss;
919
920		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
921			rt2560_update_plcp(sc);
922			rt2560_set_basicrates(sc);
923			rt2560_set_bssid(sc, ni->ni_bssid);
924		}
925
926		if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
927		    ic->ic_opmode == IEEE80211_M_IBSS) {
928			m = ieee80211_beacon_alloc(ic, ni, &sc->sc_bo);
929			if (m == NULL) {
930				aprint_error_dev(sc->sc_dev, "could not allocate beacon\n");
931				error = ENOBUFS;
932				break;
933			}
934
935			ieee80211_ref_node(ni);
936			error = rt2560_tx_bcn(sc, m, ni);
937			if (error != 0)
938				break;
939		}
940
941		/* turn association led on */
942		rt2560_update_led(sc, 1, 0);
943
944		if (ic->ic_opmode != IEEE80211_M_MONITOR) {
945			callout_reset(&sc->rssadapt_ch, hz / 10,
946			    rt2560_update_rssadapt, sc);
947			rt2560_enable_tsf_sync(sc);
948		}
949		break;
950	}
951
952	return (error != 0) ? error : sc->sc_newstate(ic, nstate, arg);
953}
954
955/*
956 * Read 16 bits at address 'addr' from the serial EEPROM (either 93C46 or
957 * 93C66).
958 */
959uint16_t
960rt2560_eeprom_read(struct rt2560_softc *sc, uint8_t addr)
961{
962	uint32_t tmp;
963	uint16_t val;
964	int n;
965
966	/* clock C once before the first command */
967	RT2560_EEPROM_CTL(sc, 0);
968
969	RT2560_EEPROM_CTL(sc, RT2560_S);
970	RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_C);
971	RT2560_EEPROM_CTL(sc, RT2560_S);
972
973	/* write start bit (1) */
974	RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_D);
975	RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_D | RT2560_C);
976
977	/* write READ opcode (10) */
978	RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_D);
979	RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_D | RT2560_C);
980	RT2560_EEPROM_CTL(sc, RT2560_S);
981	RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_C);
982
983	/* write address (A5-A0 or A7-A0) */
984	n = (RAL_READ(sc, RT2560_CSR21) & RT2560_93C46) ? 5 : 7;
985	for (; n >= 0; n--) {
986		RT2560_EEPROM_CTL(sc, RT2560_S |
987		    (((addr >> n) & 1) << RT2560_SHIFT_D));
988		RT2560_EEPROM_CTL(sc, RT2560_S |
989		    (((addr >> n) & 1) << RT2560_SHIFT_D) | RT2560_C);
990	}
991
992	RT2560_EEPROM_CTL(sc, RT2560_S);
993
994	/* read data Q15-Q0 */
995	val = 0;
996	for (n = 15; n >= 0; n--) {
997		RT2560_EEPROM_CTL(sc, RT2560_S | RT2560_C);
998		tmp = RAL_READ(sc, RT2560_CSR21);
999		val |= ((tmp & RT2560_Q) >> RT2560_SHIFT_Q) << n;
1000		RT2560_EEPROM_CTL(sc, RT2560_S);
1001	}
1002
1003	RT2560_EEPROM_CTL(sc, 0);
1004
1005	/* clear Chip Select and clock C */
1006	RT2560_EEPROM_CTL(sc, RT2560_S);
1007	RT2560_EEPROM_CTL(sc, 0);
1008	RT2560_EEPROM_CTL(sc, RT2560_C);
1009
1010	return val;
1011}
1012
1013/*
1014 * Some frames were processed by the hardware cipher engine and are ready for
1015 * transmission.
1016 */
1017void
1018rt2560_encryption_intr(struct rt2560_softc *sc)
1019{
1020	struct rt2560_tx_desc *desc;
1021	int hw;
1022
1023	/* retrieve last descriptor index processed by cipher engine */
1024	hw = (RAL_READ(sc, RT2560_SECCSR1) - sc->txq.physaddr) /
1025	    RT2560_TX_DESC_SIZE;
1026
1027	for (; sc->txq.next_encrypt != hw;) {
1028		desc = &sc->txq.desc[sc->txq.next_encrypt];
1029
1030		bus_dmamap_sync(sc->sc_dmat, sc->txq.map,
1031		    sc->txq.next_encrypt * RT2560_TX_DESC_SIZE,
1032		    RT2560_TX_DESC_SIZE, BUS_DMASYNC_POSTREAD);
1033
1034		if (le32toh(desc->flags) &
1035		    (RT2560_TX_BUSY | RT2560_TX_CIPHER_BUSY))
1036			break;
1037
1038		/* for TKIP, swap eiv field to fix a bug in ASIC */
1039		if ((le32toh(desc->flags) & RT2560_TX_CIPHER_MASK) ==
1040		    RT2560_TX_CIPHER_TKIP)
1041			desc->eiv = bswap32(desc->eiv);
1042
1043		/* mark the frame ready for transmission */
1044		desc->flags |= htole32(RT2560_TX_BUSY | RT2560_TX_VALID);
1045
1046		bus_dmamap_sync(sc->sc_dmat, sc->txq.map,
1047		    sc->txq.next_encrypt * RT2560_TX_DESC_SIZE,
1048		    RT2560_TX_DESC_SIZE, BUS_DMASYNC_PREWRITE);
1049
1050		DPRINTFN(15, ("encryption done idx=%u\n",
1051		    sc->txq.next_encrypt));
1052
1053		sc->txq.next_encrypt =
1054		    (sc->txq.next_encrypt + 1) % RT2560_TX_RING_COUNT;
1055	}
1056
1057	/* kick Tx */
1058	RAL_WRITE(sc, RT2560_TXCSR0, RT2560_KICK_TX);
1059}
1060
1061void
1062rt2560_tx_intr(struct rt2560_softc *sc)
1063{
1064	struct ieee80211com *ic = &sc->sc_ic;
1065	struct ifnet *ifp = ic->ic_ifp;
1066	struct rt2560_tx_desc *desc;
1067	struct rt2560_tx_data *data;
1068	struct rt2560_node *rn;
1069	int s;
1070
1071	s = splnet();
1072
1073	for (;;) {
1074		desc = &sc->txq.desc[sc->txq.next];
1075		data = &sc->txq.data[sc->txq.next];
1076
1077		bus_dmamap_sync(sc->sc_dmat, sc->txq.map,
1078		    sc->txq.next * RT2560_TX_DESC_SIZE, RT2560_TX_DESC_SIZE,
1079		    BUS_DMASYNC_POSTREAD);
1080
1081		if ((le32toh(desc->flags) & RT2560_TX_BUSY) ||
1082		    (le32toh(desc->flags) & RT2560_TX_CIPHER_BUSY) ||
1083		    !(le32toh(desc->flags) & RT2560_TX_VALID))
1084			break;
1085
1086		rn = (struct rt2560_node *)data->ni;
1087
1088		switch (le32toh(desc->flags) & RT2560_TX_RESULT_MASK) {
1089		case RT2560_TX_SUCCESS:
1090			DPRINTFN(10, ("data frame sent successfully\n"));
1091			if (data->id.id_node != NULL) {
1092				ieee80211_rssadapt_raise_rate(ic,
1093				    &rn->rssadapt, &data->id);
1094			}
1095			if_statinc(ifp, if_opackets);
1096			break;
1097
1098		case RT2560_TX_SUCCESS_RETRY:
1099			DPRINTFN(9, ("data frame sent after %u retries\n",
1100			    (le32toh(desc->flags) >> 5) & 0x7));
1101			if_statinc(ifp, if_opackets);
1102			break;
1103
1104		case RT2560_TX_FAIL_RETRY:
1105			DPRINTFN(9, ("sending data frame failed (too much "
1106			    "retries)\n"));
1107			if (data->id.id_node != NULL) {
1108				ieee80211_rssadapt_lower_rate(ic, data->ni,
1109				    &rn->rssadapt, &data->id);
1110			}
1111			if_statinc(ifp, if_oerrors);
1112			break;
1113
1114		case RT2560_TX_FAIL_INVALID:
1115		case RT2560_TX_FAIL_OTHER:
1116		default:
1117			aprint_error_dev(sc->sc_dev,
1118			    "sending data frame failed 0x%08x\n",
1119			    le32toh(desc->flags));
1120			if_statinc(ifp, if_oerrors);
1121		}
1122
1123		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1124		    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
1125		bus_dmamap_unload(sc->sc_dmat, data->map);
1126		m_freem(data->m);
1127		data->m = NULL;
1128		ieee80211_free_node(data->ni);
1129		data->ni = NULL;
1130
1131		/* descriptor is no longer valid */
1132		desc->flags &= ~htole32(RT2560_TX_VALID);
1133
1134		bus_dmamap_sync(sc->sc_dmat, sc->txq.map,
1135		    sc->txq.next * RT2560_TX_DESC_SIZE, RT2560_TX_DESC_SIZE,
1136		    BUS_DMASYNC_PREWRITE);
1137
1138		DPRINTFN(15, ("tx done idx=%u\n", sc->txq.next));
1139
1140		sc->txq.queued--;
1141		sc->txq.next = (sc->txq.next + 1) % RT2560_TX_RING_COUNT;
1142	}
1143
1144	sc->sc_tx_timer = 0;
1145	ifp->if_flags &= ~IFF_OACTIVE;
1146	rt2560_start(ifp); /* in softint */
1147
1148	splx(s);
1149}
1150
1151void
1152rt2560_prio_intr(struct rt2560_softc *sc)
1153{
1154	struct ieee80211com *ic = &sc->sc_ic;
1155	struct ifnet *ifp = ic->ic_ifp;
1156	struct rt2560_tx_desc *desc;
1157	struct rt2560_tx_data *data;
1158	int s;
1159
1160	s = splnet();
1161
1162	for (;;) {
1163		desc = &sc->prioq.desc[sc->prioq.next];
1164		data = &sc->prioq.data[sc->prioq.next];
1165
1166		bus_dmamap_sync(sc->sc_dmat, sc->prioq.map,
1167		    sc->prioq.next * RT2560_TX_DESC_SIZE, RT2560_TX_DESC_SIZE,
1168		    BUS_DMASYNC_POSTREAD);
1169
1170		if ((le32toh(desc->flags) & RT2560_TX_BUSY) ||
1171		    !(le32toh(desc->flags) & RT2560_TX_VALID))
1172			break;
1173
1174		switch (le32toh(desc->flags) & RT2560_TX_RESULT_MASK) {
1175		case RT2560_TX_SUCCESS:
1176			DPRINTFN(10, ("mgt frame sent successfully\n"));
1177			break;
1178
1179		case RT2560_TX_SUCCESS_RETRY:
1180			DPRINTFN(9, ("mgt frame sent after %u retries\n",
1181			    (le32toh(desc->flags) >> 5) & 0x7));
1182			break;
1183
1184		case RT2560_TX_FAIL_RETRY:
1185			DPRINTFN(9, ("sending mgt frame failed (too much "
1186			    "retries)\n"));
1187			break;
1188
1189		case RT2560_TX_FAIL_INVALID:
1190		case RT2560_TX_FAIL_OTHER:
1191		default:
1192			aprint_error_dev(sc->sc_dev, "sending mgt frame failed 0x%08x\n",
1193			    le32toh(desc->flags));
1194		}
1195
1196		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1197		    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
1198		bus_dmamap_unload(sc->sc_dmat, data->map);
1199		m_freem(data->m);
1200		data->m = NULL;
1201		ieee80211_free_node(data->ni);
1202		data->ni = NULL;
1203
1204		/* descriptor is no longer valid */
1205		desc->flags &= ~htole32(RT2560_TX_VALID);
1206
1207		bus_dmamap_sync(sc->sc_dmat, sc->prioq.map,
1208		    sc->prioq.next * RT2560_TX_DESC_SIZE, RT2560_TX_DESC_SIZE,
1209		    BUS_DMASYNC_PREWRITE);
1210
1211		DPRINTFN(15, ("prio done idx=%u\n", sc->prioq.next));
1212
1213		sc->prioq.queued--;
1214		sc->prioq.next = (sc->prioq.next + 1) % RT2560_PRIO_RING_COUNT;
1215	}
1216
1217	sc->sc_tx_timer = 0;
1218	ifp->if_flags &= ~IFF_OACTIVE;
1219	rt2560_start(ifp); /* in softint */
1220
1221	splx(s);
1222}
1223
1224/*
1225 * Some frames were processed by the hardware cipher engine and are ready for
1226 * transmission to the IEEE802.11 layer.
1227 */
1228void
1229rt2560_decryption_intr(struct rt2560_softc *sc)
1230{
1231	struct ieee80211com *ic = &sc->sc_ic;
1232	struct ifnet *ifp = ic->ic_ifp;
1233	struct rt2560_rx_desc *desc;
1234	struct rt2560_rx_data *data;
1235	struct rt2560_node *rn;
1236	struct ieee80211_frame *wh;
1237	struct ieee80211_node *ni;
1238	struct mbuf *mnew, *m;
1239	int hw, error, s;
1240
1241	/* retrieve last descriptor index processed by cipher engine */
1242	hw = (RAL_READ(sc, RT2560_SECCSR0) - sc->rxq.physaddr) /
1243	    RT2560_RX_DESC_SIZE;
1244
1245	for (; sc->rxq.cur_decrypt != hw;) {
1246		desc = &sc->rxq.desc[sc->rxq.cur_decrypt];
1247		data = &sc->rxq.data[sc->rxq.cur_decrypt];
1248
1249		bus_dmamap_sync(sc->sc_dmat, sc->rxq.map,
1250		    sc->rxq.cur_decrypt * RT2560_TX_DESC_SIZE,
1251		    RT2560_TX_DESC_SIZE, BUS_DMASYNC_POSTREAD);
1252
1253		if (le32toh(desc->flags) &
1254		    (RT2560_RX_BUSY | RT2560_RX_CIPHER_BUSY))
1255			break;
1256
1257		if (data->drop) {
1258			if_statinc(ifp, if_ierrors);
1259			goto skip;
1260		}
1261
1262		if ((le32toh(desc->flags) & RT2560_RX_CIPHER_MASK) != 0 &&
1263		    (le32toh(desc->flags) & RT2560_RX_ICV_ERROR)) {
1264			if_statinc(ifp, if_ierrors);
1265			goto skip;
1266		}
1267
1268		/*
1269		 * Try to allocate a new mbuf for this ring element and load it
1270		 * before processing the current mbuf.  If the ring element
1271		 * cannot be loaded, drop the received packet and reuse the old
1272		 * mbuf.  In the unlikely case that the old mbuf can't be
1273		 * reloaded either, explicitly panic.
1274		 */
1275		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
1276		if (mnew == NULL) {
1277			if_statinc(ifp, if_ierrors);
1278			goto skip;
1279		}
1280
1281		MCLGET(mnew, M_DONTWAIT);
1282		if (!(mnew->m_flags & M_EXT)) {
1283			m_freem(mnew);
1284			if_statinc(ifp, if_ierrors);
1285			goto skip;
1286		}
1287
1288		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1289		    data->map->dm_mapsize, BUS_DMASYNC_POSTREAD);
1290		bus_dmamap_unload(sc->sc_dmat, data->map);
1291
1292		error = bus_dmamap_load(sc->sc_dmat, data->map,
1293		    mtod(mnew, void *), MCLBYTES, NULL, BUS_DMA_NOWAIT);
1294		if (error != 0) {
1295			m_freem(mnew);
1296
1297			/* try to reload the old mbuf */
1298			error = bus_dmamap_load(sc->sc_dmat, data->map,
1299			    mtod(data->m, void *), MCLBYTES, NULL,
1300			    BUS_DMA_NOWAIT);
1301			if (error != 0) {
1302				/* very unlikely that it will fail... */
1303				panic("%s: could not load old rx mbuf",
1304				    device_xname(sc->sc_dev));
1305			}
1306			/* physical address may have changed */
1307			desc->physaddr = htole32(data->map->dm_segs->ds_addr);
1308			if_statinc(ifp, if_ierrors);
1309			goto skip;
1310		}
1311
1312		/*
1313		 * New mbuf successfully loaded, update Rx ring and continue
1314		 * processing.
1315		 */
1316		m = data->m;
1317		data->m = mnew;
1318		desc->physaddr = htole32(data->map->dm_segs->ds_addr);
1319
1320		/* finalize mbuf */
1321		m_set_rcvif(m, ifp);
1322		m->m_pkthdr.len = m->m_len =
1323		    (le32toh(desc->flags) >> 16) & 0xfff;
1324
1325		s = splnet();
1326
1327		if (sc->sc_drvbpf != NULL) {
1328			struct rt2560_rx_radiotap_header *tap = &sc->sc_rxtap;
1329			uint32_t tsf_lo, tsf_hi;
1330
1331			/* get timestamp (low and high 32 bits) */
1332			tsf_hi = RAL_READ(sc, RT2560_CSR17);
1333			tsf_lo = RAL_READ(sc, RT2560_CSR16);
1334
1335			tap->wr_tsf =
1336			    htole64(((uint64_t)tsf_hi << 32) | tsf_lo);
1337			tap->wr_flags = 0;
1338			tap->wr_rate = rt2560_rxrate(desc);
1339			tap->wr_chan_freq = htole16(ic->ic_ibss_chan->ic_freq);
1340			tap->wr_chan_flags =
1341			    htole16(ic->ic_ibss_chan->ic_flags);
1342			tap->wr_antenna = sc->rx_ant;
1343			tap->wr_antsignal = desc->rssi;
1344
1345			bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m,
1346			    BPF_D_IN);
1347		}
1348
1349		wh = mtod(m, struct ieee80211_frame *);
1350		ni = ieee80211_find_rxnode(ic,
1351		    (struct ieee80211_frame_min *)wh);
1352
1353		/* send the frame to the 802.11 layer */
1354		ieee80211_input(ic, m, ni, desc->rssi, 0);
1355
1356		/* give rssi to the rate adatation algorithm */
1357		rn = (struct rt2560_node *)ni;
1358		ieee80211_rssadapt_input(ic, ni, &rn->rssadapt, desc->rssi);
1359
1360		/* node is no longer needed */
1361		ieee80211_free_node(ni);
1362
1363		splx(s);
1364
1365skip:		desc->flags = htole32(RT2560_RX_BUSY);
1366
1367		bus_dmamap_sync(sc->sc_dmat, sc->rxq.map,
1368		    sc->rxq.cur_decrypt * RT2560_TX_DESC_SIZE,
1369		    RT2560_TX_DESC_SIZE, BUS_DMASYNC_PREWRITE);
1370
1371		DPRINTFN(15, ("decryption done idx=%u\n", sc->rxq.cur_decrypt));
1372
1373		sc->rxq.cur_decrypt =
1374		    (sc->rxq.cur_decrypt + 1) % RT2560_RX_RING_COUNT;
1375	}
1376
1377	/*
1378	 * In HostAP mode, ieee80211_input() will enqueue packets in if_snd
1379	 * without calling if_start().
1380	 */
1381	s = splnet();
1382	if (!IFQ_IS_EMPTY(&ifp->if_snd) && !(ifp->if_flags & IFF_OACTIVE))
1383		rt2560_start(ifp);
1384	splx(s);
1385}
1386
1387/*
1388 * Some frames were received. Pass them to the hardware cipher engine before
1389 * sending them to the 802.11 layer.
1390 */
1391void
1392rt2560_rx_intr(struct rt2560_softc *sc)
1393{
1394	struct rt2560_rx_desc *desc;
1395	struct rt2560_rx_data *data;
1396
1397	for (;;) {
1398		desc = &sc->rxq.desc[sc->rxq.cur];
1399		data = &sc->rxq.data[sc->rxq.cur];
1400
1401		bus_dmamap_sync(sc->sc_dmat, sc->rxq.map,
1402		    sc->rxq.cur * RT2560_RX_DESC_SIZE, RT2560_RX_DESC_SIZE,
1403		    BUS_DMASYNC_POSTREAD);
1404
1405		if (le32toh(desc->flags) &
1406		    (RT2560_RX_BUSY | RT2560_RX_CIPHER_BUSY))
1407			break;
1408
1409		data->drop = 0;
1410
1411		if (le32toh(desc->flags) &
1412		    (RT2560_RX_PHY_ERROR | RT2560_RX_CRC_ERROR)) {
1413			/*
1414			 * This should not happen since we did not request
1415			 * to receive those frames when we filled RXCSR0.
1416			 */
1417			DPRINTFN(5, ("PHY or CRC error flags 0x%08x\n",
1418			    le32toh(desc->flags)));
1419			data->drop = 1;
1420		}
1421
1422		if (((le32toh(desc->flags) >> 16) & 0xfff) > MCLBYTES) {
1423			DPRINTFN(5, ("bad length\n"));
1424			data->drop = 1;
1425		}
1426
1427		/* mark the frame for decryption */
1428		desc->flags |= htole32(RT2560_RX_CIPHER_BUSY);
1429
1430		bus_dmamap_sync(sc->sc_dmat, sc->rxq.map,
1431		    sc->rxq.cur * RT2560_RX_DESC_SIZE, RT2560_RX_DESC_SIZE,
1432		    BUS_DMASYNC_PREWRITE);
1433
1434		DPRINTFN(15, ("rx done idx=%u\n", sc->rxq.cur));
1435
1436		sc->rxq.cur = (sc->rxq.cur + 1) % RT2560_RX_RING_COUNT;
1437	}
1438
1439	/* kick decrypt */
1440	RAL_WRITE(sc, RT2560_SECCSR0, RT2560_KICK_DECRYPT);
1441}
1442
1443/*
1444 * This function is called periodically in IBSS mode when a new beacon must be
1445 * sent out.
1446 */
1447static void
1448rt2560_beacon_expire(struct rt2560_softc *sc)
1449{
1450	struct ieee80211com *ic = &sc->sc_ic;
1451	struct rt2560_tx_data *data;
1452
1453	if (ic->ic_opmode != IEEE80211_M_IBSS &&
1454	    ic->ic_opmode != IEEE80211_M_HOSTAP)
1455		return;
1456
1457	data = &sc->bcnq.data[sc->bcnq.next];
1458
1459	bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1460	    data->map->dm_mapsize, BUS_DMASYNC_POSTWRITE);
1461	bus_dmamap_unload(sc->sc_dmat, data->map);
1462
1463	ieee80211_beacon_update(ic, data->ni, &sc->sc_bo, data->m, 1);
1464
1465	bpf_mtap3(ic->ic_rawbpf, data->m, BPF_D_OUT);
1466	rt2560_tx_bcn(sc, data->m, data->ni);
1467
1468	DPRINTFN(15, ("beacon expired\n"));
1469
1470	sc->bcnq.next = (sc->bcnq.next + 1) % RT2560_BEACON_RING_COUNT;
1471}
1472
1473static void
1474rt2560_wakeup_expire(struct rt2560_softc *sc)
1475{
1476	DPRINTFN(15, ("wakeup expired\n"));
1477}
1478
1479int
1480rt2560_intr(void *arg)
1481{
1482	struct rt2560_softc *sc = arg;
1483	struct ifnet *ifp = &sc->sc_if;
1484	uint32_t r;
1485
1486	if (!device_is_active(sc->sc_dev))
1487		return 0;
1488
1489	if ((r = RAL_READ(sc, RT2560_CSR7)) == 0)
1490		return 0;       /* not for us */
1491
1492	/* disable interrupts */
1493	RAL_WRITE(sc, RT2560_CSR8, 0xffffffff);
1494
1495	/* don't re-enable interrupts if we're shutting down */
1496	if (!(ifp->if_flags & IFF_RUNNING))
1497		return 0;
1498
1499	softint_schedule(sc->sc_soft_ih);
1500	return 1;
1501}
1502
1503static void
1504rt2560_softintr(void *arg)
1505{
1506	struct rt2560_softc *sc = arg;
1507	struct ifnet *ifp = &sc->sc_if;
1508	uint32_t r;
1509
1510	if (!device_is_active(sc->sc_dev) || !(ifp->if_flags & IFF_RUNNING))
1511		return;
1512
1513	if ((r = RAL_READ(sc, RT2560_CSR7)) == 0)
1514		goto out;
1515
1516	/* acknowledge interrupts */
1517	RAL_WRITE(sc, RT2560_CSR7, r);
1518
1519	if (r & RT2560_BEACON_EXPIRE)
1520		rt2560_beacon_expire(sc);
1521
1522	if (r & RT2560_WAKEUP_EXPIRE)
1523		rt2560_wakeup_expire(sc);
1524
1525	if (r & RT2560_ENCRYPTION_DONE)
1526		rt2560_encryption_intr(sc);
1527
1528	if (r & RT2560_TX_DONE)
1529		rt2560_tx_intr(sc);
1530
1531	if (r & RT2560_PRIO_DONE)
1532		rt2560_prio_intr(sc);
1533
1534	if (r & RT2560_DECRYPTION_DONE)
1535		rt2560_decryption_intr(sc);
1536
1537	if (r & RT2560_RX_DONE)
1538		rt2560_rx_intr(sc);
1539
1540out:
1541	/* re-enable interrupts */
1542	RAL_WRITE(sc, RT2560_CSR8, RT2560_INTR_MASK);
1543}
1544
1545/* quickly determine if a given rate is CCK or OFDM */
1546#define RAL_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
1547
1548#define RAL_ACK_SIZE	14	/* 10 + 4(FCS) */
1549#define RAL_CTS_SIZE	14	/* 10 + 4(FCS) */
1550
1551#define RAL_SIFS		10	/* us */
1552
1553#define RT2560_RXTX_TURNAROUND	10	/* us */
1554
1555/*
1556 * This function is only used by the Rx radiotap code. It returns the rate at
1557 * which a given frame was received.
1558 */
1559static uint8_t
1560rt2560_rxrate(struct rt2560_rx_desc *desc)
1561{
1562	if (le32toh(desc->flags) & RT2560_RX_OFDM) {
1563		/* reverse function of rt2560_plcp_signal */
1564		switch (desc->rate) {
1565		case 0xb:	return 12;
1566		case 0xf:	return 18;
1567		case 0xa:	return 24;
1568		case 0xe:	return 36;
1569		case 0x9:	return 48;
1570		case 0xd:	return 72;
1571		case 0x8:	return 96;
1572		case 0xc:	return 108;
1573		}
1574	} else {
1575		if (desc->rate == 10)
1576			return 2;
1577		if (desc->rate == 20)
1578			return 4;
1579		if (desc->rate == 55)
1580			return 11;
1581		if (desc->rate == 110)
1582			return 22;
1583	}
1584	return 2;	/* should not get there */
1585}
1586
1587/*
1588 * Return the expected ack rate for a frame transmitted at rate `rate'.
1589 * XXX: this should depend on the destination node basic rate set.
1590 */
1591static int
1592rt2560_ack_rate(struct ieee80211com *ic, int rate)
1593{
1594	switch (rate) {
1595	/* CCK rates */
1596	case 2:
1597		return 2;
1598	case 4:
1599	case 11:
1600	case 22:
1601		return (ic->ic_curmode == IEEE80211_MODE_11B) ? 4 : rate;
1602
1603	/* OFDM rates */
1604	case 12:
1605	case 18:
1606		return 12;
1607	case 24:
1608	case 36:
1609		return 24;
1610	case 48:
1611	case 72:
1612	case 96:
1613	case 108:
1614		return 48;
1615	}
1616
1617	/* default to 1Mbps */
1618	return 2;
1619}
1620
1621/*
1622 * Compute the duration (in us) needed to transmit `len' bytes at rate `rate'.
1623 * The function automatically determines the operating mode depending on the
1624 * given rate. `flags' indicates whether short preamble is in use or not.
1625 */
1626static uint16_t
1627rt2560_txtime(int len, int rate, uint32_t flags)
1628{
1629	uint16_t txtime;
1630
1631	if (RAL_RATE_IS_OFDM(rate)) {
1632		/* IEEE Std 802.11a-1999, pp. 37 */
1633		txtime = (8 + 4 * len + 3 + rate - 1) / rate;
1634		txtime = 16 + 4 + 4 * txtime + 6;
1635	} else {
1636		/* IEEE Std 802.11b-1999, pp. 28 */
1637		txtime = (16 * len + rate - 1) / rate;
1638		if (rate != 2 && (flags & IEEE80211_F_SHPREAMBLE))
1639			txtime +=  72 + 24;
1640		else
1641			txtime += 144 + 48;
1642	}
1643	return txtime;
1644}
1645
1646static uint8_t
1647rt2560_plcp_signal(int rate)
1648{
1649	switch (rate) {
1650	/* CCK rates (returned values are device-dependent) */
1651	case 2:		return 0x0;
1652	case 4:		return 0x1;
1653	case 11:	return 0x2;
1654	case 22:	return 0x3;
1655
1656	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1657	case 12:	return 0xb;
1658	case 18:	return 0xf;
1659	case 24:	return 0xa;
1660	case 36:	return 0xe;
1661	case 48:	return 0x9;
1662	case 72:	return 0xd;
1663	case 96:	return 0x8;
1664	case 108:	return 0xc;
1665
1666	/* unsupported rates (should not get there) */
1667	default:	return 0xff;
1668	}
1669}
1670
1671static void
1672rt2560_setup_tx_desc(struct rt2560_softc *sc, struct rt2560_tx_desc *desc,
1673    uint32_t flags, int len, int rate, int encrypt, bus_addr_t physaddr)
1674{
1675	struct ieee80211com *ic = &sc->sc_ic;
1676	uint16_t plcp_length;
1677	int remainder;
1678
1679	desc->flags = htole32(flags);
1680	desc->flags |= htole32(len << 16);
1681	desc->flags |= encrypt ? htole32(RT2560_TX_CIPHER_BUSY) :
1682	    htole32(RT2560_TX_BUSY | RT2560_TX_VALID);
1683
1684	desc->physaddr = htole32(physaddr);
1685	desc->wme = htole16(
1686	    RT2560_AIFSN(2) |
1687	    RT2560_LOGCWMIN(3) |
1688	    RT2560_LOGCWMAX(8));
1689
1690	/* setup PLCP fields */
1691	desc->plcp_signal  = rt2560_plcp_signal(rate);
1692	desc->plcp_service = 4;
1693
1694	len += IEEE80211_CRC_LEN;
1695	if (RAL_RATE_IS_OFDM(rate)) {
1696		desc->flags |= htole32(RT2560_TX_OFDM);
1697
1698		plcp_length = len & 0xfff;
1699		desc->plcp_length_hi = plcp_length >> 6;
1700		desc->plcp_length_lo = plcp_length & 0x3f;
1701	} else {
1702		plcp_length = (16 * len + rate - 1) / rate;
1703		if (rate == 22) {
1704			remainder = (16 * len) % 22;
1705			if (remainder != 0 && remainder < 7)
1706				desc->plcp_service |= RT2560_PLCP_LENGEXT;
1707		}
1708		desc->plcp_length_hi = plcp_length >> 8;
1709		desc->plcp_length_lo = plcp_length & 0xff;
1710
1711		if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1712			desc->plcp_signal |= 0x08;
1713	}
1714}
1715
1716static int
1717rt2560_tx_bcn(struct rt2560_softc *sc, struct mbuf *m0,
1718    struct ieee80211_node *ni)
1719{
1720	struct rt2560_tx_desc *desc;
1721	struct rt2560_tx_data *data;
1722	int rate, error;
1723
1724	desc = &sc->bcnq.desc[sc->bcnq.cur];
1725	data = &sc->bcnq.data[sc->bcnq.cur];
1726
1727	rate = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? 12 : 2;
1728
1729	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1730	    BUS_DMA_NOWAIT);
1731	if (error != 0) {
1732		aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n",
1733		    error);
1734		m_freem(m0);
1735		return error;
1736	}
1737
1738	data->m = m0;
1739	data->ni = ni;
1740
1741	rt2560_setup_tx_desc(sc, desc, RT2560_TX_IFS_NEWBACKOFF |
1742	    RT2560_TX_TIMESTAMP, m0->m_pkthdr.len, rate, 0,
1743	    data->map->dm_segs->ds_addr);
1744
1745	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
1746	    BUS_DMASYNC_PREWRITE);
1747	bus_dmamap_sync(sc->sc_dmat, sc->bcnq.map,
1748	    sc->bcnq.cur * RT2560_TX_DESC_SIZE, RT2560_TX_DESC_SIZE,
1749	    BUS_DMASYNC_PREWRITE);
1750
1751	return 0;
1752}
1753
1754static int
1755rt2560_tx_mgt(struct rt2560_softc *sc, struct mbuf *m0,
1756    struct ieee80211_node *ni)
1757{
1758	struct ieee80211com *ic = &sc->sc_ic;
1759	struct rt2560_tx_desc *desc;
1760	struct rt2560_tx_data *data;
1761	struct ieee80211_frame *wh;
1762	struct ieee80211_key *k;
1763	uint16_t dur;
1764	uint32_t flags = 0;
1765	int rate, error;
1766
1767	desc = &sc->prioq.desc[sc->prioq.cur];
1768	data = &sc->prioq.data[sc->prioq.cur];
1769
1770	rate = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? 12 : 2;
1771
1772	wh = mtod(m0, struct ieee80211_frame *);
1773
1774	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1775		k = ieee80211_crypto_encap(ic, ni, m0);
1776		if (k == NULL) {
1777			m_freem(m0);
1778			return ENOBUFS;
1779		}
1780
1781		/* packet header may have moved, reset our local pointer */
1782		wh = mtod(m0, struct ieee80211_frame *);
1783	}
1784
1785	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1786	    BUS_DMA_NOWAIT);
1787	if (error != 0) {
1788		aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n",
1789		    error);
1790		m_freem(m0);
1791		return error;
1792	}
1793
1794	if (sc->sc_drvbpf != NULL) {
1795		struct rt2560_tx_radiotap_header *tap = &sc->sc_txtap;
1796
1797		tap->wt_flags = 0;
1798		tap->wt_rate = rate;
1799		tap->wt_chan_freq = htole16(ic->ic_ibss_chan->ic_freq);
1800		tap->wt_chan_flags = htole16(ic->ic_ibss_chan->ic_flags);
1801		tap->wt_antenna = sc->tx_ant;
1802
1803		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0, BPF_D_OUT);
1804	}
1805
1806	data->m = m0;
1807	data->ni = ni;
1808
1809	wh = mtod(m0, struct ieee80211_frame *);
1810
1811	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1812		flags |= RT2560_TX_ACK;
1813
1814		dur = rt2560_txtime(RAL_ACK_SIZE, rate, ic->ic_flags) +
1815		    RAL_SIFS;
1816		*(uint16_t *)wh->i_dur = htole16(dur);
1817
1818		/* tell hardware to add timestamp for probe responses */
1819		if ((wh->i_fc[0] &
1820		    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1821		    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1822			flags |= RT2560_TX_TIMESTAMP;
1823	}
1824
1825	rt2560_setup_tx_desc(sc, desc, flags, m0->m_pkthdr.len, rate, 0,
1826	    data->map->dm_segs->ds_addr);
1827
1828	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
1829	    BUS_DMASYNC_PREWRITE);
1830	bus_dmamap_sync(sc->sc_dmat, sc->prioq.map,
1831	    sc->prioq.cur * RT2560_TX_DESC_SIZE, RT2560_TX_DESC_SIZE,
1832	    BUS_DMASYNC_PREWRITE);
1833
1834	DPRINTFN(10, ("sending mgt frame len=%u idx=%u rate=%u\n",
1835	    m0->m_pkthdr.len, sc->prioq.cur, rate));
1836
1837	/* kick prio */
1838	sc->prioq.queued++;
1839	sc->prioq.cur = (sc->prioq.cur + 1) % RT2560_PRIO_RING_COUNT;
1840	RAL_WRITE(sc, RT2560_TXCSR0, RT2560_KICK_PRIO);
1841
1842	return 0;
1843}
1844
1845/*
1846 * Build a RTS control frame.
1847 */
1848static struct mbuf *
1849rt2560_get_rts(struct rt2560_softc *sc, struct ieee80211_frame *wh,
1850    uint16_t dur)
1851{
1852	struct ieee80211_frame_rts *rts;
1853	struct mbuf *m;
1854
1855	MGETHDR(m, M_DONTWAIT, MT_DATA);
1856	if (m == NULL) {
1857		sc->sc_ic.ic_stats.is_tx_nobuf++;
1858		aprint_error_dev(sc->sc_dev, "could not allocate RTS frame\n");
1859		return NULL;
1860	}
1861
1862	rts = mtod(m, struct ieee80211_frame_rts *);
1863
1864	rts->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_CTL |
1865	    IEEE80211_FC0_SUBTYPE_RTS;
1866	rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1867	*(uint16_t *)rts->i_dur = htole16(dur);
1868	IEEE80211_ADDR_COPY(rts->i_ra, wh->i_addr1);
1869	IEEE80211_ADDR_COPY(rts->i_ta, wh->i_addr2);
1870
1871	m->m_pkthdr.len = m->m_len = sizeof (struct ieee80211_frame_rts);
1872
1873	return m;
1874}
1875
1876static int
1877rt2560_tx_data(struct rt2560_softc *sc, struct mbuf *m0,
1878    struct ieee80211_node *ni)
1879{
1880	struct ieee80211com *ic = &sc->sc_ic;
1881	struct rt2560_tx_desc *desc;
1882	struct rt2560_tx_data *data;
1883	struct rt2560_node *rn;
1884	struct ieee80211_rateset *rs;
1885	struct ieee80211_frame *wh;
1886	struct ieee80211_key *k;
1887	struct mbuf *mnew;
1888	uint16_t dur;
1889	uint32_t flags = 0;
1890	int rate, error;
1891
1892	wh = mtod(m0, struct ieee80211_frame *);
1893
1894	if (ic->ic_fixed_rate != IEEE80211_FIXED_RATE_NONE) {
1895		rs = &ic->ic_sup_rates[ic->ic_curmode];
1896		rate = rs->rs_rates[ic->ic_fixed_rate];
1897	} else {
1898		rs = &ni->ni_rates;
1899		rn = (struct rt2560_node *)ni;
1900		ni->ni_txrate = ieee80211_rssadapt_choose(&rn->rssadapt, rs,
1901		    wh, m0->m_pkthdr.len, -1, NULL, 0);
1902		rate = rs->rs_rates[ni->ni_txrate];
1903	}
1904	rate &= IEEE80211_RATE_VAL;
1905
1906	if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1907		k = ieee80211_crypto_encap(ic, ni, m0);
1908		if (k == NULL) {
1909			m_freem(m0);
1910			return ENOBUFS;
1911		}
1912
1913		/* packet header may have moved, reset our local pointer */
1914		wh = mtod(m0, struct ieee80211_frame *);
1915	}
1916
1917	/*
1918	 * IEEE Std 802.11-1999, pp 82: "A STA shall use an RTS/CTS exchange
1919	 * for directed frames only when the length of the MPDU is greater
1920	 * than the length threshold indicated by [...]" ic_rtsthreshold.
1921	 */
1922	if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1923	    m0->m_pkthdr.len > ic->ic_rtsthreshold) {
1924		struct mbuf *m;
1925		int rtsrate, ackrate;
1926
1927		rtsrate = IEEE80211_IS_CHAN_5GHZ(ni->ni_chan) ? 12 : 2;
1928		ackrate = rt2560_ack_rate(ic, rate);
1929
1930		dur = rt2560_txtime(m0->m_pkthdr.len + 4, rate, ic->ic_flags) +
1931		      rt2560_txtime(RAL_CTS_SIZE, rtsrate, ic->ic_flags) +
1932		      rt2560_txtime(RAL_ACK_SIZE, ackrate, ic->ic_flags) +
1933		      3 * RAL_SIFS;
1934
1935		m = rt2560_get_rts(sc, wh, dur);
1936
1937		desc = &sc->txq.desc[sc->txq.cur_encrypt];
1938		data = &sc->txq.data[sc->txq.cur_encrypt];
1939
1940		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m,
1941		    BUS_DMA_NOWAIT);
1942		if (error != 0) {
1943			aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n",
1944			    error);
1945			m_freem(m);
1946			m_freem(m0);
1947			return error;
1948		}
1949
1950		/* avoid multiple free() of the same node for each fragment */
1951		ieee80211_ref_node(ni);
1952
1953		data->m = m;
1954		data->ni = ni;
1955
1956		/* RTS frames are not taken into account for rssadapt */
1957		data->id.id_node = NULL;
1958
1959		rt2560_setup_tx_desc(sc, desc, RT2560_TX_ACK |
1960		    RT2560_TX_MORE_FRAG, m->m_pkthdr.len, rtsrate, 1,
1961		    data->map->dm_segs->ds_addr);
1962
1963		bus_dmamap_sync(sc->sc_dmat, data->map, 0,
1964		    data->map->dm_mapsize, BUS_DMASYNC_PREWRITE);
1965		bus_dmamap_sync(sc->sc_dmat, sc->txq.map,
1966		    sc->txq.cur_encrypt * RT2560_TX_DESC_SIZE,
1967		    RT2560_TX_DESC_SIZE, BUS_DMASYNC_PREWRITE);
1968
1969		sc->txq.queued++;
1970		sc->txq.cur_encrypt =
1971		    (sc->txq.cur_encrypt + 1) % RT2560_TX_RING_COUNT;
1972
1973		/*
1974		 * IEEE Std 802.11-1999: when an RTS/CTS exchange is used, the
1975		 * asynchronous data frame shall be transmitted after the CTS
1976		 * frame and a SIFS period.
1977		 */
1978		flags |= RT2560_TX_LONG_RETRY | RT2560_TX_IFS_SIFS;
1979	}
1980
1981	data = &sc->txq.data[sc->txq.cur_encrypt];
1982	desc = &sc->txq.desc[sc->txq.cur_encrypt];
1983
1984	error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
1985	    BUS_DMA_NOWAIT);
1986	if (error != 0 && error != EFBIG) {
1987		aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n",
1988		    error);
1989		m_freem(m0);
1990		return error;
1991	}
1992	if (error != 0) {
1993		/* too many fragments, linearize */
1994
1995		MGETHDR(mnew, M_DONTWAIT, MT_DATA);
1996		if (mnew == NULL) {
1997			m_freem(m0);
1998			return ENOMEM;
1999		}
2000
2001		m_copy_pkthdr(mnew, m0);
2002		if (m0->m_pkthdr.len > MHLEN) {
2003			MCLGET(mnew, M_DONTWAIT);
2004			if (!(mnew->m_flags & M_EXT)) {
2005				m_freem(m0);
2006				m_freem(mnew);
2007				return ENOMEM;
2008			}
2009		}
2010
2011		m_copydata(m0, 0, m0->m_pkthdr.len, mtod(mnew, void *));
2012		m_freem(m0);
2013		mnew->m_len = mnew->m_pkthdr.len;
2014		m0 = mnew;
2015
2016		error = bus_dmamap_load_mbuf(sc->sc_dmat, data->map, m0,
2017		    BUS_DMA_NOWAIT);
2018		if (error != 0) {
2019			aprint_error_dev(sc->sc_dev, "could not map mbuf (error %d)\n",
2020			    error);
2021			m_freem(m0);
2022			return error;
2023		}
2024
2025		/* packet header have moved, reset our local pointer */
2026		wh = mtod(m0, struct ieee80211_frame *);
2027	}
2028
2029	if (sc->sc_drvbpf != NULL) {
2030		struct rt2560_tx_radiotap_header *tap = &sc->sc_txtap;
2031
2032		tap->wt_flags = 0;
2033		tap->wt_rate = rate;
2034		tap->wt_chan_freq = htole16(ic->ic_ibss_chan->ic_freq);
2035		tap->wt_chan_flags = htole16(ic->ic_ibss_chan->ic_flags);
2036		tap->wt_antenna = sc->tx_ant;
2037
2038		bpf_mtap2(sc->sc_drvbpf, tap, sc->sc_txtap_len, m0, BPF_D_OUT);
2039	}
2040
2041	data->m = m0;
2042	data->ni = ni;
2043
2044	/* remember link conditions for rate adaptation algorithm */
2045	if (ic->ic_fixed_rate == IEEE80211_FIXED_RATE_NONE) {
2046		data->id.id_len = m0->m_pkthdr.len;
2047		data->id.id_rateidx = ni->ni_txrate;
2048		data->id.id_node = ni;
2049		data->id.id_rssi = ni->ni_rssi;
2050	} else
2051		data->id.id_node = NULL;
2052
2053	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
2054		flags |= RT2560_TX_ACK;
2055
2056		dur = rt2560_txtime(RAL_ACK_SIZE, rt2560_ack_rate(ic, rate),
2057		    ic->ic_flags) + RAL_SIFS;
2058		*(uint16_t *)wh->i_dur = htole16(dur);
2059	}
2060
2061	rt2560_setup_tx_desc(sc, desc, flags, m0->m_pkthdr.len, rate, 1,
2062	    data->map->dm_segs->ds_addr);
2063
2064	bus_dmamap_sync(sc->sc_dmat, data->map, 0, data->map->dm_mapsize,
2065	    BUS_DMASYNC_PREWRITE);
2066	bus_dmamap_sync(sc->sc_dmat, sc->txq.map,
2067	    sc->txq.cur_encrypt * RT2560_TX_DESC_SIZE, RT2560_TX_DESC_SIZE,
2068	    BUS_DMASYNC_PREWRITE);
2069
2070	DPRINTFN(10, ("sending data frame len=%u idx=%u rate=%u\n",
2071	    m0->m_pkthdr.len, sc->txq.cur_encrypt, rate));
2072
2073	/* kick encrypt */
2074	sc->txq.queued++;
2075	sc->txq.cur_encrypt = (sc->txq.cur_encrypt + 1) % RT2560_TX_RING_COUNT;
2076	RAL_WRITE(sc, RT2560_SECCSR1, RT2560_KICK_ENCRYPT);
2077
2078	return 0;
2079}
2080
2081static void
2082rt2560_start(struct ifnet *ifp)
2083{
2084	struct rt2560_softc *sc = ifp->if_softc;
2085	struct ieee80211com *ic = &sc->sc_ic;
2086	struct mbuf *m0;
2087	struct ieee80211_node *ni;
2088	struct ether_header *eh;
2089
2090	/*
2091	 * net80211 may still try to send management frames even if the
2092	 * IFF_RUNNING flag is not set...
2093	 */
2094	if ((ifp->if_flags & (IFF_RUNNING | IFF_OACTIVE)) != IFF_RUNNING)
2095		return;
2096
2097	for (;;) {
2098		IF_POLL(&ic->ic_mgtq, m0);
2099		if (m0 != NULL) {
2100			if (sc->prioq.queued >= RT2560_PRIO_RING_COUNT) {
2101				ifp->if_flags |= IFF_OACTIVE;
2102				break;
2103			}
2104			IF_DEQUEUE(&ic->ic_mgtq, m0);
2105			if (m0 == NULL)
2106				break;
2107
2108			ni = M_GETCTX(m0, struct ieee80211_node *);
2109			M_CLEARCTX(m0);
2110			bpf_mtap3(ic->ic_rawbpf, m0, BPF_D_OUT);
2111			if (rt2560_tx_mgt(sc, m0, ni) != 0)
2112				break;
2113
2114		} else {
2115			if (ic->ic_state != IEEE80211_S_RUN)
2116				break;
2117			IFQ_DEQUEUE(&ifp->if_snd, m0);
2118			if (m0 == NULL)
2119				break;
2120			if (sc->txq.queued >= RT2560_TX_RING_COUNT - 1) {
2121				ifp->if_flags |= IFF_OACTIVE;
2122				break;
2123			}
2124
2125			if (m0->m_len < sizeof (struct ether_header) &&
2126			    !(m0 = m_pullup(m0, sizeof (struct ether_header))))
2127                                continue;
2128
2129			eh = mtod(m0, struct ether_header *);
2130			ni = ieee80211_find_txnode(ic, eh->ether_dhost);
2131			if (ni == NULL) {
2132				m_freem(m0);
2133				continue;
2134			}
2135			bpf_mtap(ifp, m0, BPF_D_OUT);
2136
2137			m0 = ieee80211_encap(ic, m0, ni);
2138			if (m0 == NULL) {
2139				ieee80211_free_node(ni);
2140				continue;
2141                        }
2142
2143			bpf_mtap3(ic->ic_rawbpf, m0, BPF_D_OUT);
2144
2145			if (rt2560_tx_data(sc, m0, ni) != 0) {
2146				ieee80211_free_node(ni);
2147				if_statinc(ifp, if_oerrors);
2148				break;
2149			}
2150		}
2151
2152		sc->sc_tx_timer = 5;
2153		ifp->if_timer = 1;
2154	}
2155}
2156
2157static void
2158rt2560_watchdog(struct ifnet *ifp)
2159{
2160	struct rt2560_softc *sc = ifp->if_softc;
2161
2162	ifp->if_timer = 0;
2163
2164	if (sc->sc_tx_timer > 0) {
2165		if (--sc->sc_tx_timer == 0) {
2166			aprint_error_dev(sc->sc_dev, "device timeout\n");
2167			rt2560_init(ifp);
2168			if_statinc(ifp, if_oerrors);
2169			return;
2170		}
2171		ifp->if_timer = 1;
2172	}
2173
2174	ieee80211_watchdog(&sc->sc_ic);
2175}
2176
2177/*
2178 * This function allows for fast channel switching in monitor mode (used by
2179 * net-mgmt/kismet). In IBSS mode, we must explicitly reset the interface to
2180 * generate a new beacon frame.
2181 */
2182static int
2183rt2560_reset(struct ifnet *ifp)
2184{
2185	struct rt2560_softc *sc = ifp->if_softc;
2186	struct ieee80211com *ic = &sc->sc_ic;
2187
2188	if (ic->ic_opmode != IEEE80211_M_MONITOR)
2189		return ENETRESET;
2190
2191	rt2560_set_chan(sc, ic->ic_curchan);
2192
2193	return 0;
2194}
2195
2196int
2197rt2560_ioctl(struct ifnet *ifp, u_long cmd, void *data)
2198{
2199	struct rt2560_softc *sc = ifp->if_softc;
2200	struct ieee80211com *ic = &sc->sc_ic;
2201	int s, error = 0;
2202
2203	s = splnet();
2204
2205	switch (cmd) {
2206	case SIOCSIFFLAGS:
2207		if ((error = ifioctl_common(ifp, cmd, data)) != 0)
2208			break;
2209		if (ifp->if_flags & IFF_UP) {
2210			if (ifp->if_flags & IFF_RUNNING)
2211				rt2560_update_promisc(sc);
2212			else
2213				rt2560_init(ifp);
2214		} else {
2215			if (ifp->if_flags & IFF_RUNNING)
2216				rt2560_stop(ifp, 1);
2217		}
2218		break;
2219
2220	case SIOCADDMULTI:
2221	case SIOCDELMULTI:
2222		/* XXX no h/w multicast filter? --dyoung */
2223		if ((error = ether_ioctl(ifp, cmd, data)) == ENETRESET)
2224			error = 0;
2225		break;
2226
2227	case SIOCS80211CHANNEL:
2228		/*
2229		 * This allows for fast channel switching in monitor mode
2230		 * (used by kismet). In IBSS mode, we must explicitly reset
2231		 * the interface to generate a new beacon frame.
2232		 */
2233		error = ieee80211_ioctl(ic, cmd, data);
2234		if (error == ENETRESET &&
2235		    ic->ic_opmode == IEEE80211_M_MONITOR) {
2236			rt2560_set_chan(sc, ic->ic_ibss_chan);
2237			error = 0;
2238		}
2239		break;
2240
2241	default:
2242		error = ieee80211_ioctl(ic, cmd, data);
2243	}
2244
2245	if (error == ENETRESET) {
2246		if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
2247		    (IFF_UP | IFF_RUNNING))
2248			rt2560_init(ifp);
2249		error = 0;
2250	}
2251
2252	splx(s);
2253
2254	return error;
2255}
2256
2257static void
2258rt2560_bbp_write(struct rt2560_softc *sc, uint8_t reg, uint8_t val)
2259{
2260	uint32_t tmp;
2261	int ntries;
2262
2263	for (ntries = 0; ntries < 100; ntries++) {
2264		if (!(RAL_READ(sc, RT2560_BBPCSR) & RT2560_BBP_BUSY))
2265			break;
2266		DELAY(1);
2267	}
2268	if (ntries == 100) {
2269		aprint_error_dev(sc->sc_dev, "could not write to BBP\n");
2270		return;
2271	}
2272
2273	tmp = RT2560_BBP_WRITE | RT2560_BBP_BUSY | reg << 8 | val;
2274	RAL_WRITE(sc, RT2560_BBPCSR, tmp);
2275
2276	DPRINTFN(15, ("BBP R%u <- 0x%02x\n", reg, val));
2277}
2278
2279static uint8_t
2280rt2560_bbp_read(struct rt2560_softc *sc, uint8_t reg)
2281{
2282	uint32_t val;
2283	int ntries;
2284
2285	val = RT2560_BBP_BUSY | reg << 8;
2286	RAL_WRITE(sc, RT2560_BBPCSR, val);
2287
2288	for (ntries = 0; ntries < 100; ntries++) {
2289		val = RAL_READ(sc, RT2560_BBPCSR);
2290		if (!(val & RT2560_BBP_BUSY))
2291			return val & 0xff;
2292		DELAY(1);
2293	}
2294
2295	aprint_error_dev(sc->sc_dev, "could not read from BBP\n");
2296	return 0;
2297}
2298
2299static void
2300rt2560_rf_write(struct rt2560_softc *sc, uint8_t reg, uint32_t val)
2301{
2302	uint32_t tmp;
2303	int ntries;
2304
2305	for (ntries = 0; ntries < 100; ntries++) {
2306		if (!(RAL_READ(sc, RT2560_RFCSR) & RT2560_RF_BUSY))
2307			break;
2308		DELAY(1);
2309	}
2310	if (ntries == 100) {
2311		aprint_error_dev(sc->sc_dev, "could not write to RF\n");
2312		return;
2313	}
2314
2315	tmp = RT2560_RF_BUSY | RT2560_RF_20BIT | (val & 0xfffff) << 2 |
2316	    (reg & 0x3);
2317	RAL_WRITE(sc, RT2560_RFCSR, tmp);
2318
2319	/* remember last written value in sc */
2320	sc->rf_regs[reg] = val;
2321
2322	DPRINTFN(15, ("RF R[%u] <- 0x%05x\n", reg & 0x3, val & 0xfffff));
2323}
2324
2325static void
2326rt2560_set_chan(struct rt2560_softc *sc, struct ieee80211_channel *c)
2327{
2328	struct ieee80211com *ic = &sc->sc_ic;
2329	uint8_t power, tmp;
2330	u_int i, chan;
2331
2332	chan = ieee80211_chan2ieee(ic, c);
2333	if (chan == 0 || chan == IEEE80211_CHAN_ANY)
2334		return;
2335
2336	if (IEEE80211_IS_CHAN_2GHZ(c))
2337		power = uimin(sc->txpow[chan - 1], 31);
2338	else
2339		power = 31;
2340
2341	DPRINTFN(2, ("setting channel to %u, txpower to %u\n", chan, power));
2342
2343	switch (sc->rf_rev) {
2344	case RT2560_RF_2522:
2345		rt2560_rf_write(sc, RT2560_RF1, 0x00814);
2346		rt2560_rf_write(sc, RT2560_RF2, rt2560_rf2522_r2[chan - 1]);
2347		rt2560_rf_write(sc, RT2560_RF3, power << 7 | 0x00040);
2348		break;
2349
2350	case RT2560_RF_2523:
2351		rt2560_rf_write(sc, RT2560_RF1, 0x08804);
2352		rt2560_rf_write(sc, RT2560_RF2, rt2560_rf2523_r2[chan - 1]);
2353		rt2560_rf_write(sc, RT2560_RF3, power << 7 | 0x38044);
2354		rt2560_rf_write(sc, RT2560_RF4,
2355		    (chan == 14) ? 0x00280 : 0x00286);
2356		break;
2357
2358	case RT2560_RF_2524:
2359		rt2560_rf_write(sc, RT2560_RF1, 0x0c808);
2360		rt2560_rf_write(sc, RT2560_RF2, rt2560_rf2524_r2[chan - 1]);
2361		rt2560_rf_write(sc, RT2560_RF3, power << 7 | 0x00040);
2362		rt2560_rf_write(sc, RT2560_RF4,
2363		    (chan == 14) ? 0x00280 : 0x00286);
2364		break;
2365
2366	case RT2560_RF_2525:
2367		rt2560_rf_write(sc, RT2560_RF1, 0x08808);
2368		rt2560_rf_write(sc, RT2560_RF2, rt2560_rf2525_hi_r2[chan - 1]);
2369		rt2560_rf_write(sc, RT2560_RF3, power << 7 | 0x18044);
2370		rt2560_rf_write(sc, RT2560_RF4,
2371		    (chan == 14) ? 0x00280 : 0x00286);
2372
2373		rt2560_rf_write(sc, RT2560_RF1, 0x08808);
2374		rt2560_rf_write(sc, RT2560_RF2, rt2560_rf2525_r2[chan - 1]);
2375		rt2560_rf_write(sc, RT2560_RF3, power << 7 | 0x18044);
2376		rt2560_rf_write(sc, RT2560_RF4,
2377		    (chan == 14) ? 0x00280 : 0x00286);
2378		break;
2379
2380	case RT2560_RF_2525E:
2381		rt2560_rf_write(sc, RT2560_RF1, 0x08808);
2382		rt2560_rf_write(sc, RT2560_RF2, rt2560_rf2525e_r2[chan - 1]);
2383		rt2560_rf_write(sc, RT2560_RF3, power << 7 | 0x18044);
2384		rt2560_rf_write(sc, RT2560_RF4,
2385		    (chan == 14) ? 0x00286 : 0x00282);
2386		break;
2387
2388	case RT2560_RF_2526:
2389		rt2560_rf_write(sc, RT2560_RF2, rt2560_rf2526_hi_r2[chan - 1]);
2390		rt2560_rf_write(sc, RT2560_RF4,
2391		   (chan & 1) ? 0x00386 : 0x00381);
2392		rt2560_rf_write(sc, RT2560_RF1, 0x08804);
2393
2394		rt2560_rf_write(sc, RT2560_RF2, rt2560_rf2526_r2[chan - 1]);
2395		rt2560_rf_write(sc, RT2560_RF3, power << 7 | 0x18044);
2396		rt2560_rf_write(sc, RT2560_RF4,
2397		    (chan & 1) ? 0x00386 : 0x00381);
2398		break;
2399
2400	/* dual-band RF */
2401	case RT2560_RF_5222:
2402		for (i = 0; rt2560_rf5222[i].chan != chan; i++);
2403
2404		rt2560_rf_write(sc, RT2560_RF1, rt2560_rf5222[i].r1);
2405		rt2560_rf_write(sc, RT2560_RF2, rt2560_rf5222[i].r2);
2406		rt2560_rf_write(sc, RT2560_RF3, power << 7 | 0x00040);
2407		rt2560_rf_write(sc, RT2560_RF4, rt2560_rf5222[i].r4);
2408		break;
2409	}
2410
2411	if (ic->ic_opmode != IEEE80211_M_MONITOR &&
2412	    ic->ic_state != IEEE80211_S_SCAN) {
2413		/* set Japan filter bit for channel 14 */
2414		tmp = rt2560_bbp_read(sc, 70);
2415
2416		tmp &= ~RT2560_JAPAN_FILTER;
2417		if (chan == 14)
2418			tmp |= RT2560_JAPAN_FILTER;
2419
2420		rt2560_bbp_write(sc, 70, tmp);
2421
2422		DELAY(1000); /* RF needs a 1ms delay here */
2423		rt2560_disable_rf_tune(sc);
2424
2425		/* clear CRC errors */
2426		RAL_READ(sc, RT2560_CNT0);
2427	}
2428}
2429
2430/*
2431 * Disable RF auto-tuning.
2432 */
2433static void
2434rt2560_disable_rf_tune(struct rt2560_softc *sc)
2435{
2436	uint32_t tmp;
2437
2438	if (sc->rf_rev != RT2560_RF_2523) {
2439		tmp = sc->rf_regs[RT2560_RF1] & ~RT2560_RF1_AUTOTUNE;
2440		rt2560_rf_write(sc, RT2560_RF1, tmp);
2441	}
2442
2443	tmp = sc->rf_regs[RT2560_RF3] & ~RT2560_RF3_AUTOTUNE;
2444	rt2560_rf_write(sc, RT2560_RF3, tmp);
2445
2446	DPRINTFN(2, ("disabling RF autotune\n"));
2447}
2448
2449/*
2450 * Refer to IEEE Std 802.11-1999 pp. 123 for more information on TSF
2451 * synchronization.
2452 */
2453static void
2454rt2560_enable_tsf_sync(struct rt2560_softc *sc)
2455{
2456	struct ieee80211com *ic = &sc->sc_ic;
2457	uint16_t logcwmin, preload;
2458	uint32_t tmp;
2459
2460	/* first, disable TSF synchronization */
2461	RAL_WRITE(sc, RT2560_CSR14, 0);
2462
2463	tmp = 16 * ic->ic_bss->ni_intval;
2464	RAL_WRITE(sc, RT2560_CSR12, tmp);
2465
2466	RAL_WRITE(sc, RT2560_CSR13, 0);
2467
2468	logcwmin = 5;
2469	preload = (ic->ic_opmode == IEEE80211_M_STA) ? 384 : 1024;
2470	tmp = logcwmin << 16 | preload;
2471	RAL_WRITE(sc, RT2560_BCNOCSR, tmp);
2472
2473	/* finally, enable TSF synchronization */
2474	tmp = RT2560_ENABLE_TSF | RT2560_ENABLE_TBCN;
2475	if (ic->ic_opmode == IEEE80211_M_STA)
2476		tmp |= RT2560_ENABLE_TSF_SYNC(1);
2477	else
2478		tmp |= RT2560_ENABLE_TSF_SYNC(2) |
2479		       RT2560_ENABLE_BEACON_GENERATOR;
2480	RAL_WRITE(sc, RT2560_CSR14, tmp);
2481
2482	DPRINTF(("enabling TSF synchronization\n"));
2483}
2484
2485static void
2486rt2560_update_plcp(struct rt2560_softc *sc)
2487{
2488	struct ieee80211com *ic = &sc->sc_ic;
2489
2490	/* no short preamble for 1Mbps */
2491	RAL_WRITE(sc, RT2560_PLCP1MCSR, 0x00700400);
2492
2493	if (!(ic->ic_flags & IEEE80211_F_SHPREAMBLE)) {
2494		/* values taken from the reference driver */
2495		RAL_WRITE(sc, RT2560_PLCP2MCSR,   0x00380401);
2496		RAL_WRITE(sc, RT2560_PLCP5p5MCSR, 0x00150402);
2497		RAL_WRITE(sc, RT2560_PLCP11MCSR,  0x000b8403);
2498	} else {
2499		/* same values as above or'ed 0x8 */
2500		RAL_WRITE(sc, RT2560_PLCP2MCSR,   0x00380409);
2501		RAL_WRITE(sc, RT2560_PLCP5p5MCSR, 0x0015040a);
2502		RAL_WRITE(sc, RT2560_PLCP11MCSR,  0x000b840b);
2503	}
2504
2505	DPRINTF(("updating PLCP for %s preamble\n",
2506	    (ic->ic_flags & IEEE80211_F_SHPREAMBLE) ? "short" : "long"));
2507}
2508
2509/*
2510 * IEEE 802.11a uses short slot time. Refer to IEEE Std 802.11-1999 pp. 85 to
2511 * know how these values are computed.
2512 */
2513static void
2514rt2560_update_slot(struct ifnet *ifp)
2515{
2516	struct rt2560_softc *sc = ifp->if_softc;
2517	struct ieee80211com *ic = &sc->sc_ic;
2518	uint8_t slottime;
2519	uint16_t sifs, pifs, difs, eifs;
2520	uint32_t tmp;
2521
2522	slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
2523
2524	/* define the MAC slot boundaries */
2525	sifs = RAL_SIFS - RT2560_RXTX_TURNAROUND;
2526	pifs = sifs + slottime;
2527	difs = sifs + 2 * slottime;
2528	eifs = (ic->ic_curmode == IEEE80211_MODE_11B) ? 364 : 60;
2529
2530	tmp = RAL_READ(sc, RT2560_CSR11);
2531	tmp = (tmp & ~0x1f00) | slottime << 8;
2532	RAL_WRITE(sc, RT2560_CSR11, tmp);
2533
2534	tmp = pifs << 16 | sifs;
2535	RAL_WRITE(sc, RT2560_CSR18, tmp);
2536
2537	tmp = eifs << 16 | difs;
2538	RAL_WRITE(sc, RT2560_CSR19, tmp);
2539
2540	DPRINTF(("setting slottime to %uus\n", slottime));
2541}
2542
2543static void
2544rt2560_set_basicrates(struct rt2560_softc *sc)
2545{
2546	struct ieee80211com *ic = &sc->sc_ic;
2547
2548	/* update basic rate set */
2549	if (ic->ic_curmode == IEEE80211_MODE_11B) {
2550		/* 11b basic rates: 1, 2Mbps */
2551		RAL_WRITE(sc, RT2560_ARSP_PLCP_1, 0x3);
2552	} else if (IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan)) {
2553		/* 11a basic rates: 6, 12, 24Mbps */
2554		RAL_WRITE(sc, RT2560_ARSP_PLCP_1, 0x150);
2555	} else {
2556		/* 11g basic rates: 1, 2, 5.5, 11, 6, 12, 24Mbps */
2557		RAL_WRITE(sc, RT2560_ARSP_PLCP_1, 0x15f);
2558	}
2559}
2560
2561static void
2562rt2560_update_led(struct rt2560_softc *sc, int led1, int led2)
2563{
2564	uint32_t tmp;
2565
2566	/* set ON period to 70ms and OFF period to 30ms */
2567	tmp = led1 << 16 | led2 << 17 | 70 << 8 | 30;
2568	RAL_WRITE(sc, RT2560_LEDCSR, tmp);
2569}
2570
2571static void
2572rt2560_set_bssid(struct rt2560_softc *sc, uint8_t *bssid)
2573{
2574	uint32_t tmp;
2575
2576	tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24;
2577	RAL_WRITE(sc, RT2560_CSR5, tmp);
2578
2579	tmp = bssid[4] | bssid[5] << 8;
2580	RAL_WRITE(sc, RT2560_CSR6, tmp);
2581
2582	DPRINTF(("setting BSSID to %s\n", ether_sprintf(bssid)));
2583}
2584
2585static void
2586rt2560_set_macaddr(struct rt2560_softc *sc, uint8_t *addr)
2587{
2588	uint32_t tmp;
2589
2590	tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24;
2591	RAL_WRITE(sc, RT2560_CSR3, tmp);
2592
2593	tmp = addr[4] | addr[5] << 8;
2594	RAL_WRITE(sc, RT2560_CSR4, tmp);
2595
2596	DPRINTF(("setting MAC address to %s\n", ether_sprintf(addr)));
2597}
2598
2599static void
2600rt2560_get_macaddr(struct rt2560_softc *sc, uint8_t *addr)
2601{
2602	uint32_t tmp;
2603
2604	tmp = RAL_READ(sc, RT2560_CSR3);
2605	addr[0] = tmp & 0xff;
2606	addr[1] = (tmp >>  8) & 0xff;
2607	addr[2] = (tmp >> 16) & 0xff;
2608	addr[3] = (tmp >> 24);
2609
2610	tmp = RAL_READ(sc, RT2560_CSR4);
2611	addr[4] = tmp & 0xff;
2612	addr[5] = (tmp >> 8) & 0xff;
2613}
2614
2615static void
2616rt2560_update_promisc(struct rt2560_softc *sc)
2617{
2618	struct ifnet *ifp = &sc->sc_if;
2619	uint32_t tmp;
2620
2621	tmp = RAL_READ(sc, RT2560_RXCSR0);
2622
2623	tmp &= ~RT2560_DROP_NOT_TO_ME;
2624	if (!(ifp->if_flags & IFF_PROMISC))
2625		tmp |= RT2560_DROP_NOT_TO_ME;
2626
2627	RAL_WRITE(sc, RT2560_RXCSR0, tmp);
2628
2629	DPRINTF(("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
2630	    "entering" : "leaving"));
2631}
2632
2633static void
2634rt2560_set_txantenna(struct rt2560_softc *sc, int antenna)
2635{
2636	uint32_t tmp;
2637	uint8_t tx;
2638
2639	tx = rt2560_bbp_read(sc, RT2560_BBP_TX) & ~RT2560_BBP_ANTMASK;
2640	if (antenna == 1)
2641		tx |= RT2560_BBP_ANTA;
2642	else if (antenna == 2)
2643		tx |= RT2560_BBP_ANTB;
2644	else
2645		tx |= RT2560_BBP_DIVERSITY;
2646
2647	/* need to force I/Q flip for RF 2525e, 2526 and 5222 */
2648	if (sc->rf_rev == RT2560_RF_2525E || sc->rf_rev == RT2560_RF_2526 ||
2649	    sc->rf_rev == RT2560_RF_5222)
2650		tx |= RT2560_BBP_FLIPIQ;
2651
2652	rt2560_bbp_write(sc, RT2560_BBP_TX, tx);
2653
2654	/* update values for CCK and OFDM in BBPCSR1 */
2655	tmp = RAL_READ(sc, RT2560_BBPCSR1) & ~0x00070007;
2656	tmp |= (tx & 0x7) << 16 | (tx & 0x7);
2657	RAL_WRITE(sc, RT2560_BBPCSR1, tmp);
2658}
2659
2660static void
2661rt2560_set_rxantenna(struct rt2560_softc *sc, int antenna)
2662{
2663	uint8_t rx;
2664
2665	rx = rt2560_bbp_read(sc, RT2560_BBP_RX) & ~RT2560_BBP_ANTMASK;
2666	if (antenna == 1)
2667		rx |= RT2560_BBP_ANTA;
2668	else if (antenna == 2)
2669		rx |= RT2560_BBP_ANTB;
2670	else
2671		rx |= RT2560_BBP_DIVERSITY;
2672
2673	/* need to force no I/Q flip for RF 2525e and 2526 */
2674	if (sc->rf_rev == RT2560_RF_2525E || sc->rf_rev == RT2560_RF_2526)
2675		rx &= ~RT2560_BBP_FLIPIQ;
2676
2677	rt2560_bbp_write(sc, RT2560_BBP_RX, rx);
2678}
2679
2680static const char *
2681rt2560_get_rf(int rev)
2682{
2683	switch (rev) {
2684	case RT2560_RF_2522:	return "RT2522";
2685	case RT2560_RF_2523:	return "RT2523";
2686	case RT2560_RF_2524:	return "RT2524";
2687	case RT2560_RF_2525:	return "RT2525";
2688	case RT2560_RF_2525E:	return "RT2525e";
2689	case RT2560_RF_2526:	return "RT2526";
2690	case RT2560_RF_5222:	return "RT5222";
2691	default:		return "unknown";
2692	}
2693}
2694
2695static void
2696rt2560_read_eeprom(struct rt2560_softc *sc)
2697{
2698	uint16_t val;
2699	int i;
2700
2701	val = rt2560_eeprom_read(sc, RT2560_EEPROM_CONFIG0);
2702	sc->rf_rev =   (val >> 11) & 0x1f;
2703	sc->hw_radio = (val >> 10) & 0x1;
2704	sc->led_mode = (val >> 6)  & 0x7;
2705	sc->rx_ant =   (val >> 4)  & 0x3;
2706	sc->tx_ant =   (val >> 2)  & 0x3;
2707	sc->nb_ant =   val & 0x3;
2708
2709	/* read default values for BBP registers */
2710	for (i = 0; i < 16; i++) {
2711		val = rt2560_eeprom_read(sc, RT2560_EEPROM_BBP_BASE + i);
2712		sc->bbp_prom[i].reg = val >> 8;
2713		sc->bbp_prom[i].val = val & 0xff;
2714	}
2715
2716	/* read Tx power for all b/g channels */
2717	for (i = 0; i < 14 / 2; i++) {
2718		val = rt2560_eeprom_read(sc, RT2560_EEPROM_TXPOWER + i);
2719		sc->txpow[i * 2] = val >> 8;
2720		sc->txpow[i * 2 + 1] = val & 0xff;
2721	}
2722}
2723
2724static int
2725rt2560_bbp_init(struct rt2560_softc *sc)
2726{
2727#define N(a)	(sizeof (a) / sizeof ((a)[0]))
2728	int i, ntries;
2729
2730	/* wait for BBP to be ready */
2731	for (ntries = 0; ntries < 100; ntries++) {
2732		if (rt2560_bbp_read(sc, RT2560_BBP_VERSION) != 0)
2733			break;
2734		DELAY(1);
2735	}
2736	if (ntries == 100) {
2737		aprint_error_dev(sc->sc_dev, "timeout waiting for BBP\n");
2738		return EIO;
2739	}
2740
2741	/* initialize BBP registers to default values */
2742	for (i = 0; i < N(rt2560_def_bbp); i++) {
2743		rt2560_bbp_write(sc, rt2560_def_bbp[i].reg,
2744		    rt2560_def_bbp[i].val);
2745	}
2746#if 0
2747	/* initialize BBP registers to values stored in EEPROM */
2748	for (i = 0; i < 16; i++) {
2749		if (sc->bbp_prom[i].reg == 0xff)
2750			continue;
2751		rt2560_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2752	}
2753#endif
2754
2755	return 0;
2756#undef N
2757}
2758
2759static int
2760rt2560_init(struct ifnet *ifp)
2761{
2762#define N(a)	(sizeof (a) / sizeof ((a)[0]))
2763	struct rt2560_softc *sc = ifp->if_softc;
2764	struct ieee80211com *ic = &sc->sc_ic;
2765	uint32_t tmp;
2766	int i;
2767
2768	/* for CardBus, power on the socket */
2769	if (!(sc->sc_flags & RT2560_ENABLED)) {
2770		if (sc->sc_enable != NULL && (*sc->sc_enable)(sc) != 0) {
2771			aprint_error_dev(sc->sc_dev, "could not enable device\n");
2772			return EIO;
2773		}
2774		sc->sc_flags |= RT2560_ENABLED;
2775	}
2776
2777	rt2560_stop(ifp, 1);
2778
2779	/* setup tx rings */
2780	tmp = RT2560_PRIO_RING_COUNT << 24 |
2781	      RT2560_ATIM_RING_COUNT << 16 |
2782	      RT2560_TX_RING_COUNT   <<  8 |
2783	      RT2560_TX_DESC_SIZE;
2784
2785	/* rings _must_ be initialized in this _exact_ order! */
2786	RAL_WRITE(sc, RT2560_TXCSR2, tmp);
2787	RAL_WRITE(sc, RT2560_TXCSR3, sc->txq.physaddr);
2788	RAL_WRITE(sc, RT2560_TXCSR5, sc->prioq.physaddr);
2789	RAL_WRITE(sc, RT2560_TXCSR4, sc->atimq.physaddr);
2790	RAL_WRITE(sc, RT2560_TXCSR6, sc->bcnq.physaddr);
2791
2792	/* setup rx ring */
2793	tmp = RT2560_RX_RING_COUNT << 8 | RT2560_RX_DESC_SIZE;
2794
2795	RAL_WRITE(sc, RT2560_RXCSR1, tmp);
2796	RAL_WRITE(sc, RT2560_RXCSR2, sc->rxq.physaddr);
2797
2798	/* initialize MAC registers to default values */
2799	for (i = 0; i < N(rt2560_def_mac); i++)
2800		RAL_WRITE(sc, rt2560_def_mac[i].reg, rt2560_def_mac[i].val);
2801
2802	IEEE80211_ADDR_COPY(ic->ic_myaddr, CLLADDR(ifp->if_sadl));
2803	rt2560_set_macaddr(sc, ic->ic_myaddr);
2804
2805	/* set basic rate set (will be updated later) */
2806	RAL_WRITE(sc, RT2560_ARSP_PLCP_1, 0x153);
2807
2808	rt2560_update_slot(ifp);
2809	rt2560_update_plcp(sc);
2810	rt2560_update_led(sc, 0, 0);
2811
2812	RAL_WRITE(sc, RT2560_CSR1, RT2560_RESET_ASIC);
2813	RAL_WRITE(sc, RT2560_CSR1, RT2560_HOST_READY);
2814
2815	if (rt2560_bbp_init(sc) != 0) {
2816		rt2560_stop(ifp, 1);
2817		return EIO;
2818	}
2819
2820	rt2560_set_txantenna(sc, 1);
2821	rt2560_set_rxantenna(sc, 1);
2822
2823	/* set default BSS channel */
2824	ic->ic_bss->ni_chan = ic->ic_ibss_chan;
2825	rt2560_set_chan(sc, ic->ic_bss->ni_chan);
2826
2827	/* kick Rx */
2828	tmp = RT2560_DROP_PHY_ERROR | RT2560_DROP_CRC_ERROR;
2829	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2830		tmp |= RT2560_DROP_CTL | RT2560_DROP_VERSION_ERROR;
2831		if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2832			tmp |= RT2560_DROP_TODS;
2833		if (!(ifp->if_flags & IFF_PROMISC))
2834			tmp |= RT2560_DROP_NOT_TO_ME;
2835	}
2836	RAL_WRITE(sc, RT2560_RXCSR0, tmp);
2837
2838	/* clear old FCS and Rx FIFO errors */
2839	RAL_READ(sc, RT2560_CNT0);
2840	RAL_READ(sc, RT2560_CNT4);
2841
2842	/* clear any pending interrupts */
2843	RAL_WRITE(sc, RT2560_CSR7, 0xffffffff);
2844
2845	/* enable interrupts */
2846	RAL_WRITE(sc, RT2560_CSR8, RT2560_INTR_MASK);
2847
2848	ifp->if_flags &= ~IFF_OACTIVE;
2849	ifp->if_flags |= IFF_RUNNING;
2850
2851	if (ic->ic_opmode == IEEE80211_M_MONITOR)
2852		ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2853	else
2854		ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2855
2856	return 0;
2857#undef N
2858}
2859
2860static void
2861rt2560_stop(struct ifnet *ifp, int disable)
2862{
2863	struct rt2560_softc *sc = ifp->if_softc;
2864	struct ieee80211com *ic = &sc->sc_ic;
2865
2866	sc->sc_tx_timer = 0;
2867	ifp->if_timer = 0;
2868	ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2869
2870	ieee80211_new_state(ic, IEEE80211_S_INIT, -1);	/* free all nodes */
2871
2872	/* abort Tx */
2873	RAL_WRITE(sc, RT2560_TXCSR0, RT2560_ABORT_TX);
2874
2875	/* disable Rx */
2876	RAL_WRITE(sc, RT2560_RXCSR0, RT2560_DISABLE_RX);
2877
2878	/* reset ASIC (and thus, BBP) */
2879	RAL_WRITE(sc, RT2560_CSR1, RT2560_RESET_ASIC);
2880	RAL_WRITE(sc, RT2560_CSR1, 0);
2881
2882	/* disable interrupts */
2883	RAL_WRITE(sc, RT2560_CSR8, 0xffffffff);
2884
2885	/* clear any pending interrupt */
2886	RAL_WRITE(sc, RT2560_CSR7, 0xffffffff);
2887
2888	/* reset Tx and Rx rings */
2889	rt2560_reset_tx_ring(sc, &sc->txq);
2890	rt2560_reset_tx_ring(sc, &sc->atimq);
2891	rt2560_reset_tx_ring(sc, &sc->prioq);
2892	rt2560_reset_tx_ring(sc, &sc->bcnq);
2893	rt2560_reset_rx_ring(sc, &sc->rxq);
2894}
2895