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