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