Turn off Sample TX rate control algorithm support for 2661d BBP. Due to
[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.19 2007/04/22 11:44:56 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                 int rssi;
1108
1109                 desc = &sc->rxq.desc[sc->rxq.cur];
1110                 data = &sc->rxq.data[sc->rxq.cur];
1111
1112                 if (le32toh(desc->flags) & RT2661_RX_BUSY)
1113                         break;
1114
1115                 if ((le32toh(desc->flags) & RT2661_RX_PHY_ERROR) ||
1116                     (le32toh(desc->flags) & RT2661_RX_CRC_ERROR)) {
1117                         /*
1118                          * This should not happen since we did not request
1119                          * to receive those frames when we filled TXRX_CSR0.
1120                          */
1121                         DPRINTFN(5, ("PHY or CRC error flags 0x%08x\n",
1122                             le32toh(desc->flags)));
1123                         ifp->if_ierrors++;
1124                         goto skip;
1125                 }
1126
1127                 if ((le32toh(desc->flags) & RT2661_RX_CIPHER_MASK) != 0) {
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 =
1179                     (le32toh(desc->flags) >> 16) & 0xfff;
1180
1181                 rssi = rt2661_get_rssi(sc, desc->rssi);
1182
1183                 wh = mtod(m, struct ieee80211_frame_min *);
1184                 ni = ieee80211_find_rxnode(ic, wh);
1185
1186                 /* Error happened during RSSI conversion. */
1187                 if (rssi < 0)
1188                         rssi = ni->ni_rssi;
1189
1190                 if (sc->sc_drvbpf != NULL) {
1191                         struct rt2661_rx_radiotap_header *tap = &sc->sc_rxtap;
1192                         uint32_t tsf_lo, tsf_hi;
1193
1194                         /* get timestamp (low and high 32 bits) */
1195                         tsf_hi = RAL_READ(sc, RT2661_TXRX_CSR13);
1196                         tsf_lo = RAL_READ(sc, RT2661_TXRX_CSR12);
1197
1198                         tap->wr_tsf =
1199                             htole64(((uint64_t)tsf_hi << 32) | tsf_lo);
1200                         tap->wr_flags = 0;
1201                         tap->wr_rate = rt2661_rxrate(desc);
1202                         tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
1203                         tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
1204                         tap->wr_antsignal = rssi;
1205
1206                         bpf_ptap(sc->sc_drvbpf, m, tap, sc->sc_rxtap_len);
1207                 }
1208
1209                 /* send the frame to the 802.11 layer */
1210                 ieee80211_input(ic, m, ni, rssi, 0);
1211
1212                 /* node is no longer needed */
1213                 ieee80211_free_node(ni);
1214
1215 skip:           desc->flags |= htole32(RT2661_RX_BUSY);
1216
1217                 DPRINTFN(15, ("rx intr idx=%u\n", sc->rxq.cur));
1218
1219                 sc->rxq.cur = (sc->rxq.cur + 1) % RT2661_RX_RING_COUNT;
1220         }
1221
1222         bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1223             BUS_DMASYNC_PREWRITE);
1224 }
1225
1226 /* ARGSUSED */
1227 static void
1228 rt2661_mcu_beacon_expire(struct rt2661_softc *sc)
1229 {
1230         /* do nothing */
1231 }
1232
1233 static void
1234 rt2661_mcu_wakeup(struct rt2661_softc *sc)
1235 {
1236         RAL_WRITE(sc, RT2661_MAC_CSR11, 5 << 16);
1237
1238         RAL_WRITE(sc, RT2661_SOFT_RESET_CSR, 0x7);
1239         RAL_WRITE(sc, RT2661_IO_CNTL_CSR, 0x18);
1240         RAL_WRITE(sc, RT2661_PCI_USEC_CSR, 0x20);
1241
1242         /* send wakeup command to MCU */
1243         rt2661_tx_cmd(sc, RT2661_MCU_CMD_WAKEUP, 0);
1244 }
1245
1246 static void
1247 rt2661_mcu_cmd_intr(struct rt2661_softc *sc)
1248 {
1249         RAL_READ(sc, RT2661_M2H_CMD_DONE_CSR);
1250         RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
1251 }
1252
1253 static void
1254 rt2661_intr(void *arg)
1255 {
1256         struct rt2661_softc *sc = arg;
1257         struct ifnet *ifp = &sc->sc_ic.ic_if;
1258         uint32_t r1, r2;
1259
1260         /* disable MAC and MCU interrupts */
1261         RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffff7f);
1262         RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
1263
1264         /* don't re-enable interrupts if we're shutting down */
1265         if (!(ifp->if_flags & IFF_RUNNING))
1266                 return;
1267
1268         r1 = RAL_READ(sc, RT2661_INT_SOURCE_CSR);
1269         RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, r1);
1270
1271         r2 = RAL_READ(sc, RT2661_MCU_INT_SOURCE_CSR);
1272         RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, r2);
1273
1274         if (r1 & RT2661_MGT_DONE)
1275                 rt2661_tx_dma_intr(sc, &sc->mgtq);
1276
1277         if (r1 & RT2661_RX_DONE)
1278                 rt2661_rx_intr(sc);
1279
1280         if (r1 & RT2661_TX0_DMA_DONE)
1281                 rt2661_tx_dma_intr(sc, &sc->txq[0]);
1282
1283         if (r1 & RT2661_TX1_DMA_DONE)
1284                 rt2661_tx_dma_intr(sc, &sc->txq[1]);
1285
1286         if (r1 & RT2661_TX2_DMA_DONE)
1287                 rt2661_tx_dma_intr(sc, &sc->txq[2]);
1288
1289         if (r1 & RT2661_TX3_DMA_DONE)
1290                 rt2661_tx_dma_intr(sc, &sc->txq[3]);
1291
1292         if (r1 & RT2661_TX_DONE)
1293                 rt2661_tx_intr(sc);
1294
1295         if (r2 & RT2661_MCU_CMD_DONE)
1296                 rt2661_mcu_cmd_intr(sc);
1297
1298         if (r2 & RT2661_MCU_BEACON_EXPIRE)
1299                 rt2661_mcu_beacon_expire(sc);
1300
1301         if (r2 & RT2661_MCU_WAKEUP)
1302                 rt2661_mcu_wakeup(sc);
1303
1304         /* re-enable MAC and MCU interrupts */
1305         RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
1306         RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
1307 }
1308
1309 /* quickly determine if a given rate is CCK or OFDM */
1310 #define RAL_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
1311
1312 #define RAL_ACK_SIZE    (sizeof(struct ieee80211_frame_ack) + IEEE80211_FCS_LEN)
1313 #define RAL_CTS_SIZE    (sizeof(struct ieee80211_frame_cts) + IEEE80211_FCS_LEN)
1314
1315 /*
1316  * This function is only used by the Rx radiotap code. It returns the rate at
1317  * which a given frame was received.
1318  */
1319 static uint8_t
1320 rt2661_rxrate(struct rt2661_rx_desc *desc)
1321 {
1322         if (le32toh(desc->flags) & RT2661_RX_OFDM) {
1323                 /* reverse function of rt2661_plcp_signal */
1324                 switch (desc->rate & 0xf) {
1325                 case 0xb:       return 12;
1326                 case 0xf:       return 18;
1327                 case 0xa:       return 24;
1328                 case 0xe:       return 36;
1329                 case 0x9:       return 48;
1330                 case 0xd:       return 72;
1331                 case 0x8:       return 96;
1332                 case 0xc:       return 108;
1333                 }
1334         } else {
1335                 if (desc->rate == 10)
1336                         return 2;
1337                 if (desc->rate == 20)
1338                         return 4;
1339                 if (desc->rate == 55)
1340                         return 11;
1341                 if (desc->rate == 110)
1342                         return 22;
1343         }
1344         return 2;       /* should not get there */
1345 }
1346
1347 static uint8_t
1348 rt2661_plcp_signal(int rate)
1349 {
1350         switch (rate) {
1351         /* CCK rates (returned values are device-dependent) */
1352         case 2:         return 0x0;
1353         case 4:         return 0x1;
1354         case 11:        return 0x2;
1355         case 22:        return 0x3;
1356
1357         /* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1358         case 12:        return 0xb;
1359         case 18:        return 0xf;
1360         case 24:        return 0xa;
1361         case 36:        return 0xe;
1362         case 48:        return 0x9;
1363         case 72:        return 0xd;
1364         case 96:        return 0x8;
1365         case 108:       return 0xc;
1366
1367         /* unsupported rates (should not get there) */
1368         default:        return 0xff;
1369         }
1370 }
1371
1372 static void
1373 rt2661_setup_tx_desc(struct rt2661_softc *sc, struct rt2661_tx_desc *desc,
1374     uint32_t flags, uint16_t xflags, int len, int rate,
1375     const bus_dma_segment_t *segs, int nsegs, int ac, int ratectl)
1376 {
1377         struct ieee80211com *ic = &sc->sc_ic;
1378         uint16_t plcp_length;
1379         int i, remainder;
1380
1381         desc->flags = htole32(flags);
1382         desc->flags |= htole32(len << 16);
1383         desc->flags |= htole32(RT2661_TX_VALID);
1384
1385         desc->xflags = htole16(xflags);
1386         desc->xflags |= htole16(nsegs << 13);
1387
1388         desc->wme = htole16(
1389             RT2661_QID(ac) |
1390             RT2661_AIFSN(2) |
1391             RT2661_LOGCWMIN(4) |
1392             RT2661_LOGCWMAX(10));
1393
1394         /*
1395          * Remember whether TX rate control information should be gathered.
1396          * This field is driver private data only.  It will be made available
1397          * by the NIC in STA_CSR4 on Tx done interrupts.
1398          */
1399         desc->qid = ratectl;
1400
1401         /* setup PLCP fields */
1402         desc->plcp_signal  = rt2661_plcp_signal(rate);
1403         desc->plcp_service = 4;
1404
1405         len += IEEE80211_CRC_LEN;
1406         if (RAL_RATE_IS_OFDM(rate)) {
1407                 desc->flags |= htole32(RT2661_TX_OFDM);
1408
1409                 plcp_length = len & 0xfff;
1410                 desc->plcp_length_hi = plcp_length >> 6;
1411                 desc->plcp_length_lo = plcp_length & 0x3f;
1412         } else {
1413                 plcp_length = (16 * len + rate - 1) / rate;
1414                 if (rate == 22) {
1415                         remainder = (16 * len) % 22;
1416                         if (remainder != 0 && remainder < 7)
1417                                 desc->plcp_service |= RT2661_PLCP_LENGEXT;
1418                 }
1419                 desc->plcp_length_hi = plcp_length >> 8;
1420                 desc->plcp_length_lo = plcp_length & 0xff;
1421
1422                 if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1423                         desc->plcp_signal |= 0x08;
1424         }
1425
1426         /* RT2x61 supports scatter with up to 5 segments */
1427         for (i = 0; i < nsegs; i++) {
1428                 desc->addr[i] = htole32(segs[i].ds_addr);
1429                 desc->len [i] = htole16(segs[i].ds_len);
1430         }
1431
1432         desc->flags |= htole32(RT2661_TX_BUSY);
1433 }
1434
1435 static int
1436 rt2661_tx_mgt(struct rt2661_softc *sc, struct mbuf *m0,
1437     struct ieee80211_node *ni)
1438 {
1439         struct ieee80211com *ic = &sc->sc_ic;
1440         struct rt2661_tx_desc *desc;
1441         struct rt2661_data *data;
1442         struct ieee80211_frame *wh;
1443         struct rt2661_dmamap map;
1444         uint16_t dur;
1445         uint32_t flags = 0;     /* XXX HWSEQ */
1446         int rate, error;
1447
1448         desc = &sc->mgtq.desc[sc->mgtq.cur];
1449         data = &sc->mgtq.data[sc->mgtq.cur];
1450
1451         /* send mgt frames at the lowest available rate */
1452         rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1453
1454         error = bus_dmamap_load_mbuf(sc->mgtq.data_dmat, data->map, m0,
1455                                      rt2661_dma_map_mbuf, &map, 0);
1456         if (error != 0) {
1457                 device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1458                     error);
1459                 ieee80211_free_node(ni);
1460                 m_freem(m0);
1461                 return error;
1462         }
1463
1464         if (sc->sc_drvbpf != NULL) {
1465                 struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1466
1467                 tap->wt_flags = 0;
1468                 tap->wt_rate = rate;
1469                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1470                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1471
1472                 bpf_ptap(sc->sc_drvbpf, m0, tap, sc->sc_txtap_len);
1473         }
1474
1475         data->m = m0;
1476
1477         wh = mtod(m0, struct ieee80211_frame *);
1478
1479         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1480                 flags |= RT2661_TX_NEED_ACK;
1481
1482                 dur = ieee80211_txtime(ni, RAL_ACK_SIZE, rate, ic->ic_flags) +
1483                       sc->sc_sifs;
1484                 *(uint16_t *)wh->i_dur = htole16(dur);
1485
1486                 /* tell hardware to add timestamp in probe responses */
1487                 if ((wh->i_fc[0] &
1488                     (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1489                     (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1490                         flags |= RT2661_TX_TIMESTAMP;
1491         }
1492
1493         rt2661_setup_tx_desc(sc, desc, flags, 0 /* XXX HWSEQ */,
1494             m0->m_pkthdr.len, rate, map.segs, map.nseg, RT2661_QID_MGT, 0);
1495
1496         bus_dmamap_sync(sc->mgtq.data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1497         bus_dmamap_sync(sc->mgtq.desc_dmat, sc->mgtq.desc_map,
1498             BUS_DMASYNC_PREWRITE);
1499
1500         DPRINTFN(10, ("sending mgt frame len=%u idx=%u rate=%u\n",
1501             m0->m_pkthdr.len, sc->mgtq.cur, rate));
1502
1503         /* kick mgt */
1504         sc->mgtq.queued++;
1505         sc->mgtq.cur = (sc->mgtq.cur + 1) % RT2661_MGT_RING_COUNT;
1506         RAL_WRITE(sc, RT2661_TX_CNTL_CSR, RT2661_KICK_MGT);
1507
1508         ieee80211_free_node(ni);
1509
1510         return 0;
1511 }
1512
1513 /*
1514  * Build a RTS control frame.
1515  */
1516 static struct mbuf *
1517 rt2661_get_rts(struct rt2661_softc *sc, struct ieee80211_frame *wh,
1518     uint16_t dur)
1519 {
1520         struct ieee80211_frame_rts *rts;
1521         struct mbuf *m;
1522
1523         MGETHDR(m, MB_DONTWAIT, MT_DATA);
1524         if (m == NULL) {
1525                 sc->sc_ic.ic_stats.is_tx_nobuf++;
1526                 device_printf(sc->sc_dev, "could not allocate RTS frame\n");
1527                 return NULL;
1528         }
1529
1530         rts = mtod(m, struct ieee80211_frame_rts *);
1531
1532         rts->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_CTL |
1533             IEEE80211_FC0_SUBTYPE_RTS;
1534         rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1535         *(uint16_t *)rts->i_dur = htole16(dur);
1536         IEEE80211_ADDR_COPY(rts->i_ra, wh->i_addr1);
1537         IEEE80211_ADDR_COPY(rts->i_ta, wh->i_addr2);
1538
1539         m->m_pkthdr.len = m->m_len = sizeof (struct ieee80211_frame_rts);
1540
1541         return m;
1542 }
1543
1544 static int
1545 rt2661_tx_data(struct rt2661_softc *sc, struct mbuf *m0,
1546     struct ieee80211_node *ni, int ac)
1547 {
1548         struct ieee80211com *ic = &sc->sc_ic;
1549         struct rt2661_tx_ring *txq = &sc->txq[ac];
1550         struct rt2661_tx_desc *desc;
1551         struct rt2661_data *data;
1552         struct rt2661_tx_ratectl *rctl;
1553         struct ieee80211_frame *wh;
1554         struct ieee80211_key *k;
1555         const struct chanAccParams *cap;
1556         struct mbuf *mnew;
1557         struct rt2661_dmamap map;
1558         uint16_t dur;
1559         uint32_t flags = 0;
1560         int error, rate, ackrate, noack = 0, rateidx;
1561
1562         wh = mtod(m0, struct ieee80211_frame *);
1563         if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
1564                 cap = &ic->ic_wme.wme_chanParams;
1565                 noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
1566         }
1567
1568         if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1569                 k = ieee80211_crypto_encap(ic, ni, m0);
1570                 if (k == NULL) {
1571                         m_freem(m0);
1572                         return ENOBUFS;
1573                 }
1574
1575                 /* packet header may have moved, reset our local pointer */
1576                 wh = mtod(m0, struct ieee80211_frame *);
1577         }
1578
1579         ieee80211_ratectl_findrate(ni, m0->m_pkthdr.len, &rateidx, 1);
1580         rate = IEEE80211_RS_RATE(&ni->ni_rates, rateidx);
1581
1582         ackrate = ieee80211_ack_rate(ni, rate);
1583
1584         /*
1585          * IEEE Std 802.11-1999, pp 82: "A STA shall use an RTS/CTS exchange
1586          * for directed frames only when the length of the MPDU is greater
1587          * than the length threshold indicated by [...]" ic_rtsthreshold.
1588          */
1589         if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1590             m0->m_pkthdr.len > ic->ic_rtsthreshold) {
1591                 struct mbuf *m;
1592                 uint16_t dur;
1593                 int rtsrate;
1594
1595                 rtsrate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1596
1597                 /* XXX: noack (QoS)? */
1598                 dur = ieee80211_txtime(ni, m0->m_pkthdr.len + IEEE80211_FCS_LEN,
1599                                        rate, ic->ic_flags) +
1600                       ieee80211_txtime(ni, RAL_CTS_SIZE, rtsrate, ic->ic_flags)+
1601                       ieee80211_txtime(ni, RAL_ACK_SIZE, ackrate, ic->ic_flags)+
1602                       3 * sc->sc_sifs;
1603
1604                 m = rt2661_get_rts(sc, wh, dur);
1605
1606                 desc = &txq->desc[txq->cur];
1607                 data = &txq->data[txq->cur];
1608
1609                 error = bus_dmamap_load_mbuf(txq->data_dmat, data->map, m,
1610                                              rt2661_dma_map_mbuf, &map, 0);
1611                 if (error != 0) {
1612                         device_printf(sc->sc_dev,
1613                             "could not map mbuf (error %d)\n", error);
1614                         m_freem(m);
1615                         m_freem(m0);
1616                         return error;
1617                 }
1618
1619                 data->m = m;
1620
1621                 rt2661_setup_tx_desc(sc, desc, RT2661_TX_NEED_ACK |
1622                                      RT2661_TX_MORE_FRAG, 0, m->m_pkthdr.len,
1623                                      rtsrate, map.segs, map.nseg, ac, 0);
1624
1625                 bus_dmamap_sync(txq->data_dmat, data->map,
1626                     BUS_DMASYNC_PREWRITE);
1627
1628                 txq->queued++;
1629                 txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1630
1631                 /*
1632                  * IEEE Std 802.11-1999: when an RTS/CTS exchange is used, the
1633                  * asynchronous data frame shall be transmitted after the CTS
1634                  * frame and a SIFS period.
1635                  */
1636                 flags |= RT2661_TX_LONG_RETRY | RT2661_TX_IFS;
1637         }
1638
1639         data = &txq->data[txq->cur];
1640         desc = &txq->desc[txq->cur];
1641
1642         error = bus_dmamap_load_mbuf(txq->data_dmat, data->map, m0,
1643                                      rt2661_dma_map_mbuf, &map, 0);
1644         if (error != 0 && error != EFBIG) {
1645                 device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1646                     error);
1647                 m_freem(m0);
1648                 return error;
1649         }
1650         if (error != 0) {
1651                 mnew = m_defrag(m0, MB_DONTWAIT);
1652                 if (mnew == NULL) {
1653                         device_printf(sc->sc_dev,
1654                             "could not defragment mbuf\n");
1655                         m_freem(m0);
1656                         return ENOBUFS;
1657                 }
1658                 m0 = mnew;
1659
1660                 error = bus_dmamap_load_mbuf(txq->data_dmat, data->map, m0,
1661                                              rt2661_dma_map_mbuf, &map, 0);
1662                 if (error != 0) {
1663                         device_printf(sc->sc_dev,
1664                             "could not map mbuf (error %d)\n", error);
1665                         m_freem(m0);
1666                         return error;
1667                 }
1668
1669                 /* packet header have moved, reset our local pointer */
1670                 wh = mtod(m0, struct ieee80211_frame *);
1671         }
1672
1673         if (sc->sc_drvbpf != NULL) {
1674                 struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1675
1676                 tap->wt_flags = 0;
1677                 tap->wt_rate = rate;
1678                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1679                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1680
1681                 bpf_ptap(sc->sc_drvbpf, m0, tap, sc->sc_txtap_len);
1682         }
1683
1684         data->m = m0;
1685
1686         rctl = kmalloc(sizeof(*rctl), M_RT2661, M_NOWAIT);
1687         if (rctl != NULL) {
1688                 rctl->ni = ni;
1689                 rctl->len = m0->m_pkthdr.len;
1690                 rctl->rateidx = rateidx;
1691                 STAILQ_INSERT_TAIL(&sc->tx_ratectl, rctl, link);
1692         }
1693
1694         if (!noack && !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1695                 flags |= RT2661_TX_NEED_ACK;
1696
1697                 dur = ieee80211_txtime(ni, RAL_ACK_SIZE, ackrate, ic->ic_flags)+
1698                       sc->sc_sifs;
1699                 *(uint16_t *)wh->i_dur = htole16(dur);
1700         }
1701
1702         rt2661_setup_tx_desc(sc, desc, flags, 0, m0->m_pkthdr.len, rate,
1703                              map.segs, map.nseg, ac, rctl != NULL);
1704
1705         bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1706         bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1707
1708         DPRINTFN(10, ("sending data frame len=%u idx=%u rate=%u\n",
1709             m0->m_pkthdr.len, txq->cur, rate));
1710
1711         /* kick Tx */
1712         txq->queued++;
1713         txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1714         RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 1 << ac);
1715
1716         if (rctl == NULL)
1717                 ieee80211_free_node(ni);
1718
1719         return 0;
1720 }
1721
1722 static void
1723 rt2661_start(struct ifnet *ifp)
1724 {
1725         struct rt2661_softc *sc = ifp->if_softc;
1726         struct ieee80211com *ic = &sc->sc_ic;
1727         struct mbuf *m0;
1728         struct ether_header *eh;
1729         struct ieee80211_node *ni;
1730         int ac;
1731
1732         /* prevent management frames from being sent if we're not ready */
1733         if (!(ifp->if_flags & IFF_RUNNING))
1734                 return;
1735
1736         for (;;) {
1737                 IF_POLL(&ic->ic_mgtq, m0);
1738                 if (m0 != NULL) {
1739                         if (sc->mgtq.queued >= RT2661_MGT_RING_COUNT) {
1740                                 ifp->if_flags |= IFF_OACTIVE;
1741                                 break;
1742                         }
1743                         IF_DEQUEUE(&ic->ic_mgtq, m0);
1744
1745                         ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
1746                         m0->m_pkthdr.rcvif = NULL;
1747
1748                         if (ic->ic_rawbpf != NULL)
1749                                 bpf_mtap(ic->ic_rawbpf, m0);
1750
1751                         if (rt2661_tx_mgt(sc, m0, ni) != 0)
1752                                 break;
1753                 } else {
1754                         if (ic->ic_state != IEEE80211_S_RUN)
1755                                 break;
1756
1757                         m0 = ifq_dequeue(&ifp->if_snd, NULL);
1758                         if (m0 == NULL)
1759                                 break;
1760
1761                         if (m0->m_len < sizeof (struct ether_header) &&
1762                             !(m0 = m_pullup(m0, sizeof (struct ether_header))))
1763                                 continue;
1764
1765                         eh = mtod(m0, struct ether_header *);
1766                         ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1767                         if (ni == NULL) {
1768                                 m_freem(m0);
1769                                 ifp->if_oerrors++;
1770                                 continue;
1771                         }
1772
1773                         /* classify mbuf so we can find which tx ring to use */
1774                         if (ieee80211_classify(ic, m0, ni) != 0) {
1775                                 m_freem(m0);
1776                                 ieee80211_free_node(ni);
1777                                 ifp->if_oerrors++;
1778                                 continue;
1779                         }
1780
1781                         /* no QoS encapsulation for EAPOL frames */
1782                         ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
1783                             M_WME_GETAC(m0) : WME_AC_BE;
1784
1785                         if (sc->txq[ac].queued >= RT2661_TX_RING_COUNT - 1) {
1786                                 /* there is no place left in this ring */
1787                                 ifp->if_flags |= IFF_OACTIVE;
1788                                 m_freem(m0);
1789                                 ieee80211_free_node(ni);
1790                                 break;
1791                         }
1792
1793                         BPF_MTAP(ifp, m0);
1794
1795                         m0 = ieee80211_encap(ic, m0, ni);
1796                         if (m0 == NULL) {
1797                                 ieee80211_free_node(ni);
1798                                 ifp->if_oerrors++;
1799                                 continue;
1800                         }
1801
1802                         if (ic->ic_rawbpf != NULL)
1803                                 bpf_mtap(ic->ic_rawbpf, m0);
1804
1805                         if (rt2661_tx_data(sc, m0, ni, ac) != 0) {
1806                                 ieee80211_free_node(ni);
1807                                 ifp->if_oerrors++;
1808                                 break;
1809                         }
1810                 }
1811
1812                 sc->sc_tx_timer = 5;
1813                 ifp->if_timer = 1;
1814         }
1815 }
1816
1817 static void
1818 rt2661_watchdog(struct ifnet *ifp)
1819 {
1820         struct rt2661_softc *sc = ifp->if_softc;
1821         struct ieee80211com *ic = &sc->sc_ic;
1822
1823         ifp->if_timer = 0;
1824
1825         if (sc->sc_tx_timer > 0) {
1826                 if (--sc->sc_tx_timer == 0) {
1827                         device_printf(sc->sc_dev, "device timeout\n");
1828                         rt2661_init(sc);
1829                         ifp->if_oerrors++;
1830                         return;
1831                 }
1832                 ifp->if_timer = 1;
1833         }
1834
1835         ieee80211_watchdog(ic);
1836 }
1837
1838 /*
1839  * This function allows for fast channel switching in monitor mode (used by
1840  * net-mgmt/kismet). In IBSS mode, we must explicitly reset the interface to
1841  * generate a new beacon frame.
1842  */
1843 static int
1844 rt2661_reset(struct ifnet *ifp)
1845 {
1846         struct rt2661_softc *sc = ifp->if_softc;
1847         struct ieee80211com *ic = &sc->sc_ic;
1848
1849         if (ic->ic_opmode != IEEE80211_M_MONITOR)
1850                 return ENETRESET;
1851
1852         rt2661_set_chan(sc, ic->ic_curchan);
1853
1854         return 0;
1855 }
1856
1857 static int
1858 rt2661_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cr)
1859 {
1860         struct rt2661_softc *sc = ifp->if_softc;
1861         struct ieee80211com *ic = &sc->sc_ic;
1862         int error = 0;
1863
1864         switch (cmd) {
1865         case SIOCSIFFLAGS:
1866                 if (ifp->if_flags & IFF_UP) {
1867                         if (ifp->if_flags & IFF_RUNNING)
1868                                 rt2661_update_promisc(sc);
1869                         else
1870                                 rt2661_init(sc);
1871                 } else {
1872                         if (ifp->if_flags & IFF_RUNNING)
1873                                 rt2661_stop(sc);
1874                 }
1875                 break;
1876
1877         default:
1878                 error = ieee80211_ioctl(ic, cmd, data, cr);
1879         }
1880
1881         if (error == ENETRESET) {
1882                 if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1883                     (IFF_UP | IFF_RUNNING) &&
1884                     (ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
1885                         rt2661_init(sc);
1886                 error = 0;
1887         }
1888         return error;
1889 }
1890
1891 static void
1892 rt2661_bbp_write(struct rt2661_softc *sc, uint8_t reg, uint8_t val)
1893 {
1894         uint32_t tmp;
1895         int ntries;
1896
1897         for (ntries = 0; ntries < 100; ntries++) {
1898                 if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
1899                         break;
1900                 DELAY(1);
1901         }
1902         if (ntries == 100) {
1903                 device_printf(sc->sc_dev, "could not write to BBP\n");
1904                 return;
1905         }
1906
1907         tmp = RT2661_BBP_BUSY | (reg & 0x7f) << 8 | val;
1908         RAL_WRITE(sc, RT2661_PHY_CSR3, tmp);
1909
1910         DPRINTFN(15, ("BBP R%u <- 0x%02x\n", reg, val));
1911 }
1912
1913 static uint8_t
1914 rt2661_bbp_read(struct rt2661_softc *sc, uint8_t reg)
1915 {
1916         uint32_t val;
1917         int ntries;
1918
1919         for (ntries = 0; ntries < 100; ntries++) {
1920                 if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
1921                         break;
1922                 DELAY(1);
1923         }
1924         if (ntries == 100) {
1925                 device_printf(sc->sc_dev, "could not read from BBP\n");
1926                 return 0;
1927         }
1928
1929         val = RT2661_BBP_BUSY | RT2661_BBP_READ | reg << 8;
1930         RAL_WRITE(sc, RT2661_PHY_CSR3, val);
1931
1932         for (ntries = 0; ntries < 100; ntries++) {
1933                 val = RAL_READ(sc, RT2661_PHY_CSR3);
1934                 if (!(val & RT2661_BBP_BUSY))
1935                         return val & 0xff;
1936                 DELAY(1);
1937         }
1938
1939         device_printf(sc->sc_dev, "could not read from BBP\n");
1940         return 0;
1941 }
1942
1943 static void
1944 rt2661_rf_write(struct rt2661_softc *sc, uint8_t reg, uint32_t val)
1945 {
1946         uint32_t tmp;
1947         int ntries;
1948
1949         for (ntries = 0; ntries < 100; ntries++) {
1950                 if (!(RAL_READ(sc, RT2661_PHY_CSR4) & RT2661_RF_BUSY))
1951                         break;
1952                 DELAY(1);
1953         }
1954         if (ntries == 100) {
1955                 device_printf(sc->sc_dev, "could not write to RF\n");
1956                 return;
1957         }
1958
1959         tmp = RT2661_RF_BUSY | RT2661_RF_21BIT | (val & 0x1fffff) << 2 |
1960             (reg & 3);
1961         RAL_WRITE(sc, RT2661_PHY_CSR4, tmp);
1962
1963         /* remember last written value in sc */
1964         sc->rf_regs[reg] = val;
1965
1966         DPRINTFN(15, ("RF R[%u] <- 0x%05x\n", reg & 3, val & 0x1fffff));
1967 }
1968
1969 static int
1970 rt2661_tx_cmd(struct rt2661_softc *sc, uint8_t cmd, uint16_t arg)
1971 {
1972         if (RAL_READ(sc, RT2661_H2M_MAILBOX_CSR) & RT2661_H2M_BUSY)
1973                 return EIO;     /* there is already a command pending */
1974
1975         RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR,
1976             RT2661_H2M_BUSY | RT2661_TOKEN_NO_INTR << 16 | arg);
1977
1978         RAL_WRITE(sc, RT2661_HOST_CMD_CSR, RT2661_KICK_CMD | cmd);
1979
1980         return 0;
1981 }
1982
1983 static void
1984 rt2661_select_antenna(struct rt2661_softc *sc)
1985 {
1986         uint8_t bbp4, bbp77;
1987         uint32_t tmp;
1988
1989         bbp4  = rt2661_bbp_read(sc,  4);
1990         bbp77 = rt2661_bbp_read(sc, 77);
1991
1992         /* TBD */
1993
1994         /* make sure Rx is disabled before switching antenna */
1995         tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
1996         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
1997
1998         rt2661_bbp_write(sc,  4, bbp4);
1999         rt2661_bbp_write(sc, 77, bbp77);
2000
2001         /* restore Rx filter */
2002         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2003 }
2004
2005 /*
2006  * Enable multi-rate retries for frames sent at OFDM rates.
2007  * In 802.11b/g mode, allow fallback to CCK rates.
2008  */
2009 static void
2010 rt2661_enable_mrr(struct rt2661_softc *sc)
2011 {
2012         struct ieee80211com *ic = &sc->sc_ic;
2013         uint32_t tmp;
2014
2015         tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
2016
2017         tmp &= ~RT2661_MRR_CCK_FALLBACK;
2018         if (!IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan))
2019                 tmp |= RT2661_MRR_CCK_FALLBACK;
2020         tmp |= RT2661_MRR_ENABLED;
2021         tmp |= RT2661_SRETRY_LIMIT(7) | RT2661_LRETRY_LIMIT(4);
2022
2023         RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
2024 }
2025
2026 static void
2027 rt2661_set_txpreamble(struct rt2661_softc *sc)
2028 {
2029         uint32_t tmp;
2030
2031         tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
2032
2033         tmp &= ~RT2661_SHORT_PREAMBLE;
2034         if (sc->sc_ic.ic_flags & IEEE80211_F_SHPREAMBLE)
2035                 tmp |= RT2661_SHORT_PREAMBLE;
2036
2037         RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
2038 }
2039
2040 static void
2041 rt2661_set_ackrates(struct rt2661_softc *sc, const struct ieee80211_rateset *rs)
2042 {
2043 #define RV(r)   ((r) & IEEE80211_RATE_VAL)
2044         struct ieee80211com *ic = &sc->sc_ic;
2045         uint32_t mask = 0;
2046         uint8_t rate;
2047         int i, j;
2048
2049         for (i = 0; i < rs->rs_nrates; i++) {
2050                 rate = rs->rs_rates[i];
2051
2052                 if (!(rate & IEEE80211_RATE_BASIC))
2053                         continue;
2054
2055                 /*
2056                  * Find h/w rate index.  We know it exists because the rate
2057                  * set has already been negotiated.
2058                  */
2059                 for (j = 0; rt2661_rateset_11g.rs_rates[j] != RV(rate); j++)
2060                         ; /* EMPTY */
2061
2062                 mask |= 1 << j;
2063         }
2064
2065         if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan) &&
2066             ic->ic_curmode != IEEE80211_MODE_11B &&
2067             ieee80211_iserp_rateset(ic, rs)) {
2068                 /*
2069                  * Always set following rates as ACK rates to conform
2070                  * IEEE Std 802.11g-2003 clause 9.6
2071                  *
2072                  * 24Mbits/s    0x100
2073                  * 12Mbits/s    0x040
2074                  *  6Mbits/s    0x010
2075                  */
2076                 mask |= 0x150;
2077         }
2078
2079         RAL_WRITE(sc, RT2661_TXRX_CSR5, mask);
2080
2081         DPRINTF(("Setting ack rate mask to 0x%x\n", mask));
2082 #undef RV
2083 }
2084
2085 /*
2086  * Reprogram MAC/BBP to switch to a new band.  Values taken from the reference
2087  * driver.
2088  */
2089 static void
2090 rt2661_select_band(struct rt2661_softc *sc, struct ieee80211_channel *c)
2091 {
2092         uint8_t bbp17, bbp35, bbp96, bbp97, bbp98, bbp104;
2093         uint32_t tmp;
2094
2095         /* update all BBP registers that depend on the band */
2096         bbp17 = 0x20; bbp96 = 0x48; bbp104 = 0x2c;
2097         bbp35 = 0x50; bbp97 = 0x48; bbp98  = 0x48;
2098         if (IEEE80211_IS_CHAN_5GHZ(c)) {
2099                 bbp17 += 0x08; bbp96 += 0x10; bbp104 += 0x0c;
2100                 bbp35 += 0x10; bbp97 += 0x10; bbp98  += 0x10;
2101         }
2102         if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2103             (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2104                 bbp17 += 0x10; bbp96 += 0x10; bbp104 += 0x10;
2105         }
2106
2107         rt2661_bbp_write(sc,  17, bbp17);
2108         rt2661_bbp_write(sc,  96, bbp96);
2109         rt2661_bbp_write(sc, 104, bbp104);
2110
2111         if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2112             (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2113                 rt2661_bbp_write(sc, 75, 0x80);
2114                 rt2661_bbp_write(sc, 86, 0x80);
2115                 rt2661_bbp_write(sc, 88, 0x80);
2116         }
2117
2118         rt2661_bbp_write(sc, 35, bbp35);
2119         rt2661_bbp_write(sc, 97, bbp97);
2120         rt2661_bbp_write(sc, 98, bbp98);
2121
2122         tmp = RAL_READ(sc, RT2661_PHY_CSR0);
2123         tmp &= ~(RT2661_PA_PE_2GHZ | RT2661_PA_PE_5GHZ);
2124         if (IEEE80211_IS_CHAN_2GHZ(c))
2125                 tmp |= RT2661_PA_PE_2GHZ;
2126         else
2127                 tmp |= RT2661_PA_PE_5GHZ;
2128         RAL_WRITE(sc, RT2661_PHY_CSR0, tmp);
2129 }
2130
2131 static void
2132 rt2661_set_chan(struct rt2661_softc *sc, struct ieee80211_channel *c)
2133 {
2134         struct ieee80211com *ic = &sc->sc_ic;
2135         const struct rfprog *rfprog;
2136         uint8_t bbp3, bbp94 = RT2661_BBPR94_DEFAULT;
2137         int8_t power;
2138         u_int i, chan;
2139
2140         chan = ieee80211_chan2ieee(ic, c);
2141         if (chan == 0 || chan == IEEE80211_CHAN_ANY)
2142                 return;
2143
2144         /* select the appropriate RF settings based on what EEPROM says */
2145         rfprog = (sc->rfprog == 0) ? rt2661_rf5225_1 : rt2661_rf5225_2;
2146
2147         /* find the settings for this channel (we know it exists) */
2148         for (i = 0; rfprog[i].chan != chan; i++);
2149
2150         power = sc->txpow[i];
2151         if (power < 0) {
2152                 bbp94 += power;
2153                 power = 0;
2154         } else if (power > 31) {
2155                 bbp94 += power - 31;
2156                 power = 31;
2157         }
2158
2159         /*
2160          * If we are switching from the 2GHz band to the 5GHz band or
2161          * vice-versa, BBP registers need to be reprogrammed.
2162          */
2163         if (c->ic_flags != sc->sc_curchan->ic_flags) {
2164                 rt2661_select_band(sc, c);
2165                 rt2661_select_antenna(sc);
2166         }
2167         sc->sc_curchan = c;
2168
2169         rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2170         rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2171         rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2172         rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2173
2174         DELAY(200);
2175
2176         rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2177         rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2178         rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7 | 1);
2179         rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2180
2181         DELAY(200);
2182
2183         rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2184         rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2185         rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2186         rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2187
2188         /* enable smart mode for MIMO-capable RFs */
2189         bbp3 = rt2661_bbp_read(sc, 3);
2190
2191         bbp3 &= ~RT2661_SMART_MODE;
2192         if (sc->rf_rev == RT2661_RF_5325 || sc->rf_rev == RT2661_RF_2529)
2193                 bbp3 |= RT2661_SMART_MODE;
2194
2195         rt2661_bbp_write(sc, 3, bbp3);
2196
2197         if (bbp94 != RT2661_BBPR94_DEFAULT)
2198                 rt2661_bbp_write(sc, 94, bbp94);
2199
2200         /* 5GHz radio needs a 1ms delay here */
2201         if (IEEE80211_IS_CHAN_5GHZ(c))
2202                 DELAY(1000);
2203
2204         sc->sc_sifs = IEEE80211_IS_CHAN_5GHZ(c) ? IEEE80211_DUR_OFDM_SIFS
2205                                                 : IEEE80211_DUR_SIFS;
2206 }
2207
2208 static void
2209 rt2661_set_bssid(struct rt2661_softc *sc, const uint8_t *bssid)
2210 {
2211         uint32_t tmp;
2212
2213         tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24;
2214         RAL_WRITE(sc, RT2661_MAC_CSR4, tmp);
2215
2216         tmp = bssid[4] | bssid[5] << 8 | RT2661_ONE_BSSID << 16;
2217         RAL_WRITE(sc, RT2661_MAC_CSR5, tmp);
2218 }
2219
2220 static void
2221 rt2661_set_macaddr(struct rt2661_softc *sc, const uint8_t *addr)
2222 {
2223         uint32_t tmp;
2224
2225         tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24;
2226         RAL_WRITE(sc, RT2661_MAC_CSR2, tmp);
2227
2228         tmp = addr[4] | addr[5] << 8;
2229         RAL_WRITE(sc, RT2661_MAC_CSR3, tmp);
2230 }
2231
2232 static void
2233 rt2661_update_promisc(struct rt2661_softc *sc)
2234 {
2235         struct ifnet *ifp = sc->sc_ic.ic_ifp;
2236         uint32_t tmp;
2237
2238         tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2239
2240         tmp &= ~RT2661_DROP_NOT_TO_ME;
2241         if (!(ifp->if_flags & IFF_PROMISC))
2242                 tmp |= RT2661_DROP_NOT_TO_ME;
2243
2244         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2245
2246         DPRINTF(("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
2247             "entering" : "leaving"));
2248 }
2249
2250 /*
2251  * Update QoS (802.11e) settings for each h/w Tx ring.
2252  */
2253 static int
2254 rt2661_wme_update(struct ieee80211com *ic)
2255 {
2256         struct rt2661_softc *sc = ic->ic_ifp->if_softc;
2257         const struct wmeParams *wmep;
2258
2259         wmep = ic->ic_wme.wme_chanParams.cap_wmeParams;
2260
2261         /* XXX: not sure about shifts. */
2262         /* XXX: the reference driver plays with AC_VI settings too. */
2263
2264         /* update TxOp */
2265         RAL_WRITE(sc, RT2661_AC_TXOP_CSR0,
2266             wmep[WME_AC_BE].wmep_txopLimit << 16 |
2267             wmep[WME_AC_BK].wmep_txopLimit);
2268         RAL_WRITE(sc, RT2661_AC_TXOP_CSR1,
2269             wmep[WME_AC_VI].wmep_txopLimit << 16 |
2270             wmep[WME_AC_VO].wmep_txopLimit);
2271
2272         /* update CWmin */
2273         RAL_WRITE(sc, RT2661_CWMIN_CSR,
2274             wmep[WME_AC_BE].wmep_logcwmin << 12 |
2275             wmep[WME_AC_BK].wmep_logcwmin <<  8 |
2276             wmep[WME_AC_VI].wmep_logcwmin <<  4 |
2277             wmep[WME_AC_VO].wmep_logcwmin);
2278
2279         /* update CWmax */
2280         RAL_WRITE(sc, RT2661_CWMAX_CSR,
2281             wmep[WME_AC_BE].wmep_logcwmax << 12 |
2282             wmep[WME_AC_BK].wmep_logcwmax <<  8 |
2283             wmep[WME_AC_VI].wmep_logcwmax <<  4 |
2284             wmep[WME_AC_VO].wmep_logcwmax);
2285
2286         /* update Aifsn */
2287         RAL_WRITE(sc, RT2661_AIFSN_CSR,
2288             wmep[WME_AC_BE].wmep_aifsn << 12 |
2289             wmep[WME_AC_BK].wmep_aifsn <<  8 |
2290             wmep[WME_AC_VI].wmep_aifsn <<  4 |
2291             wmep[WME_AC_VO].wmep_aifsn);
2292
2293         return 0;
2294 }
2295
2296 static void
2297 rt2661_update_slot(struct ifnet *ifp)
2298 {
2299         struct rt2661_softc *sc = ifp->if_softc;
2300         struct ieee80211com *ic = &sc->sc_ic;
2301         uint8_t slottime;
2302         uint32_t tmp;
2303
2304         slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
2305
2306         tmp = RAL_READ(sc, RT2661_MAC_CSR9);
2307         tmp = (tmp & ~0xff) | slottime;
2308         RAL_WRITE(sc, RT2661_MAC_CSR9, tmp);
2309 }
2310
2311 static const char *
2312 rt2661_get_rf(int rev)
2313 {
2314         switch (rev) {
2315         case RT2661_RF_5225:    return "RT5225";
2316         case RT2661_RF_5325:    return "RT5325 (MIMO XR)";
2317         case RT2661_RF_2527:    return "RT2527";
2318         case RT2661_RF_2529:    return "RT2529 (MIMO XR)";
2319         default:                return "unknown";
2320         }
2321 }
2322
2323 static void
2324 rt2661_read_config(struct rt2661_softc *sc)
2325 {
2326         struct ieee80211com *ic = &sc->sc_ic;
2327         uint16_t val;
2328         int i, start_chan;
2329
2330         /* read MAC address */
2331         val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC01);
2332         ic->ic_myaddr[0] = val & 0xff;
2333         ic->ic_myaddr[1] = val >> 8;
2334
2335         val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC23);
2336         ic->ic_myaddr[2] = val & 0xff;
2337         ic->ic_myaddr[3] = val >> 8;
2338
2339         val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC45);
2340         ic->ic_myaddr[4] = val & 0xff;
2341         ic->ic_myaddr[5] = val >> 8;
2342
2343         val = rt2661_eeprom_read(sc, RT2661_EEPROM_ANTENNA);
2344         /* XXX: test if different from 0xffff? */
2345         sc->rf_rev   = (val >> 11) & 0x1f;
2346         sc->hw_radio = (val >> 10) & 0x1;
2347         sc->rx_ant   = (val >> 4)  & 0x3;
2348         sc->tx_ant   = (val >> 2)  & 0x3;
2349         sc->nb_ant   = val & 0x3;
2350
2351         DPRINTF(("RF revision=%d\n", sc->rf_rev));
2352
2353         val = rt2661_eeprom_read(sc, RT2661_EEPROM_CONFIG2);
2354         sc->ext_5ghz_lna = (val >> 6) & 0x1;
2355         sc->ext_2ghz_lna = (val >> 4) & 0x1;
2356
2357         DPRINTF(("External 2GHz LNA=%d\nExternal 5GHz LNA=%d\n",
2358             sc->ext_2ghz_lna, sc->ext_5ghz_lna));
2359
2360         val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_2GHZ_OFFSET);
2361         if ((val & 0xff) != 0xff)
2362                 sc->rssi_2ghz_corr = (int8_t)(val & 0xff);      /* signed */
2363
2364         /* Only [-10, 10] is valid */
2365         if (sc->rssi_2ghz_corr < -10 || sc->rssi_2ghz_corr > 10)
2366                 sc->rssi_2ghz_corr = 0;
2367
2368         val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_5GHZ_OFFSET);
2369         if ((val & 0xff) != 0xff)
2370                 sc->rssi_5ghz_corr = (int8_t)(val & 0xff);      /* signed */
2371
2372         /* Only [-10, 10] is valid */
2373         if (sc->rssi_5ghz_corr < -10 || sc->rssi_5ghz_corr > 10)
2374                 sc->rssi_5ghz_corr = 0;
2375
2376         /* adjust RSSI correction for external low-noise amplifier */
2377         if (sc->ext_2ghz_lna)
2378                 sc->rssi_2ghz_corr -= 14;
2379         if (sc->ext_5ghz_lna)
2380                 sc->rssi_5ghz_corr -= 14;
2381
2382         DPRINTF(("RSSI 2GHz corr=%d\nRSSI 5GHz corr=%d\n",
2383             sc->rssi_2ghz_corr, sc->rssi_5ghz_corr));
2384
2385         val = rt2661_eeprom_read(sc, RT2661_EEPROM_FREQ_OFFSET);
2386         if ((val >> 8) != 0xff)
2387                 sc->rfprog = (val >> 8) & 0x3;
2388         if ((val & 0xff) != 0xff)
2389                 sc->rffreq = val & 0xff;
2390
2391         DPRINTF(("RF prog=%d\nRF freq=%d\n", sc->rfprog, sc->rffreq));
2392
2393 #define NCHAN_2GHZ      14
2394 #define NCHAN_5GHZ      24
2395         /*
2396          * Read channel TX power
2397          */
2398         start_chan = 0;
2399         rt2661_read_txpower_config(sc, RT2661_EEPROM_TXPOWER_2GHZ,
2400                                    NCHAN_2GHZ, &start_chan);
2401         rt2661_read_txpower_config(sc, RT2661_EEPROM_TXPOWER_5GHZ,
2402                                    NCHAN_5GHZ, &start_chan);
2403 #undef NCHAN_2GHZ
2404 #undef NCHAN_5GHZ
2405
2406         /* read vendor-specific BBP values */
2407         for (i = 0; i < 16; i++) {
2408                 val = rt2661_eeprom_read(sc, RT2661_EEPROM_BBP_BASE + i);
2409                 if (val == 0 || val == 0xffff)
2410                         continue;       /* skip invalid entries */
2411                 sc->bbp_prom[i].reg = val >> 8;
2412                 sc->bbp_prom[i].val = val & 0xff;
2413                 DPRINTF(("BBP R%d=%02x\n", sc->bbp_prom[i].reg,
2414                     sc->bbp_prom[i].val));
2415         }
2416
2417         val = rt2661_eeprom_read(sc, RT2661_EEPROM_LED_OFFSET);
2418         DPRINTF(("LED %02x\n", val));
2419         if (val == 0xffff) {
2420                 sc->mcu_led = RT2661_MCU_LED_DEFAULT;
2421         } else {
2422 #define N(arr)  (int)(sizeof(arr) / sizeof(arr[0]))
2423
2424                 for (i = 0; i < N(led_ee2mcu); ++i) {
2425                         if (val & led_ee2mcu[i].ee_bit)
2426                                 sc->mcu_led |= led_ee2mcu[i].mcu_bit;
2427                 }
2428
2429 #undef N
2430
2431                 sc->mcu_led |= ((val >> RT2661_EE_LED_MODE_SHIFT) &
2432                                 RT2661_EE_LED_MODE_MASK);
2433         }
2434 }
2435
2436 static int
2437 rt2661_bbp_init(struct rt2661_softc *sc)
2438 {
2439 #define N(a)    (sizeof (a) / sizeof ((a)[0]))
2440         int i, ntries;
2441         uint8_t val;
2442
2443         /* wait for BBP to be ready */
2444         for (ntries = 0; ntries < 100; ntries++) {
2445                 val = rt2661_bbp_read(sc, 0);
2446                 if (val != 0 && val != 0xff)
2447                         break;
2448                 DELAY(100);
2449         }
2450         if (ntries == 100) {
2451                 device_printf(sc->sc_dev, "timeout waiting for BBP\n");
2452                 return EIO;
2453         }
2454
2455         /* initialize BBP registers to default values */
2456         for (i = 0; i < N(rt2661_def_bbp); i++) {
2457                 rt2661_bbp_write(sc, rt2661_def_bbp[i].reg,
2458                     rt2661_def_bbp[i].val);
2459         }
2460
2461         /* write vendor-specific BBP values (from EEPROM) */
2462         for (i = 0; i < 16; i++) {
2463                 if (sc->bbp_prom[i].reg == 0)
2464                         continue;
2465                 rt2661_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2466         }
2467
2468         return 0;
2469 #undef N
2470 }
2471
2472 static void
2473 rt2661_init(void *priv)
2474 {
2475 #define N(a)    (sizeof (a) / sizeof ((a)[0]))
2476         struct rt2661_softc *sc = priv;
2477         struct ieee80211com *ic = &sc->sc_ic;
2478         struct ifnet *ifp = ic->ic_ifp;
2479         uint32_t tmp, sta[3];
2480         int i, ntries;
2481
2482         rt2661_stop(sc);
2483
2484         /* initialize Tx rings */
2485         RAL_WRITE(sc, RT2661_AC1_BASE_CSR, sc->txq[1].physaddr);
2486         RAL_WRITE(sc, RT2661_AC0_BASE_CSR, sc->txq[0].physaddr);
2487         RAL_WRITE(sc, RT2661_AC2_BASE_CSR, sc->txq[2].physaddr);
2488         RAL_WRITE(sc, RT2661_AC3_BASE_CSR, sc->txq[3].physaddr);
2489
2490         /* initialize Mgt ring */
2491         RAL_WRITE(sc, RT2661_MGT_BASE_CSR, sc->mgtq.physaddr);
2492
2493         /* initialize Rx ring */
2494         RAL_WRITE(sc, RT2661_RX_BASE_CSR, sc->rxq.physaddr);
2495
2496         /* initialize Tx rings sizes */
2497         RAL_WRITE(sc, RT2661_TX_RING_CSR0,
2498             RT2661_TX_RING_COUNT << 24 |
2499             RT2661_TX_RING_COUNT << 16 |
2500             RT2661_TX_RING_COUNT <<  8 |
2501             RT2661_TX_RING_COUNT);
2502
2503         RAL_WRITE(sc, RT2661_TX_RING_CSR1,
2504             RT2661_TX_DESC_WSIZE << 16 |
2505             RT2661_TX_RING_COUNT <<  8 |        /* XXX: HCCA ring unused */
2506             RT2661_MGT_RING_COUNT);
2507
2508         /* initialize Rx rings */
2509         RAL_WRITE(sc, RT2661_RX_RING_CSR,
2510             RT2661_RX_DESC_BACK  << 16 |
2511             RT2661_RX_DESC_WSIZE <<  8 |
2512             RT2661_RX_RING_COUNT);
2513
2514         /* XXX: some magic here */
2515         RAL_WRITE(sc, RT2661_TX_DMA_DST_CSR, 0xaa);
2516
2517         /* load base addresses of all 5 Tx rings (4 data + 1 mgt) */
2518         RAL_WRITE(sc, RT2661_LOAD_TX_RING_CSR, 0x1f);
2519
2520         /* load base address of Rx ring */
2521         RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 2);
2522
2523         /* initialize MAC registers to default values */
2524         for (i = 0; i < N(rt2661_def_mac); i++)
2525                 RAL_WRITE(sc, rt2661_def_mac[i].reg, rt2661_def_mac[i].val);
2526
2527         IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2528         rt2661_set_macaddr(sc, ic->ic_myaddr);
2529
2530         /* set host ready */
2531         RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2532         RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2533
2534         /* wait for BBP/RF to wakeup */
2535         for (ntries = 0; ntries < 1000; ntries++) {
2536                 if (RAL_READ(sc, RT2661_MAC_CSR12) & 8)
2537                         break;
2538                 DELAY(1000);
2539         }
2540         if (ntries == 1000) {
2541                 kprintf("timeout waiting for BBP/RF to wakeup\n");
2542                 rt2661_stop(sc);
2543                 return;
2544         }
2545
2546         if (rt2661_bbp_init(sc) != 0) {
2547                 rt2661_stop(sc);
2548                 return;
2549         }
2550
2551         /* select default channel */
2552         sc->sc_curchan = ic->ic_curchan;
2553         rt2661_select_band(sc, sc->sc_curchan);
2554         rt2661_select_antenna(sc);
2555         rt2661_set_chan(sc, sc->sc_curchan);
2556
2557         /* update Rx filter */
2558         tmp = RAL_READ(sc, RT2661_TXRX_CSR0) & 0xffff;
2559
2560         tmp |= RT2661_DROP_PHY_ERROR | RT2661_DROP_CRC_ERROR;
2561         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2562                 tmp |= RT2661_DROP_CTL | RT2661_DROP_VER_ERROR |
2563                        RT2661_DROP_ACKCTS;
2564                 if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2565                         tmp |= RT2661_DROP_TODS;
2566                 if (!(ifp->if_flags & IFF_PROMISC))
2567                         tmp |= RT2661_DROP_NOT_TO_ME;
2568         }
2569
2570         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2571
2572         /* clear STA registers */
2573         RAL_READ_REGION_4(sc, RT2661_STA_CSR0, sta, N(sta));
2574
2575         /* initialize ASIC */
2576         RAL_WRITE(sc, RT2661_MAC_CSR1, 4);
2577
2578         /* clear any pending interrupt */
2579         RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2580
2581         /* enable interrupts */
2582         RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
2583         RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
2584
2585         /* kick Rx */
2586         RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 1);
2587
2588         ifp->if_flags &= ~IFF_OACTIVE;
2589         ifp->if_flags |= IFF_RUNNING;
2590
2591         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2592                 if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
2593                         ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2594         } else
2595                 ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2596 #undef N
2597 }
2598
2599 void
2600 rt2661_stop(void *priv)
2601 {
2602         struct rt2661_softc *sc = priv;
2603         struct ieee80211com *ic = &sc->sc_ic;
2604         struct ifnet *ifp = ic->ic_ifp;
2605         struct rt2661_tx_ratectl *rctl;
2606         uint32_t tmp;
2607
2608         ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2609
2610         sc->sc_tx_timer = 0;
2611         ifp->if_timer = 0;
2612         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2613
2614         /* abort Tx (for all 5 Tx rings) */
2615         RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 0x1f << 16);
2616
2617         /* disable Rx (value remains after reset!) */
2618         tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2619         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2620
2621         /* reset ASIC */
2622         RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2623         RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2624
2625         /* disable interrupts */
2626         RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffffff);
2627         RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
2628
2629         /* clear any pending interrupt */
2630         RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2631         RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, 0xffffffff);
2632
2633         while ((rctl = STAILQ_FIRST(&sc->tx_ratectl)) != NULL) {
2634                 STAILQ_REMOVE_HEAD(&sc->tx_ratectl, link);
2635                 ieee80211_free_node(rctl->ni);
2636                 rctl->ni = NULL;
2637                 kfree(rctl, M_RT2661);
2638         }
2639
2640         /* reset Tx and Rx rings */
2641         rt2661_reset_tx_ring(sc, &sc->txq[0]);
2642         rt2661_reset_tx_ring(sc, &sc->txq[1]);
2643         rt2661_reset_tx_ring(sc, &sc->txq[2]);
2644         rt2661_reset_tx_ring(sc, &sc->txq[3]);
2645         rt2661_reset_tx_ring(sc, &sc->mgtq);
2646         rt2661_reset_rx_ring(sc, &sc->rxq);
2647 }
2648
2649 static int
2650 rt2661_load_microcode(struct rt2661_softc *sc, const uint8_t *ucode, int size)
2651 {
2652         int ntries;
2653
2654         /* reset 8051 */
2655         RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2656
2657         /* cancel any pending Host to MCU command */
2658         RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR, 0);
2659         RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
2660         RAL_WRITE(sc, RT2661_HOST_CMD_CSR, 0);
2661
2662         /* write 8051's microcode */
2663         RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET | RT2661_MCU_SEL);
2664         RAL_WRITE_REGION_1(sc, RT2661_MCU_CODE_BASE, ucode, size);
2665         RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2666
2667         /* kick 8051's ass */
2668         RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, 0);
2669
2670         /* wait for 8051 to initialize */
2671         for (ntries = 0; ntries < 500; ntries++) {
2672                 if (RAL_READ(sc, RT2661_MCU_CNTL_CSR) & RT2661_MCU_READY)
2673                         break;
2674                 DELAY(100);
2675         }
2676         if (ntries == 500) {
2677                 kprintf("timeout waiting for MCU to initialize\n");
2678                 return EIO;
2679         }
2680         return 0;
2681 }
2682
2683 #ifdef notyet
2684 /*
2685  * Dynamically tune Rx sensitivity (BBP register 17) based on average RSSI and
2686  * false CCA count.  This function is called periodically (every seconds) when
2687  * in the RUN state.  Values taken from the reference driver.
2688  */
2689 static void
2690 rt2661_rx_tune(struct rt2661_softc *sc)
2691 {
2692         uint8_t bbp17;
2693         uint16_t cca;
2694         int lo, hi, dbm;
2695
2696         /*
2697          * Tuning range depends on operating band and on the presence of an
2698          * external low-noise amplifier.
2699          */
2700         lo = 0x20;
2701         if (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan))
2702                 lo += 0x08;
2703         if ((IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan) && sc->ext_2ghz_lna) ||
2704             (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan) && sc->ext_5ghz_lna))
2705                 lo += 0x10;
2706         hi = lo + 0x20;
2707
2708         /* retrieve false CCA count since last call (clear on read) */
2709         cca = RAL_READ(sc, RT2661_STA_CSR1) & 0xffff;
2710
2711         if (dbm >= -35) {
2712                 bbp17 = 0x60;
2713         } else if (dbm >= -58) {
2714                 bbp17 = hi;
2715         } else if (dbm >= -66) {
2716                 bbp17 = lo + 0x10;
2717         } else if (dbm >= -74) {
2718                 bbp17 = lo + 0x08;
2719         } else {
2720                 /* RSSI < -74dBm, tune using false CCA count */
2721
2722                 bbp17 = sc->bbp17; /* current value */
2723
2724                 hi -= 2 * (-74 - dbm);
2725                 if (hi < lo)
2726                         hi = lo;
2727
2728                 if (bbp17 > hi) {
2729                         bbp17 = hi;
2730
2731                 } else if (cca > 512) {
2732                         if (++bbp17 > hi)
2733                                 bbp17 = hi;
2734                 } else if (cca < 100) {
2735                         if (--bbp17 < lo)
2736                                 bbp17 = lo;
2737                 }
2738         }
2739
2740         if (bbp17 != sc->bbp17) {
2741                 rt2661_bbp_write(sc, 17, bbp17);
2742                 sc->bbp17 = bbp17;
2743         }
2744 }
2745
2746 /*
2747  * Enter/Leave radar detection mode.
2748  * This is for 802.11h additional regulatory domains.
2749  */
2750 static void
2751 rt2661_radar_start(struct rt2661_softc *sc)
2752 {
2753         uint32_t tmp;
2754
2755         /* disable Rx */
2756         tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2757         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2758
2759         rt2661_bbp_write(sc, 82, 0x20);
2760         rt2661_bbp_write(sc, 83, 0x00);
2761         rt2661_bbp_write(sc, 84, 0x40);
2762
2763         /* save current BBP registers values */
2764         sc->bbp18 = rt2661_bbp_read(sc, 18);
2765         sc->bbp21 = rt2661_bbp_read(sc, 21);
2766         sc->bbp22 = rt2661_bbp_read(sc, 22);
2767         sc->bbp16 = rt2661_bbp_read(sc, 16);
2768         sc->bbp17 = rt2661_bbp_read(sc, 17);
2769         sc->bbp64 = rt2661_bbp_read(sc, 64);
2770
2771         rt2661_bbp_write(sc, 18, 0xff);
2772         rt2661_bbp_write(sc, 21, 0x3f);
2773         rt2661_bbp_write(sc, 22, 0x3f);
2774         rt2661_bbp_write(sc, 16, 0xbd);
2775         rt2661_bbp_write(sc, 17, sc->ext_5ghz_lna ? 0x44 : 0x34);
2776         rt2661_bbp_write(sc, 64, 0x21);
2777
2778         /* restore Rx filter */
2779         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2780 }
2781
2782 static int
2783 rt2661_radar_stop(struct rt2661_softc *sc)
2784 {
2785         uint8_t bbp66;
2786
2787         /* read radar detection result */
2788         bbp66 = rt2661_bbp_read(sc, 66);
2789
2790         /* restore BBP registers values */
2791         rt2661_bbp_write(sc, 16, sc->bbp16);
2792         rt2661_bbp_write(sc, 17, sc->bbp17);
2793         rt2661_bbp_write(sc, 18, sc->bbp18);
2794         rt2661_bbp_write(sc, 21, sc->bbp21);
2795         rt2661_bbp_write(sc, 22, sc->bbp22);
2796         rt2661_bbp_write(sc, 64, sc->bbp64);
2797
2798         return bbp66 == 1;
2799 }
2800 #endif
2801
2802 static int
2803 rt2661_prepare_beacon(struct rt2661_softc *sc)
2804 {
2805         struct ieee80211com *ic = &sc->sc_ic;
2806         struct ieee80211_beacon_offsets bo;
2807         struct rt2661_tx_desc desc;
2808         struct mbuf *m0;
2809         int rate;
2810
2811         m0 = ieee80211_beacon_alloc(ic, ic->ic_bss, &bo);
2812         if (m0 == NULL) {
2813                 device_printf(sc->sc_dev, "could not allocate beacon frame\n");
2814                 return ENOBUFS;
2815         }
2816
2817         /* send beacons at the lowest available rate */
2818         rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan) ? 12 : 2;
2819
2820         rt2661_setup_tx_desc(sc, &desc, RT2661_TX_TIMESTAMP, RT2661_TX_HWSEQ,
2821             m0->m_pkthdr.len, rate, NULL, 0, RT2661_QID_MGT, 0);
2822
2823         /* copy the first 24 bytes of Tx descriptor into NIC memory */
2824         RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0, (uint8_t *)&desc, 24);
2825
2826         /* copy beacon header and payload into NIC memory */
2827         RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0 + 24,
2828             mtod(m0, uint8_t *), m0->m_pkthdr.len);
2829
2830         m_freem(m0);
2831         return 0;
2832 }
2833
2834 /*
2835  * Enable TSF synchronization and tell h/w to start sending beacons for IBSS
2836  * and HostAP operating modes.
2837  */
2838 static void
2839 rt2661_enable_tsf_sync(struct rt2661_softc *sc)
2840 {
2841         struct ieee80211com *ic = &sc->sc_ic;
2842         uint32_t tmp;
2843
2844         if (ic->ic_opmode != IEEE80211_M_STA) {
2845                 /*
2846                  * Change default 16ms TBTT adjustment to 8ms.
2847                  * Must be done before enabling beacon generation.
2848                  */
2849                 RAL_WRITE(sc, RT2661_TXRX_CSR10, 1 << 12 | 8);
2850         }
2851
2852         tmp = RAL_READ(sc, RT2661_TXRX_CSR9) & 0xff000000;
2853
2854         /* set beacon interval (in 1/16ms unit) */
2855         tmp |= ic->ic_bss->ni_intval * 16;
2856
2857         tmp |= RT2661_TSF_TICKING | RT2661_ENABLE_TBTT;
2858         if (ic->ic_opmode == IEEE80211_M_STA)
2859                 tmp |= RT2661_TSF_MODE(1);
2860         else
2861                 tmp |= RT2661_TSF_MODE(2) | RT2661_GENERATE_BEACON;
2862
2863         RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp);
2864 }
2865
2866 /*
2867  * Retrieve the "Received Signal Strength Indicator" from the raw values
2868  * contained in Rx descriptors.  The computation depends on which band the
2869  * frame was received.  Correction values taken from the reference driver.
2870  */
2871 static int
2872 rt2661_get_rssi(struct rt2661_softc *sc, uint8_t raw)
2873 {
2874         int lna, agc, rssi;
2875
2876         lna = (raw >> 5) & 0x3;
2877         agc = raw & 0x1f;
2878
2879         if (lna == 0) {
2880                 /*
2881                  * No RSSI mapping
2882                  *
2883                  * NB: Since RSSI is relative to noise floor, -1 is
2884                  *     adequate for caller to know error happened.
2885                  */
2886                 return -1;
2887         }
2888
2889         rssi = (2 * agc) - RT2661_NOISE_FLOOR;
2890
2891         if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan)) {
2892                 rssi += sc->rssi_2ghz_corr;
2893
2894                 if (lna == 1)
2895                         rssi -= 64;
2896                 else if (lna == 2)
2897                         rssi -= 74;
2898                 else if (lna == 3)
2899                         rssi -= 90;
2900         } else {
2901                 rssi += sc->rssi_5ghz_corr;
2902
2903                 if (lna == 1)
2904                         rssi -= 64;
2905                 else if (lna == 2)
2906                         rssi -= 86;
2907                 else if (lna == 3)
2908                         rssi -= 100;
2909         }
2910         return rssi;
2911 }
2912
2913 static void
2914 rt2661_dma_map_mbuf(void *arg, bus_dma_segment_t *seg, int nseg,
2915                     bus_size_t map_size __unused, int error)
2916 {
2917         struct rt2661_dmamap *map = arg;
2918
2919         if (error)
2920                 return;
2921
2922         KASSERT(nseg <= RT2661_MAX_SCATTER, ("too many DMA segments"));
2923
2924         bcopy(seg, map->segs, nseg * sizeof(bus_dma_segment_t));
2925         map->nseg = nseg;
2926 }
2927
2928 static void
2929 rt2661_led_newstate(struct rt2661_softc *sc, enum ieee80211_state nstate)
2930 {
2931         struct ieee80211com *ic = &sc->sc_ic;
2932         uint32_t off, on;
2933         uint32_t mail = sc->mcu_led;
2934
2935         if (RAL_READ(sc, RT2661_H2M_MAILBOX_CSR) & RT2661_H2M_BUSY) {
2936                 DPRINTF(("%s failed\n", __func__));
2937                 return;
2938         }
2939
2940         switch (nstate) {
2941         case IEEE80211_S_INIT:
2942                 mail &= ~(RT2661_MCU_LED_LINKA | RT2661_MCU_LED_LINKG |
2943                           RT2661_MCU_LED_RF);
2944                 break;
2945         default:
2946                 if (ic->ic_curchan == NULL)
2947                         return;
2948
2949                 on = RT2661_MCU_LED_LINKG;
2950                 off = RT2661_MCU_LED_LINKA;
2951                 if (IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan)) {
2952                         on = RT2661_MCU_LED_LINKA;
2953                         off = RT2661_MCU_LED_LINKG;
2954                 }
2955
2956                 mail |= RT2661_MCU_LED_RF | on;
2957                 mail &= ~off;
2958                 break;
2959         }
2960
2961         RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR,
2962                   RT2661_H2M_BUSY | RT2661_TOKEN_NO_INTR << 16 | mail);
2963         RAL_WRITE(sc, RT2661_HOST_CMD_CSR, RT2661_KICK_CMD | RT2661_MCU_SET_LED);
2964 }
2965
2966 static void
2967 rt2661_read_txpower_config(struct rt2661_softc *sc, uint8_t txpwr_ofs,
2968                            int nchan, int *start_chan0)
2969 {
2970         int i, loop_max;
2971         int start_chan = *start_chan0;
2972
2973         KASSERT(nchan % 2 == 0, ("number of channels %d is not even\n", nchan));
2974         KASSERT(start_chan + nchan <= RT2661_NCHAN_MAX, ("too many channels"));
2975
2976         loop_max = nchan / 2;
2977
2978         for (i = 0; i < loop_max; i++) {
2979                 int chan_idx, j;
2980                 uint16_t val;
2981
2982                 val = rt2661_eeprom_read(sc, txpwr_ofs + i);
2983                 chan_idx = i * 2 + start_chan;
2984
2985                 for (j = 0; j < 2; ++j) {
2986                         int8_t tx_power;        /* signed */
2987
2988                         tx_power = (int8_t)((val >> (8 * j)) & 0xff);
2989                         if (tx_power > RT2661_TXPOWER_MAX)
2990                                 tx_power = RT2661_TXPOWER_DEFAULT;
2991
2992                         sc->txpow[chan_idx] = tx_power;
2993                         DPRINTF(("Channel=%d Tx power=%d\n",
2994                             rt2661_rf5225_1[chan_idx].chan, sc->txpow[chan_idx]));
2995
2996                         ++chan_idx;
2997                 }
2998         }
2999         *start_chan0 += nchan;
3000 }