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