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