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