xref: /freebsd/sys/dev/ral/rt2661.c (revision 389e4940069316fe667ffa263fa7d6390d0a960f)
1 /*	$FreeBSD$	*/
2 
3 /*-
4  * Copyright (c) 2006
5  *	Damien Bergamini <damien.bergamini@free.fr>
6  *
7  * Permission to use, copy, modify, and distribute this software for any
8  * purpose with or without fee is hereby granted, provided that the above
9  * copyright notice and this permission notice appear in all copies.
10  *
11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
18  */
19 
20 #include <sys/cdefs.h>
21 __FBSDID("$FreeBSD$");
22 
23 /*-
24  * Ralink Technology RT2561, RT2561S and RT2661 chipset driver
25  * http://www.ralinktech.com/
26  */
27 
28 #include <sys/param.h>
29 #include <sys/sysctl.h>
30 #include <sys/sockio.h>
31 #include <sys/mbuf.h>
32 #include <sys/kernel.h>
33 #include <sys/socket.h>
34 #include <sys/systm.h>
35 #include <sys/malloc.h>
36 #include <sys/lock.h>
37 #include <sys/mutex.h>
38 #include <sys/module.h>
39 #include <sys/bus.h>
40 #include <sys/endian.h>
41 #include <sys/firmware.h>
42 
43 #include <machine/bus.h>
44 #include <machine/resource.h>
45 #include <sys/rman.h>
46 
47 #include <net/bpf.h>
48 #include <net/if.h>
49 #include <net/if_var.h>
50 #include <net/if_arp.h>
51 #include <net/ethernet.h>
52 #include <net/if_dl.h>
53 #include <net/if_media.h>
54 #include <net/if_types.h>
55 
56 #include <net80211/ieee80211_var.h>
57 #include <net80211/ieee80211_radiotap.h>
58 #include <net80211/ieee80211_regdomain.h>
59 #include <net80211/ieee80211_ratectl.h>
60 
61 #include <netinet/in.h>
62 #include <netinet/in_systm.h>
63 #include <netinet/in_var.h>
64 #include <netinet/ip.h>
65 #include <netinet/if_ether.h>
66 
67 #include <dev/ral/rt2661reg.h>
68 #include <dev/ral/rt2661var.h>
69 
70 #define RAL_DEBUG
71 #ifdef RAL_DEBUG
72 #define DPRINTF(sc, fmt, ...) do {				\
73 	if (sc->sc_debug > 0)					\
74 		printf(fmt, __VA_ARGS__);			\
75 } while (0)
76 #define DPRINTFN(sc, n, fmt, ...) do {				\
77 	if (sc->sc_debug >= (n))				\
78 		printf(fmt, __VA_ARGS__);			\
79 } while (0)
80 #else
81 #define DPRINTF(sc, fmt, ...)
82 #define DPRINTFN(sc, n, fmt, ...)
83 #endif
84 
85 static struct ieee80211vap *rt2661_vap_create(struct ieee80211com *,
86 			    const char [IFNAMSIZ], int, enum ieee80211_opmode,
87 			    int, const uint8_t [IEEE80211_ADDR_LEN],
88 			    const uint8_t [IEEE80211_ADDR_LEN]);
89 static void		rt2661_vap_delete(struct ieee80211vap *);
90 static void		rt2661_dma_map_addr(void *, bus_dma_segment_t *, int,
91 			    int);
92 static int		rt2661_alloc_tx_ring(struct rt2661_softc *,
93 			    struct rt2661_tx_ring *, int);
94 static void		rt2661_reset_tx_ring(struct rt2661_softc *,
95 			    struct rt2661_tx_ring *);
96 static void		rt2661_free_tx_ring(struct rt2661_softc *,
97 			    struct rt2661_tx_ring *);
98 static int		rt2661_alloc_rx_ring(struct rt2661_softc *,
99 			    struct rt2661_rx_ring *, int);
100 static void		rt2661_reset_rx_ring(struct rt2661_softc *,
101 			    struct rt2661_rx_ring *);
102 static void		rt2661_free_rx_ring(struct rt2661_softc *,
103 			    struct rt2661_rx_ring *);
104 static int		rt2661_newstate(struct ieee80211vap *,
105 			    enum ieee80211_state, int);
106 static uint16_t		rt2661_eeprom_read(struct rt2661_softc *, uint8_t);
107 static void		rt2661_rx_intr(struct rt2661_softc *);
108 static void		rt2661_tx_intr(struct rt2661_softc *);
109 static void		rt2661_tx_dma_intr(struct rt2661_softc *,
110 			    struct rt2661_tx_ring *);
111 static void		rt2661_mcu_beacon_expire(struct rt2661_softc *);
112 static void		rt2661_mcu_wakeup(struct rt2661_softc *);
113 static void		rt2661_mcu_cmd_intr(struct rt2661_softc *);
114 static void		rt2661_scan_start(struct ieee80211com *);
115 static void		rt2661_scan_end(struct ieee80211com *);
116 static void		rt2661_getradiocaps(struct ieee80211com *, int, int *,
117 			    struct ieee80211_channel[]);
118 static void		rt2661_set_channel(struct ieee80211com *);
119 static void		rt2661_setup_tx_desc(struct rt2661_softc *,
120 			    struct rt2661_tx_desc *, uint32_t, uint16_t, int,
121 			    int, const bus_dma_segment_t *, int, int);
122 static int		rt2661_tx_data(struct rt2661_softc *, struct mbuf *,
123 			    struct ieee80211_node *, int);
124 static int		rt2661_tx_mgt(struct rt2661_softc *, struct mbuf *,
125 			    struct ieee80211_node *);
126 static int		rt2661_transmit(struct ieee80211com *, struct mbuf *);
127 static void		rt2661_start(struct rt2661_softc *);
128 static int		rt2661_raw_xmit(struct ieee80211_node *, struct mbuf *,
129 			    const struct ieee80211_bpf_params *);
130 static void		rt2661_watchdog(void *);
131 static void		rt2661_parent(struct ieee80211com *);
132 static void		rt2661_bbp_write(struct rt2661_softc *, uint8_t,
133 			    uint8_t);
134 static uint8_t		rt2661_bbp_read(struct rt2661_softc *, uint8_t);
135 static void		rt2661_rf_write(struct rt2661_softc *, uint8_t,
136 			    uint32_t);
137 static int		rt2661_tx_cmd(struct rt2661_softc *, uint8_t,
138 			    uint16_t);
139 static void		rt2661_select_antenna(struct rt2661_softc *);
140 static void		rt2661_enable_mrr(struct rt2661_softc *);
141 static void		rt2661_set_txpreamble(struct rt2661_softc *);
142 static void		rt2661_set_basicrates(struct rt2661_softc *,
143 			    const struct ieee80211_rateset *);
144 static void		rt2661_select_band(struct rt2661_softc *,
145 			    struct ieee80211_channel *);
146 static void		rt2661_set_chan(struct rt2661_softc *,
147 			    struct ieee80211_channel *);
148 static void		rt2661_set_bssid(struct rt2661_softc *,
149 			    const uint8_t *);
150 static void		rt2661_set_macaddr(struct rt2661_softc *,
151 			   const uint8_t *);
152 static void		rt2661_update_promisc(struct ieee80211com *);
153 static int		rt2661_wme_update(struct ieee80211com *) __unused;
154 static void		rt2661_update_slot(struct ieee80211com *);
155 static const char	*rt2661_get_rf(int);
156 static void		rt2661_read_eeprom(struct rt2661_softc *,
157 			    uint8_t macaddr[IEEE80211_ADDR_LEN]);
158 static int		rt2661_bbp_init(struct rt2661_softc *);
159 static void		rt2661_init_locked(struct rt2661_softc *);
160 static void		rt2661_init(void *);
161 static void             rt2661_stop_locked(struct rt2661_softc *);
162 static void		rt2661_stop(void *);
163 static int		rt2661_load_microcode(struct rt2661_softc *);
164 #ifdef notyet
165 static void		rt2661_rx_tune(struct rt2661_softc *);
166 static void		rt2661_radar_start(struct rt2661_softc *);
167 static int		rt2661_radar_stop(struct rt2661_softc *);
168 #endif
169 static int		rt2661_prepare_beacon(struct rt2661_softc *,
170 			    struct ieee80211vap *);
171 static void		rt2661_enable_tsf_sync(struct rt2661_softc *);
172 static void		rt2661_enable_tsf(struct rt2661_softc *);
173 static int		rt2661_get_rssi(struct rt2661_softc *, uint8_t);
174 
175 static const struct {
176 	uint32_t	reg;
177 	uint32_t	val;
178 } rt2661_def_mac[] = {
179 	RT2661_DEF_MAC
180 };
181 
182 static const struct {
183 	uint8_t	reg;
184 	uint8_t	val;
185 } rt2661_def_bbp[] = {
186 	RT2661_DEF_BBP
187 };
188 
189 static const struct rfprog {
190 	uint8_t		chan;
191 	uint32_t	r1, r2, r3, r4;
192 }  rt2661_rf5225_1[] = {
193 	RT2661_RF5225_1
194 }, rt2661_rf5225_2[] = {
195 	RT2661_RF5225_2
196 };
197 
198 static const uint8_t rt2661_chan_2ghz[] =
199 	{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
200 static const uint8_t rt2661_chan_5ghz[] =
201 	{ 36, 40, 44, 48, 52, 56, 60, 64,
202 	  100, 104, 108, 112, 116, 120, 124, 128, 132, 136, 140,
203 	  149, 153, 157, 161, 165 };
204 
205 int
206 rt2661_attach(device_t dev, int id)
207 {
208 	struct rt2661_softc *sc = device_get_softc(dev);
209 	struct ieee80211com *ic = &sc->sc_ic;
210 	uint32_t val;
211 	int error, ac, ntries;
212 
213 	sc->sc_id = id;
214 	sc->sc_dev = dev;
215 
216 	mtx_init(&sc->sc_mtx, device_get_nameunit(dev), MTX_NETWORK_LOCK,
217 	    MTX_DEF | MTX_RECURSE);
218 
219 	callout_init_mtx(&sc->watchdog_ch, &sc->sc_mtx, 0);
220 	mbufq_init(&sc->sc_snd, ifqmaxlen);
221 
222 	/* wait for NIC to initialize */
223 	for (ntries = 0; ntries < 1000; ntries++) {
224 		if ((val = RAL_READ(sc, RT2661_MAC_CSR0)) != 0)
225 			break;
226 		DELAY(1000);
227 	}
228 	if (ntries == 1000) {
229 		device_printf(sc->sc_dev,
230 		    "timeout waiting for NIC to initialize\n");
231 		error = EIO;
232 		goto fail1;
233 	}
234 
235 	/* retrieve RF rev. no and various other things from EEPROM */
236 	rt2661_read_eeprom(sc, ic->ic_macaddr);
237 
238 	device_printf(dev, "MAC/BBP RT%X, RF %s\n", val,
239 	    rt2661_get_rf(sc->rf_rev));
240 
241 	/*
242 	 * Allocate Tx and Rx rings.
243 	 */
244 	for (ac = 0; ac < 4; ac++) {
245 		error = rt2661_alloc_tx_ring(sc, &sc->txq[ac],
246 		    RT2661_TX_RING_COUNT);
247 		if (error != 0) {
248 			device_printf(sc->sc_dev,
249 			    "could not allocate Tx ring %d\n", ac);
250 			goto fail2;
251 		}
252 	}
253 
254 	error = rt2661_alloc_tx_ring(sc, &sc->mgtq, RT2661_MGT_RING_COUNT);
255 	if (error != 0) {
256 		device_printf(sc->sc_dev, "could not allocate Mgt ring\n");
257 		goto fail2;
258 	}
259 
260 	error = rt2661_alloc_rx_ring(sc, &sc->rxq, RT2661_RX_RING_COUNT);
261 	if (error != 0) {
262 		device_printf(sc->sc_dev, "could not allocate Rx ring\n");
263 		goto fail3;
264 	}
265 
266 	ic->ic_softc = sc;
267 	ic->ic_name = device_get_nameunit(dev);
268 	ic->ic_opmode = IEEE80211_M_STA;
269 	ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
270 
271 	/* set device capabilities */
272 	ic->ic_caps =
273 		  IEEE80211_C_STA		/* station mode */
274 		| IEEE80211_C_IBSS		/* ibss, nee adhoc, mode */
275 		| IEEE80211_C_HOSTAP		/* hostap mode */
276 		| IEEE80211_C_MONITOR		/* monitor mode */
277 		| IEEE80211_C_AHDEMO		/* adhoc demo mode */
278 		| IEEE80211_C_WDS		/* 4-address traffic works */
279 		| IEEE80211_C_MBSS		/* mesh point link mode */
280 		| IEEE80211_C_SHPREAMBLE	/* short preamble supported */
281 		| IEEE80211_C_SHSLOT		/* short slot time supported */
282 		| IEEE80211_C_WPA		/* capable of WPA1+WPA2 */
283 		| IEEE80211_C_BGSCAN		/* capable of bg scanning */
284 #ifdef notyet
285 		| IEEE80211_C_TXFRAG		/* handle tx frags */
286 		| IEEE80211_C_WME		/* 802.11e */
287 #endif
288 		;
289 
290 	rt2661_getradiocaps(ic, IEEE80211_CHAN_MAX, &ic->ic_nchans,
291 	    ic->ic_channels);
292 
293 	ieee80211_ifattach(ic);
294 #if 0
295 	ic->ic_wme.wme_update = rt2661_wme_update;
296 #endif
297 	ic->ic_scan_start = rt2661_scan_start;
298 	ic->ic_scan_end = rt2661_scan_end;
299 	ic->ic_getradiocaps = rt2661_getradiocaps;
300 	ic->ic_set_channel = rt2661_set_channel;
301 	ic->ic_updateslot = rt2661_update_slot;
302 	ic->ic_update_promisc = rt2661_update_promisc;
303 	ic->ic_raw_xmit = rt2661_raw_xmit;
304 	ic->ic_transmit = rt2661_transmit;
305 	ic->ic_parent = rt2661_parent;
306 	ic->ic_vap_create = rt2661_vap_create;
307 	ic->ic_vap_delete = rt2661_vap_delete;
308 
309 	ieee80211_radiotap_attach(ic,
310 	    &sc->sc_txtap.wt_ihdr, sizeof(sc->sc_txtap),
311 		RT2661_TX_RADIOTAP_PRESENT,
312 	    &sc->sc_rxtap.wr_ihdr, sizeof(sc->sc_rxtap),
313 		RT2661_RX_RADIOTAP_PRESENT);
314 
315 #ifdef RAL_DEBUG
316 	SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
317 	    SYSCTL_CHILDREN(device_get_sysctl_tree(dev)), OID_AUTO,
318 	    "debug", CTLFLAG_RW, &sc->sc_debug, 0, "debug msgs");
319 #endif
320 	if (bootverbose)
321 		ieee80211_announce(ic);
322 
323 	return 0;
324 
325 fail3:	rt2661_free_tx_ring(sc, &sc->mgtq);
326 fail2:	while (--ac >= 0)
327 		rt2661_free_tx_ring(sc, &sc->txq[ac]);
328 fail1:	mtx_destroy(&sc->sc_mtx);
329 	return error;
330 }
331 
332 int
333 rt2661_detach(void *xsc)
334 {
335 	struct rt2661_softc *sc = xsc;
336 	struct ieee80211com *ic = &sc->sc_ic;
337 
338 	RAL_LOCK(sc);
339 	rt2661_stop_locked(sc);
340 	RAL_UNLOCK(sc);
341 
342 	ieee80211_ifdetach(ic);
343 	mbufq_drain(&sc->sc_snd);
344 
345 	rt2661_free_tx_ring(sc, &sc->txq[0]);
346 	rt2661_free_tx_ring(sc, &sc->txq[1]);
347 	rt2661_free_tx_ring(sc, &sc->txq[2]);
348 	rt2661_free_tx_ring(sc, &sc->txq[3]);
349 	rt2661_free_tx_ring(sc, &sc->mgtq);
350 	rt2661_free_rx_ring(sc, &sc->rxq);
351 
352 	mtx_destroy(&sc->sc_mtx);
353 
354 	return 0;
355 }
356 
357 static struct ieee80211vap *
358 rt2661_vap_create(struct ieee80211com *ic, const char name[IFNAMSIZ], int unit,
359     enum ieee80211_opmode opmode, int flags,
360     const uint8_t bssid[IEEE80211_ADDR_LEN],
361     const uint8_t mac[IEEE80211_ADDR_LEN])
362 {
363 	struct rt2661_softc *sc = ic->ic_softc;
364 	struct rt2661_vap *rvp;
365 	struct ieee80211vap *vap;
366 
367 	switch (opmode) {
368 	case IEEE80211_M_STA:
369 	case IEEE80211_M_IBSS:
370 	case IEEE80211_M_AHDEMO:
371 	case IEEE80211_M_MONITOR:
372 	case IEEE80211_M_HOSTAP:
373 	case IEEE80211_M_MBSS:
374 		/* XXXRP: TBD */
375 		if (!TAILQ_EMPTY(&ic->ic_vaps)) {
376 			device_printf(sc->sc_dev, "only 1 vap supported\n");
377 			return NULL;
378 		}
379 		if (opmode == IEEE80211_M_STA)
380 			flags |= IEEE80211_CLONE_NOBEACONS;
381 		break;
382 	case IEEE80211_M_WDS:
383 		if (TAILQ_EMPTY(&ic->ic_vaps) ||
384 		    ic->ic_opmode != IEEE80211_M_HOSTAP) {
385 			device_printf(sc->sc_dev,
386 			    "wds only supported in ap mode\n");
387 			return NULL;
388 		}
389 		/*
390 		 * Silently remove any request for a unique
391 		 * bssid; WDS vap's always share the local
392 		 * mac address.
393 		 */
394 		flags &= ~IEEE80211_CLONE_BSSID;
395 		break;
396 	default:
397 		device_printf(sc->sc_dev, "unknown opmode %d\n", opmode);
398 		return NULL;
399 	}
400 	rvp = malloc(sizeof(struct rt2661_vap), M_80211_VAP, M_WAITOK | M_ZERO);
401 	vap = &rvp->ral_vap;
402 	ieee80211_vap_setup(ic, vap, name, unit, opmode, flags, bssid);
403 
404 	/* override state transition machine */
405 	rvp->ral_newstate = vap->iv_newstate;
406 	vap->iv_newstate = rt2661_newstate;
407 #if 0
408 	vap->iv_update_beacon = rt2661_beacon_update;
409 #endif
410 
411 	ieee80211_ratectl_init(vap);
412 	/* complete setup */
413 	ieee80211_vap_attach(vap, ieee80211_media_change,
414 	    ieee80211_media_status, mac);
415 	if (TAILQ_FIRST(&ic->ic_vaps) == vap)
416 		ic->ic_opmode = opmode;
417 	return vap;
418 }
419 
420 static void
421 rt2661_vap_delete(struct ieee80211vap *vap)
422 {
423 	struct rt2661_vap *rvp = RT2661_VAP(vap);
424 
425 	ieee80211_ratectl_deinit(vap);
426 	ieee80211_vap_detach(vap);
427 	free(rvp, M_80211_VAP);
428 }
429 
430 void
431 rt2661_shutdown(void *xsc)
432 {
433 	struct rt2661_softc *sc = xsc;
434 
435 	rt2661_stop(sc);
436 }
437 
438 void
439 rt2661_suspend(void *xsc)
440 {
441 	struct rt2661_softc *sc = xsc;
442 
443 	rt2661_stop(sc);
444 }
445 
446 void
447 rt2661_resume(void *xsc)
448 {
449 	struct rt2661_softc *sc = xsc;
450 
451 	if (sc->sc_ic.ic_nrunning > 0)
452 		rt2661_init(sc);
453 }
454 
455 static void
456 rt2661_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
457 {
458 	if (error != 0)
459 		return;
460 
461 	KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
462 
463 	*(bus_addr_t *)arg = segs[0].ds_addr;
464 }
465 
466 static int
467 rt2661_alloc_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring,
468     int count)
469 {
470 	int i, error;
471 
472 	ring->count = count;
473 	ring->queued = 0;
474 	ring->cur = ring->next = ring->stat = 0;
475 
476 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 4, 0,
477 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
478 	    count * RT2661_TX_DESC_SIZE, 1, count * RT2661_TX_DESC_SIZE,
479 	    0, NULL, NULL, &ring->desc_dmat);
480 	if (error != 0) {
481 		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
482 		goto fail;
483 	}
484 
485 	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
486 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
487 	if (error != 0) {
488 		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
489 		goto fail;
490 	}
491 
492 	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
493 	    count * RT2661_TX_DESC_SIZE, rt2661_dma_map_addr, &ring->physaddr,
494 	    0);
495 	if (error != 0) {
496 		device_printf(sc->sc_dev, "could not load desc DMA map\n");
497 		goto fail;
498 	}
499 
500 	ring->data = malloc(count * sizeof (struct rt2661_tx_data), M_DEVBUF,
501 	    M_NOWAIT | M_ZERO);
502 	if (ring->data == NULL) {
503 		device_printf(sc->sc_dev, "could not allocate soft data\n");
504 		error = ENOMEM;
505 		goto fail;
506 	}
507 
508 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
509 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
510 	    RT2661_MAX_SCATTER, MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
511 	if (error != 0) {
512 		device_printf(sc->sc_dev, "could not create data DMA tag\n");
513 		goto fail;
514 	}
515 
516 	for (i = 0; i < count; i++) {
517 		error = bus_dmamap_create(ring->data_dmat, 0,
518 		    &ring->data[i].map);
519 		if (error != 0) {
520 			device_printf(sc->sc_dev, "could not create DMA map\n");
521 			goto fail;
522 		}
523 	}
524 
525 	return 0;
526 
527 fail:	rt2661_free_tx_ring(sc, ring);
528 	return error;
529 }
530 
531 static void
532 rt2661_reset_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring)
533 {
534 	struct rt2661_tx_desc *desc;
535 	struct rt2661_tx_data *data;
536 	int i;
537 
538 	for (i = 0; i < ring->count; i++) {
539 		desc = &ring->desc[i];
540 		data = &ring->data[i];
541 
542 		if (data->m != NULL) {
543 			bus_dmamap_sync(ring->data_dmat, data->map,
544 			    BUS_DMASYNC_POSTWRITE);
545 			bus_dmamap_unload(ring->data_dmat, data->map);
546 			m_freem(data->m);
547 			data->m = NULL;
548 		}
549 
550 		if (data->ni != NULL) {
551 			ieee80211_free_node(data->ni);
552 			data->ni = NULL;
553 		}
554 
555 		desc->flags = 0;
556 	}
557 
558 	bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
559 
560 	ring->queued = 0;
561 	ring->cur = ring->next = ring->stat = 0;
562 }
563 
564 static void
565 rt2661_free_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring)
566 {
567 	struct rt2661_tx_data *data;
568 	int i;
569 
570 	if (ring->desc != NULL) {
571 		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
572 		    BUS_DMASYNC_POSTWRITE);
573 		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
574 		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
575 	}
576 
577 	if (ring->desc_dmat != NULL)
578 		bus_dma_tag_destroy(ring->desc_dmat);
579 
580 	if (ring->data != NULL) {
581 		for (i = 0; i < ring->count; i++) {
582 			data = &ring->data[i];
583 
584 			if (data->m != NULL) {
585 				bus_dmamap_sync(ring->data_dmat, data->map,
586 				    BUS_DMASYNC_POSTWRITE);
587 				bus_dmamap_unload(ring->data_dmat, data->map);
588 				m_freem(data->m);
589 			}
590 
591 			if (data->ni != NULL)
592 				ieee80211_free_node(data->ni);
593 
594 			if (data->map != NULL)
595 				bus_dmamap_destroy(ring->data_dmat, data->map);
596 		}
597 
598 		free(ring->data, M_DEVBUF);
599 	}
600 
601 	if (ring->data_dmat != NULL)
602 		bus_dma_tag_destroy(ring->data_dmat);
603 }
604 
605 static int
606 rt2661_alloc_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring,
607     int count)
608 {
609 	struct rt2661_rx_desc *desc;
610 	struct rt2661_rx_data *data;
611 	bus_addr_t physaddr;
612 	int i, error;
613 
614 	ring->count = count;
615 	ring->cur = ring->next = 0;
616 
617 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 4, 0,
618 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL,
619 	    count * RT2661_RX_DESC_SIZE, 1, count * RT2661_RX_DESC_SIZE,
620 	    0, NULL, NULL, &ring->desc_dmat);
621 	if (error != 0) {
622 		device_printf(sc->sc_dev, "could not create desc DMA tag\n");
623 		goto fail;
624 	}
625 
626 	error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
627 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO, &ring->desc_map);
628 	if (error != 0) {
629 		device_printf(sc->sc_dev, "could not allocate DMA memory\n");
630 		goto fail;
631 	}
632 
633 	error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
634 	    count * RT2661_RX_DESC_SIZE, rt2661_dma_map_addr, &ring->physaddr,
635 	    0);
636 	if (error != 0) {
637 		device_printf(sc->sc_dev, "could not load desc DMA map\n");
638 		goto fail;
639 	}
640 
641 	ring->data = malloc(count * sizeof (struct rt2661_rx_data), M_DEVBUF,
642 	    M_NOWAIT | M_ZERO);
643 	if (ring->data == NULL) {
644 		device_printf(sc->sc_dev, "could not allocate soft data\n");
645 		error = ENOMEM;
646 		goto fail;
647 	}
648 
649 	/*
650 	 * Pre-allocate Rx buffers and populate Rx ring.
651 	 */
652 	error = bus_dma_tag_create(bus_get_dma_tag(sc->sc_dev), 1, 0,
653 	    BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES,
654 	    1, MCLBYTES, 0, NULL, NULL, &ring->data_dmat);
655 	if (error != 0) {
656 		device_printf(sc->sc_dev, "could not create data DMA tag\n");
657 		goto fail;
658 	}
659 
660 	for (i = 0; i < count; i++) {
661 		desc = &sc->rxq.desc[i];
662 		data = &sc->rxq.data[i];
663 
664 		error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
665 		if (error != 0) {
666 			device_printf(sc->sc_dev, "could not create DMA map\n");
667 			goto fail;
668 		}
669 
670 		data->m = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
671 		if (data->m == NULL) {
672 			device_printf(sc->sc_dev,
673 			    "could not allocate rx mbuf\n");
674 			error = ENOMEM;
675 			goto fail;
676 		}
677 
678 		error = bus_dmamap_load(ring->data_dmat, data->map,
679 		    mtod(data->m, void *), MCLBYTES, rt2661_dma_map_addr,
680 		    &physaddr, 0);
681 		if (error != 0) {
682 			device_printf(sc->sc_dev,
683 			    "could not load rx buf DMA map");
684 			goto fail;
685 		}
686 
687 		desc->flags = htole32(RT2661_RX_BUSY);
688 		desc->physaddr = htole32(physaddr);
689 	}
690 
691 	bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
692 
693 	return 0;
694 
695 fail:	rt2661_free_rx_ring(sc, ring);
696 	return error;
697 }
698 
699 static void
700 rt2661_reset_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring)
701 {
702 	int i;
703 
704 	for (i = 0; i < ring->count; i++)
705 		ring->desc[i].flags = htole32(RT2661_RX_BUSY);
706 
707 	bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
708 
709 	ring->cur = ring->next = 0;
710 }
711 
712 static void
713 rt2661_free_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring)
714 {
715 	struct rt2661_rx_data *data;
716 	int i;
717 
718 	if (ring->desc != NULL) {
719 		bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
720 		    BUS_DMASYNC_POSTWRITE);
721 		bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
722 		bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
723 	}
724 
725 	if (ring->desc_dmat != NULL)
726 		bus_dma_tag_destroy(ring->desc_dmat);
727 
728 	if (ring->data != NULL) {
729 		for (i = 0; i < ring->count; i++) {
730 			data = &ring->data[i];
731 
732 			if (data->m != NULL) {
733 				bus_dmamap_sync(ring->data_dmat, data->map,
734 				    BUS_DMASYNC_POSTREAD);
735 				bus_dmamap_unload(ring->data_dmat, data->map);
736 				m_freem(data->m);
737 			}
738 
739 			if (data->map != NULL)
740 				bus_dmamap_destroy(ring->data_dmat, data->map);
741 		}
742 
743 		free(ring->data, M_DEVBUF);
744 	}
745 
746 	if (ring->data_dmat != NULL)
747 		bus_dma_tag_destroy(ring->data_dmat);
748 }
749 
750 static int
751 rt2661_newstate(struct ieee80211vap *vap, enum ieee80211_state nstate, int arg)
752 {
753 	struct rt2661_vap *rvp = RT2661_VAP(vap);
754 	struct ieee80211com *ic = vap->iv_ic;
755 	struct rt2661_softc *sc = ic->ic_softc;
756 	int error;
757 
758 	if (nstate == IEEE80211_S_INIT && vap->iv_state == IEEE80211_S_RUN) {
759 		uint32_t tmp;
760 
761 		/* abort TSF synchronization */
762 		tmp = RAL_READ(sc, RT2661_TXRX_CSR9);
763 		RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp & ~0x00ffffff);
764 	}
765 
766 	error = rvp->ral_newstate(vap, nstate, arg);
767 
768 	if (error == 0 && nstate == IEEE80211_S_RUN) {
769 		struct ieee80211_node *ni = vap->iv_bss;
770 
771 		if (vap->iv_opmode != IEEE80211_M_MONITOR) {
772 			rt2661_enable_mrr(sc);
773 			rt2661_set_txpreamble(sc);
774 			rt2661_set_basicrates(sc, &ni->ni_rates);
775 			rt2661_set_bssid(sc, ni->ni_bssid);
776 		}
777 
778 		if (vap->iv_opmode == IEEE80211_M_HOSTAP ||
779 		    vap->iv_opmode == IEEE80211_M_IBSS ||
780 		    vap->iv_opmode == IEEE80211_M_MBSS) {
781 			error = rt2661_prepare_beacon(sc, vap);
782 			if (error != 0)
783 				return error;
784 		}
785 		if (vap->iv_opmode != IEEE80211_M_MONITOR)
786 			rt2661_enable_tsf_sync(sc);
787 		else
788 			rt2661_enable_tsf(sc);
789 	}
790 	return error;
791 }
792 
793 /*
794  * Read 16 bits at address 'addr' from the serial EEPROM (either 93C46 or
795  * 93C66).
796  */
797 static uint16_t
798 rt2661_eeprom_read(struct rt2661_softc *sc, uint8_t addr)
799 {
800 	uint32_t tmp;
801 	uint16_t val;
802 	int n;
803 
804 	/* clock C once before the first command */
805 	RT2661_EEPROM_CTL(sc, 0);
806 
807 	RT2661_EEPROM_CTL(sc, RT2661_S);
808 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
809 	RT2661_EEPROM_CTL(sc, RT2661_S);
810 
811 	/* write start bit (1) */
812 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
813 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
814 
815 	/* write READ opcode (10) */
816 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
817 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
818 	RT2661_EEPROM_CTL(sc, RT2661_S);
819 	RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
820 
821 	/* write address (A5-A0 or A7-A0) */
822 	n = (RAL_READ(sc, RT2661_E2PROM_CSR) & RT2661_93C46) ? 5 : 7;
823 	for (; n >= 0; n--) {
824 		RT2661_EEPROM_CTL(sc, RT2661_S |
825 		    (((addr >> n) & 1) << RT2661_SHIFT_D));
826 		RT2661_EEPROM_CTL(sc, RT2661_S |
827 		    (((addr >> n) & 1) << RT2661_SHIFT_D) | RT2661_C);
828 	}
829 
830 	RT2661_EEPROM_CTL(sc, RT2661_S);
831 
832 	/* read data Q15-Q0 */
833 	val = 0;
834 	for (n = 15; n >= 0; n--) {
835 		RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
836 		tmp = RAL_READ(sc, RT2661_E2PROM_CSR);
837 		val |= ((tmp & RT2661_Q) >> RT2661_SHIFT_Q) << n;
838 		RT2661_EEPROM_CTL(sc, RT2661_S);
839 	}
840 
841 	RT2661_EEPROM_CTL(sc, 0);
842 
843 	/* clear Chip Select and clock C */
844 	RT2661_EEPROM_CTL(sc, RT2661_S);
845 	RT2661_EEPROM_CTL(sc, 0);
846 	RT2661_EEPROM_CTL(sc, RT2661_C);
847 
848 	return val;
849 }
850 
851 static void
852 rt2661_tx_intr(struct rt2661_softc *sc)
853 {
854 	struct ieee80211_ratectl_tx_status *txs = &sc->sc_txs;
855 	struct rt2661_tx_ring *txq;
856 	struct rt2661_tx_data *data;
857 	uint32_t val;
858 	int error, qid;
859 
860 	txs->flags = IEEE80211_RATECTL_TX_FAIL_LONG;
861 	for (;;) {
862 		struct ieee80211_node *ni;
863 		struct mbuf *m;
864 
865 		val = RAL_READ(sc, RT2661_STA_CSR4);
866 		if (!(val & RT2661_TX_STAT_VALID))
867 			break;
868 
869 		/* retrieve the queue in which this frame was sent */
870 		qid = RT2661_TX_QID(val);
871 		txq = (qid <= 3) ? &sc->txq[qid] : &sc->mgtq;
872 
873 		/* retrieve rate control algorithm context */
874 		data = &txq->data[txq->stat];
875 		m = data->m;
876 		data->m = NULL;
877 		ni = data->ni;
878 		data->ni = NULL;
879 
880 		/* if no frame has been sent, ignore */
881 		if (ni == NULL)
882 			continue;
883 
884 		switch (RT2661_TX_RESULT(val)) {
885 		case RT2661_TX_SUCCESS:
886 			txs->status = IEEE80211_RATECTL_TX_SUCCESS;
887 			txs->long_retries = RT2661_TX_RETRYCNT(val);
888 
889 			DPRINTFN(sc, 10, "data frame sent successfully after "
890 			    "%d retries\n", txs->long_retries);
891 			if (data->rix != IEEE80211_FIXED_RATE_NONE)
892 				ieee80211_ratectl_tx_complete(ni, txs);
893 			error = 0;
894 			break;
895 
896 		case RT2661_TX_RETRY_FAIL:
897 			txs->status = IEEE80211_RATECTL_TX_FAIL_LONG;
898 			txs->long_retries = RT2661_TX_RETRYCNT(val);
899 
900 			DPRINTFN(sc, 9, "%s\n",
901 			    "sending data frame failed (too much retries)");
902 			if (data->rix != IEEE80211_FIXED_RATE_NONE)
903 				ieee80211_ratectl_tx_complete(ni, txs);
904 			error = 1;
905 			break;
906 
907 		default:
908 			/* other failure */
909 			device_printf(sc->sc_dev,
910 			    "sending data frame failed 0x%08x\n", val);
911 			error = 1;
912 		}
913 
914 		DPRINTFN(sc, 15, "tx done q=%d idx=%u\n", qid, txq->stat);
915 
916 		txq->queued--;
917 		if (++txq->stat >= txq->count)	/* faster than % count */
918 			txq->stat = 0;
919 
920 		ieee80211_tx_complete(ni, m, error);
921 	}
922 
923 	sc->sc_tx_timer = 0;
924 
925 	rt2661_start(sc);
926 }
927 
928 static void
929 rt2661_tx_dma_intr(struct rt2661_softc *sc, struct rt2661_tx_ring *txq)
930 {
931 	struct rt2661_tx_desc *desc;
932 	struct rt2661_tx_data *data;
933 
934 	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_POSTREAD);
935 
936 	for (;;) {
937 		desc = &txq->desc[txq->next];
938 		data = &txq->data[txq->next];
939 
940 		if ((le32toh(desc->flags) & RT2661_TX_BUSY) ||
941 		    !(le32toh(desc->flags) & RT2661_TX_VALID))
942 			break;
943 
944 		bus_dmamap_sync(txq->data_dmat, data->map,
945 		    BUS_DMASYNC_POSTWRITE);
946 		bus_dmamap_unload(txq->data_dmat, data->map);
947 
948 		/* descriptor is no longer valid */
949 		desc->flags &= ~htole32(RT2661_TX_VALID);
950 
951 		DPRINTFN(sc, 15, "tx dma done q=%p idx=%u\n", txq, txq->next);
952 
953 		if (++txq->next >= txq->count)	/* faster than % count */
954 			txq->next = 0;
955 	}
956 
957 	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
958 }
959 
960 static void
961 rt2661_rx_intr(struct rt2661_softc *sc)
962 {
963 	struct ieee80211com *ic = &sc->sc_ic;
964 	struct rt2661_rx_desc *desc;
965 	struct rt2661_rx_data *data;
966 	bus_addr_t physaddr;
967 	struct ieee80211_frame *wh;
968 	struct ieee80211_node *ni;
969 	struct mbuf *mnew, *m;
970 	int error;
971 
972 	bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
973 	    BUS_DMASYNC_POSTREAD);
974 
975 	for (;;) {
976 		int8_t rssi, nf;
977 
978 		desc = &sc->rxq.desc[sc->rxq.cur];
979 		data = &sc->rxq.data[sc->rxq.cur];
980 
981 		if (le32toh(desc->flags) & RT2661_RX_BUSY)
982 			break;
983 
984 		if ((le32toh(desc->flags) & RT2661_RX_PHY_ERROR) ||
985 		    (le32toh(desc->flags) & RT2661_RX_CRC_ERROR)) {
986 			/*
987 			 * This should not happen since we did not request
988 			 * to receive those frames when we filled TXRX_CSR0.
989 			 */
990 			DPRINTFN(sc, 5, "PHY or CRC error flags 0x%08x\n",
991 			    le32toh(desc->flags));
992 			counter_u64_add(ic->ic_ierrors, 1);
993 			goto skip;
994 		}
995 
996 		if ((le32toh(desc->flags) & RT2661_RX_CIPHER_MASK) != 0) {
997 			counter_u64_add(ic->ic_ierrors, 1);
998 			goto skip;
999 		}
1000 
1001 		/*
1002 		 * Try to allocate a new mbuf for this ring element and load it
1003 		 * before processing the current mbuf. If the ring element
1004 		 * cannot be loaded, drop the received packet and reuse the old
1005 		 * mbuf. In the unlikely case that the old mbuf can't be
1006 		 * reloaded either, explicitly panic.
1007 		 */
1008 		mnew = m_getcl(M_NOWAIT, MT_DATA, M_PKTHDR);
1009 		if (mnew == NULL) {
1010 			counter_u64_add(ic->ic_ierrors, 1);
1011 			goto skip;
1012 		}
1013 
1014 		bus_dmamap_sync(sc->rxq.data_dmat, data->map,
1015 		    BUS_DMASYNC_POSTREAD);
1016 		bus_dmamap_unload(sc->rxq.data_dmat, data->map);
1017 
1018 		error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1019 		    mtod(mnew, void *), MCLBYTES, rt2661_dma_map_addr,
1020 		    &physaddr, 0);
1021 		if (error != 0) {
1022 			m_freem(mnew);
1023 
1024 			/* try to reload the old mbuf */
1025 			error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1026 			    mtod(data->m, void *), MCLBYTES,
1027 			    rt2661_dma_map_addr, &physaddr, 0);
1028 			if (error != 0) {
1029 				/* very unlikely that it will fail... */
1030 				panic("%s: could not load old rx mbuf",
1031 				    device_get_name(sc->sc_dev));
1032 			}
1033 			counter_u64_add(ic->ic_ierrors, 1);
1034 			goto skip;
1035 		}
1036 
1037 		/*
1038 	 	 * New mbuf successfully loaded, update Rx ring and continue
1039 		 * processing.
1040 		 */
1041 		m = data->m;
1042 		data->m = mnew;
1043 		desc->physaddr = htole32(physaddr);
1044 
1045 		/* finalize mbuf */
1046 		m->m_pkthdr.len = m->m_len =
1047 		    (le32toh(desc->flags) >> 16) & 0xfff;
1048 
1049 		rssi = rt2661_get_rssi(sc, desc->rssi);
1050 		/* Error happened during RSSI conversion. */
1051 		if (rssi < 0)
1052 			rssi = -30;	/* XXX ignored by net80211 */
1053 		nf = RT2661_NOISE_FLOOR;
1054 
1055 		if (ieee80211_radiotap_active(ic)) {
1056 			struct rt2661_rx_radiotap_header *tap = &sc->sc_rxtap;
1057 			uint32_t tsf_lo, tsf_hi;
1058 
1059 			/* get timestamp (low and high 32 bits) */
1060 			tsf_hi = RAL_READ(sc, RT2661_TXRX_CSR13);
1061 			tsf_lo = RAL_READ(sc, RT2661_TXRX_CSR12);
1062 
1063 			tap->wr_tsf =
1064 			    htole64(((uint64_t)tsf_hi << 32) | tsf_lo);
1065 			tap->wr_flags = 0;
1066 			tap->wr_rate = ieee80211_plcp2rate(desc->rate,
1067 			    (desc->flags & htole32(RT2661_RX_OFDM)) ?
1068 				IEEE80211_T_OFDM : IEEE80211_T_CCK);
1069 			tap->wr_antsignal = nf + rssi;
1070 			tap->wr_antnoise = nf;
1071 		}
1072 		sc->sc_flags |= RAL_INPUT_RUNNING;
1073 		RAL_UNLOCK(sc);
1074 		wh = mtod(m, struct ieee80211_frame *);
1075 
1076 		/* send the frame to the 802.11 layer */
1077 		ni = ieee80211_find_rxnode(ic,
1078 		    (struct ieee80211_frame_min *)wh);
1079 		if (ni != NULL) {
1080 			(void) ieee80211_input(ni, m, rssi, nf);
1081 			ieee80211_free_node(ni);
1082 		} else
1083 			(void) ieee80211_input_all(ic, m, rssi, nf);
1084 
1085 		RAL_LOCK(sc);
1086 		sc->sc_flags &= ~RAL_INPUT_RUNNING;
1087 
1088 skip:		desc->flags |= htole32(RT2661_RX_BUSY);
1089 
1090 		DPRINTFN(sc, 15, "rx intr idx=%u\n", sc->rxq.cur);
1091 
1092 		sc->rxq.cur = (sc->rxq.cur + 1) % RT2661_RX_RING_COUNT;
1093 	}
1094 
1095 	bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1096 	    BUS_DMASYNC_PREWRITE);
1097 }
1098 
1099 /* ARGSUSED */
1100 static void
1101 rt2661_mcu_beacon_expire(struct rt2661_softc *sc)
1102 {
1103 	/* do nothing */
1104 }
1105 
1106 static void
1107 rt2661_mcu_wakeup(struct rt2661_softc *sc)
1108 {
1109 	RAL_WRITE(sc, RT2661_MAC_CSR11, 5 << 16);
1110 
1111 	RAL_WRITE(sc, RT2661_SOFT_RESET_CSR, 0x7);
1112 	RAL_WRITE(sc, RT2661_IO_CNTL_CSR, 0x18);
1113 	RAL_WRITE(sc, RT2661_PCI_USEC_CSR, 0x20);
1114 
1115 	/* send wakeup command to MCU */
1116 	rt2661_tx_cmd(sc, RT2661_MCU_CMD_WAKEUP, 0);
1117 }
1118 
1119 static void
1120 rt2661_mcu_cmd_intr(struct rt2661_softc *sc)
1121 {
1122 	RAL_READ(sc, RT2661_M2H_CMD_DONE_CSR);
1123 	RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
1124 }
1125 
1126 void
1127 rt2661_intr(void *arg)
1128 {
1129 	struct rt2661_softc *sc = arg;
1130 	uint32_t r1, r2;
1131 
1132 	RAL_LOCK(sc);
1133 
1134 	/* disable MAC and MCU interrupts */
1135 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffff7f);
1136 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
1137 
1138 	/* don't re-enable interrupts if we're shutting down */
1139 	if (!(sc->sc_flags & RAL_RUNNING)) {
1140 		RAL_UNLOCK(sc);
1141 		return;
1142 	}
1143 
1144 	r1 = RAL_READ(sc, RT2661_INT_SOURCE_CSR);
1145 	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, r1);
1146 
1147 	r2 = RAL_READ(sc, RT2661_MCU_INT_SOURCE_CSR);
1148 	RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, r2);
1149 
1150 	if (r1 & RT2661_MGT_DONE)
1151 		rt2661_tx_dma_intr(sc, &sc->mgtq);
1152 
1153 	if (r1 & RT2661_RX_DONE)
1154 		rt2661_rx_intr(sc);
1155 
1156 	if (r1 & RT2661_TX0_DMA_DONE)
1157 		rt2661_tx_dma_intr(sc, &sc->txq[0]);
1158 
1159 	if (r1 & RT2661_TX1_DMA_DONE)
1160 		rt2661_tx_dma_intr(sc, &sc->txq[1]);
1161 
1162 	if (r1 & RT2661_TX2_DMA_DONE)
1163 		rt2661_tx_dma_intr(sc, &sc->txq[2]);
1164 
1165 	if (r1 & RT2661_TX3_DMA_DONE)
1166 		rt2661_tx_dma_intr(sc, &sc->txq[3]);
1167 
1168 	if (r1 & RT2661_TX_DONE)
1169 		rt2661_tx_intr(sc);
1170 
1171 	if (r2 & RT2661_MCU_CMD_DONE)
1172 		rt2661_mcu_cmd_intr(sc);
1173 
1174 	if (r2 & RT2661_MCU_BEACON_EXPIRE)
1175 		rt2661_mcu_beacon_expire(sc);
1176 
1177 	if (r2 & RT2661_MCU_WAKEUP)
1178 		rt2661_mcu_wakeup(sc);
1179 
1180 	/* re-enable MAC and MCU interrupts */
1181 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
1182 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
1183 
1184 	RAL_UNLOCK(sc);
1185 }
1186 
1187 static uint8_t
1188 rt2661_plcp_signal(int rate)
1189 {
1190 	switch (rate) {
1191 	/* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1192 	case 12:	return 0xb;
1193 	case 18:	return 0xf;
1194 	case 24:	return 0xa;
1195 	case 36:	return 0xe;
1196 	case 48:	return 0x9;
1197 	case 72:	return 0xd;
1198 	case 96:	return 0x8;
1199 	case 108:	return 0xc;
1200 
1201 	/* CCK rates (NB: not IEEE std, device-specific) */
1202 	case 2:		return 0x0;
1203 	case 4:		return 0x1;
1204 	case 11:	return 0x2;
1205 	case 22:	return 0x3;
1206 	}
1207 	return 0xff;		/* XXX unsupported/unknown rate */
1208 }
1209 
1210 static void
1211 rt2661_setup_tx_desc(struct rt2661_softc *sc, struct rt2661_tx_desc *desc,
1212     uint32_t flags, uint16_t xflags, int len, int rate,
1213     const bus_dma_segment_t *segs, int nsegs, int ac)
1214 {
1215 	struct ieee80211com *ic = &sc->sc_ic;
1216 	uint16_t plcp_length;
1217 	int i, remainder;
1218 
1219 	desc->flags = htole32(flags);
1220 	desc->flags |= htole32(len << 16);
1221 	desc->flags |= htole32(RT2661_TX_BUSY | RT2661_TX_VALID);
1222 
1223 	desc->xflags = htole16(xflags);
1224 	desc->xflags |= htole16(nsegs << 13);
1225 
1226 	desc->wme = htole16(
1227 	    RT2661_QID(ac) |
1228 	    RT2661_AIFSN(2) |
1229 	    RT2661_LOGCWMIN(4) |
1230 	    RT2661_LOGCWMAX(10));
1231 
1232 	/*
1233 	 * Remember in which queue this frame was sent. This field is driver
1234 	 * private data only. It will be made available by the NIC in STA_CSR4
1235 	 * on Tx interrupts.
1236 	 */
1237 	desc->qid = ac;
1238 
1239 	/* setup PLCP fields */
1240 	desc->plcp_signal  = rt2661_plcp_signal(rate);
1241 	desc->plcp_service = 4;
1242 
1243 	len += IEEE80211_CRC_LEN;
1244 	if (ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM) {
1245 		desc->flags |= htole32(RT2661_TX_OFDM);
1246 
1247 		plcp_length = len & 0xfff;
1248 		desc->plcp_length_hi = plcp_length >> 6;
1249 		desc->plcp_length_lo = plcp_length & 0x3f;
1250 	} else {
1251 		plcp_length = howmany(16 * len, rate);
1252 		if (rate == 22) {
1253 			remainder = (16 * len) % 22;
1254 			if (remainder != 0 && remainder < 7)
1255 				desc->plcp_service |= RT2661_PLCP_LENGEXT;
1256 		}
1257 		desc->plcp_length_hi = plcp_length >> 8;
1258 		desc->plcp_length_lo = plcp_length & 0xff;
1259 
1260 		if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1261 			desc->plcp_signal |= 0x08;
1262 	}
1263 
1264 	/* RT2x61 supports scatter with up to 5 segments */
1265 	for (i = 0; i < nsegs; i++) {
1266 		desc->addr[i] = htole32(segs[i].ds_addr);
1267 		desc->len [i] = htole16(segs[i].ds_len);
1268 	}
1269 }
1270 
1271 static int
1272 rt2661_tx_mgt(struct rt2661_softc *sc, struct mbuf *m0,
1273     struct ieee80211_node *ni)
1274 {
1275 	struct ieee80211vap *vap = ni->ni_vap;
1276 	struct ieee80211com *ic = ni->ni_ic;
1277 	struct rt2661_tx_desc *desc;
1278 	struct rt2661_tx_data *data;
1279 	struct ieee80211_frame *wh;
1280 	struct ieee80211_key *k;
1281 	bus_dma_segment_t segs[RT2661_MAX_SCATTER];
1282 	uint16_t dur;
1283 	uint32_t flags = 0;	/* XXX HWSEQ */
1284 	int nsegs, rate, error;
1285 
1286 	desc = &sc->mgtq.desc[sc->mgtq.cur];
1287 	data = &sc->mgtq.data[sc->mgtq.cur];
1288 
1289 	rate = ni->ni_txparms->mgmtrate;
1290 
1291 	wh = mtod(m0, struct ieee80211_frame *);
1292 
1293 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1294 		k = ieee80211_crypto_encap(ni, m0);
1295 		if (k == NULL) {
1296 			m_freem(m0);
1297 			return ENOBUFS;
1298 		}
1299 	}
1300 
1301 	error = bus_dmamap_load_mbuf_sg(sc->mgtq.data_dmat, data->map, m0,
1302 	    segs, &nsegs, 0);
1303 	if (error != 0) {
1304 		device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1305 		    error);
1306 		m_freem(m0);
1307 		return error;
1308 	}
1309 
1310 	if (ieee80211_radiotap_active_vap(vap)) {
1311 		struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1312 
1313 		tap->wt_flags = 0;
1314 		tap->wt_rate = rate;
1315 
1316 		ieee80211_radiotap_tx(vap, m0);
1317 	}
1318 
1319 	data->m = m0;
1320 	data->ni = ni;
1321 	/* management frames are not taken into account for amrr */
1322 	data->rix = IEEE80211_FIXED_RATE_NONE;
1323 
1324 	wh = mtod(m0, struct ieee80211_frame *);
1325 
1326 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1327 		flags |= RT2661_TX_NEED_ACK;
1328 
1329 		dur = ieee80211_ack_duration(ic->ic_rt,
1330 		    rate, ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1331 		*(uint16_t *)wh->i_dur = htole16(dur);
1332 
1333 		/* tell hardware to add timestamp in probe responses */
1334 		if ((wh->i_fc[0] &
1335 		    (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1336 		    (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1337 			flags |= RT2661_TX_TIMESTAMP;
1338 	}
1339 
1340 	rt2661_setup_tx_desc(sc, desc, flags, 0 /* XXX HWSEQ */,
1341 	    m0->m_pkthdr.len, rate, segs, nsegs, RT2661_QID_MGT);
1342 
1343 	bus_dmamap_sync(sc->mgtq.data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1344 	bus_dmamap_sync(sc->mgtq.desc_dmat, sc->mgtq.desc_map,
1345 	    BUS_DMASYNC_PREWRITE);
1346 
1347 	DPRINTFN(sc, 10, "sending mgt frame len=%u idx=%u rate=%u\n",
1348 	    m0->m_pkthdr.len, sc->mgtq.cur, rate);
1349 
1350 	/* kick mgt */
1351 	sc->mgtq.queued++;
1352 	sc->mgtq.cur = (sc->mgtq.cur + 1) % RT2661_MGT_RING_COUNT;
1353 	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, RT2661_KICK_MGT);
1354 
1355 	return 0;
1356 }
1357 
1358 static int
1359 rt2661_sendprot(struct rt2661_softc *sc, int ac,
1360     const struct mbuf *m, struct ieee80211_node *ni, int prot, int rate)
1361 {
1362 	struct ieee80211com *ic = ni->ni_ic;
1363 	struct rt2661_tx_ring *txq = &sc->txq[ac];
1364 	struct rt2661_tx_desc *desc;
1365 	struct rt2661_tx_data *data;
1366 	struct mbuf *mprot;
1367 	int protrate, flags, error;
1368 	bus_dma_segment_t segs[RT2661_MAX_SCATTER];
1369 	int nsegs;
1370 
1371 	mprot = ieee80211_alloc_prot(ni, m, rate, prot);
1372 	if (mprot == NULL) {
1373 		if_inc_counter(ni->ni_vap->iv_ifp, IFCOUNTER_OERRORS, 1);
1374 		device_printf(sc->sc_dev,
1375 		    "could not allocate mbuf for protection mode %d\n", prot);
1376 		return ENOBUFS;
1377 	}
1378 
1379 	data = &txq->data[txq->cur];
1380 	desc = &txq->desc[txq->cur];
1381 
1382 	error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, mprot, segs,
1383 	    &nsegs, 0);
1384 	if (error != 0) {
1385 		device_printf(sc->sc_dev,
1386 		    "could not map mbuf (error %d)\n", error);
1387 		m_freem(mprot);
1388 		return error;
1389 	}
1390 
1391 	data->m = mprot;
1392 	data->ni = ieee80211_ref_node(ni);
1393 	/* ctl frames are not taken into account for amrr */
1394 	data->rix = IEEE80211_FIXED_RATE_NONE;
1395 
1396 	protrate = ieee80211_ctl_rate(ic->ic_rt, rate);
1397 	flags = RT2661_TX_MORE_FRAG;
1398 	if (prot == IEEE80211_PROT_RTSCTS)
1399 		flags |= RT2661_TX_NEED_ACK;
1400 
1401 	rt2661_setup_tx_desc(sc, desc, flags, 0, mprot->m_pkthdr.len,
1402 	    protrate, segs, 1, ac);
1403 
1404 	bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1405 	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1406 
1407 	txq->queued++;
1408 	txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1409 
1410 	return 0;
1411 }
1412 
1413 static int
1414 rt2661_tx_data(struct rt2661_softc *sc, struct mbuf *m0,
1415     struct ieee80211_node *ni, int ac)
1416 {
1417 	struct ieee80211vap *vap = ni->ni_vap;
1418 	struct ieee80211com *ic = &sc->sc_ic;
1419 	struct rt2661_tx_ring *txq = &sc->txq[ac];
1420 	struct rt2661_tx_desc *desc;
1421 	struct rt2661_tx_data *data;
1422 	struct ieee80211_frame *wh;
1423 	const struct ieee80211_txparam *tp = ni->ni_txparms;
1424 	struct ieee80211_key *k;
1425 	struct mbuf *mnew;
1426 	bus_dma_segment_t segs[RT2661_MAX_SCATTER];
1427 	uint16_t dur;
1428 	uint32_t flags;
1429 	int error, nsegs, rate, noack = 0;
1430 
1431 	wh = mtod(m0, struct ieee80211_frame *);
1432 
1433 	if (m0->m_flags & M_EAPOL) {
1434 		rate = tp->mgmtrate;
1435 	} else if (IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1436 		rate = tp->mcastrate;
1437 	} else if (tp->ucastrate != IEEE80211_FIXED_RATE_NONE) {
1438 		rate = tp->ucastrate;
1439 	} else {
1440 		(void) ieee80211_ratectl_rate(ni, NULL, 0);
1441 		rate = ni->ni_txrate;
1442 	}
1443 	rate &= IEEE80211_RATE_VAL;
1444 
1445 	if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS)
1446 		noack = !! ieee80211_wme_vap_ac_is_noack(vap, ac);
1447 
1448 	if (wh->i_fc[1] & IEEE80211_FC1_PROTECTED) {
1449 		k = ieee80211_crypto_encap(ni, m0);
1450 		if (k == NULL) {
1451 			m_freem(m0);
1452 			return ENOBUFS;
1453 		}
1454 
1455 		/* packet header may have moved, reset our local pointer */
1456 		wh = mtod(m0, struct ieee80211_frame *);
1457 	}
1458 
1459 	flags = 0;
1460 	if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1461 		int prot = IEEE80211_PROT_NONE;
1462 		if (m0->m_pkthdr.len + IEEE80211_CRC_LEN > vap->iv_rtsthreshold)
1463 			prot = IEEE80211_PROT_RTSCTS;
1464 		else if ((ic->ic_flags & IEEE80211_F_USEPROT) &&
1465 		    ieee80211_rate2phytype(ic->ic_rt, rate) == IEEE80211_T_OFDM)
1466 			prot = ic->ic_protmode;
1467 		if (prot != IEEE80211_PROT_NONE) {
1468 			error = rt2661_sendprot(sc, ac, m0, ni, prot, rate);
1469 			if (error) {
1470 				m_freem(m0);
1471 				return error;
1472 			}
1473 			flags |= RT2661_TX_LONG_RETRY | RT2661_TX_IFS;
1474 		}
1475 	}
1476 
1477 	data = &txq->data[txq->cur];
1478 	desc = &txq->desc[txq->cur];
1479 
1480 	error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m0, segs,
1481 	    &nsegs, 0);
1482 	if (error != 0 && error != EFBIG) {
1483 		device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1484 		    error);
1485 		m_freem(m0);
1486 		return error;
1487 	}
1488 	if (error != 0) {
1489 		mnew = m_defrag(m0, M_NOWAIT);
1490 		if (mnew == NULL) {
1491 			device_printf(sc->sc_dev,
1492 			    "could not defragment mbuf\n");
1493 			m_freem(m0);
1494 			return ENOBUFS;
1495 		}
1496 		m0 = mnew;
1497 
1498 		error = bus_dmamap_load_mbuf_sg(txq->data_dmat, data->map, m0,
1499 		    segs, &nsegs, 0);
1500 		if (error != 0) {
1501 			device_printf(sc->sc_dev,
1502 			    "could not map mbuf (error %d)\n", error);
1503 			m_freem(m0);
1504 			return error;
1505 		}
1506 
1507 		/* packet header have moved, reset our local pointer */
1508 		wh = mtod(m0, struct ieee80211_frame *);
1509 	}
1510 
1511 	if (ieee80211_radiotap_active_vap(vap)) {
1512 		struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1513 
1514 		tap->wt_flags = 0;
1515 		tap->wt_rate = rate;
1516 
1517 		ieee80211_radiotap_tx(vap, m0);
1518 	}
1519 
1520 	data->m = m0;
1521 	data->ni = ni;
1522 
1523 	/* remember link conditions for rate adaptation algorithm */
1524 	if (tp->ucastrate == IEEE80211_FIXED_RATE_NONE) {
1525 		data->rix = ni->ni_txrate;
1526 		/* XXX probably need last rssi value and not avg */
1527 		data->rssi = ic->ic_node_getrssi(ni);
1528 	} else
1529 		data->rix = IEEE80211_FIXED_RATE_NONE;
1530 
1531 	if (!noack && !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1532 		flags |= RT2661_TX_NEED_ACK;
1533 
1534 		dur = ieee80211_ack_duration(ic->ic_rt,
1535 		    rate, ic->ic_flags & IEEE80211_F_SHPREAMBLE);
1536 		*(uint16_t *)wh->i_dur = htole16(dur);
1537 	}
1538 
1539 	rt2661_setup_tx_desc(sc, desc, flags, 0, m0->m_pkthdr.len, rate, segs,
1540 	    nsegs, ac);
1541 
1542 	bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1543 	bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1544 
1545 	DPRINTFN(sc, 10, "sending data frame len=%u idx=%u rate=%u\n",
1546 	    m0->m_pkthdr.len, txq->cur, rate);
1547 
1548 	/* kick Tx */
1549 	txq->queued++;
1550 	txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1551 	RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 1 << ac);
1552 
1553 	return 0;
1554 }
1555 
1556 static int
1557 rt2661_transmit(struct ieee80211com *ic, struct mbuf *m)
1558 {
1559 	struct rt2661_softc *sc = ic->ic_softc;
1560 	int error;
1561 
1562 	RAL_LOCK(sc);
1563 	if ((sc->sc_flags & RAL_RUNNING) == 0) {
1564 		RAL_UNLOCK(sc);
1565 		return (ENXIO);
1566 	}
1567 	error = mbufq_enqueue(&sc->sc_snd, m);
1568 	if (error) {
1569 		RAL_UNLOCK(sc);
1570 		return (error);
1571 	}
1572 	rt2661_start(sc);
1573 	RAL_UNLOCK(sc);
1574 
1575 	return (0);
1576 }
1577 
1578 static void
1579 rt2661_start(struct rt2661_softc *sc)
1580 {
1581 	struct mbuf *m;
1582 	struct ieee80211_node *ni;
1583 	int ac;
1584 
1585 	RAL_LOCK_ASSERT(sc);
1586 
1587 	/* prevent management frames from being sent if we're not ready */
1588 	if (!(sc->sc_flags & RAL_RUNNING) || sc->sc_invalid)
1589 		return;
1590 
1591 	while ((m = mbufq_dequeue(&sc->sc_snd)) != NULL) {
1592 		ac = M_WME_GETAC(m);
1593 		if (sc->txq[ac].queued >= RT2661_TX_RING_COUNT - 1) {
1594 			/* there is no place left in this ring */
1595 			mbufq_prepend(&sc->sc_snd, m);
1596 			break;
1597 		}
1598 		ni = (struct ieee80211_node *) m->m_pkthdr.rcvif;
1599 		if (rt2661_tx_data(sc, m, ni, ac) != 0) {
1600 			if_inc_counter(ni->ni_vap->iv_ifp,
1601 			    IFCOUNTER_OERRORS, 1);
1602 			ieee80211_free_node(ni);
1603 			break;
1604 		}
1605 		sc->sc_tx_timer = 5;
1606 	}
1607 }
1608 
1609 static int
1610 rt2661_raw_xmit(struct ieee80211_node *ni, struct mbuf *m,
1611 	const struct ieee80211_bpf_params *params)
1612 {
1613 	struct ieee80211com *ic = ni->ni_ic;
1614 	struct rt2661_softc *sc = ic->ic_softc;
1615 
1616 	RAL_LOCK(sc);
1617 
1618 	/* prevent management frames from being sent if we're not ready */
1619 	if (!(sc->sc_flags & RAL_RUNNING)) {
1620 		RAL_UNLOCK(sc);
1621 		m_freem(m);
1622 		return ENETDOWN;
1623 	}
1624 	if (sc->mgtq.queued >= RT2661_MGT_RING_COUNT) {
1625 		RAL_UNLOCK(sc);
1626 		m_freem(m);
1627 		return ENOBUFS;		/* XXX */
1628 	}
1629 
1630 	/*
1631 	 * Legacy path; interpret frame contents to decide
1632 	 * precisely how to send the frame.
1633 	 * XXX raw path
1634 	 */
1635 	if (rt2661_tx_mgt(sc, m, ni) != 0)
1636 		goto bad;
1637 	sc->sc_tx_timer = 5;
1638 
1639 	RAL_UNLOCK(sc);
1640 
1641 	return 0;
1642 bad:
1643 	RAL_UNLOCK(sc);
1644 	return EIO;		/* XXX */
1645 }
1646 
1647 static void
1648 rt2661_watchdog(void *arg)
1649 {
1650 	struct rt2661_softc *sc = (struct rt2661_softc *)arg;
1651 
1652 	RAL_LOCK_ASSERT(sc);
1653 
1654 	KASSERT(sc->sc_flags & RAL_RUNNING, ("not running"));
1655 
1656 	if (sc->sc_invalid)		/* card ejected */
1657 		return;
1658 
1659 	if (sc->sc_tx_timer > 0 && --sc->sc_tx_timer == 0) {
1660 		device_printf(sc->sc_dev, "device timeout\n");
1661 		rt2661_init_locked(sc);
1662 		counter_u64_add(sc->sc_ic.ic_oerrors, 1);
1663 		/* NB: callout is reset in rt2661_init() */
1664 		return;
1665 	}
1666 	callout_reset(&sc->watchdog_ch, hz, rt2661_watchdog, sc);
1667 }
1668 
1669 static void
1670 rt2661_parent(struct ieee80211com *ic)
1671 {
1672 	struct rt2661_softc *sc = ic->ic_softc;
1673 	int startall = 0;
1674 
1675 	RAL_LOCK(sc);
1676 	if (ic->ic_nrunning > 0) {
1677 		if ((sc->sc_flags & RAL_RUNNING) == 0) {
1678 			rt2661_init_locked(sc);
1679 			startall = 1;
1680 		} else
1681 			rt2661_update_promisc(ic);
1682 	} else if (sc->sc_flags & RAL_RUNNING)
1683 		rt2661_stop_locked(sc);
1684 	RAL_UNLOCK(sc);
1685 	if (startall)
1686 		ieee80211_start_all(ic);
1687 }
1688 
1689 static void
1690 rt2661_bbp_write(struct rt2661_softc *sc, uint8_t reg, uint8_t val)
1691 {
1692 	uint32_t tmp;
1693 	int ntries;
1694 
1695 	for (ntries = 0; ntries < 100; ntries++) {
1696 		if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
1697 			break;
1698 		DELAY(1);
1699 	}
1700 	if (ntries == 100) {
1701 		device_printf(sc->sc_dev, "could not write to BBP\n");
1702 		return;
1703 	}
1704 
1705 	tmp = RT2661_BBP_BUSY | (reg & 0x7f) << 8 | val;
1706 	RAL_WRITE(sc, RT2661_PHY_CSR3, tmp);
1707 
1708 	DPRINTFN(sc, 15, "BBP R%u <- 0x%02x\n", reg, val);
1709 }
1710 
1711 static uint8_t
1712 rt2661_bbp_read(struct rt2661_softc *sc, uint8_t reg)
1713 {
1714 	uint32_t val;
1715 	int ntries;
1716 
1717 	for (ntries = 0; ntries < 100; ntries++) {
1718 		if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
1719 			break;
1720 		DELAY(1);
1721 	}
1722 	if (ntries == 100) {
1723 		device_printf(sc->sc_dev, "could not read from BBP\n");
1724 		return 0;
1725 	}
1726 
1727 	val = RT2661_BBP_BUSY | RT2661_BBP_READ | reg << 8;
1728 	RAL_WRITE(sc, RT2661_PHY_CSR3, val);
1729 
1730 	for (ntries = 0; ntries < 100; ntries++) {
1731 		val = RAL_READ(sc, RT2661_PHY_CSR3);
1732 		if (!(val & RT2661_BBP_BUSY))
1733 			return val & 0xff;
1734 		DELAY(1);
1735 	}
1736 
1737 	device_printf(sc->sc_dev, "could not read from BBP\n");
1738 	return 0;
1739 }
1740 
1741 static void
1742 rt2661_rf_write(struct rt2661_softc *sc, uint8_t reg, uint32_t val)
1743 {
1744 	uint32_t tmp;
1745 	int ntries;
1746 
1747 	for (ntries = 0; ntries < 100; ntries++) {
1748 		if (!(RAL_READ(sc, RT2661_PHY_CSR4) & RT2661_RF_BUSY))
1749 			break;
1750 		DELAY(1);
1751 	}
1752 	if (ntries == 100) {
1753 		device_printf(sc->sc_dev, "could not write to RF\n");
1754 		return;
1755 	}
1756 
1757 	tmp = RT2661_RF_BUSY | RT2661_RF_21BIT | (val & 0x1fffff) << 2 |
1758 	    (reg & 3);
1759 	RAL_WRITE(sc, RT2661_PHY_CSR4, tmp);
1760 
1761 	/* remember last written value in sc */
1762 	sc->rf_regs[reg] = val;
1763 
1764 	DPRINTFN(sc, 15, "RF R[%u] <- 0x%05x\n", reg & 3, val & 0x1fffff);
1765 }
1766 
1767 static int
1768 rt2661_tx_cmd(struct rt2661_softc *sc, uint8_t cmd, uint16_t arg)
1769 {
1770 	if (RAL_READ(sc, RT2661_H2M_MAILBOX_CSR) & RT2661_H2M_BUSY)
1771 		return EIO;	/* there is already a command pending */
1772 
1773 	RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR,
1774 	    RT2661_H2M_BUSY | RT2661_TOKEN_NO_INTR << 16 | arg);
1775 
1776 	RAL_WRITE(sc, RT2661_HOST_CMD_CSR, RT2661_KICK_CMD | cmd);
1777 
1778 	return 0;
1779 }
1780 
1781 static void
1782 rt2661_select_antenna(struct rt2661_softc *sc)
1783 {
1784 	uint8_t bbp4, bbp77;
1785 	uint32_t tmp;
1786 
1787 	bbp4  = rt2661_bbp_read(sc,  4);
1788 	bbp77 = rt2661_bbp_read(sc, 77);
1789 
1790 	/* TBD */
1791 
1792 	/* make sure Rx is disabled before switching antenna */
1793 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
1794 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
1795 
1796 	rt2661_bbp_write(sc,  4, bbp4);
1797 	rt2661_bbp_write(sc, 77, bbp77);
1798 
1799 	/* restore Rx filter */
1800 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
1801 }
1802 
1803 /*
1804  * Enable multi-rate retries for frames sent at OFDM rates.
1805  * In 802.11b/g mode, allow fallback to CCK rates.
1806  */
1807 static void
1808 rt2661_enable_mrr(struct rt2661_softc *sc)
1809 {
1810 	struct ieee80211com *ic = &sc->sc_ic;
1811 	uint32_t tmp;
1812 
1813 	tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
1814 
1815 	tmp &= ~RT2661_MRR_CCK_FALLBACK;
1816 	if (!IEEE80211_IS_CHAN_5GHZ(ic->ic_bsschan))
1817 		tmp |= RT2661_MRR_CCK_FALLBACK;
1818 	tmp |= RT2661_MRR_ENABLED;
1819 
1820 	RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
1821 }
1822 
1823 static void
1824 rt2661_set_txpreamble(struct rt2661_softc *sc)
1825 {
1826 	struct ieee80211com *ic = &sc->sc_ic;
1827 	uint32_t tmp;
1828 
1829 	tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
1830 
1831 	tmp &= ~RT2661_SHORT_PREAMBLE;
1832 	if (ic->ic_flags & IEEE80211_F_SHPREAMBLE)
1833 		tmp |= RT2661_SHORT_PREAMBLE;
1834 
1835 	RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
1836 }
1837 
1838 static void
1839 rt2661_set_basicrates(struct rt2661_softc *sc,
1840     const struct ieee80211_rateset *rs)
1841 {
1842 	struct ieee80211com *ic = &sc->sc_ic;
1843 	uint32_t mask = 0;
1844 	uint8_t rate;
1845 	int i;
1846 
1847 	for (i = 0; i < rs->rs_nrates; i++) {
1848 		rate = rs->rs_rates[i];
1849 
1850 		if (!(rate & IEEE80211_RATE_BASIC))
1851 			continue;
1852 
1853 		mask |= 1 << ieee80211_legacy_rate_lookup(ic->ic_rt,
1854 		    IEEE80211_RV(rate));
1855 	}
1856 
1857 	RAL_WRITE(sc, RT2661_TXRX_CSR5, mask);
1858 
1859 	DPRINTF(sc, "Setting basic rate mask to 0x%x\n", mask);
1860 }
1861 
1862 /*
1863  * Reprogram MAC/BBP to switch to a new band.  Values taken from the reference
1864  * driver.
1865  */
1866 static void
1867 rt2661_select_band(struct rt2661_softc *sc, struct ieee80211_channel *c)
1868 {
1869 	uint8_t bbp17, bbp35, bbp96, bbp97, bbp98, bbp104;
1870 	uint32_t tmp;
1871 
1872 	/* update all BBP registers that depend on the band */
1873 	bbp17 = 0x20; bbp96 = 0x48; bbp104 = 0x2c;
1874 	bbp35 = 0x50; bbp97 = 0x48; bbp98  = 0x48;
1875 	if (IEEE80211_IS_CHAN_5GHZ(c)) {
1876 		bbp17 += 0x08; bbp96 += 0x10; bbp104 += 0x0c;
1877 		bbp35 += 0x10; bbp97 += 0x10; bbp98  += 0x10;
1878 	}
1879 	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
1880 	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
1881 		bbp17 += 0x10; bbp96 += 0x10; bbp104 += 0x10;
1882 	}
1883 
1884 	rt2661_bbp_write(sc,  17, bbp17);
1885 	rt2661_bbp_write(sc,  96, bbp96);
1886 	rt2661_bbp_write(sc, 104, bbp104);
1887 
1888 	if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
1889 	    (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
1890 		rt2661_bbp_write(sc, 75, 0x80);
1891 		rt2661_bbp_write(sc, 86, 0x80);
1892 		rt2661_bbp_write(sc, 88, 0x80);
1893 	}
1894 
1895 	rt2661_bbp_write(sc, 35, bbp35);
1896 	rt2661_bbp_write(sc, 97, bbp97);
1897 	rt2661_bbp_write(sc, 98, bbp98);
1898 
1899 	tmp = RAL_READ(sc, RT2661_PHY_CSR0);
1900 	tmp &= ~(RT2661_PA_PE_2GHZ | RT2661_PA_PE_5GHZ);
1901 	if (IEEE80211_IS_CHAN_2GHZ(c))
1902 		tmp |= RT2661_PA_PE_2GHZ;
1903 	else
1904 		tmp |= RT2661_PA_PE_5GHZ;
1905 	RAL_WRITE(sc, RT2661_PHY_CSR0, tmp);
1906 }
1907 
1908 static void
1909 rt2661_set_chan(struct rt2661_softc *sc, struct ieee80211_channel *c)
1910 {
1911 	struct ieee80211com *ic = &sc->sc_ic;
1912 	const struct rfprog *rfprog;
1913 	uint8_t bbp3, bbp94 = RT2661_BBPR94_DEFAULT;
1914 	int8_t power;
1915 	u_int i, chan;
1916 
1917 	chan = ieee80211_chan2ieee(ic, c);
1918 	KASSERT(chan != 0 && chan != IEEE80211_CHAN_ANY, ("chan 0x%x", chan));
1919 
1920 	/* select the appropriate RF settings based on what EEPROM says */
1921 	rfprog = (sc->rfprog == 0) ? rt2661_rf5225_1 : rt2661_rf5225_2;
1922 
1923 	/* find the settings for this channel (we know it exists) */
1924 	for (i = 0; rfprog[i].chan != chan; i++);
1925 
1926 	power = sc->txpow[i];
1927 	if (power < 0) {
1928 		bbp94 += power;
1929 		power = 0;
1930 	} else if (power > 31) {
1931 		bbp94 += power - 31;
1932 		power = 31;
1933 	}
1934 
1935 	/*
1936 	 * If we are switching from the 2GHz band to the 5GHz band or
1937 	 * vice-versa, BBP registers need to be reprogrammed.
1938 	 */
1939 	if (c->ic_flags != sc->sc_curchan->ic_flags) {
1940 		rt2661_select_band(sc, c);
1941 		rt2661_select_antenna(sc);
1942 	}
1943 	sc->sc_curchan = c;
1944 
1945 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
1946 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
1947 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
1948 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
1949 
1950 	DELAY(200);
1951 
1952 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
1953 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
1954 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7 | 1);
1955 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
1956 
1957 	DELAY(200);
1958 
1959 	rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
1960 	rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
1961 	rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
1962 	rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
1963 
1964 	/* enable smart mode for MIMO-capable RFs */
1965 	bbp3 = rt2661_bbp_read(sc, 3);
1966 
1967 	bbp3 &= ~RT2661_SMART_MODE;
1968 	if (sc->rf_rev == RT2661_RF_5325 || sc->rf_rev == RT2661_RF_2529)
1969 		bbp3 |= RT2661_SMART_MODE;
1970 
1971 	rt2661_bbp_write(sc, 3, bbp3);
1972 
1973 	if (bbp94 != RT2661_BBPR94_DEFAULT)
1974 		rt2661_bbp_write(sc, 94, bbp94);
1975 
1976 	/* 5GHz radio needs a 1ms delay here */
1977 	if (IEEE80211_IS_CHAN_5GHZ(c))
1978 		DELAY(1000);
1979 }
1980 
1981 static void
1982 rt2661_set_bssid(struct rt2661_softc *sc, const uint8_t *bssid)
1983 {
1984 	uint32_t tmp;
1985 
1986 	tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24;
1987 	RAL_WRITE(sc, RT2661_MAC_CSR4, tmp);
1988 
1989 	tmp = bssid[4] | bssid[5] << 8 | RT2661_ONE_BSSID << 16;
1990 	RAL_WRITE(sc, RT2661_MAC_CSR5, tmp);
1991 }
1992 
1993 static void
1994 rt2661_set_macaddr(struct rt2661_softc *sc, const uint8_t *addr)
1995 {
1996 	uint32_t tmp;
1997 
1998 	tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24;
1999 	RAL_WRITE(sc, RT2661_MAC_CSR2, tmp);
2000 
2001 	tmp = addr[4] | addr[5] << 8;
2002 	RAL_WRITE(sc, RT2661_MAC_CSR3, tmp);
2003 }
2004 
2005 static void
2006 rt2661_update_promisc(struct ieee80211com *ic)
2007 {
2008 	struct rt2661_softc *sc = ic->ic_softc;
2009 	uint32_t tmp;
2010 
2011 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2012 
2013 	tmp &= ~RT2661_DROP_NOT_TO_ME;
2014 	if (ic->ic_promisc == 0)
2015 		tmp |= RT2661_DROP_NOT_TO_ME;
2016 
2017 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2018 
2019 	DPRINTF(sc, "%s promiscuous mode\n",
2020 	    (ic->ic_promisc > 0) ?  "entering" : "leaving");
2021 }
2022 
2023 /*
2024  * Update QoS (802.11e) settings for each h/w Tx ring.
2025  */
2026 static int
2027 rt2661_wme_update(struct ieee80211com *ic)
2028 {
2029 	struct rt2661_softc *sc = ic->ic_softc;
2030 	struct chanAccParams chp;
2031 	const struct wmeParams *wmep;
2032 
2033 	ieee80211_wme_ic_getparams(ic, &chp);
2034 
2035 	wmep = chp.cap_wmeParams;
2036 
2037 	/* XXX: not sure about shifts. */
2038 	/* XXX: the reference driver plays with AC_VI settings too. */
2039 
2040 	/* update TxOp */
2041 	RAL_WRITE(sc, RT2661_AC_TXOP_CSR0,
2042 	    wmep[WME_AC_BE].wmep_txopLimit << 16 |
2043 	    wmep[WME_AC_BK].wmep_txopLimit);
2044 	RAL_WRITE(sc, RT2661_AC_TXOP_CSR1,
2045 	    wmep[WME_AC_VI].wmep_txopLimit << 16 |
2046 	    wmep[WME_AC_VO].wmep_txopLimit);
2047 
2048 	/* update CWmin */
2049 	RAL_WRITE(sc, RT2661_CWMIN_CSR,
2050 	    wmep[WME_AC_BE].wmep_logcwmin << 12 |
2051 	    wmep[WME_AC_BK].wmep_logcwmin <<  8 |
2052 	    wmep[WME_AC_VI].wmep_logcwmin <<  4 |
2053 	    wmep[WME_AC_VO].wmep_logcwmin);
2054 
2055 	/* update CWmax */
2056 	RAL_WRITE(sc, RT2661_CWMAX_CSR,
2057 	    wmep[WME_AC_BE].wmep_logcwmax << 12 |
2058 	    wmep[WME_AC_BK].wmep_logcwmax <<  8 |
2059 	    wmep[WME_AC_VI].wmep_logcwmax <<  4 |
2060 	    wmep[WME_AC_VO].wmep_logcwmax);
2061 
2062 	/* update Aifsn */
2063 	RAL_WRITE(sc, RT2661_AIFSN_CSR,
2064 	    wmep[WME_AC_BE].wmep_aifsn << 12 |
2065 	    wmep[WME_AC_BK].wmep_aifsn <<  8 |
2066 	    wmep[WME_AC_VI].wmep_aifsn <<  4 |
2067 	    wmep[WME_AC_VO].wmep_aifsn);
2068 
2069 	return 0;
2070 }
2071 
2072 static void
2073 rt2661_update_slot(struct ieee80211com *ic)
2074 {
2075 	struct rt2661_softc *sc = ic->ic_softc;
2076 	uint8_t slottime;
2077 	uint32_t tmp;
2078 
2079 	slottime = IEEE80211_GET_SLOTTIME(ic);
2080 
2081 	tmp = RAL_READ(sc, RT2661_MAC_CSR9);
2082 	tmp = (tmp & ~0xff) | slottime;
2083 	RAL_WRITE(sc, RT2661_MAC_CSR9, tmp);
2084 }
2085 
2086 static const char *
2087 rt2661_get_rf(int rev)
2088 {
2089 	switch (rev) {
2090 	case RT2661_RF_5225:	return "RT5225";
2091 	case RT2661_RF_5325:	return "RT5325 (MIMO XR)";
2092 	case RT2661_RF_2527:	return "RT2527";
2093 	case RT2661_RF_2529:	return "RT2529 (MIMO XR)";
2094 	default:		return "unknown";
2095 	}
2096 }
2097 
2098 static void
2099 rt2661_read_eeprom(struct rt2661_softc *sc, uint8_t macaddr[IEEE80211_ADDR_LEN])
2100 {
2101 	uint16_t val;
2102 	int i;
2103 
2104 	/* read MAC address */
2105 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC01);
2106 	macaddr[0] = val & 0xff;
2107 	macaddr[1] = val >> 8;
2108 
2109 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC23);
2110 	macaddr[2] = val & 0xff;
2111 	macaddr[3] = val >> 8;
2112 
2113 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC45);
2114 	macaddr[4] = val & 0xff;
2115 	macaddr[5] = val >> 8;
2116 
2117 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_ANTENNA);
2118 	/* XXX: test if different from 0xffff? */
2119 	sc->rf_rev   = (val >> 11) & 0x1f;
2120 	sc->hw_radio = (val >> 10) & 0x1;
2121 	sc->rx_ant   = (val >> 4)  & 0x3;
2122 	sc->tx_ant   = (val >> 2)  & 0x3;
2123 	sc->nb_ant   = val & 0x3;
2124 
2125 	DPRINTF(sc, "RF revision=%d\n", sc->rf_rev);
2126 
2127 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_CONFIG2);
2128 	sc->ext_5ghz_lna = (val >> 6) & 0x1;
2129 	sc->ext_2ghz_lna = (val >> 4) & 0x1;
2130 
2131 	DPRINTF(sc, "External 2GHz LNA=%d\nExternal 5GHz LNA=%d\n",
2132 	    sc->ext_2ghz_lna, sc->ext_5ghz_lna);
2133 
2134 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_2GHZ_OFFSET);
2135 	if ((val & 0xff) != 0xff)
2136 		sc->rssi_2ghz_corr = (int8_t)(val & 0xff);	/* signed */
2137 
2138 	/* Only [-10, 10] is valid */
2139 	if (sc->rssi_2ghz_corr < -10 || sc->rssi_2ghz_corr > 10)
2140 		sc->rssi_2ghz_corr = 0;
2141 
2142 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_5GHZ_OFFSET);
2143 	if ((val & 0xff) != 0xff)
2144 		sc->rssi_5ghz_corr = (int8_t)(val & 0xff);	/* signed */
2145 
2146 	/* Only [-10, 10] is valid */
2147 	if (sc->rssi_5ghz_corr < -10 || sc->rssi_5ghz_corr > 10)
2148 		sc->rssi_5ghz_corr = 0;
2149 
2150 	/* adjust RSSI correction for external low-noise amplifier */
2151 	if (sc->ext_2ghz_lna)
2152 		sc->rssi_2ghz_corr -= 14;
2153 	if (sc->ext_5ghz_lna)
2154 		sc->rssi_5ghz_corr -= 14;
2155 
2156 	DPRINTF(sc, "RSSI 2GHz corr=%d\nRSSI 5GHz corr=%d\n",
2157 	    sc->rssi_2ghz_corr, sc->rssi_5ghz_corr);
2158 
2159 	val = rt2661_eeprom_read(sc, RT2661_EEPROM_FREQ_OFFSET);
2160 	if ((val >> 8) != 0xff)
2161 		sc->rfprog = (val >> 8) & 0x3;
2162 	if ((val & 0xff) != 0xff)
2163 		sc->rffreq = val & 0xff;
2164 
2165 	DPRINTF(sc, "RF prog=%d\nRF freq=%d\n", sc->rfprog, sc->rffreq);
2166 
2167 	/* read Tx power for all a/b/g channels */
2168 	for (i = 0; i < 19; i++) {
2169 		val = rt2661_eeprom_read(sc, RT2661_EEPROM_TXPOWER + i);
2170 		sc->txpow[i * 2] = (int8_t)(val >> 8);		/* signed */
2171 		DPRINTF(sc, "Channel=%d Tx power=%d\n",
2172 		    rt2661_rf5225_1[i * 2].chan, sc->txpow[i * 2]);
2173 		sc->txpow[i * 2 + 1] = (int8_t)(val & 0xff);	/* signed */
2174 		DPRINTF(sc, "Channel=%d Tx power=%d\n",
2175 		    rt2661_rf5225_1[i * 2 + 1].chan, sc->txpow[i * 2 + 1]);
2176 	}
2177 
2178 	/* read vendor-specific BBP values */
2179 	for (i = 0; i < 16; i++) {
2180 		val = rt2661_eeprom_read(sc, RT2661_EEPROM_BBP_BASE + i);
2181 		if (val == 0 || val == 0xffff)
2182 			continue;	/* skip invalid entries */
2183 		sc->bbp_prom[i].reg = val >> 8;
2184 		sc->bbp_prom[i].val = val & 0xff;
2185 		DPRINTF(sc, "BBP R%d=%02x\n", sc->bbp_prom[i].reg,
2186 		    sc->bbp_prom[i].val);
2187 	}
2188 }
2189 
2190 static int
2191 rt2661_bbp_init(struct rt2661_softc *sc)
2192 {
2193 	int i, ntries;
2194 	uint8_t val;
2195 
2196 	/* wait for BBP to be ready */
2197 	for (ntries = 0; ntries < 100; ntries++) {
2198 		val = rt2661_bbp_read(sc, 0);
2199 		if (val != 0 && val != 0xff)
2200 			break;
2201 		DELAY(100);
2202 	}
2203 	if (ntries == 100) {
2204 		device_printf(sc->sc_dev, "timeout waiting for BBP\n");
2205 		return EIO;
2206 	}
2207 
2208 	/* initialize BBP registers to default values */
2209 	for (i = 0; i < nitems(rt2661_def_bbp); i++) {
2210 		rt2661_bbp_write(sc, rt2661_def_bbp[i].reg,
2211 		    rt2661_def_bbp[i].val);
2212 	}
2213 
2214 	/* write vendor-specific BBP values (from EEPROM) */
2215 	for (i = 0; i < 16; i++) {
2216 		if (sc->bbp_prom[i].reg == 0)
2217 			continue;
2218 		rt2661_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2219 	}
2220 
2221 	return 0;
2222 }
2223 
2224 static void
2225 rt2661_init_locked(struct rt2661_softc *sc)
2226 {
2227 	struct ieee80211com *ic = &sc->sc_ic;
2228 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2229 	uint32_t tmp, sta[3];
2230 	int i, error, ntries;
2231 
2232 	RAL_LOCK_ASSERT(sc);
2233 
2234 	if ((sc->sc_flags & RAL_FW_LOADED) == 0) {
2235 		error = rt2661_load_microcode(sc);
2236 		if (error != 0) {
2237 			device_printf(sc->sc_dev,
2238 			    "%s: could not load 8051 microcode, error %d\n",
2239 			    __func__, error);
2240 			return;
2241 		}
2242 		sc->sc_flags |= RAL_FW_LOADED;
2243 	}
2244 
2245 	rt2661_stop_locked(sc);
2246 
2247 	/* initialize Tx rings */
2248 	RAL_WRITE(sc, RT2661_AC1_BASE_CSR, sc->txq[1].physaddr);
2249 	RAL_WRITE(sc, RT2661_AC0_BASE_CSR, sc->txq[0].physaddr);
2250 	RAL_WRITE(sc, RT2661_AC2_BASE_CSR, sc->txq[2].physaddr);
2251 	RAL_WRITE(sc, RT2661_AC3_BASE_CSR, sc->txq[3].physaddr);
2252 
2253 	/* initialize Mgt ring */
2254 	RAL_WRITE(sc, RT2661_MGT_BASE_CSR, sc->mgtq.physaddr);
2255 
2256 	/* initialize Rx ring */
2257 	RAL_WRITE(sc, RT2661_RX_BASE_CSR, sc->rxq.physaddr);
2258 
2259 	/* initialize Tx rings sizes */
2260 	RAL_WRITE(sc, RT2661_TX_RING_CSR0,
2261 	    RT2661_TX_RING_COUNT << 24 |
2262 	    RT2661_TX_RING_COUNT << 16 |
2263 	    RT2661_TX_RING_COUNT <<  8 |
2264 	    RT2661_TX_RING_COUNT);
2265 
2266 	RAL_WRITE(sc, RT2661_TX_RING_CSR1,
2267 	    RT2661_TX_DESC_WSIZE << 16 |
2268 	    RT2661_TX_RING_COUNT <<  8 |	/* XXX: HCCA ring unused */
2269 	    RT2661_MGT_RING_COUNT);
2270 
2271 	/* initialize Rx rings */
2272 	RAL_WRITE(sc, RT2661_RX_RING_CSR,
2273 	    RT2661_RX_DESC_BACK  << 16 |
2274 	    RT2661_RX_DESC_WSIZE <<  8 |
2275 	    RT2661_RX_RING_COUNT);
2276 
2277 	/* XXX: some magic here */
2278 	RAL_WRITE(sc, RT2661_TX_DMA_DST_CSR, 0xaa);
2279 
2280 	/* load base addresses of all 5 Tx rings (4 data + 1 mgt) */
2281 	RAL_WRITE(sc, RT2661_LOAD_TX_RING_CSR, 0x1f);
2282 
2283 	/* load base address of Rx ring */
2284 	RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 2);
2285 
2286 	/* initialize MAC registers to default values */
2287 	for (i = 0; i < nitems(rt2661_def_mac); i++)
2288 		RAL_WRITE(sc, rt2661_def_mac[i].reg, rt2661_def_mac[i].val);
2289 
2290 	rt2661_set_macaddr(sc, vap ? vap->iv_myaddr : ic->ic_macaddr);
2291 
2292 	/* set host ready */
2293 	RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2294 	RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2295 
2296 	/* wait for BBP/RF to wakeup */
2297 	for (ntries = 0; ntries < 1000; ntries++) {
2298 		if (RAL_READ(sc, RT2661_MAC_CSR12) & 8)
2299 			break;
2300 		DELAY(1000);
2301 	}
2302 	if (ntries == 1000) {
2303 		printf("timeout waiting for BBP/RF to wakeup\n");
2304 		rt2661_stop_locked(sc);
2305 		return;
2306 	}
2307 
2308 	if (rt2661_bbp_init(sc) != 0) {
2309 		rt2661_stop_locked(sc);
2310 		return;
2311 	}
2312 
2313 	/* select default channel */
2314 	sc->sc_curchan = ic->ic_curchan;
2315 	rt2661_select_band(sc, sc->sc_curchan);
2316 	rt2661_select_antenna(sc);
2317 	rt2661_set_chan(sc, sc->sc_curchan);
2318 
2319 	/* update Rx filter */
2320 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0) & 0xffff;
2321 
2322 	tmp |= RT2661_DROP_PHY_ERROR | RT2661_DROP_CRC_ERROR;
2323 	if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2324 		tmp |= RT2661_DROP_CTL | RT2661_DROP_VER_ERROR |
2325 		       RT2661_DROP_ACKCTS;
2326 		if (ic->ic_opmode != IEEE80211_M_HOSTAP &&
2327 		    ic->ic_opmode != IEEE80211_M_MBSS)
2328 			tmp |= RT2661_DROP_TODS;
2329 		if (ic->ic_promisc == 0)
2330 			tmp |= RT2661_DROP_NOT_TO_ME;
2331 	}
2332 
2333 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2334 
2335 	/* clear STA registers */
2336 	RAL_READ_REGION_4(sc, RT2661_STA_CSR0, sta, nitems(sta));
2337 
2338 	/* initialize ASIC */
2339 	RAL_WRITE(sc, RT2661_MAC_CSR1, 4);
2340 
2341 	/* clear any pending interrupt */
2342 	RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2343 
2344 	/* enable interrupts */
2345 	RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
2346 	RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
2347 
2348 	/* kick Rx */
2349 	RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 1);
2350 
2351 	sc->sc_flags |= RAL_RUNNING;
2352 
2353 	callout_reset(&sc->watchdog_ch, hz, rt2661_watchdog, sc);
2354 }
2355 
2356 static void
2357 rt2661_init(void *priv)
2358 {
2359 	struct rt2661_softc *sc = priv;
2360 	struct ieee80211com *ic = &sc->sc_ic;
2361 
2362 	RAL_LOCK(sc);
2363 	rt2661_init_locked(sc);
2364 	RAL_UNLOCK(sc);
2365 
2366 	if (sc->sc_flags & RAL_RUNNING)
2367 		ieee80211_start_all(ic);		/* start all vap's */
2368 }
2369 
2370 void
2371 rt2661_stop_locked(struct rt2661_softc *sc)
2372 {
2373 	volatile int *flags = &sc->sc_flags;
2374 	uint32_t tmp;
2375 
2376 	while (*flags & RAL_INPUT_RUNNING)
2377 		msleep(sc, &sc->sc_mtx, 0, "ralrunning", hz/10);
2378 
2379 	callout_stop(&sc->watchdog_ch);
2380 	sc->sc_tx_timer = 0;
2381 
2382 	if (sc->sc_flags & RAL_RUNNING) {
2383 		sc->sc_flags &= ~RAL_RUNNING;
2384 
2385 		/* abort Tx (for all 5 Tx rings) */
2386 		RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 0x1f << 16);
2387 
2388 		/* disable Rx (value remains after reset!) */
2389 		tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2390 		RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2391 
2392 		/* reset ASIC */
2393 		RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2394 		RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2395 
2396 		/* disable interrupts */
2397 		RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffffff);
2398 		RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
2399 
2400 		/* clear any pending interrupt */
2401 		RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2402 		RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, 0xffffffff);
2403 
2404 		/* reset Tx and Rx rings */
2405 		rt2661_reset_tx_ring(sc, &sc->txq[0]);
2406 		rt2661_reset_tx_ring(sc, &sc->txq[1]);
2407 		rt2661_reset_tx_ring(sc, &sc->txq[2]);
2408 		rt2661_reset_tx_ring(sc, &sc->txq[3]);
2409 		rt2661_reset_tx_ring(sc, &sc->mgtq);
2410 		rt2661_reset_rx_ring(sc, &sc->rxq);
2411 	}
2412 }
2413 
2414 void
2415 rt2661_stop(void *priv)
2416 {
2417 	struct rt2661_softc *sc = priv;
2418 
2419 	RAL_LOCK(sc);
2420 	rt2661_stop_locked(sc);
2421 	RAL_UNLOCK(sc);
2422 }
2423 
2424 static int
2425 rt2661_load_microcode(struct rt2661_softc *sc)
2426 {
2427 	const struct firmware *fp;
2428 	const char *imagename;
2429 	int ntries, error;
2430 
2431 	RAL_LOCK_ASSERT(sc);
2432 
2433 	switch (sc->sc_id) {
2434 	case 0x0301: imagename = "rt2561sfw"; break;
2435 	case 0x0302: imagename = "rt2561fw"; break;
2436 	case 0x0401: imagename = "rt2661fw"; break;
2437 	default:
2438 		device_printf(sc->sc_dev, "%s: unexpected pci device id 0x%x, "
2439 		    "don't know how to retrieve firmware\n",
2440 		    __func__, sc->sc_id);
2441 		return EINVAL;
2442 	}
2443 	RAL_UNLOCK(sc);
2444 	fp = firmware_get(imagename);
2445 	RAL_LOCK(sc);
2446 	if (fp == NULL) {
2447 		device_printf(sc->sc_dev,
2448 		    "%s: unable to retrieve firmware image %s\n",
2449 		    __func__, imagename);
2450 		return EINVAL;
2451 	}
2452 
2453 	/*
2454 	 * Load 8051 microcode into NIC.
2455 	 */
2456 	/* reset 8051 */
2457 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2458 
2459 	/* cancel any pending Host to MCU command */
2460 	RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR, 0);
2461 	RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
2462 	RAL_WRITE(sc, RT2661_HOST_CMD_CSR, 0);
2463 
2464 	/* write 8051's microcode */
2465 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET | RT2661_MCU_SEL);
2466 	RAL_WRITE_REGION_1(sc, RT2661_MCU_CODE_BASE, fp->data, fp->datasize);
2467 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2468 
2469 	/* kick 8051's ass */
2470 	RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, 0);
2471 
2472 	/* wait for 8051 to initialize */
2473 	for (ntries = 0; ntries < 500; ntries++) {
2474 		if (RAL_READ(sc, RT2661_MCU_CNTL_CSR) & RT2661_MCU_READY)
2475 			break;
2476 		DELAY(100);
2477 	}
2478 	if (ntries == 500) {
2479 		device_printf(sc->sc_dev,
2480 		    "%s: timeout waiting for MCU to initialize\n", __func__);
2481 		error = EIO;
2482 	} else
2483 		error = 0;
2484 
2485 	firmware_put(fp, FIRMWARE_UNLOAD);
2486 	return error;
2487 }
2488 
2489 #ifdef notyet
2490 /*
2491  * Dynamically tune Rx sensitivity (BBP register 17) based on average RSSI and
2492  * false CCA count.  This function is called periodically (every seconds) when
2493  * in the RUN state.  Values taken from the reference driver.
2494  */
2495 static void
2496 rt2661_rx_tune(struct rt2661_softc *sc)
2497 {
2498 	uint8_t bbp17;
2499 	uint16_t cca;
2500 	int lo, hi, dbm;
2501 
2502 	/*
2503 	 * Tuning range depends on operating band and on the presence of an
2504 	 * external low-noise amplifier.
2505 	 */
2506 	lo = 0x20;
2507 	if (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan))
2508 		lo += 0x08;
2509 	if ((IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan) && sc->ext_2ghz_lna) ||
2510 	    (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan) && sc->ext_5ghz_lna))
2511 		lo += 0x10;
2512 	hi = lo + 0x20;
2513 
2514 	/* retrieve false CCA count since last call (clear on read) */
2515 	cca = RAL_READ(sc, RT2661_STA_CSR1) & 0xffff;
2516 
2517 	if (dbm >= -35) {
2518 		bbp17 = 0x60;
2519 	} else if (dbm >= -58) {
2520 		bbp17 = hi;
2521 	} else if (dbm >= -66) {
2522 		bbp17 = lo + 0x10;
2523 	} else if (dbm >= -74) {
2524 		bbp17 = lo + 0x08;
2525 	} else {
2526 		/* RSSI < -74dBm, tune using false CCA count */
2527 
2528 		bbp17 = sc->bbp17; /* current value */
2529 
2530 		hi -= 2 * (-74 - dbm);
2531 		if (hi < lo)
2532 			hi = lo;
2533 
2534 		if (bbp17 > hi) {
2535 			bbp17 = hi;
2536 
2537 		} else if (cca > 512) {
2538 			if (++bbp17 > hi)
2539 				bbp17 = hi;
2540 		} else if (cca < 100) {
2541 			if (--bbp17 < lo)
2542 				bbp17 = lo;
2543 		}
2544 	}
2545 
2546 	if (bbp17 != sc->bbp17) {
2547 		rt2661_bbp_write(sc, 17, bbp17);
2548 		sc->bbp17 = bbp17;
2549 	}
2550 }
2551 
2552 /*
2553  * Enter/Leave radar detection mode.
2554  * This is for 802.11h additional regulatory domains.
2555  */
2556 static void
2557 rt2661_radar_start(struct rt2661_softc *sc)
2558 {
2559 	uint32_t tmp;
2560 
2561 	/* disable Rx */
2562 	tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2563 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2564 
2565 	rt2661_bbp_write(sc, 82, 0x20);
2566 	rt2661_bbp_write(sc, 83, 0x00);
2567 	rt2661_bbp_write(sc, 84, 0x40);
2568 
2569 	/* save current BBP registers values */
2570 	sc->bbp18 = rt2661_bbp_read(sc, 18);
2571 	sc->bbp21 = rt2661_bbp_read(sc, 21);
2572 	sc->bbp22 = rt2661_bbp_read(sc, 22);
2573 	sc->bbp16 = rt2661_bbp_read(sc, 16);
2574 	sc->bbp17 = rt2661_bbp_read(sc, 17);
2575 	sc->bbp64 = rt2661_bbp_read(sc, 64);
2576 
2577 	rt2661_bbp_write(sc, 18, 0xff);
2578 	rt2661_bbp_write(sc, 21, 0x3f);
2579 	rt2661_bbp_write(sc, 22, 0x3f);
2580 	rt2661_bbp_write(sc, 16, 0xbd);
2581 	rt2661_bbp_write(sc, 17, sc->ext_5ghz_lna ? 0x44 : 0x34);
2582 	rt2661_bbp_write(sc, 64, 0x21);
2583 
2584 	/* restore Rx filter */
2585 	RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2586 }
2587 
2588 static int
2589 rt2661_radar_stop(struct rt2661_softc *sc)
2590 {
2591 	uint8_t bbp66;
2592 
2593 	/* read radar detection result */
2594 	bbp66 = rt2661_bbp_read(sc, 66);
2595 
2596 	/* restore BBP registers values */
2597 	rt2661_bbp_write(sc, 16, sc->bbp16);
2598 	rt2661_bbp_write(sc, 17, sc->bbp17);
2599 	rt2661_bbp_write(sc, 18, sc->bbp18);
2600 	rt2661_bbp_write(sc, 21, sc->bbp21);
2601 	rt2661_bbp_write(sc, 22, sc->bbp22);
2602 	rt2661_bbp_write(sc, 64, sc->bbp64);
2603 
2604 	return bbp66 == 1;
2605 }
2606 #endif
2607 
2608 static int
2609 rt2661_prepare_beacon(struct rt2661_softc *sc, struct ieee80211vap *vap)
2610 {
2611 	struct ieee80211com *ic = vap->iv_ic;
2612 	struct rt2661_tx_desc desc;
2613 	struct mbuf *m0;
2614 	int rate;
2615 
2616 	if ((m0 = ieee80211_beacon_alloc(vap->iv_bss))== NULL) {
2617 		device_printf(sc->sc_dev, "could not allocate beacon frame\n");
2618 		return ENOBUFS;
2619 	}
2620 
2621 	/* send beacons at the lowest available rate */
2622 	rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_bsschan) ? 12 : 2;
2623 
2624 	rt2661_setup_tx_desc(sc, &desc, RT2661_TX_TIMESTAMP, RT2661_TX_HWSEQ,
2625 	    m0->m_pkthdr.len, rate, NULL, 0, RT2661_QID_MGT);
2626 
2627 	/* copy the first 24 bytes of Tx descriptor into NIC memory */
2628 	RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0, (uint8_t *)&desc, 24);
2629 
2630 	/* copy beacon header and payload into NIC memory */
2631 	RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0 + 24,
2632 	    mtod(m0, uint8_t *), m0->m_pkthdr.len);
2633 
2634 	m_freem(m0);
2635 
2636 	return 0;
2637 }
2638 
2639 /*
2640  * Enable TSF synchronization and tell h/w to start sending beacons for IBSS
2641  * and HostAP operating modes.
2642  */
2643 static void
2644 rt2661_enable_tsf_sync(struct rt2661_softc *sc)
2645 {
2646 	struct ieee80211com *ic = &sc->sc_ic;
2647 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2648 	uint32_t tmp;
2649 
2650 	if (vap->iv_opmode != IEEE80211_M_STA) {
2651 		/*
2652 		 * Change default 16ms TBTT adjustment to 8ms.
2653 		 * Must be done before enabling beacon generation.
2654 		 */
2655 		RAL_WRITE(sc, RT2661_TXRX_CSR10, 1 << 12 | 8);
2656 	}
2657 
2658 	tmp = RAL_READ(sc, RT2661_TXRX_CSR9) & 0xff000000;
2659 
2660 	/* set beacon interval (in 1/16ms unit) */
2661 	tmp |= vap->iv_bss->ni_intval * 16;
2662 
2663 	tmp |= RT2661_TSF_TICKING | RT2661_ENABLE_TBTT;
2664 	if (vap->iv_opmode == IEEE80211_M_STA)
2665 		tmp |= RT2661_TSF_MODE(1);
2666 	else
2667 		tmp |= RT2661_TSF_MODE(2) | RT2661_GENERATE_BEACON;
2668 
2669 	RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp);
2670 }
2671 
2672 static void
2673 rt2661_enable_tsf(struct rt2661_softc *sc)
2674 {
2675 	RAL_WRITE(sc, RT2661_TXRX_CSR9,
2676 	      (RAL_READ(sc, RT2661_TXRX_CSR9) & 0xff000000)
2677 	    | RT2661_TSF_TICKING | RT2661_TSF_MODE(2));
2678 }
2679 
2680 /*
2681  * Retrieve the "Received Signal Strength Indicator" from the raw values
2682  * contained in Rx descriptors.  The computation depends on which band the
2683  * frame was received.  Correction values taken from the reference driver.
2684  */
2685 static int
2686 rt2661_get_rssi(struct rt2661_softc *sc, uint8_t raw)
2687 {
2688 	int lna, agc, rssi;
2689 
2690 	lna = (raw >> 5) & 0x3;
2691 	agc = raw & 0x1f;
2692 
2693 	if (lna == 0) {
2694 		/*
2695 		 * No mapping available.
2696 		 *
2697 		 * NB: Since RSSI is relative to noise floor, -1 is
2698 		 *     adequate for caller to know error happened.
2699 		 */
2700 		return -1;
2701 	}
2702 
2703 	rssi = (2 * agc) - RT2661_NOISE_FLOOR;
2704 
2705 	if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan)) {
2706 		rssi += sc->rssi_2ghz_corr;
2707 
2708 		if (lna == 1)
2709 			rssi -= 64;
2710 		else if (lna == 2)
2711 			rssi -= 74;
2712 		else if (lna == 3)
2713 			rssi -= 90;
2714 	} else {
2715 		rssi += sc->rssi_5ghz_corr;
2716 
2717 		if (lna == 1)
2718 			rssi -= 64;
2719 		else if (lna == 2)
2720 			rssi -= 86;
2721 		else if (lna == 3)
2722 			rssi -= 100;
2723 	}
2724 	return rssi;
2725 }
2726 
2727 static void
2728 rt2661_scan_start(struct ieee80211com *ic)
2729 {
2730 	struct rt2661_softc *sc = ic->ic_softc;
2731 	uint32_t tmp;
2732 
2733 	/* abort TSF synchronization */
2734 	tmp = RAL_READ(sc, RT2661_TXRX_CSR9);
2735 	RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp & ~0xffffff);
2736 	rt2661_set_bssid(sc, ieee80211broadcastaddr);
2737 }
2738 
2739 static void
2740 rt2661_scan_end(struct ieee80211com *ic)
2741 {
2742 	struct rt2661_softc *sc = ic->ic_softc;
2743 	struct ieee80211vap *vap = TAILQ_FIRST(&ic->ic_vaps);
2744 
2745 	rt2661_enable_tsf_sync(sc);
2746 	/* XXX keep local copy */
2747 	rt2661_set_bssid(sc, vap->iv_bss->ni_bssid);
2748 }
2749 
2750 static void
2751 rt2661_getradiocaps(struct ieee80211com *ic,
2752     int maxchans, int *nchans, struct ieee80211_channel chans[])
2753 {
2754 	struct rt2661_softc *sc = ic->ic_softc;
2755 	uint8_t bands[IEEE80211_MODE_BYTES];
2756 
2757 	memset(bands, 0, sizeof(bands));
2758 	setbit(bands, IEEE80211_MODE_11B);
2759 	setbit(bands, IEEE80211_MODE_11G);
2760 	ieee80211_add_channel_list_2ghz(chans, maxchans, nchans,
2761 	    rt2661_chan_2ghz, nitems(rt2661_chan_2ghz), bands, 0);
2762 
2763 	if (sc->rf_rev == RT2661_RF_5225 || sc->rf_rev == RT2661_RF_5325) {
2764 		setbit(bands, IEEE80211_MODE_11A);
2765 		ieee80211_add_channel_list_5ghz(chans, maxchans, nchans,
2766 		    rt2661_chan_5ghz, nitems(rt2661_chan_5ghz), bands, 0);
2767 	}
2768 }
2769 
2770 static void
2771 rt2661_set_channel(struct ieee80211com *ic)
2772 {
2773 	struct rt2661_softc *sc = ic->ic_softc;
2774 
2775 	RAL_LOCK(sc);
2776 	rt2661_set_chan(sc, ic->ic_curchan);
2777 	RAL_UNLOCK(sc);
2778 
2779 }
2780