- Store tx rate control parameters in drivers, so switching between tx rate
[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.23 2008/01/15 09:01:13 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);
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_set_chan(sc, ic->ic_curchan);
940
941                 ni = ic->ic_bss;
942
943                 if (ic->ic_opmode != IEEE80211_M_MONITOR) {
944                         rt2661_enable_mrr(sc);
945                         rt2661_set_txpreamble(sc);
946                         rt2661_set_ackrates(sc, &ni->ni_rates);
947                         rt2661_set_bssid(sc, ni->ni_bssid);
948                 }
949
950                 if (ic->ic_opmode == IEEE80211_M_HOSTAP ||
951                     ic->ic_opmode == IEEE80211_M_IBSS) {
952                         if ((error = rt2661_prepare_beacon(sc)) != 0)
953                                 break;
954                 }
955
956                 if (ic->ic_opmode != IEEE80211_M_MONITOR)
957                         rt2661_enable_tsf_sync(sc);
958                 break;
959         }       
960
961         return (error != 0) ? error : sc->sc_newstate(ic, nstate, arg);
962 }
963
964 /*
965  * Read 16 bits at address 'addr' from the serial EEPROM (either 93C46 or
966  * 93C66).
967  */
968 static uint16_t
969 rt2661_eeprom_read(struct rt2661_softc *sc, uint8_t addr)
970 {
971         uint32_t tmp;
972         uint16_t val;
973         int n;
974
975         /* clock C once before the first command */
976         RT2661_EEPROM_CTL(sc, 0);
977
978         RT2661_EEPROM_CTL(sc, RT2661_S);
979         RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
980         RT2661_EEPROM_CTL(sc, RT2661_S);
981
982         /* write start bit (1) */
983         RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
984         RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
985
986         /* write READ opcode (10) */
987         RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D);
988         RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_D | RT2661_C);
989         RT2661_EEPROM_CTL(sc, RT2661_S);
990         RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
991
992         /* write address (A5-A0 or A7-A0) */
993         n = (RAL_READ(sc, RT2661_E2PROM_CSR) & RT2661_93C46) ? 5 : 7;
994         for (; n >= 0; n--) {
995                 RT2661_EEPROM_CTL(sc, RT2661_S |
996                     (((addr >> n) & 1) << RT2661_SHIFT_D));
997                 RT2661_EEPROM_CTL(sc, RT2661_S |
998                     (((addr >> n) & 1) << RT2661_SHIFT_D) | RT2661_C);
999         }
1000
1001         RT2661_EEPROM_CTL(sc, RT2661_S);
1002
1003         /* read data Q15-Q0 */
1004         val = 0;
1005         for (n = 15; n >= 0; n--) {
1006                 RT2661_EEPROM_CTL(sc, RT2661_S | RT2661_C);
1007                 tmp = RAL_READ(sc, RT2661_E2PROM_CSR);
1008                 val |= ((tmp & RT2661_Q) >> RT2661_SHIFT_Q) << n;
1009                 RT2661_EEPROM_CTL(sc, RT2661_S);
1010         }
1011
1012         RT2661_EEPROM_CTL(sc, 0);
1013
1014         /* clear Chip Select and clock C */
1015         RT2661_EEPROM_CTL(sc, RT2661_S);
1016         RT2661_EEPROM_CTL(sc, 0);
1017         RT2661_EEPROM_CTL(sc, RT2661_C);
1018
1019         return val;
1020 }
1021
1022 static void
1023 rt2661_tx_intr(struct rt2661_softc *sc)
1024 {
1025         struct ieee80211com *ic = &sc->sc_ic;
1026         struct ifnet *ifp = ic->ic_ifp;
1027         struct rt2661_tx_ratectl *rctl;
1028         uint32_t val, result;
1029         int retrycnt;
1030
1031         for (;;) {
1032                 struct ieee80211_ratectl_res res;
1033
1034                 val = RAL_READ(sc, RT2661_STA_CSR4);
1035                 if (!(val & RT2661_TX_STAT_VALID))
1036                         break;
1037
1038                 /* Gather statistics */
1039                 result = RT2661_TX_RESULT(val);
1040                 if (result == RT2661_TX_SUCCESS)
1041                         ifp->if_opackets++;
1042                 else
1043                         ifp->if_oerrors++;
1044
1045                 /* No rate control */
1046                 if (RT2661_TX_QID(val) == 0)
1047                         continue;
1048
1049                 /* retrieve rate control algorithm context */
1050                 rctl = STAILQ_FIRST(&sc->tx_ratectl);
1051                 if (rctl == NULL) {
1052                         /*
1053                          * XXX
1054                          * This really should not happen.  Maybe we should
1055                          * use assertion here?  But why should we rely on
1056                          * hardware to do the correct things?  Even the
1057                          * reference driver (RT61?) provided by Ralink does
1058                          * not provide enough clue that this kind of interrupt
1059                          * is promised to be generated for each packet.  So
1060                          * just print a message and keep going ...
1061                          */
1062                         if_printf(ifp, "WARNING: no rate control information\n");
1063                         continue;
1064                 }
1065                 STAILQ_REMOVE_HEAD(&sc->tx_ratectl, link);
1066
1067                 retrycnt = 7;
1068                 switch (result) {
1069                 case RT2661_TX_SUCCESS:
1070                         retrycnt = RT2661_TX_RETRYCNT(val);
1071                         DPRINTFN(10, ("data frame sent successfully after "
1072                             "%d retries\n", retrycnt));
1073                         break;
1074
1075                 case RT2661_TX_RETRY_FAIL:
1076                         DPRINTFN(9, ("sending data frame failed (too much "
1077                             "retries)\n"));
1078                         break;
1079
1080                 default:
1081                         /* other failure */
1082                         device_printf(sc->sc_dev,
1083                             "sending data frame failed 0x%08x\n", val);
1084                         break;
1085                 }
1086
1087                 res.rc_res_rateidx = rctl->rateidx;
1088                 res.rc_res_tries = retrycnt + 1;
1089                 ieee80211_ratectl_tx_complete(rctl->ni, rctl->len, &res, 1,
1090                         retrycnt, 0, result != RT2661_TX_SUCCESS);
1091
1092                 ieee80211_free_node(rctl->ni);
1093                 rctl->ni = NULL;
1094                 kfree(rctl, M_RT2661);
1095         }
1096 }
1097
1098 static void
1099 rt2661_tx_dma_intr(struct rt2661_softc *sc, struct rt2661_tx_ring *txq)
1100 {
1101         struct rt2661_tx_desc *desc;
1102         struct rt2661_data *data;
1103
1104         bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_POSTREAD);
1105
1106         for (;;) {
1107                 desc = &txq->desc[txq->next];
1108                 data = &txq->data[txq->next];
1109
1110                 if ((le32toh(desc->flags) & RT2661_TX_BUSY) ||
1111                     !(le32toh(desc->flags) & RT2661_TX_VALID))
1112                         break;
1113
1114                 bus_dmamap_sync(txq->data_dmat, data->map,
1115                     BUS_DMASYNC_POSTWRITE);
1116                 bus_dmamap_unload(txq->data_dmat, data->map);
1117                 m_freem(data->m);
1118                 data->m = NULL;
1119
1120                 /* descriptor is no longer valid */
1121                 desc->flags &= ~htole32(RT2661_TX_VALID);
1122
1123                 DPRINTFN(15, ("tx dma done q=%p idx=%u\n", txq, txq->next));
1124
1125                 txq->queued--;
1126                 if (++txq->next >= txq->count)  /* faster than % count */
1127                         txq->next = 0;
1128         }
1129
1130         bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1131
1132         if (txq->queued < txq->count) {
1133                 struct ifnet *ifp = &sc->sc_ic.ic_if;
1134
1135                 sc->sc_tx_timer = 0;
1136                 ifp->if_flags &= ~IFF_OACTIVE;
1137                 rt2661_start(ifp);
1138         }
1139 }
1140
1141 static void
1142 rt2661_rx_intr(struct rt2661_softc *sc)
1143 {
1144         struct ieee80211com *ic = &sc->sc_ic;
1145         struct ifnet *ifp = ic->ic_ifp;
1146         struct rt2661_rx_desc *desc;
1147         struct rt2661_data *data;
1148         bus_addr_t physaddr;
1149         struct ieee80211_frame_min *wh;
1150         struct ieee80211_node *ni;
1151         struct mbuf *mnew, *m;
1152         int error;
1153
1154         bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1155             BUS_DMASYNC_POSTREAD);
1156
1157         for (;;) {
1158                 uint32_t flags;
1159                 int rssi;
1160
1161                 desc = &sc->rxq.desc[sc->rxq.cur];
1162                 data = &sc->rxq.data[sc->rxq.cur];
1163                 flags = le32toh(desc->flags);
1164
1165                 if (flags & RT2661_RX_BUSY)
1166                         break;
1167
1168                 if (flags & RT2661_RX_CRC_ERROR) {
1169                         /*
1170                          * This should not happen since we did not request
1171                          * to receive those frames when we filled TXRX_CSR0.
1172                          */
1173                         DPRINTFN(5, ("CRC error flags 0x%08x\n", flags));
1174                         ifp->if_ierrors++;
1175                         goto skip;
1176                 }
1177
1178                 if (flags & RT2661_RX_CIPHER_MASK) {
1179                         DPRINTFN(5, ("cipher error 0x%08x\n", flags));
1180                         ifp->if_ierrors++;
1181                         goto skip;
1182                 }
1183
1184                 /*
1185                  * Try to allocate a new mbuf for this ring element and load it
1186                  * before processing the current mbuf. If the ring element
1187                  * cannot be loaded, drop the received packet and reuse the old
1188                  * mbuf. In the unlikely case that the old mbuf can't be
1189                  * reloaded either, explicitly panic.
1190                  */
1191                 mnew = m_getcl(MB_DONTWAIT, MT_DATA, M_PKTHDR);
1192                 if (mnew == NULL) {
1193                         ifp->if_ierrors++;
1194                         goto skip;
1195                 }
1196
1197                 bus_dmamap_sync(sc->rxq.data_dmat, data->map,
1198                     BUS_DMASYNC_POSTREAD);
1199                 bus_dmamap_unload(sc->rxq.data_dmat, data->map);
1200
1201                 error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1202                     mtod(mnew, void *), MCLBYTES, rt2661_dma_map_addr,
1203                     &physaddr, 0);
1204                 if (error != 0) {
1205                         m_freem(mnew);
1206
1207                         /* try to reload the old mbuf */
1208                         error = bus_dmamap_load(sc->rxq.data_dmat, data->map,
1209                             mtod(data->m, void *), MCLBYTES,
1210                             rt2661_dma_map_addr, &physaddr, 0);
1211                         if (error != 0) {
1212                                 /* very unlikely that it will fail... */
1213                                 panic("%s: could not load old rx mbuf",
1214                                     device_get_name(sc->sc_dev));
1215                         }
1216                         ifp->if_ierrors++;
1217                         goto skip;
1218                 }
1219
1220                 /*
1221                  * New mbuf successfully loaded, update Rx ring and continue
1222                  * processing.
1223                  */
1224                 m = data->m;
1225                 data->m = mnew;
1226                 desc->physaddr = htole32(physaddr);
1227
1228                 /* finalize mbuf */
1229                 m->m_pkthdr.rcvif = ifp;
1230                 m->m_pkthdr.len = m->m_len = (flags >> 16) & 0xfff;
1231
1232                 rssi = rt2661_get_rssi(sc, desc->rssi);
1233
1234                 wh = mtod(m, struct ieee80211_frame_min *);
1235                 if (wh->i_fc[1] & IEEE80211_FC1_WEP)
1236                         DPRINTFN(5, ("keyix %d\n", RT2661_RX_KEYIX(flags)));
1237
1238                 ni = ieee80211_find_rxnode(ic, wh);
1239
1240                 /* Error happened during RSSI conversion. */
1241                 if (rssi < 0)
1242                         rssi = ni->ni_rssi;
1243
1244                 if (sc->sc_drvbpf != NULL) {
1245                         struct rt2661_rx_radiotap_header *tap = &sc->sc_rxtap;
1246                         uint32_t tsf_lo, tsf_hi;
1247
1248                         /* get timestamp (low and high 32 bits) */
1249                         tsf_hi = RAL_READ(sc, RT2661_TXRX_CSR13);
1250                         tsf_lo = RAL_READ(sc, RT2661_TXRX_CSR12);
1251
1252                         tap->wr_tsf =
1253                             htole64(((uint64_t)tsf_hi << 32) | tsf_lo);
1254                         tap->wr_flags = 0;
1255                         tap->wr_rate = rt2661_rxrate(desc);
1256                         tap->wr_chan_freq = htole16(ic->ic_curchan->ic_freq);
1257                         tap->wr_chan_flags = htole16(ic->ic_curchan->ic_flags);
1258                         tap->wr_antsignal = rssi;
1259
1260                         bpf_ptap(sc->sc_drvbpf, m, tap, sc->sc_rxtap_len);
1261                 }
1262
1263                 /* send the frame to the 802.11 layer */
1264                 if (RT2661_RX_CIPHER(flags) != RT2661_CIPHER_NONE) {
1265                         struct ieee80211_crypto_iv iv;
1266
1267                         memcpy(iv.ic_iv, desc->iv, sizeof(iv.ic_iv));
1268                         memcpy(iv.ic_eiv, desc->eiv, sizeof(iv.ic_eiv));
1269                         ieee80211_input_withiv(ic, m, ni, rssi, 0, &iv);
1270                 } else {
1271                         ieee80211_input(ic, m, ni, rssi, 0);
1272                 }
1273
1274                 /* node is no longer needed */
1275                 ieee80211_free_node(ni);
1276
1277 skip:           desc->flags |= htole32(RT2661_RX_BUSY);
1278
1279                 DPRINTFN(15, ("rx intr idx=%u\n", sc->rxq.cur));
1280
1281                 sc->rxq.cur = (sc->rxq.cur + 1) % RT2661_RX_RING_COUNT;
1282         }
1283
1284         bus_dmamap_sync(sc->rxq.desc_dmat, sc->rxq.desc_map,
1285             BUS_DMASYNC_PREWRITE);
1286 }
1287
1288 /* ARGSUSED */
1289 static void
1290 rt2661_mcu_beacon_expire(struct rt2661_softc *sc)
1291 {
1292         /* do nothing */
1293 }
1294
1295 static void
1296 rt2661_mcu_wakeup(struct rt2661_softc *sc)
1297 {
1298         RAL_WRITE(sc, RT2661_MAC_CSR11, 5 << 16);
1299
1300         RAL_WRITE(sc, RT2661_SOFT_RESET_CSR, 0x7);
1301         RAL_WRITE(sc, RT2661_IO_CNTL_CSR, 0x18);
1302         RAL_WRITE(sc, RT2661_PCI_USEC_CSR, 0x20);
1303
1304         /* send wakeup command to MCU */
1305         rt2661_tx_cmd(sc, RT2661_MCU_CMD_WAKEUP, 0);
1306 }
1307
1308 static void
1309 rt2661_mcu_cmd_intr(struct rt2661_softc *sc)
1310 {
1311         RAL_READ(sc, RT2661_M2H_CMD_DONE_CSR);
1312         RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
1313 }
1314
1315 static void
1316 rt2661_intr(void *arg)
1317 {
1318         struct rt2661_softc *sc = arg;
1319         struct ifnet *ifp = &sc->sc_ic.ic_if;
1320         uint32_t r1, r2;
1321
1322         /* disable MAC and MCU interrupts */
1323         RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffff7f);
1324         RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
1325
1326         /* don't re-enable interrupts if we're shutting down */
1327         if (!(ifp->if_flags & IFF_RUNNING))
1328                 return;
1329
1330         r1 = RAL_READ(sc, RT2661_INT_SOURCE_CSR);
1331         RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, r1);
1332
1333         r2 = RAL_READ(sc, RT2661_MCU_INT_SOURCE_CSR);
1334         RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, r2);
1335
1336         if (r1 & RT2661_MGT_DONE)
1337                 rt2661_tx_dma_intr(sc, &sc->mgtq);
1338
1339         if (r1 & RT2661_RX_DONE)
1340                 rt2661_rx_intr(sc);
1341
1342         if (r1 & RT2661_TX0_DMA_DONE)
1343                 rt2661_tx_dma_intr(sc, &sc->txq[0]);
1344
1345         if (r1 & RT2661_TX1_DMA_DONE)
1346                 rt2661_tx_dma_intr(sc, &sc->txq[1]);
1347
1348         if (r1 & RT2661_TX2_DMA_DONE)
1349                 rt2661_tx_dma_intr(sc, &sc->txq[2]);
1350
1351         if (r1 & RT2661_TX3_DMA_DONE)
1352                 rt2661_tx_dma_intr(sc, &sc->txq[3]);
1353
1354         if (r1 & RT2661_TX_DONE)
1355                 rt2661_tx_intr(sc);
1356
1357         if (r2 & RT2661_MCU_CMD_DONE)
1358                 rt2661_mcu_cmd_intr(sc);
1359
1360         if (r2 & RT2661_MCU_BEACON_EXPIRE)
1361                 rt2661_mcu_beacon_expire(sc);
1362
1363         if (r2 & RT2661_MCU_WAKEUP)
1364                 rt2661_mcu_wakeup(sc);
1365
1366         /* re-enable MAC and MCU interrupts */
1367         RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
1368         RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
1369 }
1370
1371 /* quickly determine if a given rate is CCK or OFDM */
1372 #define RAL_RATE_IS_OFDM(rate) ((rate) >= 12 && (rate) != 22)
1373
1374 #define RAL_ACK_SIZE    (sizeof(struct ieee80211_frame_ack) + IEEE80211_CRC_LEN)
1375 #define RAL_CTS_SIZE    (sizeof(struct ieee80211_frame_cts) + IEEE80211_CRC_LEN)
1376
1377 /*
1378  * This function is only used by the Rx radiotap code. It returns the rate at
1379  * which a given frame was received.
1380  */
1381 static uint8_t
1382 rt2661_rxrate(struct rt2661_rx_desc *desc)
1383 {
1384         if (le32toh(desc->flags) & RT2661_RX_OFDM) {
1385                 /* reverse function of rt2661_plcp_signal */
1386                 switch (desc->rate & 0xf) {
1387                 case 0xb:       return 12;
1388                 case 0xf:       return 18;
1389                 case 0xa:       return 24;
1390                 case 0xe:       return 36;
1391                 case 0x9:       return 48;
1392                 case 0xd:       return 72;
1393                 case 0x8:       return 96;
1394                 case 0xc:       return 108;
1395                 }
1396         } else {
1397                 if (desc->rate == 10)
1398                         return 2;
1399                 if (desc->rate == 20)
1400                         return 4;
1401                 if (desc->rate == 55)
1402                         return 11;
1403                 if (desc->rate == 110)
1404                         return 22;
1405         }
1406         return 2;       /* should not get there */
1407 }
1408
1409 static uint8_t
1410 rt2661_plcp_signal(int rate)
1411 {
1412         switch (rate) {
1413         /* CCK rates (returned values are device-dependent) */
1414         case 2:         return 0x0;
1415         case 4:         return 0x1;
1416         case 11:        return 0x2;
1417         case 22:        return 0x3;
1418
1419         /* OFDM rates (cf IEEE Std 802.11a-1999, pp. 14 Table 80) */
1420         case 12:        return 0xb;
1421         case 18:        return 0xf;
1422         case 24:        return 0xa;
1423         case 36:        return 0xe;
1424         case 48:        return 0x9;
1425         case 72:        return 0xd;
1426         case 96:        return 0x8;
1427         case 108:       return 0xc;
1428
1429         /* unsupported rates (should not get there) */
1430         default:        return 0xff;
1431         }
1432 }
1433
1434 static void
1435 rt2661_setup_tx_desc(struct rt2661_softc *sc, struct rt2661_tx_desc *desc,
1436     uint32_t flags, uint16_t xflags, int len, int rate,
1437     const bus_dma_segment_t *segs, int nsegs, int ac, int ratectl,
1438     const struct ieee80211_key *key, void *buf,
1439     const struct ieee80211_crypto_iv *iv)
1440 {
1441         const struct ieee80211_cipher *cip = NULL;
1442         struct ieee80211com *ic = &sc->sc_ic;
1443         uint16_t plcp_length;
1444         int i, remainder;
1445
1446         if (key != NULL)
1447                 cip = key->wk_cipher;
1448
1449         desc->flags = htole32(flags);
1450         desc->flags |= htole32(len << 16);
1451         desc->flags |= htole32(RT2661_TX_VALID);
1452         if (key != NULL) {
1453                 int cipher = rt2661_cipher(key);
1454
1455                 desc->flags |= htole32(cipher << 29);
1456                 desc->flags |= htole32(key->wk_keyix << 10);
1457                 if (key->wk_keyix >= IEEE80211_WEP_NKID)
1458                         desc->flags |= htole32(RT2661_TX_PAIRWISE_KEY);
1459
1460                 /* XXX fragmentation */
1461                 desc->flags |= htole32(RT2661_TX_HWMIC);
1462         }
1463
1464         desc->xflags = htole16(xflags);
1465         desc->xflags |= htole16(nsegs << 13);
1466         if (key != NULL) {
1467                 int hdrsize;
1468
1469                 hdrsize = ieee80211_hdrspace(ic, buf);
1470                 desc->xflags |= htole16(hdrsize);
1471         }
1472
1473         desc->wme = htole16(
1474             RT2661_QID(ac) |
1475             RT2661_AIFSN(2) |
1476             RT2661_LOGCWMIN(4) |
1477             RT2661_LOGCWMAX(10));
1478
1479         if (key != NULL && iv != NULL) {
1480                 memcpy(desc->iv, iv->ic_iv, sizeof(desc->iv));
1481                 memcpy(desc->eiv, iv->ic_eiv, sizeof(desc->eiv));
1482         }
1483
1484         /*
1485          * Remember whether TX rate control information should be gathered.
1486          * This field is driver private data only.  It will be made available
1487          * by the NIC in STA_CSR4 on Tx done interrupts.
1488          */
1489         desc->qid = ratectl;
1490
1491         /* setup PLCP fields */
1492         desc->plcp_signal  = rt2661_plcp_signal(rate);
1493         desc->plcp_service = 4;
1494
1495         len += IEEE80211_CRC_LEN;
1496         if (cip != NULL) {
1497                 len += cip->ic_header + cip->ic_trailer;
1498
1499                 /* XXX fragmentation */
1500                 len += cip->ic_miclen;
1501         }
1502
1503         if (RAL_RATE_IS_OFDM(rate)) {
1504                 desc->flags |= htole32(RT2661_TX_OFDM);
1505
1506                 plcp_length = len & 0xfff;
1507                 desc->plcp_length_hi = plcp_length >> 6;
1508                 desc->plcp_length_lo = plcp_length & 0x3f;
1509         } else {
1510                 plcp_length = (16 * len + rate - 1) / rate;
1511                 if (rate == 22) {
1512                         remainder = (16 * len) % 22;
1513                         if (remainder != 0 && remainder < 7)
1514                                 desc->plcp_service |= RT2661_PLCP_LENGEXT;
1515                 }
1516                 desc->plcp_length_hi = plcp_length >> 8;
1517                 desc->plcp_length_lo = plcp_length & 0xff;
1518
1519                 if (rate != 2 && (ic->ic_flags & IEEE80211_F_SHPREAMBLE))
1520                         desc->plcp_signal |= 0x08;
1521         }
1522
1523         /* RT2x61 supports scatter with up to 5 segments */
1524         for (i = 0; i < nsegs; i++) {
1525                 desc->addr[i] = htole32(segs[i].ds_addr);
1526                 desc->len [i] = htole16(segs[i].ds_len);
1527         }
1528
1529         desc->flags |= htole32(RT2661_TX_BUSY);
1530 }
1531
1532 static int
1533 rt2661_tx_mgt(struct rt2661_softc *sc, struct mbuf *m0,
1534     struct ieee80211_node *ni)
1535 {
1536         struct ieee80211com *ic = &sc->sc_ic;
1537         struct rt2661_tx_desc *desc;
1538         struct rt2661_data *data;
1539         struct ieee80211_frame *wh;
1540         struct rt2661_dmamap map;
1541         uint16_t dur;
1542         uint32_t flags = 0;     /* XXX HWSEQ */
1543         int rate, error;
1544
1545         desc = &sc->mgtq.desc[sc->mgtq.cur];
1546         data = &sc->mgtq.data[sc->mgtq.cur];
1547
1548         /* send mgt frames at the lowest available rate */
1549         rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1550
1551         error = bus_dmamap_load_mbuf(sc->mgtq.data_dmat, data->map, m0,
1552                                      rt2661_dma_map_mbuf, &map, 0);
1553         if (error != 0) {
1554                 device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1555                     error);
1556                 ieee80211_free_node(ni);
1557                 m_freem(m0);
1558                 return error;
1559         }
1560
1561         if (sc->sc_drvbpf != NULL) {
1562                 struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1563
1564                 tap->wt_flags = 0;
1565                 tap->wt_rate = rate;
1566                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1567                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1568
1569                 bpf_ptap(sc->sc_drvbpf, m0, tap, sc->sc_txtap_len);
1570         }
1571
1572         data->m = m0;
1573
1574         wh = mtod(m0, struct ieee80211_frame *);
1575
1576         if (!IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1577                 flags |= RT2661_TX_NEED_ACK;
1578
1579                 dur = ieee80211_txtime(ni, RAL_ACK_SIZE, rate, ic->ic_flags) +
1580                       sc->sc_sifs;
1581                 *(uint16_t *)wh->i_dur = htole16(dur);
1582
1583                 /* tell hardware to add timestamp in probe responses */
1584                 if ((wh->i_fc[0] &
1585                     (IEEE80211_FC0_TYPE_MASK | IEEE80211_FC0_SUBTYPE_MASK)) ==
1586                     (IEEE80211_FC0_TYPE_MGT | IEEE80211_FC0_SUBTYPE_PROBE_RESP))
1587                         flags |= RT2661_TX_TIMESTAMP;
1588         }
1589
1590         rt2661_setup_tx_desc(sc, desc, flags, 0 /* XXX HWSEQ */,
1591             m0->m_pkthdr.len, rate, map.segs, map.nseg, RT2661_QID_MGT, 0, NULL, NULL, NULL);
1592
1593         bus_dmamap_sync(sc->mgtq.data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1594         bus_dmamap_sync(sc->mgtq.desc_dmat, sc->mgtq.desc_map,
1595             BUS_DMASYNC_PREWRITE);
1596
1597         DPRINTFN(10, ("sending mgt frame len=%u idx=%u rate=%u\n",
1598             m0->m_pkthdr.len, sc->mgtq.cur, rate));
1599
1600         /* kick mgt */
1601         sc->mgtq.queued++;
1602         sc->mgtq.cur = (sc->mgtq.cur + 1) % RT2661_MGT_RING_COUNT;
1603         RAL_WRITE(sc, RT2661_TX_CNTL_CSR, RT2661_KICK_MGT);
1604
1605         ieee80211_free_node(ni);
1606
1607         return 0;
1608 }
1609
1610 /*
1611  * Build a RTS control frame.
1612  */
1613 static struct mbuf *
1614 rt2661_get_rts(struct rt2661_softc *sc, struct ieee80211_frame *wh,
1615     uint16_t dur)
1616 {
1617         struct ieee80211_frame_rts *rts;
1618         struct mbuf *m;
1619
1620         MGETHDR(m, MB_DONTWAIT, MT_DATA);
1621         if (m == NULL) {
1622                 sc->sc_ic.ic_stats.is_tx_nobuf++;
1623                 device_printf(sc->sc_dev, "could not allocate RTS frame\n");
1624                 return NULL;
1625         }
1626
1627         rts = mtod(m, struct ieee80211_frame_rts *);
1628
1629         rts->i_fc[0] = IEEE80211_FC0_VERSION_0 | IEEE80211_FC0_TYPE_CTL |
1630             IEEE80211_FC0_SUBTYPE_RTS;
1631         rts->i_fc[1] = IEEE80211_FC1_DIR_NODS;
1632         *(uint16_t *)rts->i_dur = htole16(dur);
1633         IEEE80211_ADDR_COPY(rts->i_ra, wh->i_addr1);
1634         IEEE80211_ADDR_COPY(rts->i_ta, wh->i_addr2);
1635
1636         m->m_pkthdr.len = m->m_len = sizeof (struct ieee80211_frame_rts);
1637
1638         return m;
1639 }
1640
1641 static int
1642 rt2661_tx_data(struct rt2661_softc *sc, struct mbuf *m0,
1643     struct ieee80211_node *ni, int ac)
1644 {
1645         struct ieee80211com *ic = &sc->sc_ic;
1646         struct rt2661_tx_ring *txq = &sc->txq[ac];
1647         struct rt2661_tx_desc *desc;
1648         struct rt2661_data *data;
1649         struct rt2661_tx_ratectl *rctl;
1650         struct ieee80211_frame *wh;
1651         struct ieee80211_key *k = NULL;
1652         const struct chanAccParams *cap;
1653         struct mbuf *mnew;
1654         struct rt2661_dmamap map;
1655         uint16_t dur;
1656         uint32_t flags = 0;
1657         int error, rate, ackrate, noack = 0, rateidx;
1658         struct ieee80211_crypto_iv iv, *ivp = NULL;
1659
1660         wh = mtod(m0, struct ieee80211_frame *);
1661         if (wh->i_fc[0] & IEEE80211_FC0_SUBTYPE_QOS) {
1662                 cap = &ic->ic_wme.wme_chanParams;
1663                 noack = cap->cap_wmeParams[ac].wmep_noackPolicy;
1664         }
1665
1666         if (wh->i_fc[1] & IEEE80211_FC1_WEP) {
1667                 k = ieee80211_crypto_findkey(ic, ni, m0);
1668                 if (k == NULL) {
1669                         m_freem(m0);
1670                         return ENOBUFS;
1671                 }
1672
1673                 if (k->wk_flags & IEEE80211_KEY_SWCRYPT) {
1674                         k = ieee80211_crypto_encap_withkey(ic, m0, k);
1675                 } else {
1676                         k = ieee80211_crypto_getiv(ic, &iv, k);
1677                         ivp = &iv;
1678                 }
1679                 if (k == NULL) {
1680                         m_freem(m0);
1681                         return ENOBUFS;
1682                 }
1683
1684                 if (ivp == NULL)
1685                         k = NULL;
1686
1687                 /* packet header may have moved, reset our local pointer */
1688                 wh = mtod(m0, struct ieee80211_frame *);
1689         }
1690
1691         ieee80211_ratectl_findrate(ni, m0->m_pkthdr.len, &rateidx, 1);
1692         rate = IEEE80211_RS_RATE(&ni->ni_rates, rateidx);
1693
1694         ackrate = ieee80211_ack_rate(ni, rate);
1695
1696         /*
1697          * IEEE Std 802.11-1999, pp 82: "A STA shall use an RTS/CTS exchange
1698          * for directed frames only when the length of the MPDU is greater
1699          * than the length threshold indicated by [...]" ic_rtsthreshold.
1700          */
1701         if (!IEEE80211_IS_MULTICAST(wh->i_addr1) &&
1702             m0->m_pkthdr.len > ic->ic_rtsthreshold) {
1703                 struct mbuf *m;
1704                 uint16_t dur;
1705                 int rtsrate;
1706
1707                 rtsrate = IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan) ? 12 : 2;
1708
1709                 /* XXX: noack (QoS)? */
1710                 dur = ieee80211_txtime(ni, m0->m_pkthdr.len + IEEE80211_CRC_LEN,
1711                                        rate, ic->ic_flags) +
1712                       ieee80211_txtime(ni, RAL_CTS_SIZE, rtsrate, ic->ic_flags)+
1713                       ieee80211_txtime(ni, RAL_ACK_SIZE, ackrate, ic->ic_flags)+
1714                       3 * sc->sc_sifs;
1715
1716                 m = rt2661_get_rts(sc, wh, dur);
1717
1718                 desc = &txq->desc[txq->cur];
1719                 data = &txq->data[txq->cur];
1720
1721                 error = bus_dmamap_load_mbuf(txq->data_dmat, data->map, m,
1722                                              rt2661_dma_map_mbuf, &map, 0);
1723                 if (error != 0) {
1724                         device_printf(sc->sc_dev,
1725                             "could not map mbuf (error %d)\n", error);
1726                         m_freem(m);
1727                         m_freem(m0);
1728                         return error;
1729                 }
1730
1731                 data->m = m;
1732
1733                 rt2661_setup_tx_desc(sc, desc, RT2661_TX_NEED_ACK |
1734                                      RT2661_TX_MORE_FRAG, 0, m->m_pkthdr.len,
1735                                      rtsrate, map.segs, map.nseg, ac, 0, NULL, NULL, NULL);
1736
1737                 bus_dmamap_sync(txq->data_dmat, data->map,
1738                     BUS_DMASYNC_PREWRITE);
1739
1740                 txq->queued++;
1741                 txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1742
1743                 /*
1744                  * IEEE Std 802.11-1999: when an RTS/CTS exchange is used, the
1745                  * asynchronous data frame shall be transmitted after the CTS
1746                  * frame and a SIFS period.
1747                  */
1748                 flags |= RT2661_TX_LONG_RETRY | RT2661_TX_IFS;
1749         }
1750
1751         data = &txq->data[txq->cur];
1752         desc = &txq->desc[txq->cur];
1753
1754         error = bus_dmamap_load_mbuf(txq->data_dmat, data->map, m0,
1755                                      rt2661_dma_map_mbuf, &map, 0);
1756         if (error != 0 && error != EFBIG) {
1757                 device_printf(sc->sc_dev, "could not map mbuf (error %d)\n",
1758                     error);
1759                 m_freem(m0);
1760                 return error;
1761         }
1762         if (error != 0) {
1763                 mnew = m_defrag(m0, MB_DONTWAIT);
1764                 if (mnew == NULL) {
1765                         device_printf(sc->sc_dev,
1766                             "could not defragment mbuf\n");
1767                         m_freem(m0);
1768                         return ENOBUFS;
1769                 }
1770                 m0 = mnew;
1771
1772                 error = bus_dmamap_load_mbuf(txq->data_dmat, data->map, m0,
1773                                              rt2661_dma_map_mbuf, &map, 0);
1774                 if (error != 0) {
1775                         device_printf(sc->sc_dev,
1776                             "could not map mbuf (error %d)\n", error);
1777                         m_freem(m0);
1778                         return error;
1779                 }
1780
1781                 /* packet header have moved, reset our local pointer */
1782                 wh = mtod(m0, struct ieee80211_frame *);
1783         }
1784
1785         if (sc->sc_drvbpf != NULL) {
1786                 struct rt2661_tx_radiotap_header *tap = &sc->sc_txtap;
1787
1788                 tap->wt_flags = 0;
1789                 tap->wt_rate = rate;
1790                 tap->wt_chan_freq = htole16(ic->ic_curchan->ic_freq);
1791                 tap->wt_chan_flags = htole16(ic->ic_curchan->ic_flags);
1792
1793                 bpf_ptap(sc->sc_drvbpf, m0, tap, sc->sc_txtap_len);
1794         }
1795
1796         data->m = m0;
1797
1798         rctl = kmalloc(sizeof(*rctl), M_RT2661, M_NOWAIT);
1799         if (rctl != NULL) {
1800                 rctl->ni = ni;
1801                 rctl->len = m0->m_pkthdr.len;
1802                 rctl->rateidx = rateidx;
1803                 STAILQ_INSERT_TAIL(&sc->tx_ratectl, rctl, link);
1804         }
1805
1806         if (!noack && !IEEE80211_IS_MULTICAST(wh->i_addr1)) {
1807                 flags |= RT2661_TX_NEED_ACK;
1808
1809                 dur = ieee80211_txtime(ni, RAL_ACK_SIZE, ackrate, ic->ic_flags)+
1810                       sc->sc_sifs;
1811                 *(uint16_t *)wh->i_dur = htole16(dur);
1812         }
1813
1814         rt2661_setup_tx_desc(sc, desc, flags, 0, m0->m_pkthdr.len, rate,
1815                              map.segs, map.nseg, ac, rctl != NULL, k, wh, ivp);
1816
1817         bus_dmamap_sync(txq->data_dmat, data->map, BUS_DMASYNC_PREWRITE);
1818         bus_dmamap_sync(txq->desc_dmat, txq->desc_map, BUS_DMASYNC_PREWRITE);
1819
1820         DPRINTFN(10, ("sending data frame len=%u idx=%u rate=%u\n",
1821             m0->m_pkthdr.len, txq->cur, rate));
1822
1823         /* kick Tx */
1824         txq->queued++;
1825         txq->cur = (txq->cur + 1) % RT2661_TX_RING_COUNT;
1826         RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 1 << ac);
1827
1828         if (rctl == NULL)
1829                 ieee80211_free_node(ni);
1830
1831         return 0;
1832 }
1833
1834 static void
1835 rt2661_start(struct ifnet *ifp)
1836 {
1837         struct rt2661_softc *sc = ifp->if_softc;
1838         struct ieee80211com *ic = &sc->sc_ic;
1839         struct mbuf *m0;
1840         struct ether_header *eh;
1841         struct ieee80211_node *ni;
1842         int ac;
1843
1844         /* prevent management frames from being sent if we're not ready */
1845         if (!(ifp->if_flags & IFF_RUNNING))
1846                 return;
1847
1848         for (;;) {
1849                 IF_POLL(&ic->ic_mgtq, m0);
1850                 if (m0 != NULL) {
1851                         if (sc->mgtq.queued >= RT2661_MGT_RING_COUNT) {
1852                                 ifp->if_flags |= IFF_OACTIVE;
1853                                 break;
1854                         }
1855                         IF_DEQUEUE(&ic->ic_mgtq, m0);
1856
1857                         ni = (struct ieee80211_node *)m0->m_pkthdr.rcvif;
1858                         m0->m_pkthdr.rcvif = NULL;
1859
1860                         if (ic->ic_rawbpf != NULL)
1861                                 bpf_mtap(ic->ic_rawbpf, m0);
1862
1863                         if (rt2661_tx_mgt(sc, m0, ni) != 0)
1864                                 break;
1865                 } else {
1866                         if (ic->ic_state != IEEE80211_S_RUN)
1867                                 break;
1868
1869                         m0 = ifq_dequeue(&ifp->if_snd, NULL);
1870                         if (m0 == NULL)
1871                                 break;
1872
1873                         if (m0->m_len < sizeof (struct ether_header) &&
1874                             !(m0 = m_pullup(m0, sizeof (struct ether_header))))
1875                                 continue;
1876
1877                         eh = mtod(m0, struct ether_header *);
1878                         ni = ieee80211_find_txnode(ic, eh->ether_dhost);
1879                         if (ni == NULL) {
1880                                 m_freem(m0);
1881                                 ifp->if_oerrors++;
1882                                 continue;
1883                         }
1884
1885                         /* classify mbuf so we can find which tx ring to use */
1886                         if (ieee80211_classify(ic, m0, ni) != 0) {
1887                                 m_freem(m0);
1888                                 ieee80211_free_node(ni);
1889                                 ifp->if_oerrors++;
1890                                 continue;
1891                         }
1892
1893                         /* no QoS encapsulation for EAPOL frames */
1894                         ac = (eh->ether_type != htons(ETHERTYPE_PAE)) ?
1895                             M_WME_GETAC(m0) : WME_AC_BE;
1896
1897                         if (sc->txq[ac].queued >= RT2661_TX_RING_COUNT - 1) {
1898                                 /* there is no place left in this ring */
1899                                 ifp->if_flags |= IFF_OACTIVE;
1900                                 m_freem(m0);
1901                                 ieee80211_free_node(ni);
1902                                 break;
1903                         }
1904
1905                         BPF_MTAP(ifp, m0);
1906
1907                         m0 = ieee80211_encap(ic, m0, ni);
1908                         if (m0 == NULL) {
1909                                 ieee80211_free_node(ni);
1910                                 ifp->if_oerrors++;
1911                                 continue;
1912                         }
1913
1914                         if (ic->ic_rawbpf != NULL)
1915                                 bpf_mtap(ic->ic_rawbpf, m0);
1916
1917                         if (rt2661_tx_data(sc, m0, ni, ac) != 0) {
1918                                 ieee80211_free_node(ni);
1919                                 ifp->if_oerrors++;
1920                                 break;
1921                         }
1922                 }
1923
1924                 sc->sc_tx_timer = 5;
1925                 ifp->if_timer = 1;
1926         }
1927 }
1928
1929 static void
1930 rt2661_watchdog(struct ifnet *ifp)
1931 {
1932         struct rt2661_softc *sc = ifp->if_softc;
1933         struct ieee80211com *ic = &sc->sc_ic;
1934
1935         ifp->if_timer = 0;
1936
1937         if (sc->sc_tx_timer > 0) {
1938                 if (--sc->sc_tx_timer == 0) {
1939                         device_printf(sc->sc_dev, "device timeout\n");
1940                         rt2661_init(sc);
1941                         ifp->if_oerrors++;
1942                         return;
1943                 }
1944                 ifp->if_timer = 1;
1945         }
1946
1947         ieee80211_watchdog(ic);
1948 }
1949
1950 /*
1951  * This function allows for fast channel switching in monitor mode (used by
1952  * net-mgmt/kismet). In IBSS mode, we must explicitly reset the interface to
1953  * generate a new beacon frame.
1954  */
1955 static int
1956 rt2661_reset(struct ifnet *ifp)
1957 {
1958         struct rt2661_softc *sc = ifp->if_softc;
1959         struct ieee80211com *ic = &sc->sc_ic;
1960
1961         if (ic->ic_opmode != IEEE80211_M_MONITOR)
1962                 return ENETRESET;
1963
1964         rt2661_set_chan(sc, ic->ic_curchan);
1965
1966         return 0;
1967 }
1968
1969 static int
1970 rt2661_ioctl(struct ifnet *ifp, u_long cmd, caddr_t data, struct ucred *cr)
1971 {
1972         struct rt2661_softc *sc = ifp->if_softc;
1973         struct ieee80211com *ic = &sc->sc_ic;
1974         int error = 0;
1975
1976         switch (cmd) {
1977         case SIOCSIFFLAGS:
1978                 if (ifp->if_flags & IFF_UP) {
1979                         if (ifp->if_flags & IFF_RUNNING)
1980                                 rt2661_update_promisc(sc);
1981                         else
1982                                 rt2661_init(sc);
1983                 } else {
1984                         if (ifp->if_flags & IFF_RUNNING)
1985                                 rt2661_stop(sc);
1986                 }
1987                 break;
1988
1989         default:
1990                 error = ieee80211_ioctl(ic, cmd, data, cr);
1991         }
1992
1993         if (error == ENETRESET) {
1994                 if ((ifp->if_flags & (IFF_UP | IFF_RUNNING)) ==
1995                     (IFF_UP | IFF_RUNNING) &&
1996                     (ic->ic_roaming != IEEE80211_ROAMING_MANUAL))
1997                         rt2661_init(sc);
1998                 error = 0;
1999         }
2000         return error;
2001 }
2002
2003 static void
2004 rt2661_bbp_write(struct rt2661_softc *sc, uint8_t reg, uint8_t val)
2005 {
2006         uint32_t tmp;
2007         int ntries;
2008
2009         for (ntries = 0; ntries < 100; ntries++) {
2010                 if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
2011                         break;
2012                 DELAY(1);
2013         }
2014         if (ntries == 100) {
2015                 device_printf(sc->sc_dev, "could not write to BBP\n");
2016                 return;
2017         }
2018
2019         tmp = RT2661_BBP_BUSY | (reg & 0x7f) << 8 | val;
2020         RAL_WRITE(sc, RT2661_PHY_CSR3, tmp);
2021
2022         DPRINTFN(15, ("BBP R%u <- 0x%02x\n", reg, val));
2023 }
2024
2025 static uint8_t
2026 rt2661_bbp_read(struct rt2661_softc *sc, uint8_t reg)
2027 {
2028         uint32_t val;
2029         int ntries;
2030
2031         for (ntries = 0; ntries < 100; ntries++) {
2032                 if (!(RAL_READ(sc, RT2661_PHY_CSR3) & RT2661_BBP_BUSY))
2033                         break;
2034                 DELAY(1);
2035         }
2036         if (ntries == 100) {
2037                 device_printf(sc->sc_dev, "could not read from BBP\n");
2038                 return 0;
2039         }
2040
2041         val = RT2661_BBP_BUSY | RT2661_BBP_READ | reg << 8;
2042         RAL_WRITE(sc, RT2661_PHY_CSR3, val);
2043
2044         for (ntries = 0; ntries < 100; ntries++) {
2045                 val = RAL_READ(sc, RT2661_PHY_CSR3);
2046                 if (!(val & RT2661_BBP_BUSY))
2047                         return val & 0xff;
2048                 DELAY(1);
2049         }
2050
2051         device_printf(sc->sc_dev, "could not read from BBP\n");
2052         return 0;
2053 }
2054
2055 static void
2056 rt2661_rf_write(struct rt2661_softc *sc, uint8_t reg, uint32_t val)
2057 {
2058         uint32_t tmp;
2059         int ntries;
2060
2061         for (ntries = 0; ntries < 100; ntries++) {
2062                 if (!(RAL_READ(sc, RT2661_PHY_CSR4) & RT2661_RF_BUSY))
2063                         break;
2064                 DELAY(1);
2065         }
2066         if (ntries == 100) {
2067                 device_printf(sc->sc_dev, "could not write to RF\n");
2068                 return;
2069         }
2070
2071         tmp = RT2661_RF_BUSY | RT2661_RF_21BIT | (val & 0x1fffff) << 2 |
2072             (reg & 3);
2073         RAL_WRITE(sc, RT2661_PHY_CSR4, tmp);
2074
2075         /* remember last written value in sc */
2076         sc->rf_regs[reg] = val;
2077
2078         DPRINTFN(15, ("RF R[%u] <- 0x%05x\n", reg & 3, val & 0x1fffff));
2079 }
2080
2081 static int
2082 rt2661_tx_cmd(struct rt2661_softc *sc, uint8_t cmd, uint16_t arg)
2083 {
2084         if (RAL_READ(sc, RT2661_H2M_MAILBOX_CSR) & RT2661_H2M_BUSY)
2085                 return EIO;     /* there is already a command pending */
2086
2087         RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR,
2088             RT2661_H2M_BUSY | RT2661_TOKEN_NO_INTR << 16 | arg);
2089
2090         RAL_WRITE(sc, RT2661_HOST_CMD_CSR, RT2661_KICK_CMD | cmd);
2091
2092         return 0;
2093 }
2094
2095 static void
2096 rt2661_select_antenna(struct rt2661_softc *sc)
2097 {
2098         uint8_t bbp4, bbp77;
2099         uint32_t tmp;
2100
2101         bbp4  = rt2661_bbp_read(sc,  4);
2102         bbp77 = rt2661_bbp_read(sc, 77);
2103
2104         /* TBD */
2105
2106         /* make sure Rx is disabled before switching antenna */
2107         tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2108         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2109
2110         rt2661_bbp_write(sc,  4, bbp4);
2111         rt2661_bbp_write(sc, 77, bbp77);
2112
2113         /* restore Rx filter */
2114         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2115 }
2116
2117 /*
2118  * Enable multi-rate retries for frames sent at OFDM rates.
2119  * In 802.11b/g mode, allow fallback to CCK rates.
2120  */
2121 static void
2122 rt2661_enable_mrr(struct rt2661_softc *sc)
2123 {
2124         struct ieee80211com *ic = &sc->sc_ic;
2125         uint32_t tmp;
2126
2127         tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
2128
2129         tmp &= ~RT2661_MRR_CCK_FALLBACK;
2130         if (!IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan))
2131                 tmp |= RT2661_MRR_CCK_FALLBACK;
2132         tmp |= RT2661_MRR_ENABLED;
2133         tmp |= RT2661_SRETRY_LIMIT(7) | RT2661_LRETRY_LIMIT(4);
2134
2135         RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
2136 }
2137
2138 static void
2139 rt2661_set_txpreamble(struct rt2661_softc *sc)
2140 {
2141         uint32_t tmp;
2142
2143         tmp = RAL_READ(sc, RT2661_TXRX_CSR4);
2144
2145         tmp &= ~RT2661_SHORT_PREAMBLE;
2146         if (sc->sc_ic.ic_flags & IEEE80211_F_SHPREAMBLE)
2147                 tmp |= RT2661_SHORT_PREAMBLE;
2148
2149         RAL_WRITE(sc, RT2661_TXRX_CSR4, tmp);
2150 }
2151
2152 static void
2153 rt2661_set_ackrates(struct rt2661_softc *sc, const struct ieee80211_rateset *rs)
2154 {
2155 #define RV(r)   ((r) & IEEE80211_RATE_VAL)
2156         struct ieee80211com *ic = &sc->sc_ic;
2157         uint32_t mask = 0;
2158         uint8_t rate;
2159         int i, j;
2160
2161         for (i = 0; i < rs->rs_nrates; i++) {
2162                 rate = rs->rs_rates[i];
2163
2164                 if (!(rate & IEEE80211_RATE_BASIC))
2165                         continue;
2166
2167                 /*
2168                  * Find h/w rate index.  We know it exists because the rate
2169                  * set has already been negotiated.
2170                  */
2171                 for (j = 0; rt2661_rateset_11g.rs_rates[j] != RV(rate); j++)
2172                         ; /* EMPTY */
2173
2174                 mask |= 1 << j;
2175         }
2176
2177         if (IEEE80211_IS_CHAN_2GHZ(ic->ic_curchan) &&
2178             ic->ic_curmode != IEEE80211_MODE_11B &&
2179             ieee80211_iserp_rateset(ic, rs)) {
2180                 /*
2181                  * Always set following rates as ACK rates to conform
2182                  * IEEE Std 802.11g-2003 clause 9.6
2183                  *
2184                  * 24Mbits/s    0x100
2185                  * 12Mbits/s    0x040
2186                  *  6Mbits/s    0x010
2187                  */
2188                 mask |= 0x150;
2189         }
2190
2191         RAL_WRITE(sc, RT2661_TXRX_CSR5, mask);
2192
2193         DPRINTF(("Setting ack rate mask to 0x%x\n", mask));
2194 #undef RV
2195 }
2196
2197 /*
2198  * Reprogram MAC/BBP to switch to a new band.  Values taken from the reference
2199  * driver.
2200  */
2201 static void
2202 rt2661_select_band(struct rt2661_softc *sc, struct ieee80211_channel *c)
2203 {
2204         uint8_t bbp17, bbp35, bbp96, bbp97, bbp98, bbp104;
2205         uint32_t tmp;
2206
2207         /* update all BBP registers that depend on the band */
2208         bbp17 = 0x20; bbp96 = 0x48; bbp104 = 0x2c;
2209         bbp35 = 0x50; bbp97 = 0x48; bbp98  = 0x48;
2210         if (IEEE80211_IS_CHAN_5GHZ(c)) {
2211                 bbp17 += 0x08; bbp96 += 0x10; bbp104 += 0x0c;
2212                 bbp35 += 0x10; bbp97 += 0x10; bbp98  += 0x10;
2213         }
2214         if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2215             (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2216                 bbp17 += 0x10; bbp96 += 0x10; bbp104 += 0x10;
2217         }
2218
2219         rt2661_bbp_write(sc,  17, bbp17);
2220         rt2661_bbp_write(sc,  96, bbp96);
2221         rt2661_bbp_write(sc, 104, bbp104);
2222
2223         if ((IEEE80211_IS_CHAN_2GHZ(c) && sc->ext_2ghz_lna) ||
2224             (IEEE80211_IS_CHAN_5GHZ(c) && sc->ext_5ghz_lna)) {
2225                 rt2661_bbp_write(sc, 75, 0x80);
2226                 rt2661_bbp_write(sc, 86, 0x80);
2227                 rt2661_bbp_write(sc, 88, 0x80);
2228         }
2229
2230         rt2661_bbp_write(sc, 35, bbp35);
2231         rt2661_bbp_write(sc, 97, bbp97);
2232         rt2661_bbp_write(sc, 98, bbp98);
2233
2234         tmp = RAL_READ(sc, RT2661_PHY_CSR0);
2235         tmp &= ~(RT2661_PA_PE_2GHZ | RT2661_PA_PE_5GHZ);
2236         if (IEEE80211_IS_CHAN_2GHZ(c))
2237                 tmp |= RT2661_PA_PE_2GHZ;
2238         else
2239                 tmp |= RT2661_PA_PE_5GHZ;
2240         RAL_WRITE(sc, RT2661_PHY_CSR0, tmp);
2241 }
2242
2243 static void
2244 rt2661_set_chan(struct rt2661_softc *sc, struct ieee80211_channel *c)
2245 {
2246         struct ieee80211com *ic = &sc->sc_ic;
2247         const struct rfprog *rfprog;
2248         uint8_t bbp3, bbp94 = RT2661_BBPR94_DEFAULT;
2249         int8_t power;
2250         u_int i, chan;
2251
2252         chan = ieee80211_chan2ieee(ic, c);
2253         if (chan == 0 || chan == IEEE80211_CHAN_ANY)
2254                 return;
2255
2256         /* select the appropriate RF settings based on what EEPROM says */
2257         rfprog = (sc->rfprog == 0) ? rt2661_rf5225_1 : rt2661_rf5225_2;
2258
2259         /* find the settings for this channel (we know it exists) */
2260         for (i = 0; rfprog[i].chan != chan; i++);
2261
2262         power = sc->txpow[i];
2263         if (power < 0) {
2264                 bbp94 += power;
2265                 power = 0;
2266         } else if (power > 31) {
2267                 bbp94 += power - 31;
2268                 power = 31;
2269         }
2270
2271         /*
2272          * If we are switching from the 2GHz band to the 5GHz band or
2273          * vice-versa, BBP registers need to be reprogrammed.
2274          */
2275         if (c->ic_flags != sc->sc_curchan->ic_flags) {
2276                 rt2661_select_band(sc, c);
2277                 rt2661_select_antenna(sc);
2278         }
2279         sc->sc_curchan = c;
2280
2281         rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2282         rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2283         rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2284         rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2285
2286         DELAY(200);
2287
2288         rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2289         rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2290         rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7 | 1);
2291         rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2292
2293         DELAY(200);
2294
2295         rt2661_rf_write(sc, RAL_RF1, rfprog[i].r1);
2296         rt2661_rf_write(sc, RAL_RF2, rfprog[i].r2);
2297         rt2661_rf_write(sc, RAL_RF3, rfprog[i].r3 | power << 7);
2298         rt2661_rf_write(sc, RAL_RF4, rfprog[i].r4 | sc->rffreq << 10);
2299
2300         /* enable smart mode for MIMO-capable RFs */
2301         bbp3 = rt2661_bbp_read(sc, 3);
2302
2303         bbp3 &= ~RT2661_SMART_MODE;
2304         if (sc->rf_rev == RT2661_RF_5325 || sc->rf_rev == RT2661_RF_2529)
2305                 bbp3 |= RT2661_SMART_MODE;
2306
2307         rt2661_bbp_write(sc, 3, bbp3);
2308
2309         if (bbp94 != RT2661_BBPR94_DEFAULT)
2310                 rt2661_bbp_write(sc, 94, bbp94);
2311
2312         /* 5GHz radio needs a 1ms delay here */
2313         if (IEEE80211_IS_CHAN_5GHZ(c))
2314                 DELAY(1000);
2315
2316         sc->sc_sifs = IEEE80211_IS_CHAN_5GHZ(c) ? IEEE80211_DUR_OFDM_SIFS
2317                                                 : IEEE80211_DUR_SIFS;
2318 }
2319
2320 static void
2321 rt2661_set_bssid(struct rt2661_softc *sc, const uint8_t *bssid)
2322 {
2323         uint32_t tmp;
2324
2325         tmp = bssid[0] | bssid[1] << 8 | bssid[2] << 16 | bssid[3] << 24;
2326         RAL_WRITE(sc, RT2661_MAC_CSR4, tmp);
2327
2328         tmp = bssid[4] | bssid[5] << 8 | RT2661_ONE_BSSID << 16;
2329         RAL_WRITE(sc, RT2661_MAC_CSR5, tmp);
2330 }
2331
2332 static void
2333 rt2661_set_macaddr(struct rt2661_softc *sc, const uint8_t *addr)
2334 {
2335         uint32_t tmp;
2336
2337         tmp = addr[0] | addr[1] << 8 | addr[2] << 16 | addr[3] << 24;
2338         RAL_WRITE(sc, RT2661_MAC_CSR2, tmp);
2339
2340         tmp = addr[4] | addr[5] << 8;
2341         RAL_WRITE(sc, RT2661_MAC_CSR3, tmp);
2342 }
2343
2344 static void
2345 rt2661_update_promisc(struct rt2661_softc *sc)
2346 {
2347         struct ifnet *ifp = sc->sc_ic.ic_ifp;
2348         uint32_t tmp;
2349
2350         tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2351
2352         tmp &= ~RT2661_DROP_NOT_TO_ME;
2353         if (!(ifp->if_flags & IFF_PROMISC))
2354                 tmp |= RT2661_DROP_NOT_TO_ME;
2355
2356         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2357
2358         DPRINTF(("%s promiscuous mode\n", (ifp->if_flags & IFF_PROMISC) ?
2359             "entering" : "leaving"));
2360 }
2361
2362 /*
2363  * Update QoS (802.11e) settings for each h/w Tx ring.
2364  */
2365 static int
2366 rt2661_wme_update(struct ieee80211com *ic)
2367 {
2368         struct rt2661_softc *sc = ic->ic_ifp->if_softc;
2369         const struct wmeParams *wmep;
2370
2371         wmep = ic->ic_wme.wme_chanParams.cap_wmeParams;
2372
2373         /* XXX: not sure about shifts. */
2374         /* XXX: the reference driver plays with AC_VI settings too. */
2375
2376         /* update TxOp */
2377         RAL_WRITE(sc, RT2661_AC_TXOP_CSR0,
2378             wmep[WME_AC_BE].wmep_txopLimit << 16 |
2379             wmep[WME_AC_BK].wmep_txopLimit);
2380         RAL_WRITE(sc, RT2661_AC_TXOP_CSR1,
2381             wmep[WME_AC_VI].wmep_txopLimit << 16 |
2382             wmep[WME_AC_VO].wmep_txopLimit);
2383
2384         /* update CWmin */
2385         RAL_WRITE(sc, RT2661_CWMIN_CSR,
2386             wmep[WME_AC_BE].wmep_logcwmin << 12 |
2387             wmep[WME_AC_BK].wmep_logcwmin <<  8 |
2388             wmep[WME_AC_VI].wmep_logcwmin <<  4 |
2389             wmep[WME_AC_VO].wmep_logcwmin);
2390
2391         /* update CWmax */
2392         RAL_WRITE(sc, RT2661_CWMAX_CSR,
2393             wmep[WME_AC_BE].wmep_logcwmax << 12 |
2394             wmep[WME_AC_BK].wmep_logcwmax <<  8 |
2395             wmep[WME_AC_VI].wmep_logcwmax <<  4 |
2396             wmep[WME_AC_VO].wmep_logcwmax);
2397
2398         /* update Aifsn */
2399         RAL_WRITE(sc, RT2661_AIFSN_CSR,
2400             wmep[WME_AC_BE].wmep_aifsn << 12 |
2401             wmep[WME_AC_BK].wmep_aifsn <<  8 |
2402             wmep[WME_AC_VI].wmep_aifsn <<  4 |
2403             wmep[WME_AC_VO].wmep_aifsn);
2404
2405         return 0;
2406 }
2407
2408 static void
2409 rt2661_update_slot(struct ifnet *ifp)
2410 {
2411         struct rt2661_softc *sc = ifp->if_softc;
2412         struct ieee80211com *ic = &sc->sc_ic;
2413         uint8_t slottime;
2414         uint32_t tmp;
2415
2416         slottime = (ic->ic_flags & IEEE80211_F_SHSLOT) ? 9 : 20;
2417
2418         tmp = RAL_READ(sc, RT2661_MAC_CSR9);
2419         tmp = (tmp & ~0xff) | slottime;
2420         RAL_WRITE(sc, RT2661_MAC_CSR9, tmp);
2421 }
2422
2423 static const char *
2424 rt2661_get_rf(int rev)
2425 {
2426         switch (rev) {
2427         case RT2661_RF_5225:    return "RT5225";
2428         case RT2661_RF_5325:    return "RT5325 (MIMO XR)";
2429         case RT2661_RF_2527:    return "RT2527";
2430         case RT2661_RF_2529:    return "RT2529 (MIMO XR)";
2431         default:                return "unknown";
2432         }
2433 }
2434
2435 static void
2436 rt2661_read_config(struct rt2661_softc *sc)
2437 {
2438         struct ieee80211com *ic = &sc->sc_ic;
2439         uint16_t val;
2440         int i, start_chan;
2441
2442         /* read MAC address */
2443         val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC01);
2444         ic->ic_myaddr[0] = val & 0xff;
2445         ic->ic_myaddr[1] = val >> 8;
2446
2447         val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC23);
2448         ic->ic_myaddr[2] = val & 0xff;
2449         ic->ic_myaddr[3] = val >> 8;
2450
2451         val = rt2661_eeprom_read(sc, RT2661_EEPROM_MAC45);
2452         ic->ic_myaddr[4] = val & 0xff;
2453         ic->ic_myaddr[5] = val >> 8;
2454
2455         val = rt2661_eeprom_read(sc, RT2661_EEPROM_ANTENNA);
2456         /* XXX: test if different from 0xffff? */
2457         sc->rf_rev   = (val >> 11) & 0x1f;
2458         sc->hw_radio = (val >> 10) & 0x1;
2459         sc->rx_ant   = (val >> 4)  & 0x3;
2460         sc->tx_ant   = (val >> 2)  & 0x3;
2461         sc->nb_ant   = val & 0x3;
2462
2463         DPRINTF(("RF revision=%d\n", sc->rf_rev));
2464
2465         val = rt2661_eeprom_read(sc, RT2661_EEPROM_CONFIG2);
2466         sc->ext_5ghz_lna = (val >> 6) & 0x1;
2467         sc->ext_2ghz_lna = (val >> 4) & 0x1;
2468
2469         DPRINTF(("External 2GHz LNA=%d\nExternal 5GHz LNA=%d\n",
2470             sc->ext_2ghz_lna, sc->ext_5ghz_lna));
2471
2472         val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_2GHZ_OFFSET);
2473         if ((val & 0xff) != 0xff)
2474                 sc->rssi_2ghz_corr = (int8_t)(val & 0xff);      /* signed */
2475
2476         /* Only [-10, 10] is valid */
2477         if (sc->rssi_2ghz_corr < -10 || sc->rssi_2ghz_corr > 10)
2478                 sc->rssi_2ghz_corr = 0;
2479
2480         val = rt2661_eeprom_read(sc, RT2661_EEPROM_RSSI_5GHZ_OFFSET);
2481         if ((val & 0xff) != 0xff)
2482                 sc->rssi_5ghz_corr = (int8_t)(val & 0xff);      /* signed */
2483
2484         /* Only [-10, 10] is valid */
2485         if (sc->rssi_5ghz_corr < -10 || sc->rssi_5ghz_corr > 10)
2486                 sc->rssi_5ghz_corr = 0;
2487
2488         /* adjust RSSI correction for external low-noise amplifier */
2489         if (sc->ext_2ghz_lna)
2490                 sc->rssi_2ghz_corr -= 14;
2491         if (sc->ext_5ghz_lna)
2492                 sc->rssi_5ghz_corr -= 14;
2493
2494         DPRINTF(("RSSI 2GHz corr=%d\nRSSI 5GHz corr=%d\n",
2495             sc->rssi_2ghz_corr, sc->rssi_5ghz_corr));
2496
2497         val = rt2661_eeprom_read(sc, RT2661_EEPROM_FREQ_OFFSET);
2498         if ((val >> 8) != 0xff)
2499                 sc->rfprog = (val >> 8) & 0x3;
2500         if ((val & 0xff) != 0xff)
2501                 sc->rffreq = val & 0xff;
2502
2503         DPRINTF(("RF prog=%d\nRF freq=%d\n", sc->rfprog, sc->rffreq));
2504
2505 #define NCHAN_2GHZ      14
2506 #define NCHAN_5GHZ      24
2507         /*
2508          * Read channel TX power
2509          */
2510         start_chan = 0;
2511         rt2661_read_txpower_config(sc, RT2661_EEPROM_TXPOWER_2GHZ,
2512                                    NCHAN_2GHZ, &start_chan);
2513         rt2661_read_txpower_config(sc, RT2661_EEPROM_TXPOWER_5GHZ,
2514                                    NCHAN_5GHZ, &start_chan);
2515 #undef NCHAN_2GHZ
2516 #undef NCHAN_5GHZ
2517
2518         /* read vendor-specific BBP values */
2519         for (i = 0; i < 16; i++) {
2520                 val = rt2661_eeprom_read(sc, RT2661_EEPROM_BBP_BASE + i);
2521                 if (val == 0 || val == 0xffff)
2522                         continue;       /* skip invalid entries */
2523                 sc->bbp_prom[i].reg = val >> 8;
2524                 sc->bbp_prom[i].val = val & 0xff;
2525                 DPRINTF(("BBP R%d=%02x\n", sc->bbp_prom[i].reg,
2526                     sc->bbp_prom[i].val));
2527         }
2528
2529         val = rt2661_eeprom_read(sc, RT2661_EEPROM_LED_OFFSET);
2530         DPRINTF(("LED %02x\n", val));
2531         if (val == 0xffff) {
2532                 sc->mcu_led = RT2661_MCU_LED_DEFAULT;
2533         } else {
2534 #define N(arr)  (int)(sizeof(arr) / sizeof(arr[0]))
2535
2536                 for (i = 0; i < N(led_ee2mcu); ++i) {
2537                         if (val & led_ee2mcu[i].ee_bit)
2538                                 sc->mcu_led |= led_ee2mcu[i].mcu_bit;
2539                 }
2540
2541 #undef N
2542
2543                 sc->mcu_led |= ((val >> RT2661_EE_LED_MODE_SHIFT) &
2544                                 RT2661_EE_LED_MODE_MASK);
2545         }
2546 }
2547
2548 static int
2549 rt2661_bbp_init(struct rt2661_softc *sc)
2550 {
2551 #define N(a)    (sizeof (a) / sizeof ((a)[0]))
2552         int i, ntries;
2553         uint8_t val;
2554
2555         /* wait for BBP to be ready */
2556         for (ntries = 0; ntries < 100; ntries++) {
2557                 val = rt2661_bbp_read(sc, 0);
2558                 if (val != 0 && val != 0xff)
2559                         break;
2560                 DELAY(100);
2561         }
2562         if (ntries == 100) {
2563                 device_printf(sc->sc_dev, "timeout waiting for BBP\n");
2564                 return EIO;
2565         }
2566
2567         /* initialize BBP registers to default values */
2568         for (i = 0; i < N(rt2661_def_bbp); i++) {
2569                 rt2661_bbp_write(sc, rt2661_def_bbp[i].reg,
2570                     rt2661_def_bbp[i].val);
2571         }
2572
2573         /* write vendor-specific BBP values (from EEPROM) */
2574         for (i = 0; i < 16; i++) {
2575                 if (sc->bbp_prom[i].reg == 0)
2576                         continue;
2577                 rt2661_bbp_write(sc, sc->bbp_prom[i].reg, sc->bbp_prom[i].val);
2578         }
2579
2580         return 0;
2581 #undef N
2582 }
2583
2584 static void
2585 rt2661_init(void *priv)
2586 {
2587 #define N(a)    (sizeof (a) / sizeof ((a)[0]))
2588         struct rt2661_softc *sc = priv;
2589         struct ieee80211com *ic = &sc->sc_ic;
2590         struct ifnet *ifp = ic->ic_ifp;
2591         uint32_t tmp, sta[3];
2592         int i, ntries;
2593
2594         rt2661_stop(sc);
2595
2596         /* initialize Tx rings */
2597         RAL_WRITE(sc, RT2661_AC1_BASE_CSR, sc->txq[1].physaddr);
2598         RAL_WRITE(sc, RT2661_AC0_BASE_CSR, sc->txq[0].physaddr);
2599         RAL_WRITE(sc, RT2661_AC2_BASE_CSR, sc->txq[2].physaddr);
2600         RAL_WRITE(sc, RT2661_AC3_BASE_CSR, sc->txq[3].physaddr);
2601
2602         /* initialize Mgt ring */
2603         RAL_WRITE(sc, RT2661_MGT_BASE_CSR, sc->mgtq.physaddr);
2604
2605         /* initialize Rx ring */
2606         RAL_WRITE(sc, RT2661_RX_BASE_CSR, sc->rxq.physaddr);
2607
2608         /* initialize Tx rings sizes */
2609         RAL_WRITE(sc, RT2661_TX_RING_CSR0,
2610             RT2661_TX_RING_COUNT << 24 |
2611             RT2661_TX_RING_COUNT << 16 |
2612             RT2661_TX_RING_COUNT <<  8 |
2613             RT2661_TX_RING_COUNT);
2614
2615         RAL_WRITE(sc, RT2661_TX_RING_CSR1,
2616             RT2661_TX_DESC_WSIZE << 16 |
2617             RT2661_TX_RING_COUNT <<  8 |        /* XXX: HCCA ring unused */
2618             RT2661_MGT_RING_COUNT);
2619
2620         /* initialize Rx rings */
2621         RAL_WRITE(sc, RT2661_RX_RING_CSR,
2622             RT2661_RX_DESC_BACK  << 16 |
2623             RT2661_RX_DESC_WSIZE <<  8 |
2624             RT2661_RX_RING_COUNT);
2625
2626         /* XXX: some magic here */
2627         RAL_WRITE(sc, RT2661_TX_DMA_DST_CSR, 0xaa);
2628
2629         /* load base addresses of all 5 Tx rings (4 data + 1 mgt) */
2630         RAL_WRITE(sc, RT2661_LOAD_TX_RING_CSR, 0x1f);
2631
2632         /* load base address of Rx ring */
2633         RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 2);
2634
2635         /* initialize MAC registers to default values */
2636         for (i = 0; i < N(rt2661_def_mac); i++)
2637                 RAL_WRITE(sc, rt2661_def_mac[i].reg, rt2661_def_mac[i].val);
2638
2639         IEEE80211_ADDR_COPY(ic->ic_myaddr, IF_LLADDR(ifp));
2640         rt2661_set_macaddr(sc, ic->ic_myaddr);
2641
2642         /* set host ready */
2643         RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2644         RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2645
2646         /* wait for BBP/RF to wakeup */
2647         for (ntries = 0; ntries < 1000; ntries++) {
2648                 if (RAL_READ(sc, RT2661_MAC_CSR12) & 8)
2649                         break;
2650                 DELAY(1000);
2651         }
2652         if (ntries == 1000) {
2653                 kprintf("timeout waiting for BBP/RF to wakeup\n");
2654                 rt2661_stop(sc);
2655                 return;
2656         }
2657
2658         if (rt2661_bbp_init(sc) != 0) {
2659                 rt2661_stop(sc);
2660                 return;
2661         }
2662
2663         /* select default channel */
2664         sc->sc_curchan = ic->ic_curchan;
2665         rt2661_select_band(sc, sc->sc_curchan);
2666         rt2661_select_antenna(sc);
2667         rt2661_set_chan(sc, sc->sc_curchan);
2668
2669         /* update Rx filter */
2670         tmp = RAL_READ(sc, RT2661_TXRX_CSR0) & 0xffff;
2671
2672         tmp |= RT2661_DROP_PHY_ERROR | RT2661_DROP_CRC_ERROR;
2673         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2674                 tmp |= RT2661_DROP_CTL | RT2661_DROP_VER_ERROR |
2675                        RT2661_DROP_ACKCTS;
2676                 if (ic->ic_opmode != IEEE80211_M_HOSTAP)
2677                         tmp |= RT2661_DROP_TODS;
2678                 if (!(ifp->if_flags & IFF_PROMISC))
2679                         tmp |= RT2661_DROP_NOT_TO_ME;
2680         }
2681
2682         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2683
2684         /* clear STA registers */
2685         RAL_READ_REGION_4(sc, RT2661_STA_CSR0, sta, N(sta));
2686
2687         /* initialize ASIC */
2688         RAL_WRITE(sc, RT2661_MAC_CSR1, 4);
2689
2690         /* clear any pending interrupt */
2691         RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2692
2693         /* enable interrupts */
2694         RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0x0000ff10);
2695         RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0);
2696
2697         /* kick Rx */
2698         RAL_WRITE(sc, RT2661_RX_CNTL_CSR, 1);
2699
2700         ifp->if_flags &= ~IFF_OACTIVE;
2701         ifp->if_flags |= IFF_RUNNING;
2702
2703         for (i = 0; i < IEEE80211_WEP_NKID; ++i) {
2704                 uint8_t mac[IEEE80211_ADDR_LEN];
2705                 const struct ieee80211_key *k = &ic->ic_nw_keys[i];
2706
2707                 if (k->wk_keyix != IEEE80211_KEYIX_NONE)
2708                         rt2661_key_set(ic, k, mac);
2709         }
2710
2711         if (ic->ic_opmode != IEEE80211_M_MONITOR) {
2712                 if (ic->ic_roaming != IEEE80211_ROAMING_MANUAL)
2713                         ieee80211_new_state(ic, IEEE80211_S_SCAN, -1);
2714         } else
2715                 ieee80211_new_state(ic, IEEE80211_S_RUN, -1);
2716 #undef N
2717 }
2718
2719 void
2720 rt2661_stop(void *priv)
2721 {
2722         struct rt2661_softc *sc = priv;
2723         struct ieee80211com *ic = &sc->sc_ic;
2724         struct ifnet *ifp = ic->ic_ifp;
2725         struct rt2661_tx_ratectl *rctl;
2726         uint32_t tmp;
2727
2728         ieee80211_new_state(ic, IEEE80211_S_INIT, -1);
2729
2730         sc->sc_tx_timer = 0;
2731         ifp->if_timer = 0;
2732         ifp->if_flags &= ~(IFF_RUNNING | IFF_OACTIVE);
2733
2734         /* abort Tx (for all 5 Tx rings) */
2735         RAL_WRITE(sc, RT2661_TX_CNTL_CSR, 0x1f << 16);
2736
2737         /* disable Rx (value remains after reset!) */
2738         tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2739         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2740
2741         /* reset ASIC */
2742         RAL_WRITE(sc, RT2661_MAC_CSR1, 3);
2743         RAL_WRITE(sc, RT2661_MAC_CSR1, 0);
2744
2745         /* disable interrupts */
2746         RAL_WRITE(sc, RT2661_INT_MASK_CSR, 0xffffffff);
2747         RAL_WRITE(sc, RT2661_MCU_INT_MASK_CSR, 0xffffffff);
2748
2749         /* clear any pending interrupt */
2750         RAL_WRITE(sc, RT2661_INT_SOURCE_CSR, 0xffffffff);
2751         RAL_WRITE(sc, RT2661_MCU_INT_SOURCE_CSR, 0xffffffff);
2752
2753         while ((rctl = STAILQ_FIRST(&sc->tx_ratectl)) != NULL) {
2754                 STAILQ_REMOVE_HEAD(&sc->tx_ratectl, link);
2755                 ieee80211_free_node(rctl->ni);
2756                 rctl->ni = NULL;
2757                 kfree(rctl, M_RT2661);
2758         }
2759
2760         /* reset Tx and Rx rings */
2761         rt2661_reset_tx_ring(sc, &sc->txq[0]);
2762         rt2661_reset_tx_ring(sc, &sc->txq[1]);
2763         rt2661_reset_tx_ring(sc, &sc->txq[2]);
2764         rt2661_reset_tx_ring(sc, &sc->txq[3]);
2765         rt2661_reset_tx_ring(sc, &sc->mgtq);
2766         rt2661_reset_rx_ring(sc, &sc->rxq);
2767
2768         /* Clear key map. */
2769         bzero(sc->sc_keymap, sizeof(sc->sc_keymap));
2770 }
2771
2772 static int
2773 rt2661_load_microcode(struct rt2661_softc *sc, const uint8_t *ucode, int size)
2774 {
2775         int ntries;
2776
2777         /* reset 8051 */
2778         RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2779
2780         /* cancel any pending Host to MCU command */
2781         RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR, 0);
2782         RAL_WRITE(sc, RT2661_M2H_CMD_DONE_CSR, 0xffffffff);
2783         RAL_WRITE(sc, RT2661_HOST_CMD_CSR, 0);
2784
2785         /* write 8051's microcode */
2786         RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET | RT2661_MCU_SEL);
2787         RAL_WRITE_REGION_1(sc, RT2661_MCU_CODE_BASE, ucode, size);
2788         RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, RT2661_MCU_RESET);
2789
2790         /* kick 8051's ass */
2791         RAL_WRITE(sc, RT2661_MCU_CNTL_CSR, 0);
2792
2793         /* wait for 8051 to initialize */
2794         for (ntries = 0; ntries < 500; ntries++) {
2795                 if (RAL_READ(sc, RT2661_MCU_CNTL_CSR) & RT2661_MCU_READY)
2796                         break;
2797                 DELAY(100);
2798         }
2799         if (ntries == 500) {
2800                 kprintf("timeout waiting for MCU to initialize\n");
2801                 return EIO;
2802         }
2803         return 0;
2804 }
2805
2806 #ifdef notyet
2807 /*
2808  * Dynamically tune Rx sensitivity (BBP register 17) based on average RSSI and
2809  * false CCA count.  This function is called periodically (every seconds) when
2810  * in the RUN state.  Values taken from the reference driver.
2811  */
2812 static void
2813 rt2661_rx_tune(struct rt2661_softc *sc)
2814 {
2815         uint8_t bbp17;
2816         uint16_t cca;
2817         int lo, hi, dbm;
2818
2819         /*
2820          * Tuning range depends on operating band and on the presence of an
2821          * external low-noise amplifier.
2822          */
2823         lo = 0x20;
2824         if (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan))
2825                 lo += 0x08;
2826         if ((IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan) && sc->ext_2ghz_lna) ||
2827             (IEEE80211_IS_CHAN_5GHZ(sc->sc_curchan) && sc->ext_5ghz_lna))
2828                 lo += 0x10;
2829         hi = lo + 0x20;
2830
2831         /* retrieve false CCA count since last call (clear on read) */
2832         cca = RAL_READ(sc, RT2661_STA_CSR1) & 0xffff;
2833
2834         if (dbm >= -35) {
2835                 bbp17 = 0x60;
2836         } else if (dbm >= -58) {
2837                 bbp17 = hi;
2838         } else if (dbm >= -66) {
2839                 bbp17 = lo + 0x10;
2840         } else if (dbm >= -74) {
2841                 bbp17 = lo + 0x08;
2842         } else {
2843                 /* RSSI < -74dBm, tune using false CCA count */
2844
2845                 bbp17 = sc->bbp17; /* current value */
2846
2847                 hi -= 2 * (-74 - dbm);
2848                 if (hi < lo)
2849                         hi = lo;
2850
2851                 if (bbp17 > hi) {
2852                         bbp17 = hi;
2853
2854                 } else if (cca > 512) {
2855                         if (++bbp17 > hi)
2856                                 bbp17 = hi;
2857                 } else if (cca < 100) {
2858                         if (--bbp17 < lo)
2859                                 bbp17 = lo;
2860                 }
2861         }
2862
2863         if (bbp17 != sc->bbp17) {
2864                 rt2661_bbp_write(sc, 17, bbp17);
2865                 sc->bbp17 = bbp17;
2866         }
2867 }
2868
2869 /*
2870  * Enter/Leave radar detection mode.
2871  * This is for 802.11h additional regulatory domains.
2872  */
2873 static void
2874 rt2661_radar_start(struct rt2661_softc *sc)
2875 {
2876         uint32_t tmp;
2877
2878         /* disable Rx */
2879         tmp = RAL_READ(sc, RT2661_TXRX_CSR0);
2880         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp | RT2661_DISABLE_RX);
2881
2882         rt2661_bbp_write(sc, 82, 0x20);
2883         rt2661_bbp_write(sc, 83, 0x00);
2884         rt2661_bbp_write(sc, 84, 0x40);
2885
2886         /* save current BBP registers values */
2887         sc->bbp18 = rt2661_bbp_read(sc, 18);
2888         sc->bbp21 = rt2661_bbp_read(sc, 21);
2889         sc->bbp22 = rt2661_bbp_read(sc, 22);
2890         sc->bbp16 = rt2661_bbp_read(sc, 16);
2891         sc->bbp17 = rt2661_bbp_read(sc, 17);
2892         sc->bbp64 = rt2661_bbp_read(sc, 64);
2893
2894         rt2661_bbp_write(sc, 18, 0xff);
2895         rt2661_bbp_write(sc, 21, 0x3f);
2896         rt2661_bbp_write(sc, 22, 0x3f);
2897         rt2661_bbp_write(sc, 16, 0xbd);
2898         rt2661_bbp_write(sc, 17, sc->ext_5ghz_lna ? 0x44 : 0x34);
2899         rt2661_bbp_write(sc, 64, 0x21);
2900
2901         /* restore Rx filter */
2902         RAL_WRITE(sc, RT2661_TXRX_CSR0, tmp);
2903 }
2904
2905 static int
2906 rt2661_radar_stop(struct rt2661_softc *sc)
2907 {
2908         uint8_t bbp66;
2909
2910         /* read radar detection result */
2911         bbp66 = rt2661_bbp_read(sc, 66);
2912
2913         /* restore BBP registers values */
2914         rt2661_bbp_write(sc, 16, sc->bbp16);
2915         rt2661_bbp_write(sc, 17, sc->bbp17);
2916         rt2661_bbp_write(sc, 18, sc->bbp18);
2917         rt2661_bbp_write(sc, 21, sc->bbp21);
2918         rt2661_bbp_write(sc, 22, sc->bbp22);
2919         rt2661_bbp_write(sc, 64, sc->bbp64);
2920
2921         return bbp66 == 1;
2922 }
2923 #endif
2924
2925 static int
2926 rt2661_prepare_beacon(struct rt2661_softc *sc)
2927 {
2928         struct ieee80211com *ic = &sc->sc_ic;
2929         struct ieee80211_beacon_offsets bo;
2930         struct rt2661_tx_desc desc;
2931         struct mbuf *m0;
2932         int rate;
2933
2934         m0 = ieee80211_beacon_alloc(ic, ic->ic_bss, &bo);
2935         if (m0 == NULL) {
2936                 device_printf(sc->sc_dev, "could not allocate beacon frame\n");
2937                 return ENOBUFS;
2938         }
2939
2940         /* send beacons at the lowest available rate */
2941         rate = IEEE80211_IS_CHAN_5GHZ(ic->ic_bss->ni_chan) ? 12 : 2;
2942
2943         rt2661_setup_tx_desc(sc, &desc, RT2661_TX_TIMESTAMP, RT2661_TX_HWSEQ,
2944             m0->m_pkthdr.len, rate, NULL, 0, RT2661_QID_MGT, 0, NULL, NULL, NULL);
2945
2946         /* copy the first 24 bytes of Tx descriptor into NIC memory */
2947         RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0, (uint8_t *)&desc, 24);
2948
2949         /* copy beacon header and payload into NIC memory */
2950         RAL_WRITE_REGION_1(sc, RT2661_HW_BEACON_BASE0 + 24,
2951             mtod(m0, uint8_t *), m0->m_pkthdr.len);
2952
2953         m_freem(m0);
2954         return 0;
2955 }
2956
2957 /*
2958  * Enable TSF synchronization and tell h/w to start sending beacons for IBSS
2959  * and HostAP operating modes.
2960  */
2961 static void
2962 rt2661_enable_tsf_sync(struct rt2661_softc *sc)
2963 {
2964         struct ieee80211com *ic = &sc->sc_ic;
2965         uint32_t tmp;
2966
2967         if (ic->ic_opmode != IEEE80211_M_STA) {
2968                 /*
2969                  * Change default 16ms TBTT adjustment to 8ms.
2970                  * Must be done before enabling beacon generation.
2971                  */
2972                 RAL_WRITE(sc, RT2661_TXRX_CSR10, 1 << 12 | 8);
2973         }
2974
2975         tmp = RAL_READ(sc, RT2661_TXRX_CSR9) & 0xff000000;
2976
2977         /* set beacon interval (in 1/16ms unit) */
2978         tmp |= ic->ic_bss->ni_intval * 16;
2979
2980         tmp |= RT2661_TSF_TICKING | RT2661_ENABLE_TBTT;
2981         if (ic->ic_opmode == IEEE80211_M_STA)
2982                 tmp |= RT2661_TSF_MODE(1);
2983         else
2984                 tmp |= RT2661_TSF_MODE(2) | RT2661_GENERATE_BEACON;
2985
2986         RAL_WRITE(sc, RT2661_TXRX_CSR9, tmp);
2987 }
2988
2989 /*
2990  * Retrieve the "Received Signal Strength Indicator" from the raw values
2991  * contained in Rx descriptors.  The computation depends on which band the
2992  * frame was received.  Correction values taken from the reference driver.
2993  */
2994 static int
2995 rt2661_get_rssi(struct rt2661_softc *sc, uint8_t raw)
2996 {
2997         int lna, agc, rssi;
2998
2999         lna = (raw >> 5) & 0x3;
3000         agc = raw & 0x1f;
3001
3002         if (lna == 0) {
3003                 /*
3004                  * No RSSI mapping
3005                  *
3006                  * NB: Since RSSI is relative to noise floor, -1 is
3007                  *     adequate for caller to know error happened.
3008                  */
3009                 return -1;
3010         }
3011
3012         rssi = (2 * agc) - RT2661_NOISE_FLOOR;
3013
3014         if (IEEE80211_IS_CHAN_2GHZ(sc->sc_curchan)) {
3015                 rssi += sc->rssi_2ghz_corr;
3016
3017                 if (lna == 1)
3018                         rssi -= 64;
3019                 else if (lna == 2)
3020                         rssi -= 74;
3021                 else if (lna == 3)
3022                         rssi -= 90;
3023         } else {
3024                 rssi += sc->rssi_5ghz_corr;
3025
3026                 if (lna == 1)
3027                         rssi -= 64;
3028                 else if (lna == 2)
3029                         rssi -= 86;
3030                 else if (lna == 3)
3031                         rssi -= 100;
3032         }
3033         return rssi;
3034 }
3035
3036 static void
3037 rt2661_dma_map_mbuf(void *arg, bus_dma_segment_t *seg, int nseg,
3038                     bus_size_t map_size __unused, int error)
3039 {
3040         struct rt2661_dmamap *map = arg;
3041
3042         if (error)
3043                 return;
3044
3045         KASSERT(nseg <= RT2661_MAX_SCATTER, ("too many DMA segments"));
3046
3047         bcopy(seg, map->segs, nseg * sizeof(bus_dma_segment_t));
3048         map->nseg = nseg;
3049 }
3050
3051 static void
3052 rt2661_led_newstate(struct rt2661_softc *sc, enum ieee80211_state nstate)
3053 {
3054         struct ieee80211com *ic = &sc->sc_ic;
3055         uint32_t off, on;
3056         uint32_t mail = sc->mcu_led;
3057
3058         if (RAL_READ(sc, RT2661_H2M_MAILBOX_CSR) & RT2661_H2M_BUSY) {
3059                 DPRINTF(("%s failed\n", __func__));
3060                 return;
3061         }
3062
3063         switch (nstate) {
3064         case IEEE80211_S_INIT:
3065                 mail &= ~(RT2661_MCU_LED_LINKA | RT2661_MCU_LED_LINKG |
3066                           RT2661_MCU_LED_RF);
3067                 break;
3068         default:
3069                 if (ic->ic_curchan == NULL)
3070                         return;
3071
3072                 on = RT2661_MCU_LED_LINKG;
3073                 off = RT2661_MCU_LED_LINKA;
3074                 if (IEEE80211_IS_CHAN_5GHZ(ic->ic_curchan)) {
3075                         on = RT2661_MCU_LED_LINKA;
3076                         off = RT2661_MCU_LED_LINKG;
3077                 }
3078
3079                 mail |= RT2661_MCU_LED_RF | on;
3080                 mail &= ~off;
3081                 break;
3082         }
3083
3084         RAL_WRITE(sc, RT2661_H2M_MAILBOX_CSR,
3085                   RT2661_H2M_BUSY | RT2661_TOKEN_NO_INTR << 16 | mail);
3086         RAL_WRITE(sc, RT2661_HOST_CMD_CSR, RT2661_KICK_CMD | RT2661_MCU_SET_LED);
3087 }
3088
3089 static void
3090 rt2661_read_txpower_config(struct rt2661_softc *sc, uint8_t txpwr_ofs,
3091                            int nchan, int *start_chan0)
3092 {
3093         int i, loop_max;
3094         int start_chan = *start_chan0;
3095
3096         KASSERT(nchan % 2 == 0, ("number of channels %d is not even\n", nchan));
3097         KASSERT(start_chan + nchan <= RT2661_NCHAN_MAX, ("too many channels"));
3098
3099         loop_max = nchan / 2;
3100
3101         for (i = 0; i < loop_max; i++) {
3102                 int chan_idx, j;
3103                 uint16_t val;
3104
3105                 val = rt2661_eeprom_read(sc, txpwr_ofs + i);
3106                 chan_idx = i * 2 + start_chan;
3107
3108                 for (j = 0; j < 2; ++j) {
3109                         int8_t tx_power;        /* signed */
3110
3111                         tx_power = (int8_t)((val >> (8 * j)) & 0xff);
3112                         if (tx_power > RT2661_TXPOWER_MAX)
3113                                 tx_power = RT2661_TXPOWER_DEFAULT;
3114
3115                         sc->txpow[chan_idx] = tx_power;
3116                         DPRINTF(("Channel=%d Tx power=%d\n",
3117                             rt2661_rf5225_1[chan_idx].chan, sc->txpow[chan_idx]));
3118
3119                         ++chan_idx;
3120                 }
3121         }
3122         *start_chan0 += nchan;
3123 }
3124
3125 static int
3126 rt2661_key_alloc(struct ieee80211com *ic, const struct ieee80211_key *key,
3127                  ieee80211_keyix *keyix, ieee80211_keyix *rxkeyix)
3128 {
3129         struct rt2661_softc *sc = ic->ic_if.if_softc;
3130
3131         DPRINTF(("%s: ", __func__));
3132
3133         if (key->wk_flags & IEEE80211_KEY_SWCRYPT) {
3134                 DPRINTF(("alloc sw key\n"));
3135                 return sc->sc_key_alloc(ic, key, keyix, rxkeyix);
3136         }
3137
3138         if (key->wk_flags & IEEE80211_KEY_GROUP) {      /* Global key */
3139                 DPRINTF(("alloc group key\n"));
3140
3141                 KASSERT(key >= &ic->ic_nw_keys[0] &&
3142                         key < &ic->ic_nw_keys[IEEE80211_WEP_NKID],
3143                         ("bogus group key\n"));
3144
3145                 *keyix = *rxkeyix = key - ic->ic_nw_keys;
3146                 return 1;
3147         } else {                                        /* Pairwise key */
3148                 int i;
3149
3150                 DPRINTF(("alloc pairwise key\n"));
3151
3152                 for (i = IEEE80211_WEP_NKID; i < RT2661_KEY_MAX; ++i) {
3153                         if (!RT2661_KEY_ISSET(sc, i))
3154                                 break;
3155                 }
3156 #ifndef MIXED_KEY_TEST
3157                 if (i == RT2661_KEY_MAX)
3158                         return 0;
3159 #else
3160                 if (i != IEEE80211_WEP_NKID)
3161                         return 0;
3162 #endif
3163
3164                 RT2661_KEY_SET(sc, i);
3165                 *keyix = *rxkeyix = i;
3166                 return 1;
3167         }
3168 }
3169
3170 static int
3171 rt2661_key_delete(struct ieee80211com *ic, const struct ieee80211_key *key)
3172 {
3173         struct rt2661_softc *sc = ic->ic_if.if_softc;
3174         uint32_t val;
3175
3176         DPRINTF(("%s: keyix %d, rxkeyix %d, ", __func__,
3177                  key->wk_keyix, key->wk_rxkeyix));
3178
3179         if (key->wk_flags & IEEE80211_KEY_SWCRYPT) {
3180                 DPRINTF(("delete sw key\n"));
3181                 return sc->sc_key_delete(ic, key);
3182         }
3183
3184         if (key->wk_keyix < IEEE80211_WEP_NKID) {       /* Global key */
3185                 DPRINTF(("delete global key\n"));
3186                 val = RAL_READ(sc, RT2661_SEC_CSR0);
3187                 val &= ~(1 << key->wk_keyix);
3188                 RAL_WRITE(sc, RT2661_SEC_CSR0, val);
3189         } else {                                        /* Pairwise key */
3190                 DPRINTF(("delete pairwise key\n"));
3191
3192                 RT2661_KEY_CLR(sc, key->wk_keyix);
3193                 if (key->wk_keyix < 32) {
3194                         val = RAL_READ(sc, RT2661_SEC_CSR2);
3195                         val &= ~(1 << key->wk_keyix);
3196                         RAL_WRITE(sc, RT2661_SEC_CSR2, val);
3197                 } else {
3198                         val = RAL_READ(sc, RT2661_SEC_CSR3);
3199                         val &= ~(1 << (key->wk_keyix - 32));
3200                         RAL_WRITE(sc, RT2661_SEC_CSR3, val);
3201                 }
3202         }
3203         return 1;
3204 }
3205
3206 static int
3207 rt2661_key_set(struct ieee80211com *ic, const struct ieee80211_key *key,
3208                const uint8_t mac[IEEE80211_ADDR_LEN])
3209 {
3210         struct rt2661_softc *sc = ic->ic_if.if_softc;
3211         uint32_t addr, val;
3212
3213         DPRINTF(("%s: keyix %d, rxkeyix %d, flags 0x%04x, ", __func__,
3214                  key->wk_keyix, key->wk_rxkeyix, key->wk_flags));
3215
3216         if (key->wk_flags & IEEE80211_KEY_SWCRYPT) {
3217                 DPRINTF(("set sw key\n"));
3218                 return sc->sc_key_set(ic, key, mac);
3219         }
3220
3221         if (key->wk_keyix < IEEE80211_WEP_NKID) {       /* Global Key */
3222                 int cipher, keyix_shift;
3223
3224                 DPRINTF(("set global key\n"));
3225
3226                 /*
3227                  * Install key content.
3228                  */
3229                 addr = RT2661_GLOBAL_KEY_BASE +
3230                        (key->wk_keyix * sizeof(key->wk_key));
3231                 RAL_WRITE_REGION_1(sc, addr, key->wk_key, sizeof(key->wk_key));
3232
3233                 /*
3234                  * Set key cipher.
3235                  */
3236                 cipher = rt2661_cipher(key);
3237                 keyix_shift = key->wk_keyix * 4;
3238
3239                 val = RAL_READ(sc, RT2661_SEC_CSR1);
3240                 val &= ~(0xf << keyix_shift);
3241                 val |= cipher << keyix_shift;
3242                 RAL_WRITE(sc, RT2661_SEC_CSR1, val);
3243
3244                 /*
3245                  * Enable key slot.
3246                  */
3247                 val = RAL_READ(sc, RT2661_SEC_CSR0);
3248                 val |= 1 << key->wk_keyix;
3249                 RAL_WRITE(sc, RT2661_SEC_CSR0, val);
3250         } else {                                        /* Pairwise key */
3251                 uint8_t mac_cipher[IEEE80211_ADDR_LEN + 1];
3252
3253                 DPRINTF(("set pairwise key\n"));
3254
3255                 /*
3256                  * Install key content.
3257                  */
3258                 addr = RT2661_PAIRWISE_KEY_BASE +
3259                        (key->wk_keyix * sizeof(key->wk_key));
3260                 RAL_WRITE_REGION_1(sc, addr, key->wk_key, sizeof(key->wk_key));
3261
3262                 /*
3263                  * Set target address and key cipher.
3264                  */
3265                 memcpy(mac_cipher, mac, IEEE80211_ADDR_LEN);
3266                 mac_cipher[IEEE80211_ADDR_LEN] = rt2661_cipher(key);
3267
3268                 /* XXX Actually slot size is 1 byte bigger than mac_cipher */
3269                 addr = RT2661_TARGET_ADDR_BASE +
3270                        (key->wk_keyix * (IEEE80211_ADDR_LEN + 2));
3271                 RAL_WRITE_REGION_1(sc, addr, mac_cipher, sizeof(mac_cipher));
3272
3273                 /*
3274                  * Enable key slot.
3275                  */
3276                 if (key->wk_keyix < 32) {
3277                         val = RAL_READ(sc, RT2661_SEC_CSR2);
3278                         val |= 1 << key->wk_keyix;
3279                         RAL_WRITE(sc, RT2661_SEC_CSR2, val);
3280                 } else {
3281                         val = RAL_READ(sc, RT2661_SEC_CSR3);
3282                         val |= 1 << (key->wk_keyix - 32);
3283                         RAL_WRITE(sc, RT2661_SEC_CSR3, val);
3284                 }
3285
3286                 /*
3287                  * Enable pairwise key looking up when RX.
3288                  */
3289                 RAL_WRITE(sc, RT2661_SEC_CSR4, 1);
3290         }
3291         return 1;
3292 }
3293
3294 static void *
3295 rt2661_ratectl_attach(struct ieee80211com *ic, u_int rc)
3296 {
3297         struct rt2661_softc *sc = ic->ic_if.if_softc;
3298
3299         switch (rc) {
3300         case IEEE80211_RATECTL_ONOE:
3301                 return &sc->sc_onoe_param;
3302
3303         case IEEE80211_RATECTL_SAMPLE:
3304                 if ((ic->ic_ratectl.rc_st_ratectl_cap &
3305                      IEEE80211_RATECTL_CAP_SAMPLE) == 0)
3306                         panic("sample rate control algo is not supported\n");
3307                 return &sc->sc_sample_param;
3308
3309         case IEEE80211_RATECTL_NONE:
3310                 /* This could only happen during detaching */
3311                 return NULL;
3312
3313         default:
3314                 panic("unknown rate control algo %u\n", rc);
3315                 return NULL;
3316         }
3317 }