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