Merge from vendor branch AWK:
[dragonfly.git] / sys / dev / netif / ral / rt2661.c
1 /*
2  * Copyright (c) 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/rt2661.c,v 1.4 2006/03/21 21:15:43 damien Exp $
18  * $DragonFly: src/sys/dev/netif/ral/rt2661.c,v 1.20 2007/04/28 14:40:13 sephe Exp $
19  */
20
21 /*
22  * Ralink Technology RT2561, RT2561S and RT2661 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/queue.h>
34 #include <sys/rman.h>
35 #include <sys/socket.h>
36 #include <sys/sockio.h>
37 #include <sys/sysctl.h>
38 #include <sys/serialize.h>
39
40 #include <net/bpf.h>
41 #include <net/if.h>
42 #include <net/if_arp.h>
43 #include <net/ethernet.h>
44 #include <net/if_dl.h>
45 #include <net/if_media.h>
46 #include <net/ifq_var.h>
47
48 #include <netproto/802_11/ieee80211_var.h>
49 #include <netproto/802_11/ieee80211_radiotap.h>
50
51 #include <dev/netif/ral/rt2661reg.h>
52 #include <dev/netif/ral/rt2661var.h>
53 #include <dev/netif/ral/rt2661_ucode.h>
54
55 #ifdef RAL_DEBUG
56 #define DPRINTF(x)      do { if (ral_debug > 0) kprintf x; } while (0)
57 #define DPRINTFN(n, x)  do { if (ral_debug >= (n)) kprintf x; } while (0)
58 int ral_debug = 1;
59 SYSCTL_INT(_debug, OID_AUTO, ral, CTLFLAG_RW, &ral_debug, 0, "ral debug level");
60 #else
61 #define DPRINTF(x)
62 #define DPRINTFN(n, x)
63 #endif
64
65 MALLOC_DEFINE(M_RT2661, "rt2661_ratectl", "rt2661 rate control data");
66
67 static void             rt2661_dma_map_addr(void *, bus_dma_segment_t *, int,
68                             int);
69 static void             rt2661_dma_map_mbuf(void *, bus_dma_segment_t *, int,
70                                             bus_size_t, int);
71 static int              rt2661_alloc_tx_ring(struct rt2661_softc *,
72                             struct rt2661_tx_ring *, int);
73 static void             rt2661_reset_tx_ring(struct rt2661_softc *,
74                             struct rt2661_tx_ring *);
75 static void             rt2661_free_tx_ring(struct rt2661_softc *,
76                             struct rt2661_tx_ring *);
77 static int              rt2661_alloc_rx_ring(struct rt2661_softc *,
78                             struct rt2661_rx_ring *, int);
79 static void             rt2661_reset_rx_ring(struct rt2661_softc *,
80                             struct rt2661_rx_ring *);
81 static void             rt2661_free_rx_ring(struct rt2661_softc *,
82                             struct rt2661_rx_ring *);
83 static int              rt2661_media_change(struct ifnet *);
84 static void             rt2661_next_scan(void *);
85 static int              rt2661_newstate(struct ieee80211com *,
86                             enum ieee80211_state, int);
87 static uint16_t         rt2661_eeprom_read(struct rt2661_softc *, uint8_t);
88 static void             rt2661_rx_intr(struct rt2661_softc *);
89 static void             rt2661_tx_intr(struct rt2661_softc *);
90 static void             rt2661_tx_dma_intr(struct rt2661_softc *,
91                             struct rt2661_tx_ring *);
92 static void             rt2661_mcu_beacon_expire(struct rt2661_softc *);
93 static void             rt2661_mcu_wakeup(struct rt2661_softc *);
94 static void             rt2661_mcu_cmd_intr(struct rt2661_softc *);
95 static uint8_t          rt2661_rxrate(struct rt2661_rx_desc *);
96 static uint8_t          rt2661_plcp_signal(int);
97 static void             rt2661_setup_tx_desc(struct rt2661_softc *,
98                             struct rt2661_tx_desc *, uint32_t, uint16_t, int,
99                             int, const bus_dma_segment_t *, int, int, int);
100 static struct mbuf *    rt2661_get_rts(struct rt2661_softc *,
101                             struct ieee80211_frame *, uint16_t);
102 static int              rt2661_tx_data(struct rt2661_softc *, struct mbuf *,
103                             struct ieee80211_node *, int);
104 static int              rt2661_tx_mgt(struct rt2661_softc *, struct mbuf *,
105                             struct ieee80211_node *);
106 static void             rt2661_start(struct ifnet *);
107 static void             rt2661_watchdog(struct ifnet *);
108 static int              rt2661_reset(struct ifnet *);
109 static int              rt2661_ioctl(struct ifnet *, u_long, caddr_t,
110                                      struct ucred *);
111 static void             rt2661_bbp_write(struct rt2661_softc *, uint8_t,
112                             uint8_t);
113 static uint8_t          rt2661_bbp_read(struct rt2661_softc *, uint8_t);
114 static void             rt2661_rf_write(struct rt2661_softc *, uint8_t,
115                             uint32_t);
116 static int              rt2661_tx_cmd(struct rt2661_softc *, uint8_t,
117                             uint16_t);
118 static void             rt2661_select_antenna(struct rt2661_softc *);
119 static void             rt2661_enable_mrr(struct rt2661_softc *);
120 static void             rt2661_set_txpreamble(struct rt2661_softc *);
121 static void             rt2661_set_ackrates(struct rt2661_softc *,
122                             const struct ieee80211_rateset *);
123 static void             rt2661_select_band(struct rt2661_softc *,
124                             struct ieee80211_channel *);
125 static void             rt2661_set_chan(struct rt2661_softc *,
126                             struct ieee80211_channel *);
127 static void             rt2661_set_bssid(struct rt2661_softc *,
128                             const uint8_t *);
129 static void             rt2661_set_macaddr(struct rt2661_softc *,
130                            const uint8_t *);
131 static void             rt2661_update_promisc(struct rt2661_softc *);
132 static int              rt2661_wme_update(struct ieee80211com *) __unused;
133 static void             rt2661_update_slot(struct ifnet *);
134 static const char       *rt2661_get_rf(int);
135 static void             rt2661_read_config(struct rt2661_softc *);
136 static void             rt2661_read_txpower_config(struct rt2661_softc *,
137                                                    uint8_t, int, int *);
138 static int              rt2661_bbp_init(struct rt2661_softc *);
139 static void             rt2661_init(void *);
140 static void             rt2661_stop(void *);
141 static void             rt2661_intr(void *);
142 static int              rt2661_load_microcode(struct rt2661_softc *,
143                             const uint8_t *, int);
144 #ifdef notyet
145 static void             rt2661_rx_tune(struct rt2661_softc *);
146 static void             rt2661_radar_start(struct rt2661_softc *);
147 static int              rt2661_radar_stop(struct rt2661_softc *);
148 #endif
149 static int              rt2661_prepare_beacon(struct rt2661_softc *);
150 static void             rt2661_enable_tsf_sync(struct rt2661_softc *);
151 static int              rt2661_get_rssi(struct rt2661_softc *, uint8_t);
152 static void             rt2661_led_newstate(struct rt2661_softc *,
153                                             enum ieee80211_state);
154
155 /*
156  * Supported rates for 802.11a/b/g modes (in 500Kbps unit).
157  */
158 static const struct ieee80211_rateset rt2661_rateset_11a =
159         { 8, { 12, 18, 24, 36, 48, 72, 96, 108 } };
160
161 static const struct ieee80211_rateset rt2661_rateset_11b =
162         { 4, { 2, 4, 11, 22 } };
163
164 static const struct ieee80211_rateset rt2661_rateset_11g =
165         { 12, { 2, 4, 11, 22, 12, 18, 24, 36, 48, 72, 96, 108 } };
166
167 static const struct {
168         uint32_t        reg;
169         uint32_t        val;
170 } rt2661_def_mac[] = {
171         RT2661_DEF_MAC
172 };
173
174 static const struct {
175         uint8_t reg;
176         uint8_t val;
177 } rt2661_def_bbp[] = {
178         RT2661_DEF_BBP
179 };
180
181 static const struct rfprog {
182         uint8_t         chan;
183         uint32_t        r1, r2, r3, r4;
184 }  rt2661_rf5225_1[] = {
185         RT2661_RF5225_1
186 }, rt2661_rf5225_2[] = {
187         RT2661_RF5225_2
188 };
189
190 #define LED_EE2MCU(bit) { \
191         .ee_bit         = RT2661_EE_LED_##bit, \
192         .mcu_bit        = RT2661_MCU_LED_##bit \
193 }
194 static const struct {
195         uint16_t        ee_bit;
196         uint16_t        mcu_bit;
197 } led_ee2mcu[] = {
198         LED_EE2MCU(RDYG),
199         LED_EE2MCU(RDYA),
200         LED_EE2MCU(ACT),
201         LED_EE2MCU(GPIO0),
202         LED_EE2MCU(GPIO1),
203         LED_EE2MCU(GPIO2),
204         LED_EE2MCU(GPIO3),
205         LED_EE2MCU(GPIO4)
206 };
207 #undef LED_EE2MCU
208
209 struct rt2661_dmamap {
210         bus_dma_segment_t       segs[RT2661_MAX_SCATTER];
211         int                     nseg;
212 };
213
214 int
215 rt2661_attach(device_t dev, int id)
216 {
217         struct rt2661_softc *sc = device_get_softc(dev);
218         struct ieee80211com *ic = &sc->sc_ic;
219         struct ifnet *ifp = &ic->ic_if;
220         uint32_t val, bbp_type;
221         const uint8_t *ucode = NULL;
222         int error, i, ac, ntries, size = 0;
223
224         callout_init(&sc->scan_ch);
225
226         sc->sc_irq_rid = 0;
227         sc->sc_irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->sc_irq_rid,
228                                             RF_ACTIVE | RF_SHAREABLE);
229         if (sc->sc_irq == NULL) {
230                 device_printf(dev, "could not allocate interrupt resource\n");
231                 return ENXIO;
232         }
233
234         /* wait for NIC to initialize */
235         for (ntries = 0; ntries < 1000; ntries++) {
236                 if ((val = RAL_READ(sc, RT2661_MAC_CSR0)) != 0)
237                         break;
238                 DELAY(1000);
239         }
240         if (ntries == 1000) {
241                 device_printf(sc->sc_dev,
242                     "timeout waiting for NIC to initialize\n");
243                 error = EIO;
244                 goto fail;
245         }
246         bbp_type = val;
247
248         /* retrieve RF rev. no and various other things from EEPROM */
249         rt2661_read_config(sc);
250
251         device_printf(dev, "MAC/BBP RT%X, RF %s\n", bbp_type,
252             rt2661_get_rf(sc->rf_rev));
253
254         /*
255          * Load 8051 microcode into NIC.
256          */
257         switch (id) {
258         case 0x0301:
259                 ucode = rt2561s_ucode;
260                 size = sizeof rt2561s_ucode;
261                 break;
262         case 0x0302:
263                 ucode = rt2561_ucode;
264                 size = sizeof rt2561_ucode;
265                 break;
266         case 0x0401:
267                 ucode = rt2661_ucode;
268                 size = sizeof rt2661_ucode;
269                 break;
270         }
271
272         error = rt2661_load_microcode(sc, ucode, size);
273         if (error != 0) {
274                 device_printf(sc->sc_dev, "could not load 8051 microcode\n");
275                 goto fail;
276         }
277
278         /*
279          * Allocate Tx and Rx rings.
280          */
281         for (ac = 0; ac < 4; ac++) {
282                 error = rt2661_alloc_tx_ring(sc, &sc->txq[ac],
283                     RT2661_TX_RING_COUNT);
284                 if (error != 0) {
285                         device_printf(sc->sc_dev,
286                             "could not allocate Tx ring %d\n", ac);
287                         goto fail;
288                 }
289         }
290
291         error = rt2661_alloc_tx_ring(sc, &sc->mgtq, RT2661_MGT_RING_COUNT);
292         if (error != 0) {
293                 device_printf(sc->sc_dev, "could not allocate Mgt ring\n");
294                 goto fail;
295         }
296
297         error = rt2661_alloc_rx_ring(sc, &sc->rxq, RT2661_RX_RING_COUNT);
298         if (error != 0) {
299                 device_printf(sc->sc_dev, "could not allocate Rx ring\n");
300                 goto fail;
301         }
302
303         STAILQ_INIT(&sc->tx_ratectl);
304
305         sysctl_ctx_init(&sc->sysctl_ctx);
306         sc->sysctl_tree = SYSCTL_ADD_NODE(&sc->sysctl_ctx,
307                                           SYSCTL_STATIC_CHILDREN(_hw),
308                                           OID_AUTO,
309                                           device_get_nameunit(dev),
310                                           CTLFLAG_RD, 0, "");
311         if (sc->sysctl_tree == NULL) {
312                 device_printf(dev, "could not add sysctl node\n");
313                 error = ENXIO;
314                 goto fail;
315         }
316
317         ifp->if_softc = sc;
318         if_initname(ifp, device_get_name(dev), device_get_unit(dev));
319         ifp->if_flags = IFF_BROADCAST | IFF_SIMPLEX | IFF_MULTICAST;
320         ifp->if_init = rt2661_init;
321         ifp->if_ioctl = rt2661_ioctl;
322         ifp->if_start = rt2661_start;
323         ifp->if_watchdog = rt2661_watchdog;
324         ifq_set_maxlen(&ifp->if_snd, IFQ_MAXLEN);
325         ifq_set_ready(&ifp->if_snd);
326
327         ic->ic_phytype = IEEE80211_T_OFDM; /* not only, but not used */
328         ic->ic_opmode = IEEE80211_M_STA; /* default to BSS mode */
329         ic->ic_state = IEEE80211_S_INIT;
330         rt2661_led_newstate(sc, IEEE80211_S_INIT);
331
332         ic->ic_ratectl.rc_st_ratectl_cap = IEEE80211_RATECTL_CAP_ONOE;
333         if (bbp_type == RT2661_BBP_2661D) {
334                 ic->ic_ratectl.rc_st_ratectl = IEEE80211_RATECTL_ONOE;
335         } else {
336                 ic->ic_ratectl.rc_st_ratectl_cap |=
337                         IEEE80211_RATECTL_CAP_SAMPLE;
338                 ic->ic_ratectl.rc_st_ratectl = IEEE80211_RATECTL_SAMPLE;
339         }
340
341         /* set device capabilities */
342         ic->ic_caps =
343             IEEE80211_C_IBSS |          /* IBSS mode supported */
344             IEEE80211_C_MONITOR |       /* monitor mode supported */
345             IEEE80211_C_HOSTAP |        /* HostAp mode supported */
346             IEEE80211_C_TXPMGT |        /* tx power management */
347             IEEE80211_C_SHPREAMBLE |    /* short preamble supported */
348             IEEE80211_C_SHSLOT |        /* short slot time supported */
349 #ifdef notyet
350             IEEE80211_C_WME |           /* 802.11e */
351 #endif
352             IEEE80211_C_WEP |           /* WEP */
353             IEEE80211_C_WPA;            /* 802.11i */
354
355         if (sc->rf_rev == RT2661_RF_5225 || sc->rf_rev == RT2661_RF_5325) {
356                 /* set supported .11a rates */
357                 ic->ic_sup_rates[IEEE80211_MODE_11A] = rt2661_rateset_11a;
358
359                 /* set supported .11a channels */
360                 for (i = 36; i <= 64; i += 4) {
361                         ic->ic_channels[i].ic_freq =
362                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
363                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
364                 }
365                 for (i = 100; i <= 140; i += 4) {
366                         ic->ic_channels[i].ic_freq =
367                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
368                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
369                 }
370                 for (i = 149; i <= 165; i += 4) {
371                         ic->ic_channels[i].ic_freq =
372                             ieee80211_ieee2mhz(i, IEEE80211_CHAN_5GHZ);
373                         ic->ic_channels[i].ic_flags = IEEE80211_CHAN_A;
374                 }
375         }
376
377         /* set supported .11b and .11g rates */
378         ic->ic_sup_rates[IEEE80211_MODE_11B] = rt2661_rateset_11b;
379         ic->ic_sup_rates[IEEE80211_MODE_11G] = rt2661_rateset_11g;
380
381         /* set supported .11b and .11g channels (1 through 14) */
382         for (i = 1; i <= 14; i++) {
383                 ic->ic_channels[i].ic_freq =
384                     ieee80211_ieee2mhz(i, IEEE80211_CHAN_2GHZ);
385                 ic->ic_channels[i].ic_flags =
386                     IEEE80211_CHAN_CCK | IEEE80211_CHAN_OFDM |
387                     IEEE80211_CHAN_DYN | IEEE80211_CHAN_2GHZ;
388         }
389
390         sc->sc_sifs = IEEE80211_DUR_SIFS;       /* Default SIFS */
391
392         ieee80211_ifattach(ic);
393 /*      ic->ic_wme.wme_update = rt2661_wme_update;*/
394         ic->ic_updateslot = rt2661_update_slot;
395         ic->ic_reset = rt2661_reset;
396         /* enable s/w bmiss handling in sta mode */
397         ic->ic_flags_ext |= IEEE80211_FEXT_SWBMISS;
398
399         /* override state transition machine */
400         sc->sc_newstate = ic->ic_newstate;
401         ic->ic_newstate = rt2661_newstate;
402         ieee80211_media_init(ic, rt2661_media_change, ieee80211_media_status);
403
404         bpfattach_dlt(ifp, DLT_IEEE802_11_RADIO,
405             sizeof (struct ieee80211_frame) + 64, &sc->sc_drvbpf);
406
407         sc->sc_rxtap_len = sizeof sc->sc_rxtapu;
408         sc->sc_rxtap.wr_ihdr.it_len = htole16(sc->sc_rxtap_len);
409         sc->sc_rxtap.wr_ihdr.it_present = htole32(RT2661_RX_RADIOTAP_PRESENT);
410
411         sc->sc_txtap_len = sizeof sc->sc_txtapu;
412         sc->sc_txtap.wt_ihdr.it_len = htole16(sc->sc_txtap_len);
413         sc->sc_txtap.wt_ihdr.it_present = htole32(RT2661_TX_RADIOTAP_PRESENT);
414
415         /*
416          * Add a few sysctl knobs.
417          */
418         sc->dwelltime = 200;
419
420         SYSCTL_ADD_INT(&sc->sysctl_ctx,
421             SYSCTL_CHILDREN(sc->sysctl_tree), OID_AUTO, "dwell",
422             CTLFLAG_RW, &sc->dwelltime, 0,
423             "channel dwell time (ms) for AP/station scanning");
424
425         error = bus_setup_intr(dev, sc->sc_irq, INTR_MPSAFE, rt2661_intr,
426                                sc, &sc->sc_ih, ifp->if_serializer);
427         if (error != 0) {
428                 device_printf(dev, "could not set up interrupt\n");
429                 bpfdetach(ifp);
430                 ieee80211_ifdetach(ic);
431                 goto fail;
432         }
433
434         if (bootverbose)
435                 ieee80211_announce(ic);
436         return 0;
437 fail:
438         rt2661_detach(sc);
439         return error;
440 }
441
442 int
443 rt2661_detach(void *xsc)
444 {
445         struct rt2661_softc *sc = xsc;
446         struct ieee80211com *ic = &sc->sc_ic;
447         struct ifnet *ifp = &ic->ic_if;
448
449         if (device_is_attached(sc->sc_dev)) {
450                 lwkt_serialize_enter(ifp->if_serializer);
451
452                 callout_stop(&sc->scan_ch);
453                 rt2661_stop(sc);
454                 bus_teardown_intr(sc->sc_dev, sc->sc_irq, sc->sc_ih);
455
456                 lwkt_serialize_exit(ifp->if_serializer);
457
458                 bpfdetach(ifp);
459                 ieee80211_ifdetach(ic);
460         }
461
462         rt2661_free_tx_ring(sc, &sc->txq[0]);
463         rt2661_free_tx_ring(sc, &sc->txq[1]);
464         rt2661_free_tx_ring(sc, &sc->txq[2]);
465         rt2661_free_tx_ring(sc, &sc->txq[3]);
466         rt2661_free_tx_ring(sc, &sc->mgtq);
467         rt2661_free_rx_ring(sc, &sc->rxq);
468
469         if (sc->sc_irq != NULL) {
470                 bus_release_resource(sc->sc_dev, SYS_RES_IRQ, sc->sc_irq_rid,
471                                      sc->sc_irq);
472         }
473
474         if (sc->sysctl_tree != NULL)
475                 sysctl_ctx_free(&sc->sysctl_ctx);
476
477         return 0;
478 }
479
480 void
481 rt2661_shutdown(void *xsc)
482 {
483         struct rt2661_softc *sc = xsc;
484         struct ifnet *ifp = &sc->sc_ic.ic_if;
485
486         lwkt_serialize_enter(ifp->if_serializer);
487         rt2661_stop(sc);
488         lwkt_serialize_exit(ifp->if_serializer);
489 }
490
491 void
492 rt2661_suspend(void *xsc)
493 {
494         struct rt2661_softc *sc = xsc;
495         struct ifnet *ifp = &sc->sc_ic.ic_if;
496
497         lwkt_serialize_enter(ifp->if_serializer);
498         rt2661_stop(sc);
499         lwkt_serialize_exit(ifp->if_serializer);
500 }
501
502 void
503 rt2661_resume(void *xsc)
504 {
505         struct rt2661_softc *sc = xsc;
506         struct ifnet *ifp = sc->sc_ic.ic_ifp;
507
508         lwkt_serialize_enter(ifp->if_serializer);
509         if (ifp->if_flags & IFF_UP) {
510                 ifp->if_init(ifp->if_softc);
511                 if (ifp->if_flags & IFF_RUNNING)
512                         ifp->if_start(ifp);
513         }
514         lwkt_serialize_exit(ifp->if_serializer);
515 }
516
517 static void
518 rt2661_dma_map_addr(void *arg, bus_dma_segment_t *segs, int nseg, int error)
519 {
520         if (error != 0)
521                 return;
522
523         KASSERT(nseg == 1, ("too many DMA segments, %d should be 1", nseg));
524
525         *(bus_addr_t *)arg = segs[0].ds_addr;
526 }
527
528 static int
529 rt2661_alloc_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring,
530     int count)
531 {
532         int i, error;
533
534         ring->count = count;
535         ring->queued = 0;
536         ring->cur = ring->next = 0;
537
538         error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
539             BUS_SPACE_MAXADDR, NULL, NULL, count * RT2661_TX_DESC_SIZE, 1,
540             count * RT2661_TX_DESC_SIZE, 0, &ring->desc_dmat);
541         if (error != 0) {
542                 device_printf(sc->sc_dev, "could not create desc DMA tag\n");
543                 goto fail;
544         }
545
546         error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
547             BUS_DMA_WAITOK | BUS_DMA_ZERO, &ring->desc_map);
548         if (error != 0) {
549                 device_printf(sc->sc_dev, "could not allocate DMA memory\n");
550                 goto fail;
551         }
552
553         error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
554             count * RT2661_TX_DESC_SIZE, rt2661_dma_map_addr, &ring->physaddr,
555             0);
556         if (error != 0) {
557                 device_printf(sc->sc_dev, "could not load desc DMA map\n");
558
559                 bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
560                 ring->desc = NULL;
561                 goto fail;
562         }
563
564         ring->data = kmalloc(count * sizeof (struct rt2661_data), M_DEVBUF,
565             M_WAITOK | M_ZERO);
566
567         error = bus_dma_tag_create(NULL, 1, 0, BUS_SPACE_MAXADDR_32BIT,
568             BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES * RT2661_MAX_SCATTER,
569             RT2661_MAX_SCATTER, MCLBYTES, 0, &ring->data_dmat);
570         if (error != 0) {
571                 device_printf(sc->sc_dev, "could not create data DMA tag\n");
572                 goto fail;
573         }
574
575         for (i = 0; i < count; i++) {
576                 error = bus_dmamap_create(ring->data_dmat, 0,
577                     &ring->data[i].map);
578                 if (error != 0) {
579                         device_printf(sc->sc_dev, "could not create DMA map\n");
580                         goto fail;
581                 }
582         }
583         return 0;
584
585 fail:   rt2661_free_tx_ring(sc, ring);
586         return error;
587 }
588
589 static void
590 rt2661_reset_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring)
591 {
592         struct rt2661_tx_desc *desc;
593         struct rt2661_data *data;
594         int i;
595
596         for (i = 0; i < ring->count; i++) {
597                 desc = &ring->desc[i];
598                 data = &ring->data[i];
599
600                 if (data->m != NULL) {
601                         bus_dmamap_sync(ring->data_dmat, data->map,
602                             BUS_DMASYNC_POSTWRITE);
603                         bus_dmamap_unload(ring->data_dmat, data->map);
604                         m_freem(data->m);
605                         data->m = NULL;
606                 }
607
608                 desc->flags = 0;
609         }
610
611         bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
612
613         ring->queued = 0;
614         ring->cur = ring->next = 0;
615 }
616
617 static void
618 rt2661_free_tx_ring(struct rt2661_softc *sc, struct rt2661_tx_ring *ring)
619 {
620         struct rt2661_data *data;
621         int i;
622
623         if (ring->desc != NULL) {
624                 bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
625                     BUS_DMASYNC_POSTWRITE);
626                 bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
627                 bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
628                 ring->desc = NULL;
629         }
630
631         if (ring->desc_dmat != NULL) {
632                 bus_dma_tag_destroy(ring->desc_dmat);
633                 ring->desc_dmat = NULL;
634         }
635
636         if (ring->data != NULL) {
637                 for (i = 0; i < ring->count; i++) {
638                         data = &ring->data[i];
639
640                         if (data->m != NULL) {
641                                 bus_dmamap_sync(ring->data_dmat, data->map,
642                                     BUS_DMASYNC_POSTWRITE);
643                                 bus_dmamap_unload(ring->data_dmat, data->map);
644                                 m_freem(data->m);
645                                 data->m = NULL;
646                         }
647
648                         if (data->map != NULL) {
649                                 bus_dmamap_destroy(ring->data_dmat, data->map);
650                                 data->map = NULL;
651                         }
652                 }
653
654                 kfree(ring->data, M_DEVBUF);
655                 ring->data = NULL;
656         }
657
658         if (ring->data_dmat != NULL) {
659                 bus_dma_tag_destroy(ring->data_dmat);
660                 ring->data_dmat = NULL;
661         }
662 }
663
664 static int
665 rt2661_alloc_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring,
666     int count)
667 {
668         struct rt2661_rx_desc *desc;
669         struct rt2661_data *data;
670         bus_addr_t physaddr;
671         int i, error;
672
673         ring->count = count;
674         ring->cur = ring->next = 0;
675
676         error = bus_dma_tag_create(NULL, 4, 0, BUS_SPACE_MAXADDR_32BIT,
677             BUS_SPACE_MAXADDR, NULL, NULL, count * RT2661_RX_DESC_SIZE, 1,
678             count * RT2661_RX_DESC_SIZE, 0, &ring->desc_dmat);
679         if (error != 0) {
680                 device_printf(sc->sc_dev, "could not create desc DMA tag\n");
681                 goto fail;
682         }
683
684         error = bus_dmamem_alloc(ring->desc_dmat, (void **)&ring->desc,
685             BUS_DMA_WAITOK | BUS_DMA_ZERO, &ring->desc_map);
686         if (error != 0) {
687                 device_printf(sc->sc_dev, "could not allocate DMA memory\n");
688                 goto fail;
689         }
690
691         error = bus_dmamap_load(ring->desc_dmat, ring->desc_map, ring->desc,
692             count * RT2661_RX_DESC_SIZE, rt2661_dma_map_addr, &ring->physaddr,
693             0);
694         if (error != 0) {
695                 device_printf(sc->sc_dev, "could not load desc DMA map\n");
696
697                 bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
698                 ring->desc = NULL;
699                 goto fail;
700         }
701
702         ring->data = kmalloc(count * sizeof (struct rt2661_data), M_DEVBUF,
703             M_WAITOK | M_ZERO);
704
705         /*
706          * Pre-allocate Rx buffers and populate Rx ring.
707          */
708         error = bus_dma_tag_create(NULL, 1, 0, BUS_SPACE_MAXADDR_32BIT,
709             BUS_SPACE_MAXADDR, NULL, NULL, MCLBYTES, 1, MCLBYTES, 0,
710             &ring->data_dmat);
711         if (error != 0) {
712                 device_printf(sc->sc_dev, "could not create data DMA tag\n");
713                 goto fail;
714         }
715
716         for (i = 0; i < count; i++) {
717                 desc = &sc->rxq.desc[i];
718                 data = &sc->rxq.data[i];
719
720                 error = bus_dmamap_create(ring->data_dmat, 0, &data->map);
721                 if (error != 0) {
722                         device_printf(sc->sc_dev, "could not create DMA map\n");
723                         goto fail;
724                 }
725
726                 data->m = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
727                 if (data->m == NULL) {
728                         device_printf(sc->sc_dev,
729                             "could not allocate rx mbuf\n");
730                         error = ENOMEM;
731                         goto fail;
732                 }
733
734                 error = bus_dmamap_load(ring->data_dmat, data->map,
735                     mtod(data->m, void *), MCLBYTES, rt2661_dma_map_addr,
736                     &physaddr, 0);
737                 if (error != 0) {
738                         device_printf(sc->sc_dev,
739                             "could not load rx buf DMA map");
740
741                         m_freem(data->m);
742                         data->m = NULL;
743                         goto fail;
744                 }
745
746                 desc->flags = htole32(RT2661_RX_BUSY);
747                 desc->physaddr = htole32(physaddr);
748         }
749
750         bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
751
752         return 0;
753
754 fail:   rt2661_free_rx_ring(sc, ring);
755         return error;
756 }
757
758 static void
759 rt2661_reset_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring)
760 {
761         int i;
762
763         for (i = 0; i < ring->count; i++)
764                 ring->desc[i].flags = htole32(RT2661_RX_BUSY);
765
766         bus_dmamap_sync(ring->desc_dmat, ring->desc_map, BUS_DMASYNC_PREWRITE);
767
768         ring->cur = ring->next = 0;
769 }
770
771 static void
772 rt2661_free_rx_ring(struct rt2661_softc *sc, struct rt2661_rx_ring *ring)
773 {
774         struct rt2661_data *data;
775         int i;
776
777         if (ring->desc != NULL) {
778                 bus_dmamap_sync(ring->desc_dmat, ring->desc_map,
779                     BUS_DMASYNC_POSTWRITE);
780                 bus_dmamap_unload(ring->desc_dmat, ring->desc_map);
781                 bus_dmamem_free(ring->desc_dmat, ring->desc, ring->desc_map);
782                 ring->desc = NULL;
783         }
784
785         if (ring->desc_dmat != NULL) {
786                 bus_dma_tag_destroy(ring->desc_dmat);
787                 ring->desc_dmat = NULL;
788         }
789
790         if (ring->data != NULL) {
791                 for (i = 0; i < ring->count; i++) {
792                         data = &ring->data[i];
793
794                         if (data->m != NULL) {
795                                 bus_dmamap_sync(ring->data_dmat, data->map,
796                                     BUS_DMASYNC_POSTREAD);
797                                 bus_dmamap_unload(ring->data_dmat, data->map);
798                                 m_freem(data->m);
799                                 data->m = NULL;
800                         }
801
802                         if (data->map != NULL) {
803                                 bus_dmamap_destroy(ring->data_dmat, data->map);
804                                 data->map = NULL;
805                         }
806                 }
807
808                 kfree(ring->data, M_DEVBUF);
809                 ring->data = NULL;
810         }
811
812         if (ring->data_dmat != NULL) {
813                 bus_dma_tag_destroy(ring->data_dmat);
814                 ring->data_dmat = NULL;
815         }
816 }
817
818 static int
819 rt2661_media_change(struct ifnet *ifp)
820 {
821         struct rt2661_softc *sc = ifp->if_softc;
822         int error;
823
824         error = ieee80211_media_change(ifp);
825         if (error != ENETRESET)
826                 return error;
827
828         if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) == (IFF_UP | IFF_RUNNING))
829                 rt2661_init(sc);
830         return 0;
831 }
832
833 /*
834  * This function is called periodically (every 200ms) during scanning to
835  * switch from one channel to another.
836  */
837 static void
838 rt2661_next_scan(void *arg)
839 {
840         struct rt2661_softc *sc = arg;
841         struct ieee80211com *ic = &sc->sc_ic;
842         struct ifnet *ifp = &ic->ic_if;
843
844         lwkt_serialize_enter(ifp->if_serializer);
845         if (ic->ic_state == IEEE80211_S_SCAN)
846                 ieee80211_next_scan(ic);
847         lwkt_serialize_exit(ifp->if_serializer);
848 }
849
850 static int
851 rt2661_newstate(struct ieee80211com *ic, enum ieee80211_state nstate, int arg)
852 {
853         struct rt2661_softc *sc = ic->ic_ifp->if_softc;
854         enum ieee80211_state ostate;
855         struct ieee80211_node *ni;
856         uint32_t tmp;
857         int error = 0;
858
859         ostate = ic->ic_state;
860         callout_stop(&sc->scan_ch);
861
862         if (ostate != nstate)
863                 rt2661_led_newstate(sc, nstate);
864
865         ieee80211_ratectl_newstate(ic, nstate);
866
867         switch (nstate) {
868         case IEEE80211_S_INIT:
869                 if (ostate == IEEE80211_S_RUN) {
870                         /* abort TSF synchronization */
871                         tmp = RAL_READ(sc, RT2661_TXRX_CSR9);
872                         RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp & ~0x00ffffff);
873                 }
874                 break;
875
876         case IEEE80211_S_SCAN:
877                 rt2661_set_chan(sc, ic->ic_curchan);
878                 callout_reset(&sc->scan_ch, (sc->dwelltime * hz) / 1000,
879                     rt2661_next_scan, sc);
880                 break;
881
882         case IEEE80211_S_AUTH:
883         case IEEE80211_S_ASSOC:
884                 rt2661_set_chan(sc, ic->ic_curchan);
885                 break;
886
887         case IEEE80211_S_RUN:
888                 rt2661_set_chan(sc, ic->ic_curchan);
889
890                 ni = ic->ic_bss;
891
892                 if (ic->ic_opmode != IEEE80211_M_MONITOR) {
893                         rt2661_enable_mrr(sc);
894                         rt2661_set_txpreamble(sc);
895                         rt2661_set_ackrates(sc, &ni->ni_rates);
896                         rt2661_set_bssid(sc, ni->ni_bssid);
897                 }
898
899                 if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
900                     ic->ic_opmode == IEEE80211_M_IBSS) {
901                         if ((error = rt2661_prepare_beacon(sc)) != 0)
902                                 break;
903                 }
904
905                 if (ic->ic_opmode != IEEE80211_M_MONITOR)
906                         rt2661_enable_tsf_sync(sc);
907                 break;
908         }       
909
910         return (error != 0) ? error : sc->sc_newstate(ic, nstate, arg);
911 }
912
913 /*
914  * Read 16 bits at address 'addr' from the serial EEPROM (either 93C46 or
915  * 93C66).
916  */
917 static uint16_t
918 rt2661_eeprom_read(struct rt2661_softc *sc, uint8_t addr)
919 {
920         uint32_t tmp;
921         uint16_t val;
922         int n;
923
924         /* clock C once before the first command */
925         RT2661_EEPROM_CTL(sc, 0);
926
927         RT2661_EEPROM_CTL(sc, RT2661_S);
928         RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
929         RT2661_EEPROM_CTL(sc, RT2661_S);
930
931         /* write start bit (1) */
932         RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
933         RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
934
935         /* write READ opcode (10) */
936         RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
937         RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
938         RT2661_EEPROM_CTL(sc, RT2661_S);
939         RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
940
941         /* write address (A5-A0 or A7-A0) */
942         n = (RAL_READ(sc, RT2661_E2PROM_CSR) & RT2661_93C46) ? 5 : 7;
943         for (; n >= 0; n--) {
944                 RT2661_EEPROM_CTL(sc, RT2661_S |
945                     (((addr >> n) & 1) << RT2661_SHIFT_D));
946                 RT2661_EEPROM_CTL(sc, RT2661_S |
947                     (((addr >> n) & 1) << RT2661_SHIFT_D) | RT2661_C);
948         }
949
950         RT2661_EEPROM_CTL(sc, RT2661_S);
951
952         /* read data Q15-Q0 */
953         val = 0;
954         for (n = 15; n >= 0; n--) {
955                 RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
956                 tmp = RAL_READ(sc, RT2661_E2PROM_CSR);
957                 val |= ((tmp & RT2661_Q) >> RT2661_SHIFT_Q) << n;
958                 RT2661_EEPROM_CTL(sc, RT2661_S);
959         }
960
961         RT2661_EEPROM_CTL(sc, 0);
962
963         /* clear Chip Select and clock C */
964         RT2661_EEPROM_CTL(sc, RT2661_S);
965         RT2661_EEPROM_CTL(sc, 0);
966         RT2661_EEPROM_CTL(sc, RT2661_C);
967
968         return val;
969 }
970
971 static void
972 rt2661_tx_intr(struct rt2661_softc *sc)
973 {
974         struct ieee80211com *ic = &sc->sc_ic;
975         struct ifnet *ifp = ic->ic_ifp;
976         struct rt2661_tx_ratectl *rctl;
977         uint32_t val, result;
978         int retrycnt;
979
980         for (;;) {
981                 struct ieee80211_ratectl_res res;
982
983                 val = RAL_READ(sc, RT2661_STA_CSR4);
984                 if (!(val & RT2661_TX_STAT_VALID))
985                         break;
986
987                 /* Gather statistics */
988                 result = RT2661_TX_RESULT(val);
989                 if (result == RT2661_TX_SUCCESS)
990                         ifp->if_opackets++;
991                 else
992                         ifp->if_oerrors++;
993
994                 /* No rate control */
995                 if (RT2661_TX_QID(val) == 0)
996                         continue;
997
998                 /* retrieve rate control algorithm context */
999                 rctl = STAILQ_FIRST(&sc->tx_ratectl);
1000                 if (rctl == NULL) {
1001                         /*
1002                          * XXX
1003                          * This really should not happen.  Maybe we should
1004                          * use assertion here?  But why should we rely on
1005                          * hardware to do the correct things?  Even the
1006                          * reference driver (RT61?) provided by Ralink does
1007                          * not provide enough clue that this kind of interrupt
1008                          * is promised to be generated for each packet.  So
1009                          * just print a message and keep going ...
1010                          */
1011                         if_printf(ifp, "WARNING: no rate control information\n");
1012                         continue;
1013                 }
1014                 STAILQ_REMOVE_HEAD(&sc->tx_ratectl, link);
1015
1016                 retrycnt = 7;
1017                 switch (result) {
1018                 case RT2661_TX_SUCCESS:
1019                         retrycnt = RT2661_TX_RETRYCNT(val);
1020                         DPRINTFN(10, ("data frame sent successfully after "
1021                             "%d retries\n", retrycnt));
1022                         break;
1023
1024                 case RT2661_TX_RETRY_FAIL:
1025                         DPRINTFN(9, ("sending data frame failed (too much "
1026                             "retries)\n"));
1027                         break;
1028
1029                 default:
1030                         /* other failure */
1031                         device_printf(sc->sc_dev,
1032                             "sending data frame failed 0x%08x\n", val);
1033                         break;
1034                 }
1035
1036                 res.rc_res_rateidx = rctl->rateidx;
1037                 res.rc_res_tries = retrycnt + 1;
1038                 ieee80211_ratectl_tx_complete(rctl->ni, rctl->len, &res, 1,
1039                         retrycnt, 0, result != RT2661_TX_SUCCESS);
1040
1041                 ieee80211_free_node(rctl->ni);
1042                 rctl->ni = NULL;
1043                 kfree(rctl, M_RT2661);
1044         }
1045 }
1046
1047 static void
1048 rt2661_tx_dma_intr(struct rt2661_softc *sc, struct rt2661_tx_ring *txq)
1049 {
1050         struct rt2661_tx_desc *desc;
1051         struct rt2661_data *data;
1052
1053         bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_POSTREAD);
1054
1055         for (;;) {
1056                 desc = &txq->desc[txq->next];
1057                 data = &txq->data[txq->next];
1058
1059                 if ((le32toh(desc->flags) & RT2661_TX_BUSY) ||
1060                     !(le32toh(desc->flags) & RT2661_TX_VALID))
1061                         break;
1062
1063                 bus_dmamap_sync(txq->data_dmat, data->map,
1064                     BUS_DMASYNC_POSTWRITE);
1065                 bus_dmamap_unload(txq->data_dmat, data->map);
1066                 m_freem(data->m);
1067                 data->m = NULL;
1068
1069                 /* descriptor is no longer valid */
1070                 desc->flags &= ~htole32(RT2661_TX_VALID);
1071
1072                 DPRINTFN(15, ("tx dma done q=%p idx=%u\n", txq, txq->next));
1073
1074                 txq->queued--;
1075                 if (++txq->next >= txq->count)  /* faster than % count */
1076                         txq->next = 0;
1077         }
1078
1079         bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1080
1081         if (txq->queued < txq->count) {
1082                 struct ifnet *ifp = &sc->sc_ic.ic_if;
1083
1084                 sc->sc_tx_timer = 0;
1085                 ifp->if_flags &= ~IFF_OACTIVE;
1086                 rt2661_start(ifp);
1087         }
1088 }
1089
1090 static void
1091 rt2661_rx_intr(struct rt2661_softc *sc)
1092 {
1093         struct ieee80211com *ic = &sc->sc_ic;
1094         struct ifnet *ifp = ic->ic_ifp;
1095         struct rt2661_rx_desc *desc;
1096         struct rt2661_data *data;
1097         bus_addr_t physaddr;
1098         struct ieee80211_frame_min *wh;
1099         struct ieee80211_node *ni;
1100         struct mbuf *mnew, *m;
1101         int error;
1102
1103         bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1104             BUS_DMASYNC_POSTREAD);
1105
1106         for (;;) {
1107                 uint32_t flags;
1108                 int rssi;
1109
1110                 desc = &sc->rxq.desc[sc->rxq.cur];
1111                 data = &sc->rxq.data[sc->rxq.cur];
1112                 flags = le32toh(desc->flags);
1113
1114                 if (flags & RT2661_RX_BUSY)
1115                         break;
1116
1117                 if (flags & RT2661_RX_CRC_ERROR) {
1118                         /*
1119                          * This should not happen since we did not request
1120                          * to receive those frames when we filled TXRX_CSR0.
1121                          */
1122                         DPRINTFN(5, ("CRC error flags 0x%08x\n", flags));
1123                         ifp->if_ierrors++;
1124                         goto skip;
1125                 }
1126
1127                 if (flags & RT2661_RX_CIPHER_MASK) {
1128                         ifp->if_ierrors++;
1129                         goto skip;
1130                 }
1131
1132                 /*
1133                  * Try to allocate a new mbuf for this ring element and load it
1134                  * before processing the current mbuf. If the ring element
1135                  * cannot be loaded, drop the received packet and reuse the old
1136                  * mbuf. In the unlikely case that the old mbuf can't be
1137                  * reloaded either, explicitly panic.
1138                  */
1139                 mnew = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
1140                 if (mnew == NULL) {
1141                         ifp->if_ierrors++;
1142                         goto skip;
1143                 }
1144
1145                 bus_dmamap_sync(sc->rxq.data_dmat, data->map,
1146                     BUS_DMASYNC_POSTREAD);
1147                 bus_dmamap_unload(sc->rxq.data_dmat, data->map);
1148
1149                 error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1150                     mtod(mnew, void *), MCLBYTES, rt2661_dma_map_addr,
1151                     &physaddr, 0);
1152                 if (error != 0) {
1153                         m_freem(mnew);
1154
1155                         /* try to reload the old mbuf */
1156                         error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1157                             mtod(data->m, void *), MCLBYTES,
1158                             rt2661_dma_map_addr, &physaddr, 0);
1159                         if (error != 0) {
1160                                 /* very unlikely that it will fail... */
1161                                 panic("%s: could not load old rx mbuf",
1162                                     device_get_name(sc->sc_dev));
1163                         }
1164                         ifp->if_ierrors++;
1165                         goto skip;
1166                 }
1167
1168                 /*
1169                  * New mbuf successfully loaded, update Rx ring and continue
1170                  * processing.
1171                  */
1172                 m = data->m;
1173                 data->m = mnew;
1174                 desc->physaddr = htole32(physaddr);
1175
1176                 /* finalize mbuf */
1177                 m->m_pkthdr.rcvif = ifp;
1178                 m->m_pkthdr.len = m->m_len = (flags >> 16) & 0xfff;
1179
1180                 rssi = rt2661_get_rssi(sc, desc->rssi);
1181
1182                 wh = mtod(m, struct ieee80211_frame_min *);
1183                 ni = ieee80211_find_rxnode(ic, wh);
1184
1185                 /* Error happened during RSSI conversion. */
1186                 if (rssi < 0)
1187                         rssi = ni->ni_rssi;
1188
1189                 if (sc->sc_drvbpf != NULL) {
1190                         struct rt2661_rx_radiotap_header *tap = &sc->sc_rxtap;
1191                         uint32_t tsf_lo, tsf_hi;
1192
1193                         /* get timestamp (low and high 32 bits) */
1194                         tsf_hi = RAL_READ(sc, RT2661_TXRX_CSR13);
1195                         tsf_lo = RAL_READ(sc, RT2661_TXRX_CSR12);
1196
1197                         tap->wr_tsf =
1198                             htole64(((uint64_t)tsf_hi << 32) | tsf_lo);
1199                         tap->wr_flags = 0;
1200                         tap->wr_rate = rt2661_rxrate(desc);
1201                         tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
1202                         tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
1203                         tap->wr_antsignal = rssi;
1204
1205                         bpf_ptap(sc->sc_drvbpf, m, tap, sc->sc_rxtap_len);
1206                 }
1207
1208                 /* send the frame to the 802.11 layer */
1209                 ieee80211_input(ic, m, ni, rssi, 0);
1210
1211                 /* node is no longer needed */
1212                 ieee80211_free_node(ni);
1213
1214 skip:           desc->flags |= htole32(RT2661_RX_BUSY);
1215
1216                 DPRINTFN(15, ("rx intr idx=%u\n", sc->rxq.cur));
1217
1218                 sc->rxq.cur = (sc->rxq.cur + 1) % RT2661_RX_RING_COUNT;
1219         }
1220
1221         bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1222             BUS_DMASYNC_PREWRITE);
1223 }
1224
1225 /* ARGSUSED */
1226 static void
1227 rt2661_mcu_beacon_expire(struct rt2661_softc *sc)
1228 {
1229         /* do nothing */
1230 }
1231
1232 static void
1233 rt2661_mcu_wakeup(struct rt2661_softc *sc)
1234 {
1235         RAL_WRITE(sc, RT2661_MAC_CSR11, 5 << 16);
1236
1237         RAL_WRITE(sc, RT2661_SOFT_RESET_CSR, 0x7);
1238         RAL_WRITE(sc, RT2661_IO_CNTL_CSR, 0x18);
1239         RAL_WRITE(sc, RT2661_PCI_USEC_CSR, 0x20);
1240
1241         /* send wakeup command to MCU */
1242         rt2661_tx_cmd(sc, RT2661_MCU_CMD_WAKEUP, 0);
1243 }
1244
1245 static void
1246 rt2661_mcu_cmd_intr(struct rt2661_softc *sc)
1247 {
1248         RAL_READ(sc, RT2661_M2H_CMD_DONE_CSR);
1249         RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
1250 }
1251
1252 static void
1253 rt2661_intr(void *arg)
1254 {
1255         struct rt2661_softc *sc = arg;
1256         struct ifnet *ifp = &sc->sc_ic.ic_if;
1257         uint32_t r1, r2;
1258
1259         /* disable MAC and MCU interrupts */
1260         RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffff7f);
1261         RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
1262
1263         /* don't re-enable interrupts if we're shutting down */
1264         if (!(ifp->if_flags & IFF_RUNNING))
1265                 return;
1266
1267         r1 = RAL_READ(sc, RT2661_INT_SOURCE_CSR);
1268         RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, r1);
1269
1270         r2 = RAL_READ(sc, RT2661_MCU_INT_SOURCE_CSR);
1271         RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, r2);
1272
1273         if (r1 & RT2661_MGT_DONE)
1274                 rt2661_tx_dma_intr(sc, &sc->mgtq);
1275
1276         if (r1 & RT2661_RX_DONE)
1277                 rt2661_rx_intr(sc);
1278
1279         if (r1 & RT2661_TX0_DMA_DONE)
1280                 rt2661_tx_dma_intr(sc, &sc->txq[0]);
1281
1282         if (r1 & RT2661_TX1_DMA_DONE)
1283                 rt2661_tx_dma_intr(sc, &sc->txq[1]);
1284
1285         if (r1 & RT2661_TX2_DMA_DONE)
1286                 rt2661_tx_dma_intr(sc, &sc->txq[2]);
1287
1288         if (r1 & RT2661_TX3_DMA_DONE)
1289                 rt2661_tx_dma_intr(sc, &sc->txq[3]);
1290
1291         if (r1 & RT2661_TX_DONE)
1292                 rt2661_tx_intr(sc);
1293
1294         if (r2 & RT2661_MCU_CMD_DONE)
1295                 rt2661_mcu_cmd_intr(sc);
1296
1297         if (r2 & RT2661_MCU_BEACON_EXPIRE)
1298                 rt2661_mcu_beacon_expire(sc);
1299
1300         if (r2 & RT2661_MCU_WAKEUP)
1301                 rt2661_mcu_wakeup(sc);
1302
1303         /* re-enable MAC and MCU interrupts */
1304         RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
1305         RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
1306 }
1307
1308 /* quickly determine if a given rate is CCK or OFDM */
1309 #define RAL_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
1310
1311 #define RAL_ACK_SIZE    (sizeof(struct ieee80211_frame_ack) + IEEE80211_FCS_LEN)
1312 #define RAL_CTS_SIZE    (sizeof(struct ieee80211_frame_cts) + IEEE80211_FCS_LEN)
1313
1314 /*
1315  * This function is only used by the Rx radiotap code. It returns the rate at
1316  * which a given frame was received.
1317  */
1318 static uint8_t
1319 rt2661_rxrate(struct rt2661_rx_desc *desc)
1320 {
1321         if (le32toh(desc->flags) & RT2661_RX_OFDM) {
1322                 /* reverse function of rt2661_plcp_signal */
1323                 switch (desc->rate & 0xf) {
1324                 case 0xb:       return 12;
1325                 case 0xf:       return 18;
1326                 case 0xa:       return 24;
1327                 case 0xe:       return 36;
1328                 case 0x9:       return 48;
1329                 case 0xd:       return 72;
1330                 case 0x8:       return 96;
1331                 case 0xc:       return 108;
1332                 }
1333         } else {
1334                 if (desc->rate == 10)
1335                         return 2;
1336                 if (desc->rate == 20)
1337                         return 4;
1338                 if (desc->rate == 55)
1339                         return 11;
1340                 if (desc->rate == 110)
1341                         return 22;
1342         }
1343         return 2;       /* should not get there */
1344 }
1345
1346 static uint8_t
1347 rt2661_plcp_signal(int rate)
1348 {
1349         switch (rate) {
1350         /* CCK rates (returned values are device-dependent) */
1351         case 2:         return 0x0;
1352         case 4:         return 0x1;
1353         case 11:        return 0x2;
1354         case 22:        return 0x3;
1355
1356         /* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1357         case 12:        return 0xb;
1358         case 18:        return 0xf;
1359         case 24:        return 0xa;
1360         case 36:        return 0xe;
1361         case 48:        return 0x9;
1362         case 72:        return 0xd;
1363         case 96:        return 0x8;
1364         case 108:       return 0xc;
1365
1366         /* unsupported rates (should not get there) */
1367         default:        return 0xff;
1368         }
1369 }
1370
1371 static void
1372 rt2661_setup_tx_desc(struct rt2661_softc *sc, struct rt2661_tx_desc *desc,
1373     uint32_t flags, uint16_t xflags, int len, int rate,
1374     const bus_dma_segment_t *segs, int nsegs, int ac, int ratectl)
1375 {
1376         struct ieee80211com *ic = &sc->sc_ic;
1377         uint16_t plcp_length;
1378         int i, remainder;
1379
1380         desc->flags = htole32(flags);
1381         desc->flags |= htole32(len << 16);
1382         desc->flags |= htole32(RT2661_TX_VALID);
1383
1384         desc->xflags = htole16(xflags);
1385         desc->xflags |= htole16(nsegs << 13);
1386
1387         desc->wme = htole16(
1388             RT2661_QID(ac) |
1389             RT2661_AIFSN(2) |
1390             RT2661_LOGCWMIN(4) |
1391             RT2661_LOGCWMAX(10));
1392
1393         /*
1394          * Remember whether TX rate control information should be gathered.
1395          * This field is driver private data only.  It will be made available
1396          * by the NIC in STA_CSR4 on Tx done interrupts.
1397          */
1398         desc->qid = ratectl;
1399
1400         /* setup PLCP fields */
1401         desc->plcp_signal  = rt2661_plcp_signal(rate);
1402         desc->plcp_service = 4;
1403
1404         len += IEEE80211_CRC_LEN;
1405         if (RAL_RATE_IS_OFDM(rate)) {
1406                 desc->flags |= htole32(RT2661_TX_OFDM);
1407
1408                 plcp_length = len & 0xfff;
1409                 desc->plcp_length_hi = plcp_length >> 6;
1410                 desc->plcp_length_lo = plcp_length & 0x3f;
1411         } else {
1412                 plcp_length = (16 * len + rate - 1) / rate;
1413                 if (rate == 22) {
1414                         remainder = (16 * len) % 22;
1415                         if (remainder != 0 && remainder < 7)
1416                                 desc->plcp_service |= RT2661_PLCP_LENGEXT;
1417                 }
1418                 desc->plcp_length_hi = plcp_length >> 8;
1419                 desc->plcp_length_lo = plcp_length & 0xff;
1420
1421                 if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1422                         desc->plcp_signal |= 0x08;
1423         }
1424
1425         /* RT2x61 supports scatter with up to 5 segments */
1426         for (i = 0; i < nsegs; i++) {
1427                 desc->addr[i] = htole32(segs[i].ds_addr);
1428                 desc->len [i] = htole16(segs[i].ds_len);
1429         }
1430
1431         desc->flags |= htole32(RT2661_TX_BUSY);
1432 }
1433
1434 static int
1435 rt2661_tx_mgt(struct rt2661_softc *sc, struct mbuf *m0,
1436     struct ieee80211_node *ni)
1437 {
1438         struct ieee80211com *ic = &sc->sc_ic;
1439         struct rt2661_tx_desc *desc;
1440         struct rt2661_data *data;
1441         struct ieee80211_frame *wh;
1442         struct rt2661_dmamap map;
1443         uint16_t dur;
1444         uint32_t flags = 0;     /* XXX HWSEQ */
1445         int rate, error;
1446
1447         desc = &sc->mgtq.desc[sc->mgtq.cur];
1448         data = &sc->mgtq.data[sc->mgtq.cur];
1449
1450         /* send mgt frames at the lowest available rate */
1451         rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1452
1453         error = bus_dmamap_load_mbuf(sc->mgtq.data_dmat, data->map, m0,
1454                                      rt2661_dma_map_mbuf, &map, 0);
1455         if (error != 0) {
1456                 device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1457                     error);
1458                 ieee80211_free_node(ni);
1459                 m_freem(m0);
1460                 return error;
1461         }
1462
1463         if (sc->sc_drvbpf != NULL) {
1464                 struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1465
1466                 tap->wt_flags = 0;
1467                 tap->wt_rate = rate;
1468                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1469                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1470
1471                 bpf_ptap(sc->sc_drvbpf, m0, tap, sc->sc_txtap_len);
1472         }
1473
1474         data->m = m0;
1475
1476         wh = mtod(m0, struct ieee80211_frame *);
1477
1478         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1479                 flags |= RT2661_TX_NEED_ACK;
1480
1481                 dur = ieee80211_txtime(ni, RAL_ACK_SIZE, rate, ic->ic_flags) +
1482                       sc->sc_sifs;
1483                 *(uint16_t *)wh->i_dur = htole16(dur);
1484
1485                 /* tell hardware to add timestamp in probe responses */
1486                 if ((wh->i_fc[0] &
1487                     (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1488                     (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1489                         flags |= RT2661_TX_TIMESTAMP;
1490         }
1491
1492         rt2661_setup_tx_desc(sc, desc, flags, 0 /* XXX HWSEQ */,
1493             m0->m_pkthdr.len, rate, map.segs, map.nseg, RT2661_QID_MGT, 0);
1494
1495         bus_dmamap_sync(sc->mgtq.data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1496         bus_dmamap_sync(sc->mgtq.desc_dmat, sc->mgtq.desc_map,
1497             BUS_DMASYNC_PREWRITE);
1498
1499         DPRINTFN(10, ("sending mgt frame len=%u idx=%u rate=%u\n",
1500             m0->m_pkthdr.len, sc->mgtq.cur, rate));
1501
1502         /* kick mgt */
1503         sc->mgtq.queued++;
1504         sc->mgtq.cur = (sc->mgtq.cur + 1) % RT2661_MGT_RING_COUNT;
1505         RAL_WRITE(sc, RT2661_TX_CNTL_CSR, RT2661_KICK_MGT);
1506
1507         ieee80211_free_node(ni);
1508
1509         return 0;
1510 }
1511
1512 /*
1513  * Build a RTS control frame.
1514  */
1515 static struct mbuf *
1516 rt2661_get_rts(struct rt2661_softc *sc, struct ieee80211_frame *wh,
1517     uint16_t dur)
1518 {
1519         struct ieee80211_frame_rts *rts;
1520         struct mbuf *m;
1521
1522         MGETHDR(m, MB_DONTWAIT, MT_DATA);
1523         if (m == NULL) {
1524                 sc->sc_ic.ic_stats.is_tx_nobuf++;
1525                 device_printf(sc->sc_dev, "could not allocate RTS frame\n");
1526                 return NULL;
1527         }
1528
1529         rts = mtod(m, struct ieee80211_frame_rts *);
1530
1531         rts->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_CTL |
1532             IEEE80211_FC0_SUBTYPE_RTS;
1533         rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1534         *(uint16_t *)rts->i_dur = htole16(dur);
1535         IEEE80211_ADDR_COPY(rts->i_ra, wh->i_addr1);
1536         IEEE80211_ADDR_COPY(rts->i_ta, wh->i_addr2);
1537
1538         m->m_pkthdr.len = m->m_len = sizeof (struct ieee80211_frame_rts);
1539
1540         return m;
1541 }
1542
1543 static int
1544 rt2661_tx_data(struct rt2661_softc *sc, struct mbuf *m0,
1545     struct ieee80211_node *ni, int ac)
1546 {
1547         struct ieee80211com *ic = &sc->sc_ic;
1548         struct rt2661_tx_ring *txq = &sc->txq[ac];
1549         struct rt2661_tx_desc *desc;
1550         struct rt2661_data *data;
1551         struct rt2661_tx_ratectl *rctl;
1552         struct ieee80211_frame *wh;
1553         struct ieee80211_key *k;
1554         const struct chanAccParams *cap;
1555         struct mbuf *mnew;
1556         struct rt2661_dmamap map;
1557         uint16_t dur;
1558         uint32_t flags = 0;
1559         int error, rate, ackrate, noack = 0, rateidx;
1560
1561         wh = mtod(m0, struct ieee80211_frame *);
1562         if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
1563                 cap = &ic->ic_wme.wme_chanParams;
1564                 noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
1565         }
1566
1567         if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1568                 k = ieee80211_crypto_encap(ic, ni, m0);
1569                 if (k == NULL) {
1570                         m_freem(m0);
1571                         return ENOBUFS;
1572                 }
1573
1574                 /* packet header may have moved, reset our local pointer */
1575                 wh = mtod(m0, struct ieee80211_frame *);
1576         }
1577
1578         ieee80211_ratectl_findrate(ni, m0->m_pkthdr.len, &rateidx, 1);
1579         rate = IEEE80211_RS_RATE(&ni->ni_rates, rateidx);
1580
1581         ackrate = ieee80211_ack_rate(ni, rate);
1582
1583         /*
1584          * IEEE Std 802.11-1999, pp 82: "A STA shall use an RTS/CTS exchange
1585          * for directed frames only when the length of the MPDU is greater
1586          * than the length threshold indicated by [...]" ic_rtsthreshold.
1587          */
1588         if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1589             m0->m_pkthdr.len > ic->ic_rtsthreshold) {
1590                 struct mbuf *m;
1591                 uint16_t dur;
1592                 int rtsrate;
1593
1594                 rtsrate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1595
1596                 /* XXX: noack (QoS)? */
1597                 dur = ieee80211_txtime(ni, m0->m_pkthdr.len + IEEE80211_FCS_LEN,
1598                                        rate, ic->ic_flags) +
1599                       ieee80211_txtime(ni, RAL_CTS_SIZE, rtsrate, ic->ic_flags)+
1600                       ieee80211_txtime(ni, RAL_ACK_SIZE, ackrate, ic->ic_flags)+
1601                       3 * sc->sc_sifs;
1602
1603                 m = rt2661_get_rts(sc, wh, dur);
1604
1605                 desc = &txq->desc[txq->cur];
1606                 data = &txq->data[txq->cur];
1607
1608                 error = bus_dmamap_load_mbuf(txq->data_dmat, data->map, m,
1609                                              rt2661_dma_map_mbuf, &map, 0);
1610                 if (error != 0) {
1611                         device_printf(sc->sc_dev,
1612                             "could not map mbuf (error %d)\n", error);
1613                         m_freem(m);
1614                         m_freem(m0);
1615                         return error;
1616                 }
1617
1618                 data->m = m;
1619
1620                 rt2661_setup_tx_desc(sc, desc, RT2661_TX_NEED_ACK |
1621                                      RT2661_TX_MORE_FRAG, 0, m->m_pkthdr.len,
1622                                      rtsrate, map.segs, map.nseg, ac, 0);
1623
1624                 bus_dmamap_sync(txq->data_dmat, data->map,
1625                     BUS_DMASYNC_PREWRITE);
1626
1627                 txq->queued++;
1628                 txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1629
1630                 /*
1631                  * IEEE Std 802.11-1999: when an RTS/CTS exchange is used, the
1632                  * asynchronous data frame shall be transmitted after the CTS
1633                  * frame and a SIFS period.
1634                  */
1635                 flags |= RT2661_TX_LONG_RETRY | RT2661_TX_IFS;
1636         }
1637
1638         data = &txq->data[txq->cur];
1639         desc = &txq->desc[txq->cur];
1640
1641         error = bus_dmamap_load_mbuf(txq->data_dmat, data->map, m0,
1642                                      rt2661_dma_map_mbuf, &map, 0);
1643         if (error != 0 && error != EFBIG) {
1644                 device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1645                     error);
1646                 m_freem(m0);
1647                 return error;
1648         }
1649         if (error != 0) {
1650                 mnew = m_defrag(m0, MB_DONTWAIT);
1651                 if (mnew == NULL) {
1652                         device_printf(sc->sc_dev,
1653                             "could not defragment mbuf\n");
1654                         m_freem(m0);
1655                         return ENOBUFS;
1656                 }
1657                 m0 = mnew;
1658
1659                 error = bus_dmamap_load_mbuf(txq->data_dmat, data->map, m0,
1660                                              rt2661_dma_map_mbuf, &map, 0);
1661                 if (error != 0) {
1662                         device_printf(sc->sc_dev,
1663                             "could not map mbuf (error %d)\n", error);
1664                         m_freem(m0);
1665                         return error;
1666                 }
1667
1668                 /* packet header have moved, reset our local pointer */
1669                 wh = mtod(m0, struct ieee80211_frame *);
1670         }
1671
1672         if (sc->sc_drvbpf != NULL) {
1673                 struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1674
1675                 tap->wt_flags = 0;
1676                 tap->wt_rate = rate;
1677                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1678                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1679
1680                 bpf_ptap(sc->sc_drvbpf, m0, tap, sc->sc_txtap_len);
1681         }
1682
1683         data->m = m0;
1684
1685         rctl = kmalloc(sizeof(*rctl), M_RT2661, M_NOWAIT);
1686         if (rctl != NULL) {
1687                 rctl->ni = ni;
1688                 rctl->len = m0->m_pkthdr.len;
1689                 rctl->rateidx = rateidx;
1690                 STAILQ_INSERT_TAIL(&sc->tx_ratectl, rctl, link);
1691         }
1692
1693         if (!noack && !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1694                 flags |= RT2661_TX_NEED_ACK;
1695
1696                 dur = ieee80211_txtime(ni, RAL_ACK_SIZE, ackrate, ic->ic_flags)+
1697                       sc->sc_sifs;
1698                 *(uint16_t *)wh->i_dur = htole16(dur);
1699         }
1700
1701         rt2661_setup_tx_desc(sc, desc, flags, 0, m0->m_pkthdr.len, rate,
1702                              map.segs, map.nseg, ac, rctl != NULL);
1703
1704         bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1705         bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1706
1707         DPRINTFN(10, ("sending data frame len=%u idx=%u rate=%u\n",
1708             m0->m_pkthdr.len, txq->cur, rate));
1709
1710         /* kick Tx */
1711         txq->queued++;
1712         txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1713         RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 1 << ac);
1714
1715         if (rctl == NULL)
1716                 ieee80211_free_node(ni);
1717
1718         return 0;
1719 }
1720
1721 static void
1722 rt2661_start(struct ifnet *ifp)
1723 {
1724         struct rt2661_softc *sc = ifp->if_softc;
1725         struct ieee80211com *ic = &sc->sc_ic;
1726         struct mbuf *m0;
1727         struct ether_header *eh;
1728         struct ieee80211_node *ni;
1729         int ac;
1730
1731         /* prevent management frames from being sent if we're not ready */
1732         if (!(ifp->if_flags & IFF_RUNNING))
1733                 return;
1734
1735         for (;;) {
1736                 IF_POLL(&ic->ic_mgtq, m0);
1737                 if (m0 != NULL) {
1738                         if (sc->mgtq.queued >= RT2661_MGT_RING_COUNT) {
1739                                 ifp->if_flags |= IFF_OACTIVE;
1740                                 break;
1741                         }
1742                         IF_DEQUEUE(&ic->ic_mgtq, m0);
1743
1744                         ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
1745                         m0->m_pkthdr.rcvif = NULL;
1746
1747                         if (ic->ic_rawbpf != NULL)
1748                                 bpf_mtap(ic->ic_rawbpf, m0);
1749
1750                         if (rt2661_tx_mgt(sc, m0, ni) != 0)
1751                                 break;
1752                 } else {
1753                         if (ic->ic_state != IEEE80211_S_RUN)
1754                                 break;
1755
1756                         m0 = ifq_dequeue(&ifp->if_snd, NULL);
1757                         if (m0 == NULL)
1758                                 break;
1759
1760                         if (m0->m_len < sizeof (struct ether_header) &&
1761                             !(m0 = m_pullup(m0, sizeof (struct ether_header))))
1762                                 continue;
1763
1764                         eh = mtod(m0, struct ether_header *);
1765                         ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1766                         if (ni == NULL) {
1767                                 m_freem(m0);
1768                                 ifp->if_oerrors++;
1769                                 continue;
1770                         }
1771
1772                         /* classify mbuf so we can find which tx ring to use */
1773                         if (ieee80211_classify(ic, m0, ni) != 0) {
1774                                 m_freem(m0);
1775                                 ieee80211_free_node(ni);
1776                                 ifp->if_oerrors++;
1777                                 continue;
1778                         }
1779
1780                         /* no QoS encapsulation for EAPOL frames */
1781                         ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
1782                             M_WME_GETAC(m0) : WME_AC_BE;
1783
1784                         if (sc->txq[ac].queued >= RT2661_TX_RING_COUNT - 1) {
1785                                 /* there is no place left in this ring */
1786                                 ifp->if_flags |= IFF_OACTIVE;
1787                                 m_freem(m0);
1788                                 ieee80211_free_node(ni);
1789                                 break;
1790                         }
1791
1792                         BPF_MTAP(ifp, m0);
1793
1794                         m0 = ieee80211_encap(ic, m0, ni);
1795                         if (m0 == NULL) {
1796                                 ieee80211_free_node(ni);
1797                                 ifp->if_oerrors++;
1798                                 continue;
1799                         }
1800
1801                         if (ic->ic_rawbpf != NULL)
1802                                 bpf_mtap(ic->ic_rawbpf, m0);
1803
1804                         if (rt2661_tx_data(sc, m0, ni, ac) != 0) {
1805                                 ieee80211_free_node(ni);
1806                                 ifp->if_oerrors++;
1807                                 break;
1808                         }
1809                 }
1810
1811                 sc->sc_tx_timer = 5;
1812                 ifp->if_timer = 1;
1813         }
1814 }
1815
1816 static void
1817 rt2661_watchdog(struct ifnet *ifp)
1818 {
1819         struct rt2661_softc *sc = ifp->if_softc;
1820         struct ieee80211com *ic = &sc->sc_ic;
1821
1822         ifp->if_timer = 0;
1823
1824         if (sc->sc_tx_timer > 0) {
1825                 if (--sc->sc_tx_timer == 0) {
1826                         device_printf(sc->sc_dev, "device timeout\n");
1827                         rt2661_init(sc);
1828                         ifp->if_oerrors++;
1829                         return;
1830                 }
1831                 ifp->if_timer = 1;
1832         }
1833
1834         ieee80211_watchdog(ic);
1835 }
1836
1837 /*
1838  * This function allows for fast channel switching in monitor mode (used by
1839  * net-mgmt/kismet). In IBSS mode, we must explicitly reset the interface to
1840  * generate a new beacon frame.
1841  */
1842 static int
1843 rt2661_reset(struct ifnet *ifp)
1844 {
1845         struct rt2661_softc *sc = ifp->if_softc;
1846         struct ieee80211com *ic = &sc->sc_ic;
1847
1848         if (ic->ic_opmode != IEEE80211_M_MONITOR)
1849                 return ENETRESET;
1850
1851         rt2661_set_chan(sc, ic->ic_curchan);
1852
1853         return 0;
1854 }
1855
1856 static int
1857 rt2661_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cr)
1858 {
1859         struct rt2661_softc *sc = ifp->if_softc;
1860         struct ieee80211com *ic = &sc->sc_ic;
1861         int error = 0;
1862
1863         switch (cmd) {
1864         case SIOCSIFFLAGS:
1865                 if (ifp->if_flags & IFF_UP) {
1866                         if (ifp->if_flags & IFF_RUNNING)
1867                                 rt2661_update_promisc(sc);
1868                         else
1869                                 rt2661_init(sc);
1870                 } else {
1871                         if (ifp->if_flags & IFF_RUNNING)
1872                                 rt2661_stop(sc);
1873                 }
1874                 break;
1875
1876         default:
1877                 error = ieee80211_ioctl(ic, cmd, data, cr);
1878         }
1879
1880         if (error == ENETRESET) {
1881                 if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1882                     (IFF_UP | IFF_RUNNING) &&
1883                     (ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
1884                         rt2661_init(sc);
1885                 error = 0;
1886         }
1887         return error;
1888 }
1889
1890 static void
1891 rt2661_bbp_write(struct rt2661_softc *sc, uint8_t reg, uint8_t val)
1892 {
1893         uint32_t tmp;
1894         int ntries;
1895
1896         for (ntries = 0; ntries < 100; ntries++) {
1897                 if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
1898                         break;
1899                 DELAY(1);
1900         }
1901         if (ntries == 100) {
1902                 device_printf(sc->sc_dev, "could not write to BBP\n");
1903                 return;
1904         }
1905
1906         tmp = RT2661_BBP_BUSY | (reg & 0x7f) << 8 | val;
1907         RAL_WRITE(sc, RT2661_PHY_CSR3, tmp);
1908
1909         DPRINTFN(15, ("BBP R%u <- 0x%02x\n", reg, val));
1910 }
1911
1912 static uint8_t
1913 rt2661_bbp_read(struct rt2661_softc *sc, uint8_t reg)
1914 {
1915         uint32_t val;
1916         int ntries;
1917
1918         for (ntries = 0; ntries < 100; ntries++) {
1919                 if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
1920                         break;
1921                 DELAY(1);
1922         }
1923         if (ntries == 100) {
1924                 device_printf(sc->sc_dev, "could not read from BBP\n");
1925                 return 0;
1926         }
1927
1928         val = RT2661_BBP_BUSY | RT2661_BBP_READ | reg << 8;
1929         RAL_WRITE(sc, RT2661_PHY_CSR3, val);
1930
1931         for (ntries = 0; ntries < 100; ntries++) {
1932                 val = RAL_READ(sc, RT2661_PHY_CSR3);
1933                 if (!(val & RT2661_BBP_BUSY))
1934                         return val & 0xff;
1935                 DELAY(1);
1936         }
1937
1938         device_printf(sc->sc_dev, "could not read from BBP\n");
1939         return 0;
1940 }
1941
1942 static void
1943 rt2661_rf_write(struct rt2661_softc *sc, uint8_t reg, uint32_t val)
1944 {
1945         uint32_t tmp;
1946         int ntries;
1947
1948         for (ntries = 0; ntries < 100; ntries++) {
1949                 if (!(RAL_READ(sc, RT2661_PHY_CSR4) & RT2661_RF_BUSY))
1950                         break;
1951                 DELAY(1);
1952         }
1953         if (ntries == 100) {
1954                 device_printf(sc->sc_dev, "could not write to RF\n");
1955                 return;
1956         }
1957
1958         tmp = RT2661_RF_BUSY | RT2661_RF_21BIT | (val & 0x1fffff) << 2 |
1959             (reg & 3);
1960         RAL_WRITE(sc, RT2661_PHY_CSR4, tmp);
1961
1962         /* remember last written value in sc */
1963         sc->rf_regs[reg] = val;
1964
1965         DPRINTFN(15, ("RF R[%u] <- 0x%05x\n", reg & 3, val & 0x1fffff));
1966 }
1967
1968 static int
1969 rt2661_tx_cmd(struct rt2661_softc *sc, uint8_t cmd, uint16_t arg)
1970 {
1971         if (RAL_READ(sc, RT2661_H2M_MAILBOX_CSR) & RT2661_H2M_BUSY)
1972                 return EIO;     /* there is already a command pending */
1973
1974         RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR,
1975             RT2661_H2M_BUSY | RT2661_TOKEN_NO_INTR << 16 | arg);
1976
1977         RAL_WRITE(sc, RT2661_HOST_CMD_CSR, RT2661_KICK_CMD | cmd);
1978
1979         return 0;
1980 }
1981
1982 static void
1983 rt2661_select_antenna(struct rt2661_softc *sc)
1984 {
1985         uint8_t bbp4, bbp77;
1986         uint32_t tmp;
1987
1988         bbp4  = rt2661_bbp_read(sc,  4);
1989         bbp77 = rt2661_bbp_read(sc, 77);
1990
1991         /* TBD */
1992
1993         /* make sure Rx is disabled before switching antenna */
1994         tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
1995         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
1996
1997         rt2661_bbp_write(sc,  4, bbp4);
1998         rt2661_bbp_write(sc, 77, bbp77);
1999
2000         /* restore Rx filter */
2001         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2002 }
2003
2004 /*
2005  * Enable multi-rate retries for frames sent at OFDM rates.
2006  * In 802.11b/g mode, allow fallback to CCK rates.
2007  */
2008 static void
2009 rt2661_enable_mrr(struct rt2661_softc *sc)
2010 {
2011         struct ieee80211com *ic = &sc->sc_ic;
2012         uint32_t tmp;
2013
2014         tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
2015
2016         tmp &= ~RT2661_MRR_CCK_FALLBACK;
2017         if (!IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan))
2018                 tmp |= RT2661_MRR_CCK_FALLBACK;
2019         tmp |= RT2661_MRR_ENABLED;
2020         tmp |= RT2661_SRETRY_LIMIT(7) | RT2661_LRETRY_LIMIT(4);
2021
2022         RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
2023 }
2024
2025 static void
2026 rt2661_set_txpreamble(struct rt2661_softc *sc)
2027 {
2028         uint32_t tmp;
2029
2030         tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
2031
2032         tmp &= ~RT2661_SHORT_PREAMBLE;
2033         if (sc->sc_ic.ic_flags & IEEE80211_F_SHPREAMBLE)
2034                 tmp |= RT2661_SHORT_PREAMBLE;
2035
2036         RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
2037 }
2038
2039 static void
2040 rt2661_set_ackrates(struct rt2661_softc *sc, const struct ieee80211_rateset *rs)
2041 {
2042 #define RV(r)   ((r) & IEEE80211_RATE_VAL)
2043         struct ieee80211com *ic = &sc->sc_ic;
2044         uint32_t mask = 0;
2045         uint8_t rate;
2046         int i, j;
2047
2048         for (i = 0; i < rs->rs_nrates; i++) {
2049                 rate = rs->rs_rates[i];
2050
2051                 if (!(rate & IEEE80211_RATE_BASIC))
2052                         continue;
2053
2054                 /*
2055                  * Find h/w rate index.  We know it exists because the rate
2056                  * set has already been negotiated.
2057                  */
2058                 for (j = 0; rt2661_rateset_11g.rs_rates[j] != RV(rate); j++)
2059                         ; /* EMPTY */
2060
2061                 mask |= 1 << j;
2062         }
2063
2064         if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan) &&
2065             ic->ic_curmode != IEEE80211_MODE_11B &&
2066             ieee80211_iserp_rateset(ic, rs)) {
2067                 /*
2068                  * Always set following rates as ACK rates to conform
2069                  * IEEE Std 802.11g-2003 clause 9.6
2070                  *
2071                  * 24Mbits/s    0x100
2072                  * 12Mbits/s    0x040
2073                  *  6Mbits/s    0x010
2074                  */
2075                 mask |= 0x150;
2076         }
2077
2078         RAL_WRITE(sc, RT2661_TXRX_CSR5, mask);
2079
2080         DPRINTF(("Setting ack rate mask to 0x%x\n", mask));
2081 #undef RV
2082 }
2083
2084 /*
2085  * Reprogram MAC/BBP to switch to a new band.  Values taken from the reference
2086  * driver.
2087  */
2088 static void
2089 rt2661_select_band(struct rt2661_softc *sc, struct ieee80211_channel *c)
2090 {
2091         uint8_t bbp17, bbp35, bbp96, bbp97, bbp98, bbp104;
2092         uint32_t tmp;
2093
2094         /* update all BBP registers that depend on the band */
2095         bbp17 = 0x20; bbp96 = 0x48; bbp104 = 0x2c;
2096         bbp35 = 0x50; bbp97 = 0x48; bbp98  = 0x48;
2097         if (IEEE80211_IS_CHAN_5GHZ(c)) {
2098                 bbp17 += 0x08; bbp96 += 0x10; bbp104 += 0x0c;
2099                 bbp35 += 0x10; bbp97 += 0x10; bbp98  += 0x10;
2100         }
2101         if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2102             (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2103                 bbp17 += 0x10; bbp96 += 0x10; bbp104 += 0x10;
2104         }
2105
2106         rt2661_bbp_write(sc,  17, bbp17);
2107         rt2661_bbp_write(sc,  96, bbp96);
2108         rt2661_bbp_write(sc, 104, bbp104);
2109
2110         if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2111             (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2112                 rt2661_bbp_write(sc, 75, 0x80);
2113                 rt2661_bbp_write(sc, 86, 0x80);
2114                 rt2661_bbp_write(sc, 88, 0x80);
2115         }
2116
2117         rt2661_bbp_write(sc, 35, bbp35);
2118         rt2661_bbp_write(sc, 97, bbp97);
2119         rt2661_bbp_write(sc, 98, bbp98);
2120
2121         tmp = RAL_READ(sc, RT2661_PHY_CSR0);
2122         tmp &= ~(RT2661_PA_PE_2GHZ | RT2661_PA_PE_5GHZ);
2123         if (IEEE80211_IS_CHAN_2GHZ(c))
2124                 tmp |= RT2661_PA_PE_2GHZ;
2125         else
2126                 tmp |= RT2661_PA_PE_5GHZ;
2127         RAL_WRITE(sc, RT2661_PHY_CSR0, tmp);
2128 }
2129
2130 static void
2131 rt2661_set_chan(struct rt2661_softc *sc, struct ieee80211_channel *c)
2132 {
2133         struct ieee80211com *ic = &sc->sc_ic;
2134         const struct rfprog *rfprog;
2135         uint8_t bbp3, bbp94 = RT2661_BBPR94_DEFAULT;
2136         int8_t power;
2137         u_int i, chan;
2138
2139         chan = ieee80211_chan2ieee(ic, c);
2140         if (chan == 0 || chan == IEEE80211_CHAN_ANY)
2141                 return;
2142
2143         /* select the appropriate RF settings based on what EEPROM says */
2144         rfprog = (sc->rfprog == 0) ? rt2661_rf5225_1 : rt2661_rf5225_2;
2145
2146         /* find the settings for this channel (we know it exists) */
2147         for (i = 0; rfprog[i].chan != chan; i++);
2148
2149         power = sc->txpow[i];
2150         if (power < 0) {
2151                 bbp94 += power;
2152                 power = 0;
2153         } else if (power > 31) {
2154                 bbp94 += power - 31;
2155                 power = 31;
2156         }
2157
2158         /*
2159          * If we are switching from the 2GHz band to the 5GHz band or
2160          * vice-versa, BBP registers need to be reprogrammed.
2161          */
2162         if (c->ic_flags != sc->sc_curchan->ic_flags) {
2163                 rt2661_select_band(sc, c);
2164                 rt2661_select_antenna(sc);
2165         }
2166         sc->sc_curchan = c;
2167
2168         rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2169         rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2170         rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2171         rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2172
2173         DELAY(200);
2174
2175         rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2176         rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2177         rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7 | 1);
2178         rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2179
2180         DELAY(200);
2181
2182         rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2183         rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2184         rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2185         rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2186
2187         /* enable smart mode for MIMO-capable RFs */
2188         bbp3 = rt2661_bbp_read(sc, 3);
2189
2190         bbp3 &= ~RT2661_SMART_MODE;
2191         if (sc->rf_rev == RT2661_RF_5325 || sc->rf_rev == RT2661_RF_2529)
2192                 bbp3 |= RT2661_SMART_MODE;
2193
2194         rt2661_bbp_write(sc, 3, bbp3);
2195
2196         if (bbp94 != RT2661_BBPR94_DEFAULT)
2197                 rt2661_bbp_write(sc, 94, bbp94);
2198
2199         /* 5GHz radio needs a 1ms delay here */
2200         if (IEEE80211_IS_CHAN_5GHZ(c))
2201                 DELAY(1000);
2202
2203         sc->sc_sifs = IEEE80211_IS_CHAN_5GHZ(c) ? IEEE80211_DUR_OFDM_SIFS
2204                                                 : IEEE80211_DUR_SIFS;
2205 }
2206
2207 static void
2208 rt2661_set_bssid(struct rt2661_softc *sc, const uint8_t *bssid)
2209 {
2210         uint32_t tmp;
2211
2212         tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24;
2213         RAL_WRITE(sc, RT2661_MAC_CSR4, tmp);
2214
2215         tmp = bssid[4] | bssid[5] << 8 | RT2661_ONE_BSSID << 16;
2216         RAL_WRITE(sc, RT2661_MAC_CSR5, tmp);
2217 }
2218
2219 static void
2220 rt2661_set_macaddr(struct rt2661_softc *sc, const uint8_t *addr)
2221 {
2222         uint32_t tmp;
2223
2224         tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24;
2225         RAL_WRITE(sc, RT2661_MAC_CSR2, tmp);
2226
2227         tmp = addr[4] | addr[5] << 8;
2228         RAL_WRITE(sc, RT2661_MAC_CSR3, tmp);
2229 }
2230
2231 static void
2232 rt2661_update_promisc(struct rt2661_softc *sc)
2233 {
2234         struct ifnet *ifp = sc->sc_ic.ic_ifp;
2235         uint32_t tmp;
2236
2237         tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2238
2239         tmp &= ~RT2661_DROP_NOT_TO_ME;
2240         if (!(ifp->if_flags & IFF_PROMISC))
2241                 tmp |= RT2661_DROP_NOT_TO_ME;
2242
2243         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2244
2245         DPRINTF(("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
2246             "entering" : "leaving"));
2247 }
2248
2249 /*
2250  * Update QoS (802.11e) settings for each h/w Tx ring.
2251  */
2252 static int
2253 rt2661_wme_update(struct ieee80211com *ic)
2254 {
2255         struct rt2661_softc *sc = ic->ic_ifp->if_softc;
2256         const struct wmeParams *wmep;
2257
2258         wmep = ic->ic_wme.wme_chanParams.cap_wmeParams;
2259
2260         /* XXX: not sure about shifts. */
2261         /* XXX: the reference driver plays with AC_VI settings too. */
2262
2263         /* update TxOp */
2264         RAL_WRITE(sc, RT2661_AC_TXOP_CSR0,
2265             wmep[WME_AC_BE].wmep_txopLimit << 16 |
2266             wmep[WME_AC_BK].wmep_txopLimit);
2267         RAL_WRITE(sc, RT2661_AC_TXOP_CSR1,
2268             wmep[WME_AC_VI].wmep_txopLimit << 16 |
2269             wmep[WME_AC_VO].wmep_txopLimit);
2270
2271         /* update CWmin */
2272         RAL_WRITE(sc, RT2661_CWMIN_CSR,
2273             wmep[WME_AC_BE].wmep_logcwmin << 12 |
2274             wmep[WME_AC_BK].wmep_logcwmin <<  8 |
2275             wmep[WME_AC_VI].wmep_logcwmin <<  4 |
2276             wmep[WME_AC_VO].wmep_logcwmin);
2277
2278         /* update CWmax */
2279         RAL_WRITE(sc, RT2661_CWMAX_CSR,
2280             wmep[WME_AC_BE].wmep_logcwmax << 12 |
2281             wmep[WME_AC_BK].wmep_logcwmax <<  8 |
2282             wmep[WME_AC_VI].wmep_logcwmax <<  4 |
2283             wmep[WME_AC_VO].wmep_logcwmax);
2284
2285         /* update Aifsn */
2286         RAL_WRITE(sc, RT2661_AIFSN_CSR,
2287             wmep[WME_AC_BE].wmep_aifsn << 12 |
2288             wmep[WME_AC_BK].wmep_aifsn <<  8 |
2289             wmep[WME_AC_VI].wmep_aifsn <<  4 |
2290             wmep[WME_AC_VO].wmep_aifsn);
2291
2292         return 0;
2293 }
2294
2295 static void
2296 rt2661_update_slot(struct ifnet *ifp)
2297 {
2298         struct rt2661_softc *sc = ifp->if_softc;
2299         struct ieee80211com *ic = &sc->sc_ic;
2300         uint8_t slottime;
2301         uint32_t tmp;
2302
2303         slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
2304
2305         tmp = RAL_READ(sc, RT2661_MAC_CSR9);
2306         tmp = (tmp & ~0xff) | slottime;
2307         RAL_WRITE(sc, RT2661_MAC_CSR9, tmp);
2308 }
2309
2310 static const char *
2311 rt2661_get_rf(int rev)
2312 {
2313         switch (rev) {
2314         case RT2661_RF_5225:    return "RT5225";
2315         case RT2661_RF_5325:    return "RT5325 (MIMO XR)";
2316         case RT2661_RF_2527:    return "RT2527";
2317         case RT2661_RF_2529:    return "RT2529 (MIMO XR)";
2318         default:                return "unknown";
2319         }
2320 }
2321
2322 static void
2323 rt2661_read_config(struct rt2661_softc *sc)
2324 {
2325         struct ieee80211com *ic = &sc->sc_ic;
2326         uint16_t val;
2327         int i, start_chan;
2328
2329         /* read MAC address */
2330         val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC01);
2331         ic->ic_myaddr[0] = val & 0xff;
2332         ic->ic_myaddr[1] = val >> 8;
2333
2334         val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC23);
2335         ic->ic_myaddr[2] = val & 0xff;
2336         ic->ic_myaddr[3] = val >> 8;
2337
2338         val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC45);
2339         ic->ic_myaddr[4] = val & 0xff;
2340         ic->ic_myaddr[5] = val >> 8;
2341
2342         val = rt2661_eeprom_read(sc, RT2661_EEPROM_ANTENNA);
2343         /* XXX: test if different from 0xffff? */
2344         sc->rf_rev   = (val >> 11) & 0x1f;
2345         sc->hw_radio = (val >> 10) & 0x1;
2346         sc->rx_ant   = (val >> 4)  & 0x3;
2347         sc->tx_ant   = (val >> 2)  & 0x3;
2348         sc->nb_ant   = val & 0x3;
2349
2350         DPRINTF(("RF revision=%d\n", sc->rf_rev));
2351
2352         val = rt2661_eeprom_read(sc, RT2661_EEPROM_CONFIG2);
2353         sc->ext_5ghz_lna = (val >> 6) & 0x1;
2354         sc->ext_2ghz_lna = (val >> 4) & 0x1;
2355
2356         DPRINTF(("External 2GHz LNA=%d\nExternal 5GHz LNA=%d\n",
2357             sc->ext_2ghz_lna, sc->ext_5ghz_lna));
2358
2359         val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_2GHZ_OFFSET);
2360         if ((val & 0xff) != 0xff)
2361                 sc->rssi_2ghz_corr = (int8_t)(val & 0xff);      /* signed */
2362
2363         /* Only [-10, 10] is valid */
2364         if (sc->rssi_2ghz_corr < -10 || sc->rssi_2ghz_corr > 10)
2365                 sc->rssi_2ghz_corr = 0;
2366
2367         val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_5GHZ_OFFSET);
2368         if ((val & 0xff) != 0xff)
2369                 sc->rssi_5ghz_corr = (int8_t)(val & 0xff);      /* signed */
2370
2371         /* Only [-10, 10] is valid */
2372         if (sc->rssi_5ghz_corr < -10 || sc->rssi_5ghz_corr > 10)
2373                 sc->rssi_5ghz_corr = 0;
2374
2375         /* adjust RSSI correction for external low-noise amplifier */
2376         if (sc->ext_2ghz_lna)
2377                 sc->rssi_2ghz_corr -= 14;
2378         if (sc->ext_5ghz_lna)
2379                 sc->rssi_5ghz_corr -= 14;
2380
2381         DPRINTF(("RSSI 2GHz corr=%d\nRSSI 5GHz corr=%d\n",
2382             sc->rssi_2ghz_corr, sc->rssi_5ghz_corr));
2383
2384         val = rt2661_eeprom_read(sc, RT2661_EEPROM_FREQ_OFFSET);
2385         if ((val >> 8) != 0xff)
2386                 sc->rfprog = (val >> 8) & 0x3;
2387         if ((val & 0xff) != 0xff)
2388                 sc->rffreq = val & 0xff;
2389
2390         DPRINTF(("RF prog=%d\nRF freq=%d\n", sc->rfprog, sc->rffreq));
2391
2392 #define NCHAN_2GHZ      14
2393 #define NCHAN_5GHZ      24
2394         /*
2395          * Read channel TX power
2396          */
2397         start_chan = 0;
2398         rt2661_read_txpower_config(sc, RT2661_EEPROM_TXPOWER_2GHZ,
2399                                    NCHAN_2GHZ, &start_chan);
2400         rt2661_read_txpower_config(sc, RT2661_EEPROM_TXPOWER_5GHZ,
2401                                    NCHAN_5GHZ, &start_chan);
2402 #undef NCHAN_2GHZ
2403 #undef NCHAN_5GHZ
2404
2405         /* read vendor-specific BBP values */
2406         for (i = 0; i < 16; i++) {
2407                 val = rt2661_eeprom_read(sc, RT2661_EEPROM_BBP_BASE + i);
2408                 if (val == 0 || val == 0xffff)
2409                         continue;       /* skip invalid entries */
2410                 sc->bbp_prom[i].reg = val >> 8;
2411                 sc->bbp_prom[i].val = val & 0xff;
2412                 DPRINTF(("BBP R%d=%02x\n", sc->bbp_prom[i].reg,
2413                     sc->bbp_prom[i].val));
2414         }
2415
2416         val = rt2661_eeprom_read(sc, RT2661_EEPROM_LED_OFFSET);
2417         DPRINTF(("LED %02x\n", val));
2418         if (val == 0xffff) {
2419                 sc->mcu_led = RT2661_MCU_LED_DEFAULT;
2420         } else {
2421 #define N(arr)  (int)(sizeof(arr) / sizeof(arr[0]))
2422
2423                 for (i = 0; i < N(led_ee2mcu); ++i) {
2424                         if (val & led_ee2mcu[i].ee_bit)
2425                                 sc->mcu_led |= led_ee2mcu[i].mcu_bit;
2426                 }
2427
2428 #undef N
2429
2430                 sc->mcu_led |= ((val >> RT2661_EE_LED_MODE_SHIFT) &
2431                                 RT2661_EE_LED_MODE_MASK);
2432         }
2433 }
2434
2435 static int
2436 rt2661_bbp_init(struct rt2661_softc *sc)
2437 {
2438 #define N(a)    (sizeof (a) / sizeof ((a)[0]))
2439         int i, ntries;
2440         uint8_t val;
2441
2442         /* wait for BBP to be ready */
2443         for (ntries = 0; ntries < 100; ntries++) {
2444                 val = rt2661_bbp_read(sc, 0);
2445                 if (val != 0 && val != 0xff)
2446                         break;
2447                 DELAY(100);
2448         }
2449         if (ntries == 100) {
2450                 device_printf(sc->sc_dev, "timeout waiting for BBP\n");
2451                 return EIO;
2452         }
2453
2454         /* initialize BBP registers to default values */
2455         for (i = 0; i < N(rt2661_def_bbp); i++) {
2456                 rt2661_bbp_write(sc, rt2661_def_bbp[i].reg,
2457                     rt2661_def_bbp[i].val);
2458         }
2459
2460         /* write vendor-specific BBP values (from EEPROM) */
2461         for (i = 0; i < 16; i++) {
2462                 if (sc->bbp_prom[i].reg == 0)
2463                         continue;
2464                 rt2661_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2465         }
2466
2467         return 0;
2468 #undef N
2469 }
2470
2471 static void
2472 rt2661_init(void *priv)
2473 {
2474 #define N(a)    (sizeof (a) / sizeof ((a)[0]))
2475         struct rt2661_softc *sc = priv;
2476         struct ieee80211com *ic = &sc->sc_ic;
2477         struct ifnet *ifp = ic->ic_ifp;
2478         uint32_t tmp, sta[3];
2479         int i, ntries;
2480
2481         rt2661_stop(sc);
2482
2483         /* initialize Tx rings */
2484         RAL_WRITE(sc, RT2661_AC1_BASE_CSR, sc->txq[1].physaddr);
2485         RAL_WRITE(sc, RT2661_AC0_BASE_CSR, sc->txq[0].physaddr);
2486         RAL_WRITE(sc, RT2661_AC2_BASE_CSR, sc->txq[2].physaddr);
2487         RAL_WRITE(sc, RT2661_AC3_BASE_CSR, sc->txq[3].physaddr);
2488
2489         /* initialize Mgt ring */
2490         RAL_WRITE(sc, RT2661_MGT_BASE_CSR, sc->mgtq.physaddr);
2491
2492         /* initialize Rx ring */
2493         RAL_WRITE(sc, RT2661_RX_BASE_CSR, sc->rxq.physaddr);
2494
2495         /* initialize Tx rings sizes */
2496         RAL_WRITE(sc, RT2661_TX_RING_CSR0,
2497             RT2661_TX_RING_COUNT << 24 |
2498             RT2661_TX_RING_COUNT << 16 |
2499             RT2661_TX_RING_COUNT <<  8 |
2500             RT2661_TX_RING_COUNT);
2501
2502         RAL_WRITE(sc, RT2661_TX_RING_CSR1,
2503             RT2661_TX_DESC_WSIZE << 16 |
2504             RT2661_TX_RING_COUNT <<  8 |        /* XXX: HCCA ring unused */
2505             RT2661_MGT_RING_COUNT);
2506
2507         /* initialize Rx rings */
2508         RAL_WRITE(sc, RT2661_RX_RING_CSR,
2509             RT2661_RX_DESC_BACK  << 16 |
2510             RT2661_RX_DESC_WSIZE <<  8 |
2511             RT2661_RX_RING_COUNT);
2512
2513         /* XXX: some magic here */
2514         RAL_WRITE(sc, RT2661_TX_DMA_DST_CSR, 0xaa);
2515
2516         /* load base addresses of all 5 Tx rings (4 data + 1 mgt) */
2517         RAL_WRITE(sc, RT2661_LOAD_TX_RING_CSR, 0x1f);
2518
2519         /* load base address of Rx ring */
2520         RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 2);
2521
2522         /* initialize MAC registers to default values */
2523         for (i = 0; i < N(rt2661_def_mac); i++)
2524                 RAL_WRITE(sc, rt2661_def_mac[i].reg, rt2661_def_mac[i].val);
2525
2526         IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2527         rt2661_set_macaddr(sc, ic->ic_myaddr);
2528
2529         /* set host ready */
2530         RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2531         RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2532
2533         /* wait for BBP/RF to wakeup */
2534         for (ntries = 0; ntries < 1000; ntries++) {
2535                 if (RAL_READ(sc, RT2661_MAC_CSR12) & 8)
2536                         break;
2537                 DELAY(1000);
2538         }
2539         if (ntries == 1000) {
2540                 kprintf("timeout waiting for BBP/RF to wakeup\n");
2541                 rt2661_stop(sc);
2542                 return;
2543         }
2544
2545         if (rt2661_bbp_init(sc) != 0) {
2546                 rt2661_stop(sc);
2547                 return;
2548         }
2549
2550         /* select default channel */
2551         sc->sc_curchan = ic->ic_curchan;
2552         rt2661_select_band(sc, sc->sc_curchan);
2553         rt2661_select_antenna(sc);
2554         rt2661_set_chan(sc, sc->sc_curchan);
2555
2556         /* update Rx filter */
2557         tmp = RAL_READ(sc, RT2661_TXRX_CSR0) & 0xffff;
2558
2559         tmp |= RT2661_DROP_PHY_ERROR | RT2661_DROP_CRC_ERROR;
2560         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2561                 tmp |= RT2661_DROP_CTL | RT2661_DROP_VER_ERROR |
2562                        RT2661_DROP_ACKCTS;
2563                 if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2564                         tmp |= RT2661_DROP_TODS;
2565                 if (!(ifp->if_flags & IFF_PROMISC))
2566                         tmp |= RT2661_DROP_NOT_TO_ME;
2567         }
2568
2569         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2570
2571         /* clear STA registers */
2572         RAL_READ_REGION_4(sc, RT2661_STA_CSR0, sta, N(sta));
2573
2574         /* initialize ASIC */
2575         RAL_WRITE(sc, RT2661_MAC_CSR1, 4);
2576
2577         /* clear any pending interrupt */
2578         RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2579
2580         /* enable interrupts */
2581         RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
2582         RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
2583
2584         /* kick Rx */
2585         RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 1);
2586
2587         ifp->if_flags &= ~IFF_OACTIVE;
2588         ifp->if_flags |= IFF_RUNNING;
2589
2590         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2591                 if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
2592                         ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2593         } else
2594                 ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2595 #undef N
2596 }
2597
2598 void
2599 rt2661_stop(void *priv)
2600 {
2601         struct rt2661_softc *sc = priv;
2602         struct ieee80211com *ic = &sc->sc_ic;
2603         struct ifnet *ifp = ic->ic_ifp;
2604         struct rt2661_tx_ratectl *rctl;
2605         uint32_t tmp;
2606
2607         ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2608
2609         sc->sc_tx_timer = 0;
2610         ifp->if_timer = 0;
2611         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2612
2613         /* abort Tx (for all 5 Tx rings) */
2614         RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 0x1f << 16);
2615
2616         /* disable Rx (value remains after reset!) */
2617         tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2618         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2619
2620         /* reset ASIC */
2621         RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2622         RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2623
2624         /* disable interrupts */
2625         RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffffff);
2626         RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
2627
2628         /* clear any pending interrupt */
2629         RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2630         RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, 0xffffffff);
2631
2632         while ((rctl = STAILQ_FIRST(&sc->tx_ratectl)) != NULL) {
2633                 STAILQ_REMOVE_HEAD(&sc->tx_ratectl, link);
2634                 ieee80211_free_node(rctl->ni);
2635                 rctl->ni = NULL;
2636                 kfree(rctl, M_RT2661);
2637         }
2638
2639         /* reset Tx and Rx rings */
2640         rt2661_reset_tx_ring(sc, &sc->txq[0]);
2641         rt2661_reset_tx_ring(sc, &sc->txq[1]);
2642         rt2661_reset_tx_ring(sc, &sc->txq[2]);
2643         rt2661_reset_tx_ring(sc, &sc->txq[3]);
2644         rt2661_reset_tx_ring(sc, &sc->mgtq);
2645         rt2661_reset_rx_ring(sc, &sc->rxq);
2646 }
2647
2648 static int
2649 rt2661_load_microcode(struct rt2661_softc *sc, const uint8_t *ucode, int size)
2650 {
2651         int ntries;
2652
2653         /* reset 8051 */
2654         RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2655
2656         /* cancel any pending Host to MCU command */
2657         RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR, 0);
2658         RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
2659         RAL_WRITE(sc, RT2661_HOST_CMD_CSR, 0);
2660
2661         /* write 8051's microcode */
2662         RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET | RT2661_MCU_SEL);
2663         RAL_WRITE_REGION_1(sc, RT2661_MCU_CODE_BASE, ucode, size);
2664         RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2665
2666         /* kick 8051's ass */
2667         RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, 0);
2668
2669         /* wait for 8051 to initialize */
2670         for (ntries = 0; ntries < 500; ntries++) {
2671                 if (RAL_READ(sc, RT2661_MCU_CNTL_CSR) & RT2661_MCU_READY)
2672                         break;
2673                 DELAY(100);
2674         }
2675         if (ntries == 500) {
2676                 kprintf("timeout waiting for MCU to initialize\n");
2677                 return EIO;
2678         }
2679         return 0;
2680 }
2681
2682 #ifdef notyet
2683 /*
2684  * Dynamically tune Rx sensitivity (BBP register 17) based on average RSSI and
2685  * false CCA count.  This function is called periodically (every seconds) when
2686  * in the RUN state.  Values taken from the reference driver.
2687  */
2688 static void
2689 rt2661_rx_tune(struct rt2661_softc *sc)
2690 {
2691         uint8_t bbp17;
2692         uint16_t cca;
2693         int lo, hi, dbm;
2694
2695         /*
2696          * Tuning range depends on operating band and on the presence of an
2697          * external low-noise amplifier.
2698          */
2699         lo = 0x20;
2700         if (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan))
2701                 lo += 0x08;
2702         if ((IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan) && sc->ext_2ghz_lna) ||
2703             (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan) && sc->ext_5ghz_lna))
2704                 lo += 0x10;
2705         hi = lo + 0x20;
2706
2707         /* retrieve false CCA count since last call (clear on read) */
2708         cca = RAL_READ(sc, RT2661_STA_CSR1) & 0xffff;
2709
2710         if (dbm >= -35) {
2711                 bbp17 = 0x60;
2712         } else if (dbm >= -58) {
2713                 bbp17 = hi;
2714         } else if (dbm >= -66) {
2715                 bbp17 = lo + 0x10;
2716         } else if (dbm >= -74) {
2717                 bbp17 = lo + 0x08;
2718         } else {
2719                 /* RSSI < -74dBm, tune using false CCA count */
2720
2721                 bbp17 = sc->bbp17; /* current value */
2722
2723                 hi -= 2 * (-74 - dbm);
2724                 if (hi < lo)
2725                         hi = lo;
2726
2727                 if (bbp17 > hi) {
2728                         bbp17 = hi;
2729
2730                 } else if (cca > 512) {
2731                         if (++bbp17 > hi)
2732                                 bbp17 = hi;
2733                 } else if (cca < 100) {
2734                         if (--bbp17 < lo)
2735                                 bbp17 = lo;
2736                 }
2737         }
2738
2739         if (bbp17 != sc->bbp17) {
2740                 rt2661_bbp_write(sc, 17, bbp17);
2741                 sc->bbp17 = bbp17;
2742         }
2743 }
2744
2745 /*
2746  * Enter/Leave radar detection mode.
2747  * This is for 802.11h additional regulatory domains.
2748  */
2749 static void
2750 rt2661_radar_start(struct rt2661_softc *sc)
2751 {
2752         uint32_t tmp;
2753
2754         /* disable Rx */
2755         tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2756         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2757
2758         rt2661_bbp_write(sc, 82, 0x20);
2759         rt2661_bbp_write(sc, 83, 0x00);
2760         rt2661_bbp_write(sc, 84, 0x40);
2761
2762         /* save current BBP registers values */
2763         sc->bbp18 = rt2661_bbp_read(sc, 18);
2764         sc->bbp21 = rt2661_bbp_read(sc, 21);
2765         sc->bbp22 = rt2661_bbp_read(sc, 22);
2766         sc->bbp16 = rt2661_bbp_read(sc, 16);
2767         sc->bbp17 = rt2661_bbp_read(sc, 17);
2768         sc->bbp64 = rt2661_bbp_read(sc, 64);
2769
2770         rt2661_bbp_write(sc, 18, 0xff);
2771         rt2661_bbp_write(sc, 21, 0x3f);
2772         rt2661_bbp_write(sc, 22, 0x3f);
2773         rt2661_bbp_write(sc, 16, 0xbd);
2774         rt2661_bbp_write(sc, 17, sc->ext_5ghz_lna ? 0x44 : 0x34);
2775         rt2661_bbp_write(sc, 64, 0x21);
2776
2777         /* restore Rx filter */
2778         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2779 }
2780
2781 static int
2782 rt2661_radar_stop(struct rt2661_softc *sc)
2783 {
2784         uint8_t bbp66;
2785
2786         /* read radar detection result */
2787         bbp66 = rt2661_bbp_read(sc, 66);
2788
2789         /* restore BBP registers values */
2790         rt2661_bbp_write(sc, 16, sc->bbp16);
2791         rt2661_bbp_write(sc, 17, sc->bbp17);
2792         rt2661_bbp_write(sc, 18, sc->bbp18);
2793         rt2661_bbp_write(sc, 21, sc->bbp21);
2794         rt2661_bbp_write(sc, 22, sc->bbp22);
2795         rt2661_bbp_write(sc, 64, sc->bbp64);
2796
2797         return bbp66 == 1;
2798 }
2799 #endif
2800
2801 static int
2802 rt2661_prepare_beacon(struct rt2661_softc *sc)
2803 {
2804         struct ieee80211com *ic = &sc->sc_ic;
2805         struct ieee80211_beacon_offsets bo;
2806         struct rt2661_tx_desc desc;
2807         struct mbuf *m0;
2808         int rate;
2809
2810         m0 = ieee80211_beacon_alloc(ic, ic->ic_bss, &bo);
2811         if (m0 == NULL) {
2812                 device_printf(sc->sc_dev, "could not allocate beacon frame\n");
2813                 return ENOBUFS;
2814         }
2815
2816         /* send beacons at the lowest available rate */
2817         rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan) ? 12 : 2;
2818
2819         rt2661_setup_tx_desc(sc, &desc, RT2661_TX_TIMESTAMP, RT2661_TX_HWSEQ,
2820             m0->m_pkthdr.len, rate, NULL, 0, RT2661_QID_MGT, 0);
2821
2822         /* copy the first 24 bytes of Tx descriptor into NIC memory */
2823         RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0, (uint8_t *)&desc, 24);
2824
2825         /* copy beacon header and payload into NIC memory */
2826         RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0 + 24,
2827             mtod(m0, uint8_t *), m0->m_pkthdr.len);
2828
2829         m_freem(m0);
2830         return 0;
2831 }
2832
2833 /*
2834  * Enable TSF synchronization and tell h/w to start sending beacons for IBSS
2835  * and HostAP operating modes.
2836  */
2837 static void
2838 rt2661_enable_tsf_sync(struct rt2661_softc *sc)
2839 {
2840         struct ieee80211com *ic = &sc->sc_ic;
2841         uint32_t tmp;
2842
2843         if (ic->ic_opmode != IEEE80211_M_STA) {
2844                 /*
2845                  * Change default 16ms TBTT adjustment to 8ms.
2846                  * Must be done before enabling beacon generation.
2847                  */
2848                 RAL_WRITE(sc, RT2661_TXRX_CSR10, 1 << 12 | 8);
2849         }
2850
2851         tmp = RAL_READ(sc, RT2661_TXRX_CSR9) & 0xff000000;
2852
2853         /* set beacon interval (in 1/16ms unit) */
2854         tmp |= ic->ic_bss->ni_intval * 16;
2855
2856         tmp |= RT2661_TSF_TICKING | RT2661_ENABLE_TBTT;
2857         if (ic->ic_opmode == IEEE80211_M_STA)
2858                 tmp |= RT2661_TSF_MODE(1);
2859         else
2860                 tmp |= RT2661_TSF_MODE(2) | RT2661_GENERATE_BEACON;
2861
2862         RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp);
2863 }
2864
2865 /*
2866  * Retrieve the "Received Signal Strength Indicator" from the raw values
2867  * contained in Rx descriptors.  The computation depends on which band the
2868  * frame was received.  Correction values taken from the reference driver.
2869  */
2870 static int
2871 rt2661_get_rssi(struct rt2661_softc *sc, uint8_t raw)
2872 {
2873         int lna, agc, rssi;
2874
2875         lna = (raw >> 5) & 0x3;
2876         agc = raw & 0x1f;
2877
2878         if (lna == 0) {
2879                 /*
2880                  * No RSSI mapping
2881                  *
2882                  * NB: Since RSSI is relative to noise floor, -1 is
2883                  *     adequate for caller to know error happened.
2884                  */
2885                 return -1;
2886         }
2887
2888         rssi = (2 * agc) - RT2661_NOISE_FLOOR;
2889
2890         if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan)) {
2891                 rssi += sc->rssi_2ghz_corr;
2892
2893                 if (lna == 1)
2894                         rssi -= 64;
2895                 else if (lna == 2)
2896                         rssi -= 74;
2897                 else if (lna == 3)
2898                         rssi -= 90;
2899         } else {
2900                 rssi += sc->rssi_5ghz_corr;
2901
2902                 if (lna == 1)
2903                         rssi -= 64;
2904                 else if (lna == 2)
2905                         rssi -= 86;
2906                 else if (lna == 3)
2907                         rssi -= 100;
2908         }
2909         return rssi;
2910 }
2911
2912 static void
2913 rt2661_dma_map_mbuf(void *arg, bus_dma_segment_t *seg, int nseg,
2914                     bus_size_t map_size __unused, int error)
2915 {
2916         struct rt2661_dmamap *map = arg;
2917
2918         if (error)
2919                 return;
2920
2921         KASSERT(nseg <= RT2661_MAX_SCATTER, ("too many DMA segments"));
2922
2923         bcopy(seg, map->segs, nseg * sizeof(bus_dma_segment_t));
2924         map->nseg = nseg;
2925 }
2926
2927 static void
2928 rt2661_led_newstate(struct rt2661_softc *sc, enum ieee80211_state nstate)
2929 {
2930         struct ieee80211com *ic = &sc->sc_ic;
2931         uint32_t off, on;
2932         uint32_t mail = sc->mcu_led;
2933
2934         if (RAL_READ(sc, RT2661_H2M_MAILBOX_CSR) & RT2661_H2M_BUSY) {
2935                 DPRINTF(("%s failed\n", __func__));
2936                 return;
2937         }
2938
2939         switch (nstate) {
2940         case IEEE80211_S_INIT:
2941                 mail &= ~(RT2661_MCU_LED_LINKA | RT2661_MCU_LED_LINKG |
2942                           RT2661_MCU_LED_RF);
2943                 break;
2944         default:
2945                 if (ic->ic_curchan == NULL)
2946                         return;
2947
2948                 on = RT2661_MCU_LED_LINKG;
2949                 off = RT2661_MCU_LED_LINKA;
2950                 if (IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan)) {
2951                         on = RT2661_MCU_LED_LINKA;
2952                         off = RT2661_MCU_LED_LINKG;
2953                 }
2954
2955                 mail |= RT2661_MCU_LED_RF | on;
2956                 mail &= ~off;
2957                 break;
2958         }
2959
2960         RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR,
2961                   RT2661_H2M_BUSY | RT2661_TOKEN_NO_INTR << 16 | mail);
2962         RAL_WRITE(sc, RT2661_HOST_CMD_CSR, RT2661_KICK_CMD | RT2661_MCU_SET_LED);
2963 }
2964
2965 static void
2966 rt2661_read_txpower_config(struct rt2661_softc *sc, uint8_t txpwr_ofs,
2967                            int nchan, int *start_chan0)
2968 {
2969         int i, loop_max;
2970         int start_chan = *start_chan0;
2971
2972         KASSERT(nchan % 2 == 0, ("number of channels %d is not even\n", nchan));
2973         KASSERT(start_chan + nchan <= RT2661_NCHAN_MAX, ("too many channels"));
2974
2975         loop_max = nchan / 2;
2976
2977         for (i = 0; i < loop_max; i++) {
2978                 int chan_idx, j;
2979                 uint16_t val;
2980
2981                 val = rt2661_eeprom_read(sc, txpwr_ofs + i);
2982                 chan_idx = i * 2 + start_chan;
2983
2984                 for (j = 0; j < 2; ++j) {
2985                         int8_t tx_power;        /* signed */
2986
2987                         tx_power = (int8_t)((val >> (8 * j)) & 0xff);
2988                         if (tx_power > RT2661_TXPOWER_MAX)
2989                                 tx_power = RT2661_TXPOWER_DEFAULT;
2990
2991                         sc->txpow[chan_idx] = tx_power;
2992                         DPRINTF(("Channel=%d Tx power=%d\n",
2993                             rt2661_rf5225_1[chan_idx].chan, sc->txpow[chan_idx]));
2994
2995                         ++chan_idx;
2996                 }
2997         }
2998         *start_chan0 += nchan;
2999 }