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